repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
TealCube/strife
src/main/java/land/face/strife/managers/CombatStatusManager.java
2828
/** * The MIT License Copyright (c) 2015 Teal Cube Games * * 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 land.face.strife.managers; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import land.face.strife.StrifePlugin; import land.face.strife.data.champion.Champion; import land.face.strife.data.champion.LifeSkillType; import org.bukkit.entity.Player; public class CombatStatusManager { private final StrifePlugin plugin; private final Map<Player, Integer> tickMap = new ConcurrentHashMap<>(); private static final int SECONDS_TILL_EXPIRY = 8; public CombatStatusManager(StrifePlugin plugin) { this.plugin = plugin; } public boolean isInCombat(Player player) { return tickMap.containsKey(player); } public void addPlayer(Player player) { tickMap.put(player, SECONDS_TILL_EXPIRY); } public void tickCombat() { for (Player player : tickMap.keySet()) { if (!player.isOnline() || !player.isValid()) { tickMap.remove(player); continue; } int ticksLeft = tickMap.get(player); if (ticksLeft < 1) { doExitCombat(player); tickMap.remove(player); continue; } tickMap.put(player, ticksLeft - 1); } } public void doExitCombat(Player player) { if (!tickMap.containsKey(player)) { return; } Champion champion = plugin.getChampionManager().getChampion(player); if (champion.getDetailsContainer().getExpValues() == null) { return; } for (LifeSkillType type : champion.getDetailsContainer().getExpValues().keySet()) { plugin.getSkillExperienceManager().addExperience(player, type, champion.getDetailsContainer().getExpValues().get(type), false, false); } champion.getDetailsContainer().clearAll(); } }
isc
xiongmaoshouzha/test
jeecg-p3-biz-qywx/src/main/java/com/jeecg/qywx/core/service/TextDealInterfaceService.java
326
package com.jeecg.qywx.core.service; import com.jeecg.qywx.base.entity.QywxReceivetext; /** * 文本处理接口 * @author 付明星 * */ public interface TextDealInterfaceService { /** * 文本消息处理接口 * @param receiveText 文本消息实体类 */ void dealTextMessage(QywxReceivetext receiveText); }
mit
selvasingh/azure-sdk-for-java
sdk/datafactory/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/datafactory/v2018_06_01/GoogleCloudStorageLocation.java
2402
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The location of Google Cloud Storage dataset. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class) @JsonTypeName("GoogleCloudStorageLocation") public class GoogleCloudStorageLocation extends DatasetLocation { /** * Specify the bucketName of Google Cloud Storage. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "bucketName") private Object bucketName; /** * Specify the version of Google Cloud Storage. Type: string (or Expression * with resultType string). */ @JsonProperty(value = "version") private Object version; /** * Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the bucketName value */ public Object bucketName() { return this.bucketName; } /** * Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param bucketName the bucketName value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withBucketName(Object bucketName) { this.bucketName = bucketName; return this; } /** * Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the version value */ public Object version() { return this.version; } /** * Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param version the version value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withVersion(Object version) { this.version = version; return this; } }
mit
dushantSW/ip-mobile
7.3.1/DeviceInternetInformation/app/src/main/java/se/dsv/waora/deviceinternetinformation/ConnectionActivity.java
2212
package se.dsv.waora.deviceinternetinformation; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; /** * <code>ConnectionActivity</code> presents UI for showing if the device * is connected to internet. * * @author Dushant Singh */ public class ConnectionActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initiate view TextView connectivityStatus = (TextView) findViewById(R.id.textViewDeviceConnectivity); // Get connectivity service. ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // Get active network information NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); // Check if active network is connected. boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected) { // Set status connected connectivityStatus.setText(getString(R.string.online)); connectivityStatus.setTextColor(getResources().getColor(R.color.color_on)); // Check if connected with wifi boolean isWifiOn = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if (isWifiOn) { // Set wifi status on TextView wifiTextView = (TextView) findViewById(R.id.textViewWifi); wifiTextView.setText(getString(R.string.on)); wifiTextView.setTextColor(getResources().getColor(R.color.color_on)); } else { // Set mobile data status on. TextView mobileDataTextView = (TextView) findViewById(R.id.textViewMobileData); mobileDataTextView.setText(getString(R.string.on)); mobileDataTextView.setTextColor(getResources().getColor(R.color.color_on)); } } } }
mit
Kwoin/KGate
kgate-core/src/main/java/com/github/kwoin/kgate/core/sequencer/AbstractSequencer.java
3496
package com.github.kwoin.kgate.core.sequencer; import com.github.kwoin.kgate.core.message.Message; import com.github.kwoin.kgate.core.session.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.SocketException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; /** * @author P. WILLEMET */ public abstract class AbstractSequencer<T extends Message> implements Iterator<T> { private final Logger logger = LoggerFactory.getLogger(AbstractSequencer.class); protected Session<T> session; protected boolean hasNext; protected final ByteArrayOutputStream baos = new ByteArrayOutputStream(); protected @Nullable CountDownLatch oppositeSessionSignal; public void setSession(Session<T> session) { this.session = session; hasNext = !session.getInput().isInputShutdown(); } @Override public boolean hasNext() { hasNext &= !session.getInput().isClosed(); return hasNext; } @Override @Nullable public T next() { if(!hasNext()) throw new NoSuchElementException(); baos.reset(); if(oppositeSessionSignal != null) { try { oppositeSessionSignal.await(); } catch (InterruptedException e) { logger.warn("Waiting for opposite session signal interrupted"); oppositeSessionSignal = null; } } try { return readNextMessage(); } catch (SocketException e) { logger.debug("Input read() interrupted because socket has been closed"); hasNext = false; return null; } catch (IOException e) { logger.error("Unexpected error while reading next message", e); return null; } finally { resetState(); } } protected abstract T readNextMessage() throws IOException; protected abstract void resetState(); protected void waitForOppositeSessionSignal() { if(oppositeSessionSignal == null) { logger.debug("Wait for opposite session..."); oppositeSessionSignal = new CountDownLatch(1); } } public void oppositeSessionSignal() { if(oppositeSessionSignal != null) { logger.debug("wait for opposite session RELEASED"); oppositeSessionSignal.countDown(); } } protected byte readByte() throws IOException { int read = session.getInput().getInputStream().read(); baos.write(read); return (byte) read; } protected byte[] readBytes(int n) throws IOException { byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) bytes[i] = readByte(); return bytes; } protected byte[] readUntil(byte[] end, boolean withEnd) throws IOException { int read; int cursor = 0; ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); while(cursor < end.length) { read = readByte(); cursor = read == end[cursor] ? cursor + 1 : 0; tmpBaos.write(read); } byte[] bytes = tmpBaos.toByteArray(); return withEnd ? bytes : Arrays.copyOf(bytes, bytes.length - end.length); } }
mit
kmokili/formation-dta
pizzeria-admin-app/src/main/java/fr/pizzeria/admin/web/LoginController.java
1588
package fr.pizzeria.admin.web; import java.io.IOException; import javax.servlet.RequestDispatcher; 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 javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; @WebServlet("/login") public class LoginController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp"); rd.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = req.getParameter("email"); String password = req.getParameter("password"); if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) { resp.sendError(400, "Non non non ! Zone interdite"); } else if ( StringUtils.equals(email, "admin@pizzeria.fr") && StringUtils.equals(password, "admin")) { HttpSession session = req.getSession(); session.setAttribute("email", email); resp.sendRedirect(req.getContextPath() + "/pizzas/list"); } else { resp.setStatus(403); req.setAttribute("msgerr", "Ooppps noooo"); RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp"); rd.forward(req, resp); } } }
mit
jvasileff/aos-xp
src.java/org/anodyneos/xp/tag/core/DebugTag.java
679
package org.anodyneos.xp.tag.core; import javax.servlet.jsp.el.ELException; import org.anodyneos.xp.XpException; import org.anodyneos.xp.XpOutput; import org.anodyneos.xp.tagext.XpTagSupport; import org.xml.sax.SAXException; /** * @author jvas */ public class DebugTag extends XpTagSupport { public DebugTag() { super(); } /* (non-Javadoc) * @see org.anodyneos.xp.tagext.XpTag#doTag(org.anodyneos.xp.XpContentHandler) */ public void doTag(XpOutput out) throws XpException, ELException, SAXException { XpOutput newOut = new XpOutput(new DebugCH(System.err, out.getXpContentHandler())); getXpBody().invoke(newOut); } }
mit
code-not-found/jaxws-cxf
jaxws-cxf-digital-signature/src/main/java/com/codenotfound/endpoint/TicketAgentImpl.java
588
package com.codenotfound.endpoint; import java.math.BigInteger; import org.example.ticketagent.ObjectFactory; import org.example.ticketagent.TFlightsResponse; import org.example.ticketagent.TListFlights; import org.example.ticketagent_wsdl11.TicketAgent; public class TicketAgentImpl implements TicketAgent { @Override public TFlightsResponse listFlights(TListFlights body) { ObjectFactory factory = new ObjectFactory(); TFlightsResponse response = factory.createTFlightsResponse(); response.getFlightNumber().add(BigInteger.valueOf(101)); return response; } }
mit
EaW1805/data
src/main/java/com/eaw1805/data/model/map/Region.java
7717
package com.eaw1805.data.model.map; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.model.Game; import java.io.Serializable; /** * Represents a region of the world. */ public class Region implements Serializable { /** * Required by Serializable interface. */ static final long serialVersionUID = 42L; //NOPMD /** * Region's identification number. */ private int id; // NOPMD /** * Region's code. */ private char code; /** * The name of the region. */ private String name; /** * The game this region belongs to. */ private Game game; /** * Default constructor. */ public Region() { // Empty constructor } /** * Get the Identification number of the region. * * @return the identification number of the region. */ public int getId() { return id; } /** * Set the Identification number of the region. * * @param identity the identification number of the region. */ public void setId(final int identity) { this.id = identity; } /** * Get the name of the region. * * @return the name of the region. */ public String getName() { return name; } /** * Set the thisName of the region. * * @param thisName the name of the region. */ public void setName(final String thisName) { this.name = thisName; } /** * Get the Single-char code of the region. * * @return the Single-char code of the region. */ public char getCode() { return code; } /** * Set the single-char code of the region. * * @param thisCode the single-char code of the region. */ public void setCode(final char thisCode) { this.code = thisCode; } /** * Get the game this region belongs to. * * @return The game of the region. */ public Game getGame() { return game; } /** * Set the game this region belongs to. * * @param value The game. */ public void setGame(final Game value) { this.game = value; } /** * Indicates whether some other object is "equal to" this one. * The <code>equals</code> method implements an equivalence relation * on non-null object references: * <ul> * <li>It is <i>reflexive</i>: for any non-null reference value * <code>x</code>, <code>x.equals(x)</code> should return * <code>true</code>. * <li>It is <i>symmetric</i>: for any non-null reference values * <code>x</code> and <code>y</code>, <code>x.equals(y)</code> * should return <code>true</code> if and only if * <code>y.equals(x)</code> returns <code>true</code>. * <li>It is <i>transitive</i>: for any non-null reference values * <code>x</code>, <code>y</code>, and <code>z</code>, if * <code>x.equals(y)</code> returns <code>true</code> and * <code>y.equals(z)</code> returns <code>true</code>, then * <code>x.equals(z)</code> should return <code>true</code>. * <li>It is <i>consistent</i>: for any non-null reference values * <code>x</code> and <code>y</code>, multiple invocations of * <tt>x.equals(y)</tt> consistently return <code>true</code> * or consistently return <code>false</code>, provided no * information used in <code>equals</code> comparisons on the * objects is modified. * <li>For any non-null reference value <code>x</code>, * <code>x.equals(null)</code> should return <code>false</code>. * </ul> * The <tt>equals</tt> method for class <code>Object</code> implements * the most discriminating possible equivalence relation on objects; * that is, for any non-null reference values <code>x</code> and * <code>y</code>, this method returns <code>true</code> if and only * if <code>x</code> and <code>y</code> refer to the same object * (<code>x == y</code> has the value <code>true</code>). * Note that it is generally necessary to override the <tt>hashCode</tt> * method whenever this method is overridden, so as to maintain the * general contract for the <tt>hashCode</tt> method, which states * that equal objects must have equal hash codes. * * @param obj the reference object with which to compare. * @return <code>true</code> if this object is the same as the obj * argument; <code>false</code> otherwise. * @see #hashCode() * @see java.util.Hashtable */ @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (!(obj instanceof Region)) { return false; } final Region region = (Region) obj; if (code != region.code) { return false; } if (id != region.id) { return false; } if (name != null ? !name.equals(region.name) : region.name != null) { return false; } return true; } /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * <code>java.util.Hashtable</code>. * The general contract of <code>hashCode</code> is: * <ul> * <li>Whenever it is invoked on the same object more than once during * an execution of a Java application, the <tt>hashCode</tt> method * must consistently return the same integer, provided no information * used in <tt>equals</tt> comparisons on the object is modified. * This integer need not remain consistent from one execution of an * application to another execution of the same application. * <li>If two objects are equal according to the <tt>equals(Object)</tt> * method, then calling the <code>hashCode</code> method on each of * the two objects must produce the same integer result. * <li>It is <em>not</em> required that if two objects are unequal * according to the {@link java.lang.Object#equals(java.lang.Object)} * method, then calling the <tt>hashCode</tt> method on each of the * two objects must produce distinct integer results. However, the * programmer should be aware that producing distinct integer results * for unequal objects may improve the performance of hashtables. * </ul> * As much as is reasonably practical, the hashCode method defined by * class <tt>Object</tt> does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation * technique is not required by the * Java<font size="-2"><sup>TM</sup></font> programming language.) * * @return a hash code value for this object. * @see java.lang.Object#equals(java.lang.Object) * @see java.util.Hashtable */ @Override public int hashCode() { return id; } @Override public String toString() { final StringBuilder sbld = new StringBuilder(); switch (id) { case RegionConstants.EUROPE: sbld.append("E"); break; case RegionConstants.CARIBBEAN: sbld.append("C"); break; case RegionConstants.INDIES: sbld.append("I"); break; case RegionConstants.AFRICA: sbld.append("A"); break; default: break; } return sbld.toString(); } }
mit
malaonline/Android
app/src/main/java/com/malalaoshi/android/ui/dialogs/CommentDialog.java
10909
package com.malalaoshi.android.ui.dialogs; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.malalaoshi.android.R; import com.malalaoshi.android.core.network.api.ApiExecutor; import com.malalaoshi.android.core.network.api.BaseApiContext; import com.malalaoshi.android.core.stat.StatReporter; import com.malalaoshi.android.core.utils.MiscUtil; import com.malalaoshi.android.entity.Comment; import com.malalaoshi.android.network.Constants; import com.malalaoshi.android.network.api.PostCommentApi; import com.malalaoshi.android.ui.widgets.DoubleImageView; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by donald on 2017/6/29. */ public class CommentDialog extends BaseDialog { private static String ARGS_DIALOG_COMMENT_TYPE = "comment type"; private static String ARGS_DIALOG_TEACHER_NAME = "teacher name"; private static String ARGS_DIALOG_TEACHER_AVATAR = "teacher avatar"; private static String ARGS_DIALOG_LECTURER_NAME = "lecturer name"; private static String ARGS_DIALOG_LECTURER_AVATAR = "lecturer avatar"; private static String ARGS_DIALOG_ASSIST_NAME = "assist name"; private static String ARGS_DIALOG_ASSIST_AVATAR = "assist avatar"; private static String ARGS_DIALOG_COURSE_NAME = "course name"; private static String ARGS_DIALOG_COMMENT = "comment"; private static String ARGS_DIALOG_TIMESLOT = "timeslot"; @Bind(R.id.div_comment_dialog_avatar) DoubleImageView mDivCommentDialogAvatar; @Bind(R.id.tv_comment_dialog_teacher_course) TextView mTvCommentDialogTeacherCourse; @Bind(R.id.rb_comment_dialog_score) RatingBar mRbCommentDialogScore; @Bind(R.id.et_comment_dialog_input) EditText mEtCommentDialogInput; @Bind(R.id.tv_comment_dialog_commit) TextView mTvCommentDialogCommit; @Bind(R.id.iv_comment_dialog_close) ImageView mIvCommentDialogClose; private int mCommentType; private String mTeacherName; private String mTeacherAvatar; private String mLeactureAvatar; private String mLeactureName; private String mAssistantAvatar; private String mAssistantName; private String mCourseName; private Comment mComment; private long mTimeslot; private OnCommentResultListener mResultListener; public CommentDialog(Context context) { super(context); } public CommentDialog(Context context, Bundle bundle) { super(context); if (bundle != null) { mCommentType = bundle.getInt(ARGS_DIALOG_COMMENT_TYPE); if (mCommentType == 0) { mTeacherName = bundle.getString(ARGS_DIALOG_TEACHER_NAME, ""); mTeacherAvatar = bundle.getString(ARGS_DIALOG_TEACHER_AVATAR, ""); } else if (mCommentType == 1) { mLeactureAvatar = bundle.getString(ARGS_DIALOG_LECTURER_AVATAR, ""); mLeactureName = bundle.getString(ARGS_DIALOG_LECTURER_NAME, ""); mAssistantAvatar = bundle.getString(ARGS_DIALOG_ASSIST_AVATAR, ""); mAssistantName = bundle.getString(ARGS_DIALOG_ASSIST_NAME, ""); } mCourseName = bundle.getString(ARGS_DIALOG_COURSE_NAME, ""); mComment = bundle.getParcelable(ARGS_DIALOG_COMMENT); mTimeslot = bundle.getLong(ARGS_DIALOG_TIMESLOT, 0L); } initView(); } private void initView() { setCancelable(false); if (mCommentType == 0) mDivCommentDialogAvatar.loadImg(mTeacherAvatar, "", DoubleImageView.LOAD_SIGNLE_BIG); else if (mCommentType == 1) mDivCommentDialogAvatar.loadImg(mLeactureAvatar, mAssistantAvatar, DoubleImageView.LOAD_DOUBLE); if (mComment != null) { StatReporter.commentPage(true); updateUI(mComment); mRbCommentDialogScore.setIsIndicator(true); mEtCommentDialogInput.setFocusableInTouchMode(false); mEtCommentDialogInput.setCursorVisible(false); mTvCommentDialogCommit.setText("查看评价"); } else { StatReporter.commentPage(false); mTvCommentDialogCommit.setText("提交"); mRbCommentDialogScore.setIsIndicator(false); mEtCommentDialogInput.setFocusableInTouchMode(true); mEtCommentDialogInput.setCursorVisible(true); } mTvCommentDialogTeacherCourse.setText(mCourseName); mRbCommentDialogScore.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (mComment == null){ if (fromUser && rating > 0 && mEtCommentDialogInput.getText().length() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); mEtCommentDialogInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mComment == null){ if (s.length() > 0 && mRbCommentDialogScore.getRating() > 0){ mTvCommentDialogCommit.setEnabled(true); }else { mTvCommentDialogCommit.setEnabled(false); } } } }); } @Override protected View getView() { View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment_v2, null); ButterKnife.bind(this, view); return view; } private void updateUI(Comment comment) { if (comment != null) { mRbCommentDialogScore.setRating(comment.getScore()); mEtCommentDialogInput.setText(comment.getContent()); } else { mRbCommentDialogScore.setRating(0); mEtCommentDialogInput.setText(""); } } @Override protected int getDialogStyleId() { return 0; } public static CommentDialog newInstance(Context context, String lecturerName, String lecturerAvatarUrl, String assistName, String assistAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 1); args.putString(ARGS_DIALOG_LECTURER_NAME, lecturerName); args.putString(ARGS_DIALOG_LECTURER_AVATAR, lecturerAvatarUrl); args.putString(ARGS_DIALOG_ASSIST_NAME, assistName); args.putString(ARGS_DIALOG_ASSIST_AVATAR, assistAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } public void setOnCommentResultListener(OnCommentResultListener listener) { mResultListener = listener; } public static CommentDialog newInstance(Context context, String teacherName, String teacherAvatarUrl, String courseName, Long timeslot, Comment comment) { Bundle args = new Bundle(); args.putInt(ARGS_DIALOG_COMMENT_TYPE, 0); args.putString(ARGS_DIALOG_TEACHER_NAME, teacherName); args.putString(ARGS_DIALOG_TEACHER_AVATAR, teacherAvatarUrl); args.putString(ARGS_DIALOG_COURSE_NAME, courseName); args.putParcelable(ARGS_DIALOG_COMMENT, comment); args.putLong(ARGS_DIALOG_TIMESLOT, timeslot); // f.setArguments(args); CommentDialog f = new CommentDialog(context, args); return f; } @OnClick({R.id.tv_comment_dialog_commit, R.id.iv_comment_dialog_close}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.tv_comment_dialog_commit: commit(); dismiss(); break; case R.id.iv_comment_dialog_close: dismiss(); break; } } private void commit() { StatReporter.commentSubmit(); if (mComment != null) { dismiss(); return; } float score = mRbCommentDialogScore.getRating(); if (score == 0.0) { MiscUtil.toast(R.string.rate_the_course); return; } String content = mEtCommentDialogInput.getText().toString(); if (TextUtils.isEmpty(content)) { MiscUtil.toast(R.string.write_few_reviews); return; } JSONObject json = new JSONObject(); try { json.put(Constants.TIMESLOT, mTimeslot); json.put(Constants.SCORE, score); json.put(Constants.CONTENT, content); } catch (JSONException e) { e.printStackTrace(); return; } ApiExecutor.exec(new PostCommentRequest(this, json.toString())); } public interface OnCommentResultListener { void onSuccess(Comment comment); } private static final class PostCommentRequest extends BaseApiContext<CommentDialog, Comment> { private String body; public PostCommentRequest(CommentDialog commentDialog, String body) { super(commentDialog); this.body = body; } @Override public Comment request() throws Exception { return new PostCommentApi().post(body); } @Override public void onApiSuccess(@NonNull Comment response) { get().commentSucceed(response); } @Override public void onApiFailure(Exception exception) { get().commentFailed(); } } private void commentFailed() { MiscUtil.toast(R.string.comment_failed); } private void commentSucceed(Comment response) { MiscUtil.toast(R.string.comment_succeed); if (mResultListener != null) mResultListener.onSuccess(response); dismiss(); } }
mit
pegurnee/2013-03-211
workspace/Lecture 09_18_13/src/ManageAccounts.java
1595
import java.text.NumberFormat; // **************************************************************** // ManageAccounts.java // Use Account class to create and manage Sally and Joe's bank accounts public class ManageAccounts { public static void main(String[] args) { Account acct1, acct2; NumberFormat usMoney = NumberFormat.getCurrencyInstance(); //create account1 for Sally with $1000 acct1 = new Account(1000, "Sally", 1111); //create account2 for Joe with $500 acct2 = new Account(500, "Joe", 1212); //deposit $100 to Joe's account acct2.deposit(100); //print Joe's new balance (use getBalance()) System.out.println("Joe's new balance: " + usMoney.format(acct2.getBalance())); //withdraw $50 from Sally's account acct1.withdraw(50); //print Sally's new balance (use getBalance()) System.out.println("Sally's new balance: " + usMoney.format(acct1.getBalance())); //charge fees to both accounts System.out.println("Sally's new balance after the fee is charged: " + usMoney.format(acct1.chargeFee())); System.out.println("Joe's new balance after the fee is charged: " + usMoney.format(acct2.chargeFee())); //change the name on Joe's account to Joseph acct2.changeName("Joseph"); //print summary for both accounts System.out.println(acct1); System.out.println(acct2); //close and display Sally's account acct1.close(); System.out.println(acct1); //consolidate account test (doesn't work as acct1 Account newAcct = Account.consolidate(acct1, acct2); System.out.println(acct1); } }
mit
hammadirshad/dvare
src/main/java/org/dvare/annotations/Type.java
1450
/*The MIT License (MIT) Copyright (c) 2016 Muhammad Hammad 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 Sogiftware. 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.dvare.annotations; import org.dvare.expression.datatype.DataType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Type { DataType dataType(); }
mit
Arrekusu/datamover
components/datamover-core/src/main/java/com/arekusu/datamover/model/jaxb/ModelType.java
2303
package com.arekusu.datamover.model.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.arekusu.com}DefinitionType"/> * &lt;/sequence> * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "definitionType" }) @XmlRootElement(name = "ModelType", namespace = "http://www.arekusu.com") public class ModelType { @XmlElement(name = "DefinitionType", namespace = "http://www.arekusu.com", required = true) protected DefinitionType definitionType; @XmlAttribute(name = "version") protected String version; /** * Gets the value of the definitionType property. * * @return * possible object is * {@link DefinitionType } * */ public DefinitionType getDefinitionType() { return definitionType; } /** * Sets the value of the definitionType property. * * @param value * allowed object is * {@link DefinitionType } * */ public void setDefinitionType(DefinitionType value) { this.definitionType = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } }
mit
lmarinov/Exercise-repo
Java_OOP_2021/src/SOLID/Exercise/Logger/model/appenders/FileAppender.java
670
package SOLID.Exercise.Logger.model.appenders; import SOLID.Exercise.Logger.api.File; import SOLID.Exercise.Logger.api.Layout; import SOLID.Exercise.Logger.model.files.LogFile; public class FileAppender extends BaseAppender { private File file; public FileAppender(Layout layout) { super(layout); this.setFile(new LogFile()); } public void setFile(File file) { this.file = file; } @Override public void append(String message) { this.file.write(message); } @Override public String toString() { return String.format("%s, File size: %d", super.toString(), this.file.getSize()); } }
mit
voostindie/sprox-json
src/test/java/nl/ulso/sprox/json/spotify/AlbumFactory.java
972
package nl.ulso.sprox.json.spotify; import nl.ulso.sprox.Node; import java.time.LocalDate; import java.util.List; /** * Sprox processor for Spotify API album data. This is a very simple processor that ignores most data. * <p> * This implementation creates an Artist object for each and every artist in the response. But only the first one on * album level is kept in the end. * </p> */ public class AlbumFactory { @Node("album") public Album createAlbum(@Node("name") String name, @Node("release_date") LocalDate releaseDate, Artist artist, List<Track> tracks) { return new Album(name, releaseDate, artist, tracks); } @Node("artists") public Artist createArtist(@Node("name") String name) { return new Artist(name); } @Node("items") public Track createTrack(@Node("track_number") Integer trackNumber, @Node("name") String name) { return new Track(trackNumber, name); } }
mit
DankBots/GN4R
src/main/java/com/gmail/hexragon/gn4rBot/command/ai/PrivateCleverbotCommand.java
1619
package com.gmail.hexragon.gn4rBot.command.ai; import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor; import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command; import com.gmail.hexragon.gn4rBot.util.GnarMessage; import com.google.code.chatterbotapi.ChatterBot; import com.google.code.chatterbotapi.ChatterBotFactory; import com.google.code.chatterbotapi.ChatterBotSession; import com.google.code.chatterbotapi.ChatterBotType; import net.dv8tion.jda.entities.User; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.WeakHashMap; @Command( aliases = {"cbot", "cleverbot"}, usage = "(query)", description = "Talk to Clever-Bot." ) public class PrivateCleverbotCommand extends CommandExecutor { private ChatterBotFactory factory = new ChatterBotFactory(); private ChatterBotSession session = null; private Map<User, ChatterBotSession> sessionMap = new WeakHashMap<>(); @Override public void execute(GnarMessage message, String[] args) { try { if (!sessionMap.containsKey(message.getAuthor())) { ChatterBot bot = factory.create(ChatterBotType.CLEVERBOT); sessionMap.put(message.getAuthor(), bot.createSession()); } message.replyRaw(sessionMap.get(message.getAuthor()).think(StringUtils.join(args, " "))); } catch (Exception e) { message.reply("Chat Bot encountered an exception. Restarting. `:[`"); sessionMap.remove(message.getAuthor()); } } }
mit
sanaehirotaka/logbook
main/logbook/data/ScriptLoader.java
3288
package logbook.data; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import logbook.config.AppConfig; import org.apache.commons.io.FilenameUtils; /** * スクリプトを読み込みEventListenerの実装を取得する * */ public final class ScriptLoader implements Closeable { /** ClassLoader */ private final URLClassLoader classLoader; /** ScriptEngineManager */ private final ScriptEngineManager manager; /** * コンストラクター */ public ScriptLoader() { this.classLoader = URLClassLoader.newInstance(this.getLibraries()); this.manager = new ScriptEngineManager(this.classLoader); } /** * スクリプトを読み込みEventListenerの実装を取得する<br> * * @param script スクリプト * @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null * @throws IOException * @throws ScriptException */ @CheckForNull public EventListener getEventListener(Path script) throws IOException, ScriptException { try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) { // 拡張子からScriptEngineを取得 String ext = FilenameUtils.getExtension(script.toString()); ScriptEngine engine = this.manager.getEngineByExtension(ext); if (engine != null) { // eval engine.eval(reader); // 実装を取得 EventListener listener = ((Invocable) engine).getInterface(EventListener.class); if (listener != null) { return new ScriptEventAdapter(listener, script); } } return null; } } /** * ScriptEngineManagerで使用する追加のライブラリ * * @return ライブラリ */ public URL[] getLibraries() { String[] engines = AppConfig.get().getScriptEngines(); List<URL> libs = new ArrayList<>(); for (String engine : engines) { Path path = Paths.get(engine); if (Files.isReadable(path)) { try { libs.add(path.toUri().toURL()); } catch (MalformedURLException e) { // ここに入るパターンはないはず e.printStackTrace(); } } } return libs.toArray(new URL[libs.size()]); } @Override public void close() throws IOException { this.classLoader.close(); } }
mit
Microsoft/vso-intellij
plugin/src/com/microsoft/alm/plugin/idea/tfvc/ui/ServerPathCellEditor.java
4047
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. /* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.alm.plugin.idea.tfvc.ui; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.util.ui.AbstractTableCellEditor; import com.intellij.util.ui.CellEditorComponentWithBrowseButton; import com.microsoft.alm.plugin.context.ServerContext; import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle; import com.microsoft.alm.plugin.idea.common.utils.VcsHelper; import com.microsoft.alm.plugin.idea.tfvc.ui.servertree.ServerBrowserDialog; import org.apache.commons.lang.StringUtils; import javax.swing.JTable; import javax.swing.JTextField; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ServerPathCellEditor extends AbstractTableCellEditor { private final String title; private final Project project; private final ServerContext serverContext; private CellEditorComponentWithBrowseButton<JTextField> component; public ServerPathCellEditor(final String title, final Project project, final ServerContext serverContext) { this.title = title; this.project = project; this.serverContext = serverContext; } public Object getCellEditorValue() { return component.getChildComponent().getText(); } public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) { final ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { createBrowserDialog(); } }; component = new CellEditorComponentWithBrowseButton<JTextField>(new TextFieldWithBrowseButton(listener), this); component.getChildComponent().setText((String) value); return component; } /** * Creates the browser dialog for file selection */ @VisibleForTesting protected void createBrowserDialog() { final String serverPath = getServerPath(); if (StringUtils.isNotEmpty(serverPath)) { final ServerBrowserDialog dialog = new ServerBrowserDialog(title, project, serverContext, serverPath, true, false); if (dialog.showAndGet()) { component.getChildComponent().setText(dialog.getSelectedPath()); } } else { Messages.showErrorDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG), TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE)); } } /** * Get a server path to pass into the dialog * * @return */ @VisibleForTesting protected String getServerPath() { String serverPath = (String) getCellEditorValue(); // if there is no entry in the cell to find the root server path with then find it from the server context if (StringUtils.isEmpty(serverPath) && serverContext != null && serverContext.getTeamProjectReference() != null) { serverPath = VcsHelper.TFVC_ROOT.concat(serverContext.getTeamProjectReference().getName()); } return serverPath; } }
mit
PeerWasp/PeerWasp
peerbox/src/main/java/org/peerbox/presenter/MainController.java
467
package org.peerbox.presenter; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.layout.Pane; public class MainController implements INavigatable { @FXML private Pane mainPane; /* * (non-Javadoc) * * @see org.peerbox.presenter.INavigatable#setContent(javafx.scene.Node) */ @Override public void setContent(Node content) { mainPane.getChildren().clear(); mainPane.getChildren().add(content); mainPane.requestLayout(); } }
mit
arapaka/algorithms-datastructures
algorithms/src/main/java/tutorialHorizon/arrays/InsertionSort.java
813
package tutorialHorizon.arrays; /** * Created by archithrapaka on 7/4/17. */ public class InsertionSort { public static void insertionSort(int[] items, int n) { int i, j; for (i = 1; i < n; i++) { j = i; while (j > 0 && (items[j] < items[j - 1])) { swap(items, j, j - 1); j--; } } } public static void swap(int[] items, int i, int j) { int temp = items[i]; items[i] = items[j]; items[j] = temp; } public static void display(int[] a) { for (int i : a) { System.out.print(i + " "); } } public static void main(String[] args) { int[] a = {100, 4, 30, 15, 98, 3}; insertionSort(a, a.length); display(a); } }
mit
SpongePowered/SpongeCommon
src/main/java/org/spongepowered/common/mixin/api/mcp/tileentity/TileEntityDropperMixin_API.java
1688
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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.spongepowered.common.mixin.api.mcp.tileentity; import net.minecraft.tileentity.TileEntityDropper; import org.spongepowered.api.block.tileentity.carrier.Dropper; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.asm.mixin.Mixin; @NonnullByDefault @Mixin(TileEntityDropper.class) public abstract class TileEntityDropperMixin_API extends TileEntityDispenserMixin_API implements Dropper { }
mit
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/business/contract/presenters/EditDinnerPresenter.java
261
package biz.golek.whattodofordinner.business.contract.presenters; import biz.golek.whattodofordinner.business.contract.entities.Dinner; /** * Created by Bartosz Gołek on 2016-02-10. */ public interface EditDinnerPresenter { void Show(Dinner dinner); }
mit
CMPUT301F17T11/CupOfJava
app/src/main/java/com/cmput301f17t11/cupofjava/Controllers/SaveFileController.java
8104
/* SaveFileController * * Version 1.0 * * November 13, 2017 * * Copyright (c) 2017 Cup Of Java. All rights reserved. */ package com.cmput301f17t11.cupofjava.Controllers; import android.content.Context; import com.cmput301f17t11.cupofjava.Models.Habit; import com.cmput301f17t11.cupofjava.Models.HabitEvent; import com.cmput301f17t11.cupofjava.Models.HabitList; import com.cmput301f17t11.cupofjava.Models.User; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.ArrayList; /** * Implements the file to save data to. * * @version 1.0 */ public class SaveFileController { private ArrayList<User> allUsers; //private String username; private String saveFile = "test_save_file4.sav"; public SaveFileController(){ this.allUsers = new ArrayList<User>(); } /** * Loads data from file. * * @param context instance of Context */ private void loadFromFile(Context context){ try{ FileInputStream ifStream = context.openFileInput(saveFile); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ifStream)); Gson gson = new Gson(); Type userArrayListType = new TypeToken<ArrayList<User>>(){}.getType(); this.allUsers = gson.fromJson(bufferedReader, userArrayListType); ifStream.close(); } //create a new array list if a file does not already exist catch (FileNotFoundException e){ this.allUsers = new ArrayList<User>(); saveToFile(context); } catch (IOException e){ throw new RuntimeException(); } } /** * Saves current ArrayList contents in file. * * @param context instance of Context */ private void saveToFile(Context context){ try{ FileOutputStream ofStream = context.openFileOutput(saveFile, Context.MODE_PRIVATE); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(ofStream)); Gson gson = new Gson(); gson.toJson(this.allUsers, bufferedWriter); bufferedWriter.flush(); ofStream.close(); } catch (FileNotFoundException e){ //shouldn't really happen, since a file not found would create a new file. throw new RuntimeException("Laws of nature defied!"); } catch (IOException e){ throw new RuntimeException(); } } /** * Adds new user and saves to file. * * @param context instance of Context * @param user instance of User * @see User */ public void addNewUser(Context context, User user){ loadFromFile(context); this.allUsers.add(user); saveToFile(context); } /** * Deletes all user from file. * * @param context instance of Context */ public void deleteAllUsers(Context context){ this.allUsers = new ArrayList<>(); saveToFile(context); } /** * Gets user index. * * @param context instance of Context * @param username string username * @return integer user index if username matches, -1 otherwise */ public int getUserIndex(Context context, String username){ loadFromFile(context); for (int i = 0; i < this.allUsers.size(); i++){ if (this.allUsers.get(i).getUsername().equals(username)){ return i; } } return -1; } /** * Gets HabitList instance. * * @param context instance of Context * @param userIndex integer user index * @return HabitList * @see HabitList */ public HabitList getHabitList(Context context, int userIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitList(); } /** * Gets ArrayList of type Habit. * * @param context instance of Context * @param userIndex integer user index * @return list */ public ArrayList<Habit> getHabitListAsArray(Context context, int userIndex){ loadFromFile(context); ArrayList<Habit> list = this.allUsers.get(userIndex).getHabitListAsArray(); return list; } /** * Adds a habit to a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habit instance of Habit * @see Habit */ public void addHabit(Context context, int userIndex, Habit habit){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().addHabit(habit); saveToFile(context); } /** * Gets habit from a particular user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @return instance of Habit * @see Habit */ public Habit getHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); return this.allUsers.get(userIndex).getHabitListAsArray().get(habitIndex); } /** * Deletes habit from a certain user's habit list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit */ public void deleteHabit(Context context, int userIndex, int habitIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitListAsArray().remove(habitIndex); saveToFile(context); } /** * Adds habit event to a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEvent instance of HabitEvent * @see HabitEvent */ public void addHabitEvent(Context context, int userIndex, int habitIndex, HabitEvent habitEvent){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex).addHabitEvent(habitEvent); saveToFile(context); } /** * Removes a habit event from a particular user's habit event list. * * @param context instance of Context * @param userIndex integer user index * @param habitIndex integer index of habit * @param habitEventIndex integer index of habit event */ public void removeHabitEvent(Context context, int userIndex, int habitIndex, int habitEventIndex){ loadFromFile(context); this.allUsers.get(userIndex).getHabitList().getHabit(habitIndex) .getHabitEventHistory().getHabitEvents().remove(habitEventIndex); saveToFile(context); } /** * For use in timeline view. * * @param context instance of Context * @param userIndex integer user index * @return ArrayList of HabitEvent type * @see HabitEvent */ public ArrayList<HabitEvent> getAllHabitEvents(Context context, int userIndex){ loadFromFile(context); ArrayList<HabitEvent> habitEvents = new ArrayList<>(); User user = this.allUsers.get(userIndex); ArrayList<Habit> habitList = user.getHabitListAsArray(); Habit currentHabit; ArrayList<HabitEvent> currentHabitEvents; for (int i = 0; i < habitList.size(); i++){ currentHabit = habitList.get(i); currentHabitEvents = currentHabit.getHabitEventHistory().getHabitEvents(); for (int j = 0; j < currentHabitEvents.size() ; j++){ habitEvents.add(user.getHabitListAsArray().get(i) .getHabitEventHistory().getHabitEvents().get(j)); } } return habitEvents; } }
mit
JaeW/dodroid
app/src/main/java/doit/study/droid/fragments/DislikeDialogFragment.java
3105
package doit.study.droid.fragments; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import doit.study.droid.R; public class DislikeDialogFragment extends DialogFragment { public static final String EXTRA_CAUSE = "doit.study.droid.extra_cause"; private static final String QUESTION_TEXT_KEY = "doit.study.droid.question_text_key"; private Activity mHostActivity; private View mView; private int[] mCauseIds = {R.id.question_incorrect, R.id.answer_incorrect, R.id.documentation_irrelevant}; public static DislikeDialogFragment newInstance(String questionText) { DislikeDialogFragment dislikeDialog = new DislikeDialogFragment(); Bundle arg = new Bundle(); arg.putString(QUESTION_TEXT_KEY, questionText); dislikeDialog.setArguments(arg); return dislikeDialog; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mHostActivity = getActivity(); LayoutInflater inflater = mHostActivity.getLayoutInflater(); mView = inflater.inflate(R.layout.fragment_dialog_dislike, null); AlertDialog.Builder builder = new AlertDialog.Builder(mHostActivity); builder.setMessage(getString(R.string.report_because)) .setView(mView) .setPositiveButton(mHostActivity.getString(R.string.report), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Fragment fr = getTargetFragment(); if (fr != null) { Intent intent = new Intent(); intent.putExtra(EXTRA_CAUSE, formReport()); fr.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog object and return it return builder.create(); } private String formReport() { EditText editText = (EditText) mView.findViewById(R.id.comment); StringBuilder result = new StringBuilder(" Cause:"); for (int id : mCauseIds) { CheckBox checkBox = (CheckBox) mView.findViewById(id); if (checkBox.isChecked()) result.append(checkBox.getText()) .append(","); } result.append(" Comment:"); result.append(editText.getText()); return result.toString(); } }
mit
jeanregisser/tcSlackBuildNotifier
tcslackbuildnotifier-core/src/main/java/slacknotifications/teamcity/payload/SlackNotificationPayloadManager.java
7122
package slacknotifications.teamcity.payload; import jetbrains.buildServer.messages.Status; import jetbrains.buildServer.responsibility.ResponsibilityEntry; import jetbrains.buildServer.responsibility.TestNameResponsibilityEntry; import jetbrains.buildServer.serverSide.*; import jetbrains.buildServer.tests.TestName; import slacknotifications.teamcity.BuildStateEnum; import slacknotifications.teamcity.Loggers; import slacknotifications.teamcity.payload.content.SlackNotificationPayloadContent; import java.util.Collection; public class SlackNotificationPayloadManager { SBuildServer server; public SlackNotificationPayloadManager(SBuildServer server){ this.server = server; Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting"); } public SlackNotificationPayloadContent beforeBuildFinish(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BEFORE_BUILD_FINISHED); return content; } public SlackNotificationPayloadContent buildFinished(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_FINISHED); return content; } public SlackNotificationPayloadContent buildInterrupted(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_INTERRUPTED); return content; } public SlackNotificationPayloadContent buildStarted(SRunningBuild runningBuild, SFinishedBuild previousBuild) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, runningBuild, previousBuild, BuildStateEnum.BUILD_STARTED); return content; } /** Used by versions of TeamCity less than 7.0 */ public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType, ResponsibilityInfo responsibilityInfoOld, ResponsibilityInfo responsibilityInfoNew, boolean isUserAction) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED); String oldUser = "Nobody"; String newUser = "Nobody"; try { oldUser = responsibilityInfoOld.getResponsibleUser().getDescriptiveName(); } catch (Exception e) {} try { newUser = responsibilityInfoNew.getResponsibleUser().getDescriptiveName(); } catch (Exception e) {} content.setText(buildType.getFullName().toString() + " changed responsibility from " + oldUser + " to " + newUser + " with comment '" + responsibilityInfoNew.getComment().toString().trim() + "'" ); return content; } /** Used by versions of TeamCity 7.0 and above */ public SlackNotificationPayloadContent responsibleChanged(SBuildType buildType, ResponsibilityEntry responsibilityEntryOld, ResponsibilityEntry responsibilityEntryNew) { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(server, buildType, BuildStateEnum.RESPONSIBILITY_CHANGED); String oldUser = "Nobody"; String newUser = "Nobody"; if (responsibilityEntryOld.getState() != ResponsibilityEntry.State.NONE) { oldUser = responsibilityEntryOld.getResponsibleUser().getDescriptiveName(); } if (responsibilityEntryNew.getState() != ResponsibilityEntry.State.NONE) { newUser = responsibilityEntryNew.getResponsibleUser().getDescriptiveName(); } content.setText(buildType.getFullName().toString().toString().trim() + " changed responsibility from " + oldUser + " to " + newUser + " with comment '" + responsibilityEntryNew.getComment().toString().trim() + "'" ); return content; } public SlackNotificationPayloadContent responsibleChanged(SProject project, TestNameResponsibilityEntry oldTestNameResponsibilityEntry, TestNameResponsibilityEntry newTestNameResponsibilityEntry, boolean isUserAction) { // TODO Auto-generated method stub return null; } public SlackNotificationPayloadContent responsibleChanged(SProject project, Collection<TestName> testNames, ResponsibilityEntry entry, boolean isUserAction) { // TODO Auto-generated method stub return null; } /* HashMap<String, SlackNotificationPayload> formats = new HashMap<String,SlackNotificationPayload>(); Comparator<SlackNotificationPayload> rankComparator = new SlackNotificationPayloadRankingComparator(); List<SlackNotificationPayload> orderedFormatCollection = new ArrayList<SlackNotificationPayload>(); SBuildServer server; public SlackNotificationPayloadManager(SBuildServer server){ this.server = server; Loggers.SERVER.info("SlackNotificationPayloadManager :: Starting"); } public void registerPayloadFormat(SlackNotificationPayload payloadFormat){ Loggers.SERVER.info(this.getClass().getSimpleName() + " :: Registering payload " + payloadFormat.getFormatShortName() + " with rank of " + payloadFormat.getRank()); formats.put(payloadFormat.getFormatShortName(),payloadFormat); this.orderedFormatCollection.add(payloadFormat); Collections.sort(this.orderedFormatCollection, rankComparator); Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payloads list is " + this.orderedFormatCollection.size() + " items long. Payloads are ranked in the following order.."); for (SlackNotificationPayload pl : this.orderedFormatCollection){ Loggers.SERVER.debug(this.getClass().getSimpleName() + " :: Payload Name: " + pl.getFormatShortName() + " Rank: " + pl.getRank()); } } public SlackNotificationPayload getFormat(String formatShortname){ if (formats.containsKey(formatShortname)){ return formats.get(formatShortname); } return null; } public Boolean isRegisteredFormat(String format){ return formats.containsKey(format); } public Set<String> getRegisteredFormats(){ return formats.keySet(); } public Collection<SlackNotificationPayload> getRegisteredFormatsAsCollection(){ return orderedFormatCollection; } public SBuildServer getServer() { return server; } */ }
mit
allanfish/facetime
facetime-spring/src/main/java/com/facetime/spring/support/Page.java
3885
package com.facetime.spring.support; import java.util.ArrayList; import java.util.List; import com.facetime.core.conf.ConfigUtils; import com.facetime.core.utils.StringUtils; /** * 分页类 * * @author yufei * @param <T> */ public class Page<T> { private static int BEGIN_PAGE_SIZE = 20; /** 下拉分页列表的递增数量级 */ private static int ADD_PAGE_SIZE_RATIO = 10; public static int DEFAULT_PAGE_SIZE = 10; private static int MAX_PAGE_SIZE = 200; private QueryInfo<T> queryInfo = null; private List<T> queryResult = null; public Page() { this(new QueryInfo<T>()); } public Page(QueryInfo<T> queryInfo) { this.queryInfo = queryInfo; this.queryResult = new ArrayList<T>(15); } /** * @return 下拉分页列表的递增数量级 */ public final static int getAddPageSize() { String addPageSizeRatio = ConfigUtils.getProperty("add_page_size_ratio"); if (StringUtils.isValid(addPageSizeRatio)) ADD_PAGE_SIZE_RATIO = Integer.parseInt(addPageSizeRatio); return ADD_PAGE_SIZE_RATIO; } /** * @return 默认分页下拉列表的开始值 */ public final static int getBeginPageSize() { String beginPageSize = ConfigUtils.getProperty("begin_page_size"); if (StringUtils.isValid(beginPageSize)) BEGIN_PAGE_SIZE = Integer.parseInt(beginPageSize); return BEGIN_PAGE_SIZE; } /** * 默认列表记录显示条数 */ public static final int getDefaultPageSize() { String defaultPageSize = ConfigUtils.getProperty("default_page_size"); if (StringUtils.isValid(defaultPageSize)) DEFAULT_PAGE_SIZE = Integer.parseInt(defaultPageSize); return DEFAULT_PAGE_SIZE; } /** * 默认分页列表显示的最大记录条数 */ public static final int getMaxPageSize() { String maxPageSize = ConfigUtils.getProperty("max_page_size"); if (StringUtils.isValid(maxPageSize)) { MAX_PAGE_SIZE = Integer.parseInt(maxPageSize); } return MAX_PAGE_SIZE; } public String getBeanName() { return this.queryInfo.getBeanName(); } public int getCurrentPageNo() { return this.queryInfo.getCurrentPageNo(); } public String getKey() { return this.queryInfo.getKey(); } public Integer getNeedRowNum() { return this.getPageSize() - this.getQueryResult().size(); } public long getNextPage() { return this.queryInfo.getNextPage(); } public int getPageCount() { return this.queryInfo.getPageCount(); } public int getPageSize() { return this.queryInfo.getPageSize(); } public List<T> getParams() { return this.queryInfo.getParams(); } public int getPreviousPage() { return this.queryInfo.getPreviousPage(); } public String[] getProperties() { return this.queryInfo.getProperties(); } public List<T> getQueryResult() { return this.queryResult; } public int getRecordCount() { return this.queryInfo.getRecordCount(); } public String getSql() { return this.queryInfo.getSql(); } public boolean isHasResult() { return this.queryResult != null && this.queryResult.size() > 0; } public void setBeanName(String beanNameValue) { this.queryInfo.setBeanName(beanNameValue); } public void setCurrentPageNo(int currentPageNo) { this.queryInfo.setCurrentPageNo(currentPageNo); } public void setKey(String keyValue) { this.queryInfo.setKey(keyValue); } public void setPageCount(int pageCount) { this.queryInfo.setPageCount(pageCount); } public void setPageSize(int pageSize) { this.queryInfo.setPageSize(pageSize); } public void setParams(List<T> paramsValue) { this.queryInfo.setParams(paramsValue); } public void setProperties(String[] propertiesValue) { this.queryInfo.setProperties(propertiesValue); } public void setQueryResult(List<T> list) { this.queryResult = list; } public void setRecordCount(int count) { this.queryInfo.setRecordCount(count); } public void setSql(String sql) { this.queryInfo.setSql(sql); } }
mit
Squama/Master
AdminEAP-framework/src/main/java/com/cnpc/framework/base/service/impl/DictServiceImpl.java
4363
package com.cnpc.framework.base.service.impl; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.cnpc.framework.base.entity.Dict; import com.cnpc.framework.base.pojo.TreeNode; import com.cnpc.framework.base.service.DictService; import com.cnpc.framework.constant.RedisConstant; import com.cnpc.framework.utils.StrUtil; import com.cnpc.framework.utils.TreeUtil; @Service("dictService") public class DictServiceImpl extends BaseServiceImpl implements DictService { @Override public List<TreeNode> getTreeData() { // 获取数据 String key = RedisConstant.DICT_PRE+"tree"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict order by levelCode asc"; List<Dict> dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } public List<Dict> getDictsByCode(String code) { String key = RedisConstant.DICT_PRE+ code; List dicts = redisDao.get(key, List.class); if (dicts == null) { String hql = "from Dict where code='" + code + "'"; Dict dict = this.get(hql); dicts = this.find("from Dict where parentId='" + dict.getId() + "' order by levelCode"); redisDao.add(key, dicts); return dicts; } else { return dicts; } } @Override public List<TreeNode> getTreeDataByCode(String code) { // 获取数据 String key = RedisConstant.DICT_PRE + code + "s"; List<TreeNode> tnlist = null; String tnStr = redisDao.get(key); if(!StrUtil.isEmpty(key)) { tnlist = JSON.parseArray(tnStr,TreeNode.class); } if (tnlist != null) { return tnlist; } else { String hql = "from Dict where code='" + code + "' order by levelCode asc"; List<Dict> dicts = this.find(hql); hql = "from Dict where code='" + code + "' or parent_id = '" +dicts.get(0).getId()+ "' order by levelCode asc"; dicts = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : dicts) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 tnlist = TreeUtil.getNodeList(nodelist); redisDao.save(key, tnlist); return tnlist; } } @Override public List<TreeNode> getMeasureTreeData() { // 获取数据 String hql = "from Dict WHERE (levelCode LIKE '000026%' OR levelCode LIKE '000027%') order by levelCode asc"; List<Dict> funcs = this.find(hql); Map<String, TreeNode> nodelist = new LinkedHashMap<String, TreeNode>(); for (Dict dict : funcs) { TreeNode node = new TreeNode(); node.setText(dict.getName()); node.setId(dict.getId()); node.setParentId(dict.getParentId()); node.setLevelCode(dict.getLevelCode()); nodelist.put(node.getId(), node); } // 构造树形结构 return TreeUtil.getNodeList(nodelist); } }
mit
chadrosenquist/running-route
src/main/java/com/kromracing/runningroute/client/Utils.java
1100
package com.kromracing.runningroute.client; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Widget; final public class Utils { private Utils() { } /** * Sets the HTML id for a widget. * @param widget The widget to have the id set, ex: TextBox * @param id ID in HTML, ex: textbox-location */ static void setId(final Widget widget, final String id) { if (widget instanceof CheckBox) { final Element checkBoxElement = widget.getElement(); // The first element is the actual box to check. That is the one we care about. final Element inputElement = DOM.getChild(checkBoxElement, 0); inputElement.setAttribute("id", id); //DOM.setElementAttribute(inputElement, "id", id); deprecated! } else { widget.getElement().setAttribute("id", id); //DOM.setElementAttribute(widget.getElement(), "id", id); deprecated! } } }
mit
jenkinsci/gatekeeper-plugin
src/test/java/org/paylogic/jenkins/advancedscm/MercurialRule.java
5618
/** * This file was copied from https://github.com/jenkinsci/mercurial-plugin/raw/master/src/test/java/hudson/plugins/mercurial/MercurialRule.java * so we as well have a MercurialRule to create test repos with. * The file is licensed under the MIT License, which can by found at: http://www.opensource.org/licenses/mit-license.php * More information about this file and it's authors can be found at: https://github.com/jenkinsci/mercurial-plugin/ */ package org.paylogic.jenkins.advancedscm; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.Action; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import hudson.plugins.mercurial.HgExe; import hudson.plugins.mercurial.MercurialTagAction; import hudson.scm.PollingResult; import hudson.util.ArgumentListBuilder; import hudson.util.StreamTaskListener; import org.junit.Assume; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.ExternalResource; import org.jvnet.hudson.test.JenkinsRule; import org.paylogic.jenkins.ABuildCause; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import static java.util.Collections.sort; import static org.junit.Assert.*; public final class MercurialRule extends ExternalResource { private TaskListener listener; private final JenkinsRule j; public MercurialRule(JenkinsRule j) { this.j = j; } @Override protected void before() throws Exception { listener = new StreamTaskListener(System.out, Charset.defaultCharset()); try { if (new ProcessBuilder("hg", "--version").start().waitFor() != 0) { throw new AssumptionViolatedException("hg --version signaled an error"); } } catch(IOException ioe) { String message = ioe.getMessage(); if(message.startsWith("Cannot run program \"hg\"") && message.endsWith("No such file or directory")) { throw new AssumptionViolatedException("hg is not available; please check that your PATH environment variable is properly configured"); } Assume.assumeNoException(ioe); // failed to check availability of hg } } private Launcher launcher() { return j.jenkins.createLauncher(listener); } private HgExe hgExe() throws Exception { return new HgExe(null, null, launcher(), j.jenkins, listener, new EnvVars()); } public void hg(String... args) throws Exception { HgExe hg = hgExe(); assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).join()); } public void hg(File repo, String... args) throws Exception { HgExe hg = hgExe(); assertEquals(0, hg.launch(nobody(hg.seed(false)).add(args)).pwd(repo).join()); } private static ArgumentListBuilder nobody(ArgumentListBuilder args) { return args.add("--config").add("ui.username=nobody@nowhere.net"); } public void touchAndCommit(File repo, String... names) throws Exception { for (String name : names) { FilePath toTouch = new FilePath(repo).child(name); if (!toTouch.exists()) { toTouch.getParent().mkdirs(); toTouch.touch(0); hg(repo, "add", name); } else { toTouch.write(toTouch.readToString() + "extra line\n", "UTF-8"); } } hg(repo, "commit", "--message", "added " + Arrays.toString(names)); } public String buildAndCheck(FreeStyleProject p, String name, Action... actions) throws Exception { FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0, new ABuildCause(), actions).get()); // Somehow this needs a cause or it will fail if (!b.getWorkspace().child(name).exists()) { Set<String> children = new TreeSet<String>(); for (FilePath child : b.getWorkspace().list()) { children.add(child.getName()); } fail("Could not find " + name + " among " + children); } assertNotNull(b.getAction(MercurialTagAction.class)); @SuppressWarnings("deprecation") String log = b.getLog(); return log; } public PollingResult pollSCMChanges(FreeStyleProject p) { return p.poll(new StreamTaskListener(System.out, Charset .defaultCharset())); } public String getLastChangesetId(File repo) throws Exception { return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-l1", "--template", "{node}")); } public String[] getBranches(File repo) throws Exception { String rawBranches = hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("branches")); ArrayList<String> list = new ArrayList<String>(); for (String line: rawBranches.split("\n")) { // line should contain: <branchName> <revision>:<hash> (yes, with lots of whitespace) String[] seperatedByWhitespace = line.split("\\s+"); String branchName = seperatedByWhitespace[0]; list.add(branchName); } sort(list); return list.toArray(new String[list.size()]); } public String searchLog(File repo, String query) throws Exception { return hgExe().popen(new FilePath(repo), listener, false, new ArgumentListBuilder("log", "-k", query)); } }
mit
ChinaKim/AdvanceAdapter
app/src/main/java/zhou/adapter/NormalAdapter.java
1412
package zhou.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by zzhoujay on 2015/7/22 0022. */ public class NormalAdapter extends RecyclerView.Adapter<NormalAdapter.Holder> { private List<String> msg; public NormalAdapter(List<String> msg) { this.msg = msg; } @Override public Holder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_normal, null); Holder holder = new Holder(view); return holder; } @Override public void onBindViewHolder(Holder holder, int position) { String m = msg.get(position); holder.icon.setImageResource(R.mipmap.ic_launcher); holder.text.setText(m); } @Override public int getItemCount() { return msg == null ? 0 : msg.size(); } public static class Holder extends RecyclerView.ViewHolder { public TextView text; public ImageView icon; public Holder(View itemView) { super(itemView); text = (TextView) itemView.findViewById(R.id.item_text); icon = (ImageView) itemView.findViewById(R.id.item_icon); } } }
mit
Daskie/Crazy8-CPE-103
src/UserInterface/Animation/SizeAnimation.java
731
package UserInterface.Animation; /** * Makes shit get big, makes shit get small. */ public class SizeAnimation extends Animation { protected int iW, iH, fW, fH, cW, cH; public SizeAnimation(long period, int paceType, boolean loop, int iW, int iH, int fW, int fH) { super(period, paceType, loop); this.iW = iW; this.iH = iH; this.fW = fW; this.fH = fH; this.cW = iW; this.cH = iH; } @Override protected void updateAnimation(double p) { cW = (int)Math.round((fW - iW)*p) + iW; cH = (int)Math.round((fH - iH)*p) + iH; } public int getWidth() { return cW; } public int getHeight() { return cH; } }
mit
mauriciotogneri/apply
src/main/java/com/mauriciotogneri/apply/compiler/syntactic/nodes/arithmetic/ArithmeticModuleNode.java
603
package com.mauriciotogneri.apply.compiler.syntactic.nodes.arithmetic; import com.mauriciotogneri.apply.compiler.lexical.Token; import com.mauriciotogneri.apply.compiler.syntactic.TreeNode; import com.mauriciotogneri.apply.compiler.syntactic.nodes.ExpressionBinaryNode; public class ArithmeticModuleNode extends ExpressionBinaryNode { public ArithmeticModuleNode(Token token, TreeNode left, TreeNode right) { super(token, left, right); } @Override public String sourceCode() { return String.format("mod(%s, %s)", left.sourceCode(), right.sourceCode()); } }
mit
pine613/android-hm
android-hm/src/net/pinemz/hm/gui/SettingsActivity.java
6222
package net.pinemz.hm.gui; import net.pinemz.hm.R; import net.pinemz.hm.api.HmApi; import net.pinemz.hm.api.Prefecture; import net.pinemz.hm.api.PrefectureCollection; import net.pinemz.hm.storage.CommonSettings; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.google.common.base.Optional; public class SettingsActivity extends BasicActivity { public static final String TAG = "SettingsActivity"; private RequestQueue requestQueue; private HmApi hmApi; private PrefectureCollection prefectures; private CommonSettings settings; private ListView listViewPrefectures; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_settings); this.requestQueue = Volley.newRequestQueue(this.getApplicationContext()); this.hmApi = new HmApi(this.getApplicationContext(), this.requestQueue); this.listViewPrefectures = (ListView)this.findViewById(R.id.listViewPrefectures); assert this.listViewPrefectures != null; // Ý’èƒNƒ‰ƒX‚ð€”õ this.settings = new CommonSettings(this.getApplicationContext()); } @Override protected void onResume() { Log.d(TAG, "onResume"); super.onResume(); // “s“¹•{Œ§‚ð“ǂݍž‚Þ this.loadPrefectures(); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); this.requestQueue = null; this.hmApi = null; // Ý’èƒNƒ‰ƒX‚ð‰ð•ú this.settings = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.d(TAG, "onOptionsItemSelected"); return super.onOptionsItemSelected(item); } public void okButtonClicked(View view) { Log.d(TAG, "okButtonClicked"); assert view instanceof Button; // Œ»Ý‘I‘ð‚³‚ê‚Ä‚¢‚鍀–Ú‚ðŽæ“¾ int checkedPosition = this.listViewPrefectures.getCheckedItemPosition(); Log.v(TAG, "onButtonClicked>getCheckedItemPosition = " + checkedPosition); if (checkedPosition == ListView.INVALID_POSITION) { return; } // ‘I‘ð‚³‚ê‚Ä‚¢‚é“s“¹•{Œ§–¼‚ðŽæ“¾ String checkedPrefectureName = (String)this.listViewPrefectures.getItemAtPosition(checkedPosition); assert checkedPrefectureName != null; // “s“¹•{Œ§‚̃f[ƒ^‚ðŽæ“¾ Optional<Prefecture> prefecture = this.prefectures.getByName(checkedPrefectureName); // ƒf[ƒ^‚ª³í‚É‘¶Ý‚·‚éê‡ if (prefecture.isPresent()) { Log.i(TAG, "Prefecture.id = " + prefecture.get().getId()); Log.i(TAG, "Prefecture.name = " + prefecture.get().getName()); this.saveSettings(prefecture.get()); } } public void cancelButtonClicked(View view) { Log.d(TAG, "cancelButtonClicked"); assert view instanceof Button; this.cancelSettings(); } private void setPrefectures(PrefectureCollection prefectures) { Log.d(TAG, "setPrefectures"); this.prefectures = prefectures; assert prefectures != null; ArrayAdapter<String> adapter = new ArrayAdapter<>( this.getApplicationContext(), android.R.layout.simple_list_item_single_choice, prefectures.getNames() ); this.listViewPrefectures.setAdapter(adapter); this.listViewPrefectures.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // æ“ª‚ð‰Šúó‘Ô‚Å‘I‘ð if (adapter.getCount() > 0) { int prefectureId = this.settings.loadPrefectureId(); // ƒf[ƒ^‚ª•Û‘¶‚³‚ê‚Ä‚È‚¢ê‡‚́AÅ‰‚Ì“s“¹•{Œ§‚ð‘I‘ð if (prefectureId < 0) { prefectureId = prefectures.getIds()[0]; } // “s“¹•{Œ§ ID ‚̈ꗗ‚ðŽæ“¾ Integer[] ids = prefectures.getIds(); // ˆê’v‚µ‚½ê‡A‘I‘ð for (int i = 0; i < ids.length; ++i) { if (ids[i] == prefectureId) { this.listViewPrefectures.setItemChecked(i, true); break; } } } } /** * Ý’è‚ð•Û‘¶‚·‚é * @param prefecture •Û‘¶‚·‚é“s“¹•{Œ§ */ private void saveSettings(Prefecture prefecture) { Log.d(TAG, "saveSettings"); assert prefecture != null; // ’l‚ð•Û‘¶ this.settings.savePrefectureId(prefecture.getId()); // ƒƒbƒZ[ƒW‚ð•\Ž¦ Toast.makeText( this.getApplicationContext(), R.string.setting_save_toast, Toast.LENGTH_SHORT ).show(); this.finish(); } /** * Ý’è‚Ì•Û‘¶‚ðƒLƒƒƒ“ƒZƒ‹‚·‚é */ private void cancelSettings() { Toast.makeText( this.getApplicationContext(), R.string.setting_cancel_toast, Toast.LENGTH_SHORT ).show(); this.finish(); } private void loadPrefectures() { // ƒ[ƒfƒBƒ“ƒOƒƒbƒZ[ƒW‚ð•\Ž¦ this.showProgressDialog(R.string.loading_msg_prefectures); // ƒf[ƒ^‚ð“ǂݍž‚Þ this.hmApi.getPrefectures(new HmApi.Listener<PrefectureCollection>() { @Override public void onSuccess(HmApi api, PrefectureCollection data) { Log.d(TAG, "HmApi.Listener#onSuccess"); SettingsActivity.this.closeDialog(); SettingsActivity.this.setPrefectures(data); } @Override public void onFailure() { Log.e(TAG, "HmApi.Listener#onFailure"); SettingsActivity.this.showFinishAlertDialog( R.string.network_failed_title, R.string.network_failed_msg_prefectures ); } @Override public void onException(Exception exception) { Log.e(TAG, "HmApi.Listener#onException", exception); SettingsActivity.this.showFinishAlertDialog( R.string.network_error_title, R.string.network_error_msg_prefectures ); } }); } }
mit
jamierocks/Zinc
Example/src/main/java/uk/jamierocks/zinc/example/ExampleCommands.java
2269
/* * This file is part of Zinc, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016, Jamie Mansfield <https://github.com/jamierocks> * * 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 uk.jamierocks.zinc.example; import com.google.common.collect.Lists; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandArgs; import org.spongepowered.api.text.Text; import uk.jamierocks.zinc.Command; import uk.jamierocks.zinc.TabComplete; import java.util.List; public class ExampleCommands { @Command(name = "example") public CommandResult exampleCommand(CommandSource source, CommandArgs args) { source.sendMessage(Text.of("This is the base command.")); return CommandResult.success(); } @Command(parent = "example", name = "sub") public CommandResult exampleSubCommand(CommandSource source, CommandArgs args) { source.sendMessage(Text.of("This is a sub command.")); return CommandResult.success(); } @TabComplete(name = "example") public List<String> tabComplete(CommandSource source, String args) { return Lists.newArrayList(); } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/TermsAndConditionsAcceptanceStatusCollectionPage.java
2194
// Template Source: BaseEntityCollectionPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.TermsAndConditionsAcceptanceStatus; import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionRequestBuilder; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionResponse; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Terms And Conditions Acceptance Status Collection Page. */ public class TermsAndConditionsAcceptanceStatusCollectionPage extends BaseCollectionPage<TermsAndConditionsAcceptanceStatus, TermsAndConditionsAcceptanceStatusCollectionRequestBuilder> { /** * A collection page for TermsAndConditionsAcceptanceStatus * * @param response the serialized TermsAndConditionsAcceptanceStatusCollectionResponse from the service * @param builder the request builder for the next collection page */ public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final TermsAndConditionsAcceptanceStatusCollectionResponse response, @Nonnull final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder builder) { super(response, builder); } /** * Creates the collection page for TermsAndConditionsAcceptanceStatus * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final java.util.List<TermsAndConditionsAcceptanceStatus> pageContents, @Nullable final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
mit
AgeOfWar/Telejam
src/main/java/io/github/ageofwar/telejam/updates/UpdateReader.java
4138
package io.github.ageofwar.telejam.updates; import io.github.ageofwar.telejam.Bot; import io.github.ageofwar.telejam.TelegramException; import io.github.ageofwar.telejam.methods.GetUpdates; import java.io.IOException; import java.util.Collections; import java.util.Objects; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.LongUnaryOperator; /** * Utility class that reads new updates received from a bot. * * @author Michi Palazzo */ public final class UpdateReader implements AutoCloseable { private final Bot bot; private final ConcurrentLinkedQueue<Update> updates; private final LongUnaryOperator backOff; private long lastUpdateId; /** * Constructs an UpdateReader. * * @param bot the bot that receive updates * @param backOff back off to be used when long polling fails */ public UpdateReader(Bot bot, LongUnaryOperator backOff) { this.bot = Objects.requireNonNull(bot); this.backOff = Objects.requireNonNull(backOff); updates = new ConcurrentLinkedQueue<>(); lastUpdateId = -1; } /** * Constructs an UpdateReader. * * @param bot the bot that receive updates */ public UpdateReader(Bot bot) { this(bot, a -> 500L); } /** * Returns the number of updates that can be read from this update reader without blocking by the * next invocation read method for this update reader. The next invocation * might be the same thread or another thread. * If the available updates are more than {@code Integer.MAX_VALUE}, returns * {@code Integer.MAX_VALUE}. * * @return the number of updates that can be read from this update reader * without blocking by the next invocation read method */ public int available() { return updates.size(); } /** * Tells whether this stream is ready to be read. * * @return <code>true</code> if the next read() is guaranteed not to block for input, * <code>false</code> otherwise. Note that returning false does not guarantee that the * next read will block. */ public boolean ready() { return !updates.isEmpty(); } /** * Reads one update from the stream. * * @return the read update * @throws IOException if an I/O Exception occurs * @throws InterruptedException if any thread has interrupted the current * thread while waiting for updates */ public Update read() throws IOException, InterruptedException { if (!ready()) { for (long attempts = 0; getUpdates() == 0; attempts++) { Thread.sleep(backOff.applyAsLong(attempts)); } } return updates.remove(); } /** * Retrieves new updates received from the bot. * * @return number of updates received * @throws IOException if an I/O Exception occurs */ public int getUpdates() throws IOException { try { Update[] newUpdates = getUpdates(lastUpdateId + 1); Collections.addAll(updates, newUpdates); if (newUpdates.length > 0) { lastUpdateId = newUpdates[newUpdates.length - 1].getId(); } return newUpdates.length; } catch (Throwable e) { if (!(e instanceof TelegramException)) { lastUpdateId++; } throw e; } } /** * Discards buffered updates and all received updates. * * @throws IOException if an I/O Exception occurs */ public void discardAll() throws IOException { Update[] newUpdate = getUpdates(-1); if (newUpdate.length == 1) { lastUpdateId = newUpdate[0].getId(); } updates.clear(); } private Update[] getUpdates(long offset) throws IOException { GetUpdates getUpdates = new GetUpdates() .offset(offset) .allowedUpdates(); return bot.execute(getUpdates); } @Override public void close() throws IOException { try { Update nextUpdate = updates.peek(); getUpdates(nextUpdate != null ? nextUpdate.getId() : lastUpdateId + 1); lastUpdateId = -1; updates.clear(); } catch (IOException e) { throw new IOException("Unable to close update reader", e); } } }
mit
quantumlaser/code2016
LeetCode/Answers/Leetcode-java-solution/remove_duplicates_from_sorted_list/RemoveDuplicatesfromSortedList.java
668
package remove_duplicates_from_sorted_list; import common.ListNode; public class RemoveDuplicatesfromSortedList { public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head != null) { ListNode pre = head; ListNode p = pre.next; while (p != null) { if (p.val == pre.val) { pre.next = p.next; } else { pre = p; } p = p.next; } } return head; } } public static class UnitTest { } }
mit
HSAR/Illume
src/main/java/illume/analysis/SimpleImageAnalyser.java
852
package illume.analysis; import java.awt.image.BufferedImage; /* This simple analyser example averages pixel values. */ public class SimpleImageAnalyser<T extends BufferedImage> extends AbstractImageAnalyser<T> { @Override public double analyse(T input) { int sum_r = 0; int sum_g = 0; int sum_b = 0; for (int y = 0; y < input.getHeight(); y++) { for (int x = 0; x < input.getWidth(); x++) { final int clr = input.getRGB(x, y); sum_r += (clr & 0x00ff0000) >> 16; sum_g += (clr & 0x0000ff00) >> 8; sum_b += clr & 0x000000ff; } } double sum_rgb = ((sum_r + sum_b + sum_g) / 3.0d); double avg = sum_rgb / (input.getHeight() * input.getWidth()); // 8-bit RGB return avg / 255; } }
mit
Covoex/Qarvox
src/main/java/com/covoex/qarvox/Main.java
227
package com.covoex.qarvox; import com.covoex.qarvox.Application.BasicFunction; /** * @author Myeongjun Kim */ public class Main { public static void main(String[] args) { BasicFunction.programStart(); } }
mit
borisbrodski/jmockit
main/src/mockit/external/asm4/Type.java
25672
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package mockit.external.asm4; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * A Java field or method type. This class can be used to make it easier to * manipulate type and method descriptors. * * @author Eric Bruneton * @author Chris Nokleberg */ public class Type { /** * The sort of the <tt>void</tt> type. See {@link #getSort getSort}. */ public static final int VOID = 0; /** * The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}. */ public static final int BOOLEAN = 1; /** * The sort of the <tt>char</tt> type. See {@link #getSort getSort}. */ public static final int CHAR = 2; /** * The sort of the <tt>byte</tt> type. See {@link #getSort getSort}. */ public static final int BYTE = 3; /** * The sort of the <tt>short</tt> type. See {@link #getSort getSort}. */ public static final int SHORT = 4; /** * The sort of the <tt>int</tt> type. See {@link #getSort getSort}. */ public static final int INT = 5; /** * The sort of the <tt>float</tt> type. See {@link #getSort getSort}. */ public static final int FLOAT = 6; /** * The sort of the <tt>long</tt> type. See {@link #getSort getSort}. */ public static final int LONG = 7; /** * The sort of the <tt>double</tt> type. See {@link #getSort getSort}. */ public static final int DOUBLE = 8; /** * The sort of array reference types. See {@link #getSort getSort}. */ public static final int ARRAY = 9; /** * The sort of object reference types. See {@link #getSort getSort}. */ public static final int OBJECT = 10; /** * The sort of method types. See {@link #getSort getSort}. */ public static final int METHOD = 11; /** * The <tt>void</tt> type. */ public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24) | (5 << 16) | (0 << 8) | 0, 1); /** * The <tt>boolean</tt> type. */ public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>char</tt> type. */ public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24) | (0 << 16) | (6 << 8) | 1, 1); /** * The <tt>byte</tt> type. */ public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24) | (0 << 16) | (5 << 8) | 1, 1); /** * The <tt>short</tt> type. */ public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24) | (0 << 16) | (7 << 8) | 1, 1); /** * The <tt>int</tt> type. */ public static final Type INT_TYPE = new Type(INT, null, ('I' << 24) | (0 << 16) | (0 << 8) | 1, 1); /** * The <tt>float</tt> type. */ public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24) | (2 << 16) | (2 << 8) | 1, 1); /** * The <tt>long</tt> type. */ public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24) | (1 << 16) | (1 << 8) | 2, 1); /** * The <tt>double</tt> type. */ public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24) | (3 << 16) | (3 << 8) | 2, 1); private static final Type[] NO_ARGS = new Type[0]; // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ /** * The sort of this Java type. */ private final int sort; /** * A buffer containing the internal name of this Java type. This field is * only used for reference types. */ private final char[] buf; /** * The offset of the internal name of this Java type in {@link #buf buf} or, * for primitive types, the size, descriptor and getOpcode offsets for this * type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset * for IALOAD or IASTORE, byte 3 the offset for all other instructions). */ private final int off; /** * The length of the internal name of this Java type. */ private final int len; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a reference type. * * @param sort the sort of the reference type to be constructed. * @param buf a buffer containing the descriptor of the previous type. * @param off the offset of this descriptor in the previous buffer. * @param len the length of this descriptor. */ private Type(int sort, char[] buf, int off, int len) { this.sort = sort; this.buf = buf; this.off = off; this.len = len; } /** * Returns the Java type corresponding to the given type descriptor. * * @param typeDescriptor a field or method type descriptor. * @return the Java type corresponding to the given type descriptor. */ public static Type getType(String typeDescriptor) { return getType(typeDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given internal name. * * @param internalName an internal name. * @return the Java type corresponding to the given internal name. */ public static Type getObjectType(String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); } /** * Returns the Java type corresponding to the given method descriptor. * Equivalent to <code>Type.getType(methodDescriptor)</code>. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the given method descriptor. */ public static Type getMethodType(String methodDescriptor) { return getType(methodDescriptor.toCharArray(), 0); } /** * Returns the Java type corresponding to the given class. * * @param c a class. * @return the Java type corresponding to the given class. */ public static Type getType(Class<?> c) { if (c.isPrimitive()) { if (c == Integer.TYPE) { return INT_TYPE; } else if (c == Void.TYPE) { return VOID_TYPE; } else if (c == Boolean.TYPE) { return BOOLEAN_TYPE; } else if (c == Byte.TYPE) { return BYTE_TYPE; } else if (c == Character.TYPE) { return CHAR_TYPE; } else if (c == Short.TYPE) { return SHORT_TYPE; } else if (c == Double.TYPE) { return DOUBLE_TYPE; } else if (c == Float.TYPE) { return FLOAT_TYPE; } else /* if (c == Long.TYPE) */{ return LONG_TYPE; } } else { return getType(getDescriptor(c)); } } /** * Returns the Java method type corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the Java method type corresponding to the given constructor. */ public static Type getType(Constructor<?> c) { return getType(getConstructorDescriptor(c)); } /** * Returns the Java method type corresponding to the given method. * * @param m a {@link Method Method} object. * @return the Java method type corresponding to the given method. */ public static Type getType(Method m) { return getType(getMethodDescriptor(m)); } /** * Returns the Java types corresponding to the argument types of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java types corresponding to the argument types of the given * method descriptor. */ public static Type[] getArgumentTypes(String methodDescriptor) { if (methodDescriptor.charAt(1) == ')') return NO_ARGS; char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; } /** * Returns the Java type corresponding to the return type of the given * method descriptor. * * @param methodDescriptor a method descriptor. * @return the Java type corresponding to the return type of the given * method descriptor. */ public static Type getReturnType(String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); return getType(buf, methodDescriptor.indexOf(')') + 1); } /** * Computes the size of the arguments and of the return value of a method. * * @param desc the descriptor of a method. * @return the size of the arguments of the method (plus one for the * implicit this argument), argSize, and the size of its return * value, retSize, packed into a single int i = * <tt>(argSize << 2) | retSize</tt> (argSize is therefore equal * to <tt>i >> 2</tt>, and retSize to <tt>i & 0x03</tt>). */ public static int getArgumentsAndReturnSizes(String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } } /** * Returns the Java type corresponding to the given type descriptor. For * method descriptors, buf is supposed to contain nothing more than the * descriptor itself. * * @param buf a buffer containing a type descriptor. * @param off the offset of this descriptor in the previous buffer. * @return the Java type corresponding to the given type descriptor. */ private static Type getType(char[] buf, int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); case 'L': len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); case '(': return new Type(METHOD, buf, 0, buf.length); default: throw new IllegalArgumentException("Invalid type descriptor: " + new String(buf)); } } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns the sort of this Java type. * * @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, * {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT}, * {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG}, * {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY}, * {@link #OBJECT OBJECT} or {@link #METHOD METHOD}. */ public int getSort() { return sort; } /** * Returns the number of dimensions of this array type. This method should * only be used for an array type. * * @return the number of dimensions of this array type. */ public int getDimensions() { int i = 1; while (buf[off + i] == '[') { ++i; } return i; } /** * Returns the type of the elements of this array type. This method should * only be used for an array type. * * @return Returns the type of the elements of this array type. */ public Type getElementType() { return getType(buf, off + getDimensions()); } /** * Returns the binary name of the class corresponding to this type. This * method must not be used on method types. * * @return the binary name of the class corresponding to this type. */ public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); case OBJECT: return new String(buf, off, len).replace('/', '.'); default: return null; } } /** * Returns the internal name of the class corresponding to this object or * array type. The internal name of a class is its fully qualified name (as * returned by Class.getName(), where '.' are replaced by '/'. This method * should only be used for an object or array type. * * @return the internal name of the class corresponding to this object type. */ public String getInternalName() { return new String(buf, off, len); } // ------------------------------------------------------------------------ // Conversion to type descriptors // ------------------------------------------------------------------------ /** * Returns the descriptor corresponding to this Java type. * * @return the descriptor corresponding to this Java type. */ public String getDescriptor() { StringBuffer buf = new StringBuffer(); getDescriptor(buf); return buf.toString(); } /** * Appends the descriptor corresponding to this Java type to the given * string buffer. * * @param buf the string buffer to which the descriptor must be appended. */ private void getDescriptor(StringBuffer buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == OBJECT) { buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } else { // sort == ARRAY || sort == METHOD buf.append(this.buf, off, len); } } // ------------------------------------------------------------------------ // Direct conversion from classes to type descriptors, // without intermediate Type objects // ------------------------------------------------------------------------ /** * Returns the internal name of the given class. The internal name of a * class is its fully qualified name, as returned by Class.getName(), where * '.' are replaced by '/'. * * @param c an object or array class. * @return the internal name of the given class. */ public static String getInternalName(Class<?> c) { return c.getName().replace('.', '/'); } /** * Returns the descriptor corresponding to the given Java type. * * @param c an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getDescriptor(Class<?> c) { StringBuffer buf = new StringBuffer(); getDescriptor(buf, c); return buf.toString(); } /** * Returns the descriptor corresponding to the given constructor. * * @param c a {@link Constructor Constructor} object. * @return the descriptor of the given constructor. */ public static String getConstructorDescriptor(Constructor<?> c) { Class<?>[] parameters = c.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } return buf.append(")V").toString(); } /** * Returns the descriptor corresponding to the given method. * * @param m a {@link Method Method} object. * @return the descriptor of the given method. */ public static String getMethodDescriptor(Method m) { Class<?>[] parameters = m.getParameterTypes(); StringBuffer buf = new StringBuffer(); buf.append('('); for (int i = 0; i < parameters.length; ++i) { getDescriptor(buf, parameters[i]); } buf.append(')'); getDescriptor(buf, m.getReturnType()); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * * @param buf the string buffer to which the descriptor must be appended. * @param c the class whose descriptor must be computed. */ private static void getDescriptor(StringBuffer buf, Class<?> c) { Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } // ------------------------------------------------------------------------ // Corresponding size and opcodes // ------------------------------------------------------------------------ /** * Returns the size of values of this type. This method must not be used for * method types. * * @return the size of values of this type, i.e., 2 for <tt>long</tt> and * <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise. */ public int getSize() { // the size is in byte 0 of 'off' for primitive types (buf == null) return buf == null ? off & 0xFF : 1; } /** * Returns a JVM instruction opcode adapted to this Java type. This method * must not be used for method types. * * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, * ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, * ISHR, IUSHR, IAND, IOR, IXOR and IRETURN. * @return an opcode that is similar to the given opcode, but adapted to * this Java type. For example, if this type is <tt>float</tt> and * <tt>opcode</tt> is IRETURN, this method returns FRETURN. */ public int getOpcode(int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } } // ------------------------------------------------------------------------ // Equals, hashCode and toString // ------------------------------------------------------------------------ /** * Tests if the given object is equal to this type. * * @param o the object to be compared to this type. * @return <tt>true</tt> if the given object is equal to this type. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort >= ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; } /** * Returns a hash code value for this type. * * @return a hash code value for this type. */ @Override public int hashCode() { int hc = 13 * sort; if (sort >= ARRAY) { for (int i = off, end = i + len; i < end; i++) { hc = 17 * (hc + buf[i]); } } return hc; } /** * Returns a string representation of this type. * * @return the descriptor of this type. */ @Override public String toString() { return getDescriptor(); } }
mit
chorsystem/middleware
chorDataModel/src/main/java/org/eclipse/bpel4chor/model/pbd/Query.java
3371
/** * <copyright> * </copyright> * * $Id$ */ package org.eclipse.bpel4chor.model.pbd; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Query</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}</li> * <li>{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}</li> * </ul> * </p> * * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery() * @model * @generated */ public interface Query extends ExtensibleElements { /** * Returns the value of the '<em><b>Query Language</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Query Language</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Query Language</em>' attribute. * @see #setQueryLanguage(String) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_QueryLanguage() * @model * @generated */ String getQueryLanguage(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getQueryLanguage <em>Query Language</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Query Language</em>' attribute. * @see #getQueryLanguage() * @generated */ void setQueryLanguage(String value); /** * Returns the value of the '<em><b>Opaque</b></em>' attribute. * The literals are from the enumeration {@link org.eclipse.bpel4chor.model.pbd.OpaqueBoolean}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Opaque</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Opaque</em>' attribute. * @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean * @see #setOpaque(OpaqueBoolean) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Opaque() * @model * @generated */ OpaqueBoolean getOpaque(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getOpaque <em>Opaque</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Opaque</em>' attribute. * @see org.eclipse.bpel4chor.model.pbd.OpaqueBoolean * @see #getOpaque() * @generated */ void setOpaque(OpaqueBoolean value); /** * Returns the value of the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see #setValue(String) * @see org.eclipse.bpel4chor.model.pbd.PbdPackage#getQuery_Value() * @model * @generated */ String getValue(); /** * Sets the value of the '{@link org.eclipse.bpel4chor.model.pbd.Query#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(String value); } // Query
mit
jkjoschua/poe-ladder-tracker-java
LadderTracker/src/GUIError.java
2387
import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextPane; import java.awt.SystemColor; /** * The GUIError object is used to show an error message if the Path of Exile API is not responding. * * @author Joschn */ public class GUIError{ private JFrame windowError; private JButton buttonRetry; private volatile boolean buttonPressed = false; private ButtonRetryListener buttonRetryListener = new ButtonRetryListener(); private String errorMessage = "Error! Path of Exile's API is not responding! Servers are probably down! Check www.pathofexile.com"; private String version = "2.7"; /** * Constructor for the GUIError object. */ public GUIError(){ initialize(); } /** * Initializes the GUI. */ private void initialize(){ Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // error window windowError = new JFrame(); windowError.setBounds(100, 100, 300, 145); windowError.setLocation(dim.width/2-windowError.getSize().width/2, dim.height/2-windowError.getSize().height/2); windowError.setResizable(false); windowError.setTitle("Ladder Tracker v" + version); windowError.setIconImage(new ImageIcon(getClass().getResource("icon.png")).getImage()); windowError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); windowError.getContentPane().setLayout(null); // button retry buttonRetry = new JButton("Retry"); buttonRetry.setBounds(10, 80, 274, 23); buttonRetry.addActionListener(buttonRetryListener); windowError.getContentPane().add(buttonRetry); // error text JTextPane textError = new JTextPane(); textError.setText(errorMessage); textError.setEditable(false); textError.setBackground(SystemColor.menu); textError.setBounds(10, 21, 274, 39); windowError.getContentPane().add(textError); } /** * Shows the error GUI and waits for the retry button to be pressed. */ public void show(){ windowError.setVisible(true); while(!buttonPressed){} windowError.dispose(); } /** * The definition of the action listener for the retry button. * * @author Joschn */ private class ButtonRetryListener implements ActionListener{ public void actionPerformed(ActionEvent e){ buttonPressed = true; } } }
mit
SummerBlack/MasterServer
app/src/main/java/com/lamost/update/UpdateWebService.java
2678
package com.lamost.update; import java.io.IOException; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import android.util.Log; /** * Created by Jia on 2016/4/6. */ public class UpdateWebService { private static final String TAG = "WebService"; // 命名空间 private final static String SERVICE_NS = "http://ws.smarthome.zfznjj.com/"; // 阿里云 private final static String SERVICE_URL = "http://101.201.211.87:8080/zfzn02/services/smarthome?wsdl=SmarthomeWs.wsdl"; // SOAP Action private static String soapAction = ""; // 调用的方法名称 private static String methodName = ""; private HttpTransportSE ht; private SoapSerializationEnvelope envelope; private SoapObject soapObject; private SoapObject result; public UpdateWebService() { ht = new HttpTransportSE(SERVICE_URL); // ① ht.debug = true; } public String getAppVersionVoice(String appName) { ht = new HttpTransportSE(SERVICE_URL); ht.debug = true; methodName = "getAppVersionVoice"; soapAction = SERVICE_NS + methodName;// 通常为命名空间 + 调用的方法名称 // 使用SOAP1.1协议创建Envelop对象 envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // ② // 实例化SoapObject对象 soapObject = new SoapObject(SERVICE_NS, methodName); // ③ // 将soapObject对象设置为 SoapSerializationEnvelope对象的传出SOAP消息 envelope.bodyOut = soapObject; // ⑤ envelope.dotNet = true; envelope.setOutputSoapObject(soapObject); soapObject.addProperty("appName", appName); try { // System.out.println("测试1"); ht.call(soapAction, envelope); // System.out.println("测试2"); // 根据测试发现,运行这行代码时有时会抛出空指针异常,使用加了一句进行处理 if (envelope != null && envelope.getResponse() != null) { // 获取服务器响应返回的SOAP消息 // System.out.println("测试3"); result = (SoapObject) envelope.bodyIn; // ⑦ // 接下来就是从SoapObject对象中解析响应数据的过程了 // System.out.println("测试4"); String flag = result.getProperty(0).toString(); Log.e(TAG, "*********Webservice masterReadElecticOrder 服务器返回值:" + flag); return flag; } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } finally { resetParam(); } return -1 + ""; } private void resetParam() { envelope = null; soapObject = null; result = null; } }
mit
yunxu-it/GMeizi
app/src/main/java/cn/winxo/gank/module/view/DetailActivity.java
3411
package cn.winxo.gank.module.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import cn.winxo.gank.R; import cn.winxo.gank.adapter.DetailTitleBinder; import cn.winxo.gank.adapter.DetailViewBinder; import cn.winxo.gank.base.BaseMvpActivity; import cn.winxo.gank.data.Injection; import cn.winxo.gank.data.entity.constants.Constant; import cn.winxo.gank.data.entity.remote.GankData; import cn.winxo.gank.module.contract.DetailContract; import cn.winxo.gank.module.presenter.DetailPresenter; import cn.winxo.gank.util.Toasts; import java.text.SimpleDateFormat; import java.util.Locale; import me.drakeet.multitype.Items; import me.drakeet.multitype.MultiTypeAdapter; public class DetailActivity extends BaseMvpActivity<DetailContract.Presenter> implements DetailContract.View { protected Toolbar mToolbar; protected RecyclerView mRecycler; protected SwipeRefreshLayout mSwipeLayout; private long mDate; private MultiTypeAdapter mTypeAdapter; @Override protected int setLayoutResourceID() { return R.layout.activity_detail; } @Override protected void init(Bundle savedInstanceState) { super.init(savedInstanceState); mDate = getIntent().getLongExtra(Constant.ExtraKey.DATE, -1); } @Override protected void initView() { mToolbar = findViewById(R.id.toolbar); mRecycler = findViewById(R.id.recycler); mSwipeLayout = findViewById(R.id.swipe_layout); mToolbar.setNavigationOnClickListener(view -> finish()); mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); mRecycler.setLayoutManager(new LinearLayoutManager(this)); mTypeAdapter = new MultiTypeAdapter(); mTypeAdapter.register(String.class, new DetailTitleBinder()); DetailViewBinder detailViewBinder = new DetailViewBinder(); detailViewBinder.setOnItemTouchListener((v, gankData) -> { Intent intent = new Intent(); intent.setClass(DetailActivity.this, WebActivity.class); intent.putExtra("url", gankData.getUrl()); intent.putExtra("name", gankData.getDesc()); startActivity(intent); }); mTypeAdapter.register(GankData.class, detailViewBinder); mRecycler.setAdapter(mTypeAdapter); mSwipeLayout.setOnRefreshListener(() -> mPresenter.refreshDayGank(mDate)); } @Override protected void initData() { if (mDate != -1) { String dateShow = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(mDate); mToolbar.setTitle(dateShow); mSwipeLayout.setRefreshing(true); mPresenter.loadDayGank(mDate); } else { finish(); } } @Override protected DetailPresenter onLoadPresenter() { return new DetailPresenter(this, Injection.provideGankDataSource(this)); } @Override public void showLoading() { mSwipeLayout.setRefreshing(true); } @Override public void hideLoading() { mSwipeLayout.setRefreshing(false); } @Override public void loadSuccess(Items items) { hideLoading(); mTypeAdapter.setItems(items); mTypeAdapter.notifyDataSetChanged(); } @Override public void loadFail(String message) { Toasts.showShort("数据加载失败,请稍后再试"); Log.e("DetailActivity", "loadFail: " + message); } }
mit
Samuel-Oliveira/Java_NFe
src/main/java/br/com/swconsultoria/nfe/schema/retEnvEpec/TEvento.java
40213
package br.com.swconsultoria.nfe.schema.retEnvEpec; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * Tipo Evento * * <p>Classe Java de TEvento complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="TEvento"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="infEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/> * &lt;element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;/choice> * &lt;element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/> * &lt;element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/> * &lt;element name="tpEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[0-9]{6}"/> * &lt;enumeration value="110140"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="nSeqEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[1-9]|[1][0-9]{0,1}|20"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="verEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="detEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Id" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}ID"> * &lt;pattern value="ID[0-9]{52}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}Signature"/> * &lt;/sequence> * &lt;attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEvento" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = { "infEvento", "signature" }) public class TEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento infEvento; @XmlElement(name = "Signature", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected SignatureType signature; @XmlAttribute(name = "versao", required = true) protected String versao; /** * Obtm o valor da propriedade infEvento. * * @return possible object is * {@link TEvento.InfEvento } */ public TEvento.InfEvento getInfEvento() { return infEvento; } /** * Define o valor da propriedade infEvento. * * @param value allowed object is * {@link TEvento.InfEvento } */ public void setInfEvento(TEvento.InfEvento value) { this.infEvento = value; } /** * Obtm o valor da propriedade signature. * * @return possible object is * {@link SignatureType } */ public SignatureType getSignature() { return signature; } /** * Define o valor da propriedade signature. * * @param value allowed object is * {@link SignatureType } */ public void setSignature(SignatureType value) { this.signature = value; } /** * Obtm o valor da propriedade versao. * * @return possible object is * {@link String } */ public String getVersao() { return versao; } /** * Define o valor da propriedade versao. * * @param value allowed object is * {@link String } */ public void setVersao(String value) { this.versao = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/> * &lt;element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;/choice> * &lt;element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/> * &lt;element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/> * &lt;element name="tpEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[0-9]{6}"/> * &lt;enumeration value="110140"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="nSeqEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="[1-9]|[1][0-9]{0,1}|20"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="verEvento"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="detEvento"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Id" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}ID"> * &lt;pattern value="ID[0-9]{52}"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "cOrgao", "tpAmb", "cnpj", "cpf", "chNFe", "dhEvento", "tpEvento", "nSeqEvento", "verEvento", "detEvento" }) public static class InfEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String cOrgao; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpAmb; @XmlElement(name = "CNPJ", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cnpj; @XmlElement(name = "CPF", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cpf; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String chNFe; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String dhEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String nSeqEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String verEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento.DetEvento detEvento; @XmlAttribute(name = "Id", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; /** * Obtm o valor da propriedade cOrgao. * * @return possible object is * {@link String } */ public String getCOrgao() { return cOrgao; } /** * Define o valor da propriedade cOrgao. * * @param value allowed object is * {@link String } */ public void setCOrgao(String value) { this.cOrgao = value; } /** * Obtm o valor da propriedade tpAmb. * * @return possible object is * {@link String } */ public String getTpAmb() { return tpAmb; } /** * Define o valor da propriedade tpAmb. * * @param value allowed object is * {@link String } */ public void setTpAmb(String value) { this.tpAmb = value; } /** * Obtm o valor da propriedade cnpj. * * @return possible object is * {@link String } */ public String getCNPJ() { return cnpj; } /** * Define o valor da propriedade cnpj. * * @param value allowed object is * {@link String } */ public void setCNPJ(String value) { this.cnpj = value; } /** * Obtm o valor da propriedade cpf. * * @return possible object is * {@link String } */ public String getCPF() { return cpf; } /** * Define o valor da propriedade cpf. * * @param value allowed object is * {@link String } */ public void setCPF(String value) { this.cpf = value; } /** * Obtm o valor da propriedade chNFe. * * @return possible object is * {@link String } */ public String getChNFe() { return chNFe; } /** * Define o valor da propriedade chNFe. * * @param value allowed object is * {@link String } */ public void setChNFe(String value) { this.chNFe = value; } /** * Obtm o valor da propriedade dhEvento. * * @return possible object is * {@link String } */ public String getDhEvento() { return dhEvento; } /** * Define o valor da propriedade dhEvento. * * @param value allowed object is * {@link String } */ public void setDhEvento(String value) { this.dhEvento = value; } /** * Obtm o valor da propriedade tpEvento. * * @return possible object is * {@link String } */ public String getTpEvento() { return tpEvento; } /** * Define o valor da propriedade tpEvento. * * @param value allowed object is * {@link String } */ public void setTpEvento(String value) { this.tpEvento = value; } /** * Obtm o valor da propriedade nSeqEvento. * * @return possible object is * {@link String } */ public String getNSeqEvento() { return nSeqEvento; } /** * Define o valor da propriedade nSeqEvento. * * @param value allowed object is * {@link String } */ public void setNSeqEvento(String value) { this.nSeqEvento = value; } /** * Obtm o valor da propriedade verEvento. * * @return possible object is * {@link String } */ public String getVerEvento() { return verEvento; } /** * Define o valor da propriedade verEvento. * * @param value allowed object is * {@link String } */ public void setVerEvento(String value) { this.verEvento = value; } /** * Obtm o valor da propriedade detEvento. * * @return possible object is * {@link TEvento.InfEvento.DetEvento } */ public TEvento.InfEvento.DetEvento getDetEvento() { return detEvento; } /** * Define o valor da propriedade detEvento. * * @param value allowed object is * {@link TEvento.InfEvento.DetEvento } */ public void setDetEvento(TEvento.InfEvento.DetEvento value) { this.detEvento = value; } /** * Obtm o valor da propriedade id. * * @return possible object is * {@link String } */ public String getId() { return id; } /** * Define o valor da propriedade id. * * @param value allowed object is * {@link String } */ public void setId(String value) { this.id = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}descEvento"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}cOrgaoAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpAutor"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}verAplic"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}dhEmi"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}tpNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE"/> * &lt;element name="dest"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="versao" use="required"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="1.00"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "descEvento", "cOrgaoAutor", "tpAutor", "verAplic", "dhEmi", "tpNF", "ie", "dest" }) public static class DetEvento { @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String descEvento; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String cOrgaoAutor; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpAutor; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String verAplic; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String dhEmi; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String tpNF; @XmlElement(name = "IE", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String ie; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected TEvento.InfEvento.DetEvento.Dest dest; @XmlAttribute(name = "versao", required = true) protected String versao; /** * Obtm o valor da propriedade descEvento. * * @return possible object is * {@link String } */ public String getDescEvento() { return descEvento; } /** * Define o valor da propriedade descEvento. * * @param value allowed object is * {@link String } */ public void setDescEvento(String value) { this.descEvento = value; } /** * Obtm o valor da propriedade cOrgaoAutor. * * @return possible object is * {@link String } */ public String getCOrgaoAutor() { return cOrgaoAutor; } /** * Define o valor da propriedade cOrgaoAutor. * * @param value allowed object is * {@link String } */ public void setCOrgaoAutor(String value) { this.cOrgaoAutor = value; } /** * Obtm o valor da propriedade tpAutor. * * @return possible object is * {@link String } */ public String getTpAutor() { return tpAutor; } /** * Define o valor da propriedade tpAutor. * * @param value allowed object is * {@link String } */ public void setTpAutor(String value) { this.tpAutor = value; } /** * Obtm o valor da propriedade verAplic. * * @return possible object is * {@link String } */ public String getVerAplic() { return verAplic; } /** * Define o valor da propriedade verAplic. * * @param value allowed object is * {@link String } */ public void setVerAplic(String value) { this.verAplic = value; } /** * Obtm o valor da propriedade dhEmi. * * @return possible object is * {@link String } */ public String getDhEmi() { return dhEmi; } /** * Define o valor da propriedade dhEmi. * * @param value allowed object is * {@link String } */ public void setDhEmi(String value) { this.dhEmi = value; } /** * Obtm o valor da propriedade tpNF. * * @return possible object is * {@link String } */ public String getTpNF() { return tpNF; } /** * Define o valor da propriedade tpNF. * * @param value allowed object is * {@link String } */ public void setTpNF(String value) { this.tpNF = value; } /** * Obtm o valor da propriedade ie. * * @return possible object is * {@link String } */ public String getIE() { return ie; } /** * Define o valor da propriedade ie. * * @param value allowed object is * {@link String } */ public void setIE(String value) { this.ie = value; } /** * Obtm o valor da propriedade dest. * * @return possible object is * {@link TEvento.InfEvento.DetEvento.Dest } */ public TEvento.InfEvento.DetEvento.Dest getDest() { return dest; } /** * Define o valor da propriedade dest. * * @param value allowed object is * {@link TEvento.InfEvento.DetEvento.Dest } */ public void setDest(TEvento.InfEvento.DetEvento.Dest value) { this.dest = value; } /** * Obtm o valor da propriedade versao. * * @return possible object is * {@link String } */ public String getVersao() { return versao; } /** * Define o valor da propriedade versao. * * @param value allowed object is * {@link String } */ public void setVersao(String value) { this.versao = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}UF"/> * &lt;choice> * &lt;element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpj"/> * &lt;element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/> * &lt;element name="idEstrangeiro"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;pattern value="([!-]{0}|[!-]{5,20})?"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/choice> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}IE" minOccurs="0"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vNF"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vICMS"/> * &lt;element ref="{http://www.portalfiscal.inf.br/nfe}vST"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "uf", "cnpj", "cpf", "idEstrangeiro", "ie", "vnf", "vicms", "vst" }) public static class Dest { @XmlElement(name = "UF", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) @XmlSchemaType(name = "string") protected TUf uf; @XmlElement(name = "CNPJ", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cnpj; @XmlElement(name = "CPF", namespace = "http://www.portalfiscal.inf.br/nfe") protected String cpf; @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe") protected String idEstrangeiro; @XmlElement(name = "IE", namespace = "http://www.portalfiscal.inf.br/nfe") protected String ie; @XmlElement(name = "vNF", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vnf; @XmlElement(name = "vICMS", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vicms; @XmlElement(name = "vST", namespace = "http://www.portalfiscal.inf.br/nfe", required = true) protected String vst; /** * Obtm o valor da propriedade uf. * * @return possible object is * {@link TUf } */ public TUf getUF() { return uf; } /** * Define o valor da propriedade uf. * * @param value allowed object is * {@link TUf } */ public void setUF(TUf value) { this.uf = value; } /** * Obtm o valor da propriedade cnpj. * * @return possible object is * {@link String } */ public String getCNPJ() { return cnpj; } /** * Define o valor da propriedade cnpj. * * @param value allowed object is * {@link String } */ public void setCNPJ(String value) { this.cnpj = value; } /** * Obtm o valor da propriedade cpf. * * @return possible object is * {@link String } */ public String getCPF() { return cpf; } /** * Define o valor da propriedade cpf. * * @param value allowed object is * {@link String } */ public void setCPF(String value) { this.cpf = value; } /** * Obtm o valor da propriedade idEstrangeiro. * * @return possible object is * {@link String } */ public String getIdEstrangeiro() { return idEstrangeiro; } /** * Define o valor da propriedade idEstrangeiro. * * @param value allowed object is * {@link String } */ public void setIdEstrangeiro(String value) { this.idEstrangeiro = value; } /** * Obtm o valor da propriedade ie. * * @return possible object is * {@link String } */ public String getIE() { return ie; } /** * Define o valor da propriedade ie. * * @param value allowed object is * {@link String } */ public void setIE(String value) { this.ie = value; } /** * Obtm o valor da propriedade vnf. * * @return possible object is * {@link String } */ public String getVNF() { return vnf; } /** * Define o valor da propriedade vnf. * * @param value allowed object is * {@link String } */ public void setVNF(String value) { this.vnf = value; } /** * Obtm o valor da propriedade vicms. * * @return possible object is * {@link String } */ public String getVICMS() { return vicms; } /** * Define o valor da propriedade vicms. * * @param value allowed object is * {@link String } */ public void setVICMS(String value) { this.vicms = value; } /** * Obtm o valor da propriedade vst. * * @return possible object is * {@link String } */ public String getVST() { return vst; } /** * Define o valor da propriedade vst. * * @param value allowed object is * {@link String } */ public void setVST(String value) { this.vst = value; } } } } }
mit
Azure/azure-sdk-for-java
sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/administration/DocumentModelAdminAsyncClientJavaDocCodeSnippets.java
24260
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.formrecognizer.administration; import com.azure.ai.formrecognizer.administration.models.AccountProperties; import com.azure.ai.formrecognizer.administration.models.BuildModelOptions; import com.azure.ai.formrecognizer.administration.models.CopyAuthorization; import com.azure.ai.formrecognizer.administration.models.CopyAuthorizationOptions; import com.azure.ai.formrecognizer.administration.models.CreateComposedModelOptions; import com.azure.ai.formrecognizer.administration.models.DocumentBuildMode; import com.azure.ai.formrecognizer.administration.models.DocumentModel; import com.azure.ai.formrecognizer.administration.models.ModelOperation; import com.azure.ai.formrecognizer.administration.models.ModelOperationStatus; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.util.polling.AsyncPollResponse; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Code snippet for {@link DocumentModelAdministrationAsyncClient} */ public class DocumentModelAdminAsyncClientJavaDocCodeSnippets { private final DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder().buildAsyncClient(); /** * Code snippet for {@link DocumentModelAdministrationAsyncClient} initialization */ public void formTrainingAsyncClientInInitialization() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.initialization DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder().buildAsyncClient(); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.initialization } /** * Code snippet for creating a {@link DocumentModelAdministrationAsyncClient} with pipeline */ public void createDocumentTrainingAsyncClientWithPipeline() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.pipeline.instantiation HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); DocumentModelAdministrationAsyncClient documentModelAdministrationAsyncClient = new DocumentModelAdministrationClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.pipeline.instantiation } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginBuildModel(String, DocumentBuildMode, String)} */ public void beginBuildModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}"; documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE, "model-name" ) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginBuildModel(String, DocumentBuildMode, String, BuildModelOptions)} * with options */ public void beginBuildModelWithOptions() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String-BuildModelOptions String trainingFilesUrl = "{SAS-URL-of-your-container-in-blob-storage}"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.beginBuildModel(trainingFilesUrl, DocumentBuildMode.TEMPLATE, "model-name", new BuildModelOptions() .setDescription("model desc") .setPrefix("Invoice") .setTags(attrs)) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); System.out.printf("Model assigned tags: %s%n", documentModel.getTags()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginBuildModel#String-String-BuildModelOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#deleteModel} */ public void deleteModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModel#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.deleteModel(modelId) .subscribe(ignored -> System.out.printf("Model ID: %s is deleted%n", modelId)); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModel#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#deleteModelWithResponse(String)} */ public void deleteModelWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModelWithResponse#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.deleteModelWithResponse(modelId) .subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); System.out.printf("Model ID: %s is deleted.%n", modelId); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.deleteModelWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getCopyAuthorization(String)} */ public void getCopyAuthorization() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorization#string String modelId = "my-copied-model"; documentModelAdministrationAsyncClient.getCopyAuthorization(modelId) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization for model id: %s, access token: %s, expiration time: %s, " + "target resource ID; %s, target resource region: %s%n", copyAuthorization.getTargetModelId(), copyAuthorization.getAccessToken(), copyAuthorization.getExpiresOn(), copyAuthorization.getTargetResourceId(), copyAuthorization.getTargetResourceRegion() )); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorization#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getCopyAuthorizationWithResponse(String, CopyAuthorizationOptions)} */ public void getCopyAuthorizationWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse#string-CopyAuthorizationOptions String modelId = "my-copied-model"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse(modelId, new CopyAuthorizationOptions() .setDescription("model desc") .setTags(attrs)) .subscribe(copyAuthorization -> System.out.printf("Copy Authorization response status: %s, for model id: %s, access token: %s, " + "expiration time: %s, target resource ID; %s, target resource region: %s%n", copyAuthorization.getStatusCode(), copyAuthorization.getValue().getTargetModelId(), copyAuthorization.getValue().getAccessToken(), copyAuthorization.getValue().getExpiresOn(), copyAuthorization.getValue().getTargetResourceId(), copyAuthorization.getValue().getTargetResourceRegion() )); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getCopyAuthorizationWithResponse#string-CopyAuthorizationOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getAccountProperties()} */ public void getAccountProperties() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountProperties documentModelAdministrationAsyncClient.getAccountProperties() .subscribe(accountProperties -> { System.out.printf("Max number of models that can be build for this account: %d%n", accountProperties.getDocumentModelLimit()); System.out.printf("Current count of built document analysis models: %d%n", accountProperties.getDocumentModelCount()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountProperties } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getAccountPropertiesWithResponse()} */ public void getAccountPropertiesWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountPropertiesWithResponse documentModelAdministrationAsyncClient.getAccountPropertiesWithResponse() .subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); AccountProperties accountProperties = response.getValue(); System.out.printf("Max number of models that can be build for this account: %d%n", accountProperties.getDocumentModelLimit()); System.out.printf("Current count of built document analysis models: %d%n", accountProperties.getDocumentModelCount()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getAccountPropertiesWithResponse } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCreateComposedModel(List, String)} */ public void beginCreateComposedModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String String modelId1 = "{model_Id_1}"; String modelId2 = "{model_Id_2}"; documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2), "my-composed-model") // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCreateComposedModel(List, String, CreateComposedModelOptions)} * with options */ public void beginCreateComposedModelWithOptions() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String-createComposedModelOptions String modelId1 = "{model_Id_1}"; String modelId2 = "{model_Id_2}"; Map<String, String> attrs = new HashMap<String, String>(); attrs.put("createdBy", "sample"); documentModelAdministrationAsyncClient.beginCreateComposedModel(Arrays.asList(modelId1, modelId2), "my-composed-model", new CreateComposedModelOptions().setDescription("model-desc").setTags(attrs)) // if polling operation completed, retrieve the final result. .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); System.out.printf("Model assigned tags: %s%n", documentModel.getTags()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCreateComposedModel#list-String-createComposedModelOptions } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#beginCopyModel(String, CopyAuthorization)} */ public void beginCopy() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCopyModel#string-copyAuthorization String copyModelId = "copy-model"; String targetModelId = "my-copied-model-id"; // Get authorization to copy the model to target resource documentModelAdministrationAsyncClient.getCopyAuthorization(targetModelId) // Start copy operation from the source client // The ID of the model that needs to be copied to the target resource .subscribe(copyAuthorization -> documentModelAdministrationAsyncClient.beginCopyModel(copyModelId, copyAuthorization) .filter(pollResponse -> pollResponse.getStatus().isComplete()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(documentModel -> System.out.printf("Copied model has model ID: %s, was created on: %s.%n,", documentModel.getModelId(), documentModel.getCreatedOn()))); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.beginCopyModel#string-copyAuthorization } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#listModels()} */ public void listModels() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listModels documentModelAdministrationAsyncClient.listModels() .subscribe(documentModelInfo -> System.out.printf("Model ID: %s, Model description: %s, Created on: %s.%n", documentModelInfo.getModelId(), documentModelInfo.getDescription(), documentModelInfo.getCreatedOn())); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listModels } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModel(String)} */ public void getModel() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModel#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.getModel(modelId).subscribe(documentModel -> { System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModel#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModelWithResponse(String)} */ public void getModelWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModelWithResponse#string String modelId = "{model_id}"; documentModelAdministrationAsyncClient.getModelWithResponse(modelId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); DocumentModel documentModel = response.getValue(); System.out.printf("Model ID: %s%n", documentModel.getModelId()); System.out.printf("Model Description: %s%n", documentModel.getDescription()); System.out.printf("Model Created on: %s%n", documentModel.getCreatedOn()); documentModel.getDocTypes().forEach((key, docTypeInfo) -> { docTypeInfo.getFieldSchema().forEach((field, documentFieldSchema) -> { System.out.printf("Field: %s", field); System.out.printf("Field type: %s", documentFieldSchema.getType()); System.out.printf("Field confidence: %.2f", docTypeInfo.getFieldConfidence().get(field)); }); }); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getModelWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getModel(String)} */ public void getOperation() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperation#string String operationId = "{operation_Id}"; documentModelAdministrationAsyncClient.getOperation(operationId).subscribe(modelOperation -> { System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId()); if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) { System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage()); } }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperation#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#getOperationWithResponse(String)} */ public void getOperationWithResponse() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperationWithResponse#string String operationId = "{operation_Id}"; documentModelAdministrationAsyncClient.getOperationWithResponse(operationId).subscribe(response -> { System.out.printf("Response Status Code: %d.", response.getStatusCode()); ModelOperation modelOperation = response.getValue(); System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Model ID created with this operation: %s%n", modelOperation.getModelId()); if (ModelOperationStatus.FAILED.equals(modelOperation.getStatus())) { System.out.printf("Operation fail error: %s%n", modelOperation.getError().getMessage()); } }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.getOperationWithResponse#string } /** * Code snippet for {@link DocumentModelAdministrationAsyncClient#listOperations()} */ public void listOperations() { // BEGIN: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listOperations documentModelAdministrationAsyncClient.listOperations() .subscribe(modelOperation -> { System.out.printf("Operation ID: %s%n", modelOperation.getOperationId()); System.out.printf("Operation Status: %s%n", modelOperation.getStatus()); System.out.printf("Operation Created on: %s%n", modelOperation.getCreatedOn()); System.out.printf("Operation Percent completed: %d%n", modelOperation.getPercentCompleted()); System.out.printf("Operation Kind: %s%n", modelOperation.getKind()); System.out.printf("Operation Last updated on: %s%n", modelOperation.getLastUpdatedOn()); System.out.printf("Operation resource location: %s%n", modelOperation.getResourceLocation()); }); // END: com.azure.ai.formrecognizer.administration.DocumentModelAdministrationAsyncClient.listOperations } }
mit
karim/adila
database/src/main/java/adila/db/asus5fz00m_asus5fz00md.java
259
// This file is automatically generated. package adila.db; /* * Asus ZenFone 2 Laser (ZE600KL) * * DEVICE: ASUS_Z00M * MODEL: ASUS_Z00MD */ final class asus5fz00m_asus5fz00md { public static final String DATA = "Asus|ZenFone 2 Laser (ZE600KL)|"; }
mit
leotizzei/MobileMedia-Cosmos-VP-v6
src/br/unicamp/ic/sed/mobilemedia/copyphoto/impl/PhotoViewController.java
3765
/** * University of Campinas - Brazil * Institute of Computing * SED group * * date: February 2009 * */ package br.unicamp.ic.sed.mobilemedia.copyphoto.impl; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; import br.unicamp.ic.sed.mobilemedia.copyphoto.spec.prov.IManager; import br.unicamp.ic.sed.mobilemedia.copyphoto.spec.req.IFilesystem; import br.unicamp.ic.sed.mobilemedia.main.spec.dt.IImageData; import br.unicamp.ic.sed.mobilemedia.photo.spec.prov.IPhoto; /** * TODO This whole class must be aspectized */ class PhotoViewController extends AbstractController { private AddPhotoToAlbum addPhotoToAlbum; private static final Command backCommand = new Command("Back", Command.BACK, 0); private Displayable lastScreen = null; private void setAddPhotoToAlbum(AddPhotoToAlbum addPhotoToAlbum) { this.addPhotoToAlbum = addPhotoToAlbum; } String imageName = ""; public PhotoViewController(MIDlet midlet, String imageName) { super( midlet ); this.imageName = imageName; } private AddPhotoToAlbum getAddPhotoToAlbum() { if( this.addPhotoToAlbum == null) this.addPhotoToAlbum = new AddPhotoToAlbum("Copy Photo to Album"); return addPhotoToAlbum; } /* (non-Javadoc) * @see ubc.midp.mobilephoto.core.ui.controller.ControllerInterface#handleCommand(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable) */ public boolean handleCommand(Command c) { String label = c.getLabel(); System.out.println( "<*"+this.getClass().getName()+".handleCommand() *> " + label); /** Case: Copy photo to a different album */ if (label.equals("Copy")) { this.initCopyPhotoToAlbum( ); return true; } /** Case: Save a copy in a new album */ else if (label.equals("Save Photo")) { return this.savePhoto(); /* IManager manager = ComponentFactory.createInstance(); IPhoto photo = (IPhoto) manager.getRequiredInterface("IPhoto"); return photo.postCommand( listImagesCommand ); */ }else if( label.equals("Cancel")){ if( lastScreen != null ){ MIDlet midlet = this.getMidlet(); Display.getDisplay( midlet ).setCurrent( lastScreen ); return true; } } return false; } private void initCopyPhotoToAlbum() { String title = new String("Copy Photo to Album"); String labelPhotoPath = new String("Copy to Album:"); AddPhotoToAlbum addPhotoToAlbum = new AddPhotoToAlbum( title ); addPhotoToAlbum.setPhotoName( imageName ); addPhotoToAlbum.setLabelPhotoPath( labelPhotoPath ); this.setAddPhotoToAlbum( addPhotoToAlbum ); //Get all required interfaces for this method MIDlet midlet = this.getMidlet(); //addPhotoToAlbum.setCommandListener( this ); lastScreen = Display.getDisplay( midlet ).getCurrent(); Display.getDisplay( midlet ).setCurrent( addPhotoToAlbum ); addPhotoToAlbum.setCommandListener(this); } private boolean savePhoto() { System.out.println("[PhotoViewController:savePhoto()]"); IManager manager = ComponentFactory.createInstance(); IImageData imageData = null; IFilesystem filesystem = (IFilesystem) manager.getRequiredInterface("IFilesystem"); System.out.println("[PhotoViewController:savePhoto()] filesystem="+filesystem); imageData = filesystem.getImageInfo(imageName); AddPhotoToAlbum addPhotoToAlbum = this.getAddPhotoToAlbum(); String photoName = addPhotoToAlbum.getPhotoName(); String albumName = addPhotoToAlbum.getPath(); filesystem.addImageData(photoName, imageData, albumName); if( lastScreen != null ){ MIDlet midlet = this.getMidlet(); Display.getDisplay( midlet ).setCurrent( lastScreen ); } return true; } }
mit
CodersForLife/Data-Structures-Algorithms
Searching/BinarySearch.java
932
import java.util.Scanner; public class BinarySearch { public static int binarySearch(int arr[], int num, int startIndex, int endIndex) { if (startIndex > endIndex) { return -1; } int mid = startIndex + (endIndex - startIndex) / 2; if (num == arr[mid]) { return mid; } else if (num > arr[mid]) { return binarySearch(arr, num, mid + 1, endIndex); } else { return binarySearch(arr, num, startIndex, mid - 1); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int size = s.nextInt(); int[] arr = new int[size]; for (int i = 0; i < arr.length; i++) { arr[i] = s.nextInt(); } int num = s.nextInt(); int position = binarySearch(arr, num, 0, size - 1); if (position == -1) { System.out.println("The number is not present in the array"); } else { System.out.println("The position of number in array is : " + position); } s.close(); } }
mit
dgautier/PlatformJavaClient
src/main/java/com/docuware/dev/schema/_public/services/platform/SortDirection.java
808
package com.docuware.dev.schema._public.services.platform; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; @XmlType(name = "SortDirection") @XmlEnum public enum SortDirection { @XmlEnumValue("Default") DEFAULT("Default"), @XmlEnumValue("Asc") ASC("Asc"), @XmlEnumValue("Desc") DESC("Desc"); private final String value; SortDirection(String v) { value = v; } public String value() { return value; } public static SortDirection fromValue(String v) { for (SortDirection c: SortDirection.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
lightblueseas/user-data
user-entities/src/main/java/de/alpharogroup/user/repositories/RelationPermissionsDao.java
1582
/** * The MIT License * * Copyright (C) 2015 Asterios Raptis * * 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 de.alpharogroup.user.repositories; import org.springframework.stereotype.Repository; import de.alpharogroup.db.dao.jpa.JpaEntityManagerDao; import de.alpharogroup.user.entities.RelationPermissions; @Repository("relationPermissionsDao") public class RelationPermissionsDao extends JpaEntityManagerDao<RelationPermissions, Integer> { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; }
mit
Kaioru/PokeDat
PokeDat-Data/src/main/java/io/github/kaioru/species/SpeciesLearnset.java
1388
/* * PokeDat - A Pokemon Data API. * Copyright (C) 2015 * * 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 io.github.kaioru.species; import java.io.Serializable; /** * @todo Class Description * * @author Kaioru **/ public class SpeciesLearnset implements Serializable { private static final long serialVersionUID = 5370581555765470935L; }
mit
torbjornvatn/cuke4duke
examples/guice/src/test/java/billing/CalledSteps.java
413
package billing; import cuke4duke.Then; import cuke4duke.Given; import static org.junit.Assert.assertTrue; public class CalledSteps { private boolean magic; @Given("^it is (.*)$") public void itIs(String what) { if(what.equals("magic")) { magic = true; } } @Then("^magic should happen$") public void magicShouldHappen() { assertTrue(magic); } }
mit
vincent7894/vas
vas-notification/src/main/java/org/vas/notification/NotificationWorker.java
2998
/** * The MIT License (MIT) * * Copyright (c) 2015 Vincent Vergnolle * * 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.vas.notification; import java.time.LocalDateTime; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vas.domain.repository.Address; import org.vas.domain.repository.User; import org.vas.notification.domain.repository.NotificationService; /** * Notification worker for limited users * */ public class NotificationWorker implements Runnable { protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final List<User> users; protected final Notifier notifier; protected final NotificationService notificationService; public NotificationWorker(List<User> users, NotificationService notificationService, Notifier notifier) { super(); this.users = users; this.notifier = notifier; this.notificationService = notificationService; } @Override public void run() { if(logger.isTraceEnabled()) { logger.trace("Start worker with {} users", users); } users.forEach(this::notifyUser); } protected void notifyUser(User user) { user.addresses.forEach((address) -> notifyAddress(user, address)); } protected void notifyAddress(User user, Address address) { if(logger.isTraceEnabled()) { logger.trace("Notify address {} - {}", user.username, address.label); } notificationService.listByAddress(address).forEach(notif -> doNotify(user, address, notif)); } protected void doNotify(User user, Address address, Notification notification) { if(notification.isTime(LocalDateTime.now())) { dispatch(user, address, notification); } } protected void dispatch(User user, Address address, Notification notification) { if(logger.isTraceEnabled()) { logger.trace("Dispatch notification n-{}", notification.id); } notifier.dispatch(user, address, notification); } }
mit
shuaicj/hello-java
hello-configuration/hello-configuration-case04/src/main/java/shuaicj/hello/configuration/case04/Application.java
395
package shuaicj.hello.configuration.case04; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Spring boot application. * * @author shuaicj 2019/10/12 */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
mit
attrs/webmodules
examples/react-native-web/android/app/src/main/java/com/reactnativeexample/MainActivity.java
1050
package com.reactnativeexample; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "ReactNativeExample"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }
mit
inpercima/run-and-fun
server/src/main/java/net/inpercima/runandfun/service/ActivitiesService.java
7790
package net.inpercima.runandfun.service; import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_MEDIA; import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_PAGE_SIZE_ONE; import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.inject.Inject; import com.google.common.base.Splitter; import com.google.common.base.Strings; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.stereotype.Service; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.inpercima.restapi.service.RestApiService; import net.inpercima.runandfun.app.model.AppActivity; import net.inpercima.runandfun.runkeeper.model.RunkeeperActivities; import net.inpercima.runandfun.runkeeper.model.RunkeeperActivityItem; /** * @author Marcel Jänicke * @author Sebastian Peters * @since 26.01.2015 */ @NoArgsConstructor @Service @Slf4j public class ActivitiesService { // initial release in 2008 according to http://en.wikipedia.org/wiki/RunKeeper private static final LocalDate INITIAL_RELEASE_OF_RUNKEEPER = LocalDate.of(2008, 01, 01); @Inject private AuthService authService; @Inject private RestApiService restApiService; @Inject private ActivityRepository repository; @Inject private ElasticsearchRestTemplate elasticsearchRestTemplate; public int indexActivities(final String accessToken) { final Collection<AppActivity> activities = new ArrayList<>(); final String username = authService.getAppState(accessToken).getUsername(); listActivities(accessToken, calculateFetchDate()).stream().filter(item -> !repository.existsById(item.getId())) .forEach(item -> addActivity(item, username, activities)); log.info("new activities: {}", activities.size()); if (!activities.isEmpty()) { repository.saveAll(activities); } return activities.size(); } /** * List activities live from runkeeper with an accessToken and a date. The full * size will be determined every time but with the given date only the last * items will be collected with a max. of the full size. * * @param accessToken * @param from * @return list of activity items */ private List<RunkeeperActivityItem> listActivities(final String accessToken, final LocalDate from) { log.debug("list activities for token {} until {}", accessToken, from); // get one item only to get full size int pageSize = restApiService .getForObject(ACTIVITIES_URL_PAGE_SIZE_ONE, ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class) .getBody().getSize(); // list new activities from given date with max. full size return restApiService.getForObject( String.format(ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN, pageSize, from.format(DateTimeFormatter.ISO_LOCAL_DATE)), ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class).getBody().getItemsAsList(); } private LocalDate calculateFetchDate() { final AppActivity activity = getLastActivity(); return activity == null ? INITIAL_RELEASE_OF_RUNKEEPER : activity.getDate().toLocalDate(); } private void addActivity(final RunkeeperActivityItem item, final String username, final Collection<AppActivity> activities) { final AppActivity activity = new AppActivity(item.getId(), username, item.getType(), item.getDate(), item.getDistance(), item.getDuration()); log.debug("prepare {}", activity); activities.add(activity); } /** * Get last activity from app repository. * * @return last activity */ public AppActivity getLastActivity() { return repository.findTopByOrderByDateDesc(); } /** * Count activities from app repository. * * @return count */ public Long countActivities() { return repository.count(); } /** * List activites from app repository. * * @param pageable * @param types * @param minDate * @param maxDate * @param minDistance * @param maxDistance * @param query * @return */ public SearchHits<AppActivity> listActivities(final Pageable pageable, final String types, final LocalDate minDate, final LocalDate maxDate, final Float minDistance, final Float maxDistance, final String query) { final BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); if (!Strings.isNullOrEmpty(types)) { final BoolQueryBuilder typesQuery = QueryBuilders.boolQuery(); for (final String type : Splitter.on(',').split(types)) { typesQuery.should(QueryBuilders.termQuery(AppActivity.FIELD_TYPE, type)); } queryBuilder.must(typesQuery); } if (minDate != null || maxDate != null) { addDateQuery(queryBuilder, minDate, maxDate); } if (minDistance != null || maxDistance != null) { addDistanceQuery(queryBuilder, minDistance, maxDistance); } if (!Strings.isNullOrEmpty(query)) { addFulltextQuery(queryBuilder, query); } if (!queryBuilder.hasClauses()) { queryBuilder.must(QueryBuilders.matchAllQuery()); } log.info("{}", queryBuilder); return elasticsearchRestTemplate.search( new NativeSearchQueryBuilder().withPageable(pageable).withQuery(queryBuilder).build(), AppActivity.class, IndexCoordinates.of("activity")); } private static void addFulltextQuery(final BoolQueryBuilder queryBuilder, final String query) { queryBuilder.must(QueryBuilders.termQuery("_all", query.trim())); } private static void addDateQuery(final BoolQueryBuilder queryBuilder, final LocalDate minDate, final LocalDate maxDate) { final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DATE); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"); if (minDate != null) { LocalDateTime minDateTime = minDate.atStartOfDay(); rangeQuery.gte(minDateTime.format(formatter)); } if (maxDate != null) { LocalDateTime maxDateTime = maxDate.atStartOfDay(); rangeQuery.lte(maxDateTime.format(formatter)); } queryBuilder.must(rangeQuery); } private static void addDistanceQuery(final BoolQueryBuilder queryBuilder, final Float minDistance, final Float maxDistance) { final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DISTANCE); if (minDistance != null) { rangeQuery.gte(minDistance); } if (maxDistance != null) { rangeQuery.lte(maxDistance); } queryBuilder.must(rangeQuery); } }
mit
dpak96/CellSociety
src/cellsociety_team05/SimulationException.java
139
package cellsociety_team05; public class SimulationException extends Exception { public SimulationException(String s) { super(s); } }
mit
globalforge/infix
src/test/java/com/globalforge/infix/TestAndOrSimple.java
16486
package com.globalforge.infix; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.globalforge.infix.api.InfixSimpleActions; import com.google.common.collect.ListMultimap; /*- The MIT License (MIT) Copyright (c) 2019-2020 Global Forge LLC 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. */ public class TestAndOrSimple { @BeforeClass public static void setUpBeforeClass() throws Exception { } private ListMultimap<String, String> getResults(String sampleRule) throws Exception { InfixSimpleActions rules = new InfixSimpleActions(sampleRule); String result = rules.transformFIXMsg(TestAndOrSimple.sampleMessage1); return StaticTestingUtils.parseMessage(result); } @Test public void t1() { try { String sampleRule = "&45==0 && &47==0 ? &50=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("50").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t2() { try { String sampleRule = "&45==1 && &47==0 ? &50=1 : &50=2"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("2", resultStore.get("50").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t3() { try { String sampleRule = "&45!=1 && &47==0 ? &50=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("50").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t4() { try { String sampleRule = "&45==0 && &47 != 1 ? &50=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("50").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t9() { try { String sampleRule = "&45==0 && &47==0 && &48==1.5 ? &45=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t10() { try { String sampleRule = "&45==1 && &47==0 && &48==1.5 ? &45=1 : &47=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("1", resultStore.get("47").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t11() { try { String sampleRule = "&45==0 && &47==1 && &48==1.5 ? &45=1 : &47=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("1", resultStore.get("47").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t12() { try { String sampleRule = "&45==0 && &47==0 && &48==1.6 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t13() { try { String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t14() { try { String sampleRule = "&45==0 && &47==0 || &48==1.6 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t15() { try { String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t16() { try { String sampleRule = "(&45==0 || &47==0) && (&48==1.6) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t17() { try { String sampleRule = "&45==0 || (&47==0 && &48==1.6) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("0", resultStore.get("47").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t18() { try { String sampleRule = "^&45 && ^&47 && ^&48 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t19() { try { String sampleRule = "^&45 && ^&47 && ^&50 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t20() { try { String sampleRule = "^&45 || ^&47 || ^&50 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t21() { try { String sampleRule = "!&50 && !&51 && !&52 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t22() { try { String sampleRule = "^&45 || !&51 && !&52 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t23() { try { String sampleRule = "(^&45 || !&51) && !&52 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t24() { try { String sampleRule = "^&45 || (!&51 && !&52) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t25() { try { String sampleRule = "!&50 || !&45 && !&52 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t26() { try { String sampleRule = "(!&50 || !&45) && !&52 ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t27() { try { String sampleRule = "!&50 || (!&45 && !&52) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t28() { try { String sampleRule = "!&55 && (!&54 && (!&53 && (!&47 && !&52))) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t29() { try { String sampleRule = "!&55 && (!&54 && (!&53 && (!&56 && !&52))) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t30() { try { String sampleRule = "(!&55 || (!&54 || (!&53 || (!&52 && !&47)))) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t31() { try { String sampleRule = "((((!&55 || !&54) || !&53) || !&52) && !&47) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("0", resultStore.get("45").get(0)); Assert.assertEquals("1", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t32() { try { String sampleRule = "(&382[1]->&655!=\"tarz\" || (&382[0]->&655==\"fubi\" " + "|| (&382[1]->&375==3 || (&382 >= 2 || (&45 > -1 || (&48 <=1.5 && &47 < 0.0001)))))) ? &45=1 : &48=1"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("45").get(0)); Assert.assertEquals("1.5", resultStore.get("48").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t34() { try { // left to right String sampleRule = "&45 == 0 || &43 == -100 && &207 == \"USA\" ? &43=1 : &43=2"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("2", resultStore.get("43").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } @Test public void t35() { try { String sampleRule = "&45 == 0 || (&43 == -100 && &207 == \"USA\") ? &43=1 : &43=2"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("1", resultStore.get("43").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } static final String sampleMessage1 = "8=FIX.4.4" + '\u0001' + "9=1000" + '\u0001' + "35=8" + '\u0001' + "44=3.142" + '\u0001' + "60=20130412-19:30:00.686" + '\u0001' + "75=20130412" + '\u0001' + "45=0" + '\u0001' + "47=0" + '\u0001' + "48=1.5" + '\u0001' + "49=8dhosb" + '\u0001' + "382=2" + '\u0001' + "375=1.5" + '\u0001' + "655=fubi" + '\u0001' + "375=3" + '\u0001' + "655=yubl" + '\u0001' + "10=004"; @Test public void t36() { try { // 45=0, String sampleRule = "(&45 == 0 || &43 == -100) && &207 == \"USA\" ? &43=1 : &43=2"; ListMultimap<String, String> resultStore = getResults(sampleRule); Assert.assertEquals("2", resultStore.get("43").get(0)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } }
mit
DanielBoerlage/champion-picker
src/championpicker/console/mainMenu.java
1150
package championpicker.console; import com.googlecode.lanterna.gui.*; import com.googlecode.lanterna.TerminalFacade; import com.googlecode.lanterna.terminal.Terminal; import com.googlecode.lanterna.terminal.TerminalSize; import com.googlecode.lanterna.terminal.swing.SwingTerminal; import com.googlecode.lanterna.gui.GUIScreen; import com.googlecode.lanterna.gui.dialog.DialogButtons; import com.googlecode.lanterna.gui.component.Button; import com.googlecode.lanterna.gui.component.Panel; import com.googlecode.lanterna.gui.component.Label; import com.googlecode.lanterna.gui.Window; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.screen.Screen; import championpicker.Main; import championpicker.console.mainStartUp; import championpicker.console.queueWindow; import javax.swing.JFrame; public class mainMenu extends Window{ public mainMenu(String name){ super(name); queueWindow win = new queueWindow(); addComponent(new Button("Queue!", new Action(){ public void doAction(){ System.out.println("Success!"); mainStartUp.gui.showWindow(win, GUIScreen.Position.CENTER); }})); } }
mit
MiszelHub/FuzzyDriverRefueling
Fuzzy-Driver/src/main/java/simulation/generators/PetrolStationGenerator.java
2533
package simulation.generators; import simulation.data.PetrolStation; import simulation.data.Road; /** * Created by user on 03.06.2017. */ public class PetrolStationGenerator { private Road road; private int minimalDistanceBetweenStations = 50; private int maximumDistanceBetweenStations = 200; private float minimalFuelPrice = 3.5f; private float maximumFuelPrice = 4f; public PetrolStationGenerator(Road road) { this.road = road; } public void generateStationsOnTheRoad(){ RandomIntegerGenerator generator = new RandomIntegerGenerator(); int lastStationPosition = 0; road.addPetrolStation(generateStation(lastStationPosition)); while (lastStationPosition < road.getDistance()){ int nextStationDistance = generator.generateNumberFromRange(minimalDistanceBetweenStations,maximumDistanceBetweenStations); if(lastStationPosition+nextStationDistance <= road.getDistance()){ road.addPetrolStation(generateStation(lastStationPosition+nextStationDistance)); lastStationPosition += nextStationDistance; }else{ break; } } } private PetrolStation generateStation(int positionOnRoad){ float fuelPrice = new RandomFloatGenerator().generateNumberFromRange(minimalFuelPrice,maximumFuelPrice); return new PetrolStation(positionOnRoad,fuelPrice); } public Road getRoad() { return road; } public void setRoad(Road road) { this.road = road; } public int getMinimalDistanceBetweenStations() { return minimalDistanceBetweenStations; } public void setMinimalDistanceBetweenStations(int minimalDistanceBetweenStations) { this.minimalDistanceBetweenStations = minimalDistanceBetweenStations; } public int getMaximumDistanceBetweenStations() { return maximumDistanceBetweenStations; } public void setMaximumDistanceBetweenStations(int maximumDistanceBetweenStations) { this.maximumDistanceBetweenStations = maximumDistanceBetweenStations; } public float getMinimalFuelPrice() { return minimalFuelPrice; } public void setMinimalFuelPrice(float minimalFuelPrice) { this.minimalFuelPrice = minimalFuelPrice; } public float getMaximumFuelPrice() { return maximumFuelPrice; } public void setMaximumFuelPrice(float maximumFuelPrice) { this.maximumFuelPrice = maximumFuelPrice; } }
mit
smjie2800/spring-cloud-microservice-redis-activemq-hibernate-mysql
microservice-provider-pay/src/main/java/com/boyuanitsm/pay/unionpay/config/SDKConstants.java
13548
/** * * Licensed Property to China UnionPay Co., Ltd. * * (C) Copyright of China UnionPay Co., Ltd. 2010 * All Rights Reserved. * * * Modification History: * ============================================================================= * Author Date Description * ------------ ---------- --------------------------------------------------- * xshu 2014-05-28 MPI插件包常量定义 * ============================================================================= */ package com.boyuanitsm.pay.unionpay.config; public class SDKConstants { public final static String COLUMN_DEFAULT = "-"; public final static String KEY_DELIMITER = "#"; /** memeber variable: blank. */ public static final String BLANK = ""; /** member variabel: space. */ public static final String SPACE = " "; /** memeber variable: unline. */ public static final String UNLINE = "_"; /** memeber varibale: star. */ public static final String STAR = "*"; /** memeber variable: line. */ public static final String LINE = "-"; /** memeber variable: add. */ public static final String ADD = "+"; /** memeber variable: colon. */ public final static String COLON = "|"; /** memeber variable: point. */ public final static String POINT = "."; /** memeber variable: comma. */ public final static String COMMA = ","; /** memeber variable: slash. */ public final static String SLASH = "/"; /** memeber variable: div. */ public final static String DIV = "/"; /** memeber variable: left . */ public final static String LB = "("; /** memeber variable: right. */ public final static String RB = ")"; /** memeber variable: rmb. */ public final static String CUR_RMB = "RMB"; /** memeber variable: .page size */ public static final int PAGE_SIZE = 10; /** memeber variable: String ONE. */ public static final String ONE = "1"; /** memeber variable: String ZERO. */ public static final String ZERO = "0"; /** memeber variable: number six. */ public static final int NUM_SIX = 6; /** memeber variable: equal mark. */ public static final String EQUAL = "="; /** memeber variable: operation ne. */ public static final String NE = "!="; /** memeber variable: operation le. */ public static final String LE = "<="; /** memeber variable: operation ge. */ public static final String GE = ">="; /** memeber variable: operation lt. */ public static final String LT = "<"; /** memeber variable: operation gt. */ public static final String GT = ">"; /** memeber variable: list separator. */ public static final String SEP = "./"; /** memeber variable: Y. */ public static final String Y = "Y"; /** memeber variable: AMPERSAND. */ public static final String AMPERSAND = "&"; /** memeber variable: SQL_LIKE_TAG. */ public static final String SQL_LIKE_TAG = "%"; /** memeber variable: @. */ public static final String MAIL = "@"; /** memeber variable: number zero. */ public static final int NZERO = 0; public static final String LEFT_BRACE = "{"; public static final String RIGHT_BRACE = "}"; /** memeber variable: string true. */ public static final String TRUE_STRING = "true"; /** memeber variable: string false. */ public static final String FALSE_STRING = "false"; /** memeber variable: forward success. */ public static final String SUCCESS = "success"; /** memeber variable: forward fail. */ public static final String FAIL = "fail"; /** memeber variable: global forward success. */ public static final String GLOBAL_SUCCESS = "$success"; /** memeber variable: global forward fail. */ public static final String GLOBAL_FAIL = "$fail"; public static final String UTF_8_ENCODING = "UTF-8"; public static final String GBK_ENCODING = "GBK"; public static final String CONTENT_TYPE = "Content-type"; public static final String APP_XML_TYPE = "application/xml;charset=utf-8"; public static final String APP_FORM_TYPE = "application/x-www-form-urlencoded;charset="; /******************************************** 5.0报文接口定义 ********************************************/ /** 版本号. */ public static final String param_version = "version"; /** 证书ID. */ public static final String param_certId = "certId"; /** 签名. */ public static final String param_signature = "signature"; /** 编码方式. */ public static final String param_encoding = "encoding"; /** 交易类型. */ public static final String param_txnType = "txnType"; /** 交易子类. */ public static final String param_txnSubType = "txnSubType"; /** 业务类型. */ public static final String param_bizType = "bizType"; /** 前台通知地址 . */ public static final String param_frontUrl = "frontUrl"; /** 后台通知地址. */ public static final String param_backUrl = "backUrl"; /** 接入类型. */ public static final String param_accessType = "accessType"; /** 收单机构代码. */ public static final String param_acqInsCode = "acqInsCode"; /** 商户类别. */ public static final String param_merCatCode = "merCatCode"; /** 商户类型. */ public static final String param_merType = "merType"; /** 商户代码. */ public static final String param_merId = "merId"; /** 商户名称. */ public static final String param_merName = "merName"; /** 商户简称. */ public static final String param_merAbbr = "merAbbr"; /** 二级商户代码. */ public static final String param_subMerId = "subMerId"; /** 二级商户名称. */ public static final String param_subMerName = "subMerName"; /** 二级商户简称. */ public static final String param_subMerAbbr = "subMerAbbr"; /** Cupsecure 商户代码. */ public static final String param_csMerId = "csMerId"; /** 商户订单号. */ public static final String param_orderId = "orderId"; /** 交易时间. */ public static final String param_txnTime = "txnTime"; /** 发送时间. */ public static final String param_txnSendTime = "txnSendTime"; /** 订单超时时间间隔. */ public static final String param_orderTimeoutInterval = "orderTimeoutInterval"; /** 支付超时时间. */ public static final String param_payTimeoutTime = "payTimeoutTime"; /** 默认支付方式. */ public static final String param_defaultPayType = "defaultPayType"; /** 支持支付方式. */ public static final String param_supPayType = "supPayType"; /** 支付方式. */ public static final String param_payType = "payType"; /** 自定义支付方式. */ public static final String param_customPayType = "customPayType"; /** 物流标识. */ public static final String param_shippingFlag = "shippingFlag"; /** 收货地址-国家. */ public static final String param_shippingCountryCode = "shippingCountryCode"; /** 收货地址-省. */ public static final String param_shippingProvinceCode = "shippingProvinceCode"; /** 收货地址-市. */ public static final String param_shippingCityCode = "shippingCityCode"; /** 收货地址-地区. */ public static final String param_shippingDistrictCode = "shippingDistrictCode"; /** 收货地址-详细. */ public static final String param_shippingStreet = "shippingStreet"; /** 商品总类. */ public static final String param_commodityCategory = "commodityCategory"; /** 商品名称. */ public static final String param_commodityName = "commodityName"; /** 商品URL. */ public static final String param_commodityUrl = "commodityUrl"; /** 商品单价. */ public static final String param_commodityUnitPrice = "commodityUnitPrice"; /** 商品数量. */ public static final String param_commodityQty = "commodityQty"; /** 是否预授权. */ public static final String param_isPreAuth = "isPreAuth"; /** 币种. */ public static final String param_currencyCode = "currencyCode"; /** 账户类型. */ public static final String param_accType = "accType"; /** 账号. */ public static final String param_accNo = "accNo"; /** 支付卡类型. */ public static final String param_payCardType = "payCardType"; /** 发卡机构代码. */ public static final String param_issInsCode = "issInsCode"; /** 持卡人信息. */ public static final String param_customerInfo = "customerInfo"; /** 交易金额. */ public static final String param_txnAmt = "txnAmt"; /** 余额. */ public static final String param_balance = "balance"; /** 地区代码. */ public static final String param_districtCode = "districtCode"; /** 附加地区代码. */ public static final String param_additionalDistrictCode = "additionalDistrictCode"; /** 账单类型. */ public static final String param_billType = "billType"; /** 账单号码. */ public static final String param_billNo = "billNo"; /** 账单月份. */ public static final String param_billMonth = "billMonth"; /** 账单查询要素. */ public static final String param_billQueryInfo = "billQueryInfo"; /** 账单详情. */ public static final String param_billDetailInfo = "billDetailInfo"; /** 账单金额. */ public static final String param_billAmt = "billAmt"; /** 账单金额符号. */ public static final String param_billAmtSign = "billAmtSign"; /** 绑定标识号. */ public static final String param_bindId = "bindId"; /** 风险级别. */ public static final String param_riskLevel = "riskLevel"; /** 绑定信息条数. */ public static final String param_bindInfoQty = "bindInfoQty"; /** 绑定信息集. */ public static final String param_bindInfoList = "bindInfoList"; /** 批次号. */ public static final String param_batchNo = "batchNo"; /** 总笔数. */ public static final String param_totalQty = "totalQty"; /** 总金额. */ public static final String param_totalAmt = "totalAmt"; /** 文件类型. */ public static final String param_fileType = "fileType"; /** 文件名称. */ public static final String param_fileName = "fileName"; /** 批量文件内容. */ public static final String param_fileContent = "fileContent"; /** 商户摘要. */ public static final String param_merNote = "merNote"; /** 商户自定义域. */ // public static final String param_merReserved = "merReserved";//接口变更删除 /** 请求方保留域. */ public static final String param_reqReserved = "reqReserved";// 新增接口 /** 保留域. */ public static final String param_reserved = "reserved"; /** 终端号. */ public static final String param_termId = "termId"; /** 终端类型. */ public static final String param_termType = "termType"; /** 交互模式. */ public static final String param_interactMode = "interactMode"; /** 发卡机构识别模式. */ // public static final String param_recognitionMode = "recognitionMode"; public static final String param_issuerIdentifyMode = "issuerIdentifyMode";// 接口名称变更 /** 商户端用户号. */ public static final String param_merUserId = "merUserId"; /** 持卡人IP. */ public static final String param_customerIp = "customerIp"; /** 查询流水号. */ public static final String param_queryId = "queryId"; /** 原交易查询流水号. */ public static final String param_origQryId = "origQryId"; /** 系统跟踪号. */ public static final String param_traceNo = "traceNo"; /** 交易传输时间. */ public static final String param_traceTime = "traceTime"; /** 清算日期. */ public static final String param_settleDate = "settleDate"; /** 清算币种. */ public static final String param_settleCurrencyCode = "settleCurrencyCode"; /** 清算金额. */ public static final String param_settleAmt = "settleAmt"; /** 清算汇率. */ public static final String param_exchangeRate = "exchangeRate"; /** 兑换日期. */ public static final String param_exchangeDate = "exchangeDate"; /** 响应时间. */ public static final String param_respTime = "respTime"; /** 原交易应答码. */ public static final String param_origRespCode = "origRespCode"; /** 原交易应答信息. */ public static final String param_origRespMsg = "origRespMsg"; /** 应答码. */ public static final String param_respCode = "respCode"; /** 应答码信息. */ public static final String param_respMsg = "respMsg"; // 新增四个报文字段merUserRegDt merUserEmail checkFlag activateStatus /** 商户端用户注册时间. */ public static final String param_merUserRegDt = "merUserRegDt"; /** 商户端用户注册邮箱. */ public static final String param_merUserEmail = "merUserEmail"; /** 验证标识. */ public static final String param_checkFlag = "checkFlag"; /** 开通状态. */ public static final String param_activateStatus = "activateStatus"; /** 加密证书ID. */ public static final String param_encryptCertId = "encryptCertId"; /** 用户MAC、IMEI串号、SSID. */ public static final String param_userMac = "userMac"; /** 关联交易. */ // public static final String param_relationTxnType = "relationTxnType"; /** 短信类型 */ public static final String param_smsType = "smsType"; /** 风控信息域 */ public static final String param_riskCtrlInfo = "riskCtrlInfo"; /** IC卡交易信息域 */ public static final String param_ICTransData = "ICTransData"; /** VPC交易信息域 */ public static final String param_VPCTransData = "VPCTransData"; /** 安全类型 */ public static final String param_securityType = "securityType"; /** 银联订单号 */ public static final String param_tn = "tn"; /** 分期付款手续费率 */ public static final String param_instalRate = "instalRate"; /** 分期付款手续费率 */ public static final String param_mchntFeeSubsidy = "mchntFeeSubsidy"; }
mit
joserobjr/CTFGameMods
src/main/java/br/com/gamemods/tutorial/ctf/CTFGameMods.java
131
package br.com.gamemods.tutorial.ctf; import org.bukkit.plugin.java.JavaPlugin; public class CTFGameMods extends JavaPlugin { }
mit
dperezmavro/courseworks_uni
year_3/large_scale_and_distributed_systems/src/CharCounterMain.java
1792
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CharCounterMain{ final static Charset enc = StandardCharsets.US_ASCII ; public CharCounterMain(String ch, String filedir){ if(ch.length() != 1){ System.out.println("The first argument needs to be a char, found string of length "+ch.length()); System.exit(1); } char c = ch.charAt(0); if( c != ' ' && c != '.' && Character.getNumericValue(c) < 97 && Character.getNumericValue(c) > 122 ){ //compare against the ascii integer values System.out.println("Need a character in range a-z (lowercase only) or a whitespace or a dot, found "+c+"!"); System.exit(1); } Path p = Paths.get(filedir); try { BufferedReader bf = Files.newBufferedReader(p,enc); String line; String line2 = null ; while((line = bf.readLine()) != null){ line2 += line ; } CharCounter cc = new CharCounter(c,line2); int freq = cc.getFrequency(); System.out.println(String.format("Frequency of character %c was %d", c,freq)); } catch (IOException e) { e.printStackTrace(); } System.out.println("Finished, exiting..."); } public static void main(String[] args){ if(args.length != 2){ System.out.println("Usage : CharCounterMain <char-to-look-for> <text-file-dir>"); }else{ new CharCounterMain(args[0],args[1]); } } }
mit
ivelin1936/Studing-SoftUni-
Programming Fundamentals/DataTypesAndVariables-Lab/src/com/company/Greeting.java
419
package com.company; import java.util.Scanner; public class Greeting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String firstName = scanner.nextLine(); String lastName = scanner.nextLine(); int age = Integer.parseInt(scanner.nextLine()); System.out.printf("Hello, %s %s. You are %d years old.", firstName, lastName, age); } }
mit
expositionrabbit/Sbahjsic-runtime
src/sbahjsic/runtime/Type.java
7839
package sbahjsic.runtime; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import sbahjsic.core.Warnings; import sbahjsic.core.Warnings.Level; import sbahjsic.runtime.Operator.BiOperator; import sbahjsic.runtime.Operator.UnOperator; import sbahjsic.runtime.Operator.VarargOperator; import sbahjsic.runtime.type.AnyType; import sbahjsic.runtime.type.SVoid; /** Describes a Sbahjsic type. * * <p>For all subclasses, there must only exist one instance. To enforce * this, this class implements final {@code equals()} and {@code hashCode()} * methods as they are defined in {@code Object}.*/ public abstract class Type { private final Map<String, Operator> operators = new HashMap<>(); private final Set<Type> supertypes = new HashSet<>(); private final Set<String> fields = new HashSet<>(); private final Map<String, Method> methods = new HashMap<>(); private int priority = 0; protected Type() { // Fixes a bug where AnyType tried to add AnyType.INSTANCE, which // was null at that point, to its own supertypes if(!getClass().equals(AnyType.class)) { addSupertype(AnyType.INSTANCE); } } /** Registers a new supertype for this type. * @param supertype the new supertype*/ public final void addSupertype(Type supertype) { if(getSupertypes().contains(supertype) || supertype.getSupertypes().contains(this)) { throw new RecursiveTypedefException(this.toString()); } if(this != supertype) { supertypes.add(supertype); } } /** Removes a supertype from this type if it exists. * @param supertype the supertype to remove*/ public final void removeSupertype(Type supertype) { supertypes.remove(supertype); } /** Registers an unary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addUnOperator(String op, UnOperator func) { operators.put(op, Operator.unaryOperator(func)); } /** Registers a binary operator for this type. * @param op the operator to register * @param func a function that applies this operator*/ public final void addBiOperator(String op, BiOperator func) { operators.put(op, Operator.binaryOperator(func)); } /** Adds an operator that can accept one or two arguments. * @param op the operator * @param unary the unary operator * @param binary the binary operator*/ protected final void addDoubleOperator(String op, UnOperator unary, BiOperator binary) { operators.put(op, (con, args) -> { if(args.length == 1) return unary.apply(con, args[0]); else if(args.length == 2) return binary.apply(con, args[0], args[1]); throw new OperatorCallException("Called with " + args.length + " arguments, expected 1 or 2"); }); } /** Registers a vararg operator for this type.*/ public void addVarargOperator(String op, VarargOperator func) { operators.put(op, Operator.varargOperator(func)); } /** Adds a field to this type. * @param field the field to add*/ protected final void addField(String field) { fields.add(field); } /** Returns a specific operator of this type. * @param op the operator to search * @return the operator matching {@code op} * @throws OperatorCallException if {@code op} isn't defined*/ public final Operator getOperator(String op) { if(operators.containsKey(op)) { return operators.get(op); } Operator operator = operatorLookup(op); if(operator == null) { throw new OperatorCallException("Operator " + op + " not defined on type " + getName()); } return operator; } private final Operator operatorLookup(String op) { for(Type supertype : supertypes) { if(supertype.operators.containsKey(op)) { return supertype.operators.get(op); } } for(Type supertype : supertypes) { Operator operator = supertype.operatorLookup(op); if(operator != null) { return operator; } } return null; } /** Returns a set of all defined operators of this type. * @return a set of the defined operators of this type*/ public final Set<String> getDefinedOperators() { Set<String> ops = new HashSet<>(); ops.addAll(operators.keySet()); for(Type supertype : getSupertypes()) { ops.addAll(supertype.getDefinedOperators()); } return ops; } /** Returns a set of the supertypes of this type. * @return a set of the supertypes of this type*/ public final Set<Type> getSupertypes() { Set<Type> types = new HashSet<>(); types.addAll(supertypes); for(Type supertype : supertypes) { types.addAll(supertype.getSupertypes()); } return types; } /** Returns the fields declared for this type. * @return a set of fields declared for this type*/ public final Set<String> getFields() { Set<String> allFields = new HashSet<>(); allFields.addAll(fields); for(Type supertype : getSupertypes()) { allFields.addAll(supertype.getFields()); } return allFields; } /** Adds a method to this type. * @param name the name of the method * @param method the method*/ public final void addMethod(String name, Method method) { methods.put(name, method); } /** Returns all methods defined for this type. * @return all methods defined for this type*/ public final Set<String> getMethods() { Map<String, Method> allMethods = new HashMap<>(); allMethods.putAll(methods); for(Type supertype : getSupertypes()) { allMethods.putAll(supertype.methods); } return allMethods.keySet(); } /** Returns a method of this type. * @param name the name of the method * @return the method * @throws MethodCallException if the method isn't defined for this type*/ public final Method getMethod(String name) { if(methods.containsKey(name)) { return methods.get(name); } Method method = methodLookup(name); if(method == null) { throw new MethodCallException("Method " + name + " not defined for type " + getName()); } return method; } private final Method methodLookup(String name) { for(Type supertype : supertypes) { if(supertype.methods.containsKey(name)) { return supertype.methods.get(name); } } for(Type supertype : supertypes) { Method method = supertype.methodLookup(name); if(method != null) { return method; } } return null; } /** Returns the name of this type. * @return the name of this type*/ public abstract String getName(); /** Casts a value to this type. * @param object the value to cast * @return the casted value*/ public SValue cast(SValue object) { Warnings.warn(Level.ADVICE, "Undefined cast from " + object.getType() + " to " + this); return object; } /** Returns whether this type is the subtype of some other type. That is * true if this type or any if its supertypes is the other type. * @param other the other type * @return whether this type is the subtype of the other type */ public boolean isSubtype(Type other) { return this.equals(other) || getSupertypes().contains(other); } /** Constructs an instance of this type * @param context the RuntimeContext * @param args the arguments passed to the constructor*/ public SValue construct(RuntimeContext context, SValue...args) { Warnings.warn(Level.NOTIFICATION, "Cannot instantiate " + getName()); return SVoid.VOID; } /** Returns the priority of this type, used to determine which operand * should choose the implementation of a binary operator. Defaults to zero.*/ public int priority() { return priority; } /** Sets the priority for this type.*/ public void setPriority(int p) { priority = p; } @Override public final boolean equals(Object o) { return super.equals(o); } @Override public final int hashCode() { return super.hashCode(); } @Override public final String toString() { return getName(); } }
mit
vladb55/SeptemberRepository
app/src/main/java/septemberpack/september/Asteroid.java
3547
package septemberpack.september; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Random; /** * Created by Vlady on 22.10.2015. */ /** * Данный класс реализует отрисовку астероидов */ public class Asteroid { Bitmap bitmap; /** * Координаты первого астероида */ private int line1x; private int line1y; /** * Координаты второго астероида */ private int line2x; private int line2y; /** * Координаты третьего астероида */ private int line3x; private int line3y; private Random random; /** * Конструктор получающий объект картинки будущего астероида и * задающий астероидам рандомные координаты * @param bmp - объект картинки астероида */ public Asteroid(Bitmap bmp){ this.bitmap = bmp; random = new Random(); line1x = random.nextInt(880); line2x = random.nextInt(880); line3x = random.nextInt(880); line1y = -random.nextInt(300); line2y = -random.nextInt(300) - 400; // За пределом экрана минус 400 line3y = -random.nextInt(300) - 800; // За пределом экрана минус 800 } /** * Метод отрисовки астероидов * @param canvas - прямоугольная область экрана для рисования */ public void draw(Canvas canvas){ canvas.drawBitmap(bitmap, line1x, line1y, null); // Первая линия canvas.drawBitmap(bitmap, line2x, line2y, null); // Вторая линия canvas.drawBitmap(bitmap, line3x, line3y, null); // Третья линия } /** * Метод обновляющий координаты астероидов и задающий новые координаты при уплытии за границы фона */ public void update(){ if(line1y > 1400) { line1y = -80; line1x = random.nextInt(880); } else if(line2y > 1400) { line2y = -80; line2x = random.nextInt(880); } else if(line3y > 1400) { line3y = -80; line3x = random.nextInt(880); } line1y += GamePanel.speed; line2y += GamePanel.speed; line3y += GamePanel.speed; } /* * Методы возвращают прямоугольную область астероида по его координатам, для проверки столкновения с кораблем * Реализацию можно было уместить в один метод с четырьмя параметрами, но его вызов был бы нечитаемым * Поскольку присутствуют всего три астероида, мы имеем возможность сделать для каждого свой метод */ public Rect getAsteroid1(){ return new Rect(line1x, line1y, line1x + 100, line1y + 120); } public Rect getAsteroid2(){ return new Rect(line2x, line2y, line2x + 100, line2y + 120); } public Rect getAsteroid3(){ return new Rect(line3x, line3y, line3x + 100, line3y + 120); } }
mit
Safewhere/kombit-web-java
Kombit.Samples.CH.WebsiteDemo/src/java/dk/itst/oiosaml/sp/service/SPFilter.java
12213
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <jre@trifork.com> * Rolf Njor Jensen <rolf@trifork.com> * Aage Nielsen <ani@openminds.dk> * */ package dk.itst.oiosaml.sp.service; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dk.itst.oiosaml.logging.Logger; import dk.itst.oiosaml.logging.LoggerFactory; import org.apache.commons.configuration.Configuration; import org.opensaml.DefaultBootstrap; import org.opensaml.xml.ConfigurationException; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.configuration.FileConfiguration; import dk.itst.oiosaml.configuration.SAMLConfiguration; import dk.itst.oiosaml.configuration.SAMLConfigurationFactory; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; import dk.itst.oiosaml.logging.Audit; import dk.itst.oiosaml.logging.Operation; import dk.itst.oiosaml.sp.UserAssertion; import dk.itst.oiosaml.sp.UserAssertionHolder; import dk.itst.oiosaml.sp.bindings.BindingHandler; import dk.itst.oiosaml.sp.develmode.DevelMode; import dk.itst.oiosaml.sp.develmode.DevelModeImpl; import dk.itst.oiosaml.sp.metadata.CRLChecker; import dk.itst.oiosaml.sp.metadata.IdpMetadata; import dk.itst.oiosaml.sp.metadata.SPMetadata; import dk.itst.oiosaml.sp.service.session.Request; import dk.itst.oiosaml.sp.service.session.SessionCleaner; import dk.itst.oiosaml.sp.service.session.SessionHandler; import dk.itst.oiosaml.sp.service.session.SessionHandlerFactory; import dk.itst.oiosaml.sp.service.util.Constants; /** * Servlet filter for checking if the user is authenticated. * * <p> * If the user is authenticated, a session attribute, * {@link Constants#SESSION_USER_ASSERTION} is set to contain a * {@link UserAssertion} representing the user. The application layer can access * this object to retrieve SAML attributes for the user. * </p> * * <p> * If the user is not authenticated, a &lt;AuthnRequest&gt; is created and sent * to the IdP. The protocol used for this is selected automatically based on th * available bindings in the SP and IdP metadata. * </p> * * <p> * The atual redirects are done by {@link BindingHandler} objects. * </p> * * <p> * Discovery profile is supported by looking at a request parameter named * _saml_idp. If the parameter does not exist, the browser is redirected to * {@link Constants#DISCOVERY_LOCATION}, which reads the domain cookie. If the * returned value contains ids, one of the ids is selected. If none of the ids * in the list is registered, an exception is thrown. If no value has been set, * the first configured IdP is selected automatically. * </p> * * @author Joakim Recht <jre@trifork.com> * @author Rolf Njor Jensen <rolf@trifork.com> * @author Aage Nielsen <ani@openminds.dk> */ public class SPFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(SPFilter.class); private CRLChecker crlChecker = new CRLChecker(); private boolean filterInitialized; private SAMLConfiguration conf; private String hostname; private SessionHandlerFactory sessionHandlerFactory; private AtomicBoolean cleanerRunning = new AtomicBoolean(false); private DevelMode develMode; /** * Static initializer for bootstrapping OpenSAML. */ static { try { DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { throw new WrappedException(Layer.DATAACCESS, e); } } public void destroy() { SessionCleaner.stopCleaner(); crlChecker.stopChecker(); if (sessionHandlerFactory != null) { sessionHandlerFactory.close(); } SessionHandlerFactory.Factory.close(); } /** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is * sent to the Login Site. * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); Boolean forceAuthn = false; if(request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if ((actualAssuranceLevel > 0) && (actualAssuranceLevel < assuranceLevel)) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } } protected void saveRequestAndGotoLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException { SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(request)); String protocol = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getSystemConfiguration().getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getSystemConfiguration().getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException("No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = request.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(request, hostname, relayState), response); } public void init(FilterConfig filterConfig) throws ServletException { conf = SAMLConfigurationFactory.getConfiguration(); if (conf.isConfigured()) { try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { develMode = new DevelModeImpl(); setConfiguration(conf); setFilterInitialized(true); return; } setRuntimeConfiguration(conf); setFilterInitialized(true); return; } catch (IllegalStateException e) { log.error("Unable to configure", e); } } setFilterInitialized(false); } private void setRuntimeConfiguration(Configuration conf) { restartCRLChecker(conf); setFilterInitialized(true); setConfiguration(conf); if (!IdpMetadata.getInstance().enableDiscovery()) { log.info("Discovery profile disabled, only one metadata file found"); } else { if (conf.getString(Constants.DISCOVERY_LOCATION) == null) { throw new IllegalStateException("Discovery location cannot be null when discovery profile is active"); } } setHostname(); sessionHandlerFactory = SessionHandlerFactory.Factory.newInstance(conf); sessionHandlerFactory.getHandler().resetReplayProtection(conf.getInt(Constants.PROP_NUM_TRACKED_ASSERTIONIDS)); log.info("Home url: " + conf.getString(Constants.PROP_HOME)); log.info("Assurance level: " + conf.getInt(Constants.PROP_ASSURANCE_LEVEL)); log.info("SP entity ID: " + SPMetadata.getInstance().getEntityID()); log.info("Base hostname: " + hostname); } private void setHostname() { String url = SPMetadata.getInstance().getDefaultAssertionConsumerService().getLocation(); setHostname(url.substring(0, url.indexOf('/', 8))); } private void restartCRLChecker(Configuration conf) { crlChecker.stopChecker(); int period = conf.getInt(Constants.PROP_CRL_CHECK_PERIOD, 600); if (period > 0) { crlChecker.startChecker(period, IdpMetadata.getInstance(), conf); } } public void setHostname(String hostname) { this.hostname = hostname; } public void setFilterInitialized(boolean b) { filterInitialized = b; } public boolean isFilterInitialized() { return filterInitialized; } public void setConfiguration(Configuration configuration) { SAMLConfigurationFactory.getConfiguration().setConfiguration(configuration); conf = SAMLConfigurationFactory.getConfiguration(); } public void setSessionHandlerFactory(SessionHandlerFactory sessionHandlerFactory) { this.sessionHandlerFactory = sessionHandlerFactory; } public void setDevelMode(DevelMode develMode) { this.develMode = develMode; } }
mit
zeljkot/fables-kotlin
jee/java/src/main/java/fables/kotlin/jee/rest/KittenRestService.java
1047
package fables.kotlin.jee.rest; import fables.kotlin.jee.business.KittenBusinessService; import fables.kotlin.jee.business.KittenEntity; import javax.inject.Inject; import javax.ws.rs.*; /** * JSON REST CRud service. * JEE will first create one noarg instance, and then injected instances. * * @author Zeljko Trogrlic */ @Path("kitten") public class KittenRestService { @Inject protected KittenBusinessService kittenBusinessService; @GET @Path("{id}") @Produces({"application/json"}) public KittenRest find( @PathParam("id") final int id ) { return kittenBusinessService .find(id) .map(kittenEntity -> new KittenRest(kittenEntity.getName(), kittenEntity.getCuteness())) .orElseThrow(() -> new NotFoundException("ID " + id + " not found")); } @POST @Produces({"application/json"}) public Integer add(KittenRest kittenRest) { KittenEntity kittenEntity = new KittenEntity(kittenRest.getName(), kittenRest.getCuteness()); return kittenBusinessService.add(kittenEntity); } }
mit
SunnyLy/LocalImageChoose
multi-image-selector/src/main/java/me/nereo/multi_image_selector/ClipPhotoActivity.java
11258
package me.nereo.multi_image_selector; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.AbstractDraweeController; import com.facebook.drawee.drawable.ProgressBarDrawable; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import java.io.File; import me.nereo.multi_image_selector.view.ClipImageBorderView; import me.nereo.multi_image_selector.view.zoomable.DefaultZoomableController; import me.nereo.multi_image_selector.view.zoomable.ZoomableDraweeView; /** * Created by sunny on 2015/12/22. * 图片裁剪 */ public class ClipPhotoActivity extends Activity implements OnClickListener, IBitmapShow { public static final String TAG = ClipPhotoActivity.class.getSimpleName(); private String imgUrl; private TextView mTitle; private Button mCommit; private ImageView mBack; private ZoomableDraweeView mGestureImageView; private ClipImageBorderView clip_image_borderview; //图片的平移与缩放 float mCurrentScale; float last_x = -1; float last_y = -1; boolean move = false; public static void startClipPhotoActivity(Context context, String uri) { Intent targetIntent = new Intent(context, ClipPhotoActivity.class); targetIntent.putExtra(TAG, uri); context.startActivity(targetIntent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clip_photo); setTitle("图片裁剪"); initIntentParams(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); /* new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { getBitmap(); } },100);*/ getBitmap(); } private void getBitmap() { int width = clip_image_borderview.getWidth(); int height = clip_image_borderview.getHeight(); Log.e("with", "with===" + width + "\nheight===" + height); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; /* FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(screenWidth - 40, screenWidth - 40); layoutParams.gravity = Gravity.CENTER; mGestureImageView.setLayoutParams(layoutParams);*/ if (!TextUtils.isEmpty(imgUrl)) { // ImageLoaderUtils.load(imgUrl,mGestureImageView); //解决图片倒置 ImageRequest imageRequest = ImageRequestBuilder .newBuilderWithSource(Uri.parse("file://" + imgUrl)) .setAutoRotateEnabled(true).build(); //解决图片多指缩放 DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .setTapToRetryEnabled(true) .build(); /* DefaultZoomableController controller = DefaultZoomableController.newInstance(); controller.setEnabled(true);*/ GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources()) .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER) .setProgressBarImage(new ProgressBarDrawable()) .build(); mGestureImageView.setController(controller); mGestureImageView.setHierarchy(hierarchy); //图片等比例缩放 // getAvatarBitmap(imageRequest, controller, hierarchy, ClipPhotoActivity.this); } } @Override public void onContentChanged() { mTitle = (TextView) findViewById(R.id.photo_title); mGestureImageView = (ZoomableDraweeView) findViewById(R.id.gesture_iv); mBack = (ImageView) findViewById(R.id.btn_back); mBack.setOnClickListener(this); clip_image_borderview = (ClipImageBorderView) findViewById(R.id.clip_image_borderview); mCommit = (Button) findViewById(R.id.commit); mCommit.setOnClickListener(this); } @Override public void setTitle(CharSequence title) { mTitle.setText(title); } private void initIntentParams() { Intent mIntent = getIntent(); if (mIntent != null) { imgUrl = mIntent.getStringExtra(TAG); } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_back) { finish(); } else if (id == R.id.commit) { if (mGestureImageView != null) { Bitmap bm = mGestureImageView.clip(); Log.e("bm", "bm:" + bm.toString()); Intent resultIntent = new Intent(); Bundle mBundle = new Bundle(); mBundle.putParcelable(TAG, bm); resultIntent.putExtras(mBundle); setResult(101, resultIntent); finish(); } } } private void getAvatarBitmap(ImageRequest imageRequest, final DefaultZoomableController controller, final GenericDraweeHierarchy hierarchy, final IBitmapShow callback) { ImagePipeline imagePipeline = Fresco.getImagePipeline(); DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, ClipPhotoActivity.this); dataSource.subscribe(new BaseBitmapDataSubscriber() { @Override protected void onNewResultImpl(@Nullable Bitmap bitmap) { if (bitmap != null) { if (callback != null) { callback.onBitmapLoadedSuccess(bitmap, controller, hierarchy); } } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { } }, CallerThreadExecutor.getInstance()); } @Override public void onBitmapLoadedSuccess(Bitmap bm, DefaultZoomableController controller, GenericDraweeHierarchy hierarchy) { int bmWidth = bm.getWidth(); int bmHeight = bm.getHeight(); int newWidth = clip_image_borderview.getWidth() == 0 ? 200 : clip_image_borderview.getWidth(); int newHeight = clip_image_borderview.getHeight() == 0 ? 200 : clip_image_borderview.getHeight(); Log.e("bmWidth", "bmWidth:" + bmWidth + ",\nbmHeight:" + bmHeight + ",\nnewWidth:" + newWidth + ",\nnewHeight:" + newHeight); float scaleWidth = ((float) newWidth) / bmWidth; float scaleHeight = ((float) newHeight) / bmHeight; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, bmWidth, bmHeight, matrix, true); mGestureImageView.setZoomableController(controller); mGestureImageView.setHierarchy(hierarchy); mGestureImageView.setImageBitmap(newBm); mGestureImageView.setOnTouchListener(new View.OnTouchListener() { float baseValue = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: float x = last_x = event.getRawX(); float y = last_y = event.getRawY(); move = false; break; case MotionEvent.ACTION_MOVE: if (event.getPointerCount() == 2) { //双指 float x1 = event.getX(0) - event.getX(1); float y1 = event.getY(0) - event.getY(1); //计算2点之间的距离 float value = (float) Math.sqrt(x1 * x1 + y1 * y1); if (baseValue == 0) { baseValue = value; } else { //由2点之间的距离来计算缩放比例 if ((value - baseValue) >= 10 || (baseValue - value) >= 10) { float scale = value / baseValue; img_scale(scale); } } } else if (event.getPointerCount() == 1) { //单指 float x2 = event.getRawX(); float y2 = event.getRawY(); x2 -= last_x; y2 -= last_y; if (x2 >= 10 || y2 >= 10 || x2 <= -10 || y2 <= -10) { img_translate(x2, y2); last_x = event.getRawX(); last_y = event.getRawY(); } } break; } return false; } }); } /** * 平移 * * @param x2 * @param y2 */ private void img_translate(float x2, float y2) { if (mGestureImageView != null) mGestureImageView.img_translate(x2, y2); } /** * 缩放 * * @param scale */ private void img_scale(float scale) { if (mGestureImageView != null) { mGestureImageView.img_scale(scale); } } }
mit
sheng-xiaoya/YakerWeather
app/src/test/java/wanghaisheng/com/yakerweather/ExampleUnitTest.java
322
package wanghaisheng.com.yakerweather; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
IngSW-unipv/GoldRush
GoldRush/src/goldrush/BoniMichele.java
932
/* * Code used in the "Software Engineering" course. * * Copyright 2017 by Claudio Cusano (claudio.cusano@unipv.it) * Dept of Electrical, Computer and Biomedical Engineering, * University of Pavia. */ package goldrush; /** * @author Reina Michele cl418656 * @author Bonissone Davidecl427113 */ public class BoniMichele extends GoldDigger{ // int t=0; int j=99; @Override public int chooseDiggingSite(int[] distances) { for (int i=0; i<distances.length; i++){ if (t==0){ if (distances[i]==140) { j=i; t++; } } else if (t<3) { if (distances[i]== 30) { j=i; t=0; } } else { if (distances[i]== 200) { j=i; t=0; } } } return j; } }
mit
DocuWare/PlatformJavaClient
src/com/docuware/dev/Extensions/EasyCheckoutResult.java
949
/* * 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 com.docuware.dev.Extensions; import java.io.Closeable; import java.io.InputStream; /** * * @author Patrick */ public class EasyCheckoutResult implements Closeable { private String EncodedFileName; public String getEncodedFileName() { return EncodedFileName; } void setEncodedFileName(String data) { EncodedFileName = data; } private DeserializedHttpResponseGen<InputStream> response; public DeserializedHttpResponseGen<InputStream> getResponse() { return response; } void setResponse(DeserializedHttpResponseGen<InputStream> data) { response = data; } @Override public void close() { this.response.close(); } }
mit
Milanvdm/MedicalLSTM
src/main/java/experiments/State2VecTest.java
4075
package experiments; import java.io.File; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import datahandler.word2vec.MedicalSequenceIterator; import state2vec.State2Vec; public class State2VecTest { protected static final Logger logger = LoggerFactory.getLogger(State2VecTest.class); public State2VecTest(File file, String run) throws Exception { List<Integer> windowSizes; List<Double> learningRates; if(run.equals("0")){ logger.info("Run 0"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.025, 0.1); } else if(run.equals("1")) { logger.info("Run 1"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.1); } else if(run.equals("2")) { logger.info("Run 2"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.025); } else if(run.equals("3")) { logger.info("Run 3"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.1); } else if(run.equals("4")) { logger.info("Run 4"); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.025); } else { logger.info("Run " + run); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.1); } //List<Integer> windowSizes = Arrays.asList(5, 10, 15); //List<Double> learningRates = Arrays.asList(0.025, 0.1); List<Integer> vectorLengths = Arrays.asList(50, 100); List<Integer> minWordFreqs = Arrays.asList(5, 10); int batchsize = 500; int epoch = 1; MedicalSequenceIterator<StateImpl> sequenceIterator = new MedicalSequenceIterator<StateImpl>(file, false); for(int windowSize: windowSizes) { for(double learningRate: learningRates) { for(int vectorLength: vectorLengths) { for(int minWordFreq: minWordFreqs) { logger.info("STATE2VEC - EXPERIMENT"); logger.info(""); logger.info("==PARAMETERS=="); logger.info("windowSize: " + windowSize); logger.info("learningRate: " + learningRate); logger.info("vectorLength: " + vectorLength); logger.info("batchSize: " + batchsize); logger.info("epoch: " + epoch); logger.info("minWordFreq: " + minWordFreq); logger.info(""); sequenceIterator.reset(); State2Vec state2vec = new State2Vec(); state2vec.trainSequenceVectors(sequenceIterator, windowSize, learningRate, vectorLength, batchsize, epoch, minWordFreq); List<Integer> ks = Arrays.asList(100, 1000, 5000); ClusterSeqTest clusterTest = new ClusterSeqTest(); for(int k: ks) { ResultWriter writer1 = new ResultWriter("State2Vec - ", "Cluster1Test"); writer1.writeLine("STATE2VEC - EXPERIMENT"); writer1.writeLine(""); writer1.writeLine("==PARAMETERS=="); writer1.writeLine("windowSize: " + windowSize); writer1.writeLine("learningRate: " + learningRate); writer1.writeLine("vectorLength: " + vectorLength); writer1.writeLine("batchSize: " + batchsize); writer1.writeLine("epoch: " + epoch); writer1.writeLine("minWordFreq: " + minWordFreq); writer1.writeLine(""); clusterTest.checkClusters1(state2vec.getTrainedModel(), k, writer1); ResultWriter writer2 = new ResultWriter("State2Vec - ", "Cluster2Test"); writer2.writeLine("STATE2VEC - EXPERIMENT"); writer2.writeLine(""); writer2.writeLine("==PARAMETERS=="); writer2.writeLine("windowSize: " + windowSize); writer2.writeLine("learningRate: " + learningRate); writer2.writeLine("vectorLength: " + vectorLength); writer2.writeLine("batchSize: " + batchsize); writer2.writeLine("epoch: " + epoch); writer2.writeLine("minWordFreq: " + minWordFreq); writer2.writeLine(""); clusterTest.checkClusters2(state2vec.getTrainedModel(), k, writer2); } } } } } } }
mit
LV-eMeS/eMeS_Libraries
src/main/java/lv/emes/libraries/utilities/validation/MS_ValidationError.java
706
package lv.emes.libraries.utilities.validation; /** * Actions for error that occur in validation process. * * @author eMeS * @version 1.2. */ public interface MS_ValidationError<T> { MS_ValidationError withErrorMessageFormingAction(IFuncFormValidationErrorMessage action); /** * Returns message of validation error using pre-defined method to form message. * @return formatted message describing essence of this particular validation error. */ String getMessage(); Integer getNumber(); T getObject(); /** * @param object an object to validate. * @return reference to validation error itself. */ MS_ValidationError withObject(T object); }
mit
good2000mo/OpenClassicAPI
src/main/java/ch/spacebase/openclassic/api/HeartbeatManager.java
5720
package ch.spacebase.openclassic.api; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import ch.spacebase.openclassic.api.util.Constants; /** * Manages the server's web heartbeats. */ public final class HeartbeatManager { private static final long salt = new SecureRandom().nextLong(); private static final Map<String, Runnable> customBeats = new HashMap<String, Runnable>(); private static String url = ""; /** * Gets the server's current salt. * @return The server's salt. */ public static long getSalt() { return salt; } /** * Gets the server's minecraft.net url. * @return The url. */ public static String getURL() { return url; } /** * Sets the server's known minecraft.net url. * @param url The url. */ public static void setURL(String url) { HeartbeatManager.url = url; } /** * Triggers a heartbeat. */ public static void beat() { mineBeat(); womBeat(); for(String id : customBeats.keySet()) { try { customBeats.get(id).run(); } catch(Exception e) { OpenClassic.getLogger().severe("Exception while running a custom heartbeat with the ID \"" + id + "\"!"); e.printStackTrace(); } } } /** * Adds a custom heartbeat to run when {@link beat()} is called. * @param id ID of the custom heartbeat. * @param run Runnable to call when beating. */ public static void addBeat(String id, Runnable run) { customBeats.put(id, run); } /** * Removes a custom heartbeat. * @param id ID of the heartbeat. */ public static void removeBeat(String id) { customBeats.remove(id); } /** * Clears the custom heartbeat list. */ public static void clearBeats() { customBeats.clear(); } private static void mineBeat() { URL url = null; try { url = new URL("https://minecraft.net/heartbeat.jsp?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size()); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting minecraft.net heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat: Connection doesn't support GET...?"); return; } conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String result = reader.readLine(); reader.close(); input.close(); if(!HeartbeatManager.url.equals(result)) { HeartbeatManager.url = result; OpenClassic.getLogger().info(Color.GREEN + "The server's URL is now \"" + getURL() + "\"."); try { File file = new File(OpenClassic.getGame().getDirectory(), "server-address.txt"); if(!file.exists()) file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(result); writer.close(); } catch(IOException e) { OpenClassic.getLogger().severe("Failed to save server address!"); e.printStackTrace(); } } } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } private static void womBeat() { URL url = null; try { url = new URL("http://direct.worldofminecraft.com/hb.php?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size() + "&noforward=1"); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting WOM heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setDoInput(false); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing WOM heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }
mit
jaubin/gojulutils
src/main/java/org/gojul/gojulutils/data/GojulPair.java
2277
package org.gojul.gojulutils.data; /** * Class {@code GojulPair} is a simple stupid pair class. This class is notably necessary * when emulating JOIN in database and such a class does not exist natively in the JDK. * This object is immutable as long as the object it contains are immutable. Since * this object is not serializable it should not be stored in objects which could be serialized, * especially Java HttpSession objects. * * @param <S> the type of the first object of the pair. * @param <T> the type of the second object of the pair. * @author jaubin */ public final class GojulPair<S, T> { private final S first; private final T second; /** * Constructor. Both parameters are nullable. Note that this constructor * does not perform any defensive copy as it is not possible there. * * @param first the first object. * @param second the second object. */ public GojulPair(final S first, final T second) { this.first = first; this.second = second; } /** * Return the first object. * * @return the first object. */ public S getFirst() { return first; } /** * Return the second object. * * @return the second object. */ public T getSecond() { return second; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GojulPair<?, ?> pair = (GojulPair<?, ?>) o; if (getFirst() != null ? !getFirst().equals(pair.getFirst()) : pair.getFirst() != null) return false; return getSecond() != null ? getSecond().equals(pair.getSecond()) : pair.getSecond() == null; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getFirst() != null ? getFirst().hashCode() : 0; result = 31 * result + (getSecond() != null ? getSecond().hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "GojulPair{" + "first=" + first + ", second=" + second + '}'; } }
mit
augustt198/lumen
src/test/java/me/august/lumen/data/DataTest.java
1850
package me.august.lumen.data; import me.august.lumen.compile.resolve.data.ClassData; import me.august.lumen.compile.resolve.lookup.DependencyManager; import org.junit.Assert; import org.junit.Test; public class DataTest { @Test public void testClassData() { ClassData data = ClassData.fromClass(String.class); Assert.assertEquals( String.class.getName(), data.getName() ); String[] expected = new String[]{ "java.io.Serializable", "java.lang.Comparable", "java.lang.CharSequence" }; Assert.assertArrayEquals( expected, data.getInterfaces() ); } @Test public void testAssignableTo() { DependencyManager deps = new DependencyManager(); ClassData data; data = ClassData.fromClass(String.class); Assert.assertTrue( "Expected String to be assignable to String", data.isAssignableTo("java.lang.String", deps) ); Assert.assertTrue( "Expected String to be assignable to Object", data.isAssignableTo("java.lang.Object", deps) ); Assert.assertTrue( "Expected String to be assignable to CharSequence", data.isAssignableTo("java.lang.CharSequence", deps) ); data = ClassData.fromClass(Object.class); Assert.assertFalse( "Expected Object to not be assignable to String", data.isAssignableTo("java.lang.String", deps) ); data = ClassData.fromClass(CharSequence.class); Assert.assertTrue( "Expected CharSequence to be assignable to Object", data.isAssignableTo("java.lang.Object", deps) ); } }
mit
leiasousa/MySim
src/ons/PhysicalTopology.java
6858
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ons; import ons.util.WeightedGraph; import org.w3c.dom.*; /** * The physical topology of a network refers to he physical layout of devices on * a network, or to the way that the devices on a network are arranged and how * they communicate with each other. * * @author andred */ public abstract class PhysicalTopology { protected int nodes; protected int links; protected OXC[] nodeVector; protected Link[] linkVector; protected Link[][] adjMatrix; /** * Creates a new PhysicalTopology object. Takes the XML file containing all * the information about the simulation environment and uses it to populate * the PhysicalTopology object. The physical topology is basically composed * of nodes connected by links, each supporting different wavelengths. * * @param xml file that contains the simulation environment information */ public PhysicalTopology(Element xml) { try { if (Simulator.verbose) { System.out.println(xml.getAttribute("name")); } } catch (Throwable t) { t.printStackTrace(); } } /** * Retrieves the number of nodes in a given PhysicalTopology. * * @return the value of the PhysicalTopology's nodes attribute */ public int getNumNodes() { return nodes; } /** * Retrieves the number of links in a given PhysicalTopology. * * @return number of items in the PhysicalTopology's linkVector attribute */ public int getNumLinks() { return linkVector.length; } /** * Retrieves a specific node in the PhysicalTopology object. * * @param id the node's unique identifier * @return specified node from the PhysicalTopology's nodeVector */ public OXC getNode(int id) { return nodeVector[id]; } /** * Retrieves a specific link in the PhysicalTopology object, based on its * unique identifier. * * @param linkid the link's unique identifier * @return specified link from the PhysicalTopology's linkVector */ public Link getLink(int linkid) { return linkVector[linkid]; } /** * Retrieves a specific link in the PhysicalTopology object, based on its * source and destination nodes. * * @param src the link's source node * @param dst the link's destination node * @return the specified link from the PhysicalTopology's adjMatrix */ public Link getLink(int src, int dst) { return adjMatrix[src][dst]; } /** * Retrives a given PhysicalTopology's adjancency matrix, which contains the * links between source and destination nodes. * * @return the PhysicalTopology's adjMatrix */ public Link[][] getAdjMatrix() { return adjMatrix; } /** * Says whether exists or not a link between two given nodes. * * @param node1 possible link's source node * @param node2 possible link's destination node * @return true if the link exists in the PhysicalTopology's adjMatrix */ public boolean hasLink(int node1, int node2) { if (adjMatrix[node1][node2] != null) { return true; } else { return false; } } /** * Checks if a path made of links makes sense by checking its continuity * * @param links to be checked * @return true if the link exists in the PhysicalTopology's adjMatrix */ public boolean checkLinkPath(int links[]) { for (int i = 0; i < links.length - 1; i++) { if (!(getLink(links[i]).dst == getLink(links[i + 1]).src)) { return false; } } return true; } /** * Returns a weighted graph with vertices, edges and weights representing * the physical network nodes, links and weights implemented by this class * object. * * @return an WeightedGraph class object */ public WeightedGraph getWeightedGraph() { WeightedGraph g = new WeightedGraph(nodes); for (int i = 0; i < nodes; i++) { for (int j = 0; j < nodes; j++) { if (hasLink(i, j)) { g.addEdge(i, j, getLink(i, j).getWeight()); } } } return g; } /** * * */ public void printXpressInputFile() { // Edges System.out.println("EDGES: ["); for (int i = 0; i < this.getNumNodes(); i++) { for (int j = 0; j < this.getNumNodes(); j++) { if (this.hasLink(i, j)) { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 1"); } else { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 0"); } } } System.out.println("]"); System.out.println(); // SD Pairs System.out.println("TRAFFIC: ["); for (int i = 0; i < this.getNumNodes(); i++) { for (int j = 0; j < this.getNumNodes(); j++) { if (i != j) { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 1"); } else { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 0"); } } } System.out.println("]"); } /** * Prints all nodes and links between them in the PhysicalTopology object. * * @return string containing the PhysicalTopology's adjMatrix values */ @Override public String toString() { String topo = ""; for (int i = 0; i < nodes; i++) { for (int j = 0; j < nodes; j++) { if (adjMatrix[i][j] != null) { topo += adjMatrix[i][j].toString() + "\n\n"; } } } return topo; } public abstract void createPhysicalLightpath(LightPath lp); public abstract void removePhysicalLightpath(LightPath lp); public abstract boolean canCreatePhysicalLightpath(LightPath lp); public abstract double getBW(LightPath lp); public abstract double getBWAvailable(LightPath lp); public abstract boolean canAddFlow(Flow flow, LightPath lightpath); public abstract void addFlow(Flow flow, LightPath lightpath); public abstract void addBulkData(BulkData bulkData, LightPath lightpath); public abstract void removeFlow(Flow flow, LightPath lightpath); public abstract boolean canAddBulkData(BulkData bulkData, LightPath lightpath); }
mit
StoyanVitanov/SoftwareUniversity
Java Fundamentals/Java OOP Advanced/08.ObjectCommunication&Events/exercise/task5_kingsGambitExtended/utils/MessegeLogger.java
170
package exercise.task5_kingsGambitExtended.utils; public class MessegeLogger { public static void log(String message){ System.out.println(message); } }
mit
abforce/Dino-Runner
app/src/main/java/ir/abforce/dinorunner/custom/SPixelPerfectSprite.java
544
package ir.abforce.dinorunner.custom; import com.makersf.andengine.extension.collisions.entity.sprite.PixelPerfectSprite; import com.makersf.andengine.extension.collisions.opengl.texture.region.PixelPerfectTextureRegion; import ir.abforce.dinorunner.managers.RM; /** * Created by Ali Reza on 9/4/15. */ public class SPixelPerfectSprite extends PixelPerfectSprite { public SPixelPerfectSprite(float pX, float pY, PixelPerfectTextureRegion pTextureRegion) { super(pX, pY, pTextureRegion, RM.VBO); setScale(RM.S); } }
mit
devsunny/app-galleries
batch-flow-process/src/main/java/com/asksunny/batch/tasklets/Demo1.java
341
package com.asksunny.batch.tasklets; public class Demo1 { long id; String name; public Demo1() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
mit
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/net/codec/play/game/UpdateBlockEntityCodec.java
1140
package net.glowstone.net.codec.play.game; import com.flowpowered.network.Codec; import io.netty.buffer.ByteBuf; import java.io.IOException; import net.glowstone.net.GlowBufUtils; import net.glowstone.net.message.play.game.UpdateBlockEntityMessage; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.util.BlockVector; public final class UpdateBlockEntityCodec implements Codec<UpdateBlockEntityMessage> { @Override public UpdateBlockEntityMessage decode(ByteBuf buffer) throws IOException { BlockVector pos = GlowBufUtils.readBlockPosition(buffer); int action = buffer.readByte(); CompoundTag nbt = GlowBufUtils.readCompound(buffer); return new UpdateBlockEntityMessage(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), action, nbt); } @Override public ByteBuf encode(ByteBuf buf, UpdateBlockEntityMessage message) throws IOException { GlowBufUtils.writeBlockPosition(buf, message.getX(), message.getY(), message.getZ()); buf.writeByte(message.getAction()); GlowBufUtils.writeCompound(buf, message.getNbt()); return buf; } }
mit
jlpuma24/colector-android-telecomsoftsrs
app/src/main/java/co/colector/model/request/SendSurveyRequest.java
2516
package co.colector.model.request; import java.util.ArrayList; import java.util.List; import co.colector.ColectorApplication; import co.colector.R; import co.colector.model.IdInputValue; import co.colector.model.IdValue; import co.colector.model.Survey; import co.colector.model.AnswerValue; import co.colector.session.AppSession; import co.colector.utils.NetworkUtils; /** * Created by dherrera on 11/10/15. */ public class SendSurveyRequest { private String colector_id; private String form_id; private String longitud; private String latitud; private String horaini; private String horafin; private List<IdInputValue> responses; public SendSurveyRequest(Survey survey) { this.colector_id = String.valueOf(AppSession.getInstance().getUser().getColector_id()); this.form_id = String.valueOf(survey.getForm_id()); this.longitud = survey.getInstanceLongitude(); this.latitud = survey.getInstanceLatitude(); this.horaini = survey.getInstanceHoraIni(); this.horafin = survey.getInstanceHoraFin(); this.setResponsesData(survey.getInstanceAnswers()); } public List<IdInputValue> getResponses() { return responses; } public void setResponses(List<IdInputValue> responses) { this.responses = responses; } private void setResponsesData(List<IdValue> responsesData) { responses = new ArrayList<>(); for (IdValue item : responsesData) { switch (item.getmType()) { case 6: case 14: case 16: for (AnswerValue answerValue : item.getValue()) if (!answerValue.getValue().equals("")) { int lastIndex = answerValue.getValue().length(); int slashIndex = answerValue.getValue().lastIndexOf("/"); responses.add(new IdInputValue(String.valueOf(item.getId()), ColectorApplication.getInstance().getString(R.string.image_name_format, NetworkUtils.getAndroidID(ColectorApplication.getInstance()), answerValue.getValue().substring((slashIndex + 1), lastIndex)))); } break; default: for (AnswerValue answerValue : item.getValue()) responses.add(new IdInputValue(String.valueOf(item.getId()), answerValue.getValue())); } } } }
mit
Team-2502/UpdatedRobotCode2017
src/com/team2502/robot2017/command/autonomous/ShinyFollow.java
267
package com.team2502.robot2017.command.autonomous; import edu.wpi.first.wpilibj.command.CommandGroup; public class ShinyFollow extends CommandGroup { /** * Does a follow */ public ShinyFollow() { addSequential(new AutoVisionCommand(200, 0.3)); } }
mit
caelum/rest-client
rest-server-gae/src/br/com/caelum/rest/server/SimpleAction.java
638
package br.com.caelum.rest.server; import javax.servlet.http.HttpServletRequest; public class SimpleAction implements Action { public String getUri() { return uri; } public String getRel() { return rel; } private final String uri; private final String rel; public SimpleAction(String rel, String uri) { this.rel = rel; this.uri = uri; } public SimpleAction(String rel, HttpServletRequest request, String uri) { this.rel = rel; this.uri = "http://restful-server.appspot.com" + uri; // this.uri = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + uri; } }
mit
qq137712630/MeiZiNews
app/src/main/java/com/ms/meizinewsapplication/features/meizi/model/DbGroupBreastModel.java
1004
package com.ms.meizinewsapplication.features.meizi.model; import android.content.Context; import com.ms.meizinewsapplication.features.base.pojo.ImgItem; import com.ms.retrofitlibrary.web.MyOkHttpClient; import org.loader.model.OnModelListener; import java.util.List; import rx.Observable; import rx.Subscription; /** * Created by 啟成 on 2016/3/15. */ public class DbGroupBreastModel extends DbGroupModel { private String pager_offset; public Subscription loadWeb(Context context, OnModelListener<List<ImgItem>> listener, String pager_offset) { this.pager_offset = pager_offset; return loadWeb(context, listener); } @Override protected Subscription reSubscription(Context context, OnModelListener<List<ImgItem>> listener) { Observable<String> dbGroupBreast = getDbGroup().RxDbGroupBreast( MyOkHttpClient.getCacheControl(context), pager_offset ); return rxDbGroup(dbGroupBreast, listener); } }
mit
Syncano/syncano-android-demo
Eclipse/SyncanoLib/src/com/syncano/android/lib/modules/users/ParamsUserNew.java
1864
package com.syncano.android.lib.modules.users; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.syncano.android.lib.modules.Params; import com.syncano.android.lib.modules.Response; /** * Params to create new user. */ public class ParamsUserNew extends Params { /** Name of user */ @Expose @SerializedName(value = "user_name") private String userName; /** Nickname of user */ @Expose private String nick; /** Avatar base64 for user */ @Expose private String avatar; /** User's password. */ @Expose @SerializedName(value = "password") private String password; /** * @param userName * User name defining user. Can be <code>null</code>. */ public ParamsUserNew(String userName) { setUserName(userName); } @Override public String getMethodName() { return "user.new"; } public Response instantiateResponse() { return new ResponseUserNew(); } /** * @return user name */ public String getUserName() { return userName; } /** * Sets user name * * @param user_name * user name */ public void setUserName(String userName) { this.userName = userName; } /** * @return user nickname */ public String getNick() { return nick; } /** * Sets user nickname * * @param nick * nickname */ public void setNick(String nick) { this.nick = nick; } /** * @return avatar base64 */ public String getAvatar() { return avatar; } /** * Sets avatar base64 * * @param avatar * avatar base64 */ public void setAvatar(String avatar) { this.avatar = avatar; } /** * @return password */ public String getPassword() { return password; } /** * @param Sets * user password */ public void setPassword(String password) { this.password = password; } }
mit
V2GClarity/RISE-V2G
RISE-V2G-EVCC/src/main/java/com/v2gclarity/risev2g/evcc/states/WaitForAuthorizationRes.java
4963
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 - 2019 Dr. Marc Mültin (V2G Clarity) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ package com.v2gclarity.risev2g.evcc.states; import java.util.concurrent.TimeUnit; import com.v2gclarity.risev2g.evcc.session.V2GCommunicationSessionEVCC; import com.v2gclarity.risev2g.shared.enumerations.GlobalValues; import com.v2gclarity.risev2g.shared.enumerations.V2GMessages; import com.v2gclarity.risev2g.shared.messageHandling.ReactionToIncomingMessage; import com.v2gclarity.risev2g.shared.messageHandling.TerminateSession; import com.v2gclarity.risev2g.shared.misc.TimeRestrictions; import com.v2gclarity.risev2g.shared.utils.SecurityUtils; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.AuthorizationReqType; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.AuthorizationResType; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ChargeParameterDiscoveryReqType; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.EVSEProcessingType; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.PaymentOptionType; import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.V2GMessage; public class WaitForAuthorizationRes extends ClientState { public WaitForAuthorizationRes(V2GCommunicationSessionEVCC commSessionContext) { super(commSessionContext); } @Override public ReactionToIncomingMessage processIncomingMessage(Object message) { if (isIncomingMessageValid(message, AuthorizationResType.class)) { V2GMessage v2gMessageRes = (V2GMessage) message; AuthorizationResType authorizationRes = (AuthorizationResType) v2gMessageRes.getBody().getBodyElement().getValue(); if (authorizationRes.getEVSEProcessing() == null) return new TerminateSession("EVSEProcessing parameter of AuthorizationRes is null. Parameter is mandatory."); if (authorizationRes.getEVSEProcessing().equals(EVSEProcessingType.FINISHED)) { getLogger().debug("EVSEProcessing was set to FINISHED"); getCommSessionContext().setOngoingTimer(0L); getCommSessionContext().setOngoingTimerActive(false); ChargeParameterDiscoveryReqType chargeParameterDiscoveryReq = getChargeParameterDiscoveryReq(); /* * Save this request in case the ChargeParameterDiscoveryRes indicates that the EVSE is * still processing. Then this request can just be resent instead of asking the EV again. */ getCommSessionContext().setChargeParameterDiscoveryReq(chargeParameterDiscoveryReq); return getSendMessage(chargeParameterDiscoveryReq, V2GMessages.CHARGE_PARAMETER_DISCOVERY_RES); } else { getLogger().debug("EVSEProcessing was set to ONGOING"); long elapsedTimeInMs = 0; if (getCommSessionContext().isOngoingTimerActive()) { long elapsedTime = System.nanoTime() - getCommSessionContext().getOngoingTimer(); elapsedTimeInMs = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS); if (elapsedTimeInMs > TimeRestrictions.V2G_EVCC_ONGOING_TIMEOUT) return new TerminateSession("Ongoing timer timed out for AuthorizationReq"); } else { getCommSessionContext().setOngoingTimer(System.nanoTime()); getCommSessionContext().setOngoingTimerActive(true); } // [V2G2-684] demands to send an empty AuthorizationReq if the field EVSEProcessing is set to 'Ongoing' AuthorizationReqType authorizationReq = getAuthorizationReq(null); return getSendMessage(authorizationReq, V2GMessages.AUTHORIZATION_RES, Math.min((TimeRestrictions.V2G_EVCC_ONGOING_TIMEOUT - (int) elapsedTimeInMs), TimeRestrictions.getV2gEvccMsgTimeout(V2GMessages.AUTHORIZATION_RES))); } } else { return new TerminateSession("Incoming message raised an error"); } } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/ContactFolderCollectionResponse.java
765
// Template Source: BaseEntityCollectionResponse.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.ContactFolder; import com.microsoft.graph.http.BaseCollectionResponse; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Contact Folder Collection Response. */ public class ContactFolderCollectionResponse extends BaseCollectionResponse<ContactFolder> { }
mit
anotheria/configureme
src/examples/pricing/ShowPrice.java
989
package pricing; import org.configureme.ConfigurationManager; import org.configureme.Environment; import org.configureme.GlobalEnvironment; import org.configureme.environments.DynamicEnvironment; public class ShowPrice { public static void main(String a[]){ showPrice(); showPriceIn("USA", GlobalEnvironment.INSTANCE); showPriceIn("United Kingdom", new DynamicEnvironment("europe", "uk")); showPriceIn("Germany", new DynamicEnvironment("europe", "de")); showPriceIn("Austria", new DynamicEnvironment("europe", "at")); } private static void showPriceIn(String description, Environment environment){ Pricing pricing = new Pricing(); ConfigurationManager.INSTANCE.configure(pricing, environment); System.out.println("Price in "+description+" is "+pricing.getProductPrice()); } private static void showPrice(){ Pricing pricing = new Pricing(); ConfigurationManager.INSTANCE.configure(pricing); System.out.println("Please pay "+pricing.getProductPrice()); } }
mit
gabizou/SpongeCommon
src/main/java/org/spongepowered/common/data/manipulator/block/SpongeSignaledOutputData.java
2441
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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.spongepowered.common.data.manipulator.block; import static org.spongepowered.api.data.DataQuery.of; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataQuery; import org.spongepowered.api.data.MemoryDataContainer; import org.spongepowered.api.data.manipulator.block.SignaledOutputData; import org.spongepowered.common.data.manipulator.AbstractIntData; public class SpongeSignaledOutputData extends AbstractIntData<SignaledOutputData> implements SignaledOutputData { public static final DataQuery OUTPUT_SIGNAL_STRENGTH = of("OutputSignalStrength"); public SpongeSignaledOutputData() { super(SignaledOutputData.class, 0, 0, 15); } @Override public int getOutputSignal() { return this.getValue(); } @Override public SignaledOutputData setOutputSignal(int signal) { return this.setValue(signal); } @Override public SignaledOutputData copy() { return new SpongeSignaledOutputData().setValue(this.getValue()); } @Override public DataContainer toContainer() { return new MemoryDataContainer().set(OUTPUT_SIGNAL_STRENGTH, this.getValue()); } }
mit
Luis-Gdx/escuela
Topicos Avanzados de Programacion/Tabla/Tabla con base de datos y login/src/config/Connector.java
2950
/* * 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 config; import interfaces.*; import java.sql.*; import java.util.logging.*; import javax.swing.*; /** * * @author Luis G */ public class Connector { public Connector() { } protected boolean getData(String query, Callback callback) { ResultSet rs = null; Connection conn = null; Statement stmt = null; boolean isNull = false; try { connect(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", ""); stmt = conn.createStatement(); rs = stmt.executeQuery(query); for (int i = 0; rs.next(); i++) { callback.callback(rs, i); } stmt.close(); conn.close(); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); } return isNull; } protected ResultSet getData(String query) { ResultSet rs = null; Connection conn = null; Statement stmt = null; try { connect(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", ""); stmt = conn.createStatement(); rs = stmt.executeQuery(query); } catch (Exception e) { System.out.println(e); } return rs; } protected int executeQuery(String query) { int id = -1; try { connect(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/escuela", "root", ""); Statement stmt = conn.createStatement(); id = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { id = rs.getInt(1); } stmt.close(); conn.close(); } catch (SQLException e) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, e); switch (e.getErrorCode()) { case 1062: JOptionPane.showMessageDialog(null, "Ese correo ya esta registrado", "error", 0); break; case 1054: JOptionPane.showMessageDialog(null, "El registro no existe", "error", 0); break; default: JOptionPane.showMessageDialog(null, "A ocurrido un error " + e, "error", 0); System.out.println(e); break; } } return id; } private void connect() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { } } }
mit
putin266/Vote
target/work/plugins/shiro-1.2.1/src/java/org/apache/shiro/grails/annotations/PermissionRequired.java
572
package org.apache.shiro.grails.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.shiro.authz.Permission; @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface PermissionRequired { Class<? extends Permission> type(); /** * The name of the role required to be granted this authorization. */ String target() default "*"; String actions() default ""; }
mit
bjornenalfa/GA
src/engine/CircleShape.java
1041
package engine; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; public class CircleShape extends Shape { double radius; //radius of shape public CircleShape(double rad, Vector2D v, double r, double d, Color c) { super(v, r, d, c); radius = rad; } @Override public void calculateInertia() { mass = radius * radius * Math.PI * density; inertia = radius * radius * mass; } @Override public void paint(Graphics2D g) { super.paint(g); vector.readyPoint(); g.fillOval((int) (x - radius), (int) (y - radius), (int) radius * 2, (int) radius * 2); g.drawOval((int) (x - radius), (int) (y - radius), (int) radius * 2, (int) radius * 2); g.setColor(Color.BLACK); g.drawLine((int) (x), (int) (y), (int) (x + Math.cos(rotation) * radius), (int) (y + Math.sin(rotation) * radius)); } @Override public boolean contains(Point.Double p) { return p.distanceSq(x, y) < radius * radius; } }
mit
karim/adila
database/src/main/java/adila/db/alto5_7043k.java
213
// This file is automatically generated. package adila.db; /* * Alcatel POP 2 (5) * * DEVICE: alto5 * MODEL: 7043K */ final class alto5_7043k { public static final String DATA = "Alcatel|POP 2 (5)|"; }
mit
rootulp/exercism
java/protein-translation/src/main/java/ProteinTranslator.java
1679
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; class ProteinTranslator { private static final Integer CODON_LENGTH = 3; private static final Map<String, String> CODON_TO_PROTEIN = Map.ofEntries( Map.entry("AUG", "Methionine"), Map.entry("UUU", "Phenylalanine"), Map.entry("UUC", "Phenylalanine"), Map.entry("UUA", "Leucine"), Map.entry("UUG", "Leucine"), Map.entry("UCU", "Serine"), Map.entry("UCC", "Serine"), Map.entry("UCA", "Serine"), Map.entry("UCG", "Serine"), Map.entry("UAU", "Tyrosine"), Map.entry("UAC", "Tyrosine"), Map.entry("UGU", "Cysteine"), Map.entry("UGC", "Cysteine"), Map.entry("UGG", "Tryptophan")); private static final Set<String> STOP_CODONS = Set.of("UAA", "UAG", "UGA"); public List<String> translate(final String rnaSequence) { final List<String> codons = splitIntoCodons(rnaSequence); List<String> proteins = new ArrayList<>(); for (String codon : codons) { if (STOP_CODONS.contains(codon)) { return proteins; } proteins.add(translateCodon(codon)); } ; return proteins; } private static List<String> splitIntoCodons(final String rnaSequence) { final List<String> codons = new ArrayList<>(); for (int i = 0; i < rnaSequence.length(); i += CODON_LENGTH) { codons.add(rnaSequence.substring(i, Math.min(rnaSequence.length(), i + CODON_LENGTH))); } return codons; } private static String translateCodon(final String codon) { return CODON_TO_PROTEIN.get(codon); } }
mit
Kasekopf/kolandroid
kol_base/src/main/java/com/github/kolandroid/kol/model/elements/basic/BasicGroup.java
1193
package com.github.kolandroid.kol.model.elements.basic; import com.github.kolandroid.kol.model.elements.interfaces.ModelGroup; import java.util.ArrayList; import java.util.Iterator; public class BasicGroup<E> implements ModelGroup<E> { /** * Autogenerated by eclipse. */ private static final long serialVersionUID = 356357357356695L; private final ArrayList<E> items; private final String name; public BasicGroup(String name) { this(name, new ArrayList<E>()); } public BasicGroup(String name, ArrayList<E> items) { this.name = name; this.items = items; } @Override public int size() { return items.size(); } @Override public E get(int index) { return items.get(index); } @Override public void set(int index, E value) { items.set(index, value); } @Override public void remove(int index) { items.remove(index); } public void add(E item) { items.add(item); } @Override public String getName() { return name; } @Override public Iterator<E> iterator() { return items.iterator(); } }
mit
legendblade/CraftingHarmonics
api/src/main/java/org/winterblade/minecraft/harmony/api/questing/QuestStatus.java
697
package org.winterblade.minecraft.harmony.api.questing; import org.winterblade.minecraft.scripting.api.IScriptObjectDeserializer; import org.winterblade.minecraft.scripting.api.ScriptObjectDeserializer; /** * Created by Matt on 5/29/2016. */ public enum QuestStatus { INVALID, ACTIVE, LOCKED, COMPLETE, CLOSED; @ScriptObjectDeserializer(deserializes = QuestStatus.class) public static class Deserializer implements IScriptObjectDeserializer { @Override public Object Deserialize(Object input) { if(!String.class.isAssignableFrom(input.getClass())) return null; return QuestStatus.valueOf(input.toString().toUpperCase()); } } }
mit
Ernestyj/JStudy
src/main/java/leetcode11_20/RemoveNthFromEnd.java
1586
package leetcode11_20; /**Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. */ public class RemoveNthFromEnd { // Definition for singly-linked list. public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } //one pass public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode slow = dummy, fast = dummy; //Move fast in front so that the gap between slow and fast becomes n for(int i=1; i<=n+1; i++) { //TODO 注意边界 fast = fast.next; } while(fast != null) {//Move fast to the end, maintaining the gap slow = slow.next; fast = fast.next; } slow.next = slow.next.next;//Skip the desired node return dummy.next; } //two pass public ListNode removeNthFromEnd1(ListNode head, int n) { int length = 0; ListNode temp = head; while (temp != null){ length++; temp = temp.next; } if (n == length) return head.next; temp = head; for (int i = 2; i <= length - n; i++){ //TODO 循环条件极易出错 temp = temp.next; } temp.next = temp.next.next; return head; } }
mit