hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
b22c174c5ee9e0cb0a1da8296bf8a314f2774113
2,593
/* * Copyright 2016-2017 Leon Chen * * 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 syncer.replica.io; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; /** * @author Leon Chen * @since 3.5.5 */ public class ByteBufferOutputStream extends OutputStream { protected byte buf[]; protected int count; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public ByteBufferOutputStream() { this(32); } public ByteBufferOutputStream(int size) { buf = new byte[size]; } @Override public void write(int b) { ensureCapacity(count + 1); buf[count] = (byte) b; count += 1; } @Override public void write(byte b[], int off, int len) { ensureCapacity(count + len); System.arraycopy(b, off, buf, count, len); count += len; } @Override public void close() throws IOException { } public void writeBytes(byte b[]) { write(b, 0, b.length); } public void writeTo(OutputStream out) throws IOException { out.write(buf, 0, count); } public void reset() { count = 0; } public int size() { return count; } public ByteBuffer toByteBuffer() { return ByteBuffer.wrap(buf, 0, count); } private void ensureCapacity(int capacity) { if (capacity - buf.length > 0) grow(capacity); } private void grow(int minCapacity) { int oldCapacity = buf.length; int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); buf = Arrays.copyOf(buf, newCapacity); } private static int hugeCapacity(int capacity) { if (capacity < 0) throw new OutOfMemoryError(); return (capacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } }
26.459184
80
0.626302
a3014ff44289e397f6440c2f27037885da8cf218
484
package foundation.omni.json.conversion; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.KeyDeserializer; import foundation.omni.CurrencyID; /** * Deserialization toCurrencyID for when it's used in as a map key */ public class CurrencyIDKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(String key, DeserializationContext ctxt) { return CurrencyID.of(Long.parseLong(key)); } }
30.25
75
0.78719
56a217e09cad2705f284e1662c4d421378a65907
4,809
package com.company.Logic; import com.company.Gui.MainGui; import javax.swing.*; import java.awt.*; import java.util.Random; public class DataBaseManagement { private JPanel roomFill; private JPanel tek; int roomRank = 28, i = 0; public int totalRoomFull = 0, totalRoomBlank = 0, totalCustomer = 0; JLabel[] roomNumberLine = new JLabel[roomRank]; JLabel[] roomCapacityLine = new JLabel[roomRank]; JLabel[] roomStatusLine = new JLabel[roomRank]; public String[] roomNumber = new String[roomRank]; public String[] roomCapacity = {"1", "1", "1", "1", "2", "2", "3", "1", "1", "1", "1", "2", "2", "3", "1", "1", "1", "1", "2", "2", "3", "1", "1", "1", "1", "2", "2", "3"}; public String[] roomStatus = new String[roomRank]; public String[] roomDate = new String[roomRank]; public String[] customerNumber = new String[roomRank]; public String[] customerName = new String[roomRank]; public String[] currencyName = {"Dollar", "Euro", "Pound", "Yen", "Ruble", "Franc"}; public double[] currencyRate = {5.25, 6.45, 7.10, 2.22, 0.8, 12.5}; private Color[] si = new Color[roomRank]; private MainGui mainGui; public ActionData actionData; public DataBaseManagement(MainGui mainGui) { setMainGui(mainGui); int t = 0; for (int y = 0; y < 4; y++) { for (int i = 0; i < 7; i++) { roomNumber[t] = "1" + y + i; roomStatus[t] = "Boş"; t++; } } } public JPanel getRoomFill(int i) { this.i = i; actionData = new ActionData(this, i); roomFill = new RoundedCenter(new GridLayout(3, 1), 50, ola()); roomFill.setOpaque(false); roomFill.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); roomFill.setPreferredSize(new Dimension(100, 150)); roomNumberLine[i] = new JLabel(roomNumber[i]); roomCapacityLine[i] = new JLabel(roomCapacity[i]); roomStatusLine[i] = new JLabel(roomStatus[i]); roomNumberLine[i].setFont(new Font("Tahoma", Font.BOLD, 22)); roomStatusLine[i].setIcon(new ImageIcon(getMainGui().getSettings().newIconRoomStatus)); roomCapacityLine[i].setIcon(new ImageIcon(getMainGui().getSettings().newIconRoomCapacity)); roomFill.add(roomNumberLine[i]); roomFill.add(roomCapacityLine[i]); roomFill.add(roomStatusLine[i]); roomFill.addMouseListener(actionData); return roomFill; } public void setRoomFill(JPanel roomFill) { this.roomFill = roomFill; } public void tableFill(int row) { Random tableRandom = new Random(); for (int i = 0; i < row; i++) { getMainGui().getBarMain().getPageCustomers().model.addRow(new Object[]{ roomNumber[i], customerNumber[i], customerName[i], (tableRandom.nextInt(31) + 1) + " / " + (tableRandom.nextInt(12) + 1) + " / " + (tableRandom.nextInt(70) + 1900), (tableRandom.nextInt(31) + 1) + " / " + (tableRandom.nextInt(12) + 1) + " / 2019" }); } } public JPanel getTek() { tek = new JPanel(); tek.setBackground(null); tek.setLayout(new GridLayout(4, 7, 20, 20)); for (int i = 0; i < 28; i++) { tek.add(getRoomFill(i)); } return tek; } public void setTek(JPanel tek) { this.tek = tek; } public MainGui getMainGui() { return mainGui; } public void setMainGui(MainGui mainGui) { this.mainGui = mainGui; } public Color ola() { if (roomStatus[i] == "Boş") { si[i] = new Color(127, 143, 166); } else if (roomStatus[i] == "Dolu") { si[i] = new Color(68, 189, 50); } else if (roomStatus[i] == "Kirli") { si[i] = new Color(232, 65, 24); } else if (roomStatus[i] == "Arızalı") { si[i] = new Color(251, 197, 49); } else if (roomStatus[i] == "Tadilat") { si[i] = new Color(64, 115, 158); } return si[i]; } public void customerTotal() { totalRoomFull = 0; totalRoomBlank = 0; totalCustomer = 0; for (int i = 0; i < roomStatus.length; i++) { if (roomStatus[i] == "Dolu") { totalRoomFull++; } else { totalRoomBlank++; } } for (int i = 0; i < customerNumber.length; i++) { if (customerNumber[i] != null) { totalCustomer++; } } } }
33.866197
177
0.525265
0e8677362d2716b3e2c10a07c74d24f6441e5bc8
1,677
package softwareengg.classroomvisualiser; import android.database.Cursor; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class DeleteStudentActivity extends AppCompatActivity { DBHelper myDb; DBImgHelper imDb; EditText editTextId; Button btnDelete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_student); myDb = new DBHelper(this); imDb = new DBImgHelper(this); editTextId = (EditText)findViewById(R.id.editText_id); btnDelete= (Button)findViewById(R.id.button_delete); DeleteData(); } public void DeleteData() { btnDelete.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Integer deletedRows = myDb.deleteData(Integer.parseInt( editTextId.getText().toString() )); Integer deletedImg = imDb.deleteImg(Integer.parseInt( editTextId.getText().toString() )); if(deletedRows > 0 && deletedImg > 0) Toast.makeText(DeleteStudentActivity.this,"Data Deleted",Toast.LENGTH_LONG).show(); else Toast.makeText(DeleteStudentActivity.this,"Data not Deleted Completely",Toast.LENGTH_LONG).show(); } } ); } }
35.680851
126
0.634466
6aec857c9f6edb44bf38f153871deb4e14ca258f
736
package com.dimple.project.blog.domain; import lombok.Builder; import lombok.Data; import java.io.Serializable; /** * @className: TagMapping * @description: Tag和其他表的关联 * @author: Dimple * @date: 11/22/19 */ @Data @Builder public class TagMapping implements Serializable { private Long id; private Long blogId; private Long tagId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public Long getTagId() { return tagId; } public void setTagId(Long tagId) { this.tagId = tagId; } }
16.355556
49
0.61413
5531952446735350da25e7162bea5d2dbbc9bac3
83
package com.seantcanavan.backoff; public enum Operation { ADD, SUBTRACT }
11.857143
33
0.710843
c50ead360e7c5bb6a0136a891584a3d223ea83dd
259
package com.SeleniumByAli; import org.openqa.selenium.By; public interface LogInOut { void Login(By elementForUsernameFiled, By elementForPasswordField, String username, String password, By elementForSubmitForm); void LogOut(By selector); }
28.777778
131
0.772201
245bf2026b6710e83279e8a8ab9784e29a066ee6
226
package apt.tutorial; import apt.tutorial.IPostListener; public interface IPostMonitor { void registerAccount(String user, String password, IPostListener callback); void removeAccount(IPostListener callback); }
25.111111
51
0.783186
d789c1e80045fae445793af2d61a2c82bb699f84
3,631
package com.gubatron.aoc._2020; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static com.gubatron.aoc._2020.Utils.readStringsBySeparator; public class Day13 { public static int part1(int timestamp, List<Integer> busIds) { int bestTimeDiff = Integer.MAX_VALUE; int candidateBusId = -1; for (Integer busId : busIds) { int timeDiff = busId - (timestamp % busId); if (timeDiff < bestTimeDiff) { candidateBusId = busId; bestTimeDiff = timeDiff; } } return candidateBusId * bestTimeDiff; } static class Bus { int id; int offset; BigInteger idBigInt; BigInteger offsetBigInt; public Bus(Integer busID, int i) { id = busID; offset = i; idBigInt = new BigInteger(String.valueOf(id)); offsetBigInt = new BigInteger(String.valueOf(offset)); } // meant to be used for part 2, but couldn't figure out how to increment test T fast enough // however, this served to show me what the system of equations would look like eventually // had to do this analytically boolean isTValidTForMe(final BigInteger t) { try { // (T+MyOffset) % myID == 0 return t.add(offsetBigInt).mod(idBigInt).compareTo(BigInteger.ZERO) == 0; } catch (Throwable ignore) { return false; } } } // Did this when I was trying to validate the sample inputs for different attempts of t // I just could never figure out how to increment t the right way without burning my CPU static boolean isTValidForAllBuses(final BigInteger t, List<Bus> buses) { for (Bus bus : buses) { if (!bus.isTValidTForMe(t)) { return false; } } return true; } public static String part2(List<Integer> busIds) { int offset = 0; System.out.println("Find t such that:"); for (Integer busID : busIds) { if (busID == -1) { // skip the Xs offset++; //but keep track of the offsets continue; } System.out.print("(t + " + offset++ + ") mod " + busID + " = 0,\n"); } return "\nCopy and paste that in Wolfram Alpha!\n\n402251700208309 + 748958695773119 n\n\nFor n=0 -> Ans=402251700208309"; } public static void main(String[] args) throws IOException { //List<String> lines = readStringsBySeparator(new File("resources/sample_day_13.txt"), "\n"); List<String> lines = readStringsBySeparator(new File("resources/input_day_13.txt"),"\n"); int timestamp = Integer.parseInt(lines.get(0)); List<Integer> busIds = Arrays.stream(lines.get(1).split(",")).filter(s -> !s.equals("x")).map(Integer::parseInt).collect(Collectors.toList()); System.out.println("DAY 13 - Shuttle Search"); System.out.println("Part 1: " + part1(timestamp, busIds)); // 2045 (sample 295) System.out.println("=============================="); List<Integer> busIds2 = Arrays.stream(lines.get(1).split(",")).map(s -> { if (s.equals("x")) { return -1; // mark Xs as -1 bus line ids } else return Integer.parseInt(s); }).collect(Collectors.toList()); System.out.print("Part 2: "); System.out.println(part2(busIds2)); // 402251700208309 } }
37.05102
150
0.583861
26efbd4f95aa5a727bd08c46d4312ac13bc683ac
5,543
package com.geminifile.core.service.localnetworkconn; import com.geminifile.core.service.Node; import com.geminifile.core.service.Service; import com.geminifile.core.service.localnetworkconn.comms.PeerMsgProcessorThread; import com.geminifile.core.socketmsg.msgwrapper.MsgWrapper; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.logging.Level; // TODO: STOP THIS LOOP WHEN SERVICE IS STOPPED. public class PeerCommunicationLoop implements Runnable { private final Socket sock; private final Node node; private final ObjectInputStream inStream; private final ObjectOutputStream outStream; private final ArrayBlockingQueue<MsgWrapper> outMessageQueue; private final List<PeerMsgProcessorThread> msgProcessorThreads = new ArrayList<>(); public PeerCommunicationLoop(Socket sock, Node node, ObjectInputStream inStream, ObjectOutputStream outStream) { this.sock = sock; this.node = node; this.inStream = inStream; this.outStream = outStream; // Maximum message queue is 10. outMessageQueue = new ArrayBlockingQueue<>(10, true); } public void startComms() { String threadBeginning = Thread.currentThread().getName(); // The current thread becomes the input thread, a new thread is created for the output thread. Thread outThread = new Thread(this, (Thread.currentThread().getName() + "OutStream")); // Renames the threads to get a better information Thread.currentThread().setName(Thread.currentThread().getName() + "InStream"); // Starts the thread outThread.start(); // THIS IS THE MAIN INPUT LOOP, PROCESS INPUT while (true) { // Waits until there is an prompt to send. try { Object inObj = inStream.readObject(); MsgWrapper msg = (MsgWrapper) inObj; Service.LOGGER.info("[PEER] Received Message Type " + msg.getType().name()); // Processes the message in a separate thread PeerMsgProcessorThread inProcessorThread = new PeerMsgProcessorThread(this, msg); inProcessorThread.setName(Thread.currentThread().getName() + "-MsgProcessor-" + msg.getType().name()); msgProcessorThreads.add(inProcessorThread); // And puts it into the list. inProcessorThread.start(); } catch (SocketException e) { // Means that server disconnects from the other machine. outThread.interrupt(); for (PeerMsgProcessorThread tr : msgProcessorThreads) { tr.interrupt(); } Service.LOGGER.warning("[PEER] Disconnected with: " + node.getIp().getHostAddress()); // Tries to close the IO Stream try { inStream.close(); outStream.close(); } catch (IOException ex) { Service.LOGGER.severe("[PEER] Failed to close communication io stream"); Service.LOGGER.log(Level.SEVERE, "exception", e); } break; } catch (EOFException e) { // Could mean that the server peer has disconnected from this machine. outThread.interrupt(); for (PeerMsgProcessorThread tr : msgProcessorThreads) { tr.interrupt(); } Service.LOGGER.warning("[PEER] Disconnected from: " + node.getIp().getHostAddress()); // Tries to close the IO Stream try { inStream.close(); outStream.close(); } catch (IOException ex) { Service.LOGGER.severe("[PEER] Failed to close communication io stream"); Service.LOGGER.log(Level.SEVERE, "exception", e); } break; } catch (ClassNotFoundException e) { Service.LOGGER.severe("[PEER] Class deserialization error."); Service.LOGGER.log(Level.SEVERE, "exception", e); } catch (IOException e) { Service.LOGGER.log(Level.SEVERE, "exception", e); } } } @Override public void run() { // The output thread. while(true) { try { MsgWrapper msg = outMessageQueue.take(); Service.LOGGER.info("[PEER] Sending Message Type " + msg.getType().name()); outStream.writeObject(msg); } catch (InterruptedException e) { // TODO: QUIT OR RESTART WHEN INTERRUPTED. return; } catch (IOException e) { Service.LOGGER.info("Error writing message to: " + node.getName() + " " + node.getIp().getHostAddress()); Service.LOGGER.log(Level.SEVERE, "exception", e); } } } public Socket getSock() { return sock; } public Node getNode() { return node; } public boolean sendMsg(MsgWrapper msg) { return outMessageQueue.offer(msg); } public void removeMsgProcessorThread(PeerMsgProcessorThread thread) { msgProcessorThreads.remove(thread); } }
37.707483
145
0.600036
79f308563539470c88f5f81964578af1cbd05368
3,468
/* * The MIT License (MIT) * * Copyright (C) 2018-2019 Fabricio Barros Cabral * * 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.jdbc.sql; import com.github.fabriciofx.cactoos.jdbc.Param; import com.github.fabriciofx.cactoos.jdbc.Params; import com.github.fabriciofx.cactoos.jdbc.params.ParamsNamed; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.Sticky; import org.cactoos.text.FormattedText; /** * Parse named parameters in the SQL. * * @since 0.1 */ public final class SqlParsed implements Text { /** * SQL query. */ private final Scalar<String> sql; /** * Ctor. * @param sql SQL query * @param params SQL query parameters */ public SqlParsed(final String sql, final Param... params) { this(() -> sql, new ParamsNamed(params)); } /** * Ctor. * @param sql SQL query * @param params SQL query parameters */ public SqlParsed(final Text sql, final Param... params) { this(sql, new ParamsNamed(params)); } /** * Ctor. * @param sql SQL query * @param params SQL query parameters */ public SqlParsed(final Text sql, final Params params) { this.sql = new Sticky<>( () -> { final String str = sql.asString(); final List<String> names = new LinkedList<>(); final Pattern find = Pattern.compile("(?<!')(:[\\w]*)(?!')"); final Matcher matcher = find.matcher(str); while (matcher.find()) { names.add(matcher.group().substring(1)); } for (int idx = 0; idx < names.size(); ++idx) { if (!params.contains(names.get(idx), idx)) { throw new IllegalArgumentException( new FormattedText( "SQL parameter #%d is wrong or out of order", idx + 1 ).asString() ); } } return str.replaceAll(find.pattern(), "?"); } ); } @Override public String asString() throws Exception { return this.sql.value(); } }
34
80
0.610438
7089cc170e4754696518ca8a0e67a8a24e5be4ac
9,568
package com.catherine.materialdesignapp.activities; import android.app.SearchManager; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.widget.SearchView; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import com.catherine.materialdesignapp.R; import com.catherine.materialdesignapp.fragments.FavoritesFragment; import com.catherine.materialdesignapp.fragments.HomeFragment; import com.catherine.materialdesignapp.fragments.MusicFragment; import com.catherine.materialdesignapp.listeners.OnSearchViewListener; import com.catherine.materialdesignapp.listeners.UIComponentsListener; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.tabs.TabLayout; public class UIComponentsActivity extends BaseActivity implements UIComponentsListener, SearchView.OnQueryTextListener { public final static String TAG = UIComponentsActivity.class.getSimpleName(); private enum Tag { HOME("HOME"), MUSIC("MUSIC"), FAVORITES("FAVORITES"); private final String name; Tag(String s) { name = s; } int index() { Tag[] tagArray = values(); for (int i = 0; i < tagArray.length; i++) { if (tagArray[i] == this) return i; } return 0; } } private final static String STATE_SELECTED_BOTTOM_NAVIGATION = "STATE_SELECTED_BOTTOM_NAVIGATION"; private BottomNavigationView navigationView; private Toolbar toolbar; private TabLayout tabLayout; private String[] titles; private Fragment[] fragments = new Fragment[3]; private OnSearchViewListener onSearchViewListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ui_components); initComponent(savedInstanceState); } private void initComponent(Bundle savedInstanceState) { toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); // enable back arrow on the top left area getSupportActionBar().setTitle(TAG); } navigationView = findViewById(R.id.bottom_navigation); Menu menu = navigationView.getMenu(); titles = getResources().getStringArray(R.array.ui_component_bottom_navigation); for (int i = 0; i < titles.length; i++) { menu.getItem(i).setTitle(titles[i]); } navigationView.setOnNavigationItemSelectedListener(this::onNavigationItemSelected); FloatingActionButton fab_addToPlaylist = findViewById(R.id.fab_addToPlaylist); fab_addToPlaylist.setOnClickListener(v -> { }); // ViewPager for MusicFragment tabLayout = findViewById(R.id.tab_layout); tabLayout.setVisibility(View.GONE); getSupportFragmentManager().addOnBackStackChangedListener(this::onBackStackChanged); if (savedInstanceState == null) { // initialise home fragment navigationView.setSelectedItemId(R.id.nav_home); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the app bar if it is present. getMenuInflater().inflate(R.menu.ui_components_menu, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(this); return true; } private boolean onNavigationItemSelected(@NonNull MenuItem item) { Log.d(TAG, "onNavigationItemSelected:" + item.getTitle()); return switchTab(item.getItemId()); } private boolean switchTab(int menuItemId) { String tag; Fragment f; int index; switch (menuItemId) { case R.id.nav_home: tag = Tag.HOME.name(); index = Tag.HOME.index(); if (fragments[index] == null) fragments[index] = new HomeFragment(); f = fragments[index]; toolbar.setTitle(titles[index]); tabLayout.setVisibility(View.GONE); break; case R.id.nav_music: tag = Tag.MUSIC.name(); index = Tag.MUSIC.index(); if (fragments[index] == null) { fragments[index] = new MusicFragment(); } f = fragments[index]; tabLayout.setVisibility(View.VISIBLE); break; case R.id.nav_favorite: tag = Tag.FAVORITES.name(); index = Tag.FAVORITES.index(); if (fragments[index] == null) fragments[index] = new FavoritesFragment(); f = fragments[index]; toolbar.setTitle(titles[index]); tabLayout.setVisibility(View.GONE); break; default: return false; } Log.e(TAG, String.format("onTabSwitch:%s", tag)); // check fragments in back stack, if the fragment exists, do not replace it. if (getSupportFragmentManager().getBackStackEntryCount() > 0) { FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1); String name = backStackEntry.getName(); if (tag.equals(name)) return true; } // keep only one fragment in the back stack clearBackStack(); getSupportFragmentManager().beginTransaction() .addToBackStack(tag) .replace(R.id.f_container, f, tag) .commit(); return true; } @Override public void addViewPagerManager(ViewPager viewpager, String[] titles) { tabLayout.setVisibility(View.VISIBLE); tabLayout.setupWithViewPager(viewpager); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { getSupportActionBar().setTitle(titles[tab.getPosition()]); toolbar.setTitle(titles[tab.getPosition()]); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //left<0.5, right>0.5 } @Override public void onPageSelected(int position) { Log.i(TAG, String.format("onPageSelected:%d", position)); } @Override public void onPageScrollStateChanged(int state) { } }); getSupportActionBar().setTitle(titles[viewpager.getCurrentItem()]); toolbar.setTitle(titles[viewpager.getCurrentItem()]); } @Override public void setOnSearchListener(OnSearchViewListener listener) { onSearchViewListener = listener; } @Override public void onBackPressed() { if (getSupportFragmentManager().getBackStackEntryCount() <= 1) finish(); else { getSupportFragmentManager().popBackStack(); } } private void onBackStackChanged() { Log.w(TAG, String.format("Back stack counts: %d", getSupportFragmentManager().getBackStackEntryCount())); } private void clearBackStack() { for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) { getSupportFragmentManager().popBackStack(); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt(STATE_SELECTED_BOTTOM_NAVIGATION, navigationView.getSelectedItemId()); super.onSaveInstanceState(savedInstanceState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState == null) return; int nav = savedInstanceState.getInt(STATE_SELECTED_BOTTOM_NAVIGATION); navigationView.setSelectedItemId(nav); } @Override public boolean onQueryTextSubmit(String query) { if (onSearchViewListener != null) onSearchViewListener.onQueryTextSubmit(query); return false; } @Override public boolean onQueryTextChange(String newText) { if (onSearchViewListener != null) onSearchViewListener.onQueryTextChange(newText); return false; } }
36.380228
166
0.644858
360259761998d43712b0f3ce565409b65019f960
1,961
package club.frozed.frozedsumo.game; import club.frozed.frozedsumo.FrozedSumo; import org.bukkit.entity.Player; public class Stats { private Player player; private int kills; private int deaths; private int matches; private int wins; private int losses; public Stats(Player player) { this.player = player; this.kills = FrozedSumo.statsConfig.getInt(player.getUniqueId().toString() + ".kills"); this.deaths = FrozedSumo.statsConfig.getInt(player.getUniqueId().toString() + ".deaths"); this.matches = FrozedSumo.statsConfig.getInt(player.getUniqueId().toString() + ".matches"); this.wins = FrozedSumo.statsConfig.getInt(player.getUniqueId().toString() + ".wins"); this.losses = FrozedSumo.statsConfig.getInt(player.getUniqueId().toString() + ".losses"); } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public int getKills() { return kills; } public void setKills(int kills) { this.kills = kills; } public int getDeaths() { return deaths; } public void setDeaths(int deaths) { this.deaths = deaths; } public int getMatches() { return matches; } public void setMatches(int matches) { this.matches = matches; } public int getWins() { return wins; } public void setWins(int wins) { this.wins = wins; } public int getLosses() { return losses; } public void setLosses(int losses) { this.losses = losses; } public void addKills() { this.kills += 1; } public void addDeaths() { this.deaths += 1; } public void addMatches() { this.matches += 1; } public void addWins() { this.wins += 1; } public void addLosses() { this.losses += 1; } }
21.315217
99
0.594595
1c5e1f11bb31d86490fe8e33e3a6d2d519bbe88d
4,277
package org.checkerframework.checker.oigj; import org.checkerframework.common.basetype.BaseAnnotatedTypeFactory; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.framework.type.QualifierHierarchy; import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator; import org.checkerframework.framework.type.treeannotator.TreeAnnotator; import org.checkerframework.framework.util.GraphQualifierHierarchy; import org.checkerframework.framework.util.MultiGraphQualifierHierarchy.MultiGraphFactory; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.ErrorReporter; import java.util.Collection; import javax.lang.model.element.AnnotationMirror; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; public class OwnershipAnnotatedTypeFactory extends BaseAnnotatedTypeFactory { protected final AnnotationMirror BOTTOM_QUAL; public OwnershipAnnotatedTypeFactory(BaseTypeChecker checker) { super(checker); BOTTOM_QUAL = AnnotationUtils.fromClass(elements, OIGJMutabilityBottom.class); this.postInit(); } @Override protected TreeAnnotator createTreeAnnotator() { return new ListTreeAnnotator( super.createTreeAnnotator(), new OwnershipTreeAnnotator(this) ); } // @Override // protected TypeAnnotator createTypeAnnotator() { // return new OwnershipTypeAnnotator(this); // } // TODO: do store annotations into the Element -> remove this override // Currently, many test cases fail without this. @Override public void postProcessClassTree(ClassTree tree) { } // private class OwnershipTypeAnnotator extends ImplicitsTypeAnnotator { // // public OwnershipTypeAnnotator(OwnershipAnnotatedTypeFactory atypeFactory) { // super(atypeFactory); // } // // @Override // public Void visitDeclared(AnnotatedDeclaredType type, Void p) { // if (type.isAnnotatedInHierarchy(BOTTOM_QUAL)) // return super.visitDeclared(type, p); // // /*if (elem != null && // elem.getKind() == ElementKind.CLASS && // TypesUtils.isObject(type.getUnderlyingType())) // type.addAnnotation(World.class);*/ // return super.visitDeclared(type, p); // } // } private class OwnershipTreeAnnotator extends TreeAnnotator { public OwnershipTreeAnnotator(OwnershipAnnotatedTypeFactory atypeFactory) { super(atypeFactory); } @Override public Void visitBinary(BinaryTree node, AnnotatedTypeMirror type) { type.replaceAnnotation(BOTTOM_QUAL); return super.visitBinary(node, type); } } @Override public QualifierHierarchy createQualifierHierarchy(MultiGraphFactory factory) { return new OwnershipQualifierHierarchy(factory); } private final class OwnershipQualifierHierarchy extends GraphQualifierHierarchy { public OwnershipQualifierHierarchy(MultiGraphFactory factory) { // TODO warn if bottom is not supported. super(factory, BOTTOM_QUAL); } @Override public boolean isSubtype(Collection<? extends AnnotationMirror> rhs, Collection<? extends AnnotationMirror> lhs) { if (lhs.isEmpty() || rhs.isEmpty()) { ErrorReporter.errorAbort("OwnershipQualifierHierarchy: Empty annotations in lhs: " + lhs + " or rhs: " + rhs); } // TODO: sometimes there are multiple mutability annotations in a type and // the check in the superclass that the sets contain exactly one annotation // fails. I replaced "addAnnotation" calls with "replaceAnnotation" calls, // but then other test cases fail. Some love needed here. for (AnnotationMirror lhsAnno : lhs) { for (AnnotationMirror rhsAnno : rhs) { if (isSubtype(rhsAnno, lhsAnno)) { return true; } } } return false; } } }
37.517544
126
0.678279
8bba131f4ac1c2e4d46248e43b5373c2da2969fc
109
package com.storakle.shopify.domain; public enum OrderStatusFilter { open, closed, cancelled, any }
12.111111
36
0.733945
4b9f455a3167e86da1eb1b90a0932687b14cb42b
2,701
package org.trident.control.listeners; /* * org.trident.control.listeners.ToolsMenuListener.java * (c) Copyright, 2020 - 2021 Krishna Moorthy * akrishnamoorthy007@gmail.com | github.com/KrishnaMoorthy12 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.trident.Trident; import org.trident.exception.UnsupportedFileException; import org.trident.exception.UnsupportedOperatingSystemException; import org.trident.model.TridentCompiler; import org.trident.util.TridentLogger; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; /* * (Apache v2) Trident > org.trident.control.listeners.ToolsMenuListener * @author: Krishna Moorthy */ public class ToolsMenuListener implements ActionListener { /* * Controls the actions of Tools Menu */ public static boolean isRunning = true; public void actionPerformed(ActionEvent e) { /* * Controls the actions of Tools Menu items */ try { String path = Trident.getInstance().getPath(); switch (e.getActionCommand()) { case "Compile": TridentCompiler.compile(path); break; case "Run": TridentCompiler.execute(path); break; case "Compile and Run": TridentCompiler.compile(path); Thread.sleep(3000); TridentCompiler.execute(path); break; case "Open Console": TridentCompiler.openTerminal(); break; default: } } catch (IOException ioException) { TridentLogger.getInstance().error(this.getClass(), "PROCESS_BUILD_FILEIO: " + ioException); } catch (UnsupportedOperatingSystemException unOs) { TridentLogger.getInstance().error(this.getClass(), "OS_UNSUPPORTED: " + unOs); } catch (UnsupportedFileException fileNS) { TridentLogger.getInstance().error(this.getClass(), "FILE_UNSUPPORTED: " + fileNS); } catch (Exception unknownException) { TridentLogger.getInstance().error(this.getClass(), "TOOLS_MENU_CRASH: " + unknownException); unknownException.printStackTrace(); } } }
35.077922
99
0.68271
8cbf64afda82ba03b41486c0092f4ee9a750e2b7
14,203
package com.aspartame.RemindMe; import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import android.widget.SeekBar.OnSeekBarChangeListener; public class SingleReminderActivity extends Activity { private static final String DEBUG_TAG = "SingleReminderActivity"; private SharedPreferences preferences; private DBadapter dbAdapter; private Context context; private AlarmManager am; public void onCreate(Bundle savedInstanceState) { Log.d(DEBUG_TAG, "Starting SingleReminderActivity"); super.onCreate(savedInstanceState); context = getApplicationContext(); preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); dbAdapter = new DBadapter(this); dbAdapter.open(); long time = getIntent().getLongExtra("time", 0l); String desc = getIntent().getStringExtra("desc"); if (time > 0) { this.setTitle("Edit reminder"); } createReminder(time, desc); } /* Create a reminder. If oldTime == RemindMe.NEW_REMINDER a new reminder is created, * otherwise the reminder identified by oldTime is rescheduled. */ private void createReminder(final long oldTime, String desc) { Log.d(DEBUG_TAG, "Starting createReminder"); LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View createView = li.inflate(R.layout.new_single_reminder, null); /* Create a calendar and set its values */ final Calendar cal = Calendar.getInstance(); if (oldTime > 0 ) { cal.setTimeInMillis(oldTime); } else { cal.set(Calendar.SECOND, 0); } /* Set date, time and description fields */ final boolean is24HourClock = preferences.getBoolean(getResources().getString(R.string.preferences_clock_format), false); final TextView timerTextView = (TextView) createView.findViewById(R.id.new_reminder_timer_label); final TextView dateTextView = (TextView) createView.findViewById(R.id.new_reminder_date_label); final TextView timeTextView = (TextView) createView.findViewById(R.id.new_reminder_time_label); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); String dateLabel = DateParser.formatDate(cal); String timeLabel = DateParser.parseTime(hour, minute, is24HourClock); String timerLabel = "Set Timer"; if (oldTime > 0) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); timerLabel = DateParser.parseTimer(year, month, day, hour, minute); } timerTextView.setText(timerLabel); dateTextView.setText(dateLabel); timeTextView.setText(timeLabel); EditText descView = (EditText) createView.findViewById(R.id.new_reminder_description); descView.setText(desc); /* Handle result from date- and time picker dialogs */ final DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int mYear, int mMonth, int mDay) { cal.set(mYear, mMonth, mDay); int mHour = cal.get(Calendar.HOUR_OF_DAY); int mMinute = cal.get(Calendar.MINUTE); String date = DateParser.formatDate(mYear, mMonth, mDay); String timerLabelText = DateParser.parseTimer(mYear, mMonth, mDay, mHour, mMinute); dateTextView.setText(date); timerTextView.setText(timerLabelText); } }; final TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int mHour, int mMinute) { int mYear = cal.get(Calendar.YEAR); int mMonth = cal.get(Calendar.MONTH); int mDay = cal.get(Calendar.DAY_OF_MONTH); cal.set(Calendar.HOUR_OF_DAY, mHour); cal.set(Calendar.MINUTE, mMinute); String formattedTime = DateParser.parseTime(mHour, mMinute, is24HourClock); String timerLabelText = DateParser.parseTimer(mYear, mMonth, mDay, mHour, mMinute); timeTextView.setText(formattedTime); timerTextView.setText(timerLabelText); } }; // Set onClickListener for Timer view View timerView = (View) createView.findViewById(R.id.new_reminder_timer_view); timerView.setOnClickListener(new OnClickListener() { public void onClick(View view) { showTimerPickerDialog(cal, is24HourClock, dateTextView, timeTextView, timerTextView); } }); // Set onClickListener for Date view View dateView = (View) createView.findViewById(R.id.new_reminder_date_view); dateView.setOnClickListener(new OnClickListener() { public void onClick(View view) { // Show datePicker dialog DatePickerDialog dateDialog = new DatePickerDialog(SingleReminderActivity.this, dateSetListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); Window window = dateDialog.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); dateDialog.setTitle("Choose date"); dateDialog.show(); } }); // Set onClickListener for Time view View timeView = (View) createView.findViewById(R.id.new_reminder_time_view); timeView.setOnClickListener(new OnClickListener() { public void onClick(View view) { TimePickerDialog timeDialog = new TimePickerDialog(SingleReminderActivity.this, timeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), is24HourClock); Window window = timeDialog.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); timeDialog.setTitle("Choose time"); timeDialog.show(); } }); // Set onClickListener for create alert button Button submitButton = (Button) createView.findViewById(R.id.new_reminder_submit_button); submitButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { Log.d(DEBUG_TAG, "Clicked Set reminder"); EditText descView = (EditText) createView.findViewById(R.id.new_reminder_description); String desc = descView.getText().toString(); registerReminder(cal, desc, oldTime); Log.d(DEBUG_TAG, "Reminder added to database"); setResult(RESULT_OK); finish(); } }); // Set onClickListener for cancel button Button cancelButton = (Button) createView.findViewById(R.id.new_reminder_cancel_button); cancelButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { Log.d(DEBUG_TAG, "Cancelling new single reminder"); setResult(RESULT_CANCELED); finish(); } }); setContentView(createView); } private void showTimerPickerDialog(final Calendar cal, final boolean is24HourClock, final TextView dateTextView, final TextView timeTextView, final TextView timerLabel) { AlertDialog.Builder ad = new AlertDialog.Builder(this); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); final View timerView = li.inflate(R.layout.timer_view, null); SeekBar hourBar = (SeekBar) timerView.findViewById(R.id.timer_hour_seekbar); SeekBar minuteBar = (SeekBar) timerView.findViewById(R.id.timer_minute_seekbar); int [] time = DateParser.parseIntTimer(year, month, day, hour, minute); final TextView hourValue = (TextView) timerView.findViewById(R.id.timer_hour_label); final TextView minuteValue = (TextView) timerView.findViewById(R.id.timer_minute_label); if ( (time[0] < 0) || (time[1] < 0) ) { hourBar.setProgress(0); minuteBar.setProgress(0); hourValue.setText(Integer.toString(0)); minuteValue.setText(Integer.toString(0)); } else { hourBar.setProgress(time[0]); minuteBar.setProgress(time[1]); hourValue.setText(Integer.toString(time[0])); minuteValue.setText(Integer.toString(time[1])); } final TextView hourLabel = (TextView) timerView.findViewById(R.id.timer_hour_label_text); final TextView minuteLabel = (TextView) timerView.findViewById(R.id.timer_minute_label_text); String text = (time[0] != 1) ? " hours" : " hour"; hourLabel.setText(text); text = (time[1] != 1) ? " minutes" : " minute"; minuteLabel.setText(text); OnSeekBarChangeListener onSeekBarProgress = new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar s, int progress, boolean touch) { if (touch) { if (s.getId() == R.id.timer_hour_seekbar) { String text = (progress != 1) ? " hours" : " hour"; hourValue.setText(Integer.toString(progress)); hourLabel.setText(text); } if (s.getId() == R.id.timer_minute_seekbar) { String text = (progress != 1) ? " minutes" : " minute"; minuteValue.setText(Integer.toString(progress)); minuteLabel.setText(text); } } } public void onStartTrackingTouch(SeekBar s) {} public void onStopTrackingTouch(SeekBar s) {} }; hourBar.setOnSeekBarChangeListener(onSeekBarProgress); minuteBar.setOnSeekBarChangeListener(onSeekBarProgress); // Set onClickListener for set button ad.setPositiveButton("Set", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { int timerHours = Integer.valueOf(hourValue.getText().toString()); int timerMinutes = Integer.valueOf(minuteValue.getText().toString()); long millis = System.currentTimeMillis() + (timerHours * 60 * 60 * 1000) + (timerMinutes * 60 * 1000); cal.setTimeInMillis(millis); String date = DateParser.formatDate(cal); String time = DateParser.parseTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), is24HourClock); dateTextView.setText(date); timeTextView.setText(time); timerLabel.setText(DateParser.parseTimer(timerHours, timerMinutes)); } }); // Set onClickListener for cancel button ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { // Update the timer-label in case the time has changed, // but only if a previous time has been set if (!timerLabel.getText().toString().equals("Set timer")) { int timerHours = Integer.valueOf(hourValue.getText().toString()); int timerMinutes = Integer.valueOf(minuteValue.getText().toString()); timerLabel.setText(DateParser.parseTimer(timerHours, timerMinutes)); } } }); final AlertDialog timerDialog = ad.create(); Window window = timerDialog.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); timerDialog.setIcon(R.drawable.timer2_32); timerDialog.setTitle("Set timer"); timerDialog.setView(timerView); timerDialog.show(); } private void registerReminder(Calendar cal, String desc, long oldTime) { am = (AlarmManager) getSystemService(ALARM_SERVICE); /* If rescheduling old reminder, remove it from database */ if (oldTime > 0) { PendingIntent oldIntent = newPendingIntent(oldTime, desc); am.cancel(oldIntent); int dbResult = dbAdapter.removeSingleReminder(oldTime); Log.d(DEBUG_TAG, "Rescheduling reminder, deleting " + dbResult + " rows from database"); } long newTime = cal.getTimeInMillis(); /* Check if a reminder with the same time already exists in the db. * If so, add 1 ms to the time and try again. */ while ( dbAdapter.singleReminderExists(newTime) ) { Log.d(DEBUG_TAG, "in the loop: " + newTime); ++newTime; } dbAdapter.insertSingleReminder(newTime, desc); PendingIntent newIntent = newPendingIntent(newTime, desc); // Intended use am.set(AlarmManager.RTC_WAKEUP, newTime, newIntent); /* Display a toast notifying the user */ boolean is24HourClock = preferences.getBoolean(getResources().getString(R.string.preferences_clock_format), false); String timeStr = DateParser.parseTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), is24HourClock); String dateStr = DateParser.formatDate(cal); String text = ""; if (oldTime == 0) { text = "New reminder scheduled for " + timeStr + " on " + dateStr + "."; } else { text = "Reminder rescheduled for " + timeStr + " on " + dateStr + ".";} Toast toast = Toast.makeText(SingleReminderActivity.this, text, Toast.LENGTH_LONG); toast.show(); } private PendingIntent newPendingIntent(long time, String desc) { Intent intent = new Intent(ReminderReceiver.ACTION_SINGLE_REMINDER); // Append some pseudo-random data, this is a hack to be able to schedule 2+ alarms intent.setDataAndType(Uri.parse("foo" + time), "com.aspartame.RemindMe/foo_type"); // Append useful data String soundUri = preferences.getString(getResources().getString(R.string.preferences_notification_sound), "default"); boolean vibrate = preferences.getBoolean(getResources().getString(R.string.preferences_vibration), true); intent.putExtra("soundUri", soundUri); intent.putExtra("vibrate", vibrate); intent.putExtra("desc", desc); intent.putExtra("time", time); intent.putExtra("isRepeat", false); PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); return pIntent; } @Override public void onDestroy() { dbAdapter.close(); super.onDestroy(); } }
36.890909
124
0.737872
2af26dd921780efd903d253a0082845f71973d34
553
/* * Copyright (c) 2004, 2017 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package hello; /* encapsulates a javax.jms.ObjectMessage that is sent */ public class OrderMessage implements java.io.Serializable { public String name; public String quantity; public String date; };
24.043478
78
0.734177
9c004de33aabdf6a451f68279e952930e5c86e46
132
package com.jmonkeystore.ide.editor.component; public interface PropertyChangedEvent { void propertyChanged(Object value); }
16.5
46
0.795455
8b5c7c3b4989f5875af1c7b3bb91c43aabb4c5d6
2,790
package blockstorage; import java.io.FileInputStream; import java.io.IOException; public class WriteToHDFS implements Runnable { private Cache cache; private SSD SSD; private HDFSLayer HDFSlayer; private BlockServer server; private Utils utils; String SSD_LOCATION; WriteToHDFS(Cache cache, SSD SSD, HDFSLayer HDFSlayer, BlockServer server, Utils utils){ this.cache = cache; this.SSD = SSD; this.HDFSlayer = HDFSlayer; this.server = server; this.utils = utils; this.SSD_LOCATION = utils.getSSD_LOCATION(); } synchronized void doWork() throws InterruptedException{ if(SSD.writeToHDFSQueue.size() > 0) { int pageNumber = SSD.writeToHDFSQueue.remove(); if(pageNumber == -1){return;} // if(!server.pageIndex.get(pageNumber).isLocationSSD()){ // System.out.println("Page "+pageNumber+" not in SSD."); // return; // } // System.out.println(pageNumber); server.debugLog("HDFS,2,"+pageNumber+", pageNumber "+pageNumber+" removed from writeToHDFSQueue"); String fileName = SSD_LOCATION + "/" + pageNumber; // File file = new File(fileName); try { SSD.pointersListLock.lock(); if(SSD.pointersList.contains(pageNumber) && server.pageIndex.get(pageNumber).isDirty()) { FileInputStream in = new FileInputStream(fileName); // System.out.println("Writing "+pageNumber+" to HDFS."); byte[] pageData = new byte[utils.PAGE_SIZE]; in.read(pageData); in.close(); Page page = new Page(pageNumber, pageData); HDFSlayer.writePage(page, server); server.pageIndex.updatePageIndex(pageNumber, -1, 0, 1, -1); server.debugLog("HDFS,1,"+pageNumber+", pageNumber "+pageNumber+" written to HDFSLayer"); } else{ server.pageIndex.updatePageIndex(pageNumber, -1, 0, -1, -1); } // file.delete(); SSD.pointersList.remove(pageNumber); SSD.pointersListLock.unlock(); server.debugLog("SSD,1,"+pageNumber+", pageNumber "+pageNumber+" removed from SSD"); } catch (IOException e) { System.out.println("Exception Occurred:"); e.printStackTrace(); } } else{ Thread.sleep(10); } } public void run(){ while (true) { try{ // server.Lock2.lock(); doWork(); // server.Lock2.unlock(); } catch(InterruptedException e){ System.out.println("InterruptedException in Write to HDFS thread: " + e); } // System.out.println("writeToHDFSQueue.size()="+SSD.writeToHDFSQueue.size()+" SSD.pointersList.size()="+SSD.pointersList.size()+" SSD.recencylist.size="+SSD.recencyList.size()+" server.writeToHDFSStop="+server.writeToHDFSStop); if(server.writeToHDFSStop){ if(!server.removeFromSSDThread.isAlive() && SSD.writeToHDFSQueue.size() == 0){ break; } } } System.out.println("Write to HDFS thread ended."); } }
31
232
0.678495
d8a0377c4c8e9a6039df724c3de1c39fdc49eeb0
4,134
/* * 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 brooklyn.entity.proxy.nginx; import java.util.Collection; import brooklyn.config.ConfigKey; import brooklyn.entity.Entity; import brooklyn.entity.annotation.Effector; import brooklyn.entity.basic.AbstractGroup; import brooklyn.entity.basic.ConfigKeys; import brooklyn.entity.basic.MethodEffector; import brooklyn.entity.proxy.AbstractController; import brooklyn.entity.proxy.ProxySslConfig; import brooklyn.entity.proxying.ImplementedBy; import brooklyn.event.AttributeSensor; import brooklyn.event.basic.Sensors; import brooklyn.util.flags.SetFromFlag; import com.google.common.reflect.TypeToken; /** * This is a group whose members will be made available to a load-balancer / URL forwarding service (such as nginx). * Configuration requires a <b>domain</b> and some mechanism for finding members. * The easiest way to find members is using a <b>target</b> whose children will be tracked, * but alternative membership policies can also be used. */ @ImplementedBy(UrlMappingImpl.class) public interface UrlMapping extends AbstractGroup { MethodEffector<Void> DISCARD = new MethodEffector<Void>(UrlMapping.class, "discard"); @SetFromFlag("label") ConfigKey<String> LABEL = ConfigKeys.newStringConfigKey( "urlmapping.label", "optional human-readable label to identify a server"); @SetFromFlag("domain") ConfigKey<String> DOMAIN = ConfigKeys.newStringConfigKey( "urlmapping.domain", "domain (hostname, e.g. www.foo.com) to present for this URL map rule; required."); @SetFromFlag("path") ConfigKey<String> PATH = ConfigKeys.newStringConfigKey( "urlmapping.path", "URL path (pattern) for this URL map rule. Currently only supporting regex matches "+ "(if not supplied, will match all paths at the indicated domain)"); @SetFromFlag("ssl") ConfigKey<ProxySslConfig> SSL_CONFIG = AbstractController.SSL_CONFIG; @SetFromFlag("rewrites") @SuppressWarnings("serial") ConfigKey<Collection<UrlRewriteRule>> REWRITES = ConfigKeys.newConfigKey(new TypeToken<Collection<UrlRewriteRule>>() { }, "urlmapping.rewrites", "Set of URL rewrite rules to apply"); @SetFromFlag("target") ConfigKey<Entity> TARGET_PARENT = ConfigKeys.newConfigKey(Entity.class, "urlmapping.target.parent", "optional target entity whose children will be pointed at by this mapper"); @SuppressWarnings("serial") AttributeSensor<Collection<String>> TARGET_ADDRESSES = Sensors.newSensor(new TypeToken<Collection<String>>() { }, "urlmapping.target.addresses", "set of addresses which should be forwarded to by this URL mapping"); String getUniqueLabel(); /** Adds a rewrite rule, must be called at config time. See {@link UrlRewriteRule} for more info. */ UrlMapping addRewrite(String from, String to); /** Adds a rewrite rule, must be called at config time. See {@link UrlRewriteRule} for more info. */ UrlMapping addRewrite(UrlRewriteRule rule); String getDomain(); String getPath(); Entity getTarget(); void setTarget(Entity target); void recompute(); Collection<String> getTargetAddresses(); ProxySslConfig getSsl(); @Effector(description="Unmanages the url-mapping, so it is discarded and no longer applies") void discard(); }
40.135922
125
0.740929
bcbed1c837eccb53bd094d8b02b6b607ae83a0dc
1,590
package com.horse.v7mc.mapperInterface; import java.util.Date; import java.util.List; import com.horse.v7mc.po.V7RollMonthAccounts; import org.apache.ibatis.annotations.Param; import com.horse.v7mc.po.V7RollDayAccounts; import com.horse.v7mc.po.V7RollDayAccountsExample; import com.horse.v7mc.queryVo.RollDayAccountsQVo; public interface V7RollDayAccountsMapper { int countByExample(V7RollDayAccountsExample example); int deleteByExample(V7RollDayAccountsExample example); int deleteByPrimaryKey(String id); int insert(V7RollDayAccounts record); int insertSelective(V7RollDayAccounts record); List<V7RollDayAccounts> selectByExample(V7RollDayAccountsExample example); V7RollDayAccounts selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") V7RollDayAccounts record, @Param("example") V7RollDayAccountsExample example); int updateByExample(@Param("record") V7RollDayAccounts record, @Param("example") V7RollDayAccountsExample example); int updateByPrimaryKeySelective(V7RollDayAccounts record); int updateByPrimaryKey(V7RollDayAccounts record); int getTotalAmount(RollDayAccountsQVo queryVo); List<V7RollDayAccounts> getPageData(RollDayAccountsQVo queryVo); Integer queryIsRoll(String isRoll); V7RollDayAccounts rollDay4Rec(@Param("startDate") String startDate,@Param("endDate") String endDate); V7RollDayAccounts queryChart(Date charDate); /** * 月运营数据统计调度 * @param lastMonth * @return */ V7RollMonthAccounts monthAccountsSchedule(String lastMonth); V7RollDayAccounts businessReport(); }
29.444444
128
0.803774
9d9dbd7fb275a1bd1a29754a0b36c935dbcdec90
4,274
package com.ziroom.ziroomcustomer.newclean.periodclean.bean; public class OrderDetailBean { private String burningTimeName; private String cityCode; private String cityName; private String connectName; private String connectPhone; private String createTimeName; private String cyclePlanCode; private String cyclePlanName; private String employeeCode; private String firstAppointmentTime; private String firstAppointmentTimeName; private String orderAddress; private String orderStatus; private String orderStatusName; private String planOrderCode; private String productCode; private String productName; private String remark; private String serviceTimeName; public String getBurningTimeName() { return this.burningTimeName; } public String getCityCode() { return this.cityCode; } public String getCityName() { return this.cityName; } public String getConnectName() { return this.connectName; } public String getConnectPhone() { return this.connectPhone; } public String getCreateTimeName() { return this.createTimeName; } public String getCyclePlanCode() { return this.cyclePlanCode; } public String getCyclePlanName() { return this.cyclePlanName; } public String getEmployeeCode() { return this.employeeCode; } public String getFirstAppointmentTime() { return this.firstAppointmentTime; } public String getFirstAppointmentTimeName() { return this.firstAppointmentTimeName; } public String getOrderAddress() { return this.orderAddress; } public String getOrderStatus() { return this.orderStatus; } public String getOrderStatusName() { return this.orderStatusName; } public String getPlanOrderCode() { return this.planOrderCode; } public String getProductCode() { return this.productCode; } public String getProductName() { return this.productName; } public String getRemark() { return this.remark; } public String getServiceTimeName() { return this.serviceTimeName; } public void setBurningTimeName(String paramString) { this.burningTimeName = paramString; } public void setCityCode(String paramString) { this.cityCode = paramString; } public void setCityName(String paramString) { this.cityName = paramString; } public void setConnectName(String paramString) { this.connectName = paramString; } public void setConnectPhone(String paramString) { this.connectPhone = paramString; } public void setCreateTimeName(String paramString) { this.createTimeName = paramString; } public void setCyclePlanCode(String paramString) { this.cyclePlanCode = paramString; } public void setCyclePlanName(String paramString) { this.cyclePlanName = paramString; } public void setEmployeeCode(String paramString) { this.employeeCode = paramString; } public void setFirstAppointmentTime(String paramString) { this.firstAppointmentTime = paramString; } public void setFirstAppointmentTimeName(String paramString) { this.firstAppointmentTimeName = paramString; } public void setOrderAddress(String paramString) { this.orderAddress = paramString; } public void setOrderStatus(String paramString) { this.orderStatus = paramString; } public void setOrderStatusName(String paramString) { this.orderStatusName = paramString; } public void setPlanOrderCode(String paramString) { this.planOrderCode = paramString; } public void setProductCode(String paramString) { this.productCode = paramString; } public void setProductName(String paramString) { this.productName = paramString; } public void setRemark(String paramString) { this.remark = paramString; } public void setServiceTimeName(String paramString) { this.serviceTimeName = paramString; } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/newclean/periodclean/bean/OrderDetailBean.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
19.427273
150
0.709172
9bb2a8f51644440018ebefb00fd8ebe976fb9c27
774
/* * Copyright (c) 2015 MONKEYK Information Technology Co. Ltd * www.monkeyk.com * All rights reserved. * * This software is the confidential and proprietary information of * MONKEYK Information Technology Co. Ltd ("Confidential Information"). * You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you * entered into with MONKEYK Information Technology Co. Ltd. */ package com.monkeyk.os.domain.users; import com.monkeyk.os.domain.shared.Repository; import java.util.List; /** * 2015/10/26 * * @author Shengzhao Li */ public interface UsersRepository extends Repository { Users findUsersByUsername(String username); List<Roles> findRolesByUsername(String username); }
26.689655
71
0.75969
f7385f59b967b946cf283c2ad3b92286b926fced
5,620
/** * Copyright (C) 2011 Metropolitan Transportation Authority * * 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.onebusaway.enterprise.webapp.actions.wiki; import java.text.DateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.jsp.JspException; import org.onebusaway.util.services.configuration.ConfigurationService; import org.onebusaway.enterprise.webapp.actions.OneBusAwayEnterpriseActionSupport; import org.onebusaway.enterprise.webapp.actions.wiki.model.NycWikiPageWrapper; import org.onebusaway.wiki.api.WikiDocumentService; import org.onebusaway.wiki.api.WikiRenderingService; import org.springframework.beans.factory.annotation.Autowired; public class IndexAction extends OneBusAwayEnterpriseActionSupport { private static final long serialVersionUID = 1L; @Autowired private WikiDocumentService _wikiDocumentService; @Autowired private WikiRenderingService _wikiRenderingService; @Autowired private ConfigurationService _configurationService; protected String namespace; protected String name; private boolean forceRefresh = false; private String content; private String title; private String editLink; private Date lastModifiedTimestamp; private String toc; private String adminToc; private boolean hasToc = false; private static final Pattern tocLinkPattern = Pattern.compile("<a[^>]?href=\"([^\"]*)\"[^>]?>[^<]*</a>"); public void setForceRefresh(boolean forceRefresh){ this.forceRefresh = forceRefresh; } public boolean isAdmin() { return _currentUserService.isCurrentUserAdmin(); } public boolean getHasToc() { return hasToc; } public String getGoogleAdClientId() { return _configurationService.getConfigurationValueAsString("display.googleAdsClientId", ""); } // FIXME: should replace namespace at the service level? public String getEditLink() { return editLink.replace("%{namespace}", namespace); } // FIXME: should replace namespace at the service level? public String getContent() { return content.replace("%{namespace}", namespace); } public String getTitle() { return title; } public String getToc() { String tocContent = toc; if(adminToc != null) tocContent += adminToc; // find all links in the TOC; add class="active" to the one that points to // the page we're viewing now. Matcher m = tocLinkPattern.matcher(tocContent); while (m.find()) { String match = m.group(); String matchLinkUrl = m.group(1); if(matchLinkUrl != null) { String urlEnd = this.namespace + "/" + this.name; if(matchLinkUrl.endsWith(urlEnd)) { String newMatch = match.replace("href=", "class=\"active\" href="); return tocContent.replace(match, newMatch); } } } return tocContent; } public String getLastModifiedTimestamp() { if(lastModifiedTimestamp == null) return "Unknown"; return DateFormat.getDateInstance().format(lastModifiedTimestamp) + " at " + DateFormat.getTimeInstance().format(lastModifiedTimestamp); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } @Override public String execute() throws Exception { if(namespace == null || namespace.isEmpty()) { namespace = "Main"; } if(name == null || name.isEmpty()) { name = "Index"; } if (namespace != null && name != null) { // try to get TOC page for this namespace try { NycWikiPageWrapper page = new NycWikiPageWrapper(_wikiDocumentService.getWikiPage(namespace, "TOC", getLocale(), forceRefresh)); if(page.pageExists()) { toc = _wikiRenderingService.renderPage(page); hasToc = true; } else { toc = null; hasToc = false; } } catch (Exception ex) { toc = null; hasToc = false; } if(this.isAdmin()) { // try to get admin TOC page for this namespace try { NycWikiPageWrapper adminPage = new NycWikiPageWrapper(_wikiDocumentService.getWikiPage(namespace, "AdminTOC", getLocale(), forceRefresh)); if(adminPage.pageExists()) { adminToc = _wikiRenderingService.renderPage(adminPage); hasToc = true; } else { adminToc = null; } } catch(Exception ex) { adminToc = null; } } else { adminToc = null; } // content for page try { NycWikiPageWrapper page = new NycWikiPageWrapper(_wikiDocumentService.getWikiPage(namespace, name, getLocale(), false)); if(page.pageExists()) { content = _wikiRenderingService.renderPage(page); editLink = _wikiRenderingService.getEditLink(page); title = page.getTitle(); lastModifiedTimestamp = page.getLastModified(); } else { content = null; editLink = null; title = null; lastModifiedTimestamp = null; return "NotFound"; } } catch (Exception ex) { throw new JspException(ex); } } return SUCCESS; } }
26.635071
114
0.702313
a071f881f9a8c4676a80efabd7031cbefdb80487
1,968
package seedu.address.logic.commands; import java.util.ArrayList; import seedu.address.logic.CommandObserver; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; /** * Represents a command with hidden internal logic and the ability to be executed. */ public abstract class Command { private static final ArrayList<CommandObserver> commandObservers = new ArrayList<>(); public static void setCommandObserver(CommandObserver commandObserver) { commandObservers.add(commandObserver); } /** * Updates the CommandObservers by calling the updateView method for each of them. * * @param indexOfTabToView index of tab to be viewed. */ public void updateView(Integer indexOfTabToView) { for (CommandObserver commandObserver : commandObservers) { commandObserver.updateView(indexOfTabToView); } } /** * Updates the CommandObservers by calling the updateClass command. * * @param indexOfClassToSelect index of class to be selected. */ public void updateClass(Integer indexOfClassToSelect) { for (CommandObserver commandObserver : commandObservers) { commandObserver.updateClass(indexOfClassToSelect); } } /** * Updates the CommandObservers by calling the hideTuitionClassStudentList command. */ public void hideTuitionClassStudentList() { for (CommandObserver commandObserver : commandObservers) { commandObserver.hideTuitionClassStudentList(); } } /** * Executes the command and returns the result message. * * @param model {@code Model} which the command should operate on. * @return feedback message of the operation result for display * @throws CommandException If an error occurs during command execution. */ public abstract CommandResult execute(Model model) throws CommandException; }
32.262295
89
0.70935
91c0222fd7dede07d6b2aff6b9b96634e66d0d42
1,108
package applications.spout; import applications.spout.generator.WCGenerator; import brisk.components.operators.api.AbstractSpout; import brisk.execution.ExecutionGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static applications.Constants.DEFAULT_STREAM_ID; public class WCGeneratorSpout extends AbstractSpout { private static final Logger LOG = LoggerFactory.getLogger(WCGeneratorSpout.class); private static final long serialVersionUID = 7738169734935576086L; private WCGenerator Generator; public WCGeneratorSpout() { super(LOG); } @Override public void initialize(int thread_Id, int thisTaskId, ExecutionGraph graph) { super.initialize(thread_Id, thisTaskId, graph); String delimiter = ","; int number_of_words = 10; Generator = new WCGenerator(this.getContext().getThisTaskId(), number_of_words, delimiter); } @Override public void cleanup() { } @Override public void nextTuple() throws InterruptedException { collector.emit(DEFAULT_STREAM_ID, Generator.next()); } }
29.157895
99
0.737365
d3db09897adcd6fe5f9ca3178837e681e5864d2c
2,526
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.ui; import com.google.gerrit.client.Gerrit; import com.google.gwt.aria.client.Roles; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Widget; public class LinkMenuBar extends Composite implements ScreenLoadHandler { private final FlowPanel body; public LinkMenuBar() { body = new FlowPanel(); initWidget(body); setStyleName(Gerrit.RESOURCES.css().linkMenuBar()); Roles.getMenubarRole().set(getElement()); Gerrit.EVENT_BUS.addHandler(ScreenLoadEvent.TYPE, this); } public void addItem(String text, Command imp) { add(new CommandMenuItem(text, imp)); } public void addItem(CommandMenuItem i) { add(i); } public void addItem(LinkMenuItem i) { i.setMenuBar(this); add(i); } public void insertItem(LinkMenuItem i, int beforeIndex) { i.setMenuBar(this); insert(i, beforeIndex); } public void clear() { body.clear(); } public LinkMenuItem find(String targetToken) { for (Widget w : body) { if (w instanceof LinkMenuItem) { LinkMenuItem m = (LinkMenuItem) w; if (targetToken.equals(m.getTargetHistoryToken())) { return m; } } } return null; } public void add(Widget i) { if (body.getWidgetCount() > 0) { final Widget p = body.getWidget(body.getWidgetCount() - 1); p.addStyleName(Gerrit.RESOURCES.css().linkMenuItemNotLast()); } body.add(i); } public void insert(Widget i, int beforeIndex) { if (body.getWidgetCount() == 0 || body.getWidgetCount() <= beforeIndex) { add(i); return; } body.insert(i, beforeIndex); } public int getWidgetIndex(Widget i) { return body.getWidgetIndex(i); } @Override public void onScreenLoad(ScreenLoadEvent event) {} }
27.456522
77
0.69042
5ee7e7964b00deeac461a6ef12ba573bf3ae3f3d
7,345
package com.zj.wheelview.activity; import android.content.Intent; import android.os.Handler; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.alibaba.fastjson.JSON; import com.loopj.android.http.AsyncHttpResponseHandler; import com.zj.wheelview.NetApi; import com.zj.wheelview.R; import com.zj.wheelview.adapter.OrderAdapter; import com.zj.wheelview.view.DividerItemDecoration; import com.zj.wheelview.view.LoadMoreRecyclerView; import com.zj.wheelview.view.swiperefreshlayout.SwipyRefreshLayout; import com.zj.wheelview.view.swiperefreshlayout.SwipyRefreshLayoutDirection; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.InjectView; import cz.msebera.android.httpclient.Header; public class MerchantOrderListActivity extends BaseActivity implements LoadMoreRecyclerView.LoadMoreListener, OrderAdapter.OnRecyclerViewListener, SwipyRefreshLayout.OnRefreshListener { private static final int UPDATE_ORDER = 1; @InjectView(R.id.rvOrderList) LoadMoreRecyclerView rvOrderList; @InjectView(R.id.swiperefreshlayout) SwipyRefreshLayout swiperefreshlayout; List<OrderModel> orderList = new ArrayList<>(); OrderAdapter mAdapter; String settle_date; int pageSize = 20; int pagenum = 1; int mState = 0;//0没刷新,1正在刷新 int index = -1; boolean hasMore = false; @Override protected boolean hasBackButton() { return true; } @Override protected int getLayoutResId() { return R.layout.activity_merchant_order_list; } @Override protected int getTitleResId() { return R.string.title_activity_merchant_order_list; } @Override protected void initViews() { settle_date = getIntent().getStringExtra("settle_date"); //获取商户订单列表 getOrderList(pagenum, pageSize); swiperefreshlayout.setColorSchemeResources( android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); swiperefreshlayout.setOnRefreshListener(this); swiperefreshlayout.setDirection(SwipyRefreshLayoutDirection.TOP); rvOrderList.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MerchantOrderListActivity.this); rvOrderList.setLayoutManager(layoutManager); rvOrderList.setLoadMoreListener(this); rvOrderList.setAutoLoadMoreEnable(hasMore); mAdapter = new OrderAdapter(orderList); mAdapter.setOnRecyclerViewListener(this); rvOrderList.setAdapter(mAdapter); rvOrderList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); } private void getOrderList(final int pagenum, int pageSzie) { if (pagenum == 1) { showWaitDialog(); } NetApi.getOrderList(MerchantOrderListActivity.this, settle_date, settle_date, pagenum, pageSzie, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { hideWaitDialog(); try { if (responseBody != null) { String result = new String(responseBody); LogUtil.log("result----" + result); JSONObject obj = new JSONObject(result); String resultCode = obj.getString("resultCode"); //String msg = obj.getString("msg"); if ("00".equals(resultCode)) { String data = obj.getString("data"); List<OrderModel> list = JSON.parseArray(data, OrderModel.class); orderList.addAll(list); mAdapter.refreshData(orderList); if (pagenum < Integer.parseInt(obj.getString("totalPage"))) { hasMore = true; }else { hasMore = false; } if (mState == 1) { mAdapter.notifyDataSetChanged(); rvOrderList.setAutoLoadMoreEnable(hasMore); }else { rvOrderList.notifyMoreFinish(hasMore); } }else { //CommonUtil.showToastMessage(MerchantOrderListActivity.this, msg); } } }catch (JSONException e) { e.printStackTrace(); } doneRefresh(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { hideWaitDialog(); doneRefresh(); if (responseBody != null) { String result = new String(responseBody); LogUtil.log("result----" + result); } } }); } @Override public void onItemClick(int position) { if (orderList != null && orderList.size() > 0) { index = position; OrderModel orderModel = orderList.get(position); //跳转至订单详情 Intent intent = new Intent(MerchantOrderListActivity.this, OrderDetailActivity.class); intent.putExtra("orderModel", orderModel); startActivityForResult(intent, UPDATE_ORDER); } } @Override public void onRefresh() { if (mState != 1) { //清空原有数据集 orderList.clear(); setSwipeRefreshLoadingState(); pagenum = 1; mState = 1; getOrderList(pagenum, pageSize); } } //刷新完之后 public void doneRefresh() { setSwipeRefreshLoadedState(); mState = 0; } @Override public void onLoadMore() { new Handler().postDelayed(new Runnable() { @Override public void run() { pagenum++; getOrderList(pagenum, pageSize); } }, 1000); } /** 设置顶部正在加载的状态*/ private void setSwipeRefreshLoadingState() { if (swiperefreshlayout != null) { swiperefreshlayout.setRefreshing(true); // 防止多次重复刷新 swiperefreshlayout.setEnabled(false); } } /** 设置顶部加载完毕的状态*/ private void setSwipeRefreshLoadedState() { if (swiperefreshlayout != null) { swiperefreshlayout.setRefreshing(false); swiperefreshlayout.setEnabled(true); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == UPDATE_ORDER && resultCode == RESULT_OK) { orderList.remove(index); orderList.add(index, (OrderModel) data.getSerializableExtra("orderModel")); mAdapter.notifyDataSetChanged(); } super.onActivityResult(requestCode, resultCode, data); } }
36.004902
138
0.593329
702f5cfa05772e9ffab16760b39ec13f153ee1d7
6,326
/* * 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.iotdb.confignode.manager; import org.apache.iotdb.common.rpc.thrift.TConfigNodeLocation; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.TSStatus; import org.apache.iotdb.commons.consensus.ConsensusGroupId; import org.apache.iotdb.commons.consensus.PartitionRegionId; import org.apache.iotdb.commons.utils.TestOnly; import org.apache.iotdb.confignode.client.SyncConfigNodeClientPool; import org.apache.iotdb.confignode.conf.ConfigNodeConf; import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor; import org.apache.iotdb.confignode.consensus.request.ConfigRequest; import org.apache.iotdb.confignode.consensus.request.write.ApplyConfigNodeReq; import org.apache.iotdb.confignode.consensus.statemachine.PartitionRegionStateMachine; import org.apache.iotdb.consensus.ConsensusFactory; import org.apache.iotdb.consensus.IConsensus; import org.apache.iotdb.consensus.common.Peer; import org.apache.iotdb.consensus.common.response.ConsensusReadResponse; import org.apache.iotdb.consensus.common.response.ConsensusWriteResponse; import org.apache.iotdb.rpc.TSStatusCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** ConsensusManager maintains consensus class, request will redirect to consensus layer */ public class ConsensusManager { private static final Logger LOGGER = LoggerFactory.getLogger(ConsensusManager.class); private static final ConfigNodeConf conf = ConfigNodeDescriptor.getInstance().getConf(); private ConsensusGroupId consensusGroupId; private IConsensus consensusImpl; public ConsensusManager(PartitionRegionStateMachine stateMachine) throws IOException { setConsensusLayer(stateMachine); } public void close() throws IOException { consensusImpl.stop(); } @TestOnly public void singleCopyMayWaitUntilLeaderReady() { if (conf.getConfigNodeList().size() == 1) { long startTime = System.currentTimeMillis(); long maxWaitTime = 1000 * 60; // milliseconds, which is 60s try { while (!consensusImpl.isLeader(consensusGroupId)) { Thread.sleep(100); long elapsed = System.currentTimeMillis() - startTime; if (elapsed > maxWaitTime) { return; } } } catch (InterruptedException ignored) { } } } /** Build ConfigNodeGroup ConsensusLayer */ private void setConsensusLayer(PartitionRegionStateMachine stateMachine) throws IOException { // There is only one ConfigNodeGroup consensusGroupId = new PartitionRegionId(conf.getPartitionRegionId()); // Consensus local implement consensusImpl = ConsensusFactory.getConsensusImpl( conf.getConfigNodeConsensusProtocolClass(), new TEndPoint(conf.getRpcAddress(), conf.getConsensusPort()), new File(conf.getConsensusDir()), gid -> stateMachine) .orElseThrow( () -> new IllegalArgumentException( String.format( ConsensusFactory.CONSTRUCT_FAILED_MSG, conf.getConfigNodeConsensusProtocolClass()))); consensusImpl.start(); // Build consensus group from iotdb-confignode.properties LOGGER.info("Set ConfigNode consensus group {}...", conf.getConfigNodeList()); List<Peer> peerList = new ArrayList<>(); for (TConfigNodeLocation configNodeLocation : conf.getConfigNodeList()) { peerList.add(new Peer(consensusGroupId, configNodeLocation.getConsensusEndPoint())); } consensusImpl.addConsensusGroup(consensusGroupId, peerList); // Apply ConfigNode if necessary if (conf.isNeedApply()) { TSStatus status = SyncConfigNodeClientPool.getInstance() .applyConfigNode( conf.getTargetConfigNode(), new TConfigNodeLocation( new TEndPoint(conf.getRpcAddress(), conf.getRpcPort()), new TEndPoint(conf.getRpcAddress(), conf.getConsensusPort()))); if (status.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) { LOGGER.error(status.getMessage()); throw new IOException("Apply ConfigNode failed:"); } } } /** * Apply new ConfigNode Peer into PartitionRegion * * @param applyConfigNodeReq ApplyConfigNodeReq * @return True if successfully addPeer. False if another ConfigNode is being added to the * PartitionRegion */ public boolean addConfigNodePeer(ApplyConfigNodeReq applyConfigNodeReq) { return consensusImpl .addPeer( consensusGroupId, new Peer( consensusGroupId, applyConfigNodeReq.getConfigNodeLocation().getConsensusEndPoint())) .isSuccess(); } /** Transmit PhysicalPlan to confignode.consensus.statemachine */ public ConsensusWriteResponse write(ConfigRequest req) { return consensusImpl.write(consensusGroupId, req); } /** Transmit PhysicalPlan to confignode.consensus.statemachine */ public ConsensusReadResponse read(ConfigRequest req) { return consensusImpl.read(consensusGroupId, req); } public boolean isLeader() { return consensusImpl.isLeader(consensusGroupId); } public ConsensusGroupId getConsensusGroupId() { return consensusGroupId; } // TODO: Interfaces for LoadBalancer control }
38.809816
95
0.720044
1c566b98f038b1a373e64e4d1881ae3cd47d4c73
806
package com.corosus.game.ai.btree; import com.badlogic.gdx.ai.btree.LeafTask; import com.badlogic.gdx.ai.btree.Task; import com.corosus.game.Logger; import com.corosus.game.ai.Blackboard; public class RandomTest extends LeafTask<Blackboard> { private float randChance = 0.2F; private String debug = ""; public RandomTest() { } public RandomTest setDebug(String debug) { this.debug = debug; return this; } @Override public void run() { if (Math.random() < randChance) { Logger.dbg("hit success chance, dbg: " + debug); success(); } else { Logger.dbg("still executing RandomChance, dbg: " + debug); } } @Override protected Task<Blackboard> copyTo(Task<Blackboard> task) { RandomTest test = (RandomTest) task; test.randChance = randChance; return task; } }
19.658537
61
0.698511
b293d48f0f8bd3a6668759bcecb39bba349f2116
2,271
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.masterdata.din; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.annotation.Nonempty; import com.helger.commons.lang.EnumHelper; /** * DIN C. Width and height are in portrait mode.<br> * <a href= * "http://www.din-formate.de/reihe-c-din-groessen-liste-papierformate-seitengroesse-masseinheiten-in-dpi-mm-pixel.html" * >Source</a> * * @author Philip Helger */ public enum EDINC implements IDINSize { C0 ("c0", 917, 1297), C1 ("c1", 648, 917), C2 ("c2", 458, 648), C3 ("c3", 324, 458), C4 ("c4", 229, 324), C5 ("c5", 162, 229), C6 ("c6", 114, 162), C7 ("c7", 81, 114), C8 ("c8", 57, 81), C9 ("c9", 40, 57), C10 ("c10", 28, 40); private final String m_sID; private final int m_nWidthMM; private final int m_nHeightMM; EDINC (@Nonnull @Nonempty final String sID, @Nonnegative final int nWidthMM, @Nonnegative final int nHeightMM) { m_sID = sID; m_nWidthMM = nWidthMM; m_nHeightMM = nHeightMM; } @Nonnull @Nonempty public String getID () { return m_sID; } @Nonnegative public int getWidthMM () { return m_nWidthMM; } @Nonnegative public int getHeightMM () { return m_nHeightMM; } @Nullable public static EDINC getFromIDOrNull (@Nullable final String sID) { return EnumHelper.getFromIDOrNull (EDINC.class, sID); } @Nullable public static EDINC getFromIDOrDefault (@Nullable final String sID, @Nullable final EDINC eDefault) { return EnumHelper.getFromIDOrDefault (EDINC.class, sID, eDefault); } }
25.233333
120
0.692206
7d0a40fdfcff49048b540042dea4954f4f884b83
2,077
package com.xiaoji.android.rabbitmq; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.content.ComponentName; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import com.xiaoji.cordova.plugin.rabbitmq.RabbitMQPlugin; public class RabbitMQInterface { public static void init(Context ctx, final RabbitMQPlugin plugin, JSONArray args) { Log.i("RabbitMQPlugin", "RabbitMQInterface init"); Intent intent = new Intent(ctx, RabbitMQClientService.class); // 设置初始化参数 if (args.length() == 5) { try { intent.putExtra("queueName", args.getString(0)); intent.putExtra("host", args.getString(1)); intent.putExtra("port", args.getString(2)); intent.putExtra("user", args.getString(3)); intent.putExtra("passwd", args.getString(4)); } catch (JSONException e) { Log.e("RabbitMQPlugin", "Arguments json Exception.", e.getCause()); } //ctx.startService(intent); Log.i("RabbitMQPlugin", "starting rmq service connection."); ctx.bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("RabbitMQPlugin", "rmq service connected."); RabbitMQClientService.MyBinder binder = (RabbitMQClientService.MyBinder) service; plugin.service = binder.getService(); } @Override public void onServiceDisconnected(ComponentName name) { Log.i("RabbitMQPlugin", "rmq service disconnected."); // fireEvent(BackgroundMode.Event.FAILURE, "'service disconnected'"); } }, Context.BIND_AUTO_CREATE); } else { Log.i("RabbitMQPlugin", "RabbitMQInterface init with no parameters, service unstarted."); } } }
39.188679
99
0.623977
f973c6a1f0437c43b2d35e3d696aa622f55ec33c
320
package br.com.zup.edu.stephanie.propostas.repository; import br.com.zup.edu.stephanie.propostas.model.Cartao; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface CartaoRepository extends JpaRepository<Cartao, Long> { Optional<Cartao> findById(String id); }
26.666667
71
0.809375
3ebd123a19f31635168e343b7fdd016e6f4f0506
812
package de.lmu.treeapp.activities.minigames.catchFruits; import android.graphics.Path; import android.graphics.RectF; import me.samlss.bloom.shape.ParticleShape; public class OvalShape extends ParticleShape { /** * Construct the shape of particle. * * @param centerX The center x coordinate of the particle. * @param centerY The center y coordinate of the particle. * @param radius The radius of the particle. */ public OvalShape(float centerX, float centerY, float radius) { super(centerX, centerY, radius); } @Override public void generateShape(Path path) { path.addOval(new RectF(getCenterX() - getRadius(), getCenterY() - getRadius(), getCenterX() + getRadius(), getCenterY() + getRadius()), Path.Direction.CW); } }
30.074074
114
0.678571
b5f9871799fb901451edf1d82a89eb580a91be10
776
package com.example.model; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.Date; @Data @EntityListeners(AuditingEntityListener.class) @MappedSuperclass abstract public class BaseEntity { @Id @GeneratedValue( strategy= GenerationType.AUTO, generator="native" ) @GenericGenerator( name = "native", strategy = "native" ) private Long id; @CreatedDate private Date createdDate; @LastModifiedDate private Date modifiedDate; }
22.171429
74
0.728093
187d4f9ab217c8e865b16657b97ff0ac1621310a
5,102
/* * Copyright (c) 2017 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 th.or.nectec.marlo.model; import android.os.Parcel; import android.os.Parcelable; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; public class MarloCoord implements Parcelable { public static final Parcelable.Creator<MarloCoord> CREATOR = new Parcelable.Creator<MarloCoord>() { @Override public MarloCoord createFromParcel(Parcel source) { return new MarloCoord(source); } @Override public MarloCoord[] newArray(int size) { return new MarloCoord[size]; } }; private double latitude; private double longitude; public MarloCoord(LatLng latLng) { this(latLng.latitude, latLng.longitude); } public MarloCoord(double latitude, double longitude) { setLatitude(latitude); setLongitude(longitude); } public MarloCoord(MarloCoord coordinate) { this(coordinate.getLatitude(), coordinate.getLongitude()); } //Parcelable private MarloCoord(Parcel in) { this(in.readDouble(), in.readDouble()); } public static MarloCoord fromMarker(Marker marker) { LatLng position = marker.getPosition(); return new MarloCoord(position.latitude, position.longitude); } public static MarloCoord fromGeoJson(String coordinate) { try { JSONArray array = new JSONArray(coordinate); return new MarloCoord(array.getDouble(1), array.getDouble(0)); } catch (JSONException json) { throw new RuntimeException(json); } } public static List<LatLng> toLatLngs(Iterable<MarloCoord> coordinates) { List<LatLng> latLngList = new ArrayList<>(); for (MarloCoord coord : coordinates) { latLngList.add(coord.toLatLng()); } return latLngList; } public static List<MarloCoord> clones(List<MarloCoord> blueprint) { List<MarloCoord> coords = new ArrayList<>(); for (MarloCoord coordinate : blueprint) { coords.add(new MarloCoord(coordinate)); } return coords; } public double getLatitude() { return latitude; } private void setLatitude(double latitude) { if (latitude < -90f || latitude > 90f) throw new IllegalArgumentException("-90 <= Latitude <= 90, Your values is " + latitude); this.latitude = latitude; } public double getLongitude() { return longitude; } private void setLongitude(double longitude) { if (longitude < -180f || longitude > 180f) throw new IllegalArgumentException("-180 <= longitude <= 180, Your value is " + longitude); this.longitude = longitude; } public LatLng toLatLng() { return new LatLng(latitude, longitude); } public JSONArray toGeoJson() { try { JSONArray jsonArray = new JSONArray(); jsonArray.put(0, longitude); jsonArray.put(1, latitude); return jsonArray; } catch (JSONException json) { throw new RuntimeException(json); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MarloCoord location = (MarloCoord) o; return Double.compare(location.latitude, latitude) == 0 && Double.compare(location.longitude, longitude) == 0; } @Override public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(latitude); result = (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(longitude); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return "Location{" + "latitude=" + latitude + ", longitude=" + longitude + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeDouble(this.latitude); dest.writeDouble(this.longitude); } }
29.836257
103
0.617013
496ee00a85ca61f8d892f2f61c188f3466a5d7bd
1,057
package org.ros.internal.node.response; import org.ros.internal.message.topic.TopicDescription; import org.ros.internal.node.topic.TopicDeclaration; import org.ros.namespace.GraphName; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A {@link ResultFactory} to take an object and turn it into a list of * {@link TopicDeclaration} instances. * * @author Jonathan Groff Copyright (C) NeoCoreTechs 2015,2017, 2021 */ public class TopicListResultFactory implements ResultFactory<List<TopicDeclaration>> { @Override public List<TopicDeclaration> newFromValue(Object value) { List<TopicDeclaration> descriptions = new ArrayList<TopicDeclaration>(); List<Object> topics = Arrays.asList((Object[]) value); for (Object topic : topics) { String name = (String) ((Object[]) topic)[0]; String type = (String) ((Object[]) topic)[1]; descriptions.add(TopicDeclaration.newFromTopicName(GraphName.of(name), new TopicDescription(type, null, null))); } return descriptions; } }
33.03125
109
0.728477
cd9b35ed0721f971663e773075b37669eb98084f
1,001
package de.pax.dsa.ui.internal.animations; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.scene.shape.Circle; import javafx.util.Duration; public class MoveCenterTransition extends Transition { private static final int SPEED_FACTOR = 5; private Circle circle; private double yDistance; private double xDistance; private double startX; private double startY; public MoveCenterTransition(Circle circle, double toX, double toY) { this.circle = circle; startX = circle.getCenterX(); startY = circle.getCenterY(); yDistance = toY - startY; xDistance = toX - startX; double dist = Math.sqrt(xDistance * xDistance + yDistance * yDistance); setCycleDuration(Duration.millis(dist * SPEED_FACTOR)); setInterpolator(Interpolator.LINEAR); } @Override protected void interpolate(double frac) { circle.setCenterX(startX + (xDistance * frac)); circle.setCenterY(startY + (yDistance * frac)); } }
26.342105
74
0.73027
2d0b5c678012c164f0b528a9fdcb6a1d83882c21
4,025
package com.simperium.models; import com.simperium.client.BucketObject; import com.simperium.client.BucketSchema; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Note extends BucketObject { public static class Schema extends BucketSchema<Note> { public static final String BUCKET_NAME="notes"; public Schema(){ autoIndex(); addIndex(contentIndexer); addIndex(nullIndexer); setupFullTextIndex("tags", "content"); setDefault("tags", new JSONArray()); setDefault("deleted", false); } private Indexer<Note> contentIndexer = new Indexer<Note>(){ @Override public List<Index> index(Note note){ List<Index> indexes = new ArrayList<Index>(1); indexes.add(new Index("preview", note.getPreview())); return indexes; } }; private Indexer<Note> nullIndexer = new Indexer<Note>() { @Override public List<Index> index(Note note) { List<Index> indexes = new ArrayList<Index>(1); indexes.add(new Index("null_column", null)); return indexes; } }; @Override public String getRemoteName(){ return BUCKET_NAME; } @Override public Note build(String key, JSONObject properties){ return new Note(key, properties); } @Override public void update(Note note, JSONObject properties){ note.setProperties(properties); } } private static final String SPACE=" "; private StringBuilder preview; public Note(String key, JSONObject properties){ super(key, properties); } public void addTag(String tag){ JSONArray tags = (JSONArray) get("tags"); tags.put(tag); } public void addTags(String ... newTags){ JSONArray tags = (JSONArray) get("tags"); for(String tag : newTags){ tags.put(tag); } } public void setTitle(String title){ put("title", title); } public String getTitle(){ return (String) get("title"); } public String getContent(){ return (String) get("content"); } public void setContent(String content){ preview = null; put("content", content); } public void put(String key, Object value){ try { getProperties().put(key, value); } catch (JSONException e) { // Do nothing } } public Object get(String key){ try { return getProperties().get(key); } catch (JSONException e) { // Do nothing return null; } } public CharSequence getPreview(){ if (preview != null) { return preview; } String content = getContent(); if (content == null) { return ""; } // just the first three lines preview = new StringBuilder(); int start = 0; int position = -1; int lines = 0; do { position = content.indexOf("\n", start); // if there are no new lines in the whole thing, we'll just take the whole thing if (position == -1 && start == 0) { position = content.length(); } if (position > start + 1) { int length = preview.length(); if (length > 0) { preview.append(SPACE); } preview.append(content.subSequence(start, position)); if (length > 320) { break; } lines ++; } start = position + 1; } while(lines < 3 && position > -1 && start > 0); return preview; } }
27.195946
92
0.524969
6cf0bffdb77d40122aaeb9e31f5f76ecb6b41ae2
399
package com.hardik.spring.dao; import java.util.List; import com.hardik.spring.model.Contact; /** * Contact DAO * * @author HARDIK HIRAPARA * */ public interface ContactDao { public List<Contact> getContacts(); public Contact getContactById(Integer id); public void saveContact(Contact contact); public void updateContact(Contact contact); public void deleteContact(Integer id); }
16.625
44
0.749373
2257f8c9797c7919463344afe5461799753804dc
2,072
package br.com.zup.edu.ecommerce.product; import br.com.zup.edu.ecommerce.category.Category; import br.com.zup.edu.ecommerce.product.feature.ProductFeatureRequest; import br.com.zup.edu.ecommerce.user.User; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; public class ProductRequest { @NotBlank private String name; @NotNull @Positive private BigDecimal price; @NotNull @Positive private Integer quantity; @NotBlank @Size(max = 1000) private String description; @NotNull @Size(min = 3, max = 200) private List<@Valid ProductFeatureRequest> features; @NotNull private Long categoryId; public ProductRequest(String name, BigDecimal price, Integer quantity, String description, List<@Valid ProductFeatureRequest> features, Long categoryId) { this.name = name; this.price = price; this.quantity = quantity; this.description = description; this.features = features; this.categoryId = categoryId; } public Product toModel(Category category, User user) { return new Product(name, price, quantity, description, features, category, user); } public Long getCategoryId() { return categoryId; } public List<ProductFeatureRequest> getFeatures() { return features; } public Set<String> findDuplicatedFeatures() { return features.stream() .map(ProductFeatureRequest::getName) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(e -> e.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } }
29.183099
158
0.683398
9304c26fe7cb57c9a9677d0901832686683fa7de
2,670
/* * 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 practica1; import javax.swing.JButton; /** * * @author Julia */ public class NodoMatriz { private int posicionX; private int posicionY; private NodoMatriz siguiente; private NodoMatriz anterior; private NodoMatriz abajo; private NodoMatriz arriba; private JButton boton; public NodoMatriz(int posicionX, int posicionY){ this.posicionX=posicionX; this.posicionY=posicionY; setSiguiente(null); setAnterior(null); setAbajo(null); setArriba(null); boton=new JButton(); } /** * @return the posicionX */ public int getPosicionX() { return posicionX; } /** * @param posicionX the posicionX to set */ public void setPosicionX(int posicionX) { this.posicionX = posicionX; } /** * @return the posicionY */ public int getPosicionY() { return posicionY; } /** * @param posicionY the posicionY to set */ public void setPosicionY(int posicionY) { this.posicionY = posicionY; } /** * @return the siguiente */ public NodoMatriz getSiguiente() { return siguiente; } /** * @param siguiente the siguiente to set */ public void setSiguiente(NodoMatriz siguiente) { this.siguiente = siguiente; } /** * @return the anterior */ public NodoMatriz getAnterior() { return anterior; } /** * @param anterior the anterior to set */ public void setAnterior(NodoMatriz anterior) { this.anterior = anterior; } /** * @return the abajo */ public NodoMatriz getAbajo() { return abajo; } /** * @param abajo the abajo to set */ public void setAbajo(NodoMatriz abajo) { this.abajo = abajo; } /** * @return the arriba */ public NodoMatriz getArriba() { return arriba; } /** * @param arriba the arriba to set */ public void setArriba(NodoMatriz arriba) { this.arriba = arriba; } /** * @return the boton */ public JButton getBoton() { return boton; } /** * @param boton the boton to set */ public void setBoton(JButton boton) { this.boton = boton; } }
20.381679
80
0.546442
e0b3675177e3f4c9c9395e789d5a960962a151e9
2,052
package com.github.trackexpenses.adapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.github.trackexpenses.R; import com.github.trackexpenses.models.Library; import java.util.List; import kotlin.Pair; public class OverviewAdapter extends RecyclerView.Adapter<OverviewAdapter.ViewHolder> { private List<Pair<String,String>> mData; private LayoutInflater mInflater; private Context context; // data is passed into the constructor public OverviewAdapter(Context context, List<Pair<String,String>> mData) { this.context = context; updateData(mData); this.mInflater = LayoutInflater.from(context); } public void updateData(List<Pair<String,String>> mData) { this.mData = mData; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.row_overview, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.title.setText(mData.get(position).getFirst()); holder.content.setText(mData.get(position).getSecond()); } // total number of rows @Override public int getItemCount() { return (mData == null)?0:mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder { TextView title, content; ViewHolder(View itemView) { super(itemView); title = itemView.findViewById(R.id.title_overview); content = itemView.findViewById(R.id.content_overview); } } }
28.901408
87
0.70614
58a30ff171d7afcab15c9dd5e50e7073deefd972
1,495
package nablarch.integration.router; import nablarch.fw.ExecutionContext; import nablarch.fw.MethodBinder; import nablarch.fw.web.HttpRequest; import nablarch.fw.web.HttpRequestHandler; import nablarch.fw.web.HttpResponse; import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * {@link RoutesMethodBinderFactory}のテストクラス。 */ public class RoutesMethodBinderFactoryTest { private RoutesMethodBinderFactory sut = new RoutesMethodBinderFactory(); /** * {@link RoutesMethodBinderFactory#create(String)}のテストケース */ @Test public void testCreate() throws Exception { MethodBinder<HttpRequest, Object> factory = sut.create("handle"); assertThat("RoutesMethodBinderが生成されること", factory, is(instanceOf(RoutesMethodBinder.class))); // factoryに指定したメソッドが呼び出せることも確認する HttpResponse result = (HttpResponse)factory.bind(new Action()).handle(null, new ExecutionContext()); assertThat(result.getStatusCode(), is(200)); assertThat(result.getBodyString(), is("success")); } /** * テスト用のアクションクラス。 */ public static class Action implements HttpRequestHandler { @Override public HttpResponse handle(HttpRequest request, ExecutionContext context) { HttpResponse response = new HttpResponse(200); response.write("success"); return response; } } }
31.808511
108
0.715719
b3894c2490ee5fb8f7325bf411a4940f676bb15f
1,683
package com.lwl.common.pool.jdk.mypool; import java.util.LinkedList; /** * author liuweilong * date 2019/8/19 14:14 * desc */ public class DefaultRunnableQueue implements LwlRunnableQueue { /** * 队列最大长度 */ private final int limit; /** * 拒绝策略 */ private final DenyPolicy denyPolicy; /** * 存放任务 */ private final LinkedList<Runnable> runnableList = new LinkedList<>(); /** * 线程池 */ private final LwlThreadPool threadPool; public DefaultRunnableQueue(int limit, DenyPolicy denyPolicy, LwlThreadPool threadPool) { this.limit = limit; this.denyPolicy = denyPolicy; this.threadPool = threadPool; } @Override public void offer(Runnable runnable) { synchronized (runnableList) { if (runnableList.size() >= limit) { //超过限制,启动拒绝策略 this.denyPolicy.reject(runnable, threadPool); } else { //将入到队列 runnableList.addLast(runnable); runnableList.notifyAll(); } } } @Override public Runnable task() { synchronized (runnableList) { while (runnableList.isEmpty()) { try { //如果没有任务进来,阻塞 runnableList.wait(); } catch (Exception e) { e.printStackTrace(); } } //从任务头移除一个任务 return runnableList.removeFirst(); } } @Override public int size() { //返回线程池数量 synchronized (runnableList) { return runnableList.size(); } } }
22.743243
93
0.525253
cb2e768d9483a0408d828ed23dd65f837eac8666
6,345
/** * 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.apache.aurora.scheduler.storage.db; import java.util.List; import java.util.Set; import javax.inject.Inject; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import org.apache.aurora.gen.JobUpdate; import org.apache.aurora.gen.JobUpdateInstructions; import org.apache.aurora.gen.storage.StoredJobUpdateDetails; import org.apache.aurora.scheduler.storage.JobUpdateStore; import org.apache.aurora.scheduler.storage.entities.IInstanceTaskConfig; import org.apache.aurora.scheduler.storage.entities.IJobInstanceUpdateEvent; import org.apache.aurora.scheduler.storage.entities.IJobUpdate; import org.apache.aurora.scheduler.storage.entities.IJobUpdateDetails; import org.apache.aurora.scheduler.storage.entities.IJobUpdateEvent; import org.apache.aurora.scheduler.storage.entities.IJobUpdateInstructions; import org.apache.aurora.scheduler.storage.entities.IJobUpdateQuery; import org.apache.aurora.scheduler.storage.entities.IJobUpdateSummary; import org.apache.aurora.scheduler.storage.entities.IRange; import static java.util.Objects.requireNonNull; /** * A relational database-backed job update store. */ public class DBJobUpdateStore implements JobUpdateStore.Mutable { private final JobKeyMapper jobKeyMapper; private final JobUpdateDetailsMapper detailsMapper; private final JobUpdateEventMapper jobEventMapper; private final JobInstanceUpdateEventMapper instanceEventMapper; @Inject DBJobUpdateStore( JobKeyMapper jobKeyMapper, JobUpdateDetailsMapper detailsMapper, JobUpdateEventMapper jobEventMapper, JobInstanceUpdateEventMapper instanceEventMapper) { this.jobKeyMapper = requireNonNull(jobKeyMapper); this.detailsMapper = requireNonNull(detailsMapper); this.jobEventMapper = requireNonNull(jobEventMapper); this.instanceEventMapper = requireNonNull(instanceEventMapper); } @Override public void saveJobUpdate(IJobUpdate update, String lockToken) { requireNonNull(update); requireNonNull(lockToken); jobKeyMapper.merge(update.getSummary().getJobKey().newBuilder()); detailsMapper.insert(update.newBuilder()); String updateId = update.getSummary().getUpdateId(); detailsMapper.insertLockToken(updateId, lockToken); // Insert optional instance update overrides. Set<IRange> instanceOverrides = update.getInstructions().getSettings().getUpdateOnlyTheseInstances(); if (!instanceOverrides.isEmpty()) { detailsMapper.insertInstanceOverrides(updateId, IRange.toBuildersSet(instanceOverrides)); } // Insert desired state task config and instance mappings. IInstanceTaskConfig desired = update.getInstructions().getDesiredState(); detailsMapper.insertTaskConfig( updateId, desired.getTask().newBuilder(), true, new InsertResult()); detailsMapper.insertDesiredInstances(updateId, IRange.toBuildersSet(desired.getInstances())); // Insert initial state task configs and instance mappings. for (IInstanceTaskConfig config : update.getInstructions().getInitialState()) { InsertResult result = new InsertResult(); detailsMapper.insertTaskConfig(updateId, config.getTask().newBuilder(), false, result); detailsMapper.insertTaskConfigInstances( result.getId(), IRange.toBuildersSet(config.getInstances())); } } @Override public void saveJobUpdateEvent(IJobUpdateEvent event, String updateId) { jobEventMapper.insert(updateId, event.newBuilder()); } @Override public void saveJobInstanceUpdateEvent(IJobInstanceUpdateEvent event, String updateId) { instanceEventMapper.insert(event.newBuilder(), updateId); } @Override public void deleteAllUpdatesAndEvents() { detailsMapper.truncate(); } @Override public List<IJobUpdateSummary> fetchJobUpdateSummaries(IJobUpdateQuery query) { return IJobUpdateSummary.listFromBuilders(detailsMapper.selectSummaries(query.newBuilder())); } @Override public Optional<IJobUpdateDetails> fetchJobUpdateDetails(final String updateId) { return Optional.fromNullable(detailsMapper.selectDetails(updateId)) .transform(new Function<StoredJobUpdateDetails, IJobUpdateDetails>() { @Override public IJobUpdateDetails apply(StoredJobUpdateDetails input) { return IJobUpdateDetails.build(input.getDetails()); } }); } @Override public Optional<IJobUpdate> fetchJobUpdate(String updateId) { return Optional.fromNullable(detailsMapper.selectUpdate(updateId)) .transform(new Function<JobUpdate, IJobUpdate>() { @Override public IJobUpdate apply(JobUpdate input) { return IJobUpdate.build(input); } }); } @Override public Optional<IJobUpdateInstructions> fetchJobUpdateInstructions(String updateId) { return Optional.fromNullable(detailsMapper.selectInstructions(updateId)) .transform(new Function<JobUpdateInstructions, IJobUpdateInstructions>() { @Override public IJobUpdateInstructions apply(JobUpdateInstructions input) { return IJobUpdateInstructions.build(input); } }); } @Override public Set<StoredJobUpdateDetails> fetchAllJobUpdateDetails() { return ImmutableSet.copyOf(detailsMapper.selectAllDetails()); } @Override public Optional<String> getLockToken(String updateId) { // We assume here that cascading deletes will cause a lock-update associative row to disappear // when the lock is invalidated. This further assumes that a lock row is deleted when a lock // is no longer valid. return Optional.fromNullable(detailsMapper.selectLockToken(updateId)); } }
37.323529
98
0.759653
d78be7ac163611184854c52380ce29617d37da9c
1,876
/* * Copyright 2015 Artem Mironov * * 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.jeesy.csv2b; import org.jeesy.classinfo.converter.api.StringParser; import org.jeesy.classinfo.converter.api.StringSerializer; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Define csv column metadata * @author Artem Mironov */ @Documented @Target({ ANNOTATION_TYPE, FIELD, METHOD}) @Retention(RUNTIME) public @interface CsvCol { /** * Name of the csv column as it appears in header * If empty property name will be used instead. */ String name() default ""; /** * Converter from string for this column. */ Class<? extends StringParser> parser() default StringParser.class; /** * Converter to string */ Class<? extends StringSerializer> serializer() default StringSerializer.class; /** * Reader should generate exception on columns which required but not exists in csv file * Writer should generate exception if this property is null */ boolean required() default false; /** * If csv value is empty string pass null to converters */ boolean nullIfEmpty() default true; }
29.3125
92
0.71855
a8466240bc70d1676b950377b09a199aeed86923
275
/** * Indicates that this module contains classes that need to be generated / processed. */ @ModuleGen(name="business-common", groupPackage = "io.vertx.armysystem.business.common") package io.vertx.armysystem.business.common; import io.vertx.codegen.annotations.ModuleGen;
39.285714
88
0.785455
0ab8e729d55e821775454fcc43d87cac29284f1e
1,304
package com.chenxushao.java.basis.syntax; public class TestFinally { public static void main(String[] args) { System.out.println("test1:" + testFinal1()); System.out.println("test2:" + testFinal2()); System.out.println("test3:" + testFinal3()); System.out.println("test4:" + testFinal4()); System.out.println("test5:" + testFinal5()); } static int testFinal1() { int i = 1; try { return i; } finally { System.out.println("in testFinal1():finally 肯定会被执行的!"); i = 48; } } static String testFinal2() { String str = "try"; try { return str; } finally { System.out.println("in testFinal2():finally 肯定会被执行的!"); str = "finally"; } } static StringBuilder testFinal3() { StringBuilder build = new StringBuilder("try "); try { return build; } finally { System.out.println("in testFinal3():finally 肯定会被执行的!"); build.append("finally"); build = new StringBuilder("你猜我是谁!"); } } static String testFinal4() { try { return "return in try"; } finally { System.out.println("in testFinal4():finally 肯定会被执行的!"); return "return in finally"; } } static int testFinal5() { try { throw new Exception("异常"); } catch (Exception e) { System.out.println("Exception block"); return 200; } finally { return 300; } } }
21.032258
58
0.635736
806262653dfe5984ece38f7d963e24eb2e11eb01
882
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.examples.use; import java.util.List; // Comparison note: with Mockito, classes like this cannot be final. public /*final*/ class ArticleDatabase { // Comparison note: with Mockito, methods like this cannot be final. public /*final*/ void updateNumberOfArticles(String newspaper, int articles) { } public void updateNumberOfPolishArticles(String newspaper, int polishArticles) { } public void updateNumberOfEnglishArticles(String newspaper, int i) { } public List<Article> getArticlesFor(String string) { return null; } // Comparison note: with Mockito, methods like this cannot be static. public /*static*/ void save(Article article) { } }
25.2
82
0.688209
b1bdfcd01c181e8ebbda5c5128004e09901aaf7e
1,709
package com.davidholiday.camel.harness.routebuilders; import com.davidholiday.camel.harness.util.ConnectionStringFactory; import com.davidholiday.camel.harness.routing.RouteBuilderHarness; /** * demonstrates route that makes a RESTful call in prod and uses a mock for same when running in local mode. */ public class HarnessedSampleGetServiceResponseRouteBuilder extends RouteBuilderHarness { public HarnessedSampleGetServiceResponseRouteBuilder() { super(HarnessedSampleGetServiceResponseRouteBuilder.class.getSimpleName(), false); } public void configure() throws Exception { /* configuration */ // this restConfiguration is what lets us make RESTful calls to other services. // in this case it's set up to make a call to itself. restConfiguration().producerComponent("http4") .host("localhost") .port("8889"); // resolve the correct connection string given runtime context String serviceResponseConnectionString = ConnectionStringFactory.getConnectionStringOrThrow(ConnectionStringFactory.SAMPLE_GET_SERVICE_RESPONSE_CONNECTION_STRING_KEY); /* routes */ from("direct:in").routeId(FROM_ROUTE_ID) .to(BUSINESS_LOGIC_ROUTE_FROM_NAME); from(BUSINESS_LOGIC_ROUTE_FROM_NAME).routeId(BUSINESS_LOGIC_ROUTE_ID) .description(BUSINESS_LOGIC_ROUTE_DESCRIPTION) .to(serviceResponseConnectionString) .log("exchange body is now: ${body}"); } }
35.604167
142
0.648917
c46de2ef53b6a39f6bf74e500357780a9780ae8f
576
package com.andyadc.codeblocks.kit.concurrent; import org.slf4j.MDC; import java.util.Map; /** * Slf4j 异步线程设置 MDC * * @author andy.an * @since 2018/6/4 */ public class MDCRunnable implements Runnable { private final Runnable runnable; private transient final Map<String, String> map; public MDCRunnable(Runnable runnable) { this.runnable = runnable; // 保存当前线程的MDC值 this.map = MDC.getCopyOfContextMap(); } @Override public void run() { if (map != null) { MDC.setContextMap(map); } try { runnable.run(); } finally { MDC.clear(); } } }
16
49
0.675347
536bf16c3397240fea65cc28f73a442607237403
1,113
package io.daiwei.redis.config; import io.daiwei.redis.props.RedisClientConfigureProps; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.client.RedisClient; import org.redisson.config.Config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; /** * Created by Daiwei on 2021/4/10 */ @Configuration public class RedissonConfiguration { @Resource private RedisClientConfigureProps props; @Bean public RedissonClient redissonClient() { Config config = new Config(); String addr = "redis://" + props.getConnProps().getHost() + ":" + props.getConnProps().getPort(); config.useSingleServer().setAddress(addr) .setDatabase(props.getConnProps().getDatabaseIdx()) .setPassword(props.getConnProps().getPassword()) .setUsername(props.getConnProps().getUsername()); return Redisson.create(config); } }
32.735294
105
0.730458
b2d2283c2749ec212ed291923bd46896dd9796b5
571
package com.sogeti.weatherapp.config; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class WeatherAppConfig { /*@Bean public IWeatherInfoApi getStandardWeatherInfoApi(){ return new StandardWeatherInfoApi(); } */ @Bean public RestTemplate getRestTemplate(RestTemplateBuilder restBuilder){ return restBuilder.build(); } }
27.190476
73
0.774081
6a2c777b8ec251cc9ef0617490ca1c44e7faae51
5,858
package com.otter.otterbenchmark.system; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.otter.otterbenchmark.R; import com.otter.otterbenchmark.Util; /** * Display system information (e.g., SDK, device, build). */ public class SystemInfo extends AppCompatActivity implements View.OnClickListener { private static final String TAG = SystemInfo.class.getSimpleName(); private Button rotate_screen; private TextView incremental; private TextView codename; private TextView release; private TextView sdk_int; private TextView preview_sdk_int; private TextView base_os; private TextView security_patch; private TextView user; private TextView manufacturer; private TextView host; private TextView brand; private TextView product; private TextView model; private TextView id; private TextView time; private TextView type; private TextView tags; private TextView display; private TextView fingerprint; private TextView device; private TextView board; private TextView hardware; private TextView serial; private TextView bootloader; private TextView cpu_abi; private TextView radio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_system_info); findViews(); rotate_screen.setOnClickListener(this); incremental.setText(Build.VERSION.INCREMENTAL); codename.setText(Build.VERSION.CODENAME); release.setText(Build.VERSION.RELEASE); sdk_int.setText(String.valueOf(Build.VERSION.SDK_INT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { preview_sdk_int.setText(String.valueOf(Build.VERSION.PREVIEW_SDK_INT)); base_os.setText(Build.VERSION.BASE_OS); security_patch.setText(Build.VERSION.SECURITY_PATCH); } else { preview_sdk_int.setText(R.string.system_require_api_23); base_os.setText(R.string.system_require_api_23); security_patch.setText(R.string.system_require_api_23); } user.setText(Build.USER); manufacturer.setText(Build.MANUFACTURER); host.setText(Build.HOST); brand.setText(Build.BRAND); product.setText(Build.PRODUCT); model.setText(Build.MODEL); id.setText(Build.ID); time.setText(Util.convertMillisecondToDateTime(Build.TIME)); type.setText(Build.TYPE); tags.setText(Build.TAGS); display.setText(Build.DISPLAY); fingerprint.setText(Build.FINGERPRINT); device.setText(Build.DEVICE); board.setText(Build.BOARD); hardware.setText(Build.HARDWARE); serial.setText(Build.SERIAL); bootloader.setText(Build.BOOTLOADER); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cpu_abi.setText(Build.SUPPORTED_ABIS[0]); } else { cpu_abi.setText(Build.CPU_ABI); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { radio.setText(Build.getRadioVersion()); } else { radio.setText(Build.RADIO); } } private void findViews() { rotate_screen = (Button) findViewById(R.id.rotate_screen); incremental = (TextView) findViewById(R.id.incremental); codename = (TextView) findViewById(R.id.codename); release = (TextView) findViewById(R.id.release); sdk_int = (TextView) findViewById(R.id.sdk_int); preview_sdk_int = (TextView) findViewById(R.id.preview_sdk_int); base_os = (TextView) findViewById(R.id.base_os); security_patch = (TextView) findViewById(R.id.security_patch); user = (TextView) findViewById(R.id.user); manufacturer = (TextView) findViewById(R.id.manufacturer); host = (TextView) findViewById(R.id.host); brand = (TextView) findViewById(R.id.brand); product = (TextView) findViewById(R.id.product); model = (TextView) findViewById(R.id.model); id = (TextView) findViewById(R.id.id); time = (TextView) findViewById(R.id.time); type = (TextView) findViewById(R.id.type); tags = (TextView) findViewById(R.id.tags); display = (TextView) findViewById(R.id.display); fingerprint = (TextView) findViewById(R.id.fingerprint); device = (TextView) findViewById(R.id.device); board = (TextView) findViewById(R.id.board); hardware = (TextView) findViewById(R.id.hardware); serial = (TextView) findViewById(R.id.serial); bootloader = (TextView) findViewById(R.id.bootloader); cpu_abi = (TextView) findViewById(R.id.cpu_abi); radio = (TextView) findViewById(R.id.radio); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.rotate_screen: switch (getOrientation()) { case Configuration.ORIENTATION_PORTRAIT: setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case Configuration.ORIENTATION_LANDSCAPE: setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; } break; default: break; } } private int getOrientation () { return getResources().getConfiguration().orientation; } }
37.075949
83
0.653124
2c18cf7345edb5a07df6ca60062fed0283531934
721
package com.skscd91.advent; import java.io.BufferedReader; /** * Created by sk-scd91 on 12/1/15. */ public class AdventDay1Part1 implements Advent { @Override public int getDay() { return 1; } @Override public String compute(BufferedReader input) { int floor = input.lines() .flatMapToInt(String::chars) .map(AdventDay1Part1::directionForInstruction) .sum(); return "Santa will go to floor " + floor + "."; } private static int directionForInstruction(int instruction) { return (instruction == '(') ? 1 : (instruction == ')') ? -1 : 0; } }
24.862069
71
0.538141
8c765560653a7f1d005fddd75e7a0bb8ee2fc115
696
package com.ginkgo.security.authorization; import com.ginkgo.security.config.SecurityProperties; import org.springframework.security.config.annotation.web.builders.HttpSecurity; public class DefaultAuthorizationProvider implements AuthorizationProvider { private SecurityProperties properties; public DefaultAuthorizationProvider(SecurityProperties properties) { this.properties = properties; } @Override public void setAuthorization(HttpSecurity config) throws Exception { config.authorizeRequests() .antMatchers(this.properties.getJwt().getAuthPath(), this.properties.getJwt().getTokenRefreshPath()) .permitAll(); } }
34.8
116
0.755747
14a92a1fadbaf20272e7b177995ed53669898815
3,692
import java.util.*; import java.lang.*; import java.io.*; import java.text.*; /* Name of the class has to be "Main" only if the class is public*/ public class CF1350A { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Node { long pp; long a, b; Node(long x, long y) { a = x; b = y; pp = a * b; } } static class Comp implements Comparator<Node> { public int compare(Node o1, Node o2) { if (o1.pp > o2.pp) { return 1; } else { return -1; } } } static int gcd(int x, int y) { if(y==0) return x; else return gcd(y,x%y); } static long lcm(int a, int b) { return (long) (a*b/gcd(a,b)); } static int modInv(int a, int m) { if(gcd(a,m)!=1) return -999; else return (a%m+m)%m; } static boolean isPowerOfTwo (int x) { return x!=0 && ((x&(x-1)) == 0); } static boolean isprime(int x) { for(int i=2;i<=Math.sqrt(x);i++) { if(x%i==0) return false; } return true; } static boolean prime[]; static final int INT_MAX=1000007; static void sieve() { prime=new boolean[INT_MAX]; Arrays.fill(prime,true); prime[0]=prime[1]=false; for(int i=2;i<=Math.sqrt(INT_MAX);i++) { if(prime[i]) { for(int j=i*2;j<INT_MAX;j+=i) prime[j]=false; } } } static int f(int n) { int f=1; for(int i=2;i<=Math.sqrt(n);i++) { if(n%i==0) { f=i; break; } } if(f==1) f=n; return f; } public static void main(String[] args) { FastReader sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); StringBuffer sb=new StringBuffer(); //your code starts here int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(),k=sc.nextInt(); long ans=0; if(isprime(n)) ans=2*n+2*(k-1); else if((n&1)==0) ans=n+2*k; else if((n&1)==1) { n+=f(n); --k; ans=n+2*k; } sb.append(ans+"\n"); } out.println(sb.toString()); out.close(); } }
24.289474
71
0.398429
76874ae4db4008e68cda0bebfd92cfde43eadcbf
7,408
package com.simibubi.create.content.contraptions.components.mixer; import java.util.List; import java.util.Optional; import com.simibubi.create.AllRecipeTypes; import com.simibubi.create.content.contraptions.components.press.MechanicalPressTileEntity; import com.simibubi.create.content.contraptions.fluids.FluidFX; import com.simibubi.create.content.contraptions.fluids.recipe.PotionMixingRecipeManager; import com.simibubi.create.content.contraptions.processing.BasinOperatingTileEntity; import com.simibubi.create.content.contraptions.processing.BasinTileEntity; import com.simibubi.create.foundation.advancement.AllTriggers; import com.simibubi.create.foundation.advancement.ITriggerable; import com.simibubi.create.foundation.config.AllConfigs; import com.simibubi.create.foundation.item.SmartInventory; import com.simibubi.create.foundation.tileEntity.behaviour.fluid.SmartFluidTankBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.fluid.SmartFluidTankBehaviour.TankSegment; import com.simibubi.create.foundation.utility.VecHelper; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.nbt.CompoundNBT; import net.minecraft.particles.IParticleData; import net.minecraft.particles.ItemParticleData; import net.minecraft.particles.ParticleTypes; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Direction.Axis; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; public class MechanicalMixerTileEntity extends BasinOperatingTileEntity { private static final Object shapelessOrMixingRecipesKey = new Object(); public int runningTicks; public int processingTicks; public boolean running; public MechanicalMixerTileEntity(TileEntityType<? extends MechanicalMixerTileEntity> type) { super(type); } public float getRenderedHeadOffset(float partialTicks) { int localTick; float offset = 0; if (running) { if (runningTicks < 20) { localTick = runningTicks; float num = (localTick + partialTicks) / 20f; num = ((2 - MathHelper.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } else if (runningTicks <= 20) { offset = 1; } else { localTick = 40 - runningTicks; float num = (localTick - partialTicks) / 20f; num = ((2 - MathHelper.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } } return offset + 7 / 16f; } public float getRenderedHeadRotationSpeed(float partialTicks) { float speed = getSpeed(); if (running) { if (runningTicks < 15) { return speed; } if (runningTicks <= 20) { return speed * 2; } return speed; } return speed / 2; } @Override public AxisAlignedBB getRenderBoundingBox() { return new AxisAlignedBB(pos).expand(0, -1.5, 0); } @Override protected void read(CompoundNBT compound, boolean clientPacket) { running = compound.getBoolean("Running"); runningTicks = compound.getInt("Ticks"); super.read(compound, clientPacket); if (clientPacket && hasWorld()) getBasin().ifPresent(bte -> bte.setAreFluidsMoving(running && runningTicks <= 20)); } @Override public void write(CompoundNBT compound, boolean clientPacket) { compound.putBoolean("Running", running); compound.putInt("Ticks", runningTicks); super.write(compound, clientPacket); } @Override public void tick() { super.tick(); if (runningTicks >= 40) { running = false; runningTicks = 0; return; } float speed = Math.abs(getSpeed()); if (running && world != null) { if (world.isRemote && runningTicks == 20) renderParticles(); if (!world.isRemote && runningTicks == 20) { if (processingTicks < 0) { processingTicks = MathHelper.clamp((MathHelper.log2((int) (512 / speed))) * 15 + 1, 1, 512); } else { processingTicks--; if (processingTicks == 0) { runningTicks++; processingTicks = -1; applyBasinRecipe(); sendData(); } } } if (runningTicks != 20) runningTicks++; } } public void renderParticles() { Optional<BasinTileEntity> basin = getBasin(); if (!basin.isPresent() || world == null) return; for (SmartInventory inv : basin.get() .getInvs()) { for (int slot = 0; slot < inv.getSlots(); slot++) { ItemStack stackInSlot = inv.getStackInSlot(slot); if (stackInSlot.isEmpty()) continue; ItemParticleData data = new ItemParticleData(ParticleTypes.ITEM, stackInSlot); spillParticle(data); } } for (SmartFluidTankBehaviour behaviour : basin.get() .getTanks()) { if (behaviour == null) continue; for (TankSegment tankSegment : behaviour.getTanks()) { if (tankSegment.isEmpty(0)) continue; spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid())); } } } protected void spillParticle(IParticleData data) { float angle = world.rand.nextFloat() * 360; Vec3d offset = new Vec3d(0, 0, 0.25f); offset = VecHelper.rotate(offset, angle, Axis.Y); Vec3d target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y) .add(0, .25f, 0); Vec3d center = offset.add(VecHelper.getCenterOf(pos)); target = VecHelper.offsetRandomly(target.subtract(offset), world.rand, 1 / 128f); world.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z); } @Override protected List<IRecipe<?>> getMatchingRecipes() { List<IRecipe<?>> matchingRecipes = super.getMatchingRecipes(); Optional<BasinTileEntity> basin = getBasin(); if (!basin.isPresent()) return matchingRecipes; IItemHandler availableItems = basin.get() .getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) .orElse(null); if (availableItems == null) return matchingRecipes; for (int i = 0; i < availableItems.getSlots(); i++) { ItemStack stack = availableItems.getStackInSlot(i); if (stack.isEmpty()) continue; List<MixingRecipe> list = PotionMixingRecipeManager.ALL.get(stack.getItem()); if (list == null) continue; for (MixingRecipe mixingRecipe : list) if (matchBasinRecipe(mixingRecipe)) matchingRecipes.add(mixingRecipe); } return matchingRecipes; } @Override protected <C extends IInventory> boolean matchStaticFilters(IRecipe<C> r) { return ((r.getSerializer() == IRecipeSerializer.CRAFTING_SHAPELESS && AllConfigs.SERVER.recipes.allowShapelessInMixer.get()) || r.getType() == AllRecipeTypes.MIXING.type) && !MechanicalPressTileEntity.canCompress(r.getIngredients()); } @Override public void startProcessingBasin() { if (running && runningTicks <= 20) return; super.startProcessingBasin(); running = true; runningTicks = 0; } @Override public boolean continueWithPreviousRecipe() { runningTicks = 20; return true; } @Override protected void onBasinRemoved() { if (!running) return; runningTicks = 40; running = false; } @Override protected Object getRecipeCacheKey() { return shapelessOrMixingRecipesKey; } @Override protected boolean isRunning() { return running; } @Override protected Optional<ITriggerable> getProcessedRecipeTrigger() { return Optional.of(AllTriggers.MIXER_MIX); } }
29.280632
106
0.724892
3a46c5a842964f332cd205951fc243569ee6543f
390
package net.floodlightcontroller.util; import org.fusesource.jansi.Ansi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.deva.DevaProcessPacketIn; public class UtilLog { protected static Ansi ansi; public static String blue(String string) { ansi = new Ansi(); ansi.fgBlue().a(string).fgDefault(); return ansi.toString(); } }
19.5
57
0.746154
aad983b208f439bdb5d244232f68f9e120eb579d
232
package cola.machine.game.myblocks.network; import cola.machine.game.myblocks.reflection.metadata.FieldMetadata; public interface ReplicationCheck { boolean shouldReplicate(FieldMetadata field,boolean initial,boolean toOwner); }
29
78
0.844828
af0610b11a8c7dc7d5b57819d123276841b7678c
2,067
/* * Copyright (c) 2008 Kasper Nielsen. * * 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 app.packed.inject.service; // ? Why is ProvisionMode not part of ServiceContract // A Because it should not be part of how services are used public enum ProvisionMode { ON_DEMAND, EAGER_SINGLETON, LAZY_SINGLETON; // @ImplNote //// The runtime will rarely be able to store singletons more efficent //// It a lot a situation it tempting to use either of the constant modes. //// However, you might be better of using ON_DEMAND //// A eager constant is typically stored in an array. //// So primitive types are stored as their wrapper types // LazyConstant are typically stored in wrapper object with a single volatile field } // Rename to prototype // Maaske supportere vi ikke konstanter... Og saa har en clean @Provide... // Saa kan den ogsaa bruges fra hooks /// Og hvad er constant? LAZY or EAGER? //// Saa vi har vel tre modes - ON_DEMAND, LAZY_SCOPED_SINGLETON, EAGER_SCOPED_SINGLETON /// EAGER_CONSTANT, LAZY_CONSTANT //// Med scoped mener vi at det ikke er en global singleton // Saa har vi lige den med ExtensionMember ogsaa... //// Maaske har man noget @Provide.defaultExtension = ServiceExtension.class //// Forstaaet paa den maade at man bruger ServiceExtension som default //@Provide(Constant) , @Provide(Lazy), @Provide(EVERYTIME) -> Constant early, Lazy (volatile storage) <-- kan jo godt skrive laese volatile i et object array //serviceProvide? provideServicee //ProvideService
39
157
0.731979
58bcbb9bbac9b4cf0cebfff4e1407c1152bcf41d
17,503
package me.jp.sticker.widget.edit; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.NinePatch; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.NinePatchDrawable; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.widget.TextView; import me.jp.sticker.R; import me.jp.sticker.model.StickerModel; import me.jp.sticker.util.DisplayUtil; import me.jp.sticker.util.NinePatchChunk; /** * Created by congwiny on 2016/7/11. */ public class EditStickerTextView extends EditStickerView implements StickerInputView.OnStickerTextBGChangedListener { private static final String TAG = EditStickerTextView.class.getSimpleName(); private TextView mTextView; private Bitmap mControllerBitmap, mDeleteBitmap; private float mControllerWidth, mControllerHeight, mDeleteWidth, mDeleteHeight; private Paint mPaint, mBorderPaint; private int mToolBarHeight; private static final int STICKER_GAP = 50; private float[] mOriginPoints; private float[] mOriginOuterPoints; private float[] mOuterPoints; private float[] mPoints; private RectF mOriginContentRect; private RectF mContentRect; private RectF mViewRect; private int mScreenWidth; private int mScreenHeight; private float mLastPointX, mLastPointY; private float mInitPointX, mInitPointY; private boolean mInController, mInMove; private boolean mDrawController = true; private float mStickerScaleSize = 1.0f; private Matrix mMatrix; private boolean mInDelete = false; private boolean mInEdit = true; public static final float MAX_SCALE_SIZE = 2.0f; public static final float MIN_SCALE_SIZE = 0.5f; private float mTouchSlop; private Paint mContentPaint; private int[] STICKER_TEXT_BG = new int[]{ R.drawable.shape_textview_border, R.drawable.txt_bg_black, R.drawable.txt_bg_red, R.drawable.txt_bg_yellow, R.drawable.txt_bg_green, R.drawable.txt_bg_blue, R.drawable.txt_bg_pink }; private int mStickerTextBGIndex; private String mStickerText; private OnStickerDeleteListener mOnStickerDeleteListener; private OnEditStickerTextClickListener mOnEditStickerTextClickListener; public EditStickerTextView(Context context) { this(context, null); } public EditStickerTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EditStickerTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override public int getStickerEditType() { return EDIT_TYPE_TEXT; } @Override public void applySticker() { mInEdit = false; setFocusable(false); setBackgroundColor(getResources().getColor(R.color.sticker_mask_transparent)); invalidate(); } @Override public void editSticker(StickerModel stickerModel, boolean isInitial) { mInEdit = true; mStickerText = stickerModel.getStickerText(); setTextSticker(isInitial); } @Override public void setOnStickerDeleteListener(OnStickerDeleteListener listener) { mOnStickerDeleteListener = listener; } public void setOnEditStickerTextClickListener(OnEditStickerTextClickListener listener) { mOnEditStickerTextClickListener = listener; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void init() { mStickerScaleSize = 1.0f; mMatrix = new Matrix(); mContentRect = new RectF(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setFilterBitmap(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(4.0f); mPaint.setColor(Color.WHITE); mContentPaint = new Paint(mPaint); mContentPaint.setColor(Color.GREEN); mBorderPaint = new Paint(mPaint); mBorderPaint.setColor(Color.parseColor("#99ffffff")); //mBorderPaint.setShadowLayer(DisplayUtil.dip2px(getContext(), 2.0f), 0, 0, Color.parseColor("#33000000")); mControllerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_sticker_resize); mControllerWidth = mControllerBitmap.getWidth(); mControllerHeight = mControllerBitmap.getHeight(); mDeleteBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_sticker_delete); mDeleteWidth = mDeleteBitmap.getWidth(); mDeleteHeight = mDeleteBitmap.getHeight(); mScreenWidth = DisplayUtil.getDisplayWidthPixels(getContext()); mScreenHeight = DisplayUtil.getDisplayheightPixels(getContext()); mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); setBackgroundColor(getResources().getColor(R.color.sticker_mask_dark)); } private void setTextSticker(boolean isInitial) { setFocusable(true); mTextView = new TextView(getContext()); mTextView.setText(mStickerText); mTextView.setTextSize(16); mTextView.setMaxWidth((int) (mScreenWidth * 0.8 + 0.5)); mTextView.setBackgroundDrawable(getResources() .getDrawable(STICKER_TEXT_BG[mStickerTextBGIndex])); mTextView.setTextColor(Color.WHITE); final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); mTextView.measure(widthSpec, heightSpec); int width = mTextView.getMeasuredWidth(); int height = mTextView.getMeasuredHeight(); int px = mTextView.getMeasuredWidth() + 2 * STICKER_GAP; int py = mTextView.getMeasuredHeight() + 2 * STICKER_GAP; mTextView.layout(0, 0, width, height); mOriginContentRect = new RectF(-STICKER_GAP, -STICKER_GAP, px - STICKER_GAP, py - STICKER_GAP); mPoints = new float[10]; mOriginPoints = new float[]{0, 0, width, 0, width, height, 0, height, width / 2, height / 2}; mOuterPoints = new float[10]; mOriginOuterPoints = new float[]{-STICKER_GAP, -STICKER_GAP, px - STICKER_GAP, -STICKER_GAP, px - STICKER_GAP, py - STICKER_GAP, -STICKER_GAP, py - STICKER_GAP, width / 2, height / 2}; if (isInitial) { float transtLeft = ((float) mScreenWidth - width) / 2; float transtTop = ((float) mScreenHeight - height) / 2; //图片通过矩阵进行坐标平移 mMatrix.postTranslate(transtLeft, transtTop); } postInvalidate(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if (!isFocusable()) { return super.dispatchTouchEvent(event); } if (mViewRect == null) { mViewRect = new RectF(0f, 0f, getMeasuredWidth(), getMeasuredHeight()); } float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mInitPointX = x; mInitPointY = y; if (isInController(x, y)) { mInController = true; mLastPointY = y; mLastPointX = x; break; } if (isInDelete(x, y)) { mInDelete = true; break; } PointF p = new PointF(x, y); if (isPointInMatrix(p, mOuterPoints)) { mLastPointY = y; mLastPointX = x; mInMove = true; } break; case MotionEvent.ACTION_UP: if (isInDelete(x, y) && mInDelete) { doDeleteSticker(); } PointF pointF = new PointF(x, y); //执行点击事件 if (isPointInMatrix(pointF, mPoints)) { if (caculateLength(x, y, mInitPointX, mInitPointY) <= mTouchSlop) { if (mOnEditStickerTextClickListener != null) { mOnEditStickerTextClickListener.onEditStickerTextClick(this); } } } case MotionEvent.ACTION_CANCEL: mLastPointX = 0; mLastPointY = 0; mInController = false; mInMove = false; mInDelete = false; break; case MotionEvent.ACTION_MOVE: if (mInController) { mMatrix.postRotate(rotation(event), mOuterPoints[8], mOuterPoints[9]); float nowLenght = caculateLength(mOuterPoints[0], mOuterPoints[1], mOuterPoints[8], mOuterPoints[9]); float touchLenght = caculateLength(event.getX(), event.getY(), mOuterPoints[8], mOuterPoints[9]); if (Math.sqrt((nowLenght - touchLenght) * (nowLenght - touchLenght)) > 0.0f) { float scale = touchLenght / nowLenght; float nowsc = mStickerScaleSize * scale; if (nowsc >= MIN_SCALE_SIZE && nowsc <= MAX_SCALE_SIZE) { mMatrix.postScale(scale, scale, mOuterPoints[8], mOuterPoints[9]); mStickerScaleSize = nowsc; } } invalidate(); mLastPointX = x; mLastPointY = y; break; } if (mInMove == true) { //拖动的操作 float cX = x - mLastPointX; float cY = y - mLastPointY; mInController = false; if (Math.sqrt(cX * cX + cY * cY) > 2.0f && canStickerMove(cX, cY)) { mMatrix.postTranslate(cX, cY); postInvalidate(); mLastPointX = x; mLastPointY = y; } break; } return true; } return true; } public StickerModel getStickerParam() { StickerModel param = new StickerModel(); param.setDegree(calculateLastDegree()); double stickerWidth = Math.sqrt(Math.pow(mPoints[2] - mPoints[0], 2) + Math.pow(mPoints[3] - mPoints[1], 2)); double stickerHeight = Math.sqrt(Math.pow(mPoints[4] - mPoints[2], 2) + Math.pow(mPoints[5] - mPoints[3], 2)); param.setScaleWidth((float) (stickerWidth / mScreenWidth)); param.setAspectRatio((float) (stickerWidth / stickerHeight)); param.setZoomCenterX(mPoints[8] / mScreenWidth); param.setZoomCenterY(mPoints[9] / mScreenHeight); param.setStickerUrl(""); param.setStickerText("i love you"); return param; } private float calculateLastDegree() { double delta_x = mPoints[5] - mPoints[3]; double delta_y = mPoints[2] - mPoints[4]; double radians = Math.atan2(delta_y, delta_x); return (float) Math.toDegrees(radians); } private void doDeleteSticker() { setVisibility(View.GONE); if (mOnStickerDeleteListener != null) { mOnStickerDeleteListener.onDelete(this); } } private float getCross(PointF p1, PointF p2, PointF p) { return (p2.x - p1.x) * (p.y - p1.y) - (p.x - p1.x) * (p2.y - p1.y); } private boolean isPointInMatrix(PointF p, float[] target) { PointF p1 = new PointF(target[0], target[1]); PointF p2 = new PointF(target[6], target[7]); PointF p3 = new PointF(target[4], target[5]); PointF p4 = new PointF(target[2], target[3]); return getCross(p1, p2, p) * getCross(p3, p4, p) >= 0 && getCross(p2, p3, p) * getCross(p4, p1, p) >= 0; } private float caculateLength(float x1, float y1, float x2, float y2) { float ex = x1 - x2; float ey = y1 - y2; return (float) Math.sqrt(ex * ex + ey * ey); } private float rotation(MotionEvent event) { float originDegree = calculateDegree(mLastPointX, mLastPointY); float nowDegree = calculateDegree(event.getX(), event.getY()); return nowDegree - originDegree; } private float calculateDegree(float x, float y) { double delta_x = x - mOuterPoints[8]; double delta_y = y - mOuterPoints[9]; double radians = Math.atan2(delta_y, delta_x); return (float) Math.toDegrees(radians); } private boolean canStickerMove(float cx, float cy) { float px = cx + mOuterPoints[8]; float py = cy + mOuterPoints[9]; if (mViewRect.contains(px, py)) { return true; } else { return false; } } //button.setBackgroundDrawable(loadNinePatch("/data/data/your.app/files/button_background.9.png", context)); private Drawable loadNinePatch(String path, Context context) { // Bitmap bitmap = BitmapFactory.decodeFile(path); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.txt_bg_pink); byte[] chunk = bitmap.getNinePatchChunk(); if (NinePatch.isNinePatchChunk(chunk)) { return new NinePatchDrawable(context.getResources(), bitmap, chunk, NinePatchChunk.deserialize(bitmap.getNinePatchChunk()).mPaddings, null); } else return new BitmapDrawable(bitmap); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } @Override protected void onDraw(Canvas canvas) { int count = canvas.save(); canvas.setMatrix(mMatrix); mMatrix.mapRect(mContentRect, mOriginContentRect); mMatrix.mapPoints(mPoints, mOriginPoints); mMatrix.mapPoints(mOuterPoints, mOriginOuterPoints); mTextView.draw(canvas); canvas.restoreToCount(count); if (mInEdit) { canvas.drawLine(mOuterPoints[0], mOuterPoints[1], mOuterPoints[2], mOuterPoints[3], mBorderPaint); canvas.drawLine(mOuterPoints[0], mOuterPoints[1], mOuterPoints[2], mOuterPoints[3], mBorderPaint); canvas.drawLine(mOuterPoints[2], mOuterPoints[3], mOuterPoints[4], mOuterPoints[5], mBorderPaint); canvas.drawLine(mOuterPoints[4], mOuterPoints[5], mOuterPoints[6], mOuterPoints[7], mBorderPaint); canvas.drawLine(mOuterPoints[6], mOuterPoints[7], mOuterPoints[0], mOuterPoints[1], mBorderPaint); canvas.drawBitmap(mDeleteBitmap, mOuterPoints[0] - mControllerWidth / 2, mOuterPoints[1] - mControllerHeight / 2, mBorderPaint); canvas.drawBitmap(mControllerBitmap, mOuterPoints[4] - mControllerWidth / 2, mOuterPoints[5] - mControllerHeight / 2, mBorderPaint); } } private int getStatusBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } private boolean isInDelete(float x, float y) { int position = 0; //while (position < 8) { float rx = mOuterPoints[position]; float ry = mOuterPoints[position + 1]; RectF rectF = new RectF(rx - mDeleteWidth / 2, ry - mDeleteHeight / 2, rx + mDeleteWidth / 2, ry + mDeleteHeight / 2); if (rectF.contains(x, y)) { return true; } // position += 2; //} return false; } private boolean isInController(float x, float y) { int position = 4; //while (position < 8) { float rx = mOuterPoints[position]; float ry = mOuterPoints[position + 1]; RectF rectF = new RectF(rx - mControllerWidth / 2, ry - mControllerHeight / 2, rx + mControllerWidth / 2, ry + mControllerHeight / 2); if (rectF.contains(x, y)) { return true; } // position += 2; //} return false; } @Override public void onStickerTextBGChanged(int bgIndex) { mInEdit = true; mStickerTextBGIndex = bgIndex; } public interface OnEditStickerTextClickListener { void onEditStickerTextClick(EditStickerTextView editStickerTextView); } }
34.118908
121
0.596983
6eee58bee8f0bb7d29fcbb0f682cc4ff5db0cca1
3,025
package nio; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; public class NIO2Test { @Test void writeAndRead() throws IOException { Path path = Paths.get("nio2.txt"); AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE); ByteBuffer byteBuffer = ByteBuffer.allocate(64); byteBuffer.put("test".getBytes()); byteBuffer.flip(); fileChannel.write(byteBuffer, 0, this, new CompletionHandler<>() { @Override public void completed(Integer result, NIO2Test attachment) { //method 1 try { AsynchronousFileChannel fileChannel1 = AsynchronousFileChannel.open(path, StandardOpenOption.READ); ByteBuffer buffer2 = ByteBuffer.allocate(64); fileChannel1.read(buffer2, 0, buffer2, new CompletionHandler<>() { @Override public void completed(Integer result, ByteBuffer attachment) { attachment.flip(); byte[] data = new byte[attachment.limit()]; attachment.get(data); assertEquals("test", new String(data)); } @Override public void failed(Throwable exc, ByteBuffer attachment) { fail("read fail"); } }); System.out.println("read execute"); } catch (Exception e) { fail(e); } //method 2 try { ByteBuffer buffer = ByteBuffer.allocate(64); AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ); Future<Integer> future = channel.read(buffer, 0); while (!future.isDone()){ } buffer.flip(); byte[] data = new byte[buffer.limit()]; buffer.get(data); assertEquals("test", new String(data)); } catch (IOException e) { fail(e); } } @Override public void failed(Throwable exc, NIO2Test attachment) { fail("write fail"); } }); System.out.println("write execute"); try{ Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } }
36.890244
119
0.519339
c60fbefda2eb5f51e003cfc1c3709ebe6ba4c1ab
14,308
package com.bullhornsdk.data.model.entity.core.standard; import com.bullhornsdk.data.model.entity.core.type.AbstractEntity; import com.bullhornsdk.data.model.entity.core.type.AssociationEntity; import com.bullhornsdk.data.model.entity.core.type.CreateEntity; import com.bullhornsdk.data.model.entity.core.type.DateLastModifiedEntity; import com.bullhornsdk.data.model.entity.core.type.SearchEntity; import com.bullhornsdk.data.model.entity.core.type.SoftDeleteEntity; import com.bullhornsdk.data.model.entity.core.type.UpdateEntity; import com.bullhornsdk.data.model.entity.embedded.OneToMany; import com.bullhornsdk.data.util.ReadOnly; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonRootName; import org.joda.time.DateTime; import javax.validation.constraints.Size; import java.math.BigDecimal; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonRootName(value = "data") @JsonPropertyOrder({ "id", "action", "bhTimeStamp", "candidates", "clientContacts", "commentingPerson", "comments", "corporateUsers", "dateAdded", "dateLastModified", "entities", "externalID", "isDeleted", "jobOrder", "jobOrders", "leads", "migrateGUID", "minutesSpent", "opportunities", "personReference", "placements" }) public class Note extends AbstractEntity implements SearchEntity, UpdateEntity, CreateEntity, SoftDeleteEntity, AssociationEntity, DateLastModifiedEntity { private BigDecimal luceneScore; private Integer id; @JsonIgnore @Size(max = 30) private String action; private String bhTimeStamp; private OneToMany<Candidate> candidates; private OneToMany<ClientContact> clientContacts; private Person commentingPerson; @JsonIgnore private String comments; private OneToMany<CorporateUser> corporateUsers; private DateTime dateAdded; private DateTime dateLastModified; private OneToMany<NoteEntity> entities; @JsonIgnore @Size(max = 50) private String externalID; private Boolean isDeleted; private JobOrder jobOrder; private OneToMany<JobOrder> jobOrders; private OneToMany<Lead> leads; private String migrateGUID; private Integer minutesSpent; private OneToMany<Opportunity> opportunities; private Person personReference; private OneToMany<Placement> placements; public Note() { super(); } public Note(Integer id) { super(); setId(id); } /** * Returns the entity with the required fields for an insert set. * * @return */ public Note instantiateForInsert() { Note entity = new Note(); entity.setIsDeleted(Boolean.FALSE); return entity; } @JsonIgnore public BigDecimal getLuceneScore() { return luceneScore; } @JsonProperty("_score") public void setLuceneScore(BigDecimal luceneScore) { this.luceneScore = luceneScore; } @Override @JsonProperty("id") public Integer getId() { return id; } @ReadOnly @Override @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("action") public String getAction() { return action; } @JsonIgnore public void setAction(String action) { this.action = action; } @JsonIgnore public String getBhTimeStamp() { return bhTimeStamp; } @ReadOnly @JsonProperty("bhTimeStamp") public void setBhTimeStamp(String bhTimeStamp) { this.bhTimeStamp = bhTimeStamp; } @JsonProperty("candidates") public OneToMany<Candidate> getCandidates() { return candidates; } @JsonProperty("candidates") public void setCandidates(OneToMany<Candidate> candidates) { this.candidates = candidates; } @JsonProperty("clientContacts") public OneToMany<ClientContact> getClientContacts() { return clientContacts; } @JsonProperty("clientContacts") public void setClientContacts(OneToMany<ClientContact> clientContacts) { this.clientContacts = clientContacts; } @JsonProperty("commentingPerson") public Person getCommentingPerson() { return commentingPerson; } @JsonProperty("commentingPerson") public void setCommentingPerson(Person commentingPerson) { this.commentingPerson = commentingPerson; } @JsonProperty("comments") public String getComments() { return comments; } @JsonIgnore public void setComments(String comments) { this.comments = comments; } @JsonIgnore public OneToMany<CorporateUser> getCorporateUsers() { return corporateUsers; } @JsonProperty("corporateUsers") public void setCorporateUsers(OneToMany<CorporateUser> corporateUsers) { this.corporateUsers = corporateUsers; } @JsonProperty("dateAdded") public DateTime getDateAdded() { return dateAdded; } @ReadOnly @JsonProperty("dateAdded") public void setDateAdded(DateTime dateAdded) { this.dateAdded = dateAdded; } @JsonProperty("dateLastModified") public DateTime getDateLastModified() { return dateLastModified; } @ReadOnly @JsonProperty("dateLastModified") public void setDateLastModified(DateTime dateLastModified) { this.dateLastModified = dateLastModified; } @JsonIgnore public OneToMany<NoteEntity> getEntities() { return entities; } @ReadOnly @JsonProperty("entities") public void setEntities(OneToMany<NoteEntity> entities) { this.entities = entities; } @JsonProperty("externalID") public String getExternalID() { return externalID; } @JsonProperty("externalID") public void setExternalID(String externalID) { this.externalID = externalID; } @JsonProperty("isDeleted") public Boolean getIsDeleted() { return isDeleted; } @JsonProperty("isDeleted") public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } @JsonProperty("jobOrder") public JobOrder getJobOrder() { return jobOrder; } @JsonProperty("jobOrder") public void setJobOrder(JobOrder jobOrder) { this.jobOrder = jobOrder; } @JsonProperty("jobOrders") public OneToMany<JobOrder> getJobOrders() { return jobOrders; } @JsonProperty("jobOrders") public void setJobOrders(OneToMany<JobOrder> jobOrders) { this.jobOrders = jobOrders; } @JsonProperty("leads") public OneToMany<Lead> getLeads() { return leads; } @JsonProperty("leads") public void setLeads(OneToMany<Lead> leads) { this.leads = leads; } @JsonProperty("migrateGUID") public String getMigrateGUID() { return migrateGUID; } @JsonProperty("migrateGUID") public void setMigrateGUID(String migrateGUID) { this.migrateGUID = migrateGUID; } @JsonProperty("minutesSpent") public Integer getMinutesSpent() { return minutesSpent; } @JsonProperty("minutesSpent") public void setMinutesSpent(Integer minutesSpent) { this.minutesSpent = minutesSpent; } @JsonProperty("opportunities") public OneToMany<Opportunity> getOpportunities() { return opportunities; } @JsonProperty("opportunities") public void setOpportunities(OneToMany<Opportunity> opportunities) { this.opportunities = opportunities; } @JsonProperty("personReference") public Person getPersonReference() { return personReference; } @JsonProperty("personReference") public void setPersonReference(Person personReference) { this.personReference = personReference; } @JsonProperty("placements") public OneToMany<Placement> getPlacements() { return placements; } @JsonProperty("placements") public void setPlacements(OneToMany<Placement> placements) { this.placements = placements; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Note)) return false; Note note = (Note) o; if (luceneScore != null ? !luceneScore.equals(note.luceneScore) : note.luceneScore != null) return false; if (id != null ? !id.equals(note.id) : note.id != null) return false; if (action != null ? !action.equals(note.action) : note.action != null) return false; if (bhTimeStamp != null ? !bhTimeStamp.equals(note.bhTimeStamp) : note.bhTimeStamp != null) return false; if (candidates != null ? !candidates.equals(note.candidates) : note.candidates != null) return false; if (clientContacts != null ? !clientContacts.equals(note.clientContacts) : note.clientContacts != null) return false; if (commentingPerson != null ? !commentingPerson.equals(note.commentingPerson) : note.commentingPerson != null) return false; if (comments != null ? !comments.equals(note.comments) : note.comments != null) return false; if (corporateUsers != null ? !corporateUsers.equals(note.corporateUsers) : note.corporateUsers != null) return false; if (dateAdded != null ? !dateAdded.equals(note.dateAdded) : note.dateAdded != null) return false; if (dateLastModified != null ? !dateLastModified.equals(note.dateLastModified) : note.dateLastModified != null) return false; if (entities != null ? !entities.equals(note.entities) : note.entities != null) return false; if (externalID != null ? !externalID.equals(note.externalID) : note.externalID != null) return false; if (isDeleted != null ? !isDeleted.equals(note.isDeleted) : note.isDeleted != null) return false; if (jobOrder != null ? !jobOrder.equals(note.jobOrder) : note.jobOrder != null) return false; if (jobOrders != null ? !jobOrders.equals(note.jobOrders) : note.jobOrders != null) return false; if (leads != null ? !leads.equals(note.leads) : note.leads != null) return false; if (migrateGUID != null ? !migrateGUID.equals(note.migrateGUID) : note.migrateGUID != null) return false; if (minutesSpent != null ? !minutesSpent.equals(note.minutesSpent) : note.minutesSpent != null) return false; if (opportunities != null ? !opportunities.equals(note.opportunities) : note.opportunities != null) return false; if (personReference != null ? !personReference.equals(note.personReference) : note.personReference != null) return false; return placements != null ? placements.equals(note.placements) : note.placements == null; } @Override public int hashCode() { int result = luceneScore != null ? luceneScore.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (action != null ? action.hashCode() : 0); result = 31 * result + (bhTimeStamp != null ? bhTimeStamp.hashCode() : 0); result = 31 * result + (candidates != null ? candidates.hashCode() : 0); result = 31 * result + (clientContacts != null ? clientContacts.hashCode() : 0); result = 31 * result + (commentingPerson != null ? commentingPerson.hashCode() : 0); result = 31 * result + (comments != null ? comments.hashCode() : 0); result = 31 * result + (corporateUsers != null ? corporateUsers.hashCode() : 0); result = 31 * result + (dateAdded != null ? dateAdded.hashCode() : 0); result = 31 * result + (dateLastModified != null ? dateLastModified.hashCode() : 0); result = 31 * result + (entities != null ? entities.hashCode() : 0); result = 31 * result + (externalID != null ? externalID.hashCode() : 0); result = 31 * result + (isDeleted != null ? isDeleted.hashCode() : 0); result = 31 * result + (jobOrder != null ? jobOrder.hashCode() : 0); result = 31 * result + (jobOrders != null ? jobOrders.hashCode() : 0); result = 31 * result + (leads != null ? leads.hashCode() : 0); result = 31 * result + (migrateGUID != null ? migrateGUID.hashCode() : 0); result = 31 * result + (minutesSpent != null ? minutesSpent.hashCode() : 0); result = 31 * result + (opportunities != null ? opportunities.hashCode() : 0); result = 31 * result + (personReference != null ? personReference.hashCode() : 0); result = 31 * result + (placements != null ? placements.hashCode() : 0); return result; } @Override public String toString() { return new StringBuilder("Note {") .append("\n\t\"luceneScore\": ") .append(luceneScore) .append(",\n\t\"id\": ") .append(id) .append(",\n\t\"action\": ") .append("'") .append(action).append('\'') .append(",\n\t\"bhTimeStamp\": ") .append("'") .append(bhTimeStamp).append('\'') .append(",\n\t\"candidates\": ") .append(candidates) .append(",\n\t\"clientContacts\": ") .append(clientContacts) .append(",\n\t\"commentingPerson\": ") .append(commentingPerson) .append(",\n\t\"comments\": ") .append("'") .append(comments).append('\'') .append(",\n\t\"corporateUsers\": ") .append(corporateUsers) .append(",\n\t\"dateAdded\": ") .append(dateAdded) .append(",\n\t\"dateLastModified\": ") .append(dateLastModified) .append(",\n\t\"entities\": ") .append(entities) .append(",\n\t\"externalID\": ") .append(externalID) .append(",\n\t\"isDeleted\": ") .append(isDeleted) .append(",\n\t\"jobOrder\": ") .append(jobOrder) .append(",\n\t\"jobOrders\": ") .append(jobOrders) .append(",\n\t\"leads\": ") .append(leads) .append(",\n\t\"migrateGUID\": ") .append("'") .append(migrateGUID).append('\'') .append(",\n\t\"minutesSpent\": ") .append(minutesSpent) .append(",\n\t\"opportunities\": ") .append(opportunities) .append(",\n\t\"personReference\": ") .append(personReference) .append(",\n\t\"placements\": ") .append(placements) .append('}') .toString(); } }
32.152809
155
0.657045
e79c3716374456a8fff889e6515dfb251cd5d6bf
3,777
package com.yun.bean.auth.vo; import com.yun.bean.auth.base.CompareMode; import com.yun.bean.auth.base.ParameterType; import lombok.Data; import lombok.EqualsAndHashCode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; /** * 参数视图类 * @author wxf * @date 2019/5/24 */ @Data @EqualsAndHashCode(callSuper = false) public class ParamView extends BaseVo { /** * 用户ID */ private Long userId; /** * 接口ID */ private Long apiId; /** * 接口方法URL */ private String apiUrl; /** * 参数名 */ private String paramName; /** * 参数序号 */ private int index; /** * 参数限制类型 * @see CompareMode */ private String compareMode = CompareMode.BETWEEN; /** * 参数数值类型 (Time) (数值)(字符串) * @see ParameterType */ private int paramType = ParameterType.NUMBER; /** * 参数是否允许为空 */ private Boolean enableBlank = false; /** * 参数大值 */ private Double maxValue; /** * 参数小值 */ private Double minValue; /** * 参数范围 */ private String allowValues; /** * 参数是否生效 */ private Boolean enabled = true; public boolean compare(String value) { switch (paramType) { case ParameterType.NUMBER: switch (compareMode) { case CompareMode.GE: return Double.parseDouble(value) >= minValue; case CompareMode.LE: return Double.parseDouble(value) <= maxValue; case CompareMode.BETWEEN: return Double.parseDouble(value) >= minValue && Double.parseDouble(value) <= maxValue; default: return false; } case ParameterType.STRING: String[] values = value.split(","); String[] allowv = allowValues.split(","); return Arrays.asList(allowv).containsAll(Arrays.asList(values)); case ParameterType.TIME: SimpleDateFormat fm = new SimpleDateFormat("yyyyMM"); SimpleDateFormat fd = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat fh = new SimpleDateFormat("yyyyMMddhh"); SimpleDateFormat ff = new SimpleDateFormat("yyyyMMddhhmm"); SimpleDateFormat fs = new SimpleDateFormat("yyyyMMddhhmmss"); long time; try { if (value.length() == 6) { time = fm.parse(value).getTime(); } else if (value.length() == 8) { time = fd.parse(value).getTime(); }else if (value.length() == 10) { time = fh.parse(value).getTime(); }else if (value.length() == 12) { time = ff.parse(value).getTime(); } else if (value.length() == 14) { time = fs.parse(value).getTime(); } else { time = fs.parse(value).getTime(); } } catch (ParseException e) { return false; } switch (compareMode) { case CompareMode.GE: return time >= minValue; case CompareMode.LE: return time <= maxValue; case CompareMode.BETWEEN: return time >= minValue && time <= maxValue; default: return false; } default: return false; } } }
28.832061
110
0.483982
c0d9df90a2389034bcde100135787970caa05ff6
4,512
import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.jgoodies.forms.factories.CC; import com.jgoodies.forms.layout.FormLayout; public class DialogWindow extends JDialog { /** * */ private static final long serialVersionUID = -2295277117437760048L; JTextField boxCountField; JTextField boxSizeField; JTextField regionSizeField; public DialogWindow(Frame owner) { super(owner); initComponents(); } public DialogWindow(Dialog owner) { super(owner); initComponents(); } private void initComponents() { JPanel AlgorithmDialogGUI = new JPanel(); JPanel contentPanel = new JPanel(); JLabel boxCountLabel = new JLabel(); JLabel boxSizeLabel = new JLabel(); JLabel regionSizeLabel = new JLabel(); boxCountField = new JTextField(); boxSizeField = new JTextField(); regionSizeField = new JTextField(); JButton CancelButton = new JButton(); JButton AcceptButton = new JButton(); setTitle("Window Size Selector"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); AlgorithmDialogGUI.setLayout(new BorderLayout()); contentPanel.setLayout(new FormLayout("3px, 150px, 5px, 100px, 5px", "5px, 25px, 5px, 25px, 5px, 25px, 5px, 50px")); boxCountLabel.setText("Box Row/Column Count"); contentPanel.add(boxCountLabel, CC.xywh(2, 2, 1, 1)); boxCountField.setText(Integer.toString(VisualizationBase.ROW_COLUMN_COUNT)); contentPanel.add(boxCountField, CC.xywh(4, 2, 1, 1)); boxSizeLabel.setText("Box Row/Column Size"); contentPanel.add(boxSizeLabel, CC.xywh(2, 4, 1, 1)); boxSizeField.setText(Integer.toString((int) (VisualizationBase.BOX_XY_SIZE))); contentPanel.add(boxSizeField, CC.xywh(4, 4, 1, 1)); regionSizeField.setText(Integer.toString(VisualizationBase.REGION_SIZE)); contentPanel.add(regionSizeField, CC.xywh(4, 6, 1, 1)); regionSizeLabel.setText("Region Row/Column Size"); contentPanel.add(regionSizeLabel, CC.xywh(2, 6, 1, 1)); CancelButton.setText("Cancel"); CancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CancelButtonMouseCLicked(); } }); contentPanel.add(CancelButton, CC.xywh(2, 8, 1, 1)); AcceptButton.setText("Accept"); AcceptButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AcceptButtonMouseCLicked(); } }); contentPanel.add(AcceptButton, CC.xywh(4, 8, 1, 1)); AlgorithmDialogGUI.add(contentPanel, BorderLayout.NORTH); contentPane.add(AlgorithmDialogGUI, BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } private void CancelButtonMouseCLicked() { this.dispose(); } private void AcceptButtonMouseCLicked() { VisualizationBase.VISUALIZATION_WINDOW.executor.endPathfinding(); VisualizationBase.VISUALIZATION_WINDOW.removeBoxRegionField(); VisualizationBase.ROW_COLUMN_COUNT = Integer.parseInt(boxCountField.getText()); int sizeInt = Integer.parseInt(boxSizeField.getText()); VisualizationBase.BOX_XY_SIZE = sizeInt; VisualizationBase.REGION_SIZE = Integer.parseInt(regionSizeField.getText()); Dimension windowSize = new Dimension((int) (VisualizationBase.ROW_COLUMN_COUNT*VisualizationBase.BOX_XY_SIZE), (int) (VisualizationBase.ROW_COLUMN_COUNT*VisualizationBase.BOX_XY_SIZE)); VisualizationBase.VISUALIZATION_WINDOW.setWindowSize(windowSize); Box.initializeStaticVariables(); Region.initializeStaticVariables(); VisualizationBase.VISUALIZATION_WINDOW.createBoxRegionField(); VisualizationBase.VISUALIZATION_WINDOW.invalidate(); VisualizationBase.VISUALIZATION_WINDOW.repaint(); this.dispose(); } public void keyPressed(KeyEvent key) { if (key.getKeyCode() == KeyEvent.VK_ENTER) { AcceptButtonMouseCLicked(); } if (key.getKeyCode() == KeyEvent.VK_ESCAPE) { CancelButtonMouseCLicked(); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }
27.512195
188
0.731383
4c380bf2a59e27d119faed1bc0710a036c32fd94
1,204
package io.github.kobakei.anago.usecase; import android.util.Pair; import java.util.List; import javax.inject.Inject; import io.github.kobakei.anago.entity.Repo; import io.github.kobakei.anago.repository.RepoRepository; import io.github.kobakei.anago.repository.StarRepository; import rx.Observable; import rx.Single; /** * 自分のリポジトリ一覧を取得するユースケース * Created by keisuke on 2016/09/18. */ public class GetUserReposUseCase { private final RepoRepository repoRepository; private final StarRepository starRepository; @Inject public GetUserReposUseCase(RepoRepository repoRepository, StarRepository starRepository) { this.repoRepository = repoRepository; this.starRepository = starRepository; } public Single<List<Pair<Repo, Boolean>>> run() { return repoRepository.getUserRepos(1, 10) .flatMapObservable(Observable::from) .flatMap(repo -> Observable.combineLatest( Observable.just(repo), starRepository.get(repo.owner.login, repo.name).toObservable(), Pair::create )) .toList() .toSingle(); } }
28
94
0.663621
08e0126af6574dee76d2508f2ad31cc44309b394
5,044
/* * Copyright 2017 NAVER Corp. * * 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.navercorp.pinpoint.web.mapper.stat.sampling.sampler; import com.navercorp.pinpoint.common.server.bo.stat.ActiveTraceBo; import com.navercorp.pinpoint.common.server.bo.stat.ActiveTraceHistogram; import com.navercorp.pinpoint.common.trace.BaseHistogramSchema; import com.navercorp.pinpoint.common.trace.HistogramSchema; import com.navercorp.pinpoint.common.trace.HistogramSlot; import com.navercorp.pinpoint.web.vo.chart.Point; import com.navercorp.pinpoint.web.vo.stat.SampledActiveTrace; import com.navercorp.pinpoint.web.vo.stat.chart.agent.AgentStatPoint; import com.navercorp.pinpoint.web.vo.stat.chart.agent.TitledAgentStatPoint; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.math3.util.Precision; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.IntSummaryStatistics; import java.util.List; import java.util.function.ToIntFunction; /** * @author HyunGil Jeong */ @Component public class ActiveTraceSampler implements AgentStatSampler<ActiveTraceBo, SampledActiveTrace> { @Override public SampledActiveTrace sampleDataPoints(int timeWindowIndex, long timestamp, List<ActiveTraceBo> dataPoints, ActiveTraceBo previousDataPoint) { final HistogramSchema schema = BaseHistogramSchema.getDefaultHistogramSchemaByTypeCode(dataPoints.get(0).getHistogramSchemaType()); if (schema == null) { return newUnSampledActiveTrace(timestamp); } AgentStatPoint<Integer> fast = newAgentStatPoint(schema.getFastSlot(), timestamp, dataPoints, ActiveTraceHistogram::getFastCount); AgentStatPoint<Integer> normal = newAgentStatPoint(schema.getNormalSlot(), timestamp, dataPoints, ActiveTraceHistogram::getNormalCount); AgentStatPoint<Integer> slow = newAgentStatPoint(schema.getSlowSlot(), timestamp, dataPoints, ActiveTraceHistogram::getSlowCount); AgentStatPoint<Integer> verySlow = newAgentStatPoint(schema.getVerySlowSlot(), timestamp, dataPoints, ActiveTraceHistogram::getVerySlowCount); SampledActiveTrace sampledActiveTrace = new SampledActiveTrace(fast, normal, slow, verySlow); return sampledActiveTrace; } private SampledActiveTrace newUnSampledActiveTrace(long timestamp) { Point.UncollectedPointCreator<AgentStatPoint<Integer>> uncollected = SampledActiveTrace.UNCOLLECTED_POINT_CREATOR; AgentStatPoint<Integer> fast = uncollected.createUnCollectedPoint(timestamp); AgentStatPoint<Integer> normal = uncollected.createUnCollectedPoint(timestamp); AgentStatPoint<Integer> slow = uncollected.createUnCollectedPoint(timestamp); AgentStatPoint<Integer> verySlow = uncollected.createUnCollectedPoint(timestamp); return new SampledActiveTrace(fast, normal, slow, verySlow); } private AgentStatPoint<Integer> newAgentStatPoint(HistogramSlot slot, long timestamp, List<ActiveTraceBo> dataPoints, ToIntFunction<ActiveTraceHistogram> counter) { List<Integer> fastCounts = filterActiveTraceBoList(dataPoints, counter); return createSampledTitledPoint(slot.getSlotName(), timestamp, fastCounts); } private List<Integer> filterActiveTraceBoList(List<ActiveTraceBo> dataPoints, ToIntFunction<ActiveTraceHistogram> counter) { final List<Integer> result = new ArrayList<>(dataPoints.size()); for (ActiveTraceBo activeTraceBo : dataPoints) { final ActiveTraceHistogram activeTraceHistogram = activeTraceBo.getActiveTraceHistogram(); final int count = counter.applyAsInt(activeTraceHistogram); if (count != ActiveTraceBo.UNCOLLECTED_ACTIVE_TRACE_COUNT) { result.add(count); } } return result; } private AgentStatPoint<Integer> createSampledTitledPoint(String title, long timestamp, List<Integer> values) { if (CollectionUtils.isEmpty(values)) { return SampledActiveTrace.UNCOLLECTED_POINT_CREATOR.createUnCollectedPoint(timestamp); } IntSummaryStatistics stats = values.stream() .mapToInt(Integer::intValue) .summaryStatistics(); double avg = Precision.round(stats.getAverage(), 1); return new TitledAgentStatPoint<>( title, timestamp, stats.getMin(), stats.getMax(), avg, (int) stats.getSum()); } }
48.970874
168
0.746431
52c2657a42d28903420d2901ebf5bca412a30f97
138
package br.com.lucas.pharma.dao; import br.com.lucas.pharma.domain.Historico; public class HistoricoDAO extends GenericDAO<Historico> {}
27.6
58
0.811594
6181c7412ec1bc53bc1c612b4e6156f5ce3a8edd
4,660
package org.echo.springboot.starter.fastjson; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.alibaba.fastjson.support.spring.FastJsonJsonView; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import javax.servlet.Servlet; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * <pre> * org.echo.springboot.starter.fastjson.FastJsonAutoConfiguration * </pre> * * @author liguiqing * @since V1.0.0 2019-07-05 14:58 **/ @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @AutoConfigureBefore(WebMvcAutoConfiguration.class) @EnableConfigurationProperties(value = FastJsonProperties.class) @ConditionalOnClass({Servlet.class,JSON.class}) public class FastJsonAutoConfiguration { private FastJsonProperties fastJsonProperties; public FastJsonAutoConfiguration(FastJsonProperties fastJsonProperties) { this.fastJsonProperties = fastJsonProperties; } @Bean @ConditionalOnMissingBean FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); fastJsonHttpMessageConverter.setFastJsonConfig(getFastJsonConfig()); fastJsonHttpMessageConverter.setSupportedMediaTypes(listSupportedMediaType()); return fastJsonHttpMessageConverter; } @Bean FastJsonJsonView fastJsonJsonView() { FastJsonConfig fastJsonConfig = getFastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteEnumUsingToString); FastJsonJsonView view = new FastJsonJsonView(); view.setFastJsonConfig(fastJsonConfig); return view; } @Bean FastJsonConfig getFastJsonConfig() { FastJsonConfig fastJsonConfig = new FastJsonConfig(); SerializerFeature[] serializerFeatures = fastJsonProperties.getSerializerFeatures(); if (!Objects.isNull(serializerFeatures)) { fastJsonConfig.setSerializerFeatures(serializerFeatures); } else { fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat); } fastJsonConfig.setDateFormat(fastJsonProperties.getDateFormat()); return fastJsonConfig; } /** * 获取支持的 MediaType 列表 * * @return MediaTypes */ private List<MediaType> listSupportedMediaType() { List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML); supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM); supportedMediaTypes.add(MediaType.APPLICATION_PDF); supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML); supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML); supportedMediaTypes.add(MediaType.APPLICATION_XML); supportedMediaTypes.add(MediaType.IMAGE_GIF); supportedMediaTypes.add(MediaType.IMAGE_JPEG); supportedMediaTypes.add(MediaType.IMAGE_PNG); supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM); supportedMediaTypes.add(MediaType.TEXT_HTML); supportedMediaTypes.add(MediaType.TEXT_MARKDOWN); supportedMediaTypes.add(MediaType.TEXT_PLAIN); supportedMediaTypes.add(MediaType.TEXT_XML); return supportedMediaTypes; } }
41.981982
103
0.766738
521a70646a754a3a5600aee2800861b11f6a5269
381
package com.bruce.travel.finds.model; import java.io.Serializable; /** * Created by 梦亚 on 2016/9/7. */ public class TravelDetailInfo implements Serializable, Comparable<TravelDetailInfo>{ public String content; public String getContent() { return content; } @Override public int compareTo(TravelDetailInfo another) { return 0; } }
16.565217
85
0.67979
bfba22ace345cda05934bc88418071b516dca5a7
107
public interface Problem { double fit(double x); boolean isNeighborBetter(double f0, double f1); }
21.4
51
0.719626
cfb72f789a0c096bf203cc529ea3181cc7d74fbd
376
package jianzhioffer; public class P14_1_RopeCut{ //dp public int cuttingRope(int n) { // 2 -> 1,1 // 3 -> 2,1 // 4 -> 2,2 // 5 -> 2,3 // 6 -> 3,3 // 7 -> 3,2,2 // 8 -> 3,3,2 // 9 -> 3,3,3 // 10 -> 3,3,2,2 // method: d(1) = 1; d(2) = 2; d(3) = 3; d(4) = 4; return 0; } }
17.090909
58
0.337766
6a0d3bdb7d8d7b45d4f8aeb2adc1d9ee4b054ebb
79
package lab6.organizaton; public class Technician extends TechnicalStaff { }
11.285714
46
0.810127
52ebd312a49c8c0ed807269a3476f0264f691e31
2,740
package com.greenfield.springresthateoasservice.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.greenfield.springresthateoasservice.repository.AccountRepository; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AccountRepository accountRepository; @Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return accountRepository.findByUsername(username) .map( account -> { return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER", "read", "write")); }) .orElseThrow( () -> new UsernameNotFoundException(username) ); } }; } @Bean public DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService()); return daoAuthenticationProvider; } @Autowired public void configureAuthenticationManager(AuthenticationManagerBuilder authenticationManager) throws Exception { authenticationManager.userDetailsService(userDetailsService()); authenticationManager.authenticationProvider(daoAuthenticationProvider()); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { // Permit all users access to root, H2 database console and retrieval of access token of OAuth2 protocol httpSecurity.anonymous().disable().authorizeRequests().antMatchers("/", "/oauth/token", "/console/*").permitAll(); // Disable the CSRF httpSecurity.csrf().disable(); // Enable H2 Console running inside frame httpSecurity.headers().frameOptions().disable(); } }
41.515152
154
0.815693
102fd388aaa9b556cdb7bcd2a193708d3e57d504
859
package com.harambase.pioneer.server.service; import com.harambase.pioneer.common.ResultMap; import com.harambase.pioneer.server.pojo.base.Person; public interface PersonServerService { ResultMap login(Person person); ResultMap list(String currentPage, String pageSize, String search, String order, String orderColumn, String type, String status, String role); ResultMap create(Person person); ResultMap delete(String userId); ResultMap update(String userId, Person person); ResultMap updateLastLoginTime(String userId); ResultMap retrieve(String userId); ResultMap retrieveByKeyword(String keyword); ResultMap search(String search, String type, String status, String role, String maxLength); ResultMap countActivePersonByType(String type); ResultMap updateTrailPeriod(String userId, String period); }
28.633333
146
0.776484
ba737b9ea68b031907a8e0412ebcfbfcdbcd0b5b
6,863
package com.saveandstudio.mario.cdd; import android.content.Context; import android.graphics.*; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.saveandstudio.mario.cdd.GameBasic.*; import com.saveandstudio.mario.cdd.Scenes.Scene; import java.util.Collections; public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback { //用于控制SurfaceView private SurfaceHolder surfaceHolder; //声明一个画笔 private Paint paint; //声明一条线程 private GameThread thread; //线程消亡的标识位 private boolean flag; private int touchX, touchY; private boolean touching; private boolean touchDown = false; private boolean touchUp = true; //声明一个画布 private Canvas canvas; //声明屏幕的宽高 private int screenW, screenH; //surfaceView的宽高比 private int viewW = 9, viewH = 16; private long frameDeltaTime = 16; public MySurfaceView(Context context) { this(context, null); } public MySurfaceView(Context context, @Nullable AttributeSet attributeSet) { this(context, attributeSet, 0); } public MySurfaceView(Context context, @Nullable AttributeSet attributeSet, int defferentStyleAttribute) { super(context, attributeSet, defferentStyleAttribute); Global.surfaceContext = context; surfaceHolder = getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); paint = new Paint(); paint.setColor(getResources().getColor(R.color.colorPrimary)); Scene.prePareScene(); //设置焦点 setFocusable(true); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); screenW = getWidth(); screenH = (int) ((float) screenW / (float) viewW * (float) viewH); surfaceHolder.setFixedSize(screenW, screenH); } @Override public void surfaceCreated(SurfaceHolder holder) { screenW = this.getWidth(); screenH = this.getHeight(); flag = true; thread = new GameThread(getHolder(), this); thread.setRunning(true); thread.start(); } //绘图 private void render(Canvas canvas) { try{ paint.setColor(getResources().getColor(R.color.colorPrimary)); canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint); if (Renderer.renderersList != null) { //sort Collections.sort(Renderer.renderersList); //render for (int i = 0; i < Renderer.renderersList.size(); i++) { Renderer.renderersList.get(i).Draw(canvas, paint); } } } catch (NullPointerException e){ } } //触屏事件 @Override public boolean onTouchEvent(MotionEvent event) { touchX = (int) event.getX(); touchY = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_MOVE: touching = true; return true; case MotionEvent.ACTION_DOWN: touchDown = true; touching = true; return true; case MotionEvent.ACTION_UP: touchUp = true; touching = false; return true; default: } return true; } //逻辑 private void logic() { //Update screen info GameViewInfo.screenW = screenW; GameViewInfo.screenH = screenH; updateInput(); //Update if (Scene.gameObjectsList != null) { for (int i = 0; i < Scene.gameObjectsList.size(); i++) { Scene.gameObjectsList.get(i).Update(); } } } private void updateInput(){ //Update input if (Input.touchPosition != null) { Input.touchPosition = new Vector2((float) touchX / GameViewInfo.screenW * GameViewInfo.fixedW, (float) touchY / GameViewInfo.screenH * GameViewInfo.fixedH); } Input.touching = touching; Input.touchDown = false; Input.touchUp = false; if(touchDown){ Input.touchDown = true; touchDown = false; } if(touchUp){ Input.touchUp = true; touchUp = false; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { } } flag = false; } class GameThread extends Thread { private SurfaceHolder surfaceHolder; private MySurfaceView gameView; private boolean run = false; public GameThread(SurfaceHolder surfaceHolder, MySurfaceView gameView) { this.surfaceHolder = surfaceHolder; this.gameView = gameView; } public void setRunning(boolean run) { this.run = run; } public SurfaceHolder getSurfaceHolder() { return surfaceHolder; } @Override public void run() { while (run) { logic(); try { canvas = surfaceHolder.lockCanvas(null); if (canvas != null) { synchronized (surfaceHolder) { //call methods to draw and process next fame gameView.render(canvas); } } } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } long start = System.currentTimeMillis(); long end = System.currentTimeMillis(); try { if (end - start < frameDeltaTime) { Thread.sleep(frameDeltaTime - (end - start)); GameViewInfo.deltaTime = (float) frameDeltaTime / 1000; } else { GameViewInfo.deltaTime = (float) (end - start) / 1000; } } catch (InterruptedException e) { e.printStackTrace(); } } } } }
29.83913
109
0.550051
18d43fdee21c835f96281e46340a87f9f50bce7a
9,200
package seedu.address.model.appointment; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.time.LocalDateTime; import java.util.Objects; import java.util.logging.Logger; import seedu.address.commons.core.LogsCenter; import seedu.address.model.Entity; import seedu.address.model.IdCounter; import seedu.address.model.person.client.Client; import seedu.address.model.person.client.ClientId; import seedu.address.model.person.hairdresser.Hairdresser; import seedu.address.model.person.hairdresser.HairdresserId; /** * Represents an Appointment between a client and a hairdresser. */ public class Appointment implements Entity { // Solution below adapted from // https://github.com/cs2103-ay1819s2-w13-1/main/tree/master/src/main/java/seedu/address/model/appointment private static final Logger logger = LogsCenter.getLogger(Appointment.class); private final AppointmentId id; private final ClientId clientId; private final HairdresserId hairdresserId; private final AppointmentDate date; private final AppointmentTime time; private final AppointmentStatus appointmentStatus; private final Client client; private final Hairdresser hairdresser; private final AppointmentDuration duration; /** * Constructs an {@code Appointment} with a stated status. * * @param client A valid client. * @param hairdresser A valid hairdresser. * @param date A valid appointment date * @param time A valid appointment time * @param appointmentStatus A valid appointmentStatus */ public Appointment(Client client, Hairdresser hairdresser, AppointmentDate date, AppointmentTime time, AppointmentStatus appointmentStatus) { requireAllNonNull(client, hairdresser, date, time, appointmentStatus); this.id = IdCounter.getInstance().generateNewAppointmentId(); this.client = client; this.hairdresser = hairdresser; this.clientId = client.getId(); this.hairdresserId = hairdresser.getId(); this.date = date; this.time = time; this.appointmentStatus = appointmentStatus; this.duration = new AppointmentDuration(); logger.finer("Appointment object constructed"); } /** * For id counter. * This is an existing appointment and does not need to generate a new ID. */ public Appointment(AppointmentId id, Client client, Hairdresser hairdresser, AppointmentDate date, AppointmentTime time, AppointmentStatus appointmentStatus) { requireAllNonNull(client, hairdresser, date, time, appointmentStatus); this.id = id; this.client = client; this.hairdresser = hairdresser; this.clientId = client.getId(); this.hairdresserId = hairdresser.getId(); this.date = date; this.time = time; this.appointmentStatus = appointmentStatus; this.duration = new AppointmentDuration(); logger.finer("Appointment object constructed"); } @Override public String toString() { String str = ""; str += "Appointment - "; str += "Client ID: " + clientId; str += " Hairdresser ID: " + hairdresserId; str += " Date: " + date; str += " Time: " + time; return str; } public AppointmentId getId() { return this.id; } public ClientId getClientId() { return clientId; } public HairdresserId getHairdresserId() { return hairdresserId; } public Client getClient() { return client; } /** * Replaces the representation of the client in this appointment. * * @param newClient the client to replace the existing. * @return a new Appointment object with client replaced by the new client. */ public Appointment replaceClient(Client newClient) { logger.info("Appointment " + id + " client replaced"); return new Appointment( this.id, newClient, this.hairdresser, this.date, this.time, this.appointmentStatus ); } /** * Deletes the representation of the client in this appointment. * * @return a new Appointment object with client replaced by null. */ public Appointment deleteClient() { logger.info("Appointment " + id + " client deleted"); return replaceClient(this.client.setTombstone()); } public Hairdresser getHairdresser() { return hairdresser; } /** * Replaces the representation of the Hairdresser in this appointment. * * @param newHairdresser the Hairdresser to replace the existing. * @return a new Appointment object with Hairdresser replaced by the new Hairdresser. */ public Appointment replaceHairdresser(Hairdresser newHairdresser) { logger.info("Appointment " + id + " hairdresser replaced"); return new Appointment( this.id, this.client, newHairdresser, this.date, this.time, this.appointmentStatus ); } /** * Deletes the representation of the hairdresser in this appointment. * * @return a new Appointment object with hairdresser replaced by null. */ public Appointment deleteHairdresser() { logger.info("Appointment " + id + " hairdresser deleted"); return replaceHairdresser(this.hairdresser.setTombstone()); } public AppointmentDate getDate() { return date; } public AppointmentTime getTime() { return time; } public AppointmentStatus getAppointmentStatus() { return appointmentStatus; } public LocalDateTime startDateTime() { return LocalDateTime.of(date.date, time.time); } public LocalDateTime endDateTime() { return startDateTime().plusMinutes(duration.getNumMinutes()); } public boolean isSameAppointment(Appointment that) { return isSame(that); } @Override public boolean isSame(Entity that) { return this.equals(that); } /** * Checks if this appointment is in the past compared to system time. * * @return true if the appointment is in the past. */ public boolean isPast() { LocalDateTime currentDateTime = LocalDateTime.now(); LocalDateTime appointmentDateTime = startDateTime(); return appointmentDateTime.isBefore(currentDateTime); } /** * Checks if another appointment clashes with this appointment. * Two appointments are defined to clash if they contain either the same * hairdresser or client, and they overlap in time. * * @return true if the other appointment clashes with this. */ public boolean isClash(Appointment that) { logger.fine("Checking clash between appointments " + id + " and " + that.id); // There is a clash IFF both are active, and the start time of either is between the start and end // time of the other, or their start times are the same if (!this.appointmentStatus.equals(AppointmentStatus.ACTIVE) || !that.appointmentStatus.equals(AppointmentStatus.ACTIVE)) { // At least one of the appointments are not active return false; } if (!that.getHairdresserId().equals(this.hairdresserId) && !that.getClientId().equals(this.clientId)) { // Neither the hairdresser nor the client are the same return false; } if (this.startDateTime().isAfter(that.startDateTime()) && this.startDateTime().isBefore(that.endDateTime())) { return true; } else if (that.startDateTime().isAfter(this.startDateTime()) && that.startDateTime().isBefore(this.endDateTime())) { return true; } else if (that.startDateTime().isEqual(this.startDateTime())) { return true; } else { return false; } } /** * Defines equality between appointments based on hairdresserID, * clientID, date, and time. Does not consider status. * * @param o The object to compare to. * @return true if the other appointment has the same hairdresserID, * clientID, date, and time. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Appointment)) { return false; } Appointment that = (Appointment) o; if (!this.hairdresserId.equals(that.hairdresserId)) { return false; } if (!this.clientId.equals(that.clientId)) { return false; } if (!this.date.equals(that.date)) { return false; } if (!this.time.equals(that.time)) { return false; } return true; } @Override public int hashCode() { return Objects.hash(id, clientId, hairdresserId, date, time); } }
32.280702
110
0.634891
fe553b55736d03872a0624c2979f615490bba998
250
package cn.rosycloud.service; import cn.rosycloud.pojo.Type; import com.baomidou.mybatisplus.service.IService; /** * <p> * 类型表 服务类 * </p> * * @author yangdaihua * @since 2019-01-22 */ public interface TypeService extends IService<Type> { }
14.705882
53
0.7
0165f526dfb014d28c089ed6fedd35591c4e77e9
250
package Util; /** * Created by alancosta on 5/20/16. */ public class StringUtil { public static final String EMPTY_STRING = ""; public static boolean isEmpty(String s) { return s == null || s.trim().equals(EMPTY_STRING); } }
17.857143
58
0.636
b2d1ff677d03aa5ac4db04fbc481d07dacb570db
3,576
package com.scme.order.model; public class Ysry implements java.io.Serializable { private int a1; private String a2; private String a3; private String a4; private String a5; private String a6; private String a7; private String a8; private String a9; private String a10; private String a11; private String a12; private String a13; private String a14; private String a15; private String a160; private String a161; private String a162; private String a17; private String a18; private String a19; private String rzjk; private String rzsj; private String rzdd; private String rzzb; private Branch branch; private int count; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getA1() { return a1; } public void setA1(int a1) { this.a1 = a1; } public String getA160() { return a160; } public void setA160(String a160) { this.a160 = a160; } public String getA162() { return a162; } public void setA162(String a162) { this.a162 = a162; } public String getA161() { return a161; } public void setA161(String a161) { this.a161 = a161; } public String getA2() { return a2; } public void setA2(String a2) { this.a2 = a2; } public String getA3() { return a3; } public void setA3(String a3) { this.a3 = a3; } public String getA4() { return a4; } public void setA4(String a4) { this.a4 = a4; } public String getA5() { return a5; } public void setA5(String a5) { this.a5 = a5; } public String getA6() { return a6; } public void setA6(String a6) { this.a6 = a6; } public String getA7() { return a7; } public void setA7(String a7) { this.a7 = a7; } public String getA8() { return a8; } public void setA8(String a8) { this.a8 = a8; } public String getA9() { return a9; } public void setA9(String a9) { this.a9 = a9; } public String getA10() { return a10; } public void setA10(String a10) { this.a10 = a10; } public String getA11() { return a11; } public void setA11(String a11) { this.a11 = a11; } public String getA12() { return a12; } public void setA12(String a12) { this.a12 = a12; } public String getA13() { return a13; } public void setA13(String a13) { this.a13 = a13; } public String getA14() { return a14; } public void setA14(String a14) { this.a14 = a14; } public String getA15() { return a15; } public void setA15(String a15) { this.a15 = a15; } public String getA17() { return a17; } public void setA17(String a17) { this.a17 = a17; } public String getA18() { return a18; } public void setA18(String a18) { this.a18 = a18; } public String getA19() { return a19; } public void setA19(String a19) { this.a19 = a19; } public Branch getBranch() { return branch; } public void setBranch(Branch branch) { this.branch = branch; } public String getSubname1(int len){ if(this.getBranch().getName().length()>=4) { len=4; }else{ len=this.getBranch().getName().length(); } return this.getBranch().getName().substring(0,len); } public String getRzjk() { return rzjk; } public void setRzjk(String rzjk) { this.rzjk = rzjk; } public String getRzsj() { return rzsj; } public void setRzsj(String rzsj) { this.rzsj = rzsj; } public String getRzdd() { return rzdd; } public void setRzdd(String rzdd) { this.rzdd = rzdd; } public String getRzzb() { return rzzb; } public void setRzzb(String rzzb) { this.rzzb = rzzb; } }
13.343284
53
0.645973
26ec61bb68a1f5841356a49197ba5ff91d87c644
1,446
/** * Copyright 2015 SPeCS. * * 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. under the License. */ package org.specs.matlabtocl.v2.codegen.reductionvalidators; import java.util.List; import java.util.Optional; import org.specs.matisselib.services.ScalarValueInformationBuilderService; import org.specs.matisselib.ssa.InstructionLocation; import org.specs.matlabtocl.v2.codegen.ReductionType; import org.specs.matlabtocl.v2.ssa.ParallelRegionInstance; public interface ReductionValidator { public Optional<ReductionType> verifyReduction( ParallelRegionInstance parallelInstance, int outerBlockId, List<Integer> blocks, List<String> iterVariables, List<String> reductionVariables, List<InstructionLocation> constructionInstructions, List<InstructionLocation> midUsageInstructions, ScalarValueInformationBuilderService scalarBuilderService); }
41.314286
118
0.757261
a341b052f798be2f7433da3421fe0a0c2c76ffcd
1,836
package com.xsz.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xsz.jdbc.ResourceDao; import com.xsz.jdbc.User; import com.xsz.jdbc.UserDao2; /** * Servlet implementation class DeleteUserServlet */ @WebServlet("/DeleteResourceServlet") public class DeleteResourceServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeleteResourceServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决中文乱码问题 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //获取前端传入值 String id=request.getParameter("id"); int id2=Integer.parseInt(id); //验证前端输入的用户名和密码是否存在数据库 ResourceDao jdbc=new ResourceDao(); boolean f=jdbc.delete(id2); if(f){ response.sendRedirect("resourcetable.html"); }else{ // response.getWriter().append("欢迎"+u1.getName()+"登录成功!"); response.getWriter().append("添加失败"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
28.6875
120
0.691176
854f01f3ff2545ee6d2fa024bd4168efae319884
71
/** * Utility classes for content. */ package org.xbib.content.util;
14.2
31
0.690141
e7b8be3df940557f83e8812d3469a7dcc8886978
3,377
/* * MIT License * * Copyright (c) 2020 Udo Borkowski, (ub@abego.org) * * 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 org.abego.commons.javalang; import org.abego.commons.lang.exception.MustNotInstantiateException; import org.junit.jupiter.api.Test; import static org.abego.commons.javalang.JavaLangUtil.isJavaIdentifier; import static org.abego.commons.javalang.JavaLangUtil.isValidJavaIdentifierCharButNotAtStart; import static org.abego.commons.javalang.JavaLangUtil.toJavaIdentifier; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class JavaLangUtilTest { private static final String IDENTIFIER_SAMPLE = "SomeName"; // NON-NLS @Test void constructor() { assertThrows(MustNotInstantiateException.class, JavaLangUtil::new); } @Test void toJavaIdentifier_ok() { assertEquals(IDENTIFIER_SAMPLE, toJavaIdentifier(IDENTIFIER_SAMPLE)); } @Test void toJavaIdentifier_withSpecialCharacters() { assertEquals("a_b_c_", toJavaIdentifier("a.b-c*")); // NON-NLS } @Test void toJavaIdentifier_nonIDStart() { assertEquals("_dot", toJavaIdentifier(".dot")); // NON-NLS } @Test void toJavaIdentifier_startWithDigit() { assertEquals("_123", toJavaIdentifier("123")); // NON-NLS } @Test void toJavaIdentifier_emptyString_() { assertEquals("_", toJavaIdentifier("")); // NON-NLS } @Test void isValidJavaIdentifierCharButNotAtStart_ok() { assertTrue(isValidJavaIdentifierCharButNotAtStart('9')); // NON-NLS assertFalse(isValidJavaIdentifierCharButNotAtStart('?')); // NON-NLS assertFalse(isValidJavaIdentifierCharButNotAtStart('a')); // NON-NLS } @Test void isJavaIdentifier_ok() { assertTrue(isJavaIdentifier("abc")); // NON-NLS assertTrue(isJavaIdentifier("a2")); // NON-NLS assertTrue(isJavaIdentifier("_a")); // NON-NLS assertFalse(isJavaIdentifier("")); // NON-NLS assertFalse(isJavaIdentifier("1")); // NON-NLS assertFalse(isJavaIdentifier("?")); // NON-NLS assertFalse(isJavaIdentifier("ab?")); // NON-NLS } }
37.10989
93
0.724608
6ff6355e0a57e2e4557a1544c2638589efc56f96
3,094
/* * 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.druid.math.expr.vector; import org.apache.druid.math.expr.Expr; /** * common machinery for processing two input operators and functions, which should always treat null inputs as null * output, and are backed by a primitive values instead of an object values (and need to use the null vectors instead of * checking the vector themselves for nulls) */ public abstract class BivariateFunctionVectorProcessor<TLeftInput, TRightInput, TOutput> implements ExprVectorProcessor<TOutput> { final ExprVectorProcessor<TLeftInput> left; final ExprVectorProcessor<TRightInput> right; final int maxVectorSize; final boolean[] outNulls; final TOutput outValues; protected BivariateFunctionVectorProcessor( ExprVectorProcessor<TLeftInput> left, ExprVectorProcessor<TRightInput> right, int maxVectorSize, TOutput outValues ) { this.left = left; this.right = right; this.maxVectorSize = maxVectorSize; this.outNulls = new boolean[maxVectorSize]; this.outValues = outValues; } @Override public final ExprEvalVector<TOutput> evalVector(Expr.VectorInputBinding bindings) { final ExprEvalVector<TLeftInput> lhs = left.evalVector(bindings); final ExprEvalVector<TRightInput> rhs = right.evalVector(bindings); final int currentSize = bindings.getCurrentVectorSize(); final boolean[] leftNulls = lhs.getNullVector(); final boolean[] rightNulls = rhs.getNullVector(); final boolean hasLeftNulls = leftNulls != null; final boolean hasRightNulls = rightNulls != null; final boolean hasNulls = hasLeftNulls || hasRightNulls; final TLeftInput leftInput = lhs.values(); final TRightInput rightInput = rhs.values(); if (hasNulls) { for (int i = 0; i < currentSize; i++) { outNulls[i] = (hasLeftNulls && leftNulls[i]) || (hasRightNulls && rightNulls[i]); if (!outNulls[i]) { processIndex(leftInput, rightInput, i); } } } else { for (int i = 0; i < currentSize; i++) { processIndex(leftInput, rightInput, i); outNulls[i] = false; } } return asEval(); } abstract void processIndex(TLeftInput leftInput, TRightInput rightInput, int i); abstract ExprEvalVector<TOutput> asEval(); }
35.159091
120
0.718487
503a6ff5b7d8746068406b335f5bc39654a0d2f7
421
package com.home.commonData.message.sceneBase.response.unit; import com.home.commonData.data.scene.base.PosDirDO; import com.home.commonData.message.sceneBase.response.base.CUnitRMO; import com.home.shineData.support.MaybeNull; /** 控制单位特殊移动 */ public class CUnitSpecialMoveMO extends CUnitRMO { /** 特殊移动ID */ int id; /** 当前位置 */ @MaybeNull PosDirDO posDir; /** 参数组 */ @MaybeNull int[] args; }
22.157895
69
0.71734
eebf1c7fa289e301e9c1b164b96b304471f31825
59,362
package com.google.android.gms.location.sample.geofencing; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.GeofencingApi; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.sample.geofencing.Stasiun.Bogor; import com.google.android.gms.location.sample.geofencing.Stasiun.Bojonggede; import com.google.android.gms.location.sample.geofencing.Stasiun.Cawang; import com.google.android.gms.location.sample.geofencing.Stasiun.Cikini; import com.google.android.gms.location.sample.geofencing.Stasiun.Cilebut; import com.google.android.gms.location.sample.geofencing.Stasiun.Citayam; import com.google.android.gms.location.sample.geofencing.Stasiun.Depok; import com.google.android.gms.location.sample.geofencing.Stasiun.Depokbaru; import com.google.android.gms.location.sample.geofencing.Stasiun.Durenkalibata; import com.google.android.gms.location.sample.geofencing.Stasiun.Gondangdia; import com.google.android.gms.location.sample.geofencing.Stasiun.Jakartakota; import com.google.android.gms.location.sample.geofencing.Stasiun.Jayakarta; import com.google.android.gms.location.sample.geofencing.Stasiun.Juanda; import com.google.android.gms.location.sample.geofencing.Stasiun.Lentengagung; import com.google.android.gms.location.sample.geofencing.Stasiun.Manggabesar; import com.google.android.gms.location.sample.geofencing.Stasiun.Manggarai; import com.google.android.gms.location.sample.geofencing.Stasiun.Pasarminggu; import com.google.android.gms.location.sample.geofencing.Stasiun.Pasarminggubaru; import com.google.android.gms.location.sample.geofencing.Stasiun.Pondokcina; import com.google.android.gms.location.sample.geofencing.Stasiun.RumahNopan; import com.google.android.gms.location.sample.geofencing.Stasiun.Sawahbesar; import com.google.android.gms.location.sample.geofencing.Stasiun.Tanjungbarat; import com.google.android.gms.location.sample.geofencing.Stasiun.Tebet; import com.google.android.gms.location.sample.geofencing.Stasiun.Universitasindonesia; import com.google.android.gms.location.sample.geofencing.Stasiun.Universitaspancasila; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; import java.util.Map; /** * Demonstrates how to create and remove geofences using the GeofencingApi. Uses an IntentService * to monitor geofence transitions and creates notifications whenever a device enters or exits * a geofence. * * This sample requires a device's Location settings to be turned on. It also requires * the ACCESS_FINE_LOCATION permission, as specified in AndroidManifest.xml. * * Note that this Activity implements ResultCallback<Status>, requiring that * {@code onResult} must be defined. The {@code onResult} runs when the result of calling * {@link GeofencingApi#addGeofences(GoogleApiClient, GeofencingRequest, PendingIntent)} addGeofences()} or * {@link com.google.android.gms.location.GeofencingApi#removeGeofences(GoogleApiClient, java.util.List)} removeGeofences()} * becomes available. */ public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status> { final Context context = this; protected static final String TAG = "MainActivity"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * The list of geofences used in this sample. */ protected ArrayList<Geofence> mGeofenceList; /** * Used to keep track of whether geofences were added. */ private boolean mGeofencesAdded; /** * Used when requesting to add or remove geofences. */ private PendingIntent mGeofencePendingIntent; /** * Used to persist application state about whether geofences were added. */ private SharedPreferences mSharedPreferences; // Buttons for kicking off the process of adding or removing geofences. private Button mAddGeofencesButton; private Button mRemoveGeofencesButton; private Button AddGeofencesButton; private Button RemoveGeofenceButton; private DrawerLayout drawerLayout; private ActionBarDrawerToggle toggle; NavigationView navigation; Intent i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); //---------------------------------------------------------------------------------------------------------- drawer drawerLayout = (DrawerLayout) findViewById(R.id.drawer); toggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open, R.string.close); drawerLayout.addDrawerListener(toggle); toggle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); navigation = (NavigationView) findViewById(R.id.navigation); navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { int id = menuItem.getItemId(); switch (id){ case R.id.home: i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); finish(); break; case R.id.bantuan: break; case R.id.tentang: AlertDialog.Builder info = new AlertDialog.Builder(context); info.setMessage("Applikasi ini dibuat oleh orang ganteng") .setCancelable(false).setPositiveButton("OKE", new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface arg0, int i) { arg0.cancel(); } }); AlertDialog Dialog = info.create(); Dialog.setTitle("Tentang Applikasi"); Dialog.show(); TextView text = (TextView) Dialog.findViewById(android.R.id.message); text.setTextSize(20); break; case R.id.pengaturan: i = new Intent(getApplication(), Setting.class); startActivity(i); break; case R.id.bagikan: Intent i = new Intent(Intent.ACTION_SEND); String Judul = "Sleeping In The Train"; i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT, Judul); String sAux = "\nJadikan aplikasi ini sebagai alarm anda ketika anda sedang istirahat didalam CommuterLine\n\n"; sAux = sAux + "https://www.instagram.com/alfhan63/?hl=id \n\n"; i.putExtra(Intent.EXTRA_TEXT, sAux); startActivity(Intent.createChooser(i, "Sharing Apps")); return true; case R.id.keluar: AlertDialog.Builder keluar = new AlertDialog.Builder(context); keluar.setTitle("Keluar Applikasi ?"); keluar.setMessage(" Anda Yakin Akan Keluar ? "); keluar.setCancelable(false); keluar.setPositiveButton("Ya", new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { MainActivity.this.finish(); } }); keluar.setNegativeButton("Tidak", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.cancel(); } }); AlertDialog confirm = keluar.create(); confirm.show(); break; } return false; } }); //---------------------------------------------------------------------------------------------------------- drawer //-------------------------------------------------------------------------------------------------- Spinner spinner = (Spinner) findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.stasiun, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int i, long l) { if (i == 0) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Sleeping In The Train"); alertDialog.setMessage("Pilihlah Stasiun Tujuan Anda"); alertDialog.show(); } if (i == 1) { Bogor(); } if (i == 2) { Cilebut(); } if (i == 3) { Citayam(); } if (i == 4) { Depok(); } if (i == 5) { Cilebut(); } if (i == 6) { Depokbaru(); } if (i == 7) { Pondokcina(); } if (i == 8) { Universitasindonesia(); } if (i == 9) { Universitaspancasila(); } if (i == 10) { Lentengagung(); } if (i == 11) { Tanjungbarat(); } if (i == 12) { Pasarminggu(); } if (i == 13) { Pasarminggubaru(); } if (i == 14) { Durenkalibata(); } if (i == 15) { Cawang(); } if (i == 16) { Tebet(); } if (i == 17) { Manggarai(); } if (i == 18) { Cikini(); } if (i == 19) { Gondangdia(); } if (i == 20) { Juanda(); } if (i == 21) { Sawahbesar(); } if (i == 22) { Manggabesar(); } if (i == 23) { Jayakarta(); } if (i == 24) { Jakartakota(); } if (i == 25) { Rumah(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); //-------------------------------------------------------------------------------------------------------------------------spinner-- // Get the UI widgets. AddGeofencesButton = (Button) findViewById(R.id.addgeofences); RemoveGeofenceButton = (Button) findViewById(R.id.offgeofences); mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button); mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button); // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Retrieve an instance of the SharedPreferences object. mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE); // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default. mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false); setButtonsEnabledState(); // Get the geofences used. Geofence data is hard coded in this sample. // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); } //---------------------------------------------------------------------------------------------------------- lanjutan drawer @Override public boolean onOptionsItemSelected(MenuItem item) { if (toggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } //---------------------------------------------------------------------------------------------------------- lanjutan drawer /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the LocationServices API. */ protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost for some reason. Log.i(TAG, "Connection suspended"); // onConnected() will be called again automatically when the service reconnects } /** * Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored. * Also specifies how the geofence notifications are initially triggered. */ private GeofencingRequest getGeofencingRequest() { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device // is already inside that geofence. builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); // Add the geofences to be monitored by geofencing service. builder.addGeofences(mGeofenceList); // Return a GeofencingRequest. return builder.build(); } /** * Adds geofences, which sets alerts to be notified when the device enters or exits one of the * specified geofences. Handles the success or failure results returned by addGeofences(). */ public void addGeofencesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { LocationServices.GeofencingApi.addGeofences( mGoogleApiClient, // The GeofenceRequest object. getGeofencingRequest(), // A pending intent that that is reused when calling removeGeofences(). This // pending intent is used to generate an intent when a matched geofence // transition is observed. getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); } } //------------------------------------------------------------------------------------------------------------------------gambar public void addgeo(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { LocationServices.GeofencingApi.addGeofences( mGoogleApiClient, // The GeofenceRequest object. getGeofencingRequest(), // A pending intent that that is reused when calling removeGeofences(). This // pending intent is used to generate an intent when a matched geofence // transition is observed. getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); } } public void remgeo(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { // Remove geofences. LocationServices.GeofencingApi.removeGeofences( mGoogleApiClient, // This is the same pending intent that was used in addGeofences(). getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). GeofenceTransitionsIntentService.r.stop(); GeofenceTransitionsIntentService.v.cancel(); } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); } catch (NullPointerException e) { } } //------------------------------------------------------------------------------------------------------------------------gambar /** * Removes geofences, which stops further notifications when the device enters or exits * previously registered geofences. */ public void removeGeofencesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { // Remove geofences. LocationServices.GeofencingApi.removeGeofences( mGoogleApiClient, // This is the same pending intent that was used in addGeofences(). getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); } } private void logSecurityException(SecurityException securityException) { Log.e(TAG, "Invalid location permission. " + "You need to use ACCESS_FINE_LOCATION with geofences", securityException); } /** * Runs when the result of calling addGeofences() and removeGeofences() becomes available. * Either method can complete successfully or with an error. * <p> * Since this activity implements the {@link ResultCallback} interface, we are required to * define this method. * * @param status The Status returned through a PendingIntent when addGeofences() or * removeGeofences() get called. */ public void onResult(Status status) { if (status.isSuccess()) { // Update state and save in shared preferences. mGeofencesAdded = !mGeofencesAdded; SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded); editor.apply(); // Update the UI. Adding geofences enables the Remove Geofences button, and removing // geofences enables the Add Geofences button. setButtonsEnabledState(); Toast.makeText( this, getString(mGeofencesAdded ? R.string.geofences_added : R.string.geofences_removed), Toast.LENGTH_SHORT ).show(); } else { // Get the status code for the error and log it using a user-friendly message. String errorMessage = GeofenceErrorMessages.getErrorString(this, status.getStatusCode()); Log.e(TAG, errorMessage); } } private PendingIntent getGeofencePendingIntent() { // Reuse the PendingIntent if we already have it. if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } Intent intent = new Intent(this, GeofenceTransitionsIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling // addGeofences() and removeGeofences(). return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } /** * This sample hard codes geofence data. A real app might dynamically create geofences based on * the user's location. */ //-------------------------------------------------------------------------------------------------------------------stasiun code public void Jakartakota(){ for (Map.Entry<String, LatLng> entry : Jakartakota.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Jakartakota.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Jakartakota.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) // Create the geofence. .build()); } } public void Jayakarta() { for (Map.Entry<String, LatLng> entry : Jayakarta.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Jayakarta.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Jayakarta.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER ) // Create the geofence. .build()); } } public void Manggabesar(){ for (Map.Entry<String, LatLng> entry : Manggabesar.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Manggabesar.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Manggabesar.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER ) // Create the geofence. .build()); } } public void Sawahbesar() { for (Map.Entry<String, LatLng> entry : Sawahbesar.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Sawahbesar.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Sawahbesar.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) // Create the geofence. .build()); } } public void Juanda() { for (Map.Entry<String, LatLng> entry : Juanda.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Juanda.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Juanda.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER ) // Create the geofence. .build()); } } public void Gondangdia() { for (Map.Entry<String, LatLng> entry : Gondangdia.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Gondangdia.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Gondangdia.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) // Create the geofence. .build()); } } public void Cikini() { for (Map.Entry<String, LatLng> entry : Cikini.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Cikini.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration( Cikini.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Manggarai() { for (Map.Entry<String, LatLng> entry : Manggarai.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Manggarai.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Manggarai.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Tebet() { for (Map.Entry<String, LatLng> entry : Tebet.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Tebet.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Tebet.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Cawang() { for (Map.Entry<String, LatLng> entry : Cawang.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Cawang.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Cawang.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Durenkalibata() { for (Map.Entry<String, LatLng> entry : Durenkalibata.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Durenkalibata.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Durenkalibata.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Pasarminggubaru() { for (Map.Entry<String, LatLng> entry : Pasarminggubaru.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Pasarminggubaru.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Pasarminggubaru.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Pasarminggu() { for (Map.Entry<String, LatLng> entry : Pasarminggu.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Pasarminggu.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Pasarminggu.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Tanjungbarat() { for (Map.Entry<String, LatLng> entry : Tanjungbarat.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Tanjungbarat.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Tanjungbarat.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Lentengagung() { for (Map.Entry<String, LatLng> entry : Lentengagung.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Lentengagung.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Lentengagung.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Universitaspancasila() { for (Map.Entry<String, LatLng> entry : Universitaspancasila.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Universitaspancasila.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Universitaspancasila.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Universitasindonesia() { for (Map.Entry<String, LatLng> entry : Universitasindonesia.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Universitasindonesia.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration( Universitasindonesia.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Pondokcina() { for (Map.Entry<String, LatLng> entry : Pondokcina.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Pondokcina.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Pondokcina.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Depokbaru() { for (Map.Entry<String, LatLng> entry : Depokbaru.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Depokbaru.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Depokbaru.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Depok() { for (Map.Entry<String, LatLng> entry : Depok.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Depok.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Depok.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Citayam() { for (Map.Entry<String, LatLng> entry : Citayam.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Citayam.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Citayam.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Bojonggede() { for (Map.Entry<String, LatLng> entry : Bojonggede.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Bojonggede.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Bojonggede.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Cilebut() { for (Map.Entry<String, LatLng> entry : Cilebut.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Cilebut.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Cilebut.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Bogor() { for (Map.Entry<String, LatLng> entry : Bogor.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Bogor.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Bogor.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void Rumah() { for (Map.Entry<String, LatLng> entry : Constants.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Constants.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } public void RumahNopan() { for (Map.Entry<String, LatLng> entry : RumahNopan.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, RumahNopan.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } //----------------------------------------------------------------------------------------------------------------------------stasiun code /** * Ensures that only one button is enabled at any time. The Add Geofences button is enabled * if the user hasn't yet added geofences. The Remove Geofences button is enabled if the * user has added geofences. */ private void setButtonsEnabledState() { if (mGeofencesAdded) { AddGeofencesButton.setEnabled(false); RemoveGeofenceButton.setEnabled(true); mAddGeofencesButton.setEnabled(false); mRemoveGeofencesButton.setEnabled(true); } else { AddGeofencesButton.setEnabled(true); RemoveGeofenceButton.setEnabled(false); mAddGeofencesButton.setEnabled(true); mRemoveGeofencesButton.setEnabled(false); } } }
43.015942
139
0.55581
28abfd715d03c52f67f6b0d5a483f0d39b796fef
828
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("kj") public class class287 { @ObfuscatedName("b") @ObfuscatedSignature( signature = "(Lhp;Lhp;Ljava/lang/String;Ljava/lang/String;I)Lke;", garbageValue = "-2097439358" ) @Export("SpriteBuffer_getFontByName") public static Font SpriteBuffer_getFontByName(AbstractArchive spriteArchive, AbstractArchive fontArchive, String groupName, String fileName) { int var4 = spriteArchive.getGroupId(groupName); int var5 = spriteArchive.getFileId(var4, fileName); Font var6; if (!Friend.SpriteBuffer_bufferFile(spriteArchive, var4, var5)) { var6 = null; } else { var6 = WallDecoration.SpriteBuffer_createFont(fontArchive.takeFile(var4, var5)); } return var6; } }
31.846154
143
0.770531
313cc047e52238c094d1c9ce0e0d81c75efa8bee
1,701
package com.paypal.kyc.model; import lombok.Getter; @Getter /** * Controls different KYC rejection reasons types and their messages to send to Mirakl */ public enum KYCRejectionReasonTypeEnum { //@formatter:off VERIFICATIONSTATUS_IND_REQUIRED("<li>Filled all your account details correctly.</li><li>Submitted your Proof of Identity and Proof of Address documents.</li>"), VERIFICATIONSTATUS_PROF_REQUIRED("<li>Filled all your account details correctly.</li><li>Submitted Certificate of incorporation.</li>"), BUSINESS_STAKEHOLDER_REQUIRED("<li>Filled Business Stakeholder details.</li><li>Submitted their Proof of Identity documents.</li>"), LETTER_OF_AUTHORIZATION_REQUIRED("<li>Provided a Letter of Authorization document for the nominated Business Contact who is not a Director.</li>"), UNKWOWN("<li>Unknown issue.</li>"); //@formatter:on private final String reason; private static final String HEADER = "There is an issue with verifying your details in Hyperwallet. Please ensure that you: <br /><ul>"; private static final String FOOTER = "</ul><br />For more information on document requirements please refer to the <a href=\"https://docs.hyperwallet.com/content/payee-requirements/v1/payee-verification/required-data\">Hyperwallet guidelines</a>."; KYCRejectionReasonTypeEnum(final String reason) { this.reason = reason; } /** * Gets the common error header for each message * @return {@link String} with the error header */ public static String getReasonHeader() { return HEADER; } /** * Gets the common error footer for each message * @return {@link String} with the error footer */ public static String getReasonFooter() { return FOOTER; } }
36.978261
249
0.755438
85dba923df77fe42f820d61f2ab4d52a0ff03c43
2,190
package com.yuyakaido.android.cardstackview.sample; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.FrameLayout; public class TouristSpotCardAdapter extends ArrayAdapter<TouristSpot> { // static final String FRONT = "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ"; // static final String BACK = "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ\nZ"; static final String FRONT = "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX"; static final String BACK = "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ"; public TouristSpotCardAdapter(Context context) { super(context, 0); } @NonNull @Override public View getView(int position, View contentView, @NonNull ViewGroup parent) { if (contentView == null) { FrameLayout layout = new FrameLayout(parent.getContext()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layout.setLayoutParams(params); int id = View.generateViewId(); layout.setId(id); ((AppCompatActivity)parent.getContext()) .getSupportFragmentManager() .beginTransaction() .add(id, CardViewFragment .NewInstance(Color.BLUE, FRONT, BACK)) .commit(); return layout; } else { ((AppCompatActivity)parent.getContext()) .getSupportFragmentManager() .beginTransaction() .replace(contentView.getId(), CardViewFragment .NewInstance(Color.BLUE, FRONT, BACK)) .commit(); return contentView; } } }
42.941176
152
0.628311
d5eaf36cd432b9a0d7d175d419d08cbaa8644eec
570
import java.util.Arrays; import java.util.LinkedList; import java.util.List; class Solution { public List<List<Integer>> minimumAbsDifference(int[] arr) { Arrays.parallelSort(arr); int minDif = Integer.MAX_VALUE; for (int i = 0; i < arr.length - 1; i++) { int dif = arr[i + 1] - arr[i]; minDif = Math.min(minDif, dif); } List<List<Integer>> answer = new LinkedList<>(); for (int i = 0; i < arr.length - 1; i++) { int dif = arr[i + 1] - arr[i]; if(dif == minDif) { answer.add(Arrays.asList(arr[i], arr[i+1])); } } return answer; } }
24.782609
61
0.608772
dc22eb1f97e24613fe363766d4b68710a660fe76
3,151
package net.minecraft.world.level.storage.loot.predicates; import com.google.common.collect.ImmutableSet; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import java.util.Set; import net.minecraft.core.IRegistry; import net.minecraft.resources.MinecraftKey; import net.minecraft.util.ChatDeserializer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentManager; import net.minecraft.world.level.storage.loot.LootSerializer; import net.minecraft.world.level.storage.loot.LootTableInfo; import net.minecraft.world.level.storage.loot.parameters.LootContextParameter; import net.minecraft.world.level.storage.loot.parameters.LootContextParameters; public class LootItemConditionTableBonus implements LootItemCondition { private final Enchantment a; private final float[] b; private LootItemConditionTableBonus(Enchantment enchantment, float[] afloat) { this.a = enchantment; this.b = afloat; } @Override public LootItemConditionType b() { return LootItemConditions.j; } @Override public Set<LootContextParameter<?>> a() { return ImmutableSet.of(LootContextParameters.TOOL); } public boolean test(LootTableInfo loottableinfo) { ItemStack itemstack = (ItemStack) loottableinfo.getContextParameter(LootContextParameters.TOOL); int i = itemstack != null ? EnchantmentManager.getEnchantmentLevel(this.a, itemstack) : 0; float f = this.b[Math.min(i, this.b.length - 1)]; return loottableinfo.a().nextFloat() < f; } public static LootItemCondition.a a(Enchantment enchantment, float... afloat) { return () -> { return new LootItemConditionTableBonus(enchantment, afloat); }; } public static class a implements LootSerializer<LootItemConditionTableBonus> { public a() {} public void a(JsonObject jsonobject, LootItemConditionTableBonus lootitemconditiontablebonus, JsonSerializationContext jsonserializationcontext) { jsonobject.addProperty("enchantment", IRegistry.ENCHANTMENT.getKey(lootitemconditiontablebonus.a).toString()); jsonobject.add("chances", jsonserializationcontext.serialize(lootitemconditiontablebonus.b)); } @Override public LootItemConditionTableBonus a(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext) { MinecraftKey minecraftkey = new MinecraftKey(ChatDeserializer.h(jsonobject, "enchantment")); Enchantment enchantment = (Enchantment) IRegistry.ENCHANTMENT.getOptional(minecraftkey).orElseThrow(() -> { return new JsonParseException("Invalid enchantment id: " + minecraftkey); }); float[] afloat = (float[]) ChatDeserializer.a(jsonobject, "chances", jsondeserializationcontext, float[].class); return new LootItemConditionTableBonus(enchantment, afloat); } } }
42.013333
154
0.742304
859a60af7f2f6b4444d045c7944b730d8cb70d1b
10,070
package eu.neosurance.sdk; import android.app.Activity; import android.util.Log; import android.widget.Toast; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Callback; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.Arguments; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import eu.neosurance.utils.NSRUtils; public class Module extends ReactContextBaseJavaModule { private static final String DURATION_SHORT_KEY = "SHORT"; private static final String DURATION_LONG_KEY = "LONG"; public static ReactApplicationContext ctx; public Module(ReactApplicationContext reactContext) { super(reactContext); } public static void sendEvent(ReactApplicationContext reactContext, String eventName, WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } @Override public String getName() { return "Neosurance"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT); constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG); return constants; } @ReactMethod public String getTitle(){ return "NSR SDK React Native Android!"; } @ReactMethod public void setup(final String settingsTmp, final Callback callback) { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { try { //Toast.makeText(ctx, "RUNNING SETUP...", Toast.LENGTH_LONG).show(); Log.d("Module", "setup"); JSONObject settingsJson = new JSONObject(settingsTmp); NSRSettings settings = new NSRSettings(); settings.setDisableLog(Boolean.parseBoolean(settingsJson.getString("disable_log"))); settings.setDevMode(Boolean.parseBoolean(settingsJson.getString("dev_mode"))); settings.setBaseUrl(settingsJson.getString("base_url")); settings.setCode(settingsJson.getString("code")); settings.setSecretKey(settingsJson.getString("secret_key")); settings.setPushIcon(R.drawable.nsr_logo); settings.setWorkflowDelegate(new WFDelegate(),ctx); NSR.getInstance(ctx).setup(settings, new JSONObject(), new NSRSecurityResponse() { public void completionHandler(JSONObject json, String error) throws Exception { if (error == null) { Log.d("Module", "setup response"); Log.d("Module", json.toString()); callback.invoke(json.toString()); } else { Log.e("Module", "setup error: " + error); callback.invoke(error); } } }); NSR.getInstance(ctx).askPermissions(((ReactApplicationContext) ctx).getCurrentActivity()); } catch (JSONException e) { e.printStackTrace(); } } }); } @ReactMethod public void registerUser(final String userTmp, final Callback callback) { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { try { JSONObject userJson = new JSONObject(userTmp); //Toast.makeText(ctx, "RUNNING " + userJson.getString("method") + "...", Toast.LENGTH_LONG).show(); Log.d("Module", "registerUser"); NSRUser user = new NSRUser(); user.setEmail(userJson.getString("email")); user.setCode(userJson.getString("code")); user.setFirstname(userJson.getString("firstname")); user.setLastname(userJson.getString("lastname")); user.setAddress(userJson.getString("address")); user.setZipCode(userJson.getString("cap")); user.setCity(userJson.getString("city")); user.setStateProvince(userJson.getString("province")); user.setFiscalCode(userJson.getString("fiscalCode")); if(userJson.getJSONObject("locals").length() > 0){ JSONObject locals = new JSONObject(userJson.getString("locals")); user.setLocals(locals); } callback.invoke(userTmp); NSR.getInstance(ctx).registerUser(user); } catch (JSONException e) { e.printStackTrace(); } } }); } @ReactMethod public void sendTrialEvent(final String event) { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "RUNNING SEND TRIAL EVENT...", Toast.LENGTH_LONG).show(); Log.d("Module", "sendEvent"); try { JSONObject eventJson = new JSONObject(event); Log.d("MODULE", "sendEvent"); JSONObject payload = new JSONObject(eventJson.getString("payload")); NSR.getInstance(ctx).sendEvent(eventJson.getString("event"), payload); }catch (Exception e) { Log.e("MODULE", "sendEvent exception: " + e.getMessage()); } } }); } @ReactMethod public void showApp() { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "RUNNING SHOW LIST...", Toast.LENGTH_LONG).show(); Log.d("Module", "showApp"); NSR.getInstance(ctx).showApp(); } }); } @ReactMethod public void takePicture(final String event) { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "RUNNING NSR CLAIM...", Toast.LENGTH_LONG).show(); Log.d("Module", "takePicture"); try { ctx.startActivity(NSRUtils.makeActivityWebView(event,ctx)); } catch (Exception e) { e.printStackTrace(); } } }); } @ReactMethod public void appLogin() { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "RUNNING LOGIN EXECUTED...", Toast.LENGTH_LONG).show(); Log.d("Module", "appLogin"); try { String url = WFDelegate.getData(ctx,"login_url"); //NSR.getInstance(ctx).loginExecuted(url); NSRUser.loginExecuted(url,ctx); } catch (Exception e) { e.printStackTrace(); } } }); } @ReactMethod public void appPayment() { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "RUNNING PAYMENT EXECUTED...", Toast.LENGTH_LONG).show(); Log.d("Module", "appPayment"); try { String payment_url = WFDelegate.getData(ctx,"payment_url"); JSONObject paymentJson = new JSONObject(WFDelegate.getData(ctx,"payment")); NSRUser.paymentExecuted(paymentJson,payment_url); } catch (Exception e) { e.printStackTrace(); } } }); } @ReactMethod public void policies(final Callback callback) { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "GETTING POLICIES...", Toast.LENGTH_LONG).show(); Log.d("Module", "policies"); try { JSONObject criteria = new JSONObject(); criteria.put("available",true); NSR.getInstance(ctx).policies(criteria, new NSRSecurityResponse() { public void completionHandler(JSONObject json, String error) throws Exception { if (error == null) { Log.d("Module", "policies response"); Log.d("Module", json.toString()); callback.invoke(json.toString()); } else { Log.e("Module", "policies error: " + error); callback.invoke(error); } } }); } catch (Exception e) { e.printStackTrace(); } } }); } @ReactMethod public void closeView() { ctx = getReactApplicationContext(); ctx.runOnUiQueueThread(new Runnable() { @Override public void run() { //Toast.makeText(ctx, "CLOSING VIEW...", Toast.LENGTH_LONG).show(); Log.d("Module", "closeView"); try { NSR.getInstance(ctx).closeView(); } catch (Exception e) { e.printStackTrace(); } } }); } }
29.970238
115
0.549355
02281bf1c5b8d6d89377e5104e9700c449bcdc48
849
package com.admin.provider.web.controller.response; import java.util.Date; /** * @author: Zhaotianyi * @time: 2021/10/25 14:42 */ public class AdminRoleResp { private Integer id; private String roleName; private Integer isSys; private Date createTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public Integer getIsSys() { return isSys; } public void setIsSys(Integer isSys) { this.isSys = isSys; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
18.06383
51
0.613663
91e788c257c9fd1db634daedbd2ec3d164161285
5,088
package uk.gov.digital.ho.hocs.casework.domain.model; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.*; import org.hibernate.annotations.Where; import uk.gov.digital.ho.hocs.casework.api.dto.CaseDataType; import uk.gov.digital.ho.hocs.casework.domain.exception.ApplicationExceptions; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Map; import java.util.Set; import java.util.UUID; import static uk.gov.digital.ho.hocs.casework.application.LogEvent.CASE_CREATE_FAILURE; @MappedSuperclass @AllArgsConstructor @NoArgsConstructor(access = AccessLevel.PROTECTED) public class AbstractCaseData extends AbstractJsonDataMap implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Getter @Column(name = "uuid", columnDefinition ="uuid") private UUID uuid; @Getter @Column(name = "created") private LocalDateTime created = LocalDateTime.now(); @Getter @Column(name = "type") private String type; @Getter @Column(name = "reference") private String reference; @Setter @Getter @Column(name = "deleted") private boolean deleted; @Getter @Setter(AccessLevel.PROTECTED) @Column(name = "data") private String data = "{}"; @Setter @Getter @Column(name = "primary_topic_uuid") private UUID primaryTopicUUID; @Getter @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "primary_topic_uuid", referencedColumnName = "uuid", insertable = false, updatable = false) private Topic primaryTopic; @Setter @Getter @Column(name = "primary_correspondent_uuid") private UUID primaryCorrespondentUUID; @Getter @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "primary_correspondent_uuid", referencedColumnName = "uuid", insertable = false, updatable = false) private Correspondent primaryCorrespondent; @Setter @Getter @Column(name = "case_deadline") private LocalDate caseDeadline; @Setter @Getter @Column(name = "case_deadline_warning") private LocalDate caseDeadlineWarning; @Setter @Getter @Column(name = "date_received") private LocalDate dateReceived; @Setter @Getter @Column(name = "completed") private boolean completed; @Getter @Setter @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "case_uuid", referencedColumnName = "uuid", insertable = false) private Set<ActiveStage> activeStages; @Getter @Setter @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "case_uuid", referencedColumnName = "uuid", insertable = false, updatable = false) @Where(clause = "deleted = false") private Set<CaseNote> caseNotes; public AbstractCaseData(CaseDataType type, Long caseNumber, Map<String, String> data, ObjectMapper objectMapper, LocalDate dateReceived) { this(type, caseNumber, dateReceived); update(data, objectMapper); } public AbstractCaseData(CaseDataType type, Long caseNumber, LocalDate dateReceived) { if (type == null || caseNumber == null) { throw new ApplicationExceptions.EntityCreationException("Cannot create CaseData", CASE_CREATE_FAILURE); } this.type = type.getDisplayCode(); this.reference = CaseReferenceGenerator.generateCaseReference(this.type, caseNumber, this.created); this.uuid = randomUUID(type.getShortCode()); this.dateReceived = dateReceived; } private static UUID randomUUID(String shortCode) { if (shortCode != null) { String uuid = UUID.randomUUID().toString().substring(0, 33); return UUID.fromString(uuid.concat(shortCode)); } else { throw new ApplicationExceptions.EntityCreationException("shortCode is null", CASE_CREATE_FAILURE); } } // -------- Migration Code Start -------- public AbstractCaseData(CaseDataType type, String caseReference, Map<String, String> data, ObjectMapper objectMapper, LocalDate caseDeadline, LocalDate dateReceived, LocalDateTime caseCreated) { this(type, caseReference, caseDeadline, dateReceived, caseCreated); update(data, objectMapper); } public AbstractCaseData(CaseDataType type, String caseReference, LocalDate caseDeadline, LocalDate dateReceived, LocalDateTime caseCreated) { if (type == null || caseReference == null) { throw new ApplicationExceptions.EntityCreationException("Cannot create CaseData", CASE_CREATE_FAILURE); } this.created = caseCreated; this.type = type.getDisplayCode(); this.reference = caseReference; this.uuid = randomUUID(type.getShortCode()); this.caseDeadline = caseDeadline; this.dateReceived = dateReceived; } // -------- Migration Code End -------- }
32
198
0.682586
c4550342e01ea02becd11d0470c7a556d66d5d45
3,982
/*- * #%L * anchor-plugin-image-feature * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * 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. * #L% */ package org.anchoranalysis.plugin.image.feature.bean.list.pair; import lombok.Getter; import lombok.Setter; import org.anchoranalysis.bean.annotation.AllowEmpty; import org.anchoranalysis.bean.annotation.BeanField; import org.anchoranalysis.bean.xml.exception.ProvisionFailedException; import org.anchoranalysis.feature.bean.Feature; import org.anchoranalysis.feature.bean.list.FeatureList; import org.anchoranalysis.feature.bean.list.FeatureListProvider; import org.anchoranalysis.feature.bean.list.PrependName; import org.anchoranalysis.image.feature.bean.object.pair.FeatureDeriveFromPair; import org.anchoranalysis.image.feature.bean.object.pair.First; import org.anchoranalysis.image.feature.bean.object.pair.Merged; import org.anchoranalysis.image.feature.bean.object.pair.Second; import org.anchoranalysis.image.feature.input.FeatureInputPairObjects; import org.anchoranalysis.image.feature.input.FeatureInputSingleObject; /** * Embeds each feature in a {@link FeatureDeriveFromPair} feature (<i>first</i>, <i>second</i> or * <i>merge</i>) and prepends with a string. * * @author Owen Feehan */ public class DeriveFromPair extends FeatureListProvider<FeatureInputPairObjects> { // START BEAN PROPERTIES @BeanField @Getter @Setter private FeatureListProvider<FeatureInputSingleObject> item; @BeanField @AllowEmpty @Getter @Setter private String prependString = ""; /** Either "merged" or "first" or "second" indicating which feature to delegate from */ @BeanField @Getter @Setter private String select; // END BEAN PROPERTIES @Override public FeatureList<FeatureInputPairObjects> get() throws ProvisionFailedException { return item.get().map(this::pairFromSingle); } private FeatureDeriveFromPair pairFromSingle(Feature<FeatureInputSingleObject> featExst) throws ProvisionFailedException { Feature<FeatureInputSingleObject> featExstDup = featExst.duplicateBean(); FeatureDeriveFromPair featDelegate = createNewDelegateFeature(); featDelegate.setItem(featExstDup); PrependName.setNewNameOnFeature(featDelegate, featExstDup.getFriendlyName(), prependString); return featDelegate; } private FeatureDeriveFromPair createNewDelegateFeature() throws ProvisionFailedException { if (select.equalsIgnoreCase("first")) { return new First(); } else if (select.equalsIgnoreCase("second")) { return new Second(); } else if (select.equalsIgnoreCase("merged")) { return new Merged(); } else { throw new ProvisionFailedException( "An invalid input existings for 'select'. Select one of 'first', 'second' or 'merged'"); } } }
43.758242
108
0.748368
d05fb3d90683c2b9da45be18ce59b9c323eb2bff
38,314
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package benchmarks; public class CloneBenchmark { static class CloneableObject implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } } static class CloneableManyFieldObject implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Object o4 = new Object(); Object o5 = new Object(); Object o6 = new Object(); Object o7 = new Object(); Object o8 = new Object(); Object o9 = new Object(); Object o10 = new Object(); Object o11 = new Object(); Object o12 = new Object(); Object o13 = new Object(); Object o14 = new Object(); Object o15 = new Object(); Object o16 = new Object(); Object o17 = new Object(); Object o18 = new Object(); Object o19 = new Object(); Object o20 = new Object(); Object o21 = new Object(); Object o22 = new Object(); Object o23 = new Object(); Object o24 = new Object(); Object o25 = new Object(); Object o26 = new Object(); Object o27 = new Object(); Object o28 = new Object(); Object o29 = new Object(); Object o30 = new Object(); Object o31 = new Object(); Object o32 = new Object(); Object o33 = new Object(); Object o34 = new Object(); Object o35 = new Object(); Object o36 = new Object(); Object o37 = new Object(); Object o38 = new Object(); Object o39 = new Object(); Object o40 = new Object(); Object o41 = new Object(); Object o42 = new Object(); Object o43 = new Object(); Object o44 = new Object(); Object o45 = new Object(); Object o46 = new Object(); Object o47 = new Object(); Object o48 = new Object(); Object o49 = new Object(); Object o50 = new Object(); Object o51 = new Object(); Object o52 = new Object(); Object o53 = new Object(); Object o54 = new Object(); Object o55 = new Object(); Object o56 = new Object(); Object o57 = new Object(); Object o58 = new Object(); Object o59 = new Object(); Object o60 = new Object(); Object o61 = new Object(); Object o62 = new Object(); Object o63 = new Object(); Object o64 = new Object(); Object o65 = new Object(); Object o66 = new Object(); Object o67 = new Object(); Object o68 = new Object(); Object o69 = new Object(); Object o70 = new Object(); Object o71 = new Object(); Object o72 = new Object(); Object o73 = new Object(); Object o74 = new Object(); Object o75 = new Object(); Object o76 = new Object(); Object o77 = new Object(); Object o78 = new Object(); Object o79 = new Object(); Object o80 = new Object(); Object o81 = new Object(); Object o82 = new Object(); Object o83 = new Object(); Object o84 = new Object(); Object o85 = new Object(); Object o86 = new Object(); Object o87 = new Object(); Object o88 = new Object(); Object o89 = new Object(); Object o90 = new Object(); Object o91 = new Object(); Object o92 = new Object(); Object o93 = new Object(); Object o94 = new Object(); Object o95 = new Object(); Object o96 = new Object(); Object o97 = new Object(); Object o98 = new Object(); Object o99 = new Object(); Object o100 = new Object(); Object o101 = new Object(); Object o102 = new Object(); Object o103 = new Object(); Object o104 = new Object(); Object o105 = new Object(); Object o106 = new Object(); Object o107 = new Object(); Object o108 = new Object(); Object o109 = new Object(); Object o110 = new Object(); Object o111 = new Object(); Object o112 = new Object(); Object o113 = new Object(); Object o114 = new Object(); Object o115 = new Object(); Object o116 = new Object(); Object o117 = new Object(); Object o118 = new Object(); Object o119 = new Object(); Object o120 = new Object(); Object o121 = new Object(); Object o122 = new Object(); Object o123 = new Object(); Object o124 = new Object(); Object o125 = new Object(); Object o126 = new Object(); Object o127 = new Object(); Object o128 = new Object(); Object o129 = new Object(); Object o130 = new Object(); Object o131 = new Object(); Object o132 = new Object(); Object o133 = new Object(); Object o134 = new Object(); Object o135 = new Object(); Object o136 = new Object(); Object o137 = new Object(); Object o138 = new Object(); Object o139 = new Object(); Object o140 = new Object(); Object o141 = new Object(); Object o142 = new Object(); Object o143 = new Object(); Object o144 = new Object(); Object o145 = new Object(); Object o146 = new Object(); Object o147 = new Object(); Object o148 = new Object(); Object o149 = new Object(); Object o150 = new Object(); Object o151 = new Object(); Object o152 = new Object(); Object o153 = new Object(); Object o154 = new Object(); Object o155 = new Object(); Object o156 = new Object(); Object o157 = new Object(); Object o158 = new Object(); Object o159 = new Object(); Object o160 = new Object(); Object o161 = new Object(); Object o162 = new Object(); Object o163 = new Object(); Object o164 = new Object(); Object o165 = new Object(); Object o166 = new Object(); Object o167 = new Object(); Object o168 = new Object(); Object o169 = new Object(); Object o170 = new Object(); Object o171 = new Object(); Object o172 = new Object(); Object o173 = new Object(); Object o174 = new Object(); Object o175 = new Object(); Object o176 = new Object(); Object o177 = new Object(); Object o178 = new Object(); Object o179 = new Object(); Object o180 = new Object(); Object o181 = new Object(); Object o182 = new Object(); Object o183 = new Object(); Object o184 = new Object(); Object o185 = new Object(); Object o186 = new Object(); Object o187 = new Object(); Object o188 = new Object(); Object o189 = new Object(); Object o190 = new Object(); Object o191 = new Object(); Object o192 = new Object(); Object o193 = new Object(); Object o194 = new Object(); Object o195 = new Object(); Object o196 = new Object(); Object o197 = new Object(); Object o198 = new Object(); Object o199 = new Object(); Object o200 = new Object(); Object o201 = new Object(); Object o202 = new Object(); Object o203 = new Object(); Object o204 = new Object(); Object o205 = new Object(); Object o206 = new Object(); Object o207 = new Object(); Object o208 = new Object(); Object o209 = new Object(); Object o210 = new Object(); Object o211 = new Object(); Object o212 = new Object(); Object o213 = new Object(); Object o214 = new Object(); Object o215 = new Object(); Object o216 = new Object(); Object o217 = new Object(); Object o218 = new Object(); Object o219 = new Object(); Object o220 = new Object(); Object o221 = new Object(); Object o222 = new Object(); Object o223 = new Object(); Object o224 = new Object(); Object o225 = new Object(); Object o226 = new Object(); Object o227 = new Object(); Object o228 = new Object(); Object o229 = new Object(); Object o230 = new Object(); Object o231 = new Object(); Object o232 = new Object(); Object o233 = new Object(); Object o234 = new Object(); Object o235 = new Object(); Object o236 = new Object(); Object o237 = new Object(); Object o238 = new Object(); Object o239 = new Object(); Object o240 = new Object(); Object o241 = new Object(); Object o242 = new Object(); Object o243 = new Object(); Object o244 = new Object(); Object o245 = new Object(); Object o246 = new Object(); Object o247 = new Object(); Object o248 = new Object(); Object o249 = new Object(); Object o250 = new Object(); Object o251 = new Object(); Object o252 = new Object(); Object o253 = new Object(); Object o254 = new Object(); Object o255 = new Object(); Object o256 = new Object(); Object o257 = new Object(); Object o258 = new Object(); Object o259 = new Object(); Object o260 = new Object(); Object o261 = new Object(); Object o262 = new Object(); Object o263 = new Object(); Object o264 = new Object(); Object o265 = new Object(); Object o266 = new Object(); Object o267 = new Object(); Object o268 = new Object(); Object o269 = new Object(); Object o270 = new Object(); Object o271 = new Object(); Object o272 = new Object(); Object o273 = new Object(); Object o274 = new Object(); Object o275 = new Object(); Object o276 = new Object(); Object o277 = new Object(); Object o278 = new Object(); Object o279 = new Object(); Object o280 = new Object(); Object o281 = new Object(); Object o282 = new Object(); Object o283 = new Object(); Object o284 = new Object(); Object o285 = new Object(); Object o286 = new Object(); Object o287 = new Object(); Object o288 = new Object(); Object o289 = new Object(); Object o290 = new Object(); Object o291 = new Object(); Object o292 = new Object(); Object o293 = new Object(); Object o294 = new Object(); Object o295 = new Object(); Object o296 = new Object(); Object o297 = new Object(); Object o298 = new Object(); Object o299 = new Object(); Object o300 = new Object(); Object o301 = new Object(); Object o302 = new Object(); Object o303 = new Object(); Object o304 = new Object(); Object o305 = new Object(); Object o306 = new Object(); Object o307 = new Object(); Object o308 = new Object(); Object o309 = new Object(); Object o310 = new Object(); Object o311 = new Object(); Object o312 = new Object(); Object o313 = new Object(); Object o314 = new Object(); Object o315 = new Object(); Object o316 = new Object(); Object o317 = new Object(); Object o318 = new Object(); Object o319 = new Object(); Object o320 = new Object(); Object o321 = new Object(); Object o322 = new Object(); Object o323 = new Object(); Object o324 = new Object(); Object o325 = new Object(); Object o326 = new Object(); Object o327 = new Object(); Object o328 = new Object(); Object o329 = new Object(); Object o330 = new Object(); Object o331 = new Object(); Object o332 = new Object(); Object o333 = new Object(); Object o334 = new Object(); Object o335 = new Object(); Object o336 = new Object(); Object o337 = new Object(); Object o338 = new Object(); Object o339 = new Object(); Object o340 = new Object(); Object o341 = new Object(); Object o342 = new Object(); Object o343 = new Object(); Object o344 = new Object(); Object o345 = new Object(); Object o346 = new Object(); Object o347 = new Object(); Object o348 = new Object(); Object o349 = new Object(); Object o350 = new Object(); Object o351 = new Object(); Object o352 = new Object(); Object o353 = new Object(); Object o354 = new Object(); Object o355 = new Object(); Object o356 = new Object(); Object o357 = new Object(); Object o358 = new Object(); Object o359 = new Object(); Object o360 = new Object(); Object o361 = new Object(); Object o362 = new Object(); Object o363 = new Object(); Object o364 = new Object(); Object o365 = new Object(); Object o366 = new Object(); Object o367 = new Object(); Object o368 = new Object(); Object o369 = new Object(); Object o370 = new Object(); Object o371 = new Object(); Object o372 = new Object(); Object o373 = new Object(); Object o374 = new Object(); Object o375 = new Object(); Object o376 = new Object(); Object o377 = new Object(); Object o378 = new Object(); Object o379 = new Object(); Object o380 = new Object(); Object o381 = new Object(); Object o382 = new Object(); Object o383 = new Object(); Object o384 = new Object(); Object o385 = new Object(); Object o386 = new Object(); Object o387 = new Object(); Object o388 = new Object(); Object o389 = new Object(); Object o390 = new Object(); Object o391 = new Object(); Object o392 = new Object(); Object o393 = new Object(); Object o394 = new Object(); Object o395 = new Object(); Object o396 = new Object(); Object o397 = new Object(); Object o398 = new Object(); Object o399 = new Object(); Object o400 = new Object(); Object o401 = new Object(); Object o402 = new Object(); Object o403 = new Object(); Object o404 = new Object(); Object o405 = new Object(); Object o406 = new Object(); Object o407 = new Object(); Object o408 = new Object(); Object o409 = new Object(); Object o410 = new Object(); Object o411 = new Object(); Object o412 = new Object(); Object o413 = new Object(); Object o414 = new Object(); Object o415 = new Object(); Object o416 = new Object(); Object o417 = new Object(); Object o418 = new Object(); Object o419 = new Object(); Object o420 = new Object(); Object o421 = new Object(); Object o422 = new Object(); Object o423 = new Object(); Object o424 = new Object(); Object o425 = new Object(); Object o426 = new Object(); Object o427 = new Object(); Object o428 = new Object(); Object o429 = new Object(); Object o430 = new Object(); Object o431 = new Object(); Object o432 = new Object(); Object o433 = new Object(); Object o434 = new Object(); Object o435 = new Object(); Object o436 = new Object(); Object o437 = new Object(); Object o438 = new Object(); Object o439 = new Object(); Object o440 = new Object(); Object o441 = new Object(); Object o442 = new Object(); Object o460 = new Object(); Object o461 = new Object(); Object o462 = new Object(); Object o463 = new Object(); Object o464 = new Object(); Object o465 = new Object(); Object o466 = new Object(); Object o467 = new Object(); Object o468 = new Object(); Object o469 = new Object(); Object o470 = new Object(); Object o471 = new Object(); Object o472 = new Object(); Object o473 = new Object(); Object o474 = new Object(); Object o475 = new Object(); Object o476 = new Object(); Object o477 = new Object(); Object o478 = new Object(); Object o479 = new Object(); Object o480 = new Object(); Object o481 = new Object(); Object o482 = new Object(); Object o483 = new Object(); Object o484 = new Object(); Object o485 = new Object(); Object o486 = new Object(); Object o487 = new Object(); Object o488 = new Object(); Object o489 = new Object(); Object o490 = new Object(); Object o491 = new Object(); Object o492 = new Object(); Object o493 = new Object(); Object o494 = new Object(); Object o495 = new Object(); Object o496 = new Object(); Object o497 = new Object(); Object o498 = new Object(); Object o499 = new Object(); Object o500 = new Object(); Object o501 = new Object(); Object o502 = new Object(); Object o503 = new Object(); Object o504 = new Object(); Object o505 = new Object(); Object o506 = new Object(); Object o507 = new Object(); Object o508 = new Object(); Object o509 = new Object(); Object o510 = new Object(); Object o511 = new Object(); Object o512 = new Object(); Object o513 = new Object(); Object o514 = new Object(); Object o515 = new Object(); Object o516 = new Object(); Object o517 = new Object(); Object o518 = new Object(); Object o519 = new Object(); Object o520 = new Object(); Object o521 = new Object(); Object o522 = new Object(); Object o523 = new Object(); Object o556 = new Object(); Object o557 = new Object(); Object o558 = new Object(); Object o559 = new Object(); Object o560 = new Object(); Object o561 = new Object(); Object o562 = new Object(); Object o563 = new Object(); Object o564 = new Object(); Object o565 = new Object(); Object o566 = new Object(); Object o567 = new Object(); Object o568 = new Object(); Object o569 = new Object(); Object o570 = new Object(); Object o571 = new Object(); Object o572 = new Object(); Object o573 = new Object(); Object o574 = new Object(); Object o575 = new Object(); Object o576 = new Object(); Object o577 = new Object(); Object o578 = new Object(); Object o579 = new Object(); Object o580 = new Object(); Object o581 = new Object(); Object o582 = new Object(); Object o583 = new Object(); Object o584 = new Object(); Object o585 = new Object(); Object o586 = new Object(); Object o587 = new Object(); Object o588 = new Object(); Object o589 = new Object(); Object o590 = new Object(); Object o591 = new Object(); Object o592 = new Object(); Object o593 = new Object(); Object o594 = new Object(); Object o595 = new Object(); Object o596 = new Object(); Object o597 = new Object(); Object o598 = new Object(); Object o599 = new Object(); Object o600 = new Object(); Object o601 = new Object(); Object o602 = new Object(); Object o603 = new Object(); Object o604 = new Object(); Object o605 = new Object(); Object o606 = new Object(); Object o607 = new Object(); Object o608 = new Object(); Object o609 = new Object(); Object o610 = new Object(); Object o611 = new Object(); Object o612 = new Object(); Object o613 = new Object(); Object o614 = new Object(); Object o615 = new Object(); Object o616 = new Object(); Object o617 = new Object(); Object o618 = new Object(); Object o619 = new Object(); Object o620 = new Object(); Object o621 = new Object(); Object o622 = new Object(); Object o623 = new Object(); Object o624 = new Object(); Object o625 = new Object(); Object o626 = new Object(); Object o627 = new Object(); Object o628 = new Object(); Object o629 = new Object(); Object o630 = new Object(); Object o631 = new Object(); Object o632 = new Object(); Object o633 = new Object(); Object o634 = new Object(); Object o635 = new Object(); Object o636 = new Object(); Object o637 = new Object(); Object o638 = new Object(); Object o639 = new Object(); Object o640 = new Object(); Object o641 = new Object(); Object o642 = new Object(); Object o643 = new Object(); Object o644 = new Object(); Object o645 = new Object(); Object o646 = new Object(); Object o647 = new Object(); Object o648 = new Object(); Object o649 = new Object(); Object o650 = new Object(); Object o651 = new Object(); Object o652 = new Object(); Object o653 = new Object(); Object o654 = new Object(); Object o655 = new Object(); Object o656 = new Object(); Object o657 = new Object(); Object o658 = new Object(); Object o659 = new Object(); Object o660 = new Object(); Object o661 = new Object(); Object o662 = new Object(); Object o663 = new Object(); Object o664 = new Object(); Object o665 = new Object(); Object o666 = new Object(); Object o667 = new Object(); Object o668 = new Object(); Object o669 = new Object(); Object o670 = new Object(); Object o671 = new Object(); Object o672 = new Object(); Object o673 = new Object(); Object o674 = new Object(); Object o675 = new Object(); Object o676 = new Object(); Object o677 = new Object(); Object o678 = new Object(); Object o679 = new Object(); Object o680 = new Object(); Object o681 = new Object(); Object o682 = new Object(); Object o683 = new Object(); Object o684 = new Object(); Object o685 = new Object(); Object o686 = new Object(); Object o687 = new Object(); Object o688 = new Object(); Object o734 = new Object(); Object o735 = new Object(); Object o736 = new Object(); Object o737 = new Object(); Object o738 = new Object(); Object o739 = new Object(); Object o740 = new Object(); Object o741 = new Object(); Object o742 = new Object(); Object o743 = new Object(); Object o744 = new Object(); Object o745 = new Object(); Object o746 = new Object(); Object o747 = new Object(); Object o748 = new Object(); Object o749 = new Object(); Object o750 = new Object(); Object o751 = new Object(); Object o752 = new Object(); Object o753 = new Object(); Object o754 = new Object(); Object o755 = new Object(); Object o756 = new Object(); Object o757 = new Object(); Object o758 = new Object(); Object o759 = new Object(); Object o760 = new Object(); Object o761 = new Object(); Object o762 = new Object(); Object o763 = new Object(); Object o764 = new Object(); Object o765 = new Object(); Object o766 = new Object(); Object o767 = new Object(); Object o768 = new Object(); Object o769 = new Object(); Object o770 = new Object(); Object o771 = new Object(); Object o772 = new Object(); Object o773 = new Object(); Object o774 = new Object(); Object o775 = new Object(); Object o776 = new Object(); Object o777 = new Object(); Object o778 = new Object(); Object o779 = new Object(); Object o780 = new Object(); Object o781 = new Object(); Object o782 = new Object(); Object o783 = new Object(); Object o784 = new Object(); Object o785 = new Object(); Object o786 = new Object(); Object o787 = new Object(); Object o788 = new Object(); Object o789 = new Object(); Object o790 = new Object(); Object o791 = new Object(); Object o792 = new Object(); Object o793 = new Object(); Object o794 = new Object(); Object o795 = new Object(); Object o796 = new Object(); Object o797 = new Object(); Object o798 = new Object(); Object o799 = new Object(); Object o800 = new Object(); Object o801 = new Object(); Object o802 = new Object(); Object o803 = new Object(); Object o804 = new Object(); Object o805 = new Object(); Object o806 = new Object(); Object o807 = new Object(); Object o808 = new Object(); Object o809 = new Object(); Object o810 = new Object(); Object o811 = new Object(); Object o812 = new Object(); Object o813 = new Object(); Object o848 = new Object(); Object o849 = new Object(); Object o850 = new Object(); Object o851 = new Object(); Object o852 = new Object(); Object o853 = new Object(); Object o854 = new Object(); Object o855 = new Object(); Object o856 = new Object(); Object o857 = new Object(); Object o858 = new Object(); Object o859 = new Object(); Object o860 = new Object(); Object o861 = new Object(); Object o862 = new Object(); Object o863 = new Object(); Object o864 = new Object(); Object o865 = new Object(); Object o866 = new Object(); Object o867 = new Object(); Object o868 = new Object(); Object o869 = new Object(); Object o870 = new Object(); Object o871 = new Object(); Object o872 = new Object(); Object o873 = new Object(); Object o874 = new Object(); Object o875 = new Object(); Object o876 = new Object(); Object o877 = new Object(); Object o878 = new Object(); Object o879 = new Object(); Object o880 = new Object(); Object o881 = new Object(); Object o882 = new Object(); Object o883 = new Object(); Object o884 = new Object(); Object o885 = new Object(); Object o886 = new Object(); Object o887 = new Object(); Object o888 = new Object(); Object o889 = new Object(); Object o890 = new Object(); Object o891 = new Object(); Object o892 = new Object(); Object o893 = new Object(); Object o894 = new Object(); Object o895 = new Object(); Object o896 = new Object(); Object o897 = new Object(); Object o898 = new Object(); Object o899 = new Object(); Object o900 = new Object(); Object o901 = new Object(); Object o902 = new Object(); Object o903 = new Object(); Object o904 = new Object(); Object o905 = new Object(); Object o906 = new Object(); Object o907 = new Object(); Object o908 = new Object(); Object o909 = new Object(); Object o910 = new Object(); Object o911 = new Object(); Object o912 = new Object(); Object o913 = new Object(); Object o914 = new Object(); Object o915 = new Object(); Object o916 = new Object(); Object o917 = new Object(); Object o918 = new Object(); Object o919 = new Object(); Object o920 = new Object(); Object o921 = new Object(); Object o922 = new Object(); Object o923 = new Object(); Object o924 = new Object(); Object o925 = new Object(); Object o926 = new Object(); Object o927 = new Object(); Object o928 = new Object(); Object o929 = new Object(); Object o930 = new Object(); Object o931 = new Object(); Object o932 = new Object(); Object o933 = new Object(); Object o934 = new Object(); Object o935 = new Object(); Object o936 = new Object(); Object o937 = new Object(); Object o938 = new Object(); Object o939 = new Object(); Object o940 = new Object(); Object o941 = new Object(); Object o942 = new Object(); Object o943 = new Object(); Object o944 = new Object(); Object o945 = new Object(); Object o946 = new Object(); Object o947 = new Object(); Object o948 = new Object(); Object o949 = new Object(); Object o950 = new Object(); Object o951 = new Object(); Object o952 = new Object(); Object o953 = new Object(); Object o954 = new Object(); Object o955 = new Object(); Object o956 = new Object(); Object o957 = new Object(); Object o958 = new Object(); Object o959 = new Object(); Object o960 = new Object(); Object o961 = new Object(); Object o962 = new Object(); Object o963 = new Object(); Object o964 = new Object(); Object o965 = new Object(); Object o966 = new Object(); Object o967 = new Object(); Object o968 = new Object(); Object o969 = new Object(); Object o970 = new Object(); Object o971 = new Object(); Object o972 = new Object(); Object o973 = new Object(); Object o974 = new Object(); Object o975 = new Object(); Object o976 = new Object(); Object o977 = new Object(); Object o978 = new Object(); Object o979 = new Object(); Object o980 = new Object(); Object o981 = new Object(); Object o982 = new Object(); Object o983 = new Object(); Object o984 = new Object(); Object o985 = new Object(); Object o986 = new Object(); Object o987 = new Object(); Object o988 = new Object(); Object o989 = new Object(); Object o990 = new Object(); Object o991 = new Object(); Object o992 = new Object(); Object o993 = new Object(); Object o994 = new Object(); Object o995 = new Object(); Object o996 = new Object(); Object o997 = new Object(); Object o998 = new Object(); Object o999 = new Object(); } static class Deep0 {} static class Deep1 extends Deep0 {} static class Deep2 extends Deep1 {} static class Deep3 extends Deep2 {} static class Deep4 extends Deep3 {} static class Deep5 extends Deep4 {} static class Deep6 extends Deep5 {} static class Deep7 extends Deep6 {} static class Deep8 extends Deep7 {} static class Deep9 extends Deep8 {} static class Deep10 extends Deep9 {} static class Deep11 extends Deep10 {} static class Deep12 extends Deep11 {} static class Deep13 extends Deep12 {} static class Deep14 extends Deep13 {} static class Deep15 extends Deep14 {} static class Deep16 extends Deep15 {} static class Deep17 extends Deep16 {} static class Deep18 extends Deep17 {} static class Deep19 extends Deep18 {} static class Deep20 extends Deep19 {} static class Deep21 extends Deep20 {} static class Deep22 extends Deep21 {} static class Deep23 extends Deep22 {} static class Deep24 extends Deep23 {} static class Deep25 extends Deep24 {} static class Deep26 extends Deep25 {} static class Deep27 extends Deep26 {} static class Deep28 extends Deep27 {} static class Deep29 extends Deep28 {} static class Deep30 extends Deep29 {} static class Deep31 extends Deep30 {} static class Deep32 extends Deep31 {} static class Deep33 extends Deep32 {} static class Deep34 extends Deep33 {} static class Deep35 extends Deep34 {} static class Deep36 extends Deep35 {} static class Deep37 extends Deep36 {} static class Deep38 extends Deep37 {} static class Deep39 extends Deep38 {} static class Deep40 extends Deep39 {} static class Deep41 extends Deep40 {} static class Deep42 extends Deep41 {} static class Deep43 extends Deep42 {} static class Deep44 extends Deep43 {} static class Deep45 extends Deep44 {} static class Deep46 extends Deep45 {} static class Deep47 extends Deep46 {} static class Deep48 extends Deep47 {} static class Deep49 extends Deep48 {} static class Deep50 extends Deep49 {} static class Deep51 extends Deep50 {} static class Deep52 extends Deep51 {} static class Deep53 extends Deep52 {} static class Deep54 extends Deep53 {} static class Deep55 extends Deep54 {} static class Deep56 extends Deep55 {} static class Deep57 extends Deep56 {} static class Deep58 extends Deep57 {} static class Deep59 extends Deep58 {} static class Deep60 extends Deep59 {} static class Deep61 extends Deep60 {} static class Deep62 extends Deep61 {} static class Deep63 extends Deep62 {} static class Deep64 extends Deep63 {} static class Deep65 extends Deep64 {} static class Deep66 extends Deep65 {} static class Deep67 extends Deep66 {} static class Deep68 extends Deep67 {} static class Deep69 extends Deep68 {} static class Deep70 extends Deep69 {} static class Deep71 extends Deep70 {} static class Deep72 extends Deep71 {} static class Deep73 extends Deep72 {} static class Deep74 extends Deep73 {} static class Deep75 extends Deep74 {} static class Deep76 extends Deep75 {} static class Deep77 extends Deep76 {} static class Deep78 extends Deep77 {} static class Deep79 extends Deep78 {} static class Deep80 extends Deep79 {} static class Deep81 extends Deep80 {} static class Deep82 extends Deep81 {} static class Deep83 extends Deep82 {} static class Deep84 extends Deep83 {} static class Deep85 extends Deep84 {} static class Deep86 extends Deep85 {} static class Deep87 extends Deep86 {} static class Deep88 extends Deep87 {} static class Deep89 extends Deep88 {} static class Deep90 extends Deep89 {} static class Deep91 extends Deep90 {} static class Deep92 extends Deep91 {} static class Deep93 extends Deep92 {} static class Deep94 extends Deep93 {} static class Deep95 extends Deep94 {} static class Deep96 extends Deep95 {} static class Deep97 extends Deep96 {} static class Deep98 extends Deep97 {} static class Deep99 extends Deep98 {} static class Deep100 extends Deep99 {} static class DeepCloneable extends Deep100 implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } } public void time_Object_clone(int reps) { try { CloneableObject o = new CloneableObject(); for (int rep = 0; rep < reps; ++rep) { o.clone(); } } catch (Exception e) { throw new AssertionError(e.getMessage()); } } public void time_Object_manyFieldClone(int reps) { try { CloneableManyFieldObject o = new CloneableManyFieldObject(); for (int rep = 0; rep < reps; ++rep) { o.clone(); } } catch (Exception e) { throw new AssertionError(e.getMessage()); } } public void time_Object_deepClone(int reps) { try { DeepCloneable o = new DeepCloneable(); for (int rep = 0; rep < reps; ++rep) { o.clone(); } } catch (Exception e) { throw new AssertionError(e.getMessage()); } } public void time_Array_clone(int reps) { int[] o = new int[32]; for (int rep = 0; rep < reps; ++rep) { o.clone(); } } public void time_ObjectArray_smallClone(int reps) { Object[] o = new Object[32]; for (int i = 0; i < o.length / 2; ++i) { o[i] = new Object(); } for (int rep = 0; rep < reps; ++rep) { o.clone(); } } public void time_ObjectArray_largeClone(int reps) { Object[] o = new Object[2048]; for (int i = 0; i < o.length / 2; ++i) { o[i] = new Object(); } for (int rep = 0; rep < reps; ++rep) { o.clone(); } } }
35.740672
75
0.549147