blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b673414c5217850fc376d537eef78eecdb801b3e | 428a98013d841eb9ff28938e3c13be685c9b0994 | /Assignment 1/Assign1/src/image/processing/OperationFactory.java | e1ff4d0bfdf11f93b4023a01b116b96a71369576 | [] | no_license | nelavensubas/CS1027 | 810070e937491a33aa3f94a50e2aeeef5005d806 | da0ac2533beebdbd884356ec3dd73e80b883a97b | refs/heads/master | 2023-05-15T08:49:14.417474 | 2021-06-11T21:39:29 | 2021-06-11T21:39:29 | 288,287,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 630 | java | package image.processing;
import image.processing.operations.IdentityOperation;
import image.processing.operations.InverseOperation;
public class OperationFactory {
/* Create an object able to perform specified image operation */
public static ImageOperation create(String op) {
switch (op) {
case "Contour":
return new ContourOperation();
case "Inverse":
return new InverseOperation();
case "Thresholding":
return new ThresholdingOperation();
case "Adjustment":
return new AdjustmentOperation();
case "Magnify":
return new MagnifyOperation();
default:
return new IdentityOperation();
}
}
}
| [
"[email protected]"
] | |
dadfca647114ee79f9a56d1744f2b948f37adae0 | 1df6d61b300975c4e8ac04316f9361901a78947d | /app/src/main/java/com/tomato/z/androidday36/activity/MediaPlayerActivity.java | 38a07d32d96f1ec824c5d44932e1fc749adb99a9 | [] | no_license | 18300602795/AndroidDay36 | 9e4be420d164296ec9c0e5fce1cab864053f3b84 | 01b3427c1a7f5f9b4cd5560eb67f0e99794f3824 | refs/heads/master | 2021-01-20T18:44:59.238965 | 2016-08-10T10:10:57 | 2016-08-10T10:10:57 | 65,372,458 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,969 | java | package com.tomato.z.androidday36.activity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.SeekBar;
import com.tomato.z.androidday36.R;
import com.tomato.z.androidday36.service.IService;
import com.tomato.z.androidday36.service.MusicService;
/**
* PACKAGE_NAME: com.tomato.z.androidday36.activity
* FUNCTIONAL_DESCRIPTION:
* CREATE_BY: 闫
* CREATE_TIME: 2016/8/4 14:35
* MODIFICATORY_DESCRIPTION:
* MODIFY_BY:
* MODIFICATORY_TIME:
*/
public class MediaPlayerActivity extends Activity {
SeekBar seekBar;
public static Handler handler;
MyConn conn;
IService iservice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
seekBar = (SeekBar) findViewById(R.id.seekBar);
//通过服务启动
handler = new Handler(){
//当接收到消息后执行该方法
public void handleMessage(Message message){
Bundle bundle = message.getData();
int duration = bundle.getInt("duration");
int currentPosition = bundle.getInt("currentPosition");
//更新seekBar
seekBar.setMax(duration);
seekBar.setProgress(currentPosition);
}
};
Intent intent = new Intent(this, MusicService.class);
startService(intent);
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// iservice.callSeekToPosition(progress);
}
//开始拖动
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// iservice.callSeekToPosition(seekBar.getProgress());
}
//停止拖动
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
iservice.callSeekToPosition(seekBar.getProgress());
}
});
}
public void click1(View view) {
iservice.callPlayerMusic();
}
public void click2(View view) {
iservice.callPauseMusic();
}
public void click3(View view) {
iservice.callRePlayerMusic();
}
class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iservice = (IService)service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
| [
"[email protected]"
] | |
0de8bc1ff161a67d801f29e193ea4a9846b11987 | ce9dc73f41dad472fe1a86e42b0e6ddc9387009f | /app/src/main/java/com/sxh/olddriver/utils/UrlUtils.java | a01482aa225b1dc139e44944323cb0741d950b3d | [] | no_license | CheckTiger/xiushi | 1355a46f5874fa0a05c6951061e55e0176c8adfa | 77ac43639b2dcc41eb2693336663a2eae305301e | refs/heads/master | 2021-01-19T09:28:16.754446 | 2017-04-12T05:16:47 | 2017-04-12T05:16:47 | 87,761,824 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 868 | java | package com.sxh.olddriver.utils;
/**
* Created by user on 2016/7/28.
*/
public class UrlUtils {
public static String ICON_URL = "http://pic.qiushibaike.com/system/avtnew/";
public static String PiC_UPL = "http://pic.qiushibaike.com/system/pictures/";
/**
* 返回用户头像
* @param icon_id
* @param icon
* @return
*/
public static String icon(String icon_id, String icon) {
String id = icon_id.substring(0, 4);
String str = ICON_URL + id + "/" + icon_id + "/thumb/" + icon;
return str;
}
/**
* 返回需要加载的网上图片
* @param pic_id
* @return
*/
public static String pic(String pic_id) {
String id = pic_id.substring(0, 5);//前5位
String str = PiC_UPL + id + "/" + pic_id + "/medium/app" + pic_id+".jpg";
return str;
}
}
| [
"[email protected]"
] | |
7368412f90c636381b2b72f6fea30bd9e2bdfa25 | ea681d4eae4f3603938d52a5e1bc9e5e230f5cab | /lcRound1/src/ContainerWithMostWater.java | 5d6eb9503ba11738b3868263466d0133d3da27fd | [] | no_license | ichappysky/eclipse | a71dfa2a13ecfb767ce56a83a07bef8afd8a84e5 | b994bdd1c22755b8062271e7a5365070ebfcc13d | refs/heads/master | 2016-09-08T01:27:22.484973 | 2013-12-16T00:55:02 | 2013-12-16T00:55:02 | 15,214,018 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 371 | java | public class ContainerWithMostWater {
public int maxArea(int[] h) {
if (h == null || h.length <= 1) {
return 0;
}
int left = 0;
int right = h.length - 1;
int max = 0;
while (left <= right) {
max = Math.max(max, Math.min(h[left], h[right]) * (right - left));
if (h[left] < h[right]) {
left++;
} else {
right--;
}
}
return max;
}
} | [
"[email protected]"
] | |
581d51e9ca98f47c363e95643a2e83f4c230442c | de7fa00078bd8f64a03f61d15bc89a8063a4477f | /outbound/src/main/java/com/sun/mdm/index/webservice/AssignRefObjectNode.java | a583c99a2d38801f46a111a93d3349c98f1f56f2 | [] | no_license | ameleito/Assignment_Lab | 1bf5bc9a02a668b652ff49e6b01920e5c9a19043 | d75d12a11985a9d0458d2415de81f4cfce28a000 | refs/heads/master | 2020-05-24T22:39:08.252830 | 2019-05-24T16:26:19 | 2019-05-24T16:26:19 | 187,499,905 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,012 | java |
package com.sun.mdm.index.webservice;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for assignRefObjectNode complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="assignRefObjectNode">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="callerInfo" type="{http://webservice.index.mdm.sun.com/}callerInfo" minOccurs="0"/>
* <element name="systemCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="localid" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="objectType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="sysObjBean" type="{http://webservice.index.mdm.sun.com/}systemPerson" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "assignRefObjectNode", propOrder = {
"callerInfo",
"systemCode",
"localid",
"objectType",
"sysObjBean"
})
public class AssignRefObjectNode {
protected CallerInfo callerInfo;
protected String systemCode;
protected String localid;
protected String objectType;
protected SystemPerson sysObjBean;
/**
* Gets the value of the callerInfo property.
*
* @return
* possible object is
* {@link CallerInfo }
*
*/
public CallerInfo getCallerInfo() {
return callerInfo;
}
/**
* Sets the value of the callerInfo property.
*
* @param value
* allowed object is
* {@link CallerInfo }
*
*/
public void setCallerInfo(CallerInfo value) {
this.callerInfo = value;
}
/**
* Gets the value of the systemCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSystemCode() {
return systemCode;
}
/**
* Sets the value of the systemCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemCode(String value) {
this.systemCode = value;
}
/**
* Gets the value of the localid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLocalid() {
return localid;
}
/**
* Sets the value of the localid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLocalid(String value) {
this.localid = value;
}
/**
* Gets the value of the objectType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getObjectType() {
return objectType;
}
/**
* Sets the value of the objectType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setObjectType(String value) {
this.objectType = value;
}
/**
* Gets the value of the sysObjBean property.
*
* @return
* possible object is
* {@link SystemPerson }
*
*/
public SystemPerson getSysObjBean() {
return sysObjBean;
}
/**
* Sets the value of the sysObjBean property.
*
* @param value
* allowed object is
* {@link SystemPerson }
*
*/
public void setSysObjBean(SystemPerson value) {
this.sysObjBean = value;
}
}
| [
"[email protected]"
] | |
5a66113a3aded31bb652ffcffebde4ced1fb1512 | 2869fc39e2e63d994d5dd8876476e473cb8d3986 | /pet/lvmama_common/src/main/java/com/lvmama/comm/pet/po/mobile/MobilePersistanceLog.java | 1aab4f48d43055d747988cbde4f1c9951c2fa201 | [] | no_license | kavt/feiniu_pet | bec739de7c4e2ee896de50962dbd5fb6f1e28fe9 | 82963e2e87611442d9b338d96e0343f67262f437 | refs/heads/master | 2020-12-25T17:45:16.166052 | 2016-06-13T10:02:42 | 2016-06-13T10:02:42 | 61,026,061 | 0 | 0 | null | 2016-06-13T10:02:01 | 2016-06-13T10:02:01 | null | UTF-8 | Java | false | false | 3,783 | java | package com.lvmama.comm.pet.po.mobile;
import java.io.Serializable;
import java.util.Date;
import com.lvmama.comm.utils.StringUtil;
import com.lvmama.comm.vo.Constant;
public class MobilePersistanceLog implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5678659383108415870L;
private Long mobilePersistanceLogId;
private Long objectId;
private String objectType;
private Date createdTime;
private Long lvVersion;
private String deviceId;
private String deviceIdType;
private String channel;
private String osVersion;
private String firstChannel;
private String secondChannel;
private String userAgent;
public Long getMobilePersistanceLogId() {
return mobilePersistanceLogId;
}
public void setMobilePersistanceLogId(Long mobilePersistanceLogId) {
this.mobilePersistanceLogId = mobilePersistanceLogId;
}
public Long getObjectId() {
return objectId;
}
public void setObjectId(Long objectId) {
this.objectId = objectId;
}
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType == null ? null : objectType.trim();
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Long getLvVersion() {
return lvVersion;
}
public void setLvVersion(Long lvVersion) {
this.lvVersion = lvVersion;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId == null ? null : deviceId.trim();
}
public String getDeviceIdType() {
if(!StringUtil.isEmptyString(deviceIdType)){
return deviceIdType;
}
if(getChannel()==null){
return null;
}
if(getChannel().contains("ANDROID")){
return "IEMI";
}
if(getChannel().contains("IPHONE")){
return "MAC";
}
return null;
}
public void setDeviceIdType(String deviceIdType) {
this.deviceIdType = deviceIdType == null ? null : deviceIdType.trim();
}
public String getChannel() {
return firstChannel+"_"+secondChannel;
}
public String getOsVersion() {
return osVersion;
}
public void setOsVersion(String osVersion) {
this.osVersion = osVersion == null ? null : osVersion.trim();
}
public String getFirstChannel() {
return firstChannel;
}
public void setFirstChannel(String firstChannel) {
this.firstChannel = firstChannel;
}
public String getSecondChannel() {
return secondChannel;
}
public void setSecondChannel(String secondChannel) {
this.secondChannel = secondChannel;
}
public void setChannel(String channel) {
if(channel!=null&&channel.contains("_")){
String[] array = channel.split("_");
this.setFirstChannel(array[0]);
this.setSecondChannel(array[1]);
}
this.channel = channel;
}
public boolean isClient(){
return Constant.MOBILE_PLATFORM.ANDROID.name().equals(this.firstChannel)||Constant.MOBILE_PLATFORM.IPHONE.name().equals(this.firstChannel)||Constant.MOBILE_PLATFORM.IPAD.name().equals(this.firstChannel);
}
public boolean isTouch(){
return Constant.MOBILE_PLATFORM.TOUCH.name().equals(this.firstChannel);
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
} | [
"[email protected]"
] | |
f228c7a27a7b6a3e79b357949cec455fb1d6f66e | 6738ee12bf4794557a666c9628ff3414231e4d9d | /simpleimageslider/src/main/java/com/axionteq/simpleimageslider/InfinitePagerAdapter.java | 48e7aae7aa22cac4a660eb56c7204180764ca5d6 | [
"MIT"
] | permissive | jadeleke/simpleimageslider | 66d003e27229a5d7dcb0be7a8e6eed7a68f456c0 | 305659acb4410009c16f26aaf6607a1140277531 | refs/heads/master | 2022-11-10T18:53:35.238999 | 2020-06-17T04:53:25 | 2020-06-17T04:53:25 | 269,816,286 | 1 | 0 | null | 2020-06-17T04:53:26 | 2020-06-06T00:12:42 | Java | UTF-8 | Java | false | false | 2,879 | java | package com.axionteq.simpleimageslider;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import androidx.viewpager.widget.PagerAdapter;
/**
* A PagerAdapter that wraps around another PagerAdapter to handle paging wrap-around.
* Thanks to: https://github.com/antonyt/InfiniteViewPager
*/
public class InfinitePagerAdapter extends PagerAdapter {
private static final String TAG = "InfinitePagerAdapter";
private static final boolean DEBUG = false;
private SliderAdapter adapter;
public InfinitePagerAdapter(SliderAdapter adapter) {
this.adapter = adapter;
}
public PagerAdapter getRealAdapter(){
return this.adapter;
}
@Override
public int getCount() {
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return Integer.MAX_VALUE;
}
/**
* @return the {@link #getCount()} result of the wrapped adapter
*/
public int getRealCount() {
return adapter.getCount();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if(getRealCount() == 0){
return null;
}
int virtualPosition = position % getRealCount();
debug("instantiateItem: real position: " + position);
debug("instantiateItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
return adapter.instantiateItem(container, virtualPosition);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if(getRealCount() == 0){
return;
}
int virtualPosition = position % getRealCount();
debug("destroyItem: real position: " + position);
debug("destroyItem: virtual position: " + virtualPosition);
// only expose virtual position to the inner adapter
adapter.destroyItem(container, virtualPosition, object);
}
/*
* Delegate rest of methods directly to the inner adapter.
*/
@Override
public void finishUpdate(ViewGroup container) {
adapter.finishUpdate(container);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return adapter.isViewFromObject(view, object);
}
@Override
public void restoreState(Parcelable bundle, ClassLoader classLoader) {
adapter.restoreState(bundle, classLoader);
}
@Override
public Parcelable saveState() {
return adapter.saveState();
}
@Override
public void startUpdate(ViewGroup container) {
adapter.startUpdate(container);
}
/*
* End delegation
*/
private void debug(String message) {
if (DEBUG) {
Log.d(TAG, message);
}
}
} | [
"[email protected]"
] | |
8eb885d6521705d74a7021f99e742631bc924acb | 4f50f688e0643be54b7f07305ab0204eb7892532 | /src/main/java/com/itachi1706/cheesecakeservercommands/util/TextUtil.java | 5b643d55a254945016e9c84a040060eedb98cae7 | [] | no_license | itachi1706/CheesecakeServerCommands | 69581cde67197e182b67533d403f50b10ffc0111 | 00e87e2d2e700986fc8d596464b970e2169c2992 | refs/heads/master | 2022-07-31T14:12:07.403906 | 2022-07-09T17:31:19 | 2022-07-09T17:31:19 | 42,306,163 | 1 | 0 | null | 2022-07-09T16:42:00 | 2015-09-11T12:04:27 | Java | UTF-8 | Java | false | false | 7,912 | java | package com.itachi1706.cheesecakeservercommands.util;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import java.util.List;
import java.util.stream.Stream;
public class TextUtil {
private TextUtil() {
throw new IllegalStateException("Utility class");
}
public static TextComponent getText(String text) {
return new TextComponent(text);
}
private static void sendMessage(ServerPlayer player, Component textComponent, boolean actionBar) {
player.displayClientMessage(textComponent, actionBar);
}
private static void sendGlobalMessage(PlayerList players, Component textComponent, boolean actionBar) {
for(int i = 0; i < players.getPlayers().size(); ++i) {
ServerPlayer player = players.getPlayers().get(i);
sendMessage(player, textComponent, actionBar);
}
}
// Chat msg
public static void sendChatMessage(ServerPlayer player, Component textComponent) {
sendMessage(player, textComponent, false);
}
public static void sendChatMessage(ServerPlayer player, String translationKey, Object... args) {
sendMessage(player, new TranslatableComponent(translationKey, args), false);
}
public static void sendChatMessage(ServerPlayer player, List<String> texts) {
for (String text : texts)
sendChatMessage(player, getText(text));
}
public static void sendChatMessage(CommandSourceStack sender, String translationKey, Object... args) {
sendMessage(sender, new TranslatableComponent(translationKey, args));
}
private static void sendMessage(CommandSourceStack sender, Component textComponent) {
sender.sendSuccess(textComponent, false);
}
// Action Bar (Info Message)
public static void sendActionMessage(ServerPlayer player, Component textComponent) {
sendMessage(player, textComponent, true);
}
public static void sendActionMessage(ServerPlayer player, String translationKey, Object... args) {
sendMessage(player, new TranslatableComponent(translationKey, args), true);
}
// Global Action Bar
public static void sendGlobalActionMessage(PlayerList players, String translationKey, Object... args) {
sendGlobalMessage(players, new TranslatableComponent(translationKey, args), true);
}
public static void sendGlobalActionMessage(PlayerList players, Component textComponent) {
sendGlobalMessage(players, textComponent, true);
}
// Global msg
public static void sendGlobalChatMessage(PlayerList players, String translationKey, Object... args) {
sendGlobalMessage(players, new TranslatableComponent(translationKey, args), false);
}
public static void sendGlobalChatMessage(PlayerList players, Component textComponent) {
sendGlobalMessage(players, textComponent, false);
}
// From ChatHelper
// Admin Messages
public static void sendAdminChatMessage(ServerPlayer player, Component textComponent) {
if (ServerUtil.checkIfAdminSilenced(player)) return; // Don't send if admin silenced
String text = textComponent.getString();
text = "[" + player.getName() + ": " + text + "]";
TextComponent newtext = getText(ChatFormatting.GRAY + "" + ChatFormatting.ITALIC + text);
List<ServerPlayer> players = ServerPlayerUtil.getOnlinePlayers();
LogHelper.info(text);
for (ServerPlayer serverPlayer : players) {
if (ServerPlayerUtil.isOperator(serverPlayer) && !serverPlayer.getName().equals(player.getName())) {
sendMessage(serverPlayer, newtext, false);
}
}
}
public static void sendAdminChatMessage(ServerPlayer player, String message) {
sendAdminChatMessage(player, getText(message));
}
public static void sendAdminChatMessage(CommandSourceStack sender, Component textComponent) {
if (ServerUtil.checkIfAdminSilenced(sender)) return; // Don't send if admin silenced
String text = textComponent.getString();
text = "[" + sender.getTextName() + ": " + text + "]";
TextComponent newtext = getText(ChatFormatting.GRAY + "" + ChatFormatting.ITALIC + text);
List<ServerPlayer> players = ServerPlayerUtil.getOnlinePlayers();
LogHelper.info(text);
for (ServerPlayer serverPlayer : players) {
if (ServerPlayerUtil.isOperator(serverPlayer) && !serverPlayer.getName().getString().equals(sender.getTextName())) {
sendMessage(serverPlayer, newtext, false);
}
}
}
public static void sendAdminChatMessage(CommandSourceStack sender, String message) {
sendAdminChatMessage(sender, getText(message));
}
// Utilities
public static String formatString(String unformattedString) {
unformattedString = unformattedString.replace("&0", "\u00a70");
unformattedString = unformattedString.replace("&1", "\u00a71");
unformattedString = unformattedString.replace("&2", "\u00a72");
unformattedString = unformattedString.replace("&3", "\u00a73");
unformattedString = unformattedString.replace("&4", "\u00a74");
unformattedString = unformattedString.replace("&5", "\u00a75");
unformattedString = unformattedString.replace("&6", "\u00a76");
unformattedString = unformattedString.replace("&7", "\u00a77");
unformattedString = unformattedString.replace("&8", "\u00a78");
unformattedString = unformattedString.replace("&9", "\u00a79");
unformattedString = unformattedString.replace("&a", "\u00a7a");
unformattedString = unformattedString.replace("&b", "\u00a7b");
unformattedString = unformattedString.replace("&c", "\u00a7c");
unformattedString = unformattedString.replace("&d", "\u00a7d");
unformattedString = unformattedString.replace("&e", "\u00a7e");
unformattedString = unformattedString.replace("&f", "\u00a7f");
unformattedString = unformattedString.replace("&k", "\u00a7k");
unformattedString = unformattedString.replace("&l", "\u00a7l");
unformattedString = unformattedString.replace("&m", "\u00a7m");
unformattedString = unformattedString.replace("&n", "\u00a7n");
unformattedString = unformattedString.replace("&o", "\u00a7o");
unformattedString = unformattedString.replace("&r", "\u00a7r");
return unformattedString;
}
private static final int CHAT_LENGTH = 53;
public static String generateChatBreaks() {
return generateChatBreaks('=');
}
public static String generateChatBreaks(char breakWith) {
StringBuilder sb = new StringBuilder();
Stream.generate(() -> breakWith).limit(CHAT_LENGTH).forEach(sb::append);
return sb.toString();
}
public static String centerText(String text) {
return centerText(text, ' ');
}
public static String centerText(String text, char breakWith) {
StringBuilder sb = new StringBuilder();
int noOfBreaks = (text.length() > CHAT_LENGTH) ? 0 : ((CHAT_LENGTH - text.length()) / 2);
if (text.length() < CHAT_LENGTH && breakWith == ' ') noOfBreaks *= 1.5;
Stream.generate(() -> breakWith).limit(noOfBreaks).forEach(sb::append);
sb.append(text);
if (breakWith == ' ' || text.length() > CHAT_LENGTH) return sb.toString();
int fillLeft = CHAT_LENGTH - noOfBreaks - text.length(); // Fill up the rest of the chat window
Stream.generate(() -> breakWith).limit(fillLeft).forEach(sb::append);
return sb.toString();
}
}
| [
"[email protected]"
] | |
eff528efaeff6c6f312e1b1948c46a89407f996e | c82378b541a8503acfb5701844807bf2a79a8e98 | /osgi.ee.extender.web/src/osgi/extender/web/service/WebContextListener.java | c3aa5b3d31c0946a3af49356103b3fea7cd396ed | [
"Apache-2.0"
] | permissive | gabrielbran/osgi.ee | 5c0b7a50264dd4332619539c7bc10675a4caed67 | a669f3b05af030c363677e09c17dca4f7d298075 | refs/heads/master | 2022-12-23T03:00:30.283966 | 2020-09-26T11:50:24 | 2020-09-26T11:50:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,531 | java | /*
* Copyright 2015, aVineas IT Consulting
*
* 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 osgi.extender.web.service;
import javax.servlet.ServletContext;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import osgi.extender.web.WebContextDefinition;
import osgi.extender.web.servlet.DispatchingServlet;
/**
* Component that listens for web context definitions to come up. These definitions can either be defined through normal
* OSGi services or as a result of a WAB definition header in a bundle (which is picked up elsewhere in this bundle).
* The listener registers a dispatching servlet at a standard http service to delegate all handling of a web context via
* the components and classes in this bundle. The servlet is the main entry point for all requests made to the web context.
*/
@Component
public class WebContextListener {
private HttpService httpService;
private ServiceTracker<WebContextDefinition, Context> tracker;
@Activate
void activate(BundleContext context) {
// Track the web context definitions.
tracker = new ServiceTracker<>(context, WebContextDefinition.class,
new ServiceTrackerCustomizer<WebContextDefinition, Context>() {
@Override
public Context addingService(ServiceReference<WebContextDefinition> ref) {
// Get the service.
WebContextDefinition definition = context.getService(ref);
if (definition == null) {
return null;
}
// Construct the servlet from this service.
Context ctx = create(ref.getBundle(), definition);
return ctx;
}
@Override
public void modifiedService(ServiceReference<WebContextDefinition> ref, Context ctxt) {
// Not necessary
}
@Override
public void removedService(ServiceReference<WebContextDefinition> ref, Context ctxt) {
destroy(ctxt);
}
});
new Thread(() -> tracker.open()).start();
}
@Deactivate
void destroy() {
tracker.close();
}
@Reference
void bindHttpService(HttpService service) {
httpService = service;
}
private static String path(ServletContext c) {
return c.getContextPath();
}
/**
* Create a context/servlet for a specific web context definition.
*
* @param bundle The bundle that originally registered the context definition
* @param def The definition itself
* @return A context or null if a severe error occurred
*/
Context create(Bundle bundle, WebContextDefinition def) {
try {
DispatchingServlet servlet = ServletContextParser.create(bundle, def);
httpService.registerServlet(path(servlet.getServletContext()), servlet, null, null);
return new Context(servlet);
} catch (Throwable exc) {
exc.printStackTrace();
return null;
}
}
/**
* Destroy a context. Normally done when a bundle stops or a service is unregistered.
*
* @param context The context to destroy
*/
void destroy(Context context) {
try {
httpService.unregister(path(context.servlet.getServletContext()));
} catch (Exception exc) {
exc.printStackTrace();
}
}
static class Context {
final DispatchingServlet servlet;
Context(DispatchingServlet s) {
servlet = s;
}
}
}
| [
"[email protected]"
] | |
fe88402e7d4f06f8c1cbdf4b44cf0baa03b0c069 | 59338a2db160ad65f8be8b219267d6315ea6cad1 | /app/src/main/java/com/smart/novel/wights/SonnyJackDragView.java | 0b2e642a16c1f0c0d9bff11aab07f256a61f90da | [] | no_license | 729533572/Novel-Search-App | 9758615926fc6187c4809b3d84eac9fb81838b7e | c30e3e4ba46b03375cbcf8eb657f7f4f08bc540e | refs/heads/master | 2020-05-29T19:33:57.571017 | 2019-01-31T07:08:28 | 2019-01-31T07:08:28 | 189,334,989 | 0 | 1 | null | 2019-05-30T02:55:48 | 2019-05-30T02:55:48 | null | UTF-8 | Java | false | false | 9,143 | java | package com.smart.novel.wights;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.FrameLayout;
import java.lang.reflect.Field;
/**
* 可拖动的悬浮按钮
* Created by linqs on 2017/12/21.
*/
public class SonnyJackDragView implements View.OnTouchListener {
private Builder mBuilder;
private int mStatusBarHeight, mScreenWidth, mScreenHeight;
//手指按下位置
private int mStartX, mStartY, mLastX, mLastY;
private boolean mTouchResult = false;
private SonnyJackDragView(Builder builder) {
mBuilder = builder;
initDragView();
}
public View getDragView() {
return mBuilder.view;
}
public Activity getActivity() {
return mBuilder.activity;
}
public boolean getNeedNearEdge() {
return mBuilder.needNearEdge;
}
public void setNeedNearEdge(boolean needNearEdge) {
mBuilder.needNearEdge = needNearEdge;
if (mBuilder.needNearEdge) {
moveNearEdge();
}
}
private void initDragView() {
if (null == getActivity()) {
throw new NullPointerException("the activity is null");
}
if (null == mBuilder.view) {
throw new NullPointerException("the dragView is null");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mBuilder.activity.isDestroyed()) {
return;
}
//屏幕宽高
WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
if (null != windowManager) {
DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
mScreenWidth = displayMetrics.widthPixels;
mScreenHeight = displayMetrics.heightPixels;
}
//状态栏高度
Rect frame = new Rect();
getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
mStatusBarHeight = frame.top;
if (mStatusBarHeight <= 0) {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
mStatusBarHeight = getActivity().getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
}
int left = mBuilder.needNearEdge ? 0 : mBuilder.defaultLeft;
FrameLayout.LayoutParams layoutParams = createLayoutParams(left, mStatusBarHeight + mBuilder.defaultTop, 0, 0);
FrameLayout rootLayout = (FrameLayout) getActivity().getWindow().getDecorView();
rootLayout.addView(getDragView(), layoutParams);
getDragView().setOnTouchListener(this);
}
private static SonnyJackDragView createDragView(Builder builder) {
if (null == builder) {
throw new NullPointerException("the param builder is null when execute method createDragView");
}
if (null == builder.activity) {
throw new NullPointerException("the activity is null");
}
if (null == builder.view) {
throw new NullPointerException("the view is null");
}
SonnyJackDragView sonnyJackDragView = new SonnyJackDragView(builder);
return sonnyJackDragView;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchResult = false;
mStartX = mLastX = (int) event.getRawX();
mStartY = mLastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int left, top, right, bottom;
int dx = (int) event.getRawX() - mLastX;
int dy = (int) event.getRawY() - mLastY;
left = v.getLeft() + dx;
if (left < 0) {
left = 0;
}
right = left + v.getWidth();
if (right > mScreenWidth) {
right = mScreenWidth;
left = right - v.getWidth();
}
top = v.getTop() + dy;
if (top < mStatusBarHeight + 2) {
top = mStatusBarHeight + 2;
}
bottom = top + v.getHeight();
if (bottom > mScreenHeight) {
bottom = mScreenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
mLastX = (int) event.getRawX();
mLastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
//这里需设置LayoutParams,不然按home后回再到页面等view会回到原来的地方
v.setLayoutParams(createLayoutParams(v.getLeft(), v.getTop(), 0, 0));
float endX = event.getRawX();
float endY = event.getRawY();
if (Math.abs(endX - mStartX) > 5 || Math.abs(endY - mStartY) > 5) {
//防止点击的时候稍微有点移动点击事件被拦截了
mTouchResult = true;
}
if (mTouchResult && mBuilder.needNearEdge) {
//是否每次都移至屏幕边沿
moveNearEdge();
}
break;
}
return mTouchResult;
}
/**
* 移至最近的边沿
*/
private void moveNearEdge() {
int left = getDragView().getLeft();
int lastX;
if (left + getDragView().getWidth() / 2 <= mScreenWidth / 2) {
lastX = 0;
} else {
lastX = mScreenWidth - getDragView().getWidth();
}
ValueAnimator valueAnimator = ValueAnimator.ofInt(left, lastX);
valueAnimator.setDuration(1000);
valueAnimator.setRepeatCount(0);
valueAnimator.setInterpolator(new BounceInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int left = (int) animation.getAnimatedValue();
getDragView().setLayoutParams(createLayoutParams(left, getDragView().getTop(), 0, 0));
}
});
valueAnimator.start();
}
private FrameLayout.LayoutParams createLayoutParams(int left, int top, int right, int bottom) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(mBuilder.size, mBuilder.size);
layoutParams.setMargins(left, top, right, bottom);
return layoutParams;
}
public static class Builder {
private Activity activity;
private int size = FrameLayout.LayoutParams.WRAP_CONTENT;
private int defaultTop = 0;
private int defaultLeft = 0;
private boolean needNearEdge = false;
private View view;
public Builder setActivity(Activity activity) {
this.activity = activity;
return this;
}
public Builder setSize(int size) {
this.size = size;
return this;
}
public Builder setDefaultTop(int top) {
this.defaultTop = top;
return this;
}
public Builder setDefaultLeft(int left) {
this.defaultLeft = left;
return this;
}
public Builder setNeedNearEdge(boolean needNearEdge) {
this.needNearEdge = needNearEdge;
return this;
}
public Builder setView(View view) {
this.view = view;
return this;
}
public SonnyJackDragView build() {
return createDragView(this);
}
}
}
/**
* 用法如下:
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.ic_launcher_round);
imageView.setOnClickListener(v -> Toast.makeText(MainActivity.this, "点击了...", Toast.LENGTH_SHORT).show());
SonnyJackDragView sonnyJackDragView = new SonnyJackDragView.Builder()
.setActivity(this)//当前Activity,不可为空
.setDefaultLeft(30)//初始位置左边距
.setDefaultTop(30)//初始位置上边距
.setNeedNearEdge(false)//拖动停止后,是否移到边沿
.setSize(100)//DragView大小
.setView(imageView)//设置自定义的DragView,切记不可为空
.build();
也可手动设置拖动停止后,是否移到边沿
boolean needNearEdge = sonnyJackDragView.getNeedNearEdge();
sonnyJackDragView.setNeedNearEdge(!needNearEdge);
*/
| [
"honghuotai"
] | honghuotai |
214465a0ca1077d2d92e45bcb54690d483dc92a7 | 3d4b80887e3d2b89a59f01ba621ca06b05dc6de3 | /src/main/java/com/worknomads/worknomads/ethereum/utils/ContractTransactionUtils.java | 682a1a8c32df351f31d61e93974859e6f1ba8134 | [] | no_license | pm1g14/worknomadsbackend | 0614f58007ddaf90604a9163682768c245e2f809 | 44d92190408fbddbfec404a1a4322b316c508f1a | refs/heads/master | 2023-08-27T21:15:40.718521 | 2021-10-08T23:52:23 | 2021-10-08T23:52:23 | 378,099,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,809 | java | package com.worknomads.worknomads.ethereum.utils;
import com.worknomads.worknomads.dos.ContractDO;
import com.worknomads.worknomads.ethereum.EthNetworkAPI;
import com.worknomads.worknomads.ethereum.constants.EnvironmentConstants;
import com.worknomads.worknomads.ethereum.gasprovider.CustomGasProvider;
import com.worknomads.worknomads.ethereum.wrappers.EmploymentContract_sol_EmploymentContract;
import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.crypto.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.exceptions.TransactionException;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Optional;
public class ContractTransactionUtils {
private static Logger logger = LoggerFactory.getLogger(EthNetworkAPI.class);
public static Optional<Credentials> loadCredentials(String password, String sourceFile) {
Credentials credentials = null;
try {
logger.debug("Invoking credentials...");
return Optional.of(WalletUtils.loadCredentials(password, sourceFile));
} catch (IOException e) {
logger.debug("File was not found, returning empty...");
} catch (CipherException e) {
e.printStackTrace();
}
return Optional.empty();
}
public static BigInteger getNonceForAccount(Web3j web3j, String account) {
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
account, DefaultBlockParameterName.LATEST).sendAsync().join();
return ethGetTransactionCount.getTransactionCount();
}
public static String signMessage(BigInteger nonce, String encodedFunction, String contractAddress, int networkChainId, Credentials credentials, String functionToCall) {
CustomGasProvider gasProvider = new CustomGasProvider();
BigInteger gasPrice = gasProvider.getGasPrice();
BigInteger gasLimit = gasProvider.getGasLimit(functionToCall);
RawTransaction transaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress, encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(transaction, networkChainId, credentials);
return Numeric.toHexString(signedMessage);
}
public static Optional<Credentials> getSignWalletCredentials() {
String sourceFile = "C:\\Users\\panosmav\\AppData\\Roaming\\Ethereum\\testnet\\keystore\\UTC--2021-08-16T19-46-41.527495000Z--816f37f9d8088b7ec15808b5c0811b217849614d.json";
String password = "paokaraoleG41";
return ContractTransactionUtils.loadCredentials(password, sourceFile);
}
public static void sucessOrRollbackContractCreation(String from, String to, Throwable ex, Credentials credentials, TransactionReceipt receipt, Web3j web3j) {
if (ex != null) {
loadAndDestroyContract(from, to, credentials, web3j);
web3j.shutdown();
}
else logger.debug("Successfully created and topped up contract, transaction hash: "+receipt.getTransactionHash());
}
public static void handleNonRetrievableCredentials(Optional<Credentials> credentials) throws TransactionException {
if (!credentials.isPresent()) throw new TransactionException("Wallet credentials could not be retrieved, can't sign transaction.");
}
public static Credentials createCredentialsFromPassword(String password) throws TransactionException {
if (StringUtils.isEmpty(password)) throw new TransactionException("Credentials could not be created for empty password");
return Credentials.create(EnvironmentConstants.walletPrivate);
}
public static EmploymentContract_sol_EmploymentContract loadContractFromAddress(String contractAddress, Web3j web3, Credentials credentials) {
return EmploymentContract_sol_EmploymentContract.load(
contractAddress, web3, credentials, new DefaultGasProvider());
}
public static void transferBalanceToNewContract(ContractDO contractContents, Web3j web3j, Credentials credentials, TransactionReceipt receipt) {
try {
BigInteger nonce = ContractTransactionUtils.getNonceForAccount(web3j, EnvironmentConstants.signWalletGanache);
//TODO remove these and add separate transaction wallets for each company
RawTransaction transaction = RawTransaction.createEtherTransaction(nonce, new CustomGasProvider().getGasPrice(), new CustomGasProvider().getGasLimit(), receipt.getContractAddress(), BigDecimal.valueOf(contractContents.getContractDetails().getGrossSalary()).toBigInteger());
String signed = new RawTransactionManager(
web3j,
credentials,
EmploymentContract_sol_EmploymentContract.GANACHE_CHAIN_ID).sign(transaction);
web3j.ethSendRawTransaction(signed).sendAsync();
} catch (Throwable t) {
ContractTransactionUtils.sucessOrRollbackContractCreation(EnvironmentConstants.signWalletGanache, receipt.getContractAddress(), t, credentials, receipt, web3j);
web3j.shutdown();
}
}
private static void loadAndDestroyContract(String from, String to, Credentials credentials, Web3j web3j) {
EmploymentContract_sol_EmploymentContract contractInstance = loadContractFromAddress(to, web3j, credentials);
contractInstance.kill(from);
}
}
| [
"[email protected]"
] | |
ab61513a977790d65a46d14ffb3ea77c4f45e322 | c77ab04ef4a55fee4f2cf965b1e44165b9fdc55f | /admin/src/main/java/kz/beeset/med/admin/utils/CommonService.java | 3e9128f84f896678d5c7a3d8d74e2cbf6497c26d | [] | no_license | https-github-com-blackshot/asm-med-back | 9fbfbbfb8e84e6df599d96395e3aa7069875901e | 0f52bba2f1f73d4a2099e02b7ed72848678aabab | refs/heads/master | 2020-08-21T04:37:47.943379 | 2019-10-18T20:09:39 | 2019-10-18T20:09:39 | 216,098,206 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,522 | java | package kz.beeset.med.admin.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import kz.beeset.med.admin.utils.strategy.AnnotationExclusionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
public class CommonService {
private static final Logger LOGGER = LoggerFactory.getLogger(CommonService.class);
private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").serializeNulls()
.setExclusionStrategies(new AnnotationExclusionStrategy()).create();
private static final Gson GSON_DATETIME = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls()
.setExclusionStrategies(new AnnotationExclusionStrategy()).create();
private static final Gson GSON_DATE_ONLY = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls()
.setExclusionStrategies(new AnnotationExclusionStrategy()).create();
// InternalExceptionHelper ieHelper = new InternalExceptionHelper(this.getClass().getCanonicalName());
//public static EsuvoResponse.ResponseBuilder builder = EsuvoResponse.status(EsuvoResponse.Status.OK);
public final String SUCCESS = "success", ERROR = "error";
protected String locale;
protected Long brand;
protected ResponseEntity<?> builder() {
return new ResponseEntity<>(HttpStatus.OK);
}
protected ResponseEntity<?> builder(Object object) {
return new ResponseEntity<>(object, HttpStatus.OK);
}
protected ResponseEntity<?> builder(Object object, HttpStatus httpStatus) {
return new ResponseEntity<>(object, httpStatus);
}
public String getLocale() {
if (locale == null) {
this.locale = "ru";
}
return this.locale;
}
public String success() {
Map answer = new HashMap();
answer.put("status", SUCCESS);
String response = GSON.toJson(answer);
return response;
}
public String success(Object data) {
Map answer = new HashMap<>();
answer.put("status", SUCCESS);
answer.put("data", data);
String response = GSON.toJson(answer);
return response;
}
public String successDateTime(Object data) {
Map answer = new HashMap<>();
answer.put("status", SUCCESS);
answer.put("data", data);
String response = GSON_DATETIME.toJson(answer);
return response;
}
public String successDateOnly(Object data) {
Map answer = new HashMap<>();
answer.put("status", SUCCESS);
answer.put("data", data);
String response = GSON_DATE_ONLY.toJson(answer);
return response;
}
public String error(Enum errorRef) {
String response = GSON.toJson(getErrorMap(errorRef));
LOGGER.error(response);
return response;
}
public String errorWithData(Enum errorRef, Object data) {
Map answer = getErrorMap(errorRef);
answer.put("data", data);
String response = GSON.toJson(answer);
LOGGER.error(response);
return response;
}
public String errorWithDescription(Enum errorRef, String errorDesc) {
Map answer = getErrorMap(errorRef);
answer.put("error_description", errorDesc);
String response = GSON.toJson(answer);
LOGGER.error(response);
return response;
}
public String errorWithDataAndDescription(Enum errorRef, String errorDesc, Object data) {
Map answer = getErrorMap(errorRef);
answer.put("error_description", errorDesc);
answer.put("data", data);
String response = GSON.toJson(answer);
LOGGER.error(response);
return response;
}
private Map getErrorMap(Enum errorRef) {
String errorCode = errorRef != null ? errorRef.toString() : "SYSTEM_ERROR";
Map answer = new HashMap<>();
answer.put("status", ERROR);
answer.put("error_code", errorCode);
answer.put("error_description", getErrorDescription(errorCode));
return answer;
}
private String getErrorDescription(String errorCode) {
errorCode = errorCode != null ? errorCode : "SYSTEM_ERROR";
String errorKey = getContextErrorCode(errorCode);
// try {
// if (dict.isExist(errorKey, getLocale())) {
// messagesBean.updateErrorMessageIfExist(errorKey, getLocale(), true);
// return dict.getTranslate(errorKey, getLocale());
// } else {
// messagesBean.saveNotTranslatedErrorCodes(errorKey, getLocale());
// return errorKey;
// }
// } catch (Exception e) {
// LOGGER.error("Error while get translate for " + errorKey);
// return errorKey;
// }
return errorKey;
}
public String getErrorDescription(Enum errorCode) {
return getErrorDescription(errorCode != null ? errorCode.toString() : "SYSTEM_ERROR");
}
private String getContextErrorCode(String errorCode) {
switch (errorCode) {
case "SYSTEM_ERROR":
case "SESSION_EXPIRED_OR_CLOSED":
return String.format("REST_ERROR-%s", errorCode);
default:
return String.format("REST_ERROR-%s_%s", this.getClass().getSimpleName().toLowerCase(), errorCode);
}
}
}
| [
"[email protected]"
] | |
ffe02d0b44158a3c1dddb9d9353530b0c9cd2e88 | dd779276508074e26dc4f9afb84c129c1704697b | /com-crud/src/main/java/com/crud/entities/LoginBean.java | b7449fdd24ee410c3d6c68bdf514ec3a1a50858d | [] | no_license | akashmulik/springsecurity | de20005c60ab65f3e9acf8e2b2d82f0ac334b86b | e69e4c4862b732b953fc1ac2b6a81085942b8810 | refs/heads/master | 2022-12-24T01:28:11.337201 | 2020-09-06T10:52:12 | 2020-09-06T10:52:12 | 151,362,673 | 1 | 0 | null | 2022-12-16T10:35:24 | 2018-10-03T04:56:18 | JavaScript | UTF-8 | Java | false | false | 936 | java | package com.crud.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class LoginBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 5283942463036109284L;
@Id
private int id;
private String email;
@Column(name="password")
private String pswd;
@Column(name = "active_flag")
private String isActive;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| [
"[email protected]"
] | |
1dc3b154f9a7378aa0ac25f03182e1cf3384a1c4 | cd3e2c0dcd5c4eddc65930bdc4e76820b2dc64d5 | /gulimall-third-party/src/main/java/com/gulimall/GulimallThirdPartyApplication.java | ec4b4ea30aeb922da69440d15abe91a1bf2fa79a | [
"Apache-2.0"
] | permissive | li-jiafang/gulimall | 9280d5fa16f001ac61102f219b4b8d001ecb1115 | 09dd62f947bb5c3ed159fc84ca000fafbda8bf21 | refs/heads/master | 2023-07-31T08:48:40.343031 | 2021-09-06T06:30:12 | 2021-09-06T06:30:12 | 384,025,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 437 | java | package com.gulimall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallThirdPartyApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallThirdPartyApplication.class, args);
}
}
| [
"[email protected]"
] | |
9f0694547550969a50551bd1425ef346fb78e282 | e7cfb5bdf6273a671d675a13a2d5ee4ad9cfa476 | /videotrimmerview/src/main/java/com/video/cut/utils/BackgroundExecutor.java | 542e326f5ce03bfb55c32d7b9bc414a43389328f | [] | no_license | gyymz1993/videoTrimmerView | 04b75b9d36cbd2f01f2e747b68177363f72927e9 | 3fab9b099db017a79403ec9d26595361b4c42c33 | refs/heads/master | 2020-03-23T14:22:40.703867 | 2018-08-10T07:42:59 | 2018-08-10T07:42:59 | 141,672,181 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 9,142 | java | /**
* Copyright (C) 2010-2016 eBusiness Information, Excilys Group
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.video.cut.utils;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public final class BackgroundExecutor {
private static final String TAG = "BackgroundExecutor";
public static final Executor DEFAULT_EXECUTOR = Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors());
private static Executor executor = DEFAULT_EXECUTOR;
private static final List<Task> TASKS = new ArrayList<>();
private static final ThreadLocal<String> CURRENT_SERIAL = new ThreadLocal<>();
private BackgroundExecutor() {
}
/**
* Execute a runnable after the given delay.
*
* @param runnable the task to execute
* @param delay the time from now to delay execution, in milliseconds
* <p>
* if <code>delay</code> is strictly positive and the current
* executor does not support scheduling (if
* Executor has been called with such an
* executor)
* @return Future associated to the running task
* @throws IllegalArgumentException if the current executor set by Executor
* does not support scheduling
*/
private static Future<?> directExecute(Runnable runnable, long delay) {
Future<?> future = null;
if (delay > 0) {
/* no serial, but a delay: schedule the task */
if (!(executor instanceof ScheduledExecutorService)) {
throw new IllegalArgumentException("The executor set does not support scheduling");
}
ScheduledExecutorService scheduledExecutorService = (ScheduledExecutorService) executor;
future = scheduledExecutorService.schedule(runnable, delay, TimeUnit.MILLISECONDS);
} else {
if (executor instanceof ExecutorService) {
ExecutorService executorService = (ExecutorService) executor;
future = executorService.submit(runnable);
} else {
/* non-cancellable task */
executor.execute(runnable);
}
}
return future;
}
/**
* Execute a task after (at least) its delay <strong>and</strong> after all
* tasks added with the same non-null <code>serial</code> (if any) have
* completed execution.
*
* @param task the task to execute
* @throws IllegalArgumentException if <code>task.delay</code> is strictly positive and the
* current executor does not support scheduling (if
* Executor has been called with such an
* executor)
*/
public static synchronized void execute(Task task) {
Future<?> future = null;
if (task.serial == null || !hasSerialRunning(task.serial)) {
task.executionAsked = true;
future = directExecute(task, task.remainingDelay);
}
if ((task.id != null || task.serial != null) && !task.managed.get()) {
/* keep task */
task.future = future;
TASKS.add(task);
}
}
/**
* Indicates whether a task with the specified <code>serial</code> has been
* submitted to the executor.
*
* @param serial the serial queue
* @return <code>true</code> if such a task has been submitted,
* <code>false</code> otherwise
*/
private static boolean hasSerialRunning(String serial) {
for (Task task : TASKS) {
if (task.executionAsked && serial.equals(task.serial)) {
return true;
}
}
return false;
}
/**
* Retrieve and remove the first task having the specified
* <code>serial</code> (if any).
*
* @param serial the serial queue
* @return task if found, <code>null</code> otherwise
*/
private static Task take(String serial) {
int len = TASKS.size();
for (int i = 0; i < len; i++) {
if (serial.equals(TASKS.get(i).serial)) {
return TASKS.remove(i);
}
}
return null;
}
/**
* Cancel all tasks having the specified <code>id</code>.
*
* @param id the cancellation identifier
* @param mayInterruptIfRunning <code>true</code> if the thread executing this task should be
* interrupted; otherwise, in-progress tasks are allowed to
* complete
*/
public static synchronized void cancelAll(String id, boolean mayInterruptIfRunning) {
for (int i = TASKS.size() - 1; i >= 0; i--) {
Task task = TASKS.get(i);
if (id.equals(task.id)) {
if (task.future != null) {
task.future.cancel(mayInterruptIfRunning);
if (!task.managed.getAndSet(true)) {
/*
* the task has been submitted to the executor, but its
* execution has not started yet, so that its run()
* method will never call postExecute()
*/
task.postExecute();
}
} else if (task.executionAsked) {
Log.w(TAG, "A task with id " + task.id + " cannot be cancelled (the executor set does not support it)");
} else {
/* this task has not been submitted to the executor */
TASKS.remove(i);
}
}
}
}
public static abstract class Task implements Runnable {
private String id;
private long remainingDelay;
private long targetTimeMillis; /* since epoch */
private String serial;
private boolean executionAsked;
private Future<?> future;
/*
* A task can be cancelled after it has been submitted to the executor
* but before its run() method is called. In that case, run() will never
* be called, hence neither will postExecute(): the tasks with the same
* serial identifier (if any) will never be submitted.
*
* Therefore, cancelAll() *must* call postExecute() if run() is not
* started.
*
* This flag guarantees that either cancelAll() or run() manages this
* task post execution, but not both.
*/
private AtomicBoolean managed = new AtomicBoolean();
public Task(String id, long delay, String serial) {
if (!"".equals(id)) {
this.id = id;
}
if (delay > 0) {
remainingDelay = delay;
targetTimeMillis = System.currentTimeMillis() + delay;
}
if (!"".equals(serial)) {
this.serial = serial;
}
}
@Override
public void run() {
if (managed.getAndSet(true)) {
/* cancelled and postExecute() already called */
return;
}
try {
CURRENT_SERIAL.set(serial);
execute();
} finally {
/* handle next tasks */
postExecute();
}
}
public abstract void execute();
private void postExecute() {
if (id == null && serial == null) {
/* nothing to do */
return;
}
CURRENT_SERIAL.set(null);
synchronized (BackgroundExecutor.class) {
/* execution complete */
TASKS.remove(this);
if (serial != null) {
Task next = take(serial);
if (next != null) {
if (next.remainingDelay != 0) {
/* the delay may not have elapsed yet */
next.remainingDelay = Math.max(0L, targetTimeMillis - System.currentTimeMillis());
}
/* a task having the same serial was queued, execute it */
BackgroundExecutor.execute(next);
}
}
}
}
}
}
| [
"myymz5843570"
] | myymz5843570 |
cdffb0b59acbc23b12d061945c7b9e3b3182600d | 7bd91222d410aa2178bdf10f5aef6114b6e1897f | /PackageInstaller/src/com/android/packageinstaller/permission/ui/television/PermissionAppsFragment.java | 29839c1429017e52a77ecfa4bd713b4815c8ddd1 | [
"Apache-2.0"
] | permissive | huimingli/androidsourccode | 657c53c26dbdf7e22754e8e8634f5899bf45edb7 | 74eeb77e12de91e1f14f582a64b550c5f7c33a19 | refs/heads/master | 2021-04-29T09:48:29.403003 | 2016-12-30T02:55:09 | 2016-12-30T02:55:09 | 77,655,025 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,686 | java | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.packageinstaller.permission.ui.television;
import android.annotation.Nullable;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v14.preference.SwitchPreference;
import android.support.v4.util.ArrayMap;
import android.support.v7.preference.Preference;
import android.support.v7.preference.Preference.OnPreferenceChangeListener;
import android.support.v7.preference.Preference.OnPreferenceClickListener;
import android.support.v7.preference.PreferenceScreen;
import android.util.ArraySet;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.packageinstaller.DeviceUtils;
import com.android.packageinstaller.R;
import com.android.packageinstaller.permission.model.AppPermissionGroup;
import com.android.packageinstaller.permission.model.PermissionApps;
import com.android.packageinstaller.permission.model.PermissionApps.Callback;
import com.android.packageinstaller.permission.model.PermissionApps.PermissionApp;
import com.android.packageinstaller.permission.ui.ReviewPermissionsActivity;
import com.android.packageinstaller.permission.utils.LocationUtils;
import com.android.packageinstaller.permission.utils.SafetyNetLogger;
import com.android.packageinstaller.permission.utils.Utils;
import java.util.ArrayList;
import java.util.List;
public final class PermissionAppsFragment extends SettingsWithHeader implements Callback,
OnPreferenceChangeListener {
private static final int MENU_SHOW_SYSTEM = Menu.FIRST;
private static final int MENU_HIDE_SYSTEM = Menu.FIRST + 1;
private static final String KEY_SHOW_SYSTEM_PREFS = "_showSystem";
public static PermissionAppsFragment newInstance(String permissionName) {
return setPermissionName(new PermissionAppsFragment(), permissionName);
}
private static <T extends Fragment> T setPermissionName(T fragment, String permissionName) {
Bundle arguments = new Bundle();
arguments.putString(Intent.EXTRA_PERMISSION_NAME, permissionName);
fragment.setArguments(arguments);
return fragment;
}
private PermissionApps mPermissionApps;
private PreferenceScreen mExtraScreen;
private ArrayMap<String, AppPermissionGroup> mToggledGroups;
private ArraySet<String> mLauncherPkgs;
private boolean mHasConfirmedRevoke;
private boolean mShowSystem;
private MenuItem mShowSystemMenu;
private MenuItem mHideSystemMenu;
private Callback mOnPermissionsLoadedListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLoading(true /* loading */, false /* animate */);
setHasOptionsMenu(true);
final ActionBar ab = getActivity().getActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
mLauncherPkgs = Utils.getLauncherPackages(getContext());
String groupName = getArguments().getString(Intent.EXTRA_PERMISSION_NAME);
mPermissionApps = new PermissionApps(getActivity(), groupName, this);
mPermissionApps.refresh(true);
}
@Override
public void onResume() {
super.onResume();
mPermissionApps.refresh(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
mShowSystemMenu = menu.add(Menu.NONE, MENU_SHOW_SYSTEM, Menu.NONE,
R.string.menu_show_system);
mHideSystemMenu = menu.add(Menu.NONE, MENU_HIDE_SYSTEM, Menu.NONE,
R.string.menu_hide_system);
updateMenu();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().finish();
return true;
case MENU_SHOW_SYSTEM:
case MENU_HIDE_SYSTEM:
mShowSystem = item.getItemId() == MENU_SHOW_SYSTEM;
if (mPermissionApps.getApps() != null) {
onPermissionsLoaded(mPermissionApps);
}
updateMenu();
break;
}
return super.onOptionsItemSelected(item);
}
private void updateMenu() {
mShowSystemMenu.setVisible(!mShowSystem);
mHideSystemMenu.setVisible(mShowSystem);
}
@Override
protected void onSetEmptyText(TextView textView) {
textView.setText(R.string.no_apps);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindUi(this, mPermissionApps);
}
private static void bindUi(SettingsWithHeader fragment, PermissionApps permissionApps) {
final Drawable icon = permissionApps.getIcon();
final CharSequence label = permissionApps.getLabel();
fragment.setHeader(null, null, null,
fragment.getString(R.string.permission_apps_decor_title, label));
}
private void setOnPermissionsLoadedListener(Callback callback) {
mOnPermissionsLoadedListener = callback;
}
@Override
public void onPermissionsLoaded(PermissionApps permissionApps) {
Context context = getPreferenceManager().getContext();
if (context == null) {
return;
}
boolean isTelevision = DeviceUtils.isTelevision(context);
PreferenceScreen screen = getPreferenceScreen();
ArraySet<String> preferencesToRemove = new ArraySet<>();
for (int i = 0, n = screen.getPreferenceCount(); i < n; i++) {
preferencesToRemove.add(screen.getPreference(i).getKey());
}
if (mExtraScreen != null) {
for (int i = 0, n = mExtraScreen.getPreferenceCount(); i < n; i++) {
preferencesToRemove.add(mExtraScreen.getPreference(i).getKey());
}
}
for (PermissionApp app : permissionApps.getApps()) {
if (!Utils.shouldShowPermission(app)) {
continue;
}
String key = app.getKey();
preferencesToRemove.remove(key);
Preference existingPref = screen.findPreference(key);
if (existingPref == null && mExtraScreen != null) {
existingPref = mExtraScreen.findPreference(key);
}
boolean isSystemApp = Utils.isSystem(app, mLauncherPkgs);
if (isSystemApp && !isTelevision && !mShowSystem) {
if (existingPref != null) {
screen.removePreference(existingPref);
}
continue;
}
if (existingPref != null) {
// If existing preference - only update its state.
if (app.isPolicyFixed()) {
existingPref.setSummary(getString(
R.string.permission_summary_enforced_by_policy));
}
existingPref.setPersistent(false);
existingPref.setEnabled(!app.isPolicyFixed());
if (existingPref instanceof SwitchPreference) {
((SwitchPreference) existingPref)
.setChecked(app.areRuntimePermissionsGranted());
}
continue;
}
SwitchPreference pref = new SwitchPreference(context);
pref.setOnPreferenceChangeListener(this);
pref.setKey(app.getKey());
pref.setIcon(app.getIcon());
pref.setTitle(app.getLabel());
if (app.isPolicyFixed()) {
pref.setSummary(getString(R.string.permission_summary_enforced_by_policy));
}
pref.setPersistent(false);
pref.setEnabled(!app.isPolicyFixed());
pref.setChecked(app.areRuntimePermissionsGranted());
if (isSystemApp && isTelevision) {
if (mExtraScreen == null) {
mExtraScreen = getPreferenceManager().createPreferenceScreen(context);
}
mExtraScreen.addPreference(pref);
} else {
screen.addPreference(pref);
}
}
if (mExtraScreen != null) {
preferencesToRemove.remove(KEY_SHOW_SYSTEM_PREFS);
Preference pref = screen.findPreference(KEY_SHOW_SYSTEM_PREFS);
if (pref == null) {
pref = new Preference(context);
pref.setKey(KEY_SHOW_SYSTEM_PREFS);
pref.setIcon(Utils.applyTint(context, R.drawable.ic_toc,
android.R.attr.colorControlNormal));
pref.setTitle(R.string.preference_show_system_apps);
pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
SystemAppsFragment frag = new SystemAppsFragment();
setPermissionName(frag, getArguments().getString(
Intent.EXTRA_PERMISSION_NAME));
frag.setTargetFragment(PermissionAppsFragment.this, 0);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, frag)
.addToBackStack("SystemApps")
.commit();
return true;
}
});
screen.addPreference(pref);
}
int grantedCount = 0;
for (int i = 0, n = mExtraScreen.getPreferenceCount(); i < n; i++) {
if (((SwitchPreference) mExtraScreen.getPreference(i)).isChecked()) {
grantedCount++;
}
}
pref.setSummary(getString(R.string.app_permissions_group_summary,
grantedCount, mExtraScreen.getPreferenceCount()));
}
for (String key : preferencesToRemove) {
Preference pref = screen.findPreference(key);
if (pref != null) {
screen.removePreference(pref);
} else if (mExtraScreen != null) {
pref = mExtraScreen.findPreference(key);
if (pref != null) {
mExtraScreen.removePreference(pref);
}
}
}
setLoading(false /* loading */, true /* animate */);
if (mOnPermissionsLoadedListener != null) {
mOnPermissionsLoadedListener.onPermissionsLoaded(permissionApps);
}
}
@Override
public boolean onPreferenceChange(final Preference preference, Object newValue) {
String pkg = preference.getKey();
final PermissionApp app = mPermissionApps.getApp(pkg);
if (app == null) {
return false;
}
if (LocationUtils.isLocationGroupAndProvider(mPermissionApps.getGroupName(),
app.getPackageName())) {
LocationUtils.showLocationDialog(getContext(), app.getLabel());
return false;
}
addToggledGroup(app.getPackageName(), app.getPermissionGroup());
if (app.isReviewRequired()) {
Intent intent = new Intent(getActivity(), ReviewPermissionsActivity.class);
intent.putExtra(Intent.EXTRA_PACKAGE_NAME, app.getPackageName());
startActivity(intent);
return false;
}
if (newValue == Boolean.TRUE) {
app.grantRuntimePermissions();
} else {
final boolean grantedByDefault = app.hasGrantedByDefaultPermissions();
if (grantedByDefault || (!app.hasRuntimePermissions() && !mHasConfirmedRevoke)) {
new AlertDialog.Builder(getContext())
.setMessage(grantedByDefault ? R.string.system_warning
: R.string.old_sdk_deny_warning)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.grant_dialog_button_deny_anyway,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((SwitchPreference) preference).setChecked(false);
app.revokeRuntimePermissions();
if (!grantedByDefault) {
mHasConfirmedRevoke = true;
}
}
})
.show();
return false;
} else {
app.revokeRuntimePermissions();
}
}
return true;
}
@Override
public void onPause() {
super.onPause();
logToggledGroups();
}
private void addToggledGroup(String packageName, AppPermissionGroup group) {
if (mToggledGroups == null) {
mToggledGroups = new ArrayMap<>();
}
// Double toggle is back to initial state.
if (mToggledGroups.containsKey(packageName)) {
mToggledGroups.remove(packageName);
} else {
mToggledGroups.put(packageName, group);
}
}
private void logToggledGroups() {
if (mToggledGroups != null) {
final int groupCount = mToggledGroups.size();
for (int i = 0; i < groupCount; i++) {
String packageName = mToggledGroups.keyAt(i);
List<AppPermissionGroup> groups = new ArrayList<>();
groups.add(mToggledGroups.valueAt(i));
SafetyNetLogger.logPermissionsToggled(packageName, groups);
}
mToggledGroups = null;
}
}
public static class SystemAppsFragment extends SettingsWithHeader implements Callback {
PermissionAppsFragment mOuterFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
mOuterFragment = (PermissionAppsFragment) getTargetFragment();
setLoading(true /* loading */, false /* animate */);
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
if (mOuterFragment.mExtraScreen != null) {
setPreferenceScreen();
} else {
mOuterFragment.setOnPermissionsLoadedListener(this);
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String groupName = getArguments().getString(Intent.EXTRA_PERMISSION_NAME);
PermissionApps permissionApps = new PermissionApps(getActivity(), groupName, null);
bindUi(this, permissionApps);
}
private static void bindUi(SettingsWithHeader fragment, PermissionApps permissionApps) {
final CharSequence label = permissionApps.getLabel();
fragment.setHeader(null, null, null,
fragment.getString(R.string.system_apps_decor_title, label));
}
@Override
public void onPermissionsLoaded(PermissionApps permissionApps) {
setPreferenceScreen();
mOuterFragment.setOnPermissionsLoadedListener(null);
}
private void setPreferenceScreen() {
setPreferenceScreen(mOuterFragment.mExtraScreen);
setLoading(false /* loading */, true /* animate */);
}
}
}
| [
"[email protected]"
] | |
fe30ef44924856751463f6a1277c2bf8e72a9499 | 0c49c8019eb8e10fa8dc133213a75f4d077d4800 | /app/src/main/java/com/pranjal98/instagram/searchContents.java | 24d675991a3d2e084af946a88cfe15a9984f3533 | [] | no_license | Pranjal98/Instagram_Clone | c54c5522cdacdc4f23b63ad2821bd984f4f69f80 | a36913f41e9809367b622c1663aabf2ebaa411b6 | refs/heads/master | 2021-07-06T14:55:39.907566 | 2020-09-27T17:49:22 | 2020-09-27T17:49:22 | 190,617,780 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 751 | java | package com.pranjal98.instagram;
public class searchContents {
private String dp_url;
private String UserName;
private String Key;
public searchContents() {
}
public searchContents(String dp_url, String userName, String key) {
this.dp_url = dp_url;
UserName = userName;
Key = key;
}
public String getDp_url() {
return dp_url;
}
public void setDp_url(String dp_url) {
this.dp_url = dp_url;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
}
| [
"[email protected]"
] | |
4bae32023da3e1e965fe1c58c267f2e7c2c25e33 | ad73784c5a3687c68f3eaf17d9d184dcf05b98b1 | /src/main/java/com/miaomiao/aop/cglib/CallbackFilterDemo.java | 914aed9cd6d3caa8fe54ff74175dc0322913c34a | [] | no_license | lss598018587/faceView | 75a5f95458f74347e16fd4dc1d7cb7f2145dcc8d | cb258d577d324d01fe80ff09522a5b1a07cb4900 | refs/heads/master | 2022-07-27T20:56:06.889893 | 2020-01-19T07:44:43 | 2020-01-19T07:44:43 | 205,144,965 | 0 | 0 | null | 2022-06-29T17:53:40 | 2019-08-29T11:08:54 | Java | UTF-8 | Java | false | false | 1,648 | java | package com.miaomiao.aop.cglib;
import net.sf.cglib.proxy.*;
import java.lang.reflect.Method;
public class CallbackFilterDemo {
public static void main(String[] args) {
Callback[] callbacks = new Callback[] {
new MethodInterceptorImpl(), NoOp.INSTANCE
};
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(MyClass.class);
enhancer.setCallbacks(callbacks);
enhancer.setCallbackFilter(new CallbackFilterImpl());
MyClass myClass = (MyClass) enhancer.create();
System.out.println("要执行方法了");
myClass.method();
myClass.method1();
}
private static class CallbackFilterImpl implements CallbackFilter {
@Override
public int accept(Method method) {
System.out.println("进到拦截器了:"+method.getName());
if (method.getName().equals("method"))
return 1;
else
return 0;
}
}
private static class MethodInterceptorImpl implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.err.println("Before invoke " + method);
Object result = proxy.invokeSuper(obj, args);
System.err.println("After invoke" + method);
return result;
}
}
}
class MyClass {
public void method() {
System.out.println("MyClass.method()");
}
public void method1() {
System.out.println("MyClass.method()1");
}
}
| [
"[email protected]"
] | |
ea30acb4a5eccbe4a99a3fe8687d6ae00b3165ef | 3b2c561583a0592f285d32baa69aeb644058ff4a | /src/main/java/com/entity/Property.java | 1cc145043e15eba4839ab41d50d3b24072a9cf65 | [] | no_license | xujing0/testIoc | 75e5e0ff012b686b51699571d859284ad32f2a54 | 1891d82c41b4a303741babc1216146a33b609cd2 | refs/heads/main | 2023-06-25T17:00:21.662687 | 2021-07-13T07:27:05 | 2021-07-13T07:27:05 | 385,513,816 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 613 | java | package com.entity;
/**
* 用于封装一个property标签
*/
public class Property {
//属性名称
private String name;
//属性值
private String value;
//属性的引用
private String ref;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
}
| [
"[email protected]"
] | |
381d101217fafb3aabbf23c5f71ed327b36698c2 | a4076d2da945ed61fbfde1c9785c616626bb07eb | /app/src/main/java/com/score/fragments/FragmentDashboard.java | 4ba8bc6d948186841cbbd03ba9dfaeb0ca7719ce | [] | no_license | mystvictor/RENTAL-MANAGER | db2dd9b06603a2ef072a1047c015a835e3d535a2 | 012882d5a8e693018f2e78e71d4014b4e0d78ec8 | refs/heads/master | 2021-01-22T08:27:56.210107 | 2015-07-20T19:40:56 | 2015-07-20T19:40:56 | 39,404,094 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,010 | java | package com.score.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.score.rentalmanager.R;
/**
* Created by myves.stvictor on 2015-06-12.
*/
public class FragmentDashboard extends Fragment {
public FragmentDashboard() { }
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_dashboard_layout, container, false);
// Inflate the layout for this fragment
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
| [
"[email protected]"
] | |
e5c4b1751043d0be45ca60a96943baf0381c683d | 6e7783c9c1b983de5aa268908c35b8ba4afae08b | /recycle_test/app/src/main/java/test/yuedong/com/myapplication/bitmap/ResBitmapCache.java | 079deb16a48751825098689685d669e1c9d00d84 | [] | no_license | Wxx57/shennandadao | 6e67f641998d141ffc4b43259f6610a2eac80479 | 5cce72f75085c52dd0477a7f0fd6ad180c17f68a | refs/heads/master | 2023-03-28T10:26:54.773587 | 2021-03-22T03:00:10 | 2021-03-22T03:00:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,581 | java | package test.yuedong.com.myapplication.bitmap;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import java.util.HashMap;
import java.util.HashSet;
/**
* Created with IntelliJ IDEA.
* User: virl
* Date: 14-4-25
* Time: 上午10:21
* Email: [email protected]
*/
public class ResBitmapCache implements NEBitmap.SDBitmapReleaseListener{
static ResBitmapCache sInstance;
public static ResBitmapCache instance(){
if(sInstance == null) {
sInstance = new ResBitmapCache();
}
return sInstance;
}
public static void release() {
if(sInstance != null) {
sInstance = null;
}
}
public void logCount() {
// LogEx.d("log res count begin");
// for(Integer key: resSDBitmapHashMap.keySet()) {
// NEBitmap bit = resSDBitmapHashMap.get(key);
// LogEx.d(StrUtil.linkObjects("id:", String.format("%x", key), ", count:", bit.count));
// }
// LogEx.d("log res count end");
}
private HashMap<Integer, NEBitmap> resSDBitmapHashMap;
private ResBitmapCache() {
resSDBitmapHashMap = new HashMap<Integer, NEBitmap>();
}
public NEBitmap loadRes(Resources res, Integer resId) {
NEBitmap bit = resSDBitmapHashMap.get(resId);
if(bit == null) {
bit = new NEBitmap(NEBitmap.Type.kRes, BitmapFactory.decodeResource(res, resId), resId);
bit.setReleaseListener(this);
resSDBitmapHashMap.put(resId, bit);
return bit;
}
return bit.retain();
}
public NEBitmap findRes(Integer resId) {
return resSDBitmapHashMap.get(resId);
}
public void put(Integer resId, NEBitmap bitmap) {
resSDBitmapHashMap.put(resId, bitmap);
bitmap.setReleaseListener(this);
}
public void forceReleaseAll() {
for(NEBitmap bitmap: resSDBitmapHashMap.values()) {
bitmap.bitmap().recycle();
}
resSDBitmapHashMap.clear();
}
public void releaseUnUsedBitmap() {
HashSet<Integer> removed = new HashSet<>();
for(Integer key: resSDBitmapHashMap.keySet()) {
NEBitmap bit = resSDBitmapHashMap.get(key);
if(bit.count <= 0) {
removed.add(key);
bit.bitmap().recycle();
}
}
for(Integer key: removed) {
resSDBitmapHashMap.remove(key);
}
}
@Override
public void onReleaseBitmap(NEBitmap bitmap) {
if(bitmap.count < 0) {
}
}
}
| [
""
] | |
594335c51dce0ac260718dfa79082bc1f14a2ac6 | f866fc5cb717c2e6f327d3eae39ba2e7099b944e | /app/src/main/java/com/sarl/monifywatch/linechart/LineCardTwo.java | 5b7e676417268f4e2edd21cfd4fa6222d1bb30f4 | [] | no_license | SamkeetJain/MonifyWatch | f17bf46b670806371c1bc329b9308be1a601d122 | a3ceddbeec557d8422e95bbddc8b999f44195b2f | refs/heads/master | 2021-07-24T02:35:44.752326 | 2017-11-03T19:54:09 | 2017-11-03T19:54:09 | 109,282,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,591 | java | package com.sarl.monifywatch.linechart;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.support.v7.widget.CardView;
import com.db.chart.util.Tools;
import com.db.chart.animation.Animation;
import com.db.chart.model.LineSet;
import com.db.chart.model.Point;
import com.db.chart.renderer.AxisRenderer;
import com.db.chart.view.LineChartView;
import com.sarl.monifywatch.CardController;
import com.sarl.monifywatch.R;
public class LineCardTwo extends CardController {
private final LineChartView mChart;
private final String[] mLabels =
{"", "", "", "", "START", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "FINISH", "", "", "",
""};
private final float[][] mValues =
{{35f, 37f, 47f, 49f, 43f, 46f, 80f, 83f, 65f, 68f, 28f, 55f, 58f, 50f, 53f, 53f, 57f,
48f, 50f, 53f, 54f, 25f, 27f, 35f, 37f, 35f, 80f, 82f, 55f, 59f, 85f, 82f, 60f,
55f, 63f, 65f, 58f, 60f, 63f, 60f},
{85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f,
85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f,
85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f, 85f}};
public LineCardTwo(CardView card) {
super(card);
mChart = (LineChartView) card.findViewById(R.id.chart);
}
@Override
public void show(Runnable action) {
super.show(action);
LineSet dataset = new LineSet(mLabels, mValues[0]);
dataset.setColor(Color.parseColor("#004f7f"))
.setThickness(Tools.fromDpToPx(3))
.setSmooth(true)
.beginAt(4)
.endAt(36);
for (int i = 0; i < mLabels.length; i += 5) {
Point point = (Point) dataset.getEntry(i);
point.setColor(Color.parseColor("#ffffff"));
point.setStrokeColor(Color.parseColor("#0290c3"));
if (i == 30 || i == 10) point.setRadius(Tools.fromDpToPx(6));
}
mChart.addData(dataset);
Paint thresPaint = new Paint();
thresPaint.setColor(Color.parseColor("#0079ae"));
thresPaint.setStyle(Paint.Style.STROKE);
thresPaint.setAntiAlias(true);
thresPaint.setStrokeWidth(Tools.fromDpToPx(.75f));
thresPaint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0));
Paint gridPaint = new Paint();
gridPaint.setColor(Color.parseColor("#ffffff"));
gridPaint.setStyle(Paint.Style.STROKE);
gridPaint.setAntiAlias(true);
gridPaint.setStrokeWidth(Tools.fromDpToPx(.75f));
mChart.setXLabels(AxisRenderer.LabelPosition.OUTSIDE)
.setYLabels(AxisRenderer.LabelPosition.NONE)
.setGrid(0, 7, gridPaint)
.setValueThreshold(80f, 80f, thresPaint)
.setAxisBorderValues(0, 110)
.show(new Animation().fromXY(0, .5f).withEndAction(action));
}
@Override
public void update() {
super.update();
if (firstStage) {
mChart.updateValues(0, mValues[1]);
} else {
mChart.updateValues(0, mValues[0]);
}
mChart.notifyDataUpdate();
}
@Override
public void dismiss(Runnable action) {
super.dismiss(action);
mChart.dismiss(new Animation().fromXY(1, .5f).withEndAction(action));
}
}
| [
"[email protected]"
] | |
0abdb0c6d92a5d8247cd8522b3fc9c0aa59fe23f | f6a513efdb72eb9b55e2dbef723e06b1853ba0cb | /ps-future-travel-common/src/main/java/com/future/travel/utils/TableData.java | 247f73abcba612a580b24e2911c4e1ebd14db8e5 | [] | no_license | PengFuture/PS-FUTURE-TRAVEL | cfdef4bd00a06801776c0b21f0624b7989550be7 | bba59258fd8aa41080d814d1a296c262e794e0b3 | refs/heads/master | 2023-08-17T11:12:11.871149 | 2021-09-28T07:35:47 | 2021-09-28T07:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 810 | java | package com.future.travel.utils;
import lombok.Data;
import java.util.List;
/**
* @author Peng
* @date 2021/9/13 23:17
*/
@Data
public class TableData<T> {
/**
* 响应码,默认0
*/
private Integer code;
/**
* 响应信息
*/
private String msg;
/**
* 数据统计
*/
private long count;
/**
* 数据集合
*/
private List<T> data;
public TableData() {
super();
this.code = 0;
this.msg = "";
}
public TableData(Integer code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public TableData(List<T> data, long count) {
super();
this.code = 0;
this.msg = "";
this.data = data;
this.count = count;
}
}
| [
"[email protected]"
] | |
11ba706f6f4877468f15cc78b7ce1c8b33545991 | 0c7def36209fe78a59eea361cf533ae0100a1f17 | /src/main/java/com/game/cardgame/game/dal/GameRepository.java | df87049a40bea7cccd9f03804f5c45d7540ec740 | [] | no_license | alexandregignac/card | fda7cee72043246512bd746421c729902dece9d1 | 5591768c5e0a574e50a0c89bfd256505af6b88d1 | refs/heads/master | 2020-04-23T11:22:34.284611 | 2019-02-17T15:01:08 | 2019-02-17T15:01:08 | 171,134,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 274 | java | package com.game.cardgame.game.dal;
import com.game.cardgame.game.entity.Game;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface GameRepository extends JpaRepository<Game,Long>{
} | [
"[email protected]"
] | |
328e9e5861d07f80e8741d3a962e0e4706c32b03 | 601b097b638bdd24a2e27e5775bf0d793b7b18d8 | /src/dao/JDBSConnectionFactory.java | 46f085cdfd3ee2c4c9b336898b91a024a3c4af3c | [] | no_license | konovaliuk/WhatWhereWhen | 4f8356d60b8921d2799f6818099ffe36cb9f08e6 | 9b0ea9a005795dcd2df211d80c685441d3654394 | refs/heads/master | 2020-03-17T18:51:20.589037 | 2018-05-17T15:48:25 | 2018-05-17T15:48:25 | 133,836,126 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 923 | java | package dao;
import exeptions.DaoException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class JDBSConnectionFactory implements IConnectionFactory {
protected DataSource dataSource;
protected ConnectionWrapp connection;
private JDBSConnectionFactory() throws DaoException{
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
dataSource = (DataSource)
envCtx.lookup("jdbc/libraryDB");
}catch (Exception e){
throw new DaoException("Error while creating");
}
}
@Override
public ConnectionWrapp getConnection() throws DaoException {
throw new DaoException("Some Error:((");
}
@Override
public void closeConnection() throws DaoException {
throw new DaoException("Some Error:((");
}
}
| [
"[email protected]"
] | |
3f6c7f271be18488346aecca40c8bd60e375dff6 | b13c0ea2eeedb9bcbacd0aae503c3a7b655488fe | /com.acstech.churchlife/src/com/acstech/churchlife/listhandling/IndividualListItem.java | fbef43e6b153d3ac3571cb60263596132bbcb862 | [] | no_license | mwangepatrick/ChurchLife-Android | e31be20ba30ff067ba42cdd61647d79f2f609f79 | 99ad08563bf19d04525dc232f1c1a5d9120b278f | refs/heads/master | 2020-04-10T11:00:45.654303 | 2013-05-31T19:50:59 | 2013-05-31T19:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,149 | java | package com.acstech.churchlife.listhandling;
import com.acstech.churchlife.R;
import com.acstech.churchlife.exceptionhandling.AppException;
import com.acstech.churchlife.webservice.AddressBase;
import com.acstech.churchlife.webservice.CoreIndividualEmail;
import com.acstech.churchlife.webservice.EmailBase;
import com.acstech.churchlife.webservice.PhoneBase;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.Drawable;
// see bottom for static factory methods
public class IndividualListItem {
private String _title = "";
private String _valueLine1 = "";
private String _valueLine2 = "";
private Boolean _valueLine2Visible = false;
private String _valueLine3 = "";
private Boolean _valueLine3Visible = false;
private String _actionTag = "";
private Drawable _actionImage = null;
public String getTitle() {
return _title;
}
public String getValueLine1() {
return _valueLine1;
}
public String getActionTag() {
return _actionTag;
}
// If applicable - can be null
public Drawable getActionImage() {
return _actionImage;
}
//-----------------------
//-- Line2 --
//-----------------------
public Boolean getValueLine2Visible() {
return _valueLine2Visible;
}
public String getValueLine2() {
return _valueLine2;
}
//-----------------------
//-- Line3 --
//-----------------------
public Boolean getValueLine3Visible() {
return _valueLine3Visible;
}
public String getValueLine3() {
return _valueLine3;
}
// Constructor (s)
public IndividualListItem(String title, String line1, String line2, String actionTag, Drawable actionImage) {
this(title, line1, line2, null, actionTag, actionImage);
}
public IndividualListItem(String title, String line1, String line2, String line3, String actionTag, Drawable actionImage) {
_title = title;
_valueLine1 = line1;
if (line2 != null) {
_valueLine2Visible = (line2.length() > 0);
_valueLine2 = line2;
}
if (line3 != null) {
_valueLine3Visible = (line3.length() > 0);
_valueLine3 = line3;
}
_actionTag = actionTag;
_actionImage = actionImage;
}
// Factory Methods
public static IndividualListItem NewSimpleItem(String title, String line1) {
return new IndividualListItem(title, line1, "", "", null);
}
public static IndividualListItem NewPhoneItem(Context context, PhoneBase phone) throws AppException {
String titleString = context.getResources().getString(R.string.Individual_PhoneAction);
String defaultAction = "phone:" + phone.getPhoneNumberToDial();
return new IndividualListItem(String.format(titleString, phone.PhoneType),
phone.getPhoneNumberToDisplay(),
"",
defaultAction,
context.getResources().getDrawable(R.drawable.call_sms_w));
}
public static IndividualListItem NewEmailItem(Context context, EmailBase email) throws AppException {
String titleString = context.getResources().getString(R.string.Individual_EmailAction);
return new IndividualListItem(String.format(titleString, email.EmailType),
email.Email, "",
"email:" + email.Email,
context.getResources().getDrawable(R.drawable.sym_action_email));
}
public static IndividualListItem NewAddressItem(Context context, AddressBase address) throws AppException {
String titleString = context.getResources().getString(R.string.Individual_AddressAction);
String cityStateZip = "";
if (address.City.trim().length() > 0 && address.State.trim().length() > 0) {
cityStateZip = String.format("%s, %s %s", address.City.trim(), address.State.trim(), address.Zipcode.trim());
}
String actionTag = String.format("map:%s %s %s, %s %s", address.Address, address.Address2, address.City, address.State, address.Zipcode);
return new IndividualListItem(String.format(titleString, address.AddrType),
address.Address, address.Address2, cityStateZip,
actionTag,
context.getResources().getDrawable(R.drawable.ic_menu_compass));
}
}
| [
"[email protected]"
] | |
cad487640f1add0028a8a866c4870e5a4671c412 | c491e20e03c69972f9c56a6cf58173916c089182 | /src/main/java/com/shopee/product/utils/HttpUtils.java | 20ab0e81b9dc009877d00d5d35dd37f00d5e87b6 | [] | no_license | yuanzr/shopee-product | b4c229799c5032996370ad5989eb9d7a653b6c7f | 5a014738b4cdb3143458b5948831f3af91c2373d | refs/heads/master | 2022-06-21T11:08:42.636607 | 2021-05-30T14:15:16 | 2021-05-30T14:15:16 | 243,482,710 | 1 | 2 | null | 2022-06-17T02:59:00 | 2020-02-27T09:39:20 | Java | UTF-8 | Java | false | false | 9,385 | java | package com.shopee.product.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by liuguofu on 2017/7/10.
*/
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static PoolingHttpClientConnectionManager cm;
private static String EMPTY_STR = "";
private static String CONTENT_TYPE_UTF_8 = "UTF-8";
private static String CONTENT_TYPE_GBK = "GBK";
private static String CONTENT_TYPE_JSON = "application/json";
private static final int CONNECTION_TIMEOUT_MS = 60000;
private static final int SO_TIMEOUT_MS = 60000;
private static final String proxy_host = "127.0.0.1";
private static final int proxy_port = 1080;
public static final String cookie = "SPC_IA=-1; SPC_EC=-; SPC_F=AkMLMfR3WOnh9LwvVoQ99EYtgsGGZPwI; REC_T_ID=c4735858-5611-11ea-a4db-9c7da3191b3f; SPC_SI=cspqu5wrpe75u69o2cudnppnwmswtzli; SPC_U=-; SPC_R_T_ID=\"vYvrzPrZeCEW9/cm+fnUR9TsO0WmMY1CRu6bZfJuUacCpLvZ6hnhPmMRmrt9W0D0kGgUsR5Rw9XImV9vzMxLxmHb05HqrPzohQE9afRueWs=\"; SPC_T_IV=\"ohQ/+WgeYLh3vnm1HPtBgA==\"; SPC_R_T_IV=\"ohQ/+WgeYLh3vnm1HPtBgA==\"; SPC_T_ID=\"vYvrzPrZeCEW9/cm+fnUR9TsO0WmMY1CRu6bZfJuUacCpLvZ6hnhPmMRmrt9W0D0kGgUsR5Rw9XImV9vzMxLxmHb05HqrPzohQE9afRueWs=\"";
private static void init() {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(50);// 整个连接池最大连接数
cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
SocketConfig sc = SocketConfig.custom().setSoTimeout(SO_TIMEOUT_MS).build();
cm.setDefaultSocketConfig(sc);
}
}
public static String executeGet(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 设置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000).setConnectionRequestTimeout(5000)
.setSocketTimeout(30000).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
httpGet.setHeader("User-Agent",cookie);
httpGet.setHeader("Accept","*/*");
httpGet.setHeader("Cache-Control","no-cache");
httpGet.setHeader("Postman-Token","3cfe87af-603f-499b-bbb0-0c01453f25b5");
httpGet.setHeader("Host","shopee.co.th");
httpGet.setHeader("Accept-Encoding","gzip, deflate, br");
HttpResponse response = httpClient.execute(httpGet);
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.error("executeGet error..." + httpGet.getURI());
} finally {
if (httpGet != null) {
httpGet.releaseConnection();
}
if (httpClient != null) {
httpClient.close();
}
try {
is.close();
} catch (IOException e) {
logger.error("executeGet close is error..." + httpGet.getURI());
}
}
return sb.toString();
}
/**
* Post发送请求
*
* @param url 请求地址
* @param params map对象
* @return
* @throws UnsupportedEncodingException
*/
public static String executePost(String url, Map<String, Object> params, boolean proxy) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
ArrayList pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));
if (proxy) {
return getProxyResult(httpPost);
} else {
return getResult(httpPost);
}
}
private static ArrayList covertParams2NVPS(Map<String, Object> params) {
ArrayList pairs = new ArrayList<>();
for (Map.Entry param : params.entrySet()) {
pairs.add(new BasicNameValuePair((String) param.getKey(), (String) param.getValue()));
}
return pairs;
}
/**
* 处理Http请求
*
* @param request
* @return
*/
private static String getResult(HttpRequestBase request) {
RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);
config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
config.setSocketTimeout(SO_TIMEOUT_MS);
request.setConfig(config.build());
/// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
/// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// long len = entity.getContentLength();// -1 表示长度未知
return EntityUtils.toString(entity);
}
} catch (IOException e) {
logger.error("execute getResult error..." + request.getURI());
} finally {
try {
// 释放Socket流
assert response != null;
response.close();
// 释放Connection
/// httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return EMPTY_STR;
}
/**
* 获取设置代理请求的结果
*
* @param request
* @return
*/
private static String getProxyResult(HttpRequestBase request) {
HttpHost httpHost = new HttpHost(proxy_host, proxy_port);
RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);
config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
config.setSocketTimeout(SO_TIMEOUT_MS);
config.setProxy(httpHost);
request.setConfig(config.build());
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
} catch (IOException e) {
logger.error("execute getProxyResult error..." + request.getURI());
} finally {
try {
assert response != null;
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return EMPTY_STR;
}
/**
* 通过连接池获取HttpClient
*
* @return
*/
private static CloseableHttpClient getHttpClient() {
init();
return HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(true).build();
}
public static boolean isSuccess(int code) {
return code == 200;
}
/**
* 泰文翻译英文
* @param key
* @return
*/
public static String translate(String key){
// http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=th&tl=en&q=เสื้อเชิ้ต
try {
String result = executeGet("http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=th&tl=en&q=" + key);
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray sentences = jsonObject.getJSONArray("sentences");
JSONObject jsonObject1 = sentences.getJSONObject(0);
String trans = jsonObject1.get("trans").toString();
return trans;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]){
try {
String result = executeGet("https://shopee.co.th/api/v2/item/get?itemid=2902440663&shopid=138020609");
JSONObject jsonObject = JSONObject.parseObject(result);
String json = jsonObject.toJSONString();
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
12030bc2643d8dcdeda60f90792d18be0b2e20ee | 50ef7483c5b43af36a361e0114e3a200e48e5251 | /src/main/java/com/cognizant/antlr4/TDGrammarBaseVisitor.java | 6fece10ed942be5fb8d3e70a306b92dd6b1325eb | [] | no_license | saikat9/Translator | c54ba8860694eb5ac14893ec67a4d1c9be201c00 | 5a5500bf0e126eef5f8fa54064611e3ec1dd8f4f | refs/heads/master | 2020-06-28T10:24:15.207585 | 2019-08-02T09:53:30 | 2019-08-02T09:53:30 | 200,209,279 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,453 | java | // Generated from TDGrammar.g4 by ANTLR 4.7.1
package com.cognizant.antlr4;
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
/**
* This class provides an empty implementation of {@link TDGrammarVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public class TDGrammarBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements TDGrammarVisitor<T> {
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitParse(TDGrammarParser.ParseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitError(TDGrammarParser.ErrorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSql_stmt_list(TDGrammarParser.Sql_stmt_listContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSql_stmt(TDGrammarParser.Sql_stmtContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSelect_stmt(TDGrammarParser.Select_stmtContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSelect_expr(TDGrammarParser.Select_exprContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSelect_list(TDGrammarParser.Select_listContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSelect_list_expr(TDGrammarParser.Select_list_exprContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFrom_clause(TDGrammarParser.From_clauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitKeyword(TDGrammarParser.KeywordContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExpr(TDGrammarParser.ExprContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExpr_alias_name(TDGrammarParser.Expr_alias_nameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLiteral_value(TDGrammarParser.Literal_valueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTop_expr(TDGrammarParser.Top_exprContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTable_name(TDGrammarParser.Table_nameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitColumn_name(TDGrammarParser.Column_nameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitDatabase_name(TDGrammarParser.Database_nameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTable_alias_name(TDGrammarParser.Table_alias_nameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFunction_name(TDGrammarParser.Function_nameContext ctx) { return visitChildren(ctx); }
} | [
"[email protected]"
] | |
d9bb21cea0a1ad13b29a5566e4241b8b7b4b7ae3 | fd35dd10b22abc45ed160e450237dde4581f914e | /src/test/java/org/gradle/EstructurasDatosTest.java | 588ed1eca84e4242390a5d528d53d988a9fd8ca0 | [] | no_license | jrperez175/EstructuraDeDatosGradle | a2b947b95a24e3a66eb4f1e29c987b1f4b458e5c | 90598b6e542c6be7a01c543f2e8cf09233bd81a5 | refs/heads/master | 2021-01-25T09:44:07.770645 | 2018-03-13T20:46:46 | 2018-03-13T20:46:46 | 123,313,897 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,821 | java | package org.gradle;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;
import static org.junit.Assert.*;
public class EstructurasDatosTest {
private EstructurasDatos estructuraDeDatos;
@Before
public void setup() {
estructuraDeDatos = new EstructurasDatos();
}
@Test
public void ingreso3y4Obtengo7Test() {
// arrange - definicion de la variables
int nro1 = 3;
int nro2 = 4;
/*
* EstructurasDatos estructuraDeDatos = new EstructurasDatos(); como se repite
* podemos sacar la variable a nivel global y inicializarla en el @Before
*/
// act- accion
int resultado = estructuraDeDatos.suma(nro1, nro2);
// assert
Assert.assertEquals(7, resultado);
}
@Test
public void ingreso30y50Obtengo80Test() {
// arrange definicion de la variables
int nro1 = 30;
int nro2 = 50;
// EstructurasDatos estructuraDeDatos = new EstructurasDatos();
// act- llamado a la accion
int resultado = estructuraDeDatos.suma(nro1, nro2);
// assert - lo que espero
Assert.assertEquals(80, resultado);
}
@Test
public void ingreso4yObtengo5Test() {
// arrange definicion de la variables
int nro1 = 4;
// act- accion
int resultado = estructuraDeDatos.sumarUno(nro1);
// assert
Assert.assertEquals(5, resultado);
}
@Test
public void ingreso5y3Obtengo2Test() {
// arrange definicion de la variables
int nro1 = 5;
int nro2 = 3;
// act- accion
int resultado = estructuraDeDatos.restaDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(2, resultado);
}
@Test
public void ingreso8y4Obtengo4Test() {
// arrange definicion de la variables
int nro1 = 8;
int nro2 = 4;
// act- accion
int resultado = estructuraDeDatos.restaDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(4, resultado);
}
@Test
public void ingreso4y2Obtengo2Test() {
// arrange definicion de la variables
int nro1 = 4;
int nro2 = 2;
// act- accion
int resultado = estructuraDeDatos.restaDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(2, resultado);
}
@Test
public void ingreso2y5Obtengo10Test() {
// arrange definicion de la variables
int nro1 = 2;
int nro2 = 5;
// act- accion
int resultado = estructuraDeDatos.multiplicarDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(10, resultado);
}
@Test
public void ingreso7y3Obtengo21Test() {
// arrange definicion de la variables
int nro1 = 7;
int nro2 = 3;
// act- accion
int resultado = estructuraDeDatos.multiplicarDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(21, resultado);
}
@Test
public void ingreso2y2Obtengo4Test() {
// arrange definicion de la variables
int nro1 = 2;
int nro2 = 2;
// act- accion
int resultado = estructuraDeDatos.multiplicarDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(4, resultado);
}
@Test
public void ingreso6y2Obtengo3Test() {
// arrange definicion de la variables
int nro1 = 6;
int nro2 = 2;
// act- accion
int resultado = estructuraDeDatos.dividirDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(3, resultado);
}
@Test
public void ingreso10y5Obtengo2Test() {
// arrange definicion de la variables
int nro1 = 10;
int nro2 = 5;
// act- accion
int resultado = estructuraDeDatos.dividirDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(2, resultado);
}
@Test
public void ingreso2y2Obtengo1Test() {
// arrange definicion de la variables
int nro1 = 2;
int nro2 = 2;
// act- accion
int resultado = estructuraDeDatos.dividirDosNumeros(nro1, nro2);
// assert
// Assert.assertEquals(2, resultado);
assertEquals(1, resultado);
}
@Test
public void ingreso5yObtengo4Test() {
// arrange definicion de la variables
int nro1 = 5;
// act- accion
int resultado = estructuraDeDatos.restarUno(nro1);
// assert
assertEquals(4, resultado);
}
@Test
public void ingreso4yObtengo3Test() {
// arrange definicion de la variables
int nro1 = 4;
// act- accion
int resultado = estructuraDeDatos.restarUno(nro1);
// assert
assertEquals(3, resultado);
}
@Test
public void ingreso9yObtengo8Test() {
// arrange definicion de la variables
int nro1 = 9;
// act- accion
int resultado = estructuraDeDatos.restarUno(nro1);
// assert
assertEquals(8, resultado);
}
@Test
public void ingresoholayObtengoholaTest() {
// arrange definicion de la variables
String nombre = "hola";
// act- accion
String resultado = estructuraDeDatos.devolverString(nombre);
// assert
assertEquals("hola", resultado);
}
@Test
public void ingresoBancolombiayObtengoBancolombiaTest() {
// arrange definicion de la variables
String nombre = "Bancolombia";
// act- accion
String resultado = estructuraDeDatos.devolverString(nombre);
// assert
assertEquals("Bancolombia", resultado);
}
@Test
public void ingresofUnCiOnAlyObtengofUnCiOnAlTest() {
// arrange definicion de la variables
String nombre = "fUnCiOnAl";
// act- accion
String resultado = estructuraDeDatos.devolverString(nombre);
// assert
assertEquals("fUnCiOnAl", resultado);
}
@Test
public void ingresoholayObtengoNumeroCaracteresTest() {
// arrange definicion de la variables
String nombre = "hola";
// act- accion
int resultado = estructuraDeDatos.contarCaracteres(nombre);
// assert
assertEquals(4, resultado);
}
@Test
public void ingresofUnCiOnAlyObtengoNumeroCaracteresTest() {
// arrange definicion de la variables
String nombre = "fUnCiOnAl";
// act- accion
int resultado = estructuraDeDatos.contarCaracteres(nombre);
// assert
assertEquals(9, resultado);
}
@Test
public void ingresoBancolombiayObtengoNumeroCaracteresTest() {
// arrange definicion de la variables
String nombre = "Bancolombia";
// act- accion
int resultado = estructuraDeDatos.contarCaracteres(nombre);
// assert
assertEquals(11, resultado);
}
@Test
public void ingreso5yObtengoTrueTest() {
// arrange definicion de la variables
int nro1 = 5;
// act- accion
boolean resultado = estructuraDeDatos.devolverBoleano(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingreso4yObtengoFalseTest() {
// arrange definicion de la variables
int nro1 = 4;
// act- accion
boolean resultado = estructuraDeDatos.devolverBoleano(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingreso3yObtengoFalseTest() {
// arrange definicion de la variables
int nro1 = 3;
// act- accion
boolean resultado = estructuraDeDatos.devolverBoleano(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingreso2yObtengoFalseTest() {
// arrange definicion de la variables
int nro1 = 2;
// act- accion
boolean resultado = estructuraDeDatos.devolverBoleano(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoPositivo5yObtengoPositivoTest() {
// arrange definicion de la variables
int nro1 = 5;
// act- accion
boolean resultado = estructuraDeDatos.evaluarEntero(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoNegativo3yObtengoNegativoTest() {
// arrange definicion de la variables
int nro1 = -3;
// act- accion
boolean resultado = estructuraDeDatos.evaluarEntero(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoPositivo2yObtengoPositivoTest() {
// arrange definicion de la variables
int nro1 = 2;
// act- accion
boolean resultado = estructuraDeDatos.evaluarEntero(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoNegativo5yObtengoNegativoTest() {
// arrange definicion de la variables
int nro1 = -5;
// act- accion
boolean resultado = estructuraDeDatos.evaluarEntero(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoPositivo0yObtengoPositivoTest() {
// arrange definicion de la variables
int nro1 = 0;
// act- accion
boolean resultado = estructuraDeDatos.evaluarEntero(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoNumero2yObtengoParTest() {
// arrange definicion de la variables
int nro1 = 2;
// act- accion
boolean resultado = estructuraDeDatos.evaluarParEImpar(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoNumero3yObtengoImparTest() {
// arrange definicion de la variables
int nro1 = 3;
// act- accion
boolean resultado = estructuraDeDatos.evaluarParEImpar(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoNumero4yObtengoParTest() {
// arrange definicion de la variables
int nro1 = 4;
// act- accion
boolean resultado = estructuraDeDatos.evaluarParEImpar(nro1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoNumero5yObtengoImparTest() {
// arrange definicion de la variables
int nro1 = 5;
// act- accion
boolean resultado = estructuraDeDatos.evaluarParEImpar(nro1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoNumero2yObtengo2Test() {
// arrange definicion de la variables
int nro1 = 2;
// act- accion
int resultado = estructuraDeDatos.evaluarCambioAPositivo(nro1);
// assert
assertEquals(2, resultado);
}
@Test
public void ingresoNumeroNegativo4yObtengo4Test() {
// arrange definicion de la variables
int nro1 = -4;
// act- accion
int resultado = estructuraDeDatos.evaluarCambioAPositivo(nro1);
// assert
assertEquals(4, resultado);
}
@Test
public void ingresoNumeroNegativo6yObtengo6Test() {
// arrange definicion de la variables
int nro1 = -6;
// act- accion
int resultado = estructuraDeDatos.evaluarCambioAPositivo(nro1);
// assert
assertEquals(6, resultado);
}
@Test
public void ingresoNumeroPositivo7yObtengo7Test() {
// arrange definicion de la variables
int nro1 = 7;
// act- accion
int resultado = estructuraDeDatos.evaluarCambioAPositivo(nro1);
// assert
assertEquals(7, resultado);
}
@Test
public void ingresoTrueTrueyTrueTest() {
// arrange definicion de la variables
boolean variable_1 = true;
boolean variable_2 = true;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadSi(variable_1, variable_2);
// assert
assertTrue(resultado);
}
@Test
public void ingresoTrueFalseyObtengoFalseTest() {
// arrange definicion de la variables
boolean variable_1 = true;
boolean variable_2 = false;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadSi(variable_1, variable_2);
// assert
assertFalse(resultado);
}
@Test
public void ingresoFalseTrueyObtengoFalseTest() {
// arrange definicion de la variables
boolean variable_1 = false;
boolean variable_2 = true;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadSi(variable_1, variable_2);
// assert
assertFalse(resultado);
}
@Test
public void ingresoFalseFalseyObtengoFalseTest() {
// arrange definicion de la variables
boolean variable_1 = false;
boolean variable_2 = false;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadSi(variable_1, variable_2);
// assert
assertFalse(resultado);
}
@Test
public void ingresoTrueTrueyObtengoTrueTest() {
// arrange definicion de la variables
boolean variable_1 = true;
boolean variable_2 = true;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadOr(variable_1, variable_2);
// assert
assertTrue(resultado);
}
@Test
public void ingresoTrueFalseyObtengoTrueTest() {
// arrange definicion de la variables
boolean variable_1 = true;
boolean variable_2 = false;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadOr(variable_1, variable_2);
// assert
assertTrue(resultado);
}
@Test
public void ingresoFalseTrueyObtengoTrueTest() {
// arrange definicion de la variables
boolean variable_1 = false;
boolean variable_2 = true;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadOr(variable_1, variable_2);
// assert
assertTrue(resultado);
}
@Test
public void ingresoFalseFalseyObtengoFalse2Test() {
// arrange definicion de la variables
boolean variable_1 = false;
boolean variable_2 = false;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadOr(variable_1, variable_2);
// assert
assertFalse(resultado);
}
@Test
public void ingresoTrueyObtengoFalseTest() {
// arrange definicion de la variables
boolean variable_1 = true;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadNegacion(variable_1);
// assert
assertFalse(resultado);
}
@Test
public void ingresoFalseyObtengoTrueTest() {
// arrange definicion de la variables
boolean variable_1 = false;
// act- accion
boolean resultado = estructuraDeDatos.evaluarTablasDeVerdadNegacion(variable_1);
// assert
assertTrue(resultado);
}
@Test
public void ingresoRojoyVerdeyObtengoNavidadTest() {
// arrange definicion de la variables
String color_1 = "Rojo";
String color_2 = "Verde";
// act- accion
String resultado = estructuraDeDatos.definirFestividad(color_1, color_2);
// assert
assertEquals("Navidad", resultado);
}
@Test
public void ingresoVerdeyNaranjayObtengoHalloweenTest() {
// arrange definicion de la variables
String color_1 = "Verde";
String color_2 = "Naranja";
// act- accion
String resultado = estructuraDeDatos.definirFestividad(color_1, color_2);
// assert
assertEquals("Halloween", resultado);
}
@Test
public void ingresoRojoyNaranjayObtengoPascuaTest() {
// arrange definicion de la variables
String color_1 = "Rojo";
String color_2 = "Naranja";
// act- accion
String resultado = estructuraDeDatos.definirFestividad(color_1, color_2);
// assert
assertEquals("Pascua", resultado);
}
@Test
public void ingreso8y18yObtengoTrue() {
// arrange definicion de la variables
int int1 = 8;
int int2 = 18;
// act- accion
boolean resultado = estructuraDeDatos.definirUltimo(int1, int2);
// assert
assertTrue(resultado);
}
@Test
public void ingreso3y113yObtengoTrue() {
// arrange definicion de la variables
int int1 = 3;
int int2 = 113;
// act- accion
boolean resultado = estructuraDeDatos.definirUltimo(int1, int2);
// assert
assertTrue(resultado);
}
@Test
public void ingreso6y117yObtengoTrue() {
// arrange definicion de la variables
int int1 = 6;
int int2 = 117;
// act- accion
boolean resultado = estructuraDeDatos.definirUltimo(int1, int2);
// assert
assertFalse(resultado);
}
@Test
public void ingreso8y18y30yObtengoTrue() {
// arrange definicion de la variables
int int1 = 8;
int int2 = 18;
int int3 = 30;
// act- accion
int resultado = estructuraDeDatos.definirMayor(int1, int2, int3);
// assert
assertEquals(30, resultado);
}
@Test
public void ingreso29y5y15yObtengoTrue() {
// arrange definicion de la variables
int int1 = 29;
int int2 = 5;
int int3 = 15;
// act- accion
int resultado = estructuraDeDatos.definirMayor(int1, int2, int3);
// assert
assertEquals(29, resultado);
}
@Test
public void ingreso10y50y5yObtengoTrue() {
// arrange definicion de la variables
int int1 = 10;
int int2 = 50;
int int3 = 5;
// act- accion
int resultado = estructuraDeDatos.definirMayor(int1, int2, int3);
// assert
assertEquals(50, resultado);
}
@Test
public void ingreso2y2yObtengo4() {
// arrange definicion de la variables
int int1 = 2;
int int2 = 2;
// act- accion
int resultado = estructuraDeDatos.multiplicarSumando(int1, int2);
// assert
assertEquals(4, resultado);
}
@Test
public void ingreso3y4yObtengo12() {
// arrange definicion de la variables
int int1 = 3;
int int2 = 4;
// act- accion
int resultado = estructuraDeDatos.multiplicarSumando(int1, int2);
// assert
assertEquals(12, resultado);
}
@Test
public void ingreso5y5yObtengo25() {
// arrange definicion de la variables
int int1 = 5;
int int2 = 5;
// act- accion
int resultado = estructuraDeDatos.multiplicarSumando(int1, int2);
// assert
assertEquals(25, resultado);
}
@Test
public void ingreso2y2yObtengoPotencia4() {
// arrange definicion de la variables
int int1 = 2;
int int2 = 2;
// act- accion
int resultado = estructuraDeDatos.potencia(int1, int2);
// assert
assertEquals(4, resultado);
}
@Test
public void ingreso3y4yObtengoPotencia81() {
// arrange definicion de la variables
int int1 = 3;
int int2 = 4;
// act- accion
int resultado = estructuraDeDatos.potencia(int1, int2);
// assert
assertEquals(81, resultado);
}
@Test
public void ingreso5y5yObtengoPotencia3125() {
// arrange definicion de la variables
int base = 5;
int potencia = 5;
// act- accion
int resultado = estructuraDeDatos.potencia(base, potencia);
// assert
assertEquals(3125, resultado);
}
@Test
public void ingreso2y2yObtengoPotencia4Pow() {
// arrange definicion de la variables
int int1 = 2;
int int2 = 2;
// act- accion
int resultado = estructuraDeDatos.potenciaPow(int1, int2);
// assert
assertEquals(4, resultado);
}
@Test
public void ingreso3y4yObtengoPotencia81Pow() {
// arrange definicion de la variables
int int1 = 3;
int int2 = 4;
// act- accion
int resultado = estructuraDeDatos.potenciaPow(int1, int2);
// assert
assertEquals(81, resultado);
}
@Test
public void ingreso5y5yObtengoPotencia3125Pow() {
// arrange definicion de la variables
int int1 = 5;
int int2 = 5;
// act- accion
int resultado = estructuraDeDatos.potenciaPow(int1, int2);
// assert
assertEquals(3125, resultado);
}
@Test
public void ingreso5y3y8y1yObtengoMayor8() {
// arrange definicion de la variables
int[] intArreglo = { 5, 3, 8, 1 };
// act- accion
int resultado = estructuraDeDatos.ArrayElementoMaximo(intArreglo);
// assert
assertEquals(8, resultado);
}
@Test
public void ingreso2y3y2y1yObtengoMayor3() {
// arrange definicion de la variables
int[] intArreglo = { 2, 3, 2, 1 };
// act- accion
int resultado = estructuraDeDatos.ArrayElementoMaximo(intArreglo);
// assert
assertEquals(3, resultado);
}
@Test
public void ingreso15y4y14yNeg5yObtengoMayor15() {
// arrange definicion de la variables
int[] intArreglo = { 15, 4, 14, -5 };
// act- accion
int resultado = estructuraDeDatos.ArrayElementoMaximo(intArreglo);
// assert
assertEquals(15, resultado);
}
@Test
public void ingreso6y3y8y1yObtengoTrue() {
// arrange definicion de la variables
int[] intArreglo = { 6, 3, 8, 1 };
// act- accion
boolean resultado = estructuraDeDatos.ArrayElementoSeis(intArreglo);
// assert
assertTrue(resultado);
}
@Test
public void ingreso2y3y2y6yObtengoTrue() {
// arrange definicion de la variables
int[] intArreglo = { 2, 3, 2, 6 };
// act- accion
boolean resultado = estructuraDeDatos.ArrayElementoSeis(intArreglo);
// assert
assertTrue(resultado);
}
@Test
public void ingreso6y4y14y6yObtengoTrue() {
// arrange definicion de la variables
int[] intArreglo = { 6, 4, 14, 6 };
// act- accion
boolean resultado = estructuraDeDatos.ArrayElementoSeis(intArreglo);
// assert
assertTrue(resultado);
}
@Test
public void ingreso5y4y2y1yObtengoFalse() {
// arrange definicion de la variables
int[] intArreglo = { 5, 4, 2, 1 };
// act- accion
boolean resultado = estructuraDeDatos.ArrayElementoSeis(intArreglo);
// assert
assertFalse(resultado);
}
@Test
public void ingresoArreglo6y3Arreglo9y1yObtengoArreglo() {
// arrange definicion de la variables
int[] intArreglo1 = { 6,3 };
int[] intArreglo2 = { 9,1 };
// act- accion
int[] resultado = estructuraDeDatos.ArrayMasGrande(intArreglo1, intArreglo2);
// assert
assertArrayEquals(intArreglo2,resultado);
}
@Test
public void ingresoArreglo2y3Arreglo2y6yObtengoArreglo() {
// arrange definicion de la variables
int[] intArreglo1 = { 2,3 };
int[] intArreglo2 = { 2,6 };
// act- accion
int[] resultado = estructuraDeDatos.ArrayMasGrande(intArreglo1, intArreglo2);
// assert
assertArrayEquals(intArreglo2,resultado);
}
@Test
public void ingresoArreglo6y4Arreglo1y6yObtengoArreglo() {
// arrange definicion de la variables
int[] intArreglo1 = { 6,4 };
int[] intArreglo2 = { 1,6 };
// act- accion
int[] resultado = estructuraDeDatos.ArrayMasGrande(intArreglo1, intArreglo2);
// assert
assertArrayEquals(intArreglo1,resultado);
}
@Test
public void ingresoTamano1yObtengoArreglo() {
// arrange definicion de la variables
int intContador = 1;
int [] arreglo= {0};
// act- accion
int[] resultado = estructuraDeDatos.ArrayConstruccion(intContador);
// assert
assertArrayEquals(arreglo,resultado);
}
@Test
public void ingresoTamano2yObtengoArreglo() {
// arrange definicion de la variables
int intContador = 2;
int [] arreglo= {0,1};
// act- accion
int[] resultado = estructuraDeDatos.ArrayConstruccion(intContador);
// assert
assertArrayEquals(arreglo,resultado);
}
@Test
public void ingresoTamano3yObtengoArreglo() {
// arrange definicion de la variables
int intContador = 3;
int [] arreglo= {0,1,2};
// act- accion
int[] resultado = estructuraDeDatos.ArrayConstruccion(intContador);
// assert
assertArrayEquals(arreglo,resultado);
}
@Test
public void ingresoTamano4yObtengoArreglo() {
// arrange definicion de la variables
int intContador = 4;
int [] arreglo= {0,1,2,3};
// act- accion
int[] resultado = estructuraDeDatos.ArrayConstruccion(intContador);
// assert
assertArrayEquals(arreglo,resultado);
}
@Test
public void ingresoArreglo2y2yObtengoMultiplicacionArreglo() {
// arrange definicion de la variables
int [] arreglo= {2,2};
// act- accion
int resultado = estructuraDeDatos.ArrayMultiplicacion(arreglo);
// assert
assertEquals(4,resultado);
}
@Test
public void ingresoArreglo3y4yObtengoMultiplicacionArreglo() {
// arrange definicion de la variables
int [] arreglo= {3,4};
// act- accion
int resultado = estructuraDeDatos.ArrayMultiplicacion(arreglo);
// assert
assertEquals(12,resultado);
}
@Test
public void ingresoArreglo5y5yObtengoMultiplicacionArreglo() {
// arrange definicion de la variables
int [] arreglo= {5,5};
// act- accion
int resultado = estructuraDeDatos.ArrayMultiplicacion(arreglo);
// assert
assertEquals(25,resultado);
}
@Test
public void ingresoArreglo1yObtengoFactorial() {
// arrange definicion de la variables
int num1= 1;
// act- accion
int resultado = estructuraDeDatos.Factorial(num1);
// assert
assertEquals(1,resultado);
}
@Test
public void ingresoArreglo2yObtengoFactorial() {
// arrange definicion de la variables
int num1= 2;
// act- accion
int resultado = estructuraDeDatos.Factorial(num1);
// assert
assertEquals(2,resultado);
}
@Test
public void ingresoArreglo3yObtengoFactorial() {
// arrange definicion de la variables
int num1= 3;
// act- accion
int resultado = estructuraDeDatos.Factorial(num1);
// assert
assertEquals(6,resultado);
}
@Test
public void ingresoNumero0yObtengoSumatoriaRecursiva() {
// arrange definicion de la variables
int num1= 0;
// act- accion
int resultado = estructuraDeDatos.SumatoriaRecursiva(num1);
// assert
assertEquals(0,resultado);
}
@Test
public void ingresoNumero1yObtengoSumatoriaRecursiva() {
// arrange definicion de la variables
int num1= 1;
// act- accion
int resultado = estructuraDeDatos.SumatoriaRecursiva(num1);
// assert
assertEquals(2,resultado);
}
@Test
public void ingresoNumero2yObtengoSumatoriaRecursiva() {
// arrange definicion de la variables
int num1= 2;
// act- accion
int resultado = estructuraDeDatos.SumatoriaRecursiva(num1);
// assert
assertEquals(5,resultado);
}
@Test
public void ingresoNumero4yObtengoSumatoriaRecursiva() {
// arrange definicion de la variables
int num1= 4;
// act- accion
int resultado = estructuraDeDatos.SumatoriaRecursiva(num1);
// assert
assertEquals(10,resultado);
}
}
| [
"[email protected]"
] | |
dec7604981b8038b9f8475402ef949ea6196e604 | c17e6a4bc29916381f870655651f9ea41e744e36 | /src/main/java/com/example/coronavirusdemo/models/StatsRo.java | 33b6914bbfd6371de9ef383354a1324efc021076 | [] | no_license | cosminpopescu14/coronavirus-app | dbc981d148b3e1c284df5e03a2e2cb56e4285588 | 4b56e438b1e8c90152146082213ea57f5b6d4056 | refs/heads/master | 2023-08-31T15:53:26.313894 | 2021-01-23T06:32:41 | 2021-01-23T06:32:41 | 244,305,402 | 3 | 0 | null | 2023-03-16T09:33:37 | 2020-03-02T07:18:19 | Java | UTF-8 | Java | false | false | 478 | java | package com.example.coronavirusdemo.models;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StatsRo {
private CoronaVirusStatsRo data;
@JsonProperty("data")
public CoronaVirusStatsRo getData() { return data; }
@JsonProperty("data")
public void setData(CoronaVirusStatsRo value) { this.data = value; }
@Override
public String toString() {
return "StatsRo{" +
"data=" + data +
'}';
}
}
| [
"[email protected]"
] | |
19b2669f1fb3680ac9b9e87607821e630dccef5b | ee1136d48902e52e331be61f1b83d46006258074 | /src/main/java/org/bitcoinj/core/Sha256Hash.java | 73f5e31ea842c75b31a32a6e7d151c0b736a79b4 | [
"MIT"
] | permissive | WaykiChain/wicc-wallet-utils-kotlin | 1d9361bb841e8ffa4123d39f81e17601a562e29f | 11cf81f4c567ff8aff229ebb03368642b0b0bad7 | refs/heads/master | 2021-12-15T00:45:32.088409 | 2020-08-24T09:40:07 | 2020-08-24T09:40:07 | 147,825,939 | 9 | 11 | null | 2020-01-09T10:58:20 | 2018-09-07T13:18:17 | Java | UTF-8 | Java | false | false | 9,611 | java | /*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.core;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be used as keys in a
* map. It also checks that the length is correct and provides a bit more type safety.
*/
public class Sha256Hash implements Serializable, Comparable<Sha256Hash> {
public static final int LENGTH = 32; // bytes
public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]);
private final byte[] bytes;
/**
* Use {@link #wrap(byte[])} instead.
*/
@Deprecated
public Sha256Hash(byte[] rawHashBytes) {
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
}
/**
* Use {@link #wrap(String)} instead.
*/
@Deprecated
public Sha256Hash(String hexString) {
checkArgument(hexString.length() == LENGTH * 2);
this.bytes = Utils.HEX.decode(hexString);
}
/**
* Creates a new instance that wraps the given hash value.
*
* @param rawHashBytes the raw hash bytes to wrap
* @return a new instance
* @throws IllegalArgumentException if the given array length is not exactly 32
*/
@SuppressWarnings("deprecation") // the constructor will be made private in the future
public static Sha256Hash wrap(byte[] rawHashBytes) {
return new Sha256Hash(rawHashBytes);
}
/**
* Creates a new instance that wraps the given hash value (represented as a hex string).
*
* @param hexString a hash value represented as a hex string
* @return a new instance
* @throws IllegalArgumentException if the given string is not a valid
* hex string, or if it does not represent exactly 32 bytes
*/
public static Sha256Hash wrap(String hexString) {
return wrap(Utils.HEX.decode(hexString));
}
/**
* Creates a new instance that wraps the given hash value, but with byte order reversed.
*
* @param rawHashBytes the raw hash bytes to wrap
* @return a new instance
* @throws IllegalArgumentException if the given array length is not exactly 32
*/
@SuppressWarnings("deprecation") // the constructor will be made private in the future
public static Sha256Hash wrapReversed(byte[] rawHashBytes) {
return wrap(Utils.reverseBytes(rawHashBytes));
}
/** Use {@link #of(byte[])} instead: this old name is ambiguous. */
@Deprecated
public static Sha256Hash create(byte[] contents) {
return of(contents);
}
/**
* Creates a new instance containing the calculated (one-time) hash of the given bytes.
*
* @param contents the bytes on which the hash value is calculated
* @return a new instance containing the calculated (one-time) hash
*/
public static Sha256Hash of(byte[] contents) {
return wrap(hash(contents));
}
/** Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. */
@Deprecated
public static Sha256Hash createDouble(byte[] contents) {
return twiceOf(contents);
}
/**
* Creates a new instance containing the hash of the calculated hash of the given bytes.
*
* @param contents the bytes on which the hash value is calculated
* @return a new instance containing the calculated (two-time) hash
*/
public static Sha256Hash twiceOf(byte[] contents) {
return wrap(hashTwice(contents));
}
/**
* Creates a new instance containing the calculated (one-time) hash of the given file's contents.
*
* The file contents are read fully into memory, so this method should only be used with small files.
*
* @param file the file on which the hash value is calculated
* @return a new instance containing the calculated (one-time) hash
* @throws IOException if an error occurs while reading the file
*/
public static Sha256Hash of(File file) throws IOException {
FileInputStream in = new FileInputStream(file);
try {
return of(ByteStreams.toByteArray(in));
} finally {
in.close();
}
}
/**
* Returns a new SHA-256 MessageDigest instance.
*
* This is a convenience method which wraps the checked
* exception that can never occur with a RuntimeException.
*
* @return a new SHA-256 MessageDigest instance
*/
public static MessageDigest newDigest() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); // Can't happen.
}
}
/**
* Calculates the SHA-256 hash of the given bytes.
*
* @param input the bytes to hash
* @return the hash (in big-endian order)
*/
public static byte[] hash(byte[] input) {
return hash(input, 0, input.length);
}
/**
* Calculates the SHA-256 hash of the given byte range.
*
* @param input the array containing the bytes to hash
* @param offset the offset within the array of the bytes to hash
* @param length the number of bytes to hash
* @return the hash (in big-endian order)
*/
public static byte[] hash(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest();
}
/**
* Calculates the SHA-256 hash of the given bytes,
* and then hashes the resulting hash again.
*
* @param input the bytes to hash
* @return the double-hash (in big-endian order)
*/
public static byte[] hashTwice(byte[] input) {
return hashTwice(input, 0, input.length);
}
/**
* Calculates the SHA-256 hash of the given byte range,
* and then hashes the resulting hash again.
*
* @param input the array containing the bytes to hash
* @param offset the offset within the array of the bytes to hash
* @param length the number of bytes to hash
* @return the double-hash (in big-endian order)
*/
public static byte[] hashTwice(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest(digest.digest());
}
/**
* Calculates the hash of hash on the given byte ranges. This is equivalent to
* concatenating the two ranges and then passing the result to {@link #hashTwice(byte[])}.
*/
public static byte[] hashTwice(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2) {
MessageDigest digest = newDigest();
digest.update(input1, offset1, length1);
digest.update(input2, offset2, length2);
return digest.digest(digest.digest());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return Arrays.equals(bytes, ((Sha256Hash)o).bytes);
}
/**
* Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable hash code even for
* blocks, where the goal is to try and get the first bytes to be zeros (i.e. the value as a big integer lower
* than the target value).
*/
@Override
public int hashCode() {
// Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin.
return Ints.fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]);
}
@Override
public String toString() {
return Utils.HEX.encode(bytes);
}
/**
* Returns the bytes interpreted as a positive integer.
*/
public BigInteger toBigInteger() {
return new BigInteger(1, bytes);
}
/**
* Returns the internal byte array, without defensively copying. Therefore do NOT modify the returned array.
*/
public byte[] getBytes() {
return bytes;
}
/**
* Returns a reversed copy of the internal byte array.
*/
public byte[] getReversedBytes() {
return Utils.reverseBytes(bytes);
}
@Override
public int compareTo(final Sha256Hash other) {
for (int i = LENGTH - 1; i >= 0; i--) {
final int thisByte = this.bytes[i] & 0xff;
final int otherByte = other.bytes[i] & 0xff;
if (thisByte > otherByte)
return 1;
if (thisByte < otherByte)
return -1;
}
return 0;
}
}
| [
"[email protected]"
] | |
b2709f51e4d401687adb0b1c2714a5732ad3e5b9 | fab995fb25bfd363b8f699ef4b56c00e7ea0198f | /src/simple/BadRund.java | 66c4ceeaef764305c4981558beb62e1ac5fc46e7 | [
"MIT"
] | permissive | Mangara/CodeCup2012 | 4e4bb7fae9b0d920a9e0820876c9b4980eef7d66 | f3a400bdd57a702be5a2718275cb6869e5800f42 | refs/heads/master | 2021-09-04T10:09:13.347535 | 2018-01-17T20:58:10 | 2018-01-17T20:58:10 | 117,888,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,098 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package simple;
import framework.QTTTGame;
import java.io.IOException;
import montecarlo.MCPlayer;
/**
*
* @author Sander
*/
public class BadRund extends MCPlayer {
public static void main(String[] args) throws IOException {
new BadRund();
}
public BadRund() throws IOException {
System.err.println("R BadRund");
game.run(this);
}
@Override
public byte[] selectFirstMove() {
return selectMove();
}
@Override
public byte[] selectMove() {
// Make a random move
byte move1 = randomMove();
byte move2 = randomMove();
while (move1 == move2 && game.currentTurn < 16) {
move2 = randomMove();
}
return new byte[] {move1, move2};
}
@Override
public byte selectCollapse(byte move1, byte move2) {
// Select one randomly
if (QTTTGame.random.nextBool()) {
return move1;
} else {
return move2;
}
}
}
| [
"[email protected]"
] | |
ff0d5ab8676708749767ad6407515becd254c7dc | 0387c5473495a0c0d9542f208a6c6f827d4747cd | /rbv/src/main/java/com/axway/ats/rbv/filesystem/rules/FileGidRule.java | c30ab09d03e8f245934c662624356e315b3776ac | [
"Apache-2.0"
] | permissive | radokostadinov/ats-framework | fd1c02dc5776bfa1dfc66400d357a05c19581c24 | 78b154de004aa61fee5769b7cdaaa03945a9b37d | refs/heads/master | 2021-05-07T07:38:00.646735 | 2017-11-01T13:32:04 | 2017-11-01T13:33:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,818 | java | /*
* Copyright 2017 Axway Software
*
* 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.axway.ats.rbv.filesystem.rules;
import java.util.ArrayList;
import java.util.List;
import com.axway.ats.action.objects.FilePackage;
import com.axway.ats.action.objects.model.PackageException;
import com.axway.ats.rbv.MetaData;
import com.axway.ats.rbv.filesystem.FileSystemMetaData;
import com.axway.ats.rbv.model.RbvException;
import com.axway.ats.rbv.model.RbvStorageException;
import com.axway.ats.rbv.rules.AbstractRule;
@SuppressWarnings("boxing")
public class FileGidRule extends AbstractRule {
private long gid;
public FileGidRule( long gid,
String ruleName,
boolean expectedResult ) {
super( ruleName, expectedResult, FileSystemMetaData.class );
//init members
this.gid = gid;
}
/**
* Match with the GID of the specified file.
*
* @param atsAgent the address of the remote ATS agent
* @param filePath the path name of the file for comparison
* @param ruleName the rule name
* @param expectedResult the expected result
* @throws RbvException
*/
public FileGidRule( String atsAgent,
String filePath,
String ruleName,
boolean expectedResult ) throws RbvException {
super( ruleName, expectedResult, FileSystemMetaData.class );
// get source file's gid
try {
FilePackage file = new FilePackage( atsAgent, filePath );
this.gid = file.getGid();
} catch( PackageException pe ) {
throw new RbvStorageException( pe );
}
}
@Override
public boolean performMatch(
MetaData metaData ) throws RbvException {
boolean actualResult = false;
if( metaData instanceof FileSystemMetaData ) {
//get the file from the meta data
FilePackage file = ( ( FileSystemMetaData ) metaData ).getFilePackage();
try {
//get destination file's GID
long destGid = file.getGid();
// if either of the GID values (expected and actual) is the NOT_SUPPORTED
// value then we are not able to verify them and we should return true
if( this.gid == FilePackage.ATTRIBUTE_NOT_SUPPORTED
|| destGid == FilePackage.ATTRIBUTE_NOT_SUPPORTED ) {
actualResult = true;
} else {
actualResult = destGid == this.gid;
}
} catch( PackageException pe ) {
throw new RbvStorageException( pe );
}
}
return actualResult;
}
@Override
protected String getRuleDescription() {
return "which expects file with GID " + ( getExpectedResult()
? ""
: "different than " ) + "'" + this.gid + "'";
}
public List<String> getMetaDataKeys() {
List<String> metaKeys = new ArrayList<String>();
metaKeys.add( FileSystemMetaData.FILE_PACKAGE );
return metaKeys;
}
}
| [
"[email protected]"
] | |
ea5af465e88a4f4e5a9efe0780ad1fc95750fb57 | aedf44cae53e4ed0e3173fe03120d557ba445ba7 | /src/test/java/fr/locapov/app/web/rest/util/PaginationUtilUnitTest.java | f00c48d5efb335a83a5daffcc2e36f4691f1def2 | [] | no_license | Locapov/locapov-front | 6596166dfec4c4b022e213d948a828b17acb3a10 | 2948cbe1696cc41b39662d83999a5ed29819027c | refs/heads/master | 2021-08-30T11:29:24.061672 | 2017-12-17T18:55:14 | 2017-12-17T18:55:14 | 114,560,705 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,743 | java | package fr.locapov.app.web.rest.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
/**
* Tests based on parsing algorithm in app/components/util/pagination-util.service.js
*
* @see PaginationUtil
*/
public class PaginationUtilUnitTest {
@Test
public void generatePaginationHttpHeadersTest() {
String baseUrl = "/api/_search/example";
List<String> content = new ArrayList<>();
Page<String> page = new PageImpl<>(content, new PageRequest(6, 50), 400L);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
List<String> strHeaders = headers.get(HttpHeaders.LINK);
assertNotNull(strHeaders);
assertTrue(strHeaders.size() == 1);
String headerData = strHeaders.get(0);
assertTrue(headerData.split(",").length == 4);
String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
+ "</api/_search/example?page=5&size=50>; rel=\"prev\","
+ "</api/_search/example?page=7&size=50>; rel=\"last\","
+ "</api/_search/example?page=0&size=50>; rel=\"first\"";
assertEquals(expectedData, headerData);
List<String> xTotalCountHeaders = headers.get("X-Total-Count");
assertTrue(xTotalCountHeaders.size() == 1);
assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
}
| [
"[email protected]"
] | |
3c0e0e8c1e5f0bb7c1524d39e778a4cd5124d542 | b7bcff9ea821d90071cbff87872e7640bd6aff68 | /core/src/java/org/opencrx/application/uses/ezvcard/property/Categories.java | f1234f8a3d91322eeae721e43a2232ec86a00732 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"Apache-2.0",
"JSON"
] | permissive | sangjiexun/opencrx4 | 26be272f64a872713964cbb6128c9af35d3d8516 | 4e8fb194f5b392e3efca228ab88500bcbcfb83b0 | refs/heads/master | 2020-12-28T09:36:05.167852 | 2017-10-14T08:40:57 | 2017-10-14T08:40:57 | 238,270,604 | 1 | 0 | null | 2020-02-04T18:00:05 | 2020-02-04T18:00:04 | null | UTF-8 | Java | false | false | 3,604 | java | package org.opencrx.application.uses.ezvcard.property;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.opencrx.application.uses.ezvcard.VCardVersion;
/*
Copyright (c) 2013, Michael Angstadt
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.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
/**
* <p>
* Defines a list of keywords that can be used to describe the person.
* </p>
*
* <p>
* <b>Code sample</b>
* </p>
*
* <pre class="brush:java">
* VCard vcard = new VCard();
*
* Categories categories = new Categories();
* categories.addValue("Developer");
* categories.addValue("Java coder");
* categories.addValue("Ladies' man");
* vcard.setCategories(categories);
* </pre>
*
* <p>
* <b>Property name:</b> {@code CATEGORIES}
* </p>
* <p>
* <b>Supported versions:</b> {@code 3.0, 4.0}
* </p>
* @author Michael Angstadt
*/
public class Categories extends TextListProperty implements HasAltId {
@Override
public List<Integer[]> getPids() {
return super.getPids();
}
@Override
public void addPid(int localId, int clientPidMapRef) {
super.addPid(localId, clientPidMapRef);
}
@Override
public void removePids() {
super.removePids();
}
@Override
public Integer getPref() {
return super.getPref();
}
@Override
public void setPref(Integer pref) {
super.setPref(pref);
}
//@Override
public String getAltId() {
return parameters.getAltId();
}
//@Override
public void setAltId(String altId) {
parameters.setAltId(altId);
}
/**
* Gets the TYPE parameter.
* <p>
* <b>Supported versions:</b> {@code 4.0}
* </p>
* @return the TYPE value (typically, this will be either "work" or "home")
* or null if it doesn't exist
*/
public String getType() {
return parameters.getType();
}
/**
* Sets the TYPE parameter.
* <p>
* <b>Supported versions:</b> {@code 4.0}
* </p>
* @param type the TYPE value (this should be either "work" or "home") or
* null to remove
*/
public void setType(String type) {
parameters.setType(type);
}
@Override
public Set<VCardVersion> _supportedVersions() {
return EnumSet.of(VCardVersion.V3_0, VCardVersion.V4_0);
}
}
| [
"[email protected]"
] | |
dac1f04fceed254f47d559d00808f1e2a190a46b | b39a7ccf23511fb84d31a93a59cee7d54f70bdf7 | /downloader/src/main/java/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java | 2a0a4a30d0f6e1b82e5200a174cd543427901e76 | [] | no_license | Thram/thram-expansion-tools | a9af11badc68afc6de2bd90eaa399ead04e215f3 | e6c25fba0c5af559e76730468f71ae59d0316e4c | refs/heads/master | 2021-01-18T06:30:09.021256 | 2016-01-10T22:51:41 | 2016-01-10T22:51:41 | 48,403,425 | 3 | 1 | null | 2016-06-12T20:51:56 | 2015-12-22T01:32:44 | Java | UTF-8 | Java | false | false | 9,458 | java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.vending.expansion.downloader.impl;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Messenger;
import android.support.v7.app.NotificationCompat;
import com.android.vending.expansion.downloader.R;
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
/**
* This class handles displaying the notification associated with the download
* queue going on in the download manager. It handles multiple status types;
* Some require user interaction and some do not. Some of the user interactions
* may be transient. (for example: the user is queried to continue the download
* on 3G when it started on WiFi, but then the phone locks onto WiFi again so
* the prompt automatically goes away)
* <p/>
* The application interface for the downloader also needs to understand and
* handle these transient states.
*/
public class DownloadNotification implements IDownloaderClient {
private int mState;
private final Context mContext;
private final NotificationManager mNotificationManager;
private String mCurrentTitle;
private IDownloaderClient mClientProxy;
final ICustomNotification mCustomNotification;
private Notification mNotification;
private Notification mCurrentNotification;
private CharSequence mLabel;
private String mCurrentText;
private PendingIntent mContentIntent;
private DownloadProgressInfo mProgressInfo;
static final String LOGTAG = "DownloadNotification";
static final int NOTIFICATION_ID = LOGTAG.hashCode();
public PendingIntent getClientIntent() {
return mContentIntent;
}
public void setClientIntent(PendingIntent mClientIntent) {
this.mContentIntent = mClientIntent;
}
public void resendState() {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(mState);
}
}
@Override
public void onDownloadStateChanged(int newState) {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(newState);
}
if (newState != mState) {
mState = newState;
if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
return;
}
int stringDownloadID;
int iconResource;
boolean ongoingEvent;
// get the new title string and paused text
switch (newState) {
case 0:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = R.string.state_unknown;
ongoingEvent = false;
break;
case IDownloaderClient.STATE_DOWNLOADING:
iconResource = android.R.drawable.stat_sys_download;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_FETCHING_URL:
case IDownloaderClient.STATE_CONNECTING:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_COMPLETED:
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
default:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
}
mCurrentText = mContext.getString(stringDownloadID);
mCurrentTitle = mLabel.toString();
NotificationCompat.Builder builder = new NotificationCompat.Builder(
mContext);
mCurrentNotification = builder.setContentIntent(mContentIntent)
.setSmallIcon(iconResource).setTicker(mLabel + ": " + mCurrentText)
.setAutoCancel(true).setContentTitle(mCurrentTitle)
.setContentText(mCurrentText).build();
if (ongoingEvent) {
mCurrentNotification.flags |= Notification.FLAG_ONGOING_EVENT;
} else {
mCurrentNotification.flags &= ~Notification.FLAG_ONGOING_EVENT;
mCurrentNotification.flags |= Notification.FLAG_AUTO_CANCEL;
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
}
@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
mProgressInfo = progress;
if (null != mClientProxy) {
mClientProxy.onDownloadProgress(progress);
}
if (progress.mOverallTotal <= 0) {
// we just show the text
NotificationCompat.Builder builder = new NotificationCompat.Builder(
mContext);
mNotification = builder.setContentIntent(mContentIntent)
.setSmallIcon(android.R.drawable.stat_sys_download).setTicker(mCurrentText)
.setAutoCancel(true).setContentTitle(mCurrentTitle)
.setContentText(mCurrentText).build();
mCurrentNotification = mNotification;
} else {
mCustomNotification.setCurrentBytes(progress.mOverallProgress);
mCustomNotification.setTotalBytes(progress.mOverallTotal);
mCustomNotification.setIcon(android.R.drawable.stat_sys_download);
mCustomNotification.setPendingIntent(mContentIntent);
mCustomNotification.setTicker(mLabel + ": " + mCurrentText);
mCustomNotification.setTitle(mLabel);
mCustomNotification.setTimeRemaining(progress.mTimeRemaining);
mCurrentNotification = mCustomNotification.updateNotification(mContext);
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
public interface ICustomNotification {
void setTitle(CharSequence title);
void setTicker(CharSequence ticker);
void setPendingIntent(PendingIntent mContentIntent);
void setTotalBytes(long totalBytes);
void setCurrentBytes(long currentBytes);
void setIcon(int iconResource);
void setTimeRemaining(long timeRemaining);
Notification updateNotification(Context c);
}
/**
* Called in response to onClientUpdated. Creates a new proxy and notifies
* it of the current state.
*
* @param msg the client Messenger to notify
*/
public void setMessenger(Messenger msg) {
mClientProxy = DownloaderClientMarshaller.CreateProxy(msg);
if (null != mProgressInfo) {
mClientProxy.onDownloadProgress(mProgressInfo);
}
if (mState != -1) {
mClientProxy.onDownloadStateChanged(mState);
}
}
/**
* Constructor
*
* @param ctx The context to use to obtain access to the Notification
* Service
*/
DownloadNotification(Context ctx, CharSequence applicationLabel) {
mState = -1;
mContext = ctx;
mLabel = applicationLabel;
mNotificationManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mCustomNotification = CustomNotificationFactory
.createCustomNotification();
mNotification = new Notification();
mCurrentNotification = mNotification;
}
@Override
public void onServiceConnected(Messenger m) {
}
}
| [
"[email protected]"
] | |
b620a467281897b8fcbab30298303fcf3d4a5957 | f3c0edd0705f0f286aade9e6e5510028fb5c3db1 | /Aula7/Exercicio1 Porta/Principal.java | e9260074ecc710bf052fac72c66ac512d7a6beeb | [
"MIT"
] | permissive | marciopocebon/Exercicios | 6bd00c3e6c626f4c7438151cf41c921f1bfff4b8 | ea25e81b036d000d1630cf7c2a6d831bca49d472 | refs/heads/master | 2022-10-24T07:41:32.587580 | 2020-06-15T01:54:31 | 2020-06-15T01:54:31 | 318,780,838 | 1 | 0 | MIT | 2020-12-05T12:18:29 | 2020-12-05T12:18:28 | null | UTF-8 | Java | false | false | 322 | java | public class Principal {
public static void main(String args[]) {
System.out.println("\f");
Porta porta = new Porta(25, 14, 30, "Sim", "Azul");
System.out.println(porta);
Porta porta1 = new Porta(30,40,30, "Não", "Verde");
System.out.println(porta1);
}
} | [
"[email protected]"
] | |
42b782e1b5b16b7e37a606c1c2c5a55a5f10ae77 | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-800-Files/boiler-To-Generate-800-Files/syncregions-800Files/TemperatureController3910.java | 87d97b4da1307f0d6dda2def8470625083575690 | [] | no_license | soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464889 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | Java | UTF-8 | Java | false | false | 367 | java | package syncregions;
public class TemperatureController3910 {
public execute(int temperature3910, int targetTemperature3910) {
//sync _bfpnFUbFEeqXnfGWlV3910, behaviour
1-if(temperatureDifference > 0 && boilerStatus == true) { return 1; } else if (temperatureDifference < 0 && boilerStatus == false) { return 2; } else return 0;
//endSync
}
}
| [
"[email protected]"
] | |
424adec784de80d4f4d6dd056a95fd71bd103f97 | b3c1ff870ffe77c9aa2e39f93bb725e0919a7d43 | /WOOBIN/src/woobin/Test4.java | 9d7ae4e1dc9836cb0f3a3b11c9b76937d77f1221 | [] | no_license | WOOBINKIM0518/eclipse-workspace | 96e2ea13ee0fb845717a84c32d67070fd872ef6f | 03ce277138b6e749d17f2381b0864aeeb32a485e | refs/heads/master | 2023-06-27T09:49:05.727080 | 2021-07-23T09:21:29 | 2021-07-23T09:21:29 | 385,150,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 511 | java | package woobin;
public class Test4 {
public static void main(String[] args) {
int lineCount = 4;
int starCount = 1;
int spaceCount = 0;
for (int i =0 ; i < lineCount; i++) {
for ( int j = 0; j <spaceCount; j++) {
System.out.print(' ');
}
for(int j = 0 ; j < starCount ; j++) {
System.out.print('*');
}
for (int j =0; j < spaceCount; j++ ) {
System.out.print(' ');
}
spaceCount -=1;
starCount +=1;
System.out.println();
}
}
} | [
"[email protected]"
] | |
6e1c5c56317eac5060dda8036aded88541b30f35 | 3444c615563c0c8a6542d4d3a6d07a42250b9f5b | /ex7/src/oop/ex7/types/DoubleVariable.java | b48b1506c579d279e737262c038902d94657b10d | [] | no_license | liatgin/Object-Oriented-Programming | 489957d8a3b7cb2500baa35b5a1f3778e598513c | a929a8dac67e2a9ac3238561fc6fa616b946d289 | refs/heads/master | 2021-07-09T15:24:47.116460 | 2017-10-08T12:56:54 | 2017-10-08T12:56:55 | 106,175,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 817 | java | package oop.ex7.types;
import oop.ex7.main.IllegalCodeException;
import oop.ex7.regex.RegexBox;
/**
* class Double variable.
* represents a variable of the type Double.
*/
public class DoubleVariable extends Type {
/**
* constructor.
* @param value a double value.
* @throws IllegalCodeException
*/
public DoubleVariable(String value) throws IllegalCodeException {
super(value);
isValidValue(value);
}
/**
* constructor.
* @param values an array of Double values.
* @throws IllegalCodeException
*/
public DoubleVariable(String[] values) throws IllegalCodeException {
super(values);
}
/**
* checks whether the value is valid.
*/
public void isValidValue(String value) throws IllegalCodeException {
regex=RegexBox.DOUBLE_VALUE;
super.isValidValue(value);
}
} | [
"[email protected]"
] | |
2e7c0046513e624c8d9fa986ecb6abb3c6a04c07 | d9f29ab34ea1589c87a0f532b0912bc3935a74f3 | /app/src/main/java/com/example/bustransport/TimingsFragment.java | 7245364f52345e3682230bfaf96d1f9bdff553b9 | [] | no_license | Annamayya-0513/BusTransport | e0ab98472ae9081dac0b1ff7340dc0e9541442f7 | 23a1554144d49dd695802c379b54de659fffba2d | refs/heads/master | 2021-04-10T04:41:47.199351 | 2020-03-21T05:14:54 | 2020-03-21T05:14:54 | 248,911,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 562 | java | package com.example.bustransport;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TimingsFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.timings_fragment,container,false);
}
}
| [
"[email protected]"
] | |
762b16eb7af02e27c39ef667d537285e1e7e182b | 91d05cadcb7a027e382491b252407777dcad1bce | /samples/src/main/java/org/alfonz/samples/alfonzrest/entity/RepoEntity.java | 7241aaa0edd8fca9953fbddfb116f2acc9f66c0c | [
"Apache-2.0"
] | permissive | salvopr/Alfonz | f4bb27d273d16289c817f8e52ee8607f20444db9 | 4e185bce09fe58aaeb39f10a3e6b00d24f306858 | refs/heads/master | 2020-03-18T10:16:38.876713 | 2018-03-23T16:41:27 | 2018-03-23T16:41:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,427 | java | package org.alfonz.samples.alfonzrest.entity;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
public class RepoEntity
{
@SerializedName("id") private long id;
@SerializedName("name") private String name;
@SerializedName("owner") private OwnerEntity owner;
@SerializedName("private") private boolean isPrivate;
@SerializedName("html_url") private String htmlUrl;
@SerializedName("description") private String description;
@SerializedName("fork") private boolean fork;
@SerializedName("url") private String url;
@SerializedName("created_at") private Date createdAt;
@SerializedName("updated_at") private Date updatedAt;
@SerializedName("pushed_at") private Date pushedAt;
@SerializedName("stargazers_count") private int stargazersCount;
@SerializedName("watchers_count") private int watchersCount;
@SerializedName("language") private String language;
@SerializedName("forks_count") private int forksCount;
@SerializedName("open_issues_count") private int openIssuesCount;
@SerializedName("subscribers_count") private int subscribersCount;
public RepoEntity()
{
}
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;
}
public OwnerEntity getOwner()
{
return owner;
}
public void setOwner(OwnerEntity owner)
{
this.owner = owner;
}
public boolean isPrivate()
{
return isPrivate;
}
public void setPrivate(boolean isPrivate)
{
this.isPrivate = isPrivate;
}
public String getHtmlUrl()
{
return htmlUrl;
}
public void setHtmlUrl(String htmlUrl)
{
this.htmlUrl = htmlUrl;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public boolean isFork()
{
return fork;
}
public void setFork(boolean fork)
{
this.fork = fork;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public Date getCreatedAt()
{
return createdAt;
}
public void setCreatedAt(Date createdAt)
{
this.createdAt = createdAt;
}
public Date getUpdatedAt()
{
return updatedAt;
}
public void setUpdatedAt(Date updatedAt)
{
this.updatedAt = updatedAt;
}
public Date getPushedAt()
{
return pushedAt;
}
public void setPushedAt(Date pushedAt)
{
this.pushedAt = pushedAt;
}
public int getStargazersCount()
{
return stargazersCount;
}
public void setStargazersCount(int stargazersCount)
{
this.stargazersCount = stargazersCount;
}
public int getWatchersCount()
{
return watchersCount;
}
public void setWatchersCount(int watchersCount)
{
this.watchersCount = watchersCount;
}
public String getLanguage()
{
return language;
}
public void setLanguage(String language)
{
this.language = language;
}
public int getForksCount()
{
return forksCount;
}
public void setForksCount(int forksCount)
{
this.forksCount = forksCount;
}
public int getOpenIssuesCount()
{
return openIssuesCount;
}
public void setOpenIssuesCount(int openIssuesCount)
{
this.openIssuesCount = openIssuesCount;
}
public int getSubscribersCount()
{
return subscribersCount;
}
public void setSubscribersCount(int subscribersCount)
{
this.subscribersCount = subscribersCount;
}
}
| [
"[email protected]"
] | |
7b2c6ddef3e51acedef0f38930a6e7506d46613a | 9fb373c3501c5dd1d3baac53c68b9becafe18ea6 | /src/com/pabula/fw/action/AjaxModifyRequestHelper.java | 3d8bcafc8cc9275c0e8fea3c99680ac739affcab | [] | no_license | 253133851/XCOOPER_J | 2469dab030e59985eab6576666b68382a3c5f849 | 24565e5fe0f41e70335e01b42f00ad38ac909b37 | refs/heads/master | 2021-01-01T05:24:36.170195 | 2016-05-03T04:00:46 | 2016-05-03T04:00:46 | 56,374,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,175 | java | package com.pabula.fw.action;
import com.xcooper.ENV;
import com.pabula.common.util.StrUtil;
import com.pabula.common.util.ValidateUtil;
import com.pabula.fw.exception.RuleException;
import com.pabula.fw.utility.AbstractRequestHelper;
import com.pabula.fw.utility.Command;
import com.pabula.fw.utility.VO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* �첽�ύ�ı?
* Created by sunsai on 2015/9/3.
*/
public class AjaxModifyRequestHelper extends AbstractRequestHelper {
public AjaxModifyRequestHelper(HttpServletRequest request, HttpServletResponse response, ServletContext application) {
super(request, response, application);
// ��request�е�ֵ������VO��
VO vo = this.getVOClass(request);
super.requestValueToVO(request, vo);
super.setVO(vo);
}
/**
* �ع�getCommand��������ݵ�validate����
*/
public Command getCommand() throws RuleException {
Command command = super.getCommand();
//ִ��ʵ���ҵ��Command�е�validate ���� ������ݼ�⣬�������ݲ��Ϸ��ģ����׳�RuleException����CMSController����
ValidateUtil validate = new ValidateUtil();
command.validate(getRequest(),getVO(),validate);
if (validate.hasError()) {
//�Ѵ����list����ָ���Ĵ�����ҳ���д��?��ʾ
RuleException e = new RuleException();
e.setErrColl(validate.getErrors());
throw e;
}
return command;
}
public ServletContext getApplication() {
return null;
}
/**
* ���action����̬����ҵ���VO��
* @param request
* @return
* @author pabula 2015-6-27 ����11:35:16
*/
public VO getVOClass(HttpServletRequest request) {
VO vo = null;
String voClassMainName = "";
//VO��������ƾ���actionֵȥ��ǰ���add�ַ�����action=addMember����ȥ��add������member
String busiName = (String)(StrUtil.split(request.getParameter("action"), '!').get(0));
String action = (String)(StrUtil.split(request.getParameter("action"),'!').get(1));
voClassMainName = action.substring("AjaxModify".length());
//ƴ�ӳ� ҵ��vo ����·�� ������ com.pabula.hh.Member.vo.MemberVO
String className = ENV.VO_PACKAGE_NAME + "." + busiName + ".vo." + voClassMainName + "VO";
System.err.println("VOClass: " + className);
try {
//��̬����vo��
vo = (VO) Class.forName(className).newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return vo;
}
}
| [
"[email protected]"
] | |
7e5467a006283a534a42817cabe2b658afdca28f | 632ca1acb081bf042c2600b92d712a8d9683a972 | /src/main/java/com/banner/bean/ConStantBannerType.java | d89e4e1faee51fd7c64a65ce73be56ec5ad825ba | [
"Apache-2.0"
] | permissive | oryjk/portal | 4a5b9e1a66a796fa8e6049ad75e602a7b2e0c60e | b764518e3c2d7d21bfe2b0ccd14e98a248291102 | refs/heads/master | 2021-01-10T06:03:31.348938 | 2016-01-30T02:06:39 | 2016-01-30T02:06:39 | 50,703,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 632 | java | package com.banner.bean;
import org.springframework.stereotype.Component;
/**
* Created by wangyirui on 28/12/15.
*/
@Component
public class ConStantBannerType {
public static final Integer HOME_TYPE = 1;//首页banner
public static final Integer JUEDANGTAO_TYPE = 2;//绝当淘banner
public static final Integer SHOUYITAO_TYPE = 3;//收益淘banner
public static final Integer NEWS_TYPE = 4;//新闻banner
public static final Integer ABOUTUS_TYPE = 5;//关于我们banner
public static final Integer SHOW_STATUS=1;//设为banner显示
public static final Integer HIDDEN_STATUS=0;//不设为banner
}
| [
"[email protected]"
] | |
2bddbad3d05fd28df61641b762c77f77dc70d87e | 502fb76597e782f31aae799a32d1c7b4db393d93 | /2019-2020 Season/3583/Tests/DriveSpeed.java | e1bf362a7be5582954ef5df4bf0d5f9bc49dff75 | [] | no_license | powerhawks/FTCCodeArchive | 3fd0da96b517f5953b7501fc35a46d2160255fcf | a11338a3da61d059cd5cb424316c9b34ff314403 | refs/heads/master | 2021-06-25T03:59:11.534575 | 2020-12-05T22:43:29 | 2020-12-05T22:43:29 | 172,997,069 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 284 | java | package org.firstinspires.ftc.teamcode.Tests;
enum DriveSpeed {
LOWPOWER(.25), MIDPOWER(.75), HIGHPOWER(1.0);
private double speed;
private DriveSpeed(double speed){
this.speed = speed;
}
double getSpeed(){
return speed;
}
}
| [
"[email protected]"
] | |
4e80247a551ff4c1f8c1c43bce5ec2f33b2ff780 | 432c8fa04729bc808e463b41b49f1014c5ee3241 | /report-phresco-plugin/src/main/java/com/photon/phresco/plugins/XmlReport.java | 46b8d0b705275f6d1cd2a97dfc2598a97007b14e | [] | no_license | piyushshekhar/plugins | 96cf922977cb44ba8ca2a6ad1977fdeb5efbb27e | 97dd6a429866f63c35be777e6dc82b2a3b6b235e | refs/heads/master | 2021-01-17T11:45:30.289524 | 2013-03-01T06:12:43 | 2013-03-01T06:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 436 | java | package com.photon.phresco.plugins;
import java.util.List;
public class XmlReport {
private String fileName;
private List<TestSuite> testSuites;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<TestSuite> getTestSuites() {
return testSuites;
}
public void setTestSuites(List<TestSuite> testSuites) {
this.testSuites = testSuites;
}
} | [
"[email protected]"
] | |
9114abc7ef76c14b4f652cf1260131424b756ad4 | d5f09c7b0e954cd20dd613af600afd91b039c48a | /sources/com/coolapk/market/databinding/ItemRelatedDataBinding.java | 4e9655d6825ea1faa0fc085ac4cc2c7b7a829053 | [] | no_license | t0HiiBwn/CoolapkRelease | af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3 | a6a2b03e32cde0e5163016e0078391271a8d33ab | refs/heads/main | 2022-07-29T23:28:35.867734 | 2021-03-26T11:41:18 | 2021-03-26T11:41:18 | 345,290,891 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,378 | java | package com.coolapk.market.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.databinding.Bindable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.makeramen.roundedimageview.RoundedImageView;
public abstract class ItemRelatedDataBinding extends ViewDataBinding {
public final LinearLayout cardView;
public final RoundedImageView iconView;
@Bindable
protected String mAvatar;
@Bindable
protected String mName;
public final TextView titleView;
public abstract void setAvatar(String str);
public abstract void setName(String str);
protected ItemRelatedDataBinding(Object obj, View view, int i, LinearLayout linearLayout, RoundedImageView roundedImageView, TextView textView) {
super(obj, view, i);
this.cardView = linearLayout;
this.iconView = roundedImageView;
this.titleView = textView;
}
public String getName() {
return this.mName;
}
public String getAvatar() {
return this.mAvatar;
}
public static ItemRelatedDataBinding inflate(LayoutInflater layoutInflater, ViewGroup viewGroup, boolean z) {
return inflate(layoutInflater, viewGroup, z, DataBindingUtil.getDefaultComponent());
}
@Deprecated
public static ItemRelatedDataBinding inflate(LayoutInflater layoutInflater, ViewGroup viewGroup, boolean z, Object obj) {
return (ItemRelatedDataBinding) ViewDataBinding.inflateInternal(layoutInflater, 2131558902, viewGroup, z, obj);
}
public static ItemRelatedDataBinding inflate(LayoutInflater layoutInflater) {
return inflate(layoutInflater, DataBindingUtil.getDefaultComponent());
}
@Deprecated
public static ItemRelatedDataBinding inflate(LayoutInflater layoutInflater, Object obj) {
return (ItemRelatedDataBinding) ViewDataBinding.inflateInternal(layoutInflater, 2131558902, null, false, obj);
}
public static ItemRelatedDataBinding bind(View view) {
return bind(view, DataBindingUtil.getDefaultComponent());
}
@Deprecated
public static ItemRelatedDataBinding bind(View view, Object obj) {
return (ItemRelatedDataBinding) bind(obj, view, 2131558902);
}
}
| [
"[email protected]"
] | |
5665847ee6480a89be94bc8e33e90fff3eb49c51 | 5714e16fd17e6329504d9e43ac8e2f1501906b14 | /esop/trunk/src/com/starcpt/cmuc/service/LockScreenService.java | 3508bc4465cf86319be35a6222918023f063aa2e | [] | no_license | lizhling/scAndroid_project | 688c2de23bc0eeae7fae9275dba406e01df940c4 | 452f762638cbad6a25ecb130baf3b3d3af7f20b2 | refs/heads/master | 2021-01-21T12:16:44.528698 | 2017-05-19T10:06:41 | 2017-05-19T10:06:41 | 91,785,146 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,200 | java | package com.starcpt.cmuc.service;
import com.starcpt.cmuc.broadcast.ScreenOffBroadcastReceiver;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class LockScreenService extends Service{
private ScreenOffBroadcastReceiver mScreenOffBroadcastReceiver=new ScreenOffBroadcastReceiver();
private void registerScreenOffReceiver(Context context){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mScreenOffBroadcastReceiver, intentFilter);
}
private void unregisterScreenOffReceiver(Context context){
context.unregisterReceiver(mScreenOffBroadcastReceiver);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
registerScreenOffReceiver(this);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterScreenOffReceiver(this);
}
}
| [
"[email protected]"
] | |
84a272892bd18c83c0d4a723af19a658ca24cfd1 | 21838a502fa2a579229992815c34598778c288ca | /Project Account/src/com/cg/mypaymentapp/util/ConnectionSQL.java | 1fc4b877f1b3d15f074cc7eb4d137be67e804a75 | [] | no_license | todishubham30/153104_phase2 | 730fc716e1c07ad56ae480450702c57bc132c7a1 | e588671979feddb56f00bbb5701470f805aa6310 | refs/heads/master | 2020-03-23T05:20:00.383084 | 2018-07-16T12:48:30 | 2018-07-16T12:48:30 | 141,137,672 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 512 | java | package com.cg.mypaymentapp.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionSQL {
public static Connection connection;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myPaymentApp","root","corp123");
}
catch (SQLException e){
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
a984f59c366f441245a98b7b901321451a7af9f6 | 8cd0fdb6ea81474a8cfbb3dc8cb443100e98f445 | /Arquitetura de Software/src/java/org/springframework/web/bind/annotation/PostMapping.java | 0ccc12cc5130bb0dfffbbeaf59b44cfa1333d928 | [] | no_license | JeffersonOuro/Arquitetura-de-Software | 1ae99e1e09c18d463257a682daebbc153f14aff4 | 627838ed050e4e508ed4bced56493cd8c7371f85 | refs/heads/main | 2023-05-30T20:12:02.849425 | 2021-06-22T02:16:12 | 2021-06-22T02:16:12 | 379,116,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 315 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.springframework.web.bind.annotation;
/**
*
* @author Jefferson
*/
public class PostMapping {
}
| [
"[email protected]"
] | |
f7b7f9757780bc75f3a797c9f75455f055c94308 | 5a4b1265df77ac3036f0890cca291320ecadb7e1 | /src/main/java/com/mishchenkov/entity/product/lamp/LedLamp.java | 9b31c6ff36ec18b3ac24b0de77781f59e22ec9fd | [] | no_license | oleg-mischenkov/console_shop | 21e9202711003bbe4439f668284fc739f52c4326 | 31e9192aa4af23c052c361a7bca123f9c323a926 | refs/heads/master | 2023-04-18T07:47:50.387356 | 2021-05-03T17:02:49 | 2021-05-03T17:02:49 | 364,001,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,655 | java | package com.mishchenkov.entity.product.lamp;
import com.mishchenkov.annotation.Item;
import java.util.Objects;
/**
* This object simulates an LED lamp. The lamp may have a different count of LEDs,
* and may or may not have a radiator.
*/
public abstract class LedLamp extends Lamp {
@Item(title = "Item.input.led", msg = "Item.select.led")
private int ledCount;
@Item(title = "Item.input.radiator", msg = "Item.select.radiator")
private boolean radiator;
protected LedLamp() {}
public int getLedCount() {
return ledCount;
}
public void setLedCount(int ledCount) {
this.ledCount = ledCount;
}
public boolean isRadiator() {
return radiator;
}
public void setRadiator(boolean radiator) {
this.radiator = radiator;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LedLamp ledLamp = (LedLamp) o;
return ledCount == ledLamp.ledCount && radiator == ledLamp.radiator;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), ledCount, radiator);
}
@Override
public String toString() {
return super.toString() +
", power=" + getPower() +
", colourTemperature=" + getColourTemperature() +
", height=" + getHeight() +
", diameter=" + getDiameter() +
", ledCount=" + getLedCount() +
", radiator=" + isRadiator() + System.lineSeparator();
}
}
| [
"[email protected]"
] | |
1d5514e7be11e822d74f13f79376954f991ba825 | 240b5cb7816c6db2d250c487805514da4a4664b7 | /pt/pt-dealer/pt-dealer-proc/src/main/java/com/pt/ptdealerproc/service/impl/ProcProcessServiceImpl.java | 1241df5a3f0ae0e02584ee6ba6ee1f978587510a | [] | no_license | cup1516/ProductTraceability | 355ce009c4eed34870d7d4079a8239359817cba5 | de9d2d6a35dec7a65f8c3aa41d4660ec9cf90314 | refs/heads/master | 2021-01-02T02:58:53.998896 | 2020-08-08T04:16:38 | 2020-08-08T04:16:38 | 239,458,949 | 1 | 1 | null | 2020-02-24T10:54:50 | 2020-02-10T08:09:57 | JavaScript | UTF-8 | Java | false | false | 6,930 | java | /*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng ([email protected])
*/
package com.pt.ptdealerproc.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pt.ptcommoncore.constant.CommonConstants;
import com.pt.ptcommoncore.util.IdUtils;
import com.pt.ptcommonsecurity.util.SecurityUtils;
import com.pt.ptdealerproc.dto.NodeDto;
import com.pt.ptdealerproc.dto.ProcessDto;
import com.pt.ptdealerproc.entity.ProcNodeWorker;
import com.pt.ptdealerproc.entity.ProcProcess;
import com.pt.ptdealerproc.entity.ProcProcess;
import com.pt.ptdealerproc.entity.ProcProcessNode;
import com.pt.ptdealerproc.mapper.ProcProcessMapper;
import com.pt.ptdealerproc.mapper.ProcProcessNodeMapper;
import com.pt.ptdealerproc.service.ProcNodeWorkerService;
import com.pt.ptdealerproc.service.ProcProcessNodeService;
import com.pt.ptdealerproc.service.ProcProcessService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 加工流程表
*
* @author pig code generator
* @date 2020-04-19 14:58:16
*/
@Service
@AllArgsConstructor
public class ProcProcessServiceImpl implements ProcProcessService {
private final ProcProcessNodeMapper procProcessNodeMapper;
private final ProcNodeWorkerService procNodeWorkerService;
private final ProcProcessMapper procProcessMapper;
/**
* 获取加工流程表
* @param page
* @param processDto
* @return
*/
@Override
public IPage getProcessPage(Page page, ProcessDto processDto) {
processDto.setCreateBy(SecurityUtils.getUserName());
return procProcessMapper.getProcessDtoPage(page,processDto);
}
/**
* 获取加工流程表
* @param page
* @param processDto
* @return
*/
@Override
public IPage getProcessCheckPage(Page page, ProcessDto processDto) {
return procProcessMapper.getProcessDtoCheckPage(page,processDto);
}
/**
* 查询流程信息集合
*
* @param procProcess 流程信息
* @return 流程信息集合
*/
@Override
public List<ProcProcess> selectProcessList(ProcProcess procProcess)
{
return procProcessMapper.selectProcessList(procProcess);
}
/**
* 查询所有流程
*
* @return 流程列表
*/
@Override
public List<ProcProcess> selectProcessAll()
{
return procProcessMapper.selectProcessAll();
}
/**
* 通过流程ID查询流程信息
*
* @param processId 流程ID
* @return 角色对象信息
*/
@Override
public ProcProcess selectProcessById(String processId)
{
return procProcessMapper.selectProcessById(processId);
}
/**
* 校验流程名称是否唯一
*
* @param process 流程信息
* @return 结果
*/
@Override
public Boolean checkProcessNameUnique(ProcProcess process)
{
// if(StrUtil.isEmpty(process.getProcessId())){
// return Boolean.TRUE;
// }
ProcProcess procProcess = procProcessMapper.checkProcessNameUnique(process.getProcessName());
if (procProcess != null && !procProcess.getProcessId().equals(process.getProcessId()))
{
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 校验流程编码是否唯一
*
* @param process 流程信息
* @return 结果
*/
@Override
public Boolean checkProcessCodeUnique(ProcProcess process)
{
// if(StrUtil.isEmpty(process.getProcessId())){
// return Boolean.TRUE;
// }
ProcProcess procProcess = procProcessMapper.checkProcessCodeUnique(process.getProcessName());
if (procProcess != null && !procProcess.getProcessId().equals(process.getProcessId()))
{
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* 通过流程ID查询流程使用数量
*
* @param processId 流程ID
* @return 结果
*/
@Override
public int countProcProcessById(String processId)
{
// return sysUserProcessService.countProcProcessById(processId);
return 0;
}
/**
* 删除流程信息
*
* @param processId 流程ID
* @return 结果
*/
@Override
public Boolean deleteProcessById(String processId)
{
return procProcessMapper.deleteProcessById(processId);
}
/**
* 批量删除流程信息
*
* @param processIds 需要删除的流程ID
* @return 结果
* @throws Exception 异常
*/
@Override
public Boolean deleteProcessByIds(String[] processIds)
{
for (String processId : processIds)
{
procProcessNodeMapper.deleteProcessNode(processId);
// if (countProcProcessById(processId) > 0)
// {
// return Boolean.FALSE;
// }
}
procProcessMapper.deleteProcessByIds(processIds);
return Boolean.TRUE;
}
/**
* 新增保存流程信息
*
* @param processDto 流程信息
* @return 结果
*/
@Override
public Boolean insertProcess(ProcessDto processDto)
{
processDto.setProcessId(IdUtils.simpleUUID());
procProcessMapper.insertProcess(processDto);
List<ProcProcessNode> processNodes = processDto.getProcessNodes();
processNodes.stream().forEach(procProcessNode -> procProcessNode.setProcessId(processDto.getProcessId()));
procProcessNodeMapper.batchProcessNode(processNodes);
return Boolean.TRUE;
}
/**
* 修改保存流程信息
*
* @param processDto 流程信息
* @return 结果
*/
@Override
public Boolean updateProcess(ProcessDto processDto)
{
List<ProcProcessNode> processNodes = processDto.getProcessNodes();
processNodes.stream().forEach(procProcessNode -> procProcessNode.setProcessId(processDto.getProcessId()));
procProcessNodeMapper.deleteProcessNode(processDto.getProcessId());
if(processDto.getProcessNodes().size()>0){
procProcessNodeMapper.batchProcessNode(processNodes);
}
return procProcessMapper.updateProcess(processDto);
}
@Override
public List<ProcProcess> getProcProcessList() {
return procProcessMapper.getProcProcessList();
}
@Override
public Boolean changeCheckStatus(ProcessDto processDto) {
return procProcessMapper.changeCheckStatus(processDto);
}
}
| [
"[email protected]"
] | |
4c56e2b2df395aa9ff05dad7521e1633f0b5e9b2 | 77cab7c0f4f8d8115e19f9d118f3a600d99435e4 | /Web Programming/5. Cookie, Session, Security/securityexam/src/main/java/org/edwith/webbe/securityexam/config/WebAppInitializer.java | ddf484388c055ccbd0889e2a0c64effee3fb6369 | [] | no_license | not-solved/Edwith | d595dbf7d4a14a34eb3bc1464a185f92b96fd366 | 073de471c69dcfe4bf805d3462cccb236082f83a | refs/heads/master | 2023-02-20T18:07:59.563726 | 2021-01-27T13:47:00 | 2021-01-27T13:47:00 | 332,384,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,359 | java | package org.edwith.webbe.securityexam.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.*;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// Spring Config 파일 설정
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ApplicationConfig.class, SecurityConfig.class};
}
// Spring WEB Config 파일을 설정
// WebConfig는 Bean을 RootConfig에서 설정한 곳에서부터 찾는다.
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{MvcConfig.class};
}
// DispatcherServlet이 매핑되기 위한 하나 혹은 여러 개의 패스를 지정
// 여기서는 기본 경로 ('/')에서의 서블릿에만 매핑하여 애플리케이션으로 들어오는 모든 요청을 처리
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
// 필터 설정
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
return new Filter[]{encodingFilter};
}
}
| [
"[email protected]"
] | |
80754127a2751df7c1e2903deb297668159e85b9 | 66f5079fc5fca29f46b1fb3be7463207b90b2582 | /src/escuela/Persona.java | dcc09cc5708c1c22df62be62f141292d589a76cc | [] | no_license | valenchu/PracticaHerencia | 5a60d8e386c860ff20caacc7ad130797f4019b59 | 1bd183b9ecb8363077e494857e4832088b4a249c | refs/heads/master | 2021-08-12T04:53:32.863198 | 2017-11-14T12:46:35 | 2017-11-14T12:46:35 | 110,253,534 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,132 | java | package escuela;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import java.time.Year;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import static javax.swing.UIManager.get;
public class Persona {
private String nombre = "No ingreso nombre";
private String apellido = "No ingreso apellido";
private int dia = 0;
private int mes = 0;
private int ano = 0;
public Persona(String nombre, String apellido, int dia, int mes, int ano) {
this.nombre = nombre;
this.apellido = apellido;
this.dia = dia;
this.mes = mes;
this.ano = ano;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public int dia() {
return dia;
}
public int mes() {
return mes;
}
public int ano() {
return ano;
}
protected void nombreCompleto() {
System.out.println(nombre + " " + apellido);
}
protected void calcularEdad() {
Calendar anno = Calendar.getInstance();
int años = 0;
//Saco el día actual
int D = anno.get(Calendar.DATE);
//Resto día dado a el día actual
D = D - dia;
//Saco mes actual
int M = anno.get(Calendar.MONTH);
//Resto mes edad de la persona a mes actual
M = M - mes;
//Saco año actual
int A = anno.get(Calendar.YEAR);
//Resto año de la persona a año actual
A = A - ano;
//Saco que si el día o mes es negativo se me reste un año para dar
//la edad correcta aunque estemos en el año de cambio de edad pero
//al no estar en el mes o día se le resta su edad.
if (D < 0 || M < 0) {
años = A--;
} else {
años = A;
}
System.out.println("Edad final de la persona: " + años);
}
}
| [
"[email protected]"
] | |
ee42683302d946ffbb490e508e8d170411d72ed9 | 2cd2a60068c62427d4d2a5eb4022ad76d0e05b1b | /yqq-micro-third/src/main/java/com/yqq/third/model/request/wap/RightsLeadReq.java | 3d1a34838cd8bd8b378b4622fba6280602cde53e | [] | no_license | yangchuan9369/yqq | f65e325e081b9f537807b3d0a0d60c7e790544ac | 5eaf1b7ccadadeb43cea90e2d4cb0790aa016c7c | refs/heads/master | 2023-02-18T03:35:54.411029 | 2021-01-19T09:25:01 | 2021-01-19T09:25:01 | 330,838,711 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,205 | java | /*
* 文 件 名: RightsLeadReq.java
* 版 权: Nanjing Xinwang Tech Co.,Ltd.Copyright 2013-2018,All rights reserved
* 描 述: <描述>
* 修 改 人: zhuyao 1824
* 修改时间: 2020年3月2日
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.yqq.third.model.request.wap;
import com.yqq.third.model.UserInfoBean;
import io.swagger.annotations.ApiModel;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* <会员领取权益包请求信息>
*
* @author zhuyao 1824
* @see [相关类/方法]
*/
@ApiModel(value="会员领取权益包请求信息")
public class RightsLeadReq implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 7106030201429485904L;
/**
* -会员ID
*/
@NotEmpty(message="会员ID不能为空")
private String memberId;
/**
* -会员类型编码
*/
private String memberTypeNum;
/**
* -权益包编码
*/
private String rightsBodyNum;
/**
* -权益编码
*/
@NotEmpty(message="权益编码不能为空")
private String rightsNum;
/**
* 渠道编码
*/
@NotEmpty(message="渠道编码不能为空")
private String channelNum;
/**
* 下发类型 AUTO 自动 HANDLE 手工 REISSUE补发
*/
@NotEmpty(message="下发类型不能为空")
private String handleType;
/**
* -特殊日期标志 BIRTHDAY-生日,可为空
*/
private String onceType;
/**
* 可为空,如果为空,取系统档期日期;格式:YYYYMMDDHH24MISS
*/
private String leadTime;
/**
* 领取数量
*/
@Max(value=1,message="领取数量不能小于1")
private Integer leadCount;
/**
* 江苏移动用户信息
*/
@NotNull(message="用户信息不能为空")
private UserInfoBean userInfoBean;
/**
* 领取记录号码
*/
@NotNull(message="领取记录号码不能为空")
private String drawNum;
/**
* 获取 memberId
* @return 返回 memberId
*/
public String getMemberId() {
return memberId;
}
/**
* 设置 memberId
* @param memberId 对memberId进行赋值
*/
public void setMemberId(String memberId) {
this.memberId = memberId;
}
/**
* 获取 memberTypeNum
* @return 返回 memberTypeNum
*/
public String getMemberTypeNum() {
return memberTypeNum;
}
/**
* 设置 memberTypeNum
* @param memberTypeNum 对memberTypeNum进行赋值
*/
public void setMemberTypeNum(String memberTypeNum) {
this.memberTypeNum = memberTypeNum;
}
/**
* 获取 rightsBodyNum
* @return 返回 rightsBodyNum
*/
public String getRightsBodyNum() {
return rightsBodyNum;
}
/**
* 设置 rightsBodyNum
* @param rightsBodyNum 对rightsBodyNum进行赋值
*/
public void setRightsBodyNum(String rightsBodyNum) {
this.rightsBodyNum = rightsBodyNum;
}
/**
* 获取 rightsNum
* @return 返回 rightsNum
*/
public String getRightsNum() {
return rightsNum;
}
/**
* 设置 rightsNum
* @param rightsNum 对rightsNum进行赋值
*/
public void setRightsNum(String rightsNum) {
this.rightsNum = rightsNum;
}
/**
* 获取 channelNum
* @return 返回 channelNum
*/
public String getChannelNum() {
return channelNum;
}
/**
* 设置 channelNum
* @param channelNum 对channelNum进行赋值
*/
public void setChannelNum(String channelNum) {
this.channelNum = channelNum;
}
/**
* 获取 handleType
* @return 返回 handleType
*/
public String getHandleType() {
return handleType;
}
/**
* 设置 handleType
* @param handleType 对handleType进行赋值
*/
public void setHandleType(String handleType) {
this.handleType = handleType;
}
/**
* 获取 onceType
* @return 返回 onceType
*/
public String getOnceType() {
return onceType;
}
/**
* 设置 onceType
* @param onceType 对onceType进行赋值
*/
public void setOnceType(String onceType) {
this.onceType = onceType;
}
/**
* 获取 leadTime
* @return 返回 leadTime
*/
public String getLeadTime() {
return leadTime;
}
/**
* 设置 leadTime
* @param leadTime 对leadTime进行赋值
*/
public void setLeadTime(String leadTime) {
this.leadTime = leadTime;
}
/**
* 获取 leadCount
* @return 返回 leadCount
*/
public Integer getLeadCount() {
return leadCount;
}
/**
* 设置 leadCount
* @param leadCount 对leadCount进行赋值
*/
public void setLeadCount(Integer leadCount) {
this.leadCount = leadCount;
}
/**
* 获取 userInfoBean
* @return 返回 userInfoBean
*/
public UserInfoBean getUserInfoBean() {
return userInfoBean;
}
/**
* 设置 userInfoBean
* @param userInfoBean 对userInfoBean进行赋值
*/
public void setUserInfoBean(UserInfoBean userInfoBean) {
this.userInfoBean = userInfoBean;
}
/**
* 获取 领取记录号码
*
* @return drawNum 领取记录号码
*/
public String getDrawNum() {
return this.drawNum;
}
/**
* 设置 领取记录号码
*
* @param drawNum 领取记录号码
*/
public void setDrawNum(String drawNum) {
this.drawNum = drawNum;
}
}
| [
"killer9369"
] | killer9369 |
5cc1cbb364b4228d4c3e8caecb6b054a532b75c8 | e6d8721469ee4abcb2344985be84ea99ce6b2b59 | /app/living/hz/util/FileUtil.java | 3e92d874162caaf2f939e022b008878bf99a78f3 | [] | no_license | zizih/selfws | 586787fd4b525f9d4464c4e57a9363904ec9050b | adfe8640706b8f326c8334b111d9ad5eada7ba9a | refs/heads/master | 2019-01-21T19:12:42.879769 | 2013-03-03T05:07:03 | 2013-03-03T05:07:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,480 | java | package living.hz.util;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.eclipse.jdt.core.dom.ThisExpression;
import org.eclipse.jdt.internal.core.util.PublicScanner;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import play.Play;
public class FileUtil {
public static String USERFILEPATH = "UserImg";
public static String AVATARFILEPATH = "AvatarImg";
public static String ALBUMFILEPATH = "AlbumImg";
public static String saveAvatar(File avatar, String username) {
if (avatar == null)
return null;
// path为相对路径
File target = new File(getProjectPath()
+ getAvatarRelativePath(username));
if (!target.exists()) {
target.mkdirs();
}
try {
BufferedImage image = ImageIO.read(avatar);
ImageIO.write(
image,
"JPEG",
new File(target
+ File.separator
+ username
+ avatar.getName().substring(
avatar.getName().lastIndexOf("."))));
} catch (Exception ex) {
ex.printStackTrace();
}
// copy(img, target,userName);
return getAvatarRelativePath(username) + File.separator + username
+ avatar.getName().substring(avatar.getName().lastIndexOf("."));// 路径问题
}
public static String saveAlbum(File album) {
if (album == null)
return null;
// path为相对路径
File target = new File(getProjectPath() + getAlbumRelativePath());
if (!target.exists()) {
target.mkdirs();
}
try {
BufferedImage image = ImageIO.read(album);
ImageIO.write(image, "JPEG", new File(target + File.separator
+ album.getName()));
} catch (Exception ex) {
ex.printStackTrace();
}
// copy(img, target,userName);
return getAlbumRelativePath() + File.separator + album.getName();// 路径问题
}
public static String getBasePath() {
return (String) Play.configuration.get("userImgPath");
}
public static String getRelativePath() {
return File.separator + "public" + File.separator + "images";
}
public static String getUserRelativePath() {
return getRelativePath() + File.separator + USERFILEPATH;
}
public static String getAvatarRelativePath(String username) {
return getUserRelativePath() + File.separator + AVATARFILEPATH
+ File.separator + username;
}
public static String getAlbumRelativePath() {
return getUserRelativePath() + File.separator + ALBUMFILEPATH;
}
public static String getProjectPath() {
File currentFile = new File(FileUtil.class.getClassLoader()
.getResource("").getPath());
return currentFile.getParent();
}
public static String renameAvatarPath(String oldUserName,
String newUserName, String oldAvatarPath) {
File oldFile = new File(getProjectPath()
+ getAvatarRelativePath(oldUserName) + File.separator
+ oldUserName);
File newFile = new File(getProjectPath()
+ getAvatarRelativePath(oldUserName) + File.separator
+ newUserName);
oldFile.renameTo(newFile);
String newAvatarPath = getAvatarRelativePath(oldUserName)
+ File.separator + newUserName + File.separator + newUserName
+ oldAvatarPath.substring(oldAvatarPath.lastIndexOf("."));
String tmpPath = getAvatarRelativePath(oldUserName) + File.separator
+ newUserName + File.separator + oldUserName
+ oldAvatarPath.substring(oldAvatarPath.lastIndexOf("."));
File oldAvatar = new File(getProjectPath() + tmpPath);
File newAvatar = new File(getProjectPath() + newAvatarPath);
oldAvatar.renameTo(newAvatar);
return newAvatarPath;
}
}
| [
"[email protected]"
] | |
bf272d3f0fdb293edb96274807b25a817ab51604 | 41c76671b044fbead64f491b929ae2e5f5e740cf | /src/main/java/designpattern/interpreter/InterpreterPatternEx.java | 558ba5e038f884dc37716bcef3dad20c0f997e54 | [] | no_license | FisherChen3/Java_Core | fa45dd1342e442a112420deb425b5774fbf72d34 | 6a617aff98433427adab8a5f0e05b79564dead9a | refs/heads/master | 2020-12-31T07:10:11.525876 | 2017-04-11T03:17:41 | 2017-04-11T03:17:41 | 80,557,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,240 | java | package designpattern.interpreter;
import java.util.Scanner;
/**
* Created by Fisher on 4/10/2017.
*/
public class InterpreterPatternEx {
public Context clientContext = null;
public IExpression exp = null;
public InterpreterPatternEx(Context c) {
clientContext = c;
}
public void interpret(String str) {
//We'll test 2 consecutive inputs at a time
for (int i = 0; i < 2; i++) {
System.out.println("\nEnter ur choice(1 or 2)");
Scanner in = new Scanner(System.in);
String c = in.nextLine();
if (c.equals("1")) {
exp = new IntToWords(str);
exp.interpret(clientContext);
} else {
exp = new StringToBinaryExp(str);
exp.interpret(clientContext);
}
}
}
public static void main(String[] args) {
System.out.println("\n***Interpreter Pattern Demo***\n");
System.out.println("Enter a number :");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Context context = new Context(input);
InterpreterPatternEx client = new InterpreterPatternEx(context);
client.interpret(input);
}
}
| [
"[email protected]"
] | |
f6177176eff375e9b95cf95e57212b01d146693a | 32aab6ba61d2ba2d1c22ebd3614fa40c85362846 | /backend/smarthome-sharedwifi/src/main/java/com/phicomm/smarthome/sharedwifi/protocol/downloadbill/DownloadBillResData.java | f653c5dc577e94105951e232cac720404339ca16 | [
"Apache-2.0"
] | permissive | rongwei84n/Auts_Assert_manager | d6346d14c87bc2e6eaf86c772441f73722b83ee0 | 8464d280fa7344d80191219c9491518a93a699bd | refs/heads/master | 2021-01-21T14:19:25.267322 | 2017-06-24T09:16:56 | 2017-06-24T09:16:56 | 95,267,686 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 591 | java | package com.phicomm.smarthome.sharedwifi.protocol.downloadbill;
/**
* User: rizenguo
* Date: 2014/10/25
* Time: 16:48
*/
public class DownloadBillResData {
//协议层
private String return_code = "";
private String return_msg = "";
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public String getReturn_msg() {
return return_msg;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
}
| [
"[email protected]"
] | |
ba6439179902786884fed2cb32dda70814525398 | db4ad606d8b7deebaf1003bc0a429bbb2cdb514e | /src/main/java/com/yunjae/springr2dbc/repository/CoffeeRepository.java | 58a3992ca01a4de730266db0e7366103d93c29a0 | [] | no_license | yunjaecho/spring-r2dbc | d7526ee5f59f0d52b1f0f109b3ce5b437460f7b9 | 4277a02fb9e834ad489a230470f0928bf4d8a630 | refs/heads/master | 2020-04-02T06:32:48.176798 | 2018-10-22T14:11:03 | 2018-10-22T14:11:03 | 154,155,406 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 417 | java | package com.yunjae.springr2dbc.repository;
import com.yunjae.springr2dbc.entity.Coffee;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Mono;
public interface CoffeeRepository extends ReactiveCrudRepository<Coffee, Long> {
@Query("DELETE FROM coffee")
Mono<Coffee> deleteAllById();
}
| [
"[email protected]"
] | |
9c06cec71600fc9097af94e6b3005399b4efa46d | 674a8e44b2e89fdf66b0c9f4ebc4c937c8feba24 | /projects/consulting/consulting/src/main/java/org/project/common/ejb/EJBManager.java | 9279a88ac72af2eb23d5b099768500fedf59b7be | [] | no_license | shahbazaamir/learn | 585309072c26eeff038fc57ac764485f18783704 | 4a39386825632c48fa127202ee334d0b42f3bf18 | refs/heads/master | 2022-12-22T08:21:10.564178 | 2020-04-12T14:36:28 | 2020-04-12T14:36:28 | 116,004,417 | 2 | 2 | null | 2022-12-22T04:59:27 | 2018-01-02T10:38:26 | Java | UTF-8 | Java | false | false | 340 | java | package org.project.common.ejb;
import javax.naming.InitialContext;
import org.project.naming.NamingManager;
public class EJBManager {
public static Object getEJBObject (String jndiName) throws Exception{
InitialContext context = NamingManager.getInitialContext();
Object ejbObj = context.lookup(jndiName);
return ejbObj ;
}
}
| [
"[email protected]"
] | |
4b2b2526714514eae0a769a3eb51ea6a09a8458a | d41a6999c471b3ffb4bf436beadad3e8aca6b5be | /Lesson6_homework/src/main/java/WeitHelper.java | a3d4bfe4601f0f9919bb4d5f12d12ad93562dfc9 | [] | no_license | RazmikMkhitaryan/Automation_Course | 460d97681b68a9b76cef0834e455a2acbde222b5 | 381b66add26da0289310c981ea413409a484d2ca | refs/heads/main | 2023-04-25T23:52:41.000790 | 2021-06-03T09:27:22 | 2021-06-03T09:27:22 | 365,699,326 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,205 | java | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static Driver.DriverSetup.getDriver;
public class WeitHelper {
public static final int DEFAULT_TIME = 15;
public static WeitHelper getInstance() {
WeitHelper weitHelper = new WeitHelper();
return weitHelper;
}
public WeitHelper waitForVisibilityOfElement(By location) {
try {
new WebDriverWait(getDriver(), DEFAULT_TIME).until(ExpectedConditions.visibilityOfElementLocated(location));
return this;
} catch (WebDriverException e) {
throw new Error("No such element found" + location.toString());
}
}
public WeitHelper waitElementBeClickable(By location) {
try {
new WebDriverWait(getDriver(), DEFAULT_TIME).until(ExpectedConditions.elementToBeClickable(location));
return this;
} catch (WebDriverException e) {
throw new Error("No such element found" + location.toString());
}
}
}
| [
"[email protected]"
] | |
3758f3fdec2229f45d714205c63c0ef1872e556b | a9b3cd0ad9fc2cc86c6a948e8555b68aec6a131e | /src/com/taskpad/input/Edit.java | 9461a6782fe4ae096e7406c57747f445c7577740 | [] | no_license | chanjunweimy/TaskPad | f343d135ee17a17e4a9051051e9b27fd05674cae | 3542e1e7a7ba3c236a062d561b345345b9986579 | refs/heads/master | 2020-09-12T20:45:03.774495 | 2015-09-08T01:52:59 | 2015-09-08T01:52:59 | 35,029,540 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,646 | java | //@author A0119646X
package com.taskpad.input;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Logger;
import com.taskpad.dateandtime.DateAndTimeManager;
import com.taskpad.dateandtime.InvalidQuotesException;
import com.taskpad.execute.InvalidTaskIdException;
public class Edit extends Command{
private final static Logger LOGGER = Logger.getLogger("TaskPad");
private static final int NUMBER_ARGUMENTS = 2;
private static final String COMMAND_EDIT = "EDIT";
private static String PARAMETER_TASK_ID = "TASKID";
private static String PARAMETER_DESC = "DESC";
private static String PARAMETER_DEADLINE = "DEADLINE";
private static String PARAMETER_START_DATE = "START DATE";
private static String PARAMETER_START_TIME = "START TIME";
private static String PARAMETER_END_DATE = "END DATE";
private static String PARAMETER_END_TIME = "END TIME";
private static String PARAMETER_INFO = "INFO";
private String _taskID;
private String _desc;
private String _deadline;
private String _startDate;
private String _startTime;
private String _endDate;
private String _endTime;
private String _editInput;
private String _info;
private int _deadNo;
private int _endNo;
private int _startNo;
private int _infoNo;
private static final String STRING_SPACE = " ";
private static final String STRING_COMMA = ",";
private static final String STRING_EMPTY = "";
public Edit(String input, String fullInput) {
super(input, fullInput);
}
@Override
protected void initialiseOthers(){
LOGGER.info("initializing...");
LOGGER.info("NUMBER_ARGUMENTS: " + NUMBER_ARGUMENTS);
LOGGER.info("COMMAND_EDIT: " + COMMAND_EDIT);
setNUMBER_ARGUMENTS(NUMBER_ARGUMENTS);
setCOMMAND(COMMAND_EDIT);
_taskID = null;
_desc = null;
_deadline = null;
_startDate = null;
_startTime = null;
_endDate = null;
_endTime = null;
_info = null;
_deadNo = 0;
_startNo = 0;
_endNo = 0;
_infoNo = 0;
}
@Override
protected boolean commandSpecificRun() {
clearInputParameters();
LOGGER.info("input is " + input);
_editInput = fullInput;
if(noTaskIDInPosition(fullInput)){
try {
_taskID = findTaskID(fullInput);
} catch (TaskIDException | InvalidQuotesException e) {
InputManager.outputToGui(e.getMessage());
LOGGER.severe(e.getMessage());
return false;
}
}
LOGGER.info("taskID is " + _taskID);
input = removeTaskID(fullInput, _taskID);
LOGGER.info("input is " + input);
fullInput = _editInput;
if(isDelimitedString(" " + input + " ")){
String temp = putDescInQuotesFirst(input);
if (!temp.trim().isEmpty()){
input = temp;
}
editDelimitedString();
} else {
LOGGER.info("taskID is " + _taskID);
try {
getOtherKeysValue();
} catch (InvalidTaskIdException e) {
InputManager.outputToGui("Not a valid TaskID!");
LOGGER.severe("Not a valid TaskID!");
return false;
}
}
putInputParameters();
return true;
}
/**
* delimited string syntax: edit <taskID> <desc> -d <deadline...> -s <start...> -e <end...>
*/
private void editDelimitedString() {
extractTaskID();
extractDescription();
Scanner sc = new Scanner(input);
sc.useDelimiter("\\s-");
while(sc.hasNext()){
String nextParam = sc.next().trim();
nextParam = nextParam.replaceFirst("-", STRING_EMPTY);
parseNextParam(nextParam.trim());
}
sc.close();
}
/**
* Check if second word entered is an integer (likely to be taskID)
* @param fullInput
* @return true if is integer and sets it as taskID
*/
private boolean noTaskIDInPosition(String fullInput) {
String splitInput[] = fullInput.split(STRING_SPACE);
if (isNotValidTaskID(splitInput[1])){
InputManager.outputToGui(MESSAGE_WARNING_TASKID);
return true;
} else {
int taskID = Integer.parseInt(splitInput[1]);
_taskID = "" + taskID;
return false;
}
/*
try{
int taskID = Integer.parseInt(splitInput[1]);
_taskID = "" + taskID;
return false;
} catch (NumberFormatException e){
InputManager.outputToGui(MESSAGE_WARNING_TASKID);
return true;
}
*/
}
/**
* @throws InvalidTaskIdException
*
*/
private void getOtherKeysValue() throws InvalidTaskIdException {
//String inputString = fullInput;
//inputString = removeTaskID(inputString, _taskID);
String inputString = input;
LOGGER.info("getting other parameters value (exclude ID).");
LOGGER.info("inputString is " + inputString);
String[] fullInputTokens = inputString.split(STRING_COMMA);
for (String token : fullInputTokens){
String tag = findTag(token);
LOGGER.info("token is " + token);
LOGGER.info("tag is " + tag);
switch(tag){
case "DESC":
token = removeWordDesc(token);
if (_desc == null){
_desc = token;
LOGGER.info("description is " + _desc);
} else {
_desc = _desc + STRING_COMMA + token;
LOGGER.info("description is " + _desc);
}
break;
case "DEADLINE":
_deadNo++;
token = removeWordDeadline(token);
if (token.trim().isEmpty()){
_deadline = STRING_EMPTY;
LOGGER.info("deadline is " + _deadline);
continue;
}
token = KEYWORD_DEADLINE + STRING_SPACE + token.trim();
LOGGER.info("after editing, token is " + token);
String tempDead = getDateAndTimeValue(token, POSITION_DATE_DEADLINE , POSITION_TIME_DEADLINE);
if (tempDead == null){
continue;
}
_deadline = tempDead;
LOGGER.info("deadline is " + _deadline);
break;
case "START":
_startNo++;
token = removeWordStart(token);
if (token.trim().isEmpty()){
_startDate = STRING_EMPTY;
_startTime = STRING_EMPTY;
LOGGER.info("_startDate and _startTime is " + STRING_EMPTY);
continue;
}
token = KEYWORD_STARTTIME + STRING_SPACE + token.trim();
LOGGER.info("after editing, token is " + token);
String startResult = getDateAndTimeValue(token, POSITION_DATE_STARTTIME , POSITION_TIME_STARTTIME);
LOGGER.info("startResult is " + startResult);
if (startResult == null){
continue;
}
inputStartTimeDate(startResult);
break;
case "END":
_endNo++;
token = removeWordEnd(token);
if (token.trim().isEmpty()){
_endDate = STRING_EMPTY;
_endTime = STRING_EMPTY;
LOGGER.info("_endDate and _endTime is " + STRING_EMPTY);
continue;
}
token = KEYWORD_ENDTiME + STRING_SPACE + token.trim();
LOGGER.info("after editing, token is " + token);
String endResult = getDateAndTimeValue(token, POSITION_DATE_ENDTIME , POSITION_TIME_ENDTIME);
LOGGER.info("endResult is " + endResult);
if (endResult == null){
continue;
}
inputEndTimeDate(endResult);
break;
case "INFO":
_infoNo++;
token = removeWordInfo(token);
if (_info == null){
_info = token;
LOGGER.info("information is " + _info);
} else {
_info = _info + STRING_COMMA + token;
LOGGER.info("information is " + _info);
}
break;
default:
if (_desc == null){
_desc = token;
LOGGER.info("description is " + _desc);
} else {
_desc = _desc + STRING_COMMA + token;
LOGGER.info("description is " + _desc);
}
break;
}
}
checkDesc();
showErrorWhenActionRepeated(_startNo, _deadNo, _endNo, _infoNo);
boolean isEdit = true;
ArrayList<String> times =
checkDeadLineAndEndTime(_startTime, _startDate, _taskID, _deadline, _endTime, _endDate, isEdit);
String endLatest = times.get(POSITION_TIME_ENDTIME / 2);
String startEarliest = times.get(POSITION_TIME_STARTTIME / 2);
_deadline = times.get(POSITION_TIME_DEADLINE / 2);
if (_deadline != null && !_deadline.trim().isEmpty ()){
String[] deadTokens = _deadline.split(STRING_SPACE);
_deadline = deadTokens[1] + STRING_SPACE + deadTokens[0];
}
if (endLatest == null){
_endDate = null;
_endTime = null;
}
if (startEarliest == null){
_startDate = null;
_startTime = null;
}
}
/**
* Takes in input string and finds the first integer as taskID
* @param input
* @return taskID
* @throws TaskIDException
* @throws InvalidQuotesException
*/
private String findTaskID(String input) throws TaskIDException, InvalidQuotesException{
String numberInput = DateAndTimeManager.getInstance().parseNumberString(input);
LOGGER.info("finding TaskID. Converted to numberInput");
LOGGER.info("numberInput is " + numberInput);
input = numberInput;
fullInput = numberInput;
LOGGER.info("input is " + input);
LOGGER.info("fullInput is " + fullInput);
int taskID = -1;
String[] splitInput = input.split(STRING_SPACE);
for (int i = 0; i < splitInput.length; i++){
if (taskID == -1){
String token = splitInput[i];
if (!isNotValidTaskID(token)){
taskID = Integer.parseInt(token);
break;
}
}
}
LOGGER.info("taskID is " + taskID);
if (taskID == -1){
LOGGER.severe("TASK ID is invalid!");
throw new TaskIDException();
}
return "" + taskID;
}
/**
*
*/
private void checkDesc() {
if (_desc != null){
_desc = _desc.trim();
LOGGER.info("At last, desc is " + _desc);
if (_desc.isEmpty()){
_desc = null;
}
}
}
private String findTag(String fullInput){
String tag = STRING_EMPTY;
if (containsDesc(fullInput)){
tag = "DESC";
} else if (containsDeadline(fullInput)){
tag = "DEADLINE";
} else if (containsStart(fullInput)){
tag = "START";
} else if (containsEnd(fullInput)){
tag = "END";
} else if (containsInfo(fullInput)){
tag = "INFO";
}
return tag;
}
@Override
protected boolean checkIfIncorrectArguments() throws InvalidParameterException, TaskIDException{
String inputString[] = input.split(STRING_SPACE);
if (isNotNumberArgs(inputString)){
LOGGER.severe("Throw");
LOGGER.severe("inputString is " + inputString);
throw new InvalidParameterException();
}
return false;
}
@Override
protected void initialiseParametersToNull() {
putOneParameter(PARAMETER_TASK_ID, STRING_EMPTY);
putOneParameter(PARAMETER_DESC, STRING_EMPTY);
putOneParameter(PARAMETER_DEADLINE, STRING_EMPTY);
putOneParameter(PARAMETER_START_TIME, STRING_EMPTY);
putOneParameter(PARAMETER_START_DATE, STRING_EMPTY);
putOneParameter(PARAMETER_END_TIME, STRING_EMPTY);
putOneParameter(PARAMETER_END_DATE, STRING_EMPTY);
putOneParameter(PARAMETER_INFO, STRING_EMPTY);
}
@Override
protected void putInputParameters() {
if (_deadline != null){
if (! _deadline.trim().isEmpty()){
String[] tempDeadSplit = _deadline.split(STRING_SPACE);
_deadline = tempDeadSplit[1] + STRING_SPACE + tempDeadSplit[0];
}
putOneParameter(PARAMETER_DEADLINE, _deadline);
}
putOneParameter(PARAMETER_TASK_ID, _taskID);
putOneParameter(PARAMETER_DESC, _desc);
putOneParameter(PARAMETER_START_TIME, _startTime);
putOneParameter(PARAMETER_START_DATE, _startDate);
putOneParameter(PARAMETER_END_TIME, _endTime);
putOneParameter(PARAMETER_END_DATE, _endDate);
putOneParameter(PARAMETER_INFO, _info);
}
@Override
protected void putOneParameter(String parameter, String input){
if (input != null){
inputParameters.put(parameter, input);
}
}
@Override
protected boolean isNotNumberArgs(String[] inputString){
if (inputString.length >= getNUMBER_ARGUMENTS()){
return false;
}
return true;
}
private String removeTaskID(String input, String taskID){
input = input.replaceFirst("(?i)" + COMMAND_EDIT, "");
return input.replaceFirst(taskID, "").trim();
}
@SuppressWarnings("unused")
private String removeFirstWord(String input){
return input.replace(getFirstWord(input), "").trim();
}
private static String getFirstWord(String input) {
return input.trim().split("\\s+")[0];
}
private boolean containsDesc(String input){
String inputCopy = STRING_SPACE + input.toUpperCase() + STRING_SPACE;
if (inputCopy.contains(" DESC ") || inputCopy.contains(" DESCRIPTION ")){
return true;
}
return false;
}
private boolean containsStart(String input){
String inputCopy = STRING_SPACE + input.toUpperCase() + STRING_SPACE;
if (inputCopy.contains(" START ")){
return true;
}
return false;
}
private boolean containsEnd(String input){
String inputCopy = STRING_SPACE + input.toUpperCase() + STRING_SPACE;
if (inputCopy.contains(" END ")){
return true;
}
return false;
}
private boolean containsInfo(String input){
String inputCopy = STRING_SPACE + input.toUpperCase() + STRING_SPACE;
if (inputCopy.contains(" INFO ") || inputCopy.contains(" INFORMATION ") ||
inputCopy.contains(" DETAILS ") || inputCopy.contains(" DETAIL ")){
return true;
}
return false;
}
private String removeWordDesc(String inputCopy) {
String newString = "";
int count = 0; //Just replace only one occurrence of description
String[] inputSplit = inputCopy.split(" ");
for (int i=0; i<inputSplit.length; i++){
if (isNotDescWord(inputSplit[i].trim())){
newString += inputSplit[i] + " ";
} else if (count > 0) {
newString += inputSplit[i] + " ";
} else {
count ++;
}
}
return newString;
}
private String removeWordInfo(String inputCopy) {
String newString = "";
int count = 0; //Just replace only one occurrence of description
String[] inputSplit = inputCopy.split(" ");
for (int i=0; i<inputSplit.length; i++){
LOGGER.info("token is " + inputSplit[i]);
LOGGER.info("cnt is " + count + " newString is: " + newString);
if (isNotInfoWord(inputSplit[i].trim())){
newString += inputSplit[i] + " ";
LOGGER.info("added notInfoWord: " + newString);
} else if (count > 0) {
newString += inputSplit[i] + " ";
LOGGER.info("added other InfoWord: " + newString);
} else {
count ++;
}
}
LOGGER.info("after deleting word info : " + newString);
return newString;
}
private boolean isNotInfoWord(String string) {
string = string.toUpperCase();
return (!string.equals("INFO") &&
!string.equals("INFORMATION") &&
!string.equals("DETAILS") &&
!string.equals("DETAIL"));
}
private boolean isNotDescWord(String string) {
return (!string.toUpperCase().equals("DESC") &&
!string.toUpperCase().equals("DESCRIPTION"));
}
private boolean containsDeadline(String input){
String inputCopy = STRING_SPACE + input.toUpperCase() + STRING_SPACE;
if (inputCopy.contains(" DEADLINE ") || inputCopy.contains(" DEAD ") ||
inputCopy.contains(" DATE ") || inputCopy.contains(" -D ")){
return true;
}
return false;
}
private String removeWordDeadline(String inputCopy) {
String newString = "";
int count = 0;
String[] inputSplit = inputCopy.split(" ");
for (int i=0; i<inputSplit.length; i++){
if (!isDeadlineWord(inputSplit[i].trim())){
newString += inputSplit[i] + " ";
} else if (count > 0 ){
newString += inputSplit[i] + " ";
} else {
count++;
}
}
return newString;
}
private boolean isDeadlineWord(String string) {
return string.toUpperCase().equals("DEADLINE") ||
string.toUpperCase().equals("DATE") ||
string.toUpperCase().equals("DEAD") ||
string.toUpperCase().equals("-D");
}
private String removeWordEnd(String inputCopy) {
String newString = "";
int count = 0; //Just replace only one occurrence of description
String[] inputSplit = inputCopy.split(" ");
for (int i=0; i<inputSplit.length; i++){
if (isNotEndWord(inputSplit[i].trim())){
newString += inputSplit[i] + " ";
} else if (count > 0) {
newString += inputSplit[i] + " ";
} else {
count ++;
}
}
return newString;
}
private boolean isNotEndWord(String string) {
return !string.toUpperCase().equals("END") && !string.toUpperCase().equals("-E");
}
private void inputStartTimeDate(String result){
String[] splitResult = result.split(STRING_SPACE);
_startDate = splitResult[0];
_startTime = splitResult[1];
}
private void inputEndTimeDate(String result){
String[] splitResult = result.split(STRING_SPACE);
_endDate = splitResult[0];
_endTime = splitResult[1];
}
private String removeWordStart(String inputCopy) {
String newString = "";
int count = 0; //Just replace only one occurrence of description
String[] inputSplit = inputCopy.split(" ");
for (int i = 0; i < inputSplit.length; i++){
LOGGER.info("remove " + inputSplit[i] + "?");
if (isNotStartWord(inputSplit[i].trim())){
newString += inputSplit[i] + " ";
LOGGER.info("NO");
LOGGER.info("newString is " + newString);
} else if (count > 0) {
newString += inputSplit[i] + " ";
LOGGER.info("count is " + count);
LOGGER.info("NO");
LOGGER.info("newString is " + newString);
} else {
count ++;
LOGGER.info("YES");
}
}
return newString;
}
private boolean isNotStartWord(String string) {
return !string.toUpperCase().equals("START") && !string.toUpperCase().equals("-S");
}
private boolean isDelimitedString(String input) {
if (input.contains(" -s ") || input.contains(" -d ") ||
input.contains(" -e ") || input.contains(" -i ")){
return true;
}
return false;
}
private void parseNextParam(String param){
String firstChar = getFirstChar(param);
param = removeFirstChar(param).trim();
switch (firstChar){
case "d":
_deadNo++;
processDeadline(param);
break;
case "s":
_startNo++;
processStart(param);
break;
case "e":
_endNo++;
processEnd(param);
break;
case "i":
_infoNo++;
processInfo(param);
break;
}
LOGGER.info("deadline is " + _deadline );
LOGGER.info("start time and date is " + _startTime + " " + _startDate);
LOGGER.info("end time and date is " + _endTime + " " + _endDate);
showErrorWhenActionRepeated(_startNo, _deadNo, _endNo, _infoNo);
}
private void processDeadline(String param){
if (param.isEmpty()){
return;
}
String tempDate = putDeadline(param);
_deadline = swapDeadlinePlaces(tempDate);
}
private String swapDeadlinePlaces(String deadline){
String[] tempDead = deadline.split(STRING_SPACE);
return tempDead[1] + STRING_SPACE + tempDead[0];
}
private void processEnd(String param){
if (param.isEmpty()){
return;
}
String endResult = putEndTime(param);
if (endResult != null){
inputEndResult(endResult);
}
}
private void processStart(String param){
if (param.isEmpty()){
return;
}
String startResult = putStartTime(param);
if (startResult != null){
inputStartResult(startResult);
}
}
private void inputStartResult(String startResult) {
String[] splitResult = startResult.split(STRING_SPACE);
_startDate = splitResult[0];
_startTime = splitResult[1];
}
private void inputEndResult(String endResult) {
String[] splitResult = endResult.split(STRING_SPACE);
_endDate = splitResult[0];
_endTime = splitResult[1];
}
private void extractDescription(){
int index = input.indexOf("-");
if (index != 0){
_desc = input.substring(0, index).trim();
int size = input.length();
input = input.substring(index, size).trim();
}
}
private void processInfo(String param){
param = param.trim();
if (param.isEmpty()){
return;
}
_info = param;
}
/**
* =======================================DEPRECATED=================================================================
*/
/* Helper methods for delimited string */
/**
* @deprecated
*/
private void extractTaskID() {
/*
String[] split = input.split(STRING_SPACE);
_taskID = split[0];
String newInput = STRING_EMPTY;
for (int i=1; i<split.length; i++){
newInput += split[i] + STRING_SPACE;
}
input = newInput;
*/
}
}
| [
"[email protected]"
] | |
8f636428e0da1c99c05cb0297ed1aecbe012b99a | 5cacbd84368f921fafc6e6bd529c966dc5bffb35 | /Game2/src/game2/Consumable.java | 536f431a0f8917365ad234af648805db935ae6a7 | [] | no_license | crecco24/Game2 | f48046fed4999bc998c579e7021ff23531fccc35 | c9094b9caeab49228309febbc1e629d5be4da7eb | refs/heads/master | 2021-01-20T03:31:45.502225 | 2015-11-06T03:57:40 | 2015-11-06T03:57:40 | 34,492,012 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 223 | java |
package game2;
import javalib.worldimages.*;
public interface Consumable {
Boolean isConsumed(PacMan p);
Posn getPosn();
int getScore();
boolean makeEdible();
WorldImage makeImage();
}
| [
"[email protected]"
] | |
b6d9b226a03381b01c95bff43cfb35167a21bde1 | cccb245a603c26d01617f8e1c8a0f1815e8dfb63 | /src/main/java/com/lhy/vo/JsonResult.java | 2d74c5404f22bc50a610eb2772fa3886add255e3 | [] | no_license | shally1213/dreamcloud | 093c2afd5b134cf303e2ad312c12534b58924ca8 | e4bd41792a22de028e415b585827555d74d9274a | refs/heads/master | 2023-05-09T06:43:18.640945 | 2021-05-29T08:59:17 | 2021-05-29T08:59:17 | 370,014,625 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 848 | java | package com.lhy.vo;
public class JsonResult<T> {
private String message;
private Integer code=20;
private T data;
public JsonResult() {
}
public JsonResult(T data) {
this.data = data;
}
@Override
public String toString() {
return "JsonResult{" +
"message='" + message + '\'' +
", code=" + code +
", data=" + data +
'}';
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| [
"[email protected]"
] | |
bc09ab9a0448f706b9e4303dedb7b932ae42abba | 8eb5747699fe5bd31973a6ef75719c032482401c | /problem_5/Solution.java | 5bc3d129a75f7ce5e949fa08b844d63f43e234f9 | [] | no_license | vltsu/projecteuler | 1dc7b76841dcdcb2b7a73dc8f48c5715c0618164 | f9582d203f1e2e003cff4769e3ad4acfb78c6d01 | refs/heads/master | 2021-01-01T19:52:22.917191 | 2013-12-10T21:16:46 | 2013-12-10T21:16:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,080 | java | /*
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
*/
import java.util.*;
class Solution {
public static void main(String[] args) {
assert( numberToPrimes(20).equals(new ArrayList<Integer>() {{ add(2);add(2);add(5); }} ) );
assert( numberToPrimes(19).equals(new ArrayList<Integer>() {{ add(19); }} ) );
ArrayList<Integer> a1 = new ArrayList<Integer>() {{ add(2);add(2);add(3); }};
ArrayList<Integer> a2 = new ArrayList<Integer>() {{ add(2);add(5);add(4); }};
assert(mergeArrays(a1,a2).equals(new ArrayList<Integer>() {{ add(2);add(2);add(3);add(5);add(4); }} ) );
System.out.println(getSmallestNumberDivisibleBySeries());
}
public static Integer getSmallestNumberDivisibleBySeries() {
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<Integer> multipliers = new ArrayList<Integer>();
for(int i = 20; i > 1; i--) {
multipliers = numberToPrimes(i);
result = mergeArrays(multipliers, result);
}
Integer resultNumber = 1;
for(Integer m : result) {
resultNumber *= m;
}
return resultNumber;
}
public static ArrayList<Integer> mergeArrays(ArrayList<Integer> a, ArrayList<Integer> b) {
ArrayList<Integer> result = new ArrayList<Integer>();
Integer temp = 0;
int index = 0;
Iterator<Integer> itr = a.iterator();
while(itr.hasNext()) {
temp = itr.next();
itr.remove();
index = b.indexOf(temp);
if(index >= 0) {
b.remove(index);
}
result.add(temp);
}
result.addAll(b);
return result;
}
public static ArrayList<Integer> numberToPrimes(Integer number) {
ArrayList<Integer> result = new ArrayList<Integer>();
Integer a = 2;
Integer max = number;
while(a<=max) {
if(number % a == 0) {
while(number % a == 0) {
result.add(a);
number /= a;
}
}
a++;
}
return result;
}
}
| [
"[email protected]"
] | |
8d1cd4afe6b99464689f8be989e48384dda9204a | 682d1ee51097ccf9ae07093397a02ee50ac81a63 | /app/src/main/java/com/example/truongbxph07651_asm/adapter/Thu/ThuKhoanSpinnerAdapter.java | 616ca366d4593706acce70ce9eae5db882c0b31a | [] | no_license | bxTruong/truongbxph07651_ASM | 41a8316f9964b975bb14d76cb7fa5aa49012ea33 | 36d03348ed017f8e7cd942f0bfb9bd4336c91eee | refs/heads/master | 2020-08-02T11:08:38.625343 | 2019-09-27T13:50:49 | 2019-09-27T13:50:49 | 211,329,998 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,306 | java | package com.example.truongbxph07651_asm.adapter.Thu;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import com.example.truongbxph07651_asm.R;
import com.example.truongbxph07651_asm.model.ThuLoaiModel;
import java.util.List;
public class ThuKhoanSpinnerAdapter implements SpinnerAdapter {
private List<ThuLoaiModel> thuLoaiModelList;
private Context context;
public ThuKhoanSpinnerAdapter(List<ThuLoaiModel> thuLoaiModelList, Context context) {
this.thuLoaiModelList = thuLoaiModelList;
this.context = context;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.drop_row,parent,false);
TextView tvSpinner1=convertView.findViewById(R.id.tvSpinner1);
tvSpinner1.setText(thuLoaiModelList.get(position).getName());
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.selectedview_row,parent,false);
TextView tvSpinner1=convertView.findViewById(R.id.tvSpinner1);
tvSpinner1.setText(thuLoaiModelList.get(position).getName());
return convertView;
}
@Override
public int getViewTypeCount() {
return 1;
}
//Chuyển về số hàng spinner hiển thị
@Override
public int getCount() {
return thuLoaiModelList.size();
}
@Override
public Object getItem(int position) {
return thuLoaiModelList.get(position);
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
}
| [
"[email protected]"
] | |
5e87ae4755fd5aee38d7b6de83c973684c31e83e | e189ea2403a4aaf4ccd033fab24463b041d23b2c | /src/java/servlets/UserServlet.java | 812badeb4236220140705c0ab3378b83ace61394 | [] | no_license | ashleybrown2296/Week11Lab | f48756dd6cf08fb3973296083a68af4ef6af89d9 | 09381e7ffcc7a479d33e88d1ba85d1b88f5b6b65 | refs/heads/master | 2021-08-22T15:49:53.698021 | 2017-11-30T15:15:32 | 2017-11-30T15:15:32 | 112,625,852 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,278 | java | package servlets;
import businesslogic.UserService;
import domainmodel.Role;
import domainmodel.User;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserService us = new UserService();
String action = request.getParameter("action");
if (action != null && action.equals("view")) {
String selectedUsername = request.getParameter("selectedUsername");
try {
User user = us.get(selectedUsername);
request.setAttribute("selectedUser", user);
} catch (Exception ex) {
Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
List<User> users = null;
try {
users = us.getAll();
} catch (Exception ex) {
Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("users", users);
getServletContext().getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
boolean active = request.getParameter("active") != null;
UserService us = new UserService();
try {
if (action.equals("delete")) {
String selectedUsername = request.getParameter("selectedUsername");
us.delete(selectedUsername);
} else if (action.equals("edit")) {
us.update(username, password, email, active, firstname, lastname, null);
} else if (action.equals("add")) {
us.insert(username, password, email, active, firstname, lastname);
}
} catch (Exception ex) {
request.setAttribute("errorMessage", "Whoops. Could not perform that action.");
}
List<User> users = null;
try {
users = us.getAll();
int number_notes = users.get(0).getNoteList().size();
} catch (Exception ex) {
Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("users", users);
getServletContext().getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
}
}
| [
"[email protected]"
] | |
719a78428c01d4ef2d361da52063647d3738ac63 | 4590b7b7c80aa198212c29d8849bec2d361657fa | /src/main/java/cn/edu/tsinghua/iotdb/kairosdb/query/aggregator/QueryAggregatorType.java | 536e6f775ae51601a80d3c13cb7a8229b59ffa52 | [
"Apache-2.0"
] | permissive | chengupc/iotdb-kairosdb | f1dc04e0bd5a98aeaab90b30df36e3988c3cb37e | 3507d40f24ce3ecd5549107e8f6225eb06e4137e | refs/heads/master | 2023-01-03T01:03:33.147931 | 2019-12-31T06:49:21 | 2019-12-31T06:49:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 630 | java | package cn.edu.tsinghua.iotdb.kairosdb.query.aggregator;
import static cn.edu.tsinghua.iotdb.kairosdb.util.Preconditions.checkNotNullOrEmpty;
public enum QueryAggregatorType {
AVG,
DEV,
COUNT,
FIRST,
LAST,
MAX,
MIN,
PERCENTILE,
SUM,
DIFF,
DIV,
RATE,
SAMPLER,
SAVE_AS,
FILTER;
public static QueryAggregatorType fromString(String typeStr) {
checkNotNullOrEmpty(typeStr);
for (QueryAggregatorType type : values()) {
if (type.toString().equalsIgnoreCase(typeStr)) {
return type;
}
}
throw new IllegalArgumentException("No enum constant for " + typeStr);
}
}
| [
"[email protected]"
] | |
5fa9c9a1047f083b2495847011cfe3b1e3f6a659 | c54e0cc79b6067af173396cf99043b9dd1cdae7b | /src/main/java/com/astra/space/demo/entity/SpacecraftJourneyCatalog.java | 9179e5426b1357064276f6d68803c624ab4a0b1d | [
"Apache-2.0"
] | permissive | dondemcsak/Astra-Java-SpaceCraft-Examples | aa8628c1b4df9f5ae5115242195a5351fd143b26 | d322f755912a088bfac1037d37d4afb59bfe0ee8 | refs/heads/main | 2023-06-02T17:14:41.982183 | 2021-06-13T19:50:29 | 2021-06-13T19:50:29 | 376,624,930 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,138 | java | package com.astra.space.demo.entity;
import java.io.Serializable;
import java.time.Instant;
import java.util.UUID;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder;
import com.datastax.oss.driver.api.core.type.DataTypes;
import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
import com.datastax.oss.driver.api.mapper.annotations.CqlName;
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Entity representing Table
*/
@Entity
@CqlName(SpacecraftJourneyCatalog.TABLE_NAME)
public class SpacecraftJourneyCatalog implements Serializable {
/** Serial. */
private static final long serialVersionUID = 1L;
/** Constants.*/
public static final String TABLE_NAME = "spacecraft_journey_catalog";
public static final String COLUMN_SPACECRAFT_NAME = "spacecraft_name";
public static final String COLUMN_ID = "journey_id";
public static final String COLUMN_START = "start";
public static final String COLUMN_END = "end";
public static final String COLUMN_ACTIVE = "active";
public static final String COLUMN_SUMMARY = "summary";
@PartitionKey
@CqlName(COLUMN_SPACECRAFT_NAME)
@JsonProperty(COLUMN_SPACECRAFT_NAME)
private String name;
@ClusteringColumn
@CqlName(COLUMN_ID)
@JsonProperty(COLUMN_ID)
private UUID journeyId;
@CqlName(COLUMN_START)
private Instant start;
@CqlName(COLUMN_END)
private Instant end;
@CqlName(COLUMN_ACTIVE)
private Boolean active;
@CqlName(COLUMN_SUMMARY)
private String summary;
public SpacecraftJourneyCatalog() {}
/**
* Create table if not exist.
*
* @param session
* current cql session
*/
public static void createTable(CqlSession session) {
session.execute(SchemaBuilder
.createTable(CqlIdentifier.fromCql(TABLE_NAME))
.ifNotExists()
.withPartitionKey(COLUMN_SPACECRAFT_NAME, DataTypes.TEXT)
.withClusteringColumn(COLUMN_ID, DataTypes.TIMEUUID)
.withColumn(COLUMN_START, DataTypes.TIMESTAMP)
.withColumn(COLUMN_END, DataTypes.TIMESTAMP)
.withColumn(COLUMN_ACTIVE, DataTypes.BOOLEAN)
.withColumn(COLUMN_SUMMARY, DataTypes.TEXT)
.withClusteringOrder(COLUMN_ID, ClusteringOrder.DESC)
.build());
}
/**
* Getter accessor for attribute 'name'.
*
* @return
* current value of 'name'
*/
public String getName() {
return name;
}
/**
* Setter accessor for attribute 'name'.
* @param name
* new value for 'name '
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter accessor for attribute 'journeyId'.
*
* @return
* current value of 'journeyId'
*/
public UUID getJourneyId() {
return journeyId;
}
/**
* Setter accessor for attribute 'journeyId'.
* @param journeyId
* new value for 'journeyId '
*/
public void setJourneyId(UUID journeyId) {
this.journeyId = journeyId;
}
/**
* Getter accessor for attribute 'start'.
*
* @return
* current value of 'start'
*/
public Instant getStart() {
return start;
}
/**
* Setter accessor for attribute 'start'.
* @param start
* new value for 'start '
*/
public void setStart(Instant start) {
this.start = start;
}
/**
* Getter accessor for attribute 'end'.
*
* @return
* current value of 'end'
*/
public Instant getEnd() {
return end;
}
/**
* Setter accessor for attribute 'end'.
* @param end
* new value for 'end '
*/
public void setEnd(Instant end) {
this.end = end;
}
/**
* Getter accessor for attribute 'active'.
*
* @return
* current value of 'active'
*/
public Boolean getActive() {
return active;
}
/**
* Setter accessor for attribute 'active'.
* @param active
* new value for 'active '
*/
public void setActive(Boolean active) {
this.active = active;
}
/**
* Getter accessor for attribute 'summary'.
*
* @return
* current value of 'summary'
*/
public String getSummary() {
return summary;
}
/**
* Setter accessor for attribute 'summary'.
* @param summary
* new value for 'summary '
*/
public void setSummary(String summary) {
this.summary = summary;
}
}
| [
"[email protected]"
] | |
171d7d03a25ff53c1beba17bef02828ce5431e11 | 3e6d333331318adede5d8db777f7aff3749e2c38 | /src/main/java/org/practice/linear/search/LinearSearch.java | 29afca1e3a9ac44c32e3f9732e59e18234bc0c2d | [] | no_license | raovikas/algorithms | 577156a532a337aa822c116dc078bbc63e81524d | 65d6b21ed5a39a6aebeea8e6975bff7c5f9eb84a | refs/heads/master | 2022-12-07T06:30:12.809484 | 2020-08-26T07:15:53 | 2020-08-26T07:15:53 | 283,934,844 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 569 | java | package org.practice.linear.search;
public class LinearSearch
{
public static void main(String[] args)
{
int[] arr = { 1, 22, 4, 7, 10, 6 };
int element = 2;
LinearSearch ls = new LinearSearch();
int index = ls.search(arr, element);
System.out.println("index of element 7 in array: " + index);//-1 means element is not present in array
}
private int search(int[] arr, int element)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == element)
return i;
}
return -1;
}
}
| [
"[email protected]"
] | |
faa5dea7d68003c4079c8c0b62c15d2d6f3c89dc | b0041ebe5bc592e2f9e67023b5956a11e96ae0c1 | /linkedlist/LinkedListString.java | 05b7aaa52faccf97c55496e6dca2f2e7c6c83c31 | [] | no_license | saniyat013/data-structures-101 | eeeaa86cba7b73fd1f2599d938be19236b0cc702 | 3be3b6a15b3b0e9eea9022ca76bccc2de6454aeb | refs/heads/master | 2023-03-02T20:07:43.969632 | 2021-02-09T11:47:08 | 2021-02-09T11:47:08 | 325,786,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,645 | java | package linkedlist;
class LinkedListString {
Node head;
static class Node {
String data;
Node next;
Node(String data) {
this.data = data;
next = null;
}
}
void push(String data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
void insertAfter(Node prev, String data) {
if (prev == null) {
System.out.println("This node can't be null!");
return;
}
Node newNode = new Node(data);
newNode.next = prev.next;
prev.next = newNode;
}
void insertAfterValue(String value, String data) {
if (value.equals("")) {
System.out.println("This value can't be null!");
return;
}
Node n = head;
while (n != null) {
if (n.data.equals(value)) {
Node newNode = new Node(data);
newNode.next = n.next;
n.next = newNode;
return;
}
n = n.next;
}
}
void append(String data) {
if (head == null) {
head = new Node(data);
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
Node newNode = new Node(data);
n.next = newNode;
}
}
void insertValues(String data[]) {
head = null;
for (String x : data) {
append(x);
}
}
void deleteAt(int position) {
if (position < 1 || position > getSize()) {
System.out.println("The position is not valid!");
return;
}
if (position == 1) {
head = head.next;
} else {
Node n = head;
int index = 1;
while (n != null) {
if (index == position - 1) {
n.next = n.next.next;
return;
}
n = n.next;
index++;
}
}
}
void deleteByValue(String value) {
if (value.equals("")) {
System.out.println("This value can't be null!");
return;
}
if (head.data.equals(value)) {
head = head.next;
} else {
Node n = head;
while (n.next != null) {
if (n.next.data.equals(value)) {
n.next = n.next.next;
return;
}
n = n.next;
}
System.out.println("Given value not found!");
}
}
void insertAt(int position, String data) {
if (position < 1 || position > getSize()) {
System.out.println("The position is not valid!");
return;
}
if (position == 1) {
push(data);
} else {
Node n = head;
int index = 1;
while (n != null) {
if (index == position - 1) {
Node newNode = new Node(data);
newNode.next = n.next;
n.next = newNode;
return;
}
n = n.next;
index++;
}
}
}
int getSize() {
int size = 0;
if (head == null) {
return 0;
} else {
Node n = head;
while (n != null) {
size++;
n = n.next;
}
return size;
}
}
void printList() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node n = head;
while (n != null) {
if (n.next == null) {
System.out.print(n.data);
} else {
System.out.print(n.data + "-->");
}
n = n.next;
}
System.out.println("");
}
public static void main(String[] args) {
LinkedListString list = new LinkedListString();
String values[] = {"banana", "mango", "grapes", "orange"};
list.insertValues(values);
list.printList();
list.insertAfterValue("mango", "apple");
list.printList();
list.deleteByValue("orange");
list.printList();
list.deleteByValue("figs");
list.deleteByValue("banana");
list.printList();
list.deleteByValue("mango");
list.deleteByValue("apple");
list.deleteByValue("grapes");
list.printList();
}
}
| [
"[email protected]"
] | |
54e30a500da10b2798844cd14094b69782237718 | a477fdda4d1a5e5a9d9b437b74b58ba41b0829df | /ruisiyuan/src/com/yjw/ctrl/OrderCtrl.java | b39c975fd0271ca0a6a08d274ae30f522a0d532d | [] | no_license | htyten/ruisiyuan | 9c76c34ab4f8d0983ea5aa702c6cc05735521190 | d59d9e05cac63878a95d4751a73985d802535397 | refs/heads/master | 2020-12-29T04:57:42.619158 | 2020-02-05T14:00:47 | 2020-02-05T14:00:47 | 238,462,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,540 | java | package com.yjw.ctrl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yjw.condition.OrderCondition;
import com.yjw.pojo.Account;
import com.yjw.pojo.Order;
import com.yjw.service.OrderService;
/**
* 订单管理
* @author eason
*
* 2016年6月6日下午4:21:39
*/
@Controller
@RequestMapping("order")
public class OrderCtrl extends BaseCtrl<Order> {
@Autowired
private OrderService orderService;
@RequestMapping("order_editState")
@ResponseBody
public Map<String, Object> editState(Order order, ModelMap model) {
log.info("编辑订单状态....." + order.getInfo() + " " + order.getState());
Map<String, Object> result = new HashMap<String, Object>();
// 获得当前登录用户
Account acc = (Account) model.get("loginAccount");
// 编辑备注
orderService.editState(order, acc.getAccount());
result.put("code", 1);
result.put("message", "变更订单状态成功!");
return result;
}
@RequestMapping("order_editInfo")
@ResponseBody
public Map<String, Object> editInfo(Order order, ModelMap model) {
log.info("编辑备注....." + order.getInfo());
Map<String, Object> result = new HashMap<String, Object>();
// 获得当前登录用户
Account acc = (Account) model.get("loginAccount");
// 编辑备注
orderService.editInfo(order, acc.getAccount());
result.put("code", 1);
result.put("message", "备注成功!");
return result;
}
@RequestMapping("order_table")
@ResponseBody
public Map<String, Object> table(int page, int rows,OrderCondition condition) {
log.info("easyui,分页查询....." + condition.getStateCondition());
Map<String, Object> result = new HashMap<String, Object>();
// 计算从第几条记录开始查询
int start = (page - 1) * rows;
// 设置返回对象 (一定要返回 key: total、rows)
result.put("total", orderService.getTotal(condition)); // 记录总数
result.put("rows", orderService.getItems(condition, start, rows)); // 当前页的所有记录数
return result;
}
@RequestMapping("order_list")
public String list(int stateCondition, ModelMap model) {
model.put("stateCondition", stateCondition);
log.info("进入order 管理页......." + stateCondition);
return "order/order_list";
}
}
| [
"[email protected]"
] | |
88bc28ad48d54e4a536ae26c596795966ca6df4b | 768a5d76f8d2c8c7f2b84e436ba4e4d1963171ed | /wildfly-11.0.0.CR1-quickstarts/xml-dom4j/src/main/java/org/jboss/as/quickstart/xml/DOM4JXMLParser.java | 9fa350142306491e6568d209fa6244fa3a5a0823 | [
"Apache-2.0"
] | permissive | asaini94/war_agent | dbc4252363329f1d9486416dd7efe1cde9f399ef | 079deb3388352d14d1271afdb3fe12846bdbe41c | refs/heads/master | 2020-04-22T21:02:56.201178 | 2019-02-15T06:38:58 | 2019-02-15T06:38:58 | 170,660,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,471 | java | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstart.xml;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Implementation of parser based on DOM4J.
*
* @author baranowb
*
*/
@RequestScoped
@Default
public class DOM4JXMLParser extends XMLParser {
// Inject instance of error holder
@Inject
private Errors errorHolder;
// Get the SAXReader object
private SAXReader dom4jReader = new SAXReader();
private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
DOM4JXMLParser() throws Exception {
// Set SAX error handler. So errors atleast show up in console
this.dom4jReader.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException e) throws SAXException {
errorHolder.addErrorMessage("warning", e);
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
errorHolder.addErrorMessage("fatal error", e);
}
@Override
public void error(SAXParseException e) throws SAXException {
errorHolder.addErrorMessage("error", e);
}
});
}
@Override
public List<Book> parseInternal(InputStream is) throws Exception {
Document document = this.dom4jReader.read(is);
List<Book> catalog = new ArrayList<>();
Element root = document.getRootElement();
if (!root.getQName().getName().equals("catalog")) {
throw new RuntimeException("Wrong element: " + root.getQName());
}
Iterator<?> children = root.elementIterator();
while (children.hasNext()) {
Node n = (Node) children.next();
String childName = n.getName();
if (childName == null)
continue;
if (childName.equals("book")) {
Book b = parseBook((Element) n);
catalog.add(b);
}
}
return catalog;
}
private Book parseBook(Element n) {
Book b = new Book();
Iterator<?> children = n.elementIterator();
/*
* parse book element, we have to once more iterate over children.
*/
while (children.hasNext()) {
Node child = (Node) children.next();
String childName = child.getName();
// empty/text nodes dont have name
if (childName == null)
continue;
if (childName.equals("author")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
b.setAuthor(textVal);
} else if (childName.equals("title")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
b.setTitle(textVal);
} else if (childName.equals("genre")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
b.setGenre(textVal);
} else if (childName.equals("price")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
b.setPrice(Float.parseFloat(textVal));
} else if (childName.equals("publish_date")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
Date d;
try {
d = DATE_FORMATTER.parse(textVal);
b.setPublishDate(d);
} catch (ParseException e) {
throw new RuntimeException(e);
}
} else if (childName.equals("description")) {
Element childElement = (Element) child;
String textVal = childElement.getTextTrim();
b.setDescription(textVal);
}
}
return b;
}
}
| [
"[email protected]"
] | |
93681b602e585f84bb11ed35f3b82196b5785820 | 471a1d9598d792c18392ca1485bbb3b29d1165c5 | /jadx-MFP/src/main/java/com/moat/analytics/mobile/und/MoatFactory.java | b24cc3f6ae3ea48d756dad622303bc8c071b892b | [] | no_license | reed07/MyPreferencePal | 84db3a93c114868dd3691217cc175a8675e5544f | 365b42fcc5670844187ae61b8cbc02c542aa348e | refs/heads/master | 2020-03-10T23:10:43.112303 | 2019-07-08T00:39:32 | 2019-07-08T00:39:32 | 129,635,379 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | package com.moat.analytics.mobile.und;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.moat.analytics.mobile.und.v.b;
import java.util.Map;
public abstract class MoatFactory {
public static MoatFactory create() {
try {
return new n();
} catch (Exception e) {
m.a(e);
return new b();
}
}
public abstract <T> T createCustomTracker(MoatPlugin<T> moatPlugin);
public abstract NativeDisplayTracker createNativeDisplayTracker(View view, Map<String, String> map);
public abstract NativeVideoTracker createNativeVideoTracker(String str);
public abstract WebAdTracker createWebAdTracker(ViewGroup viewGroup);
public abstract WebAdTracker createWebAdTracker(WebView webView);
}
| [
"[email protected]"
] | |
6ecd4740f8c14b69ddd1f1c9d680c0af59e05edb | b66b4ca3c7dd65cbf2d7914a2f6bd8e551be9218 | /spring-graphQL/src/main/java/com/hcl/springgraphQL/entity/Person.java | 9fd0f10cce2cd4b24706edbbcb29000e80f5888b | [] | no_license | saikumar1822/SpringBootWithMicroSerivces | b57355a0b9d475f959ce21c4b2097122dddab0a5 | 0b00b7f2e6120effac08fea218585520a22ca147 | refs/heads/master | 2023-09-05T04:55:27.460649 | 2021-10-27T11:00:36 | 2021-10-27T11:00:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,144 | java | package com.hcl.springgraphQL.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String mobile;
private String email;
private String adress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public Person(int id, String name, String mobile, String email, String adress) {
super();
this.id = id;
this.name = name;
this.mobile = mobile;
this.email = email;
this.adress = adress;
}
public Person() {
}
}
| [
"[email protected]"
] | |
ae4ec62e31037c7ad92815c1169f3d3ee3034959 | 35409e5c139f8e2af6adc09a7ab224e8501e974d | /src/javaElementary/lesson2/Main.java | 11fc2e5bbbb5697f264c3393d1c65f94debf835b | [] | no_license | OleksandraLy/javaElementary | 622bf1e1792425ad7d4bbe7b0cda9394aab4e054 | f02a4567edd013abc380137d94f1779882fbe264 | refs/heads/master | 2023-05-02T16:41:21.291933 | 2021-05-29T11:07:32 | 2021-05-29T11:07:32 | 370,380,855 | 0 | 0 | null | 2021-05-29T12:15:31 | 2021-05-24T14:29:01 | Java | UTF-8 | Java | false | false | 1,514 | java | package javaElementary.lesson2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Animal cat = new Animal("Maincoon", 2, 30, 1000);
Animal dog = new Animal("Malamute", 5, 50, 2000);
Animal bird = new Animal("parrot", 1, 10, 3000);
Animal[] animals = {cat, dog, bird};
System.out.println(animals);
Arrays.sort(animals, new CompareByPrice());
System.out.println(animals);
Arrays.sort(animals, new CompareByBreed());
System.out.println(animals);
/* Arrays.sort(animals, new Comparator<Animal>() {
@Override
public int compare(Animal o1, Animal o2) {
if (o1.price == o2.price){
int comparing = o1.speed - o2.speed;
return comparing;}
else {int comparing = o1.price - o2.price;
return comparing;
}
});
Arrays.sort(animals, new Comparator<Animal>() {
@Override
public int compare(Animal o1, Animal o2) {
int comparing2 = o1.weight - o2.weight;
return comparing2;
}
});
Arrays.sort(animals, new Comparator<Animal>() {
@Override
public int compare(Animal o1, Animal o2) {
int comparing3 = o1.price - o2.price;
return comparing3;
}
})
}*/
}
}
| [
"[email protected]"
] | |
a46fcbe446e377022c3e213a51316f281120ddb8 | df84a95b0d77eb4f5053c5debe213613394f7f56 | /sso-server/src/main/java/com/learn/sso/server/service/LoginService.java | e2e8e76e2b26ad0d3dace9f44ed5ba2432d37e9d | [] | no_license | wu00yu11/learn-sso | ba8ef145cbe4eadf96ccc0b0a11df3dd0ed9a209 | 91569ce66b27402ba7e3ed5305926e1ff6dad0ac | refs/heads/master | 2023-03-03T10:45:56.760938 | 2021-02-15T14:55:10 | 2021-02-15T14:55:10 | 332,445,265 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 117 | java | package com.learn.sso.server.service;
/**
* @author wu00y
*/
public interface LoginService {
void login();
}
| [
"[email protected]"
] | |
b0e89c9b3b280909eebfaeee133a05d11aa21a68 | 763957995defbfce3be80fdae2fbdd6b3c7edf11 | /relf/src/main/java/org/nexus_lab/relf/lib/rdfvalues/crypto/EncryptionKey.java | 69e8927e9164055d5a807e5ccb4047146bbdf4f0 | [] | no_license | nexus-lab/relf-client | f294008eed04086b5b28d898ae85240ae59e20b7 | 579fbb40285507860fc06b0536fab0605cc77d46 | refs/heads/master | 2023-06-13T03:22:58.113933 | 2021-07-05T21:20:51 | 2021-07-05T21:20:51 | 382,899,495 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,801 | java | package org.nexus_lab.relf.lib.rdfvalues.crypto;
import com.google.protobuf.ByteString;
import org.nexus_lab.relf.lib.rdfvalues.RDFBytes;
import org.nexus_lab.relf.utils.ByteUtils;
import net.badata.protobuf.converter.type.TypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Random;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @author Ruipeng Zhang
*/
@NoArgsConstructor
public class EncryptionKey extends RDFBytes {
@Getter
@Accessors(fluent = true)
private int length;
public EncryptionKey(byte[] value) {
super(value);
}
/**
* Create {@link EncryptionKey} from hexadecimal string.
*
* @param string serialized string representation of an {@link EncryptionKey}
* @return a new instance of {@link EncryptionKey}
*/
public static EncryptionKey fromHexString(String string) {
return new EncryptionKey(ByteUtils.fromHexString(string));
}
/**
* Generate a new {@link EncryptionKey} of the given length.
*
* @param length key length in bits
* @return a new instance of {@link EncryptionKey}
*/
public static EncryptionKey generateKey(int length) {
byte[] data = new byte[length / 8];
new Random().nextBytes(data);
return new EncryptionKey(data);
}
/**
* Generate a new random initialization vector of the given length.
*
* @param length vector length in bits
* @return a new initialization vector
*/
public static EncryptionKey generateRandomIV(int length) {
return generateKey(length);
}
@Override
public void setValue(byte[] value) {
length = value.length * 8;
if (length < 128) {
throw new RuntimeException(String.format(Locale.US, "Key too short (%d): %s.", length,
Arrays.toString(value)));
}
super.setValue(value);
}
@Override
public EncryptionKey parse(byte[] value) {
if (value.length % 8 != 0) {
throw new RuntimeException(
String.format(Locale.US, "Invalid key length %d (%s).", value.length,
Arrays.toString(value)));
}
setValue(value);
return this;
}
@Override
public String toString() {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(ByteUtils.toHexString(getValue()).getBytes());
return String.format("<%s> %s", getClass().getSimpleName(),
ByteUtils.toHexString(hash));
} catch (NoSuchAlgorithmException ignored) {
}
return String.format("<%s> %s", getClass().getSimpleName(), "");
}
/**
* {@link TypeConverter} for inter-conversion between {@link ByteString} and {@link
* EncryptionKey}
* during protobuf conversion.
*/
public static class Converter implements TypeConverter<EncryptionKey, ByteString> {
@Override
public EncryptionKey toDomainValue(Object instance) {
if (instance instanceof ByteString) {
return new EncryptionKey(((ByteString) instance).toByteArray());
}
throw new RuntimeException("Failed to convert protobuf values to rdf values.");
}
@Override
public ByteString toProtobufValue(Object instance) {
if (instance instanceof EncryptionKey) {
return ByteString.copyFrom(((EncryptionKey) instance).serialize());
}
throw new RuntimeException("Failed to convert rdf values to protobuf values.");
}
}
}
| [
"[email protected]"
] | |
0b69201f37efd31a51fae3d5c0b6f7610f63e26b | 1f01d9a940d4db4a4f65dccfc31350060249fdd5 | /day4/question3.java | 78e246e3b76e861ca3a2a4ee4d503e5b0c733160 | [] | no_license | sarthakblr11/JAVA | 3d2c9b5695fb8a7badd300a1aa07196ede7a3113 | fa40530fb89883587f35f394fa64062877adeec1 | refs/heads/main | 2022-12-28T10:48:32.826927 | 2020-10-16T11:26:11 | 2020-10-16T11:26:11 | 303,329,611 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | public class SumOfArray {
public static void main(String[] args) {
int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
}
} | [
"[email protected]"
] | |
ba2d22db67387569689f00bf82b99e0c0ff6cc5d | 7c5fd32e93edcd032a33bb1cb4544f53d9095d87 | /fees/src/main/java/com/emt/constant/StateConstant.java | 1e76598f0751c2f01d522ee489123c1b45a430a9 | [] | no_license | traxexee/esdemo | 00ca3fbdf8039e0bddf41ffa2aa3e1c3cad08483 | 25f412280fe15b96ee412c20996fa93875184a27 | refs/heads/master | 2023-02-02T14:17:54.482276 | 2020-12-15T09:54:14 | 2020-12-15T09:54:14 | 321,617,504 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 230 | java | package com.emt.constant;
/**
* @author 刘震
* @date 2018年12月11日 下午2:16:08
*/
public interface StateConstant {
//异常
Integer basicState=10;
//正常
Integer successState=0;
//已处理
Integer dealState=1;
}
| [
"[email protected]"
] | |
6b68657224974376a1c7e906f3b494fd11a01244 | 36ba7792e0cccfe9c217a2fe58700292af6d2204 | /in_dev_npc_combat_b/SkeletonHellhound214Combat.java | 7edf81f995588c5d8c7d9cf9c6b4dc877a25296d | [] | no_license | danielsojohn/BattleScape-Server-NoMaven | 92a678ab7d0e53a68b10d047638c580c902673cb | 793a1c8edd7381a96db0203b529c29ddf8ed8db9 | refs/heads/master | 2020-09-09T01:55:54.517436 | 2019-11-15T05:08:02 | 2019-11-15T05:08:02 | 221,307,980 | 0 | 0 | null | 2019-11-12T20:41:54 | 2019-11-12T20:41:53 | null | UTF-8 | Java | false | false | 1,880 | java | package script.npc.combat;
import java.util.Arrays;
import java.util.List;
import com.palidino.osrs.io.cache.NpcId;
import com.palidino.osrs.model.npc.combat.NpcCombatDefinition;
import com.palidino.osrs.model.npc.combat.NpcCombatHitpoints;
import com.palidino.osrs.model.npc.combat.NpcCombatStats;
import com.palidino.osrs.model.CombatBonus;
import com.palidino.osrs.model.npc.combat.NpcCombatAggression;
import com.palidino.osrs.model.npc.combat.NpcCombatType;
import com.palidino.osrs.model.npc.combat.style.NpcCombatStyle;
import com.palidino.osrs.model.npc.combat.style.NpcCombatStyleType;
import com.palidino.osrs.model.npc.combat.style.NpcCombatDamage;
import com.palidino.osrs.model.npc.combat.style.NpcCombatProjectile;
import com.palidino.osrs.model.npc.combat.NpcCombat;
import lombok.var;
public class SkeletonHellhound214Combat extends NpcCombat {
@Override
public List<NpcCombatDefinition> getCombatDefinitions() {
var combat = NpcCombatDefinition.builder();
combat.id(NpcId.SKELETON_HELLHOUND_214);
combat.hitpoints(NpcCombatHitpoints.total(110));
combat.stats(NpcCombatStats.builder().attackLevel(110).bonus(CombatBonus.DEFENCE_STAB, 75).bonus(CombatBonus.DEFENCE_SLASH, 82).bonus(CombatBonus.DEFENCE_CRUSH, 10).bonus(CombatBonus.DEFENCE_MAGIC, 105).bonus(CombatBonus.DEFENCE_RANGED, 138).build());
combat.aggression(NpcCombatAggression.builder().range(4).build());
combat.type(NpcCombatType.UNDEAD).deathAnimation(6576).blockAnimation(6578);
var style = NpcCombatStyle.builder();
style.type(NpcCombatStyleType.melee(CombatBonus.ATTACK_STAB));
style.damage(NpcCombatDamage.maximum(26));
style.animation(6579).attackSpeed(4);
style.projectile(NpcCombatProjectile.id(335));
combat.style(style.build());
return Arrays.asList(combat.build());
}
}
| [
"[email protected]"
] | |
40ead70885f3ecd2e43f3b67b5776a173c2196d5 | 3e9c8f1aa9563f002bae6ec9dc2917b3df47ce15 | /chrome/android/java/src/org/chromium/chrome/browser/tabmodel/SingleTabModelSelector.java | a99538136708d75b5abe21dba274ef055d9532ce | [
"BSD-3-Clause"
] | permissive | raymomd/chromium | f99db09e85914de2229caf47e3cc8dbbb695c560 | dbf955be0c470d6568e146420fefe10e75a08f92 | refs/heads/master | 2023-01-15T12:56:52.274925 | 2019-08-19T19:50:59 | 2019-08-19T19:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 862 | java | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tabmodel;
import android.app.Activity;
import org.chromium.chrome.browser.tab.Tab;
/**
* Simple TabModelSelector that assumes that only a single TabModel exists at a time.
*/
public class SingleTabModelSelector extends TabModelSelectorBase {
public SingleTabModelSelector(Activity activity, TabCreatorManager tabCreatorManager,
boolean incognito, boolean blockNewWindows) {
super(tabCreatorManager);
initialize(incognito, new SingleTabModel(activity, incognito, blockNewWindows));
}
public void setTab(Tab tab) {
((SingleTabModel) getCurrentModel()).setTab(tab);
markTabStateInitialized();
}
}
| [
"[email protected]"
] | |
c38601764af39fe5ee5d058434d6d68164f393cb | fd0102a0e292a5beda4ff1fc09839249863a14f4 | /src/main/java/com/platzhaltr/flatlinr/core/FlatFileIterator.java | 99274b727ef55300ef6d7f07a458805e59c6b5e1 | [] | no_license | platzhaltr/flatlinr | d8215300aa3ef6bee4fe765bbbfc108f484dfdfd | 61f5476c33e4803addf81577309f3667c996e80f | refs/heads/master | 2021-01-02T08:52:35.739851 | 2012-10-10T12:50:47 | 2012-10-10T12:50:47 | 3,228,122 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,629 | java | /*
* Copyright 2011 Oliver Schrenk
*
* 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.platzhaltr.flatlinr.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import com.platzhaltr.flatlinr.api.Feature;
import com.platzhaltr.flatlinr.api.Leaf;
import com.platzhaltr.flatlinr.api.TraverseStrategy;
/**
* Consume a hierarchical flat file.The hierarchy of the flat file can be
* descibed using {@link Node}, attaching {@link Leaf} and other child nodes to
* them, viewing the flat file as a graph.
*
* The iterator uses the graph structure to decide how toi break down each line
* into important {@link Record}s. In order to decise what nodes or leafs take
* precedence a {@link TraverseStrategy} can be supplied. The default strategy
* uses various biases to determine the next node is defined in the
* {@link DefaultTraverseStrategy}.
*
* @author Oliver Schrenk <[email protected]>
*/
public class FlatFileIterator implements Iterator<Record> {
/** The reader. */
private final BufferedReader reader;
/** The stack. */
private final Stack<Node> stack = new Stack<Node>();
/** The current line. */
private String currentLine;
/** The next line. */
private String nextLine;
/** The traverse strategy. */
private final TraverseStrategy traverseStrategy;
/**
* Instantiates a new flat file iterator.
*
* @param rootNode
* the root node
* @param file
* the file
* @throws FileNotFoundException
* the file not found exception
*/
public FlatFileIterator(final Node rootNode, final File file)
throws FileNotFoundException {
this(rootNode, new FileReader(file));
}
/**
* Instantiates a new flat file iterator.
*
* @param rootNode
* the root node
* @param file
* the file
* @param traverseStrategy
* the traverse strategy
* @throws FileNotFoundException
* the file not found exception
*/
public FlatFileIterator(final Node rootNode, final File file,
final TraverseStrategy traverseStrategy)
throws FileNotFoundException {
this(rootNode, new FileReader(file), traverseStrategy);
}
/**
* Instantiates a new flat file iterator.
*
* @param rootNode
* the flat node
* @param reader
* the reader
*/
public FlatFileIterator(final Node rootNode, final Reader reader) {
this(rootNode, reader, new DefaultTraverseStrategy());
}
/**
* Instantiates a new flat file reader.
*
* @param rootNode
* the node
* @param reader
* the reader
* @param traverseStrategy
* the traverse strategy
*/
public FlatFileIterator(final Node rootNode, final Reader reader,
final TraverseStrategy traverseStrategy) {
this.traverseStrategy = traverseStrategy;
if (reader instanceof BufferedReader) {
this.reader = (BufferedReader) reader;
} else {
this.reader = new BufferedReader(reader);
}
stack.add(rootNode);
}
/**
* Returns the next {@link Record}.
*
* @return the record
*/
@Override
public Record next() {
final Node currentNode = stack.pop();
if (currentLine == null) {
try {
currentLine = (nextLine != null) ? nextLine : reader.readLine();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
final Record record = new Record(currentNode.getId());
for (final Leaf leaf : currentNode.getLeafs()) {
if (leaf instanceof ConstantLeaf) {
final ConstantLeaf constantLeaf = (ConstantLeaf) leaf;
final String constant = constantLeaf.getConstant();
if (currentLine.startsWith(constant)) {
currentLine = currentLine.substring(constant.length());
}
} else if (leaf instanceof DelimitedLeaf) {
final DelimitedLeaf delimitedLeaf = (DelimitedLeaf) leaf;
final String delimiter = delimitedLeaf.getDelimiter();
boolean last = false;
int indexOf = currentLine.indexOf(delimiter);
if (indexOf == -1) {
indexOf = currentLine.length();
last = true;
}
final String value = apply(currentLine.substring(0, indexOf),
delimitedLeaf.getFeatures());
record.put(leaf.getId(), value);
// we reached the end of the line and leave the loop
if (last) {
break;
}
currentLine = currentLine.substring(indexOf
+ delimiter.length());
} else if (leaf instanceof LineLeaf) {
final LineLeaf lineLeaf = (LineLeaf) leaf;
final String value = apply(currentLine, lineLeaf.getFeatures());
record.put(leaf.getId(), value);
// we reached the end of the line and leave the loop
break;
}
}
try {
getNextLine();
} catch (final IOException e) {
throw new RuntimeException(e);
}
if (hasNext()) {
stack.push(traverseStrategy.getNextNode(currentNode, nextLine));
}
return record;
}
/**
* Checks if the reader can return another {@link Record} (another line).
*
* @return true, if successful
*/
@Override
public boolean hasNext() {
try {
return nextLine != null || reader.ready();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
/**
* Gets the next line.
*
* @return the next line
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String getNextLine() throws IOException {
currentLine = null;
nextLine = reader.readLine();
return nextLine;
}
/**
* Apply features.
*
* @param s
* the s
* @param features
* the features
* @return the string
*/
private String apply(String s, final List<Feature> features) {
for (final Feature feature : features) {
s = feature.convert(s);
}
return s;
}
/**
* Operation not supported.
*
* @throws UnsupportedOperationException
*/
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| [
"[email protected]"
] | |
fd2be5e6e1068c2b1976d3441294487a30459c68 | 2943f233ac0e073f585c9142f5ff66ecba7d8b13 | /MessageCore/JavaSource/com/legacytojava/message/bo/rule/RulesDataBoImpl.java | a4f1f0d8ab5d1b68a3106aaa069becb2c9e7947b | [] | no_license | barbietunnie/jboss-5-to-7-migration | 1a519afeee052cf02c51823b5bf2003d99056112 | 675e33b8510ca09e7efdb5ca63ccb73c93abba8a | refs/heads/master | 2021-01-10T18:40:13.068747 | 2015-05-29T19:01:26 | 2015-05-29T19:01:26 | 57,383,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,811 | java | package com.legacytojava.message.bo.rule;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.legacytojava.jbatch.SpringUtil;
import com.legacytojava.message.bo.TaskBaseBo;
import com.legacytojava.message.dao.rule.RuleDao;
import com.legacytojava.message.external.RuleTargetProc;
import com.legacytojava.message.vo.rule.RuleElementVo;
import com.legacytojava.message.vo.rule.RuleVo;
@Component("rulesDataBo")
public final class RulesDataBoImpl implements RulesDataBo {
static final Logger logger = Logger.getLogger(RulesDataBoImpl.class);
static final boolean isDebugEnabled = logger.isDebugEnabled();
@Autowired
private RuleDao ruleDao;
private RulesDataBoImpl() {
}
public List<RuleVo> getCurrentRules() {
List<RuleVo> rules = ruleDao.getActiveRules();
substituteTargetProc(rules);
substituteExclListProc(rules);
return rules;
}
public RuleVo getRuleByPrimaryKey(String key) {
RuleVo ruleVo = (RuleVo) ruleDao.getByPrimaryKey(key);
substituteTargetProc(ruleVo);
substituteExclListProc(ruleVo);
return ruleVo;
}
public RuleDao getRuleDao() {
return ruleDao;
}
private void substituteTargetProc(List<RuleVo> rules) {
if (rules == null || rules.size() == 0) return;
for (RuleVo rule : rules) {
substituteTargetProc(rule);
}
}
private void substituteTargetProc(RuleVo rule) {
List<RuleElementVo> elements = rule.getRuleElementVos();
if (elements == null) return;
for (RuleElementVo element : elements) {
if (element.getTargetProc() == null) continue;
Object obj = null;
try { // a TargetProc could be a class name or a bean id
obj = Class.forName(element.getTargetProc()).newInstance();
logger.info("Loaded class " + element.getTargetProc() + " for rule "
+ rule.getRuleName());
}
catch (Exception e) { // not a class name, try load it as a Bean
try {
obj = SpringUtil.getAppContext().getBean(element.getTargetProc());
logger.info("Loaded bean " + element.getTargetProc() + " for rule "
+ rule.getRuleName());
}
catch (Exception e2) {
logger.warn("Failed to load: " + element.getTargetProc() + " for rule "
+ rule.getRuleName());
}
if (obj == null) continue;
}
try {
String text = null;
if (obj instanceof TaskBaseBo) {
TaskBaseBo bo = (TaskBaseBo) obj;
text = (String) bo.process(null);
}
else if (obj instanceof RuleTargetProc) {
RuleTargetProc bo = (RuleTargetProc) obj;
text = bo.process();
}
if (text != null && text.trim().length() > 0) {
logger.info("Changing Target Text for rule: " + rule.getRuleName());
logger.info(" From: " + element.getTargetText());
logger.info(" To: " + text);
element.setTargetText(text);
}
}
catch (Exception e) {
logger.error("Exception caught", e);
throw new RuntimeException(e.toString());
}
}
}
private void substituteExclListProc(List<RuleVo> rules) {
if (rules == null || rules.size() == 0) return;
for (RuleVo rule : rules) {
substituteExclListProc(rule);
}
}
private void substituteExclListProc(RuleVo rule) {
List<RuleElementVo> elements = rule.getRuleElementVos();
if (elements == null) return;
for (RuleElementVo element : elements) {
if (element.getExclListProc() == null) continue;
Object obj = null;
try {
obj = SpringUtil.getAppContext().getBean(element.getExclListProc());
}
catch (Exception e) {
logger.error("Failed to load bean: " + element.getExclListProc() + " for rule "
+ rule.getRuleName());
}
if (obj == null || !(obj instanceof TaskBaseBo)) continue;
TaskBaseBo bo = (TaskBaseBo) obj;
try {
String text = (String) bo.process(null);
if (text != null && text.trim().length() > 0) {
logger.info("Appending Exclusion list for rule: " + rule.getRuleName());
logger.info(" Exclusion List: " + text);
String delimiter = element.getDelimiter();
if (delimiter == null || delimiter.length() == 0) {
delimiter = ",";
}
String origText = element.getExclusions();
if (origText != null && origText.length() > 0) {
origText = origText + delimiter;
}
else {
origText = "";
}
element.setExclusions(origText + text);
}
}
catch (Exception e) {
logger.error("Exception caught", e);
throw new RuntimeException(e.toString());
}
}
}
public static void main(String[] args) {
RulesDataBo bo = (RulesDataBo) SpringUtil.getAppContext().getBean("rulesDataBo");
bo.getCurrentRules();
}
}
| [
"[email protected]"
] | |
a01e0b15e4272ba48f5b394d9ba551340bfec711 | 36eaa7e145ac294415cde582b554d4d379bdec86 | /app/src/main/java/com/example/squadzframes/model/Event.java | 83a16e048abc2313b6b368b52a35fac2bbbb02de | [] | no_license | JustinAntunes-Cardoso/SquadzApplication | f0c1e4e5de9f6de63ec7fe21a41dfd13eb7d60e6 | efc2052bc2669472d3a407b53506ed3b48d71560 | refs/heads/master | 2023-04-09T12:20:01.171415 | 2021-04-24T21:34:04 | 2021-04-24T21:34:04 | 320,925,939 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,079 | java | package com.example.squadzframes.model;
public class Event {
String id;
String location;
String host;
String time;
String partySize;
String complvl;
public Event(){
this.id = "";
this.location = "";
this.host = "";
this.time = "";
this.partySize = "";
this.complvl = "";
}
public Event(String host){
this.host = "";
}
public Event(String id, String location, String host, String time, String partySize, String complvl) {
this.id = id;
this.location = location;
this.host = host;
this.time = time;
this.partySize = partySize;
this.complvl = complvl;
}
public String getId() {
return id;
}
public String getLocation() {
return location;
}
public String getHost() {
return host;
}
public String getTime() {
return time;
}
public String getPartySize() {
return partySize;
}
public String getComplvl() {
return complvl;
}
}
| [
"[email protected]"
] | |
290138abcf0f4ea511ccec248b8d4c56abb5f60e | bd7de1014ce448c2ae6cd670eeb3dc7f4fecea51 | /src/src/GFG.java | 2cb71edffc4232adf556fc7a2284ebe3ac94566b | [] | no_license | LeemonX/asu-travelling-salesman-problem | 461310dc9424c0a78190c3bd4837da899044e867 | 849d0f45dc7adbfe43ed3e071bfd4cd542523180 | refs/heads/master | 2022-11-07T23:44:00.729613 | 2020-06-24T12:58:23 | 2020-06-24T12:58:23 | 268,269,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,046 | java | import java.util.Arrays;
public class GFG {
static int N;
static int[] final_path;
static boolean[] visited;
static int final_res;
public GFG(){
N = 4;
final_path = new int[N + 1];
visited = new boolean[N];
final_res = Integer.MAX_VALUE;
}
static void copyToFinal(int[] curr_path) {
if (N >= 0) System.arraycopy(curr_path, 0, final_path, 0, N);
final_path[N] = curr_path[0];
}
static int firstMin(int[][] adj, int i) {
int min = Integer.MAX_VALUE;
for (int k = 0; k < N; k++)
if (adj[i][k] < min && i != k)
min = adj[i][k];
return min;
}
static int secondMin(int[][] adj, int i) {
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int j = 0; j < N; j++) {
if (i == j)
continue;
if (adj[i][j] <= first) {
second = first;
first = adj[i][j];
}
else if (adj[i][j] <= second && adj[i][j] != first)
second = adj[i][j];
}
return second;
}
static void TSPRec(int[][] adj, int curr_bound, int curr_weight, int level, int[] curr_path) {
if (level == N) {
if (adj[curr_path[level - 1]][curr_path[0]] != 0) {
int curr_res = curr_weight + adj[curr_path[level-1]][curr_path[0]];
if (curr_res < final_res) {
copyToFinal(curr_path);
final_res = curr_res;
}
}
return;
}
for (int i = 0; i < N; i++) {
if (adj[curr_path[level-1]][i] != 0 && !visited[i]) {
int temp = curr_bound;
curr_weight += adj[curr_path[level - 1]][i];
if (level==1)
curr_bound -= ((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2);
else
curr_bound -= ((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2);
if (curr_bound + curr_weight < final_res) {
curr_path[level] = i;
visited[i] = true;
TSPRec(adj, curr_bound, curr_weight, level + 1, curr_path);
}
curr_weight -= adj[curr_path[level-1]][i];
curr_bound = temp;
Arrays.fill(visited,false);
for (int j = 0; j <= level - 1; j++)
visited[curr_path[j]] = true;
}
}
}
static void TSP(int[][] adj) {
int[] curr_path = new int[N + 1];
int curr_bound = 0;
Arrays.fill(curr_path, -1);
Arrays.fill(visited, false);
for (int i = 0; i < N; i++)
curr_bound += (firstMin(adj, i) + secondMin(adj, i));
curr_bound = (curr_bound==1) ? curr_bound/2 + 1 : curr_bound/2;
visited[0] = true;
curr_path[0] = 0;
TSPRec(adj, curr_bound, 0, 1, curr_path);
}
}
| [
"[email protected]"
] | |
f446661dda29294ac1ae431f03b7d440359f0ca7 | 60b637aee9095ff0fd7a1affd86c6b6fe8fecf6c | /App/android/MyAR/app/src/main/java/marvyco/myar/GPSManager.java | 89f4a67ce24082169e9598291135c036ef11e2bb | [
"Apache-2.0"
] | permissive | NaTQiM/Street-name-detection | 666a2ab2201f9e53474bf26d913cfb0773336331 | cb8e29f14f41b2dc807641bbc63c0c673e086b91 | refs/heads/main | 2023-04-03T00:27:20.646140 | 2021-04-05T14:56:45 | 2021-04-05T14:56:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,253 | java | package marvyco.myar;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.List;
public class GPSManager implements LocationListener {
private Context context;
private List<onRequestGPSPermission> list_callback;
private int request_code;
public boolean isGPSEnable = false;
private boolean locationAvailable = false;
private Location location;
private LocationManager locationManager;
private OnGetLocation onGetLocation = null;
public GPSManager(Context ctx, int request_code) {
this.context = ctx;
list_callback = new ArrayList<onRequestGPSPermission>();
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
try {
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(" ERROR", " GPS");
}
if (isGPSPermissionGranted())
requestForLocation();
this.request_code = request_code;
}
public boolean isGPSPermissionGranted() {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
public void requestGPSPermission() {
ActivityCompat.requestPermissions(
(Activity) context,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS
},
request_code);
}
@SuppressLint("MissingPermission")
private void requestForLocation() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
protected void onGPSPermissionGranted(boolean result) {
if (result) {
requestForLocation();
InvokeGranted();
} else {
InvokeDenied();
if (onGetLocation != null) {
onGetLocation.Failure();
onGetLocation = null;
}
}
}
public void AddRequestGPSPermissionListener(onRequestGPSPermission callback) {
list_callback.add(callback);
}
private void InvokeGranted() {
for (onRequestGPSPermission callback :
list_callback) {
callback.Granted();
}
}
private void InvokeDenied() {
for (onRequestGPSPermission callback :
list_callback) {
callback.Denied();
}
}
public boolean getStatus() {
return isGPSEnable;
}
public Location getLocation() {
return location;
}
@Override
public void onLocationChanged(Location location) {
locationAvailable = true;
this.location = location;
Log.i("LOCATION GPS>>", this.location.getLatitude() + ", " + this.location.getLongitude());
if (onGetLocation != null) {
onGetLocation.Success(location);
onGetLocation = null;
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
isGPSEnable = true;
}
@Override
public void onProviderDisabled(String provider) {
isGPSEnable = false;
}
@SuppressLint("MissingPermission")
public void GetLocation(OnGetLocation callback) {
if (isGPSEnable) {
Location location = null;
if (isGPSPermissionGranted())
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
callback.Failure();
return;
}
callback.Success(location);
if (isGPSPermissionGranted()) {
Log.e("GPS: ", "isGPSEnable");
if (locationAvailable) {
Log.e("GPS: ", "available");
//callback.Success(location);
}
else {
Log.e("GPS: ", "request");
requestForLocation();
//onGetLocation = callback;
}
} else {
//onGetLocation = callback;
requestGPSPermission();
}
} else {
Log.e("GPS: ", "isGPSDisable");
callback.Failure();
}
}
protected interface OnGetLocation {
void Success(Location location);
void Failure();
}
protected interface onRequestGPSPermission {
void Granted();
void Denied();
}
}
| [
"[email protected]"
] | |
5bbec3ae48d16356cdaf0a7f6ecf6005a6f1bc28 | 290697a05998e282d95e8c7acf2f1ad440b2eafc | /core/src/com/mrwalker/firstgame/Entity/Models/EntityEnvEffect.java | ef4e98d7a53f5ae0bd17c49d34de7d41ef74458a | [] | no_license | szymonjanas/JamesWalkerGame | 15ef28e64595dd02ce114aca50b69f789a48847c | abc85ec2457b67f1c4fd93832b137fbdb56b70ad | refs/heads/master | 2022-08-20T20:28:44.760339 | 2020-05-29T19:59:21 | 2020-05-29T19:59:21 | 262,081,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,883 | java | package com.mrwalker.firstgame.Entity.Models;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.TimeUtils;
public class EntityEnvEffect {
/*
Entity Environmental Effects
*/
private short realSpeed = 0;
private short noise = 0; //representation of noise in circle radius
private float noiseMultiplayer = 0.5f;
private short earshot = 100;
private short defaultEarshotValue = 100;
private long periodMillis = 0;
private long startTime = 0;
private boolean allowChangeNoise(){
if (TimeUtils.timeSinceMillis(startTime) > periodMillis)
return true;
return false;
}
private void setNoise() {
if (allowChangeNoise())
this.noise = (short) (realSpeed * noiseMultiplayer);
}
public void setNoiseFor(short noise, long periodMillis) {
startTime = TimeUtils.millis();
this.periodMillis = periodMillis;
this.noise = noise;
}
public short getNoise() {
return noise;
}
public short getRealSpeed() {
return realSpeed;
}
public void setRealSpeed(Vector2 velocity) {
double temp = Math.sqrt(Math.pow(velocity.x, 2) + Math.pow(velocity.y, 2));
if (temp > 120) temp = 120;
this.realSpeed = (short) temp;
setNoise();
}
public float getNoiseMultiplayer() {
return noiseMultiplayer;
}
public void setNoiseMultiplayer(float noiseMultiplayer) {
this.noiseMultiplayer = noiseMultiplayer;
}
public short getEarshot() {
return earshot;
}
public void setEarshot(short earshot) {
this.earshot = earshot;
}
public void setDefaultEarshot(){
this.earshot = defaultEarshotValue;
}
public void setDefaultEarshotValue(short earshot){
this.defaultEarshotValue = earshot;
}
}
| [
"[email protected]"
] | |
565f8eaff6e2dc336fa0a42b644730d4a6ec2d84 | a35547ea99a947ee22a1749ff902120f2ac02c87 | /minijava/minijava-examples-new/LinearSearch.java | b2332bba526f37de00055198653067fce80f1120 | [] | no_license | johnkalog/MiniJava | 981bd44a6f8a997a99b506a638686c7c6f7d7e27 | 1b0a1f08d24d6b5e4d84b3bd621bb3eaff047718 | refs/heads/master | 2020-05-05T12:17:39.503951 | 2019-10-06T20:17:04 | 2019-10-06T20:17:04 | 180,022,570 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,712 | java | class LinearSearch{
public static void main(String[] a){
System.out.println(new LS().Start(10));
}
}
// This class contains an array of integers and
// methods to initialize, print and search the array
// using Linear Search
class LS {
int[] number ;
int size ;
// Invoke methods to initialize, print and search
// for elements on the array
public int Start(int sz){
int aux01 ;
int aux02 ;
aux01 = this.Init(sz);
aux02 = this.Print();
System.out.println(9999);
System.out.println(this.Search(8));
System.out.println(this.Search(12)) ;
System.out.println(this.Search(17)) ;
System.out.println(this.Search(50)) ;
return 55 ;
}
// Print array of integers
public int Print(){
int j ;
j = 1 ;
while (j < (size)) {
System.out.println(number[j]);
j = j + 1 ;
}
return 0 ;
}
// Search for a specific value (num) using
// linear search
public int Search(int num){
int j ;
boolean ls01 ;
int ifound ;
int aux01 ;
int aux02 ;
int nt ;
j = 1 ;
ls01 = false ;
ifound = 0 ;
//System.out.println(num);
while (j < (size)) {
aux01 = number[j] ;
aux02 = num + 1 ;
if (aux01 < num) nt = 0 ;
else if (!(aux01 < aux02)) nt = 0 ;
else {
ls01 = true ;
ifound = 1 ;
j = size ;
}
j = j + 1 ;
}
return ifound ;
}
// initialize array of integers with some
// some sequence
public int Init(int sz){
int j ;
int k ;
int aux01 ;
int aux02 ;
size = sz ;
number = new int[sz] ;
j = 1 ;
k = size + 1 ;
while (j < (size)) {
aux01 = 2 * j ;
aux02 = k - 3 ;
number[j] = aux01 + aux02 ;
j = j + 1 ;
k = k - 1 ;
}
return 0 ;
}
}
| [
"[email protected]"
] | |
ae9a50575e543a181e70b6d9f532ebd14d281606 | 5eeef357dda16437f988ee271034425788c9f7d1 | /src/main/java/inflearn/step07_DFS_BFS/_01.java | 79a20dc16136b3827844a9b3fc550411158e0f7a | [] | no_license | kimdia200/baekjoon_Algorithm | dad1a315ffca65541017c4f79bc9d19c6e7e7ad7 | 7e4daf549c8612d8ea398040597465a1a722fe4f | refs/heads/master | 2023-04-26T14:43:48.995685 | 2023-04-20T06:02:18 | 2023-04-20T06:02:18 | 194,688,304 | 4 | 0 | null | null | null | null | UHC | Java | false | false | 618 | java | package inflearn.step07_DFS_BFS;
public class _01 {
//재귀를 언제 호출하냐에 따라 결과가 달라짐
public static void main(String[] args) {
System.out.println("dfs1=============================");
new _01().dfs1(10);
System.out.println();
System.out.println("dfs2=============================");
new _01().dfs2(10);
}
private void dfs1(int i) {
if(i==0) return;
System.out.print(i+" ");
dfs1(i-1);
}
private void dfs2(int i) {
if(i==0) return;
dfs2(i-1);
System.out.print(i+" ");
}
}
| [
"[email protected]"
] | |
b25f4d2810ab860f2da2014da3cffc8b51da1cc0 | c1136f943bca02e7259438c82e2e7823dd1d562f | /app/src/main/java/com/project/ahmed/v_tracker/DevicesFragment.java | 436304436fe30e81631a40b8e8231883ed23f879 | [] | no_license | ahmedelmoughazy/V-Tracker | a2f00302e2f601411f18f8e912d57566e9d52b01 | b0cf081288ef414b4e428e2d3844707dde91e9ee | refs/heads/master | 2020-03-22T14:41:27.349551 | 2019-05-11T07:49:08 | 2019-05-11T07:49:08 | 140,197,764 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,109 | java | package com.project.ahmed.v_tracker;
import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
import static com.project.ahmed.v_tracker.ConnectingThread.bluetoothSocket;
import static com.project.ahmed.v_tracker.SearchingDevice.connectingThread;
/**
* Created by Ahmed on 11/17/2017.
*/
public class DevicesFragment extends Fragment implements LocationListener {
private Handler mHandler = new Handler();
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
public TextView statusTextView;
public ImageView statusImageView;
public ImageView sound;
public Button disconnectButton;
double latitude;
double longitude;
private FusedLocationProviderClient mFusedLocationClient;
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(getContext(), "Disconnected", Toast.LENGTH_LONG).show();
//give notification to the user
addNotification();
connectingThread.cancel();
statusTextView.setText("No Devices Are Connected");
statusImageView.setImageResource(R.drawable.disconnected); // change it later
sound.setVisibility(View.GONE);
disconnectButton.setVisibility(View.GONE);
//save last known location
if (ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
return;
}
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
//double to long
long lat = Double.doubleToRawLongBits(latitude);
long lng = Double.doubleToRawLongBits(longitude);
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
prefs.edit().putLong("latitude", lat).apply();
prefs.edit().putLong("longitude", lng).apply();
}
}
});
}
}
};
private View rootView;
private char state = '1';
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_devices, container, false);
//IntentFilter filter = new IntentFilter();
//filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
//getActivity().registerReceiver(broadcastReceiver,filter);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
//handle disconnect button
disconnectButton = rootView.findViewById(R.id.disconnect_button);
disconnectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (statusTextView.getText().equals("No Devices Are Connected")) {
Toast.makeText(getActivity(), "You Have To Be Connected First !", Toast.LENGTH_LONG).show();
} else {
connectingThread.cancel();
statusTextView.setText("No Devices Are Connected");
statusImageView.setImageResource(R.drawable.disconnected);
disconnectButton.setVisibility(View.GONE);
sound.setVisibility(View.GONE);
}
}
});
sound = rootView.findViewById(R.id.sound);
sound.setVisibility(View.GONE);
sound.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!statusTextView.getText().equals("No Devices Are Connected")) {
//ابعت حاجه لو connected
ConnectedThread thread = new ConnectedThread(connectingThread.getBluetoothSocket());
thread.write();
}
}
});
FloatingActionButton mFloatingActionButton = rootView.findViewById(R.id.fab);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), SearchingDevice.class);
startActivityForResult(i, 1);
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String name = data.getStringExtra("name");
//String mac = data.getStringExtra("mac");
//manage connection
BluetoothSocketListener bsl = new BluetoothSocketListener(bluetoothSocket, mHandler);
Thread messageListener = new Thread(bsl);
messageListener.start();
statusTextView = rootView.findViewById(R.id.status_text);
statusTextView.setText("Connected To " + name);
statusImageView = rootView.findViewById(R.id.status_image);
statusImageView.setImageResource(R.drawable.connected); // change it later
sound.setVisibility(View.VISIBLE);
disconnectButton.setVisibility(View.VISIBLE);
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
private void addNotification() {
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.find);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.tracker);
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(getActivity(),HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("trackNotification", "trackNotification");
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),0,intent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Device Disconnected")
.setTicker("Don't Forget Your Device")
.setContentText("Tap To Find")
.setContentIntent(pendingIntent)
.setAutoCancel(true) //to remove after the user clicks it
.setSound(soundUri)
.setLargeIcon(bitmap).setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bmp)
.bigLargeIcon(null));
NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
getActivity().registerReceiver(broadcastReceiver, filter);
}
@Override
public void onPause() {
super.onPause();
//getActivity().unregisterReceiver(broadcastReceiver);
}
@Override
public void onDestroyView() {
super.onDestroyView();
getActivity().unregisterReceiver(broadcastReceiver);
}
private class ConnectedThread extends Thread {
private BluetoothSocket mSocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
mSocket = socket;
try {
tmpIn = mSocket.getInputStream();
} catch (IOException ie) {
ie.printStackTrace();
}
try {
tmpOut = mSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mInputStream = tmpIn;
mOutputStream = tmpOut;
}
public void write() {
byte[] buffer = new byte[1024];
buffer[0]=(byte)state;//prepare data like this
try {
mOutputStream = mSocket.getOutputStream();
mOutputStream.write(buffer);
Log.e("message", buffer.toString()+" sent");
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
}
if (state=='1') {
state = '0';
sound.setImageResource(R.drawable.nosound);
}else if (state=='0') {
state = '1';
sound.setImageResource(R.drawable.sound);
}
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
private class MessagePoster implements Runnable {
private String message;
private Uri soundUri = Uri.parse("android.resource://com.project.ahmed.v_tracker/raw/rr");
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
public MessagePoster(String message) {
this.message = message;
}
public void run() {
RingtoneManager.getRingtone(getContext(), soundUri).play();
//vibrator.vibrate(1000);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message;
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(message));
socket.getInputStream();
//break;
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
}
| [
"[email protected]"
] | |
ff85241d051846503fcfc7c8f2d5952b3f129237 | 75e6cca0fdf75987e8bf59874de309e914096a78 | /src/test/java/testcore/controls/common/RadioControl.java | 4c17032098b8b0ce81559b0659a6d122240fb057 | [] | no_license | santhoshkumarmoolya/Neutron | d6778d49d1830615fc52c314f54a8f73c94c8377 | 997a9d7bcf0b7095f17e387f9dd272ef4f70ae89 | refs/heads/master | 2023-05-10T17:10:38.474155 | 2023-05-02T04:17:40 | 2023-05-02T04:17:40 | 226,841,964 | 0 | 0 | null | 2023-05-02T04:17:41 | 2019-12-09T10:11:59 | Java | UTF-8 | Java | false | false | 344 | java | package testcore.controls.common;
import control.WebControl;
import org.openqa.selenium.WebElement;
import page.IPage;
public class RadioControl extends WebControl {
public RadioControl(String name, IPage page, WebElement element) {
super(name, page, element);
}
@Override
public void click() {
this.getRawWebElement().click();
}
} | [
"[email protected]"
] | |
f11d83a8d965308543d35888f34d21882eb7d5f9 | 1e1b967637da64bfcb6b770b82ba1b0a9d47eba7 | /happy-log/src/main/java/org/happy/log/slf4j/Slf4jLoggerImpl.java | ea624329fd779a082b1945d73b446410fd1e0272 | [] | no_license | happy150923/happy-parent | dd03bfaf11d6f45c1086f4b39dbef51ad6ec3644 | 864d343b0409df5936987a7a819087fb4a4d2c37 | refs/heads/master | 2021-01-19T23:53:18.791692 | 2017-02-09T14:51:32 | 2017-02-09T14:51:32 | 76,442,768 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 693 | java | package org.happy.log.slf4j;
import org.happy.log.Log;
import org.slf4j.Logger;
class Slf4jLoggerImpl implements Log {
private Logger log;
public Slf4jLoggerImpl(Logger logger) {
log = logger;
}
@Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
@Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
}
@Override
public void error(String s, Throwable e) {
log.error(s, e);
}
@Override
public void error(String s) {
log.error(s);
}
@Override
public void debug(String s) {
log.debug(s);
}
@Override
public void trace(String s) {
log.trace(s);
}
@Override
public void warn(String s) {
log.warn(s);
}
}
| [
"[email protected]"
] | |
1ea6c803278088647a792b0aaf1f3eb2ce848949 | a2cdf80a1339dcc8eee5fd4d9fcbf3e9e538673d | /android/app/src/main/java/com/textfieldgesturebug/MainApplication.java | 6e540a2e490cc4e8e270b839d75693f6d5cfeaa3 | [] | no_license | desmondmc/RNTextInputGestureBug | 7b0359c17a72bc2d580e00fc1403c6d366f0354f | 34f7f076d85dc7bc8da8f722f5209909440279be | refs/heads/master | 2023-01-10T10:36:29.081860 | 2020-02-16T19:38:44 | 2020-02-16T19:38:44 | 240,950,442 | 1 | 0 | null | 2023-01-05T07:26:14 | 2020-02-16T19:17:02 | Objective-C | UTF-8 | Java | false | false | 2,286 | java | package com.textfieldgesturebug;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* @param context
*/
private static void initializeFlipper(Context context) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| [
"[email protected]"
] | |
78abbb77bed7b4b81987ca21c134c7450e125b98 | 6b0af00c82ecd16c4251b72331d398c4c7314eba | /commons/trunk/commons-pattern/src/test/java/com/xplus/commons/pattern/interpreter/node/ActionNode.java | 50e4e27e1ef83dd88cde2e55ba3fae293808d3a3 | [
"MIT"
] | permissive | hunny/xplus | 0c918259f9a4c61586cab37081ec793276297b79 | 506b963498bd3196c3d4de95893993dae2688a7d | refs/heads/master | 2021-01-22T23:29:46.425201 | 2018-07-15T04:16:37 | 2018-07-15T04:16:37 | 85,644,862 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 486 | java | package com.xplus.commons.pattern.interpreter.node;
// 动作解释:终结符表达式
public class ActionNode implements Node {
private String action;
public ActionNode(String action) {
this.action = action;
}
// 动作(移动方式)表达式的解释操作
@Override
public String interpret() {
if ("move".equalsIgnoreCase(action)) {
return "移动";
} else if ("run".equalsIgnoreCase(action)) {
return "快速移动";
}
return "无效指令";
}
}
| [
"[email protected]"
] | |
63b50c1e2d002315b5de60a199e3a534ca916fc2 | 29c4261902f7e3dc6f206f16c02a977e84d18326 | /OCSE/airlines-osce-logger-service/airlines-S3/src/main/java/com/cg/airlines/bean/Flights.java | cddbb96ef149fbf74e090549e2b7da81739c6b99 | [] | no_license | loggerservice/OSCE_LOGGER | ed7cb0cab882304f384a5dabff3c77eb418e2003 | 5a14b0e255d53f7f3e93b7ff8fcea3ce77e00e0a | refs/heads/master | 2022-06-26T04:54:42.590194 | 2019-06-17T10:59:15 | 2019-06-17T10:59:15 | 191,538,356 | 0 | 0 | null | 2022-06-21T01:16:59 | 2019-06-12T09:17:14 | Java | UTF-8 | Java | false | false | 2,848 | java | package com.cg.airlines.bean;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@SequenceGenerator(name="seq",sequenceName = "seq", initialValue= 100011, allocationSize=10)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Flights implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name="flightId")
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "seq")
private int flightId;
private String flightName;
private String depCity;
private String arrCity;
private String depDate;
private String arrDate;
private String depTime;
private String arrTime;
private int businessSeats;
private int economySeats;
private int firstclassSeats;
@OneToMany(mappedBy="flights")
private List<Bookings> bookings;
@OneToMany(mappedBy="flight")
private List<Passengers> passengers;
public int getFlightId() {
return flightId;
}
public void setFlightId(int flightId) {
this.flightId = flightId;
}
public String getFlightName() {
return flightName;
}
public void setFlightName(String flightName) {
this.flightName = flightName;
}
public String getDepCity() {
return depCity;
}
public void setDepCity(String depCity) {
this.depCity = depCity;
}
public String getArrCity() {
return arrCity;
}
public void setArrCity(String arrCity) {
this.arrCity = arrCity;
}
public String getDepDate() {
return depDate;
}
public void setDepDate(String depDate) {
this.depDate = depDate;
}
public String getArrDate() {
return arrDate;
}
public void setArrDate(String arrDate) {
this.arrDate = arrDate;
}
public String getDepTime() {
return depTime;
}
public void setDepTime(String depTime) {
this.depTime = depTime;
}
public String getArrTime() {
return arrTime;
}
public void setArrTime(String arrTime) {
this.arrTime = arrTime;
}
public int getBusinessSeats() {
return businessSeats;
}
public void setBusinessSeats(int businessSeats) {
this.businessSeats = businessSeats;
}
public int getEconomySeats() {
return economySeats;
}
public void setEconomySeats(int economySeats) {
this.economySeats = economySeats;
}
public int getFirstclassSeats() {
return firstclassSeats;
}
public void setFirstclassSeats(int firstclassSeats) {
this.firstclassSeats = firstclassSeats;
}
}
| [
"[email protected]"
] | |
bbd846ce33149360e77eb0f4677d9ba2465fbdf7 | 5d614df21b2408da5696785de97f66f15bdf4817 | /src/main/java/eu/mivrenik/particles/io/Dialog.java | cf65c9b5b5d3366c1c3897fab5645eca396dd1c7 | [
"MIT"
] | permissive | gim-/particles-in-box-java | 58e7109dd1ace556185210d5062998c13e4814cb | 4f00b8a32691d2452be53fd816a54567d2d699f2 | refs/heads/master | 2020-04-12T09:00:49.398489 | 2016-10-15T21:29:35 | 2016-10-15T21:29:35 | 65,075,956 | 6 | 1 | null | 2016-10-15T21:29:36 | 2016-08-06T09:48:08 | Java | UTF-8 | Java | false | false | 1,510 | java | package eu.mivrenik.particles.io;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import java.io.PrintWriter;
import java.io.StringWriter;
public final class Dialog {
private Dialog() {
}
public static void createExceptionDialog(final String message, final Exception ex) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Exception Dialog");
alert.setContentText(message);
// Create expandable Exception.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label("The exception stacktrace was:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
// Set expandable Exception into the dialog pane.
alert.getDialogPane().setExpandableContent(expContent);
alert.showAndWait();
}
}
| [
"[email protected]"
] | |
7277889faf9870908c8a1400134d3733a170541d | 2bdfa1041b173ffed185a121b7fdb3c86e3f76e3 | /src/com/lero/web/DormManagerServlet.java | 2ae508855848206dab3df7b9e2e901cb918f3225 | [] | no_license | a1055167474/DormManage | 10b851899c2ee67bd754d93bcbd56842d2386223 | e5809dc83470aac9210780807d9146346451b4ec | refs/heads/master | 2020-06-09T03:12:41.132135 | 2019-06-23T14:50:25 | 2019-06-23T14:50:25 | 193,359,609 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,680 | java | package com.lero.web;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.lero.dao.DormManagerDao;
import com.lero.model.DormManager;
import com.lero.model.PageBean;
import com.lero.util.DbUtil;
import com.lero.util.PropertiesUtil;
import com.lero.util.StringUtil;
public class DormManagerServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
DbUtil dbUtil = new DbUtil();
DormManagerDao dormManagerDao = new DormManagerDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String s_dormManagerText = request.getParameter("s_dormManagerText");
String searchType = request.getParameter("searchType");
String page = request.getParameter("page");
String action = request.getParameter("action");
DormManager dormManager = new DormManager();
if("preSave".equals(action)) {
dormManagerPreSave(request, response);
return;
} else if("save".equals(action)){
dormManagerSave(request, response);
return;
} else if("delete".equals(action)){
dormManagerDelete(request, response);
return;
} else
if("list".equals(action)) {
if(StringUtil.isNotEmpty(s_dormManagerText)) {
if("name".equals(searchType)) {
dormManager.setName(s_dormManagerText);
} else if("userName".equals(searchType)) {
dormManager.setUserName(s_dormManagerText);
}
}
session.removeAttribute("s_dormManagerText");
session.removeAttribute("searchType");
request.setAttribute("s_dormManagerText", s_dormManagerText);
request.setAttribute("searchType", searchType);
} else if("search".equals(action)){
if (StringUtil.isNotEmpty(s_dormManagerText)) {
if ("name".equals(searchType)) {
dormManager.setName(s_dormManagerText);
} else if ("userName".equals(searchType)) {
dormManager.setUserName(s_dormManagerText);
}
session.setAttribute("searchType", searchType);
session.setAttribute("s_dormManagerText", s_dormManagerText);
} else {
session.removeAttribute("s_dormManagerText");
session.removeAttribute("searchType");
}
} else {
if(StringUtil.isNotEmpty(s_dormManagerText)) {
if("name".equals(searchType)) {
dormManager.setName(s_dormManagerText);
} else if("userName".equals(searchType)) {
dormManager.setUserName(s_dormManagerText);
}
session.setAttribute("searchType", searchType);
session.setAttribute("s_dormManagerText", s_dormManagerText);
}
if(StringUtil.isEmpty(s_dormManagerText)) {
Object o1 = session.getAttribute("s_dormManagerText");
Object o2 = session.getAttribute("searchType");
if(o1!=null) {
if("name".equals((String)o2)) {
dormManager.setName((String)o1);
} else if("userName".equals((String)o2)) {
dormManager.setUserName((String)o1);
}
}
}
}
if(StringUtil.isEmpty(page)) {
page="1";
}
Connection con = null;
PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));
request.setAttribute("pageSize", pageBean.getPageSize());
request.setAttribute("page", pageBean.getPage());
try {
con=dbUtil.getCon();
List<DormManager> dormManagerList = dormManagerDao.dormManagerList(con, pageBean, dormManager);
int total=dormManagerDao.dormManagerCount(con, dormManager);
String pageCode = this.genPagation(total, Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));
request.setAttribute("pageCode", pageCode);
request.setAttribute("dormManagerList", dormManagerList);
request.setAttribute("mainPage", "admin/dormManager.jsp");
request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void dormManagerDelete(HttpServletRequest request,
HttpServletResponse response) {
String dormManagerId = request.getParameter("dormManagerId");
Connection con = null;
try {
con = dbUtil.getCon();
dormManagerDao.dormManagerDelete(con, dormManagerId);
request.getRequestDispatcher("dormManager?action=list").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void dormManagerSave(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
String dormManagerId = request.getParameter("dormManagerId");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String tel = request.getParameter("tel");
DormManager dormManager = new DormManager(userName, password, name, sex, tel);
if(StringUtil.isNotEmpty(dormManagerId)) {
dormManager.setDormManagerId(Integer.parseInt(dormManagerId));
}
Connection con = null;
try {
con = dbUtil.getCon();
int saveNum = 0;
if(StringUtil.isNotEmpty(dormManagerId)) {
saveNum = dormManagerDao.dormManagerUpdate(con, dormManager);
} else if(dormManagerDao.haveManagerByUser(con, dormManager.getUserName())){
request.setAttribute("dormManager", dormManager);
request.setAttribute("error", "该用户名已存在");
request.setAttribute("mainPage", "admin/dormManagerSave.jsp");
request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
return;
} else {
saveNum = dormManagerDao.dormManagerAdd(con, dormManager);
}
if(saveNum > 0) {
request.getRequestDispatcher("dormManager?action=list").forward(request, response);
} else {
request.setAttribute("dormManager", dormManager);
request.setAttribute("error", "保存失败");
request.setAttribute("mainPage", "dormManager/dormManagerSave.jsp");
request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void dormManagerPreSave(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
String dormManagerId = request.getParameter("dormManagerId");
if(StringUtil.isNotEmpty(dormManagerId)) {
Connection con = null;
try {
con = dbUtil.getCon();
DormManager dormManager = dormManagerDao.dormManagerShow(con, dormManagerId);
request.setAttribute("dormManager", dormManager);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
request.setAttribute("mainPage", "admin/dormManagerSave.jsp");
request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
}
private String genPagation(int totalNum, int currentPage, int pageSize){
int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
StringBuffer pageCode = new StringBuffer();
pageCode.append("<li><a href='dormManager?page=1'>首页</a></li>");
if(currentPage==1) {
pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
}else {
pageCode.append("<li><a href='dormManager?page="+(currentPage-1)+"'>上一页</a></li>");
}
for(int i=currentPage-2;i<=currentPage+2;i++) {
if(i<1||i>totalPage) {
continue;
}
if(i==currentPage) {
pageCode.append("<li class='active'><a href='#'>"+i+"</a></li>");
} else {
pageCode.append("<li><a href='dormManager?page="+i+"'>"+i+"</a></li>");
}
}
if(currentPage==totalPage) {
pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
} else {
pageCode.append("<li><a href='dormManager?page="+(currentPage+1)+"'>下一页</a></li>");
}
pageCode.append("<li><a href='dormManager?page="+totalPage+"'>尾页</a></li>");
return pageCode.toString();
}
}
| [
"[email protected]"
] | |
a39ef1b3dd64b41422021a95da094426b5867e5d | 4c99452860313b59656d10d56f56d6bcc0e39114 | /springboot-config/src/main/java/com/appcity/app/config/SpringbootConfigApplication.java | 9242e8dc2dbf9f205848ed06f612e902b8b486d4 | [] | no_license | appcityudea/springboot | 4f60ecfdaef68a00a9811c8a41d2888a6bd95a30 | ffa5e16864e050a18776b2845634cf39adc8b0d1 | refs/heads/main | 2023-04-13T15:42:16.115198 | 2021-04-12T14:02:46 | 2021-04-12T14:02:46 | 357,210,889 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 422 | java | package com.appcity.app.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@EnableConfigServer
@SpringBootApplication
public class SpringbootConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootConfigApplication.class, args);
}
}
| [
"David Guerrero@DESKTOP-BG2QFCV"
] | David Guerrero@DESKTOP-BG2QFCV |
7571793f344d3767c86ec597f15a488df6d1da07 | e8a829a71b8509165712c47cb2c503f112acd642 | /src/main/java/selenium/Omniful/WebSiteLoginPage.java | 1ff56d06c272e19ec3adbf509c40304cc3a2267d | [] | no_license | hadeer1993/Omniful | 0e7d7b4a8b062f86c3c1d85ce3be14d219d7718d | a02615db30a3dbf4a3a94658f2391cc04e320dba | refs/heads/main | 2023-05-27T10:11:54.769831 | 2021-06-17T15:01:58 | 2021-06-17T15:01:58 | 305,352,292 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 567 | java | package selenium.Omniful;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class WebSiteLoginPage extends PageBases {
public WebSiteLoginPage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
@FindBy(id="email")
WebElement Email;
@FindBy(id="pass")
WebElement Password;
@FindBy(id="send2")
WebElement Signin;
public void LoginMethod(String email, String pass) {
Email.sendKeys(email);
Password.sendKeys(pass);
Signin.click();
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.