blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
4ac7da9f4317906b074b4a09759df3bbb9b102dd
|
Java
|
weizx208/ForElder
|
/HeartWings/src/com/heart/bean/RegularShare.java
|
UTF-8
| 745
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.heart.bean;
import java.util.ArrayList;
public class RegularShare {
private String oldmanPhone;
private String oldmanName;
private ArrayList<String> picUrls;
private Long date;
public String getOldmanPhone() {
return oldmanPhone;
}
public void setOldmanPhone(String oldmanPhone) {
this.oldmanPhone = oldmanPhone;
}
public String getOldmanName() {
return oldmanName;
}
public void setOldmanName(String oldmanName) {
this.oldmanName = oldmanName;
}
public ArrayList<String> getPicUrls() {
return picUrls;
}
public void setPicUrls(ArrayList<String> picUrls) {
this.picUrls = picUrls;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}
| true
|
ae46ea02156da0c23b0ec5274118d38662503da4
|
Java
|
GuilhermeZenzen/APS-Engine2D
|
/src/com/aps/game/Page.java
|
UTF-8
| 792
| 3.03125
| 3
|
[
"Unlicense"
] |
permissive
|
package com.aps.game;
import java.util.ArrayList;
import com.aps.game.components.UIElement;
public class Page {
private int itemCapacity;
private ArrayList<UIElement> items = new ArrayList<UIElement>();
public Page(int itemCapacity) {
this.itemCapacity = itemCapacity;
}
public void addItem(UIElement item) {
items.add(item);
}
public void removeItem(int index) {
items.remove(index);
}
public UIElement getItem(int index) {
return items.get(index);
}
public ArrayList<UIElement> getItems(){
return items;
}
public int getSize() {
return items.size();
}
public boolean isFull() {
return items.size() >= itemCapacity;
}
public void enable(boolean enable) {
for (UIElement item : items) {
item.getGameObject().setDisabled(!enable);
}
}
}
| true
|
7f88ad25fa050624bd3f2c24e76b4d397da3eda1
|
Java
|
yanniss/pcminer
|
/src/pcminer/CommitteeRole.java
|
UTF-8
| 576
| 2.75
| 3
|
[] |
no_license
|
package pcminer;
public abstract class CommitteeRole {
public CommitteeRole(ConferenceInstance ci){
this.conferenceInstance = ci;
}
public ConferenceInstance getConferenceInstance(){
return conferenceInstance;
}
public String toString(){
return conferenceInstance.toString();
}
public String toJson(int indent){
return Util.repeat(" ", indent) + "{ " + "\"role\" : " + getRoleJson() + ", " + "\"conference\" : " + conferenceInstance.toJson() + " },";
}
public abstract String getRoleJson();
private final ConferenceInstance conferenceInstance;
}
| true
|
42cbe4954c5b07a0a3c0e3dbd8ba00f475be8826
|
Java
|
zmh19941223/microserve_basic
|
/黑马头条/heima-leadnews-crawler/src/test/java/com/heima/crawler/test/ProcessingFlowManagerTest.java
|
UTF-8
| 998
| 2.109375
| 2
|
[] |
no_license
|
package com.heima.crawler.test;
import com.heima.crawler.manager.ProcessingFlowManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProcessingFlowManagerTest {
@Autowired
private ProcessingFlowManager processingFlowManager;
@Test
public void test(){
processingFlowManager.handel();
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testReserse(){
processingFlowManager.reverseHandel();
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true
|
0a5d889d767ef0aa626634717416cb7bfc44f8d0
|
Java
|
binhdev/lab-room-manage-android
|
/app/src/main/java/huedev/org/ui/activity/main/MainActivity.java
|
UTF-8
| 8,523
| 1.8125
| 2
|
[] |
no_license
|
package huedev.org.ui.activity.main;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import huedev.org.R;
import huedev.org.data.repository.UserRepository;
import huedev.org.data.source.local.UserLocalDataSource;
import huedev.org.data.source.remote.UserRemoteDataSource;
import huedev.org.ui.activity.add.AddActivity;
import huedev.org.ui.activity.auth.login.LoginActivity;
import huedev.org.ui.activity.auth.logout.LogoutContact;
import huedev.org.ui.activity.auth.logout.LogoutPresenter;
import huedev.org.ui.activity.user.UserActivity;
import huedev.org.ui.activity.user.UserPresenter;
import huedev.org.ui.base.activity.BaseActivity;
import huedev.org.ui.fragments.MessengerFragment.MessengerFragment;
import huedev.org.ui.fragments.calendar.CalendarFragment;
import huedev.org.ui.fragments.feed.FeedFragment;
import huedev.org.ui.fragments.room.RoomFragment;
import huedev.org.ui.activity.user.update.UEditInfoActivity;
import huedev.org.utils.AppConstants;
import huedev.org.utils.AppPrefs;
import huedev.org.utils.helpers.StringHelper;
import huedev.org.utils.navigator.Navigator;
import huedev.org.utils.rx.SchedulerProvider;
public class MainActivity extends BaseActivity implements View.OnClickListener,
NavigationView.OnNavigationItemSelectedListener,
BottomNavigationView.OnNavigationItemSelectedListener,
LogoutContact.View
{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
BottomNavigationView mBtNavigation;
Toolbar mToolbar;
Navigator navigator;
LinearLayout linearLayout;
TextView tvNameUSer, tvPosition;
LogoutPresenter mLogoutPresenter;
UserPresenter mUserPresenter;
String name = "", role = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationView = findViewById(R.id.nav_view);
mDrawerLayout = findViewById(R.id.dl_main);
mToolbar = findViewById(R.id.toolbar_main);
linearLayout = findViewById(R.id.linear_container);
mBtNavigation = findViewById(R.id.navigation_main);
View headerLayout = mNavigationView.getHeaderView(0);
tvNameUSer = headerLayout.findViewById(R.id.tv_nameUser);
tvPosition = headerLayout.findViewById(R.id.tv_position);
navigator = new Navigator(this);
init();
mToolbar.setTitle("");
setupToolbar(mToolbar, R.drawable.btn_menu);
setNameUser();
setVisibleItemNavigation();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.linear_container ,new RoomFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
mToolbar.setNavigationOnClickListener(this);
mNavigationView.setNavigationItemSelectedListener(this);
mBtNavigation.setOnNavigationItemSelectedListener(this);
}
public void setNameUser(){
if (!AppPrefs.getInstance(this).getNameUser().isEmpty() && AppPrefs.getInstance(this).getRole() > -1){
name = AppPrefs.getInstance(this).getNameUser();
role = StringHelper.formatStringRole(AppPrefs.getInstance(this).getRole(), this);
}else {
name = StringHelper.getStringResourceByName("admin", this);
role = StringHelper.formatStringRole(2, this);
}
Log.e("RoleError",role);
tvNameUSer.setText(name);
tvPosition.setText(role);
}
private void setVisibleItemNavigation() {
if (!AppPrefs.getInstance(this).getApiToken().equals(AppConstants.API_TOKEN_DEFAULT)){
mNavigationView.getMenu().getItem(0).setVisible(true);
mNavigationView.getMenu().getItem(1).setVisible(true);
mNavigationView.getMenu().getItem(2).setVisible(true);
mNavigationView.getMenu().getItem(3).setVisible(false);
}else {
mNavigationView.getMenu().getItem(0).setVisible(false);
mNavigationView.getMenu().getItem(1).setVisible(false);
mNavigationView.getMenu().getItem(2).setVisible(false);
mNavigationView.getMenu().getItem(3).setVisible(true);
}
}
private void init() {
mLogoutPresenter = new LogoutPresenter(this);
UserRepository userRepository = UserRepository.getInstance(
UserLocalDataSource.getInstance(),
UserRemoteDataSource.getInstance(this));
mUserPresenter = new UserPresenter(this, userRepository, SchedulerProvider.getInstance());
mLogoutPresenter.setView(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_hometop, menu);
if (AppPrefs.getInstance(this).getRole() == 2){
menu.getItem(0).setVisible(true);
}else {
menu.getItem(0).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_add_room:
navigator.startActivity(AddActivity.class);
break;
case R.id.menu_notify:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_bt_home:
replaceFragment(new RoomFragment());
return true;
case R.id.nav_bt_calendar:
replaceFragment(new CalendarFragment());
return true;
case R.id.nav_bt_feeds:
replaceFragment(new FeedFragment());
return true;
case R.id.nav_bt_messenger:
replaceFragment(new MessengerFragment());
return true;
case R.id.nav_start_login:
menuItem.setChecked(false);
mDrawerLayout.closeDrawers();
navigator.startActivity(LoginActivity.class);
finish();
return true;
case R.id.nav_start_logout:
mLogoutPresenter.logout();
return true;
case R.id.nav_start_editInformation:
menuItem.setChecked(false);
Log.d("password", AppPrefs.getInstance(this).getPasswordUser());
navigator.startActivity(UEditInfoActivity.class);
mDrawerLayout.closeDrawers();
return true;
case R.id.nav_start_user_manager:
menuItem.setChecked(false);
navigator.startActivity(UserActivity.class);
mDrawerLayout.closeDrawers();
return true;
}
return false;
}
@Override
public void onClick(View view) {
mDrawerLayout.openDrawer(GravityCompat.START);
setNameUser();
}
private void replaceFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.linear_container ,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
@Override
public void overridePendingTransition(int enterAnim, int exitAnim) {
super.overridePendingTransition(R.anim.slide_left_in,
R.anim.slide_left_out);
}
@Override
public void showLoadingIndicator(Dialog dialog) {
}
@Override
public void hideLoadingIndicator(Dialog dialog) {
}
@Override
public void showLoginError(Throwable throwable) {
}
@Override
public void logout() {
mDrawerLayout.closeDrawers();
navigator.startActivity(MainActivity.class);
}
}
| true
|
65d59c23674bbebab2413d6cab79d8e27d10ab2b
|
Java
|
girlxiaoxiaoli/Hongmi
|
/HongMi/src/zz/guojin/hongmi/activity/QiangCodeActivity.java
|
UTF-8
| 6,063
| 1.710938
| 2
|
[] |
no_license
|
package zz.guojin.hongmi.activity;
import java.io.Flushable;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yolanda.nohttp.Logger;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zz.guojin.hongmi.bean.RuquestBean;
import zz.guojin.hongmi.utils.AppManager;
import zz.guojin.hongmi.utils.JumpUtil;
import zz.guojin.hongmi.utils.MUrlUtil;
import zz.guojin.hongmi.utils.NetUtils;
import zz.guojin.hongmi.utils.ReLoginUtil;
import zz.guojin.hongmi.utils.ToastUtils;
import zz.guojin.hongmi.utils.UiUtils;
import zz.guojin.hongmi.R;
import android.R.integer;
import android.R.raw;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
*抢单币管理
* @author Administrator
*
*/
public class QiangCodeActivity extends BaseActivity {
@Bind(R.id.img_back)
ImageView goback;
@Bind(R.id.title_main)
TextView title;
@Bind(R.id.et_code_account_qiang)
EditText account;
@Bind(R.id.et_user_qiang)
EditText user;
@Bind(R.id.et_code_second_pwd_qiang)
EditText sdpwd;
@Bind(R.id.tv_count_qiang)
TextView tv_count;
@Bind(R.id.btn_notes_qiang)
Button btn_notes;
@Bind(R.id.btn_ok_qiang)
Button btn_ok;
private Context ctx;
private String trim1;// 输入的激活码数量
private String jhmCount;// 原始可用激活码数量字符串
private int jhmCountInt;
protected static final int FLSH_UI = 100;
private Request<String> request;
// gridview激活码管理界面
// 确认转账
@OnClick(R.id.btn_ok_qiang)
public void btnConfirm(Button btn) {
trim1 = account.getText().toString().trim();
String trim2 = user.getText().toString().trim();
String trim3 = sdpwd.getText().toString().trim();
if (TextUtils.isEmpty(trim1) && TextUtils.isEmpty(trim2)
&& TextUtils.isEmpty(trim3)) {
ToastUtils.showTextToast(ctx, "内容不能为空");
}
Map<String, Object> params = new HashMap<String, Object>();
Request<String> request = NoHttp.createStringRequest(MUrlUtil.BASE_URL
+ MUrlUtil.EXCHNAGE_QIANG_CODE, RequestMethod.GET);
params.put("sh1", trim1);
params.put("user1", trim2);
params.put("ejmm1", trim3);
ToRequestUrl(request, TAG, MUrlUtil.BASE_URL
+ MUrlUtil.EXCHNAGE_QIANG_CODE,params, -1, -1, 333);
}
private Handler hanlder = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case FLSH_UI:
int trim1Int = Integer.parseInt(trim1);
jhmCountInt = Integer.valueOf(jhmCount);
int count = jhmCountInt - trim1Int;
tv_count.setText(Integer.toString(count));
jhmCountInt = count;
account.setText("");
user.setText("");
sdpwd.setText("");
break;
default:
break;
}
};
};
// 转账记录
@OnClick(R.id.btn_notes_qiang)
public void getNotes(Button btn) {
JumpUtil.JumpActivity(ctx, QiangNotesActivity.class);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点)
View v = getCurrentFocus();
if (UiUtils.isShouldHideInput(v, ev)) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
UiUtils.hideSoftInput(v.getWindowToken(), im);
}
}
return super.dispatchTouchEvent(ev);
}
// 点击左上角按钮返回上一个页面
@OnClick(R.id.img_back)
public void goBack() {
finish();
}
@Override
public int getLayoutResId() {
// TODO Auto-generated method stub
return R.layout.activity_code_qiang;
}
@Override
public void init() {
// TODO Auto-generated method stub
AppManager.getInstance().addActivity(this);
ctx = this;
}
@Override
public void initView() {
// TODO Auto-generated method stub
title.setText("抢单币转让");
}
@Override
public void initListener() {
// TODO Auto-generated method stub
}
@Override
public void initData() {
// TODO Auto-generated method stub
ToRequestUrl(request, TAG, MUrlUtil.BASE_URL + MUrlUtil.QIANG_CODE,
null, -1, -1, 33);
}
@Override
public void toStartProgressDialog() {
// TODO Auto-generated method stub
toStartProgressDialg(true);
}
@Override
public void doWhatForRequest(int what, String info) {
// TODO Auto-generated method stub
if (what == 33) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(info);
if (!jsonObject.isNull("data")) {
jhmCount = jsonObject.getJSONObject("data").getString("ue_pdb");
tv_count.setText(jhmCount);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Logger.e(TAG + e.getMessage());
}
}
if (what == 333) {
Gson gson = new Gson();
RuquestBean aee = gson.fromJson(info, RuquestBean.class);
if ("1".equals(aee.getError())) {
ToastUtils.showTextToast(ctx, aee.getMsg());
hanlder.sendEmptyMessage(FLSH_UI);
} else if ("0".equals(aee.getError())) {
ToastUtils.showTextToast(ctx, aee.getMsg());
return;
} else if ("3".equals(aee.getError())) {
ToastUtils.showTextToast(ctx, aee.getMsg());
ReLoginUtil.LoginAgain(ctx, LoginActivity.class);
return;
}
}
}
}
| true
|
a1618d42feb4f63db5a4f9993ac2990747c8a607
|
Java
|
jinhogate/G2I
|
/G2I/target/generated-sources/annotations/com/ipsofts/gestionIntervention/entities/Planification_.java
|
UTF-8
| 1,110
| 1.5625
| 2
|
[] |
no_license
|
package com.ipsofts.gestionIntervention.entities;
import com.ipsofts.gestionIntervention.entities.Demande;
import com.ipsofts.gestionIntervention.entities.Technicien;
import java.util.Date;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2017-10-24T04:17:17")
@StaticMetamodel(Planification.class)
public class Planification_ extends BaseEntity_ {
public static volatile SingularAttribute<Planification, Integer> heureFinEstimation;
public static volatile SingularAttribute<Planification, Boolean> planificationSup;
public static volatile SingularAttribute<Planification, Integer> heureDebutEstimation;
public static volatile SingularAttribute<Planification, Demande> idDemande;
public static volatile SingularAttribute<Planification, Integer> idPlanification;
public static volatile SingularAttribute<Planification, Date> datePlanification;
public static volatile SingularAttribute<Planification, Technicien> idUtilisateurT;
}
| true
|
8fa5f988a5ab590e53dccc94b2510b753b215c25
|
Java
|
akdhankh12/GNS
|
/src/edu/umass/cs/gnsserver/gnsapp/clientCommandProcessor/commandSupport/CommandHandler.java
|
UTF-8
| 13,042
| 1.679688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
* Copyright (c) 2015 University of Massachusetts
*
* 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.
*
* Initial developer(s): Abhigyan Sharma, Westy
*
*/
package edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport;
import edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commands.CommandModule;
import edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commands.BasicCommand;
import edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commands.data.AbstractUpdate;
import edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.ClientRequestHandlerInterface;
import static edu.umass.cs.gnscommon.GNSCommandProtocol.*;
import edu.umass.cs.gnsserver.gnsapp.AppReconfigurableNodeOptions;
import edu.umass.cs.gnsserver.gnsapp.GNSApp;
import edu.umass.cs.gnsserver.gnsapp.packet.CommandPacket;
import edu.umass.cs.gnscommon.CommandValueReturnPacket;
import edu.umass.cs.gnscommon.GNSResponseCode;
import edu.umass.cs.gnscommon.utils.CanonicalJSON;
import edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.ClientCommandProcessorConfig;
import edu.umass.cs.gnsserver.main.GNSConfig;
import edu.umass.cs.reconfiguration.ReconfigurationConfig.RC;
import edu.umass.cs.utils.Config;
import edu.umass.cs.utils.DelayProfiler;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.util.logging.Level;
/**
* Handles sending and receiving of commands.
*
* @author westy, arun
*/
public class CommandHandler {
// handles command processing
private static final CommandModule commandModule = new CommandModule();
private static long commandCount = 0;
/**
* Handles command packets coming in from the client.
*
* @param incomingJSON
* @param handler
* @throws JSONException
* @throws UnknownHostException
*/
private static void handlePacketCommandRequest(CommandPacket packet, boolean doNotReplyToClient,
GNSApp app)
throws JSONException, UnknownHostException {
final Long receiptTime = System.currentTimeMillis(); // instrumentation
ClientRequestHandlerInterface handler = app.getRequestHandler();
ClientCommandProcessorConfig.getLogger().log(Level.FINE,
"Command packet received: {0}", new Object[]{packet.getSummary()});
final JSONObject jsonFormattedCommand = packet.getCommand();
// Adds a field to the command to allow us to process the authentication of the signature
addMessageWithoutSignatureToCommand(jsonFormattedCommand, handler);
final BasicCommand command = commandModule.lookupCommand(jsonFormattedCommand);
runCommand(jsonFormattedCommand, command, handler, packet, doNotReplyToClient, app, receiptTime);
}
private static final long LONG_DELAY_THRESHOLD = 1;
private static void runCommand(JSONObject jsonFormattedCommand, BasicCommand command,
ClientRequestHandlerInterface handler, CommandPacket packet, boolean doNotReplyToClient, GNSApp app, long receiptTime) {
try {
final Long executeCommandStart = System.currentTimeMillis(); // instrumentation
// Other than this line, one below and some catches all of this method is instrumentation.
CommandResponse returnValue = executeCommand(command, jsonFormattedCommand, handler);
// instrumentation
DelayProfiler.updateDelay("executeCommand", executeCommandStart);
if (System.currentTimeMillis() - executeCommandStart > LONG_DELAY_THRESHOLD) {
DelayProfiler.updateDelay(packet.getRequestType() + "."
+ command.getCommandType().toString(), executeCommandStart);
}
if (System.currentTimeMillis() - executeCommandStart > LONG_DELAY_THRESHOLD) {
ClientCommandProcessorConfig.getLogger().log(Level.FINE,
"Command {0} took {1}ms of execution delay (delay logging threshold={2}ms)",
new Object[]{
command.getSummary(),
(System.currentTimeMillis() - executeCommandStart),
LONG_DELAY_THRESHOLD});
}
// the last arguments here in the call below are instrumentation that the client can use to determine LNS load
CommandValueReturnPacket returnPacket = new CommandValueReturnPacket(packet.getClientRequestId(),
packet.getLNSRequestId(),
packet.getServiceName(), returnValue,
// FIXME: for info purposes add something to record stuff this back in
0, 0,
//handler.getReceivedRequests(), handler.getRequestsPerSecond(),
System.currentTimeMillis() - receiptTime);
try {
assert(returnPacket.getErrorCode()!=null);
ClientCommandProcessorConfig.getLogger().log(Level.FINE,
"Handling command reply: {0}",
new Object[]{returnPacket});
// Possibly send the return value back to the client
handleCommandReturnValuePacketForApp(returnPacket, doNotReplyToClient, app);
} catch (IOException e) {
ClientCommandProcessorConfig.getLogger().log(Level.SEVERE,
"Problem replying to command: {0}", e);
}
} catch (JSONException e) {
ClientCommandProcessorConfig.getLogger().log(Level.SEVERE,
"Problem executing command: {0}", e);
e.printStackTrace();
}
// reply to client is true, this means this is the active replica
// that recvd the request from the gnsClient. So, let's check for sending trigger
// to Context service here.
if (AppReconfigurableNodeOptions.enableContextService) {
if (!doNotReplyToClient) {
if (command.getClass().getSuperclass() == AbstractUpdate.class) {
GNSConfig.getLogger().fine("Sending trigger to CS jsonFormattedCommand "
+ jsonFormattedCommand + " command " + command);
app.getContextServiceGNSClient().sendTiggerOnGnsCommand(jsonFormattedCommand, command, false);
}
}
}
//DelayProfiler.updateDelay("handlePacketCommandRequest", receiptTime);
}
private static class WorkerTask implements Runnable {
private final JSONObject jsonFormattedCommand;
private final BasicCommand command;
private final ClientRequestHandlerInterface handler;
private final CommandPacket packet;
private final GNSApp app;
private final long receiptTime;
private final boolean doNotReplyToClient;
public WorkerTask(JSONObject jsonFormattedCommand, BasicCommand command, ClientRequestHandlerInterface handler, CommandPacket packet, boolean doNotReplyToClient, GNSApp app, long receiptTime) {
this.jsonFormattedCommand = jsonFormattedCommand;
this.command = command;
this.handler = handler;
this.packet = packet;
this.app = app;
this.receiptTime = receiptTime;
this.doNotReplyToClient = doNotReplyToClient;
}
@Override
public void run() {
runCommand(jsonFormattedCommand, command, handler, packet, doNotReplyToClient, app, receiptTime);
}
}
// This little dance is because we need to remove the signature to get the message that was signed
// alternatively we could have the client do it but that just means a longer message
// OR we could put the signature outside the command in the packet,
// but some packets don't need a signature
private static void addMessageWithoutSignatureToCommand(JSONObject command, ClientRequestHandlerInterface handler) throws JSONException {
if (command.has(SIGNATURE)) {
String signature = command.getString(SIGNATURE);
command.remove(SIGNATURE);
String commandSansSignature = CanonicalJSON.getCanonicalForm(command);
//String commandSansSignature = JSONUtils.getCanonicalJSONString(command);
ClientCommandProcessorConfig.getLogger().log(Level.FINE,
"########CANONICAL JSON: {0}",
new Object[]{commandSansSignature});
command.put(SIGNATURE, signature);
command.put(SIGNATUREFULLMESSAGE, commandSansSignature);
}
}
/**
* Executes the given command with the parameters supplied in the JSONObject.
*
* @param command
* @param json
* @param handler
* @return a command response
*/
public static CommandResponse executeCommand(BasicCommand command, JSONObject json, ClientRequestHandlerInterface handler) {
try {
if (command != null) {
ClientCommandProcessorConfig.getLogger().log(Level.FINE,
"Executing command: {0} in packet {1}",
new Object[]{command, json});
return command.execute(json, handler);
} else {
return new CommandResponse(GNSResponseCode.OPERATION_NOT_SUPPORTED, BAD_RESPONSE + " " + OPERATION_NOT_SUPPORTED
+ " - Don't understand " + json.toString());
}
} catch (JSONException e) {
//e.printStackTrace();
return new CommandResponse(GNSResponseCode.JSON_PARSE_ERROR, BAD_RESPONSE + " " + JSON_PARSE_ERROR + " " + e
+ " while executing command.");
} catch (NoSuchAlgorithmException | InvalidKeySpecException | ParseException |
SignatureException | InvalidKeyException | UnsupportedEncodingException e) {
return new CommandResponse(GNSResponseCode.QUERY_PROCESSING_ERROR, BAD_RESPONSE + " " + QUERY_PROCESSING_ERROR + " " + e);
}
}
/**
* Called when a command packet is received by the app.
*
* @param packet
* @param doNotReplyToClient
* @param app
* @throws JSONException
* @throws IOException
*/
public static void handleCommandPacketForApp(CommandPacket packet, boolean doNotReplyToClient, GNSApp app)
throws JSONException, IOException {
// Squirrel away the host and port so we know where to send the command return value
// A little unnecessary hair for debugging... also peek inside the command.
// JSONObject command;
// String guid = null;
// CommandType commandType = packet.getCommandType();
// if ((command = packet.getCommand()) != null) {
// guid = command.optString(GUID, command.optString(NAME, null));
// }
//GNSConfig.getLogger().info("FROM: " + packet.getSenderAddress());
// app.outStandingQueries.put(packet.getClientRequestId(),
// new CommandRequestInfo(packet.getSenderAddress(), packet.getSenderPort(),
// commandType, guid, packet.getMyListeningAddress()));
handlePacketCommandRequest(packet, doNotReplyToClient, app);
}
private static long lastStatsTime = 0;
/**
* Called when a command return value packet is received by the app.
*
* @param returnPacket
* @param doNotReplyToClient
*
* @param app
* @throws JSONException
* @throws IOException
*/
public static void handleCommandReturnValuePacketForApp(CommandValueReturnPacket returnPacket,
boolean doNotReplyToClient, GNSApp app) throws JSONException, IOException {
// long id = returnPacket.getClientRequestId();
// CommandRequestInfo sentInfo;
// arun: changed get to remove as otherwise it seems to be never removed
// if ((sentInfo = app.outStandingQueries.remove//get
// (id)) != null) {
// ClientCommandProcessorConfig.getLogger()
// .log(Level.FINE,
// "{0}:{1} => {2} -> {3}",
// new Object[]{
// sentInfo.getCommandType().toString(),
// sentInfo.getGuid(),
// returnPacket.getSummary(),
// sentInfo.getHost() + "/"
// + sentInfo.getPort()});
if (!doNotReplyToClient) {
app.sendToClient(returnPacket, returnPacket.toJSONObject());
}
// shows us stats every 100 commands, but not more than once every 5 seconds
if (commandCount++ % 100 == 0 && Config.getGlobalBoolean(RC.ENABLE_INSTRUMENTATION)) {
if (System.currentTimeMillis() - lastStatsTime > 5000) {
ClientCommandProcessorConfig.getLogger().log(Level.INFO, "{0}",
new Object[]{DelayProfiler.getStats()});
lastStatsTime = System.currentTimeMillis();
}
}
// } else {
// ClientCommandProcessorConfig.getLogger().severe("Command packet info not found for "
// + id + ": " + returnPacket.getSummary());
// }
}
}
| true
|
6138d42810a61f2e911c2c382c10dfa39947223f
|
Java
|
junges521/src_awe
|
/src/main/java/com/bytedance/ies/x2c/a/q.java
|
UTF-8
| 5,798
| 1.5625
| 2
|
[] |
no_license
|
package com.bytedance.ies.x2c.a;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.a;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bytedance.ies.dmt.ui.widget.DmtTextView;
import com.bytedance.ies.x2c.c;
import com.ss.android.ugc.aweme.C0906R;
import com.ss.android.ugc.aweme.views.AutoRTLImageView;
public final class q implements c {
public final View a(Context context, ViewGroup viewGroup, boolean z) throws Exception {
Resources resources = context.getResources();
RelativeLayout relativeLayout = new RelativeLayout(context);
ViewGroup.MarginLayoutParams a2 = a.a(viewGroup, -1, -1);
relativeLayout.setBackgroundColor(resources.getColor(C0906R.color.a39));
if (viewGroup != null) {
relativeLayout.setLayoutParams(a2);
if (z) {
viewGroup.addView(relativeLayout);
}
}
ImageView imageView = new ImageView(context);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-2, -2);
imageView.setId(C0906R.id.aq8);
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams)) {
layoutParams.addRule(15, -1);
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams)) {
layoutParams.leftMargin = (int) TypedValue.applyDimension(1, 12.0f, resources.getDisplayMetrics());
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams) && Build.VERSION.SDK_INT >= 17) {
layoutParams.setMarginStart((int) TypedValue.applyDimension(1, 12.0f, resources.getDisplayMetrics()));
}
imageView.setImageResource(2130839303);
imageView.setLayoutParams(layoutParams);
if (imageView.getParent() == null) {
relativeLayout.addView(imageView);
}
DmtTextView dmtTextView = new DmtTextView(context);
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(-1, -2);
dmtTextView.setTextSize(1, 12.0f);
dmtTextView.setLineSpacing((float) ((int) TypedValue.applyDimension(1, 2.0f, resources.getDisplayMetrics())), 1.0f);
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.addRule(15, -1);
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.leftMargin = (int) TypedValue.applyDimension(1, 8.0f, resources.getDisplayMetrics());
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams2) && Build.VERSION.SDK_INT >= 17) {
layoutParams2.setMarginStart((int) TypedValue.applyDimension(1, 8.0f, resources.getDisplayMetrics()));
}
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.addRule(17, C0906R.id.aq8);
}
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.addRule(1, C0906R.id.aq8);
}
dmtTextView.setIncludeFontPadding(false);
dmtTextView.setText(C0906R.string.als);
dmtTextView.setTextColor(resources.getColorStateList(C0906R.color.ak6));
dmtTextView.setId(C0906R.id.cpd);
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.addRule(0, C0906R.id.a_a);
}
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.addRule(16, C0906R.id.a_a);
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams2)) {
layoutParams2.rightMargin = (int) TypedValue.applyDimension(1, 20.0f, resources.getDisplayMetrics());
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams2) && Build.VERSION.SDK_INT >= 17) {
layoutParams2.setMarginEnd((int) TypedValue.applyDimension(1, 20.0f, resources.getDisplayMetrics()));
}
dmtTextView.setMaxLines(1);
dmtTextView.setEllipsize(TextUtils.TruncateAt.END);
dmtTextView.setLayoutParams(layoutParams2);
if (dmtTextView.getParent() == null) {
relativeLayout.addView(dmtTextView);
}
AutoRTLImageView autoRTLImageView = new AutoRTLImageView(context);
RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(-2, -2);
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams3)) {
layoutParams3.addRule(21, -1);
}
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams3)) {
layoutParams3.addRule(11, -1);
}
if (RelativeLayout.LayoutParams.class.isInstance(layoutParams3)) {
layoutParams3.addRule(15, -1);
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams3) && Build.VERSION.SDK_INT >= 17) {
layoutParams3.setMarginEnd((int) TypedValue.applyDimension(1, 12.0f, resources.getDisplayMetrics()));
}
if (ViewGroup.MarginLayoutParams.class.isInstance(layoutParams3)) {
layoutParams3.rightMargin = (int) TypedValue.applyDimension(1, 12.0f, resources.getDisplayMetrics());
}
autoRTLImageView.setScaleType(ImageView.ScaleType.CENTER);
autoRTLImageView.setImageResource(2130839304);
autoRTLImageView.setId(C0906R.id.a_a);
autoRTLImageView.setLayoutParams(layoutParams3);
if (autoRTLImageView.getParent() == null) {
relativeLayout.addView(autoRTLImageView);
}
a.a(dmtTextView);
a.a(autoRTLImageView);
return relativeLayout;
}
}
| true
|
2924a9cb578170ae73278901576ceb3c712ac353
|
Java
|
HULordP/Sporttracker
|
/app/src/main/java/com/example/olahbence/sporttracker/Friends/MyFriends/DeleteFriends.java
|
UTF-8
| 905
| 1.992188
| 2
|
[] |
no_license
|
package com.example.olahbence.sporttracker.Friends.MyFriends;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.example.olahbence.sporttracker.R;
public class DeleteFriends extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_friends);
TextView tw = findViewById(R.id.del_friends);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String email = extras.getString("Email");
tw.append("\n" + email + "\nfrom your friends?");
}
}
public void Delete(View view) {
setResult(1);
finish();
}
public void Cancel(View view) {
setResult(0);
finish();
}
}
| true
|
00c6f572e52791062284f43a9fef7afd36fe65ba
|
Java
|
acomanzo/311OOP
|
/game/Renderable.java
|
UTF-8
| 248
| 2.546875
| 3
|
[] |
no_license
|
package rpgmain;
/**
* Represents an object whose graphics must be updated or redrawn whenever the game updates.
* @Author Tony Comanzo
* Version 1.0
*/
public interface Renderable {
/**
* Redraws this object.
*/
void render();
}
| true
|
586e8bcbc0068f224b7c38c8f77e431087200a92
|
Java
|
diegodeodati/personal-general-diego-deodati
|
/blazeds_server/Branch/reportweb/src/serviseatl/disabledvlts/SPDisabledVlts.java
|
UTF-8
| 1,307
| 2.203125
| 2
|
[] |
no_license
|
package serviseatl.disabledvlts;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import serviseatl.connection.ConnectionMarka;
import serviseatl.connection.DAOException;
public class SPDisabledVlts implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4268890024794954894L;
public List<DisabledVlts> getSPDisabledVlts(byte LocationId, int CodCasino) throws DAOException {
List<DisabledVlts> list = new ArrayList<DisabledVlts>();
Connection c = null;
CallableStatement s = null;
try {
c = ConnectionMarka.getConnection();
s = c.prepareCall("{ call Web.QLDisabledVLTs(?,?) }");
s.setByte("LocationId", LocationId);
s.setInt("CodCasino", CodCasino);
ResultSet rs = s.executeQuery();
while (rs.next()) {
list.add(new DisabledVlts(
rs.getInt("CodCasino"),
rs.getString("Ccasino"),
rs.getString("CodMaquina"),
rs.getString("FechaStr")
));
}
} catch (SQLException e) {
e.printStackTrace();
throw new DAOException(e);
} finally {
ConnectionMarka.close(c);
}
return list;
}
}
| true
|
9cf57b51f9deea77416d5ae4271bfba72cb90a3c
|
Java
|
luiz158/laboratory
|
/escola-2.3.1/src/main/java/br/gov/demoiselle/escola/security/Autorizador.java
|
UTF-8
| 737
| 2.3125
| 2
|
[] |
no_license
|
package br.gov.demoiselle.escola.security;
import java.util.Set;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import br.gov.demoiselle.escola.bean.PapelUsuario;
import br.gov.frameworkdemoiselle.security.Authorizer;
public class Autorizador implements Authorizer {
private static final long serialVersionUID = 1L;
@Inject
private Credencial credencial;
@Override
public boolean hasRole(String role) {
Set<PapelUsuario> papeis = credencial.getUsuario().getPapeis();
for(PapelUsuario papel : papeis){
if(papel.getPapel().equals(role)){
return true;
}
}
return false;
}
@Override
public boolean hasPermission(String resource, String operation) {
return false;
}
}
| true
|
ca2f49098756f470dc0450e0d5e2a393d2638141
|
Java
|
zorrowang/LintCode
|
/386.java
|
UTF-8
| 795
| 3.1875
| 3
|
[] |
no_license
|
public class Solution {
/**
* @param s: A string
* @param k: An integer
* @return: An integer
*/
public int lengthOfLongestSubstringKDistinct(String s, int k) {
// write your code here
if(s==null || s.isEmpty() || k<=0) return 0;
int start=0, end=0;
int[] cnt = new int[256];
int ret = 0, cur = 0;
while(end < s.length()) {
int n = s.charAt(end);
if (cnt[n] == 0)
cur++;
cnt[n]++;
if (cur <= k) ret = Math.max(ret, end-start+1);
while (cur > k && start < end) {
int m = s.charAt(start++);
cnt[m]--;
if (cnt[m]==0) cur--;
}
end++;
}
return ret;
}
}
| true
|
9fcc3f09cdeb44d099567842c49014927589f9d9
|
Java
|
guo1573/demo-dubbo-provider
|
/src/main/java/com/demo/provider/ProductServiceImpl.java
|
UTF-8
| 1,752
| 2.40625
| 2
|
[] |
no_license
|
package com.demo.provider;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import com.alibaba.dubbo.rpc.RpcContext;
import com.demo.entity.Product;
import com.demo.inter.ProductService;
public class ProductServiceImpl implements ProductService {
@Override
public String sayHello(final String str) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" request::"+str);
return str;
}
private AtomicInteger count = new AtomicInteger(0);;
@Override
public String sayHello(String str, Integer waitTime) {
System.out.println(count.addAndGet(1) +":" + str);
try {
if (waitTime != 0) {
Thread.sleep(waitTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return str;
}
@Override
public Product getProduct(final Product pro) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(pro.getProId());
return pro;
}
@Override
public String getProviderName(final String str) {
return RpcContext.getContext().getLocalAddressString();
}
@Override
public Date getProviderCurrentDate(String str){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
return new Date();
}
public List<String> mergeResult() {
List<String> menus = new ArrayList<String>();
menus.add("group-1.1");
menus.add("group-1.2");
return menus;
}
}
| true
|
93083bb0151b78610b776da75555f0ee93308b2b
|
Java
|
augusteiner/droidchess
|
/android.chess.dominio/src/android/chess/dominio/Convite.java
|
UTF-8
| 1,191
| 2.453125
| 2
|
[] |
no_license
|
package android.chess.dominio;
import android.chess.dominio.interfaces.IConvite;
import android.chess.dominio.interfaces.IUsuario;
/**
* @author augusteiner
*/
public class Convite implements IConvite {
/**
*
*/
private IUsuario convidado;
/**
*
*/
private IUsuario convidando;
/**
* @param convidando
* @param convidado
*/
public Convite(IUsuario convidando, IUsuario convidado) {
this.convidando = convidando;
this.convidado = convidado;
}
/*
* (non-Javadoc)
*
* @see android.chess.dominio.interfaces.IConvite#getConvidado()
*/
@Override
public IUsuario getConvidado() {
return convidado;
}
/*
* (non-Javadoc)
*
* @see android.chess.dominio.interfaces.IConvite#getConvidando()
*/
@Override
public IUsuario getConvidando() {
return convidando;
}
/**
* @param convidado
*/
public void setConvidado(IUsuario convidado) {
this.convidado = convidado;
}
/**
* @param convidando
*/
public void setConvidando(IUsuario convidando) {
this.convidando = convidando;
}
}
| true
|
e22e950b43aebd82a5bcf16340fe2c416345a1b7
|
Java
|
codesoftware/SAFWSNB
|
/SAFWS/src/java/co/com/codesoftware/persistence/entites/RespuestaPedidoEntity.java
|
UTF-8
| 1,193
| 1.984375
| 2
|
[] |
no_license
|
/*
* 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 co.com.codesoftware.persistence.entites;
import co.com.codesoftware.persistence.entites.tables.Cliente;
import co.com.codesoftware.persistence.entity.administracion.RespuestaEntity;
import java.io.Serializable;
import java.util.List;
/**
*
* @author root
*/
public class RespuestaPedidoEntity implements Serializable {
private RespuestaEntity respuesta;
private List<ProductoGenEntity> listaProductos;
private Cliente cliente;
public RespuestaEntity getRespuesta() {
return respuesta;
}
public void setRespuesta(RespuestaEntity respuesta) {
this.respuesta = respuesta;
}
public List<ProductoGenEntity> getListaProductos() {
return listaProductos;
}
public void setListaProductos(List<ProductoGenEntity> listaProductos) {
this.listaProductos = listaProductos;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
}
| true
|
de72d325b8ced174f88c1c223e46c12a3783bdc8
|
Java
|
JasenkaJaganjac/maraton
|
/src/maraton/NajboljiMaratonci.java
|
UTF-8
| 962
| 3.21875
| 3
|
[] |
no_license
|
package maraton;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.BufferedWriter;
import java.nio.file.Paths;
import java.util.Scanner;
public class NajboljiMaratonci {
public static void main(String[] args) throws IOException {
File file = new File("maraton.txt");
int n = 25;
String[] ime = new String[n];
int[] vrijeme = new int[n];
Scanner fs = new Scanner(file);
int i = 0;
while (fs.hasNext()) {
ime[i] = fs.next();
vrijeme[i] = fs.nextInt();
i++;
}
Path path = Paths.get("najboljiMaratonci.txt");
BufferedWriter bw = Files.newBufferedWriter(path);
bw.write("Najbolji ucesnici, sa vremenom manjim od 300 min su: ");
bw.newLine();
for (int j = 0; j < vrijeme.length; j++) {
if (vrijeme[j] <= 300) {
bw.write(ime[j] + ": " + vrijeme[j]);
bw.newLine();
}
bw.flush();
}
System.out.println("Fajl kreiran.");
fs.close();
}
}
| true
|
29dead744ccda487d23e685fb99a7d5691ffd9c0
|
Java
|
runbird/runbird-io-nio
|
/src/main/java/com/scy/io/BufferedByteDemo.java
|
UTF-8
| 1,392
| 3.484375
| 3
|
[] |
no_license
|
package com.scy.io;
import java.io.*;
/**
* 类名: BufferedByteDemo <br>
* 描述:BufferedOutputStream 内部缓存大小为8kb,write使用sychn修饰。每次写入都缓存数组byte中,当数组存满
* 写入文件并flush<br>
* 创建日期: 2019/3/6 <br>
*
* @author suocaiyuan
* @version V1.0
*/
public class BufferedByteDemo {
public static void main(String[] args) {
// write();
read();
}
/**
* BufferedOutputStream
*/
private static void write() {
try {
OutputStream outputStream = new FileOutputStream("c:\\scy\\test.txt");
BufferedOutputStream out = new BufferedOutputStream(outputStream);
String info = "需要系统认真的学习,才能够进行提升";
out.write(info.getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void read() {
File file = new File("c:\\scy\\test.txt");
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(file))) {
int len = -1;
byte[] bytes = new byte[1024];
while ((len = input.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
1c89712816a9a7b0b88d844c0ba46a71e26a3fbc
|
Java
|
shrikantjaiswal123/TEST
|
/src/com/serenova/SerenovaMain.java
|
UTF-8
| 1,414
| 2.625
| 3
|
[] |
no_license
|
/**
Main class to manage the whole execution of automation script
@author Shrikant Jaiswal
*
* **/
package com.serenova;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import com.serenova.script.SerenovaScript;
import com.serenova.utils.Mailer;
import com.serenova.utils.ProcessStatus;
import com.serenova.utils.Utils;
public class SerenovaMain {
public static void main(String[] args) {
try {
ProcessStatus.fileWrite();
Scanner testControlScr = Utils.getScanner("Testcases.csv");
if (ProcessStatus.isProcessIsAlive()) {
System.out.println("killing existing Browser stack process ");
ProcessStatus.destroyProcess();
Thread.sleep(10000);
}
// Starting reading test cases from file and execute it one by one
while (testControlScr.hasNext()) {
String[] nextTest = testControlScr.nextLine().split(",");
if (nextTest[2].toLowerCase().startsWith("y")) {
if (nextTest[0].equalsIgnoreCase("G2-Contact-csm")) {
SerenovaScript.executeG2Script(nextTest[0], nextTest[1], nextTest[3]);
} else {
SerenovaScript.executeScript(nextTest[0], nextTest[1], nextTest[3]);
}
Thread.sleep(5000);
}
}
// sendemail
System.out.println("MAIL SENDING START");
Mailer.send();
// terminate browserstack.exe
ProcessStatus.destroyProcess();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
3260e3796c91cb726f1a7004deb45c07e2b00398
|
Java
|
PavelOzhog/mySecondProject
|
/src/Trenirovka2/Calcul.java
|
UTF-8
| 891
| 2.75
| 3
|
[] |
no_license
|
package Trenirovka2;
public class Calcul {
// char[] chars = ("" + i).toCharArray();
public static int [] calc (int [] massiv, char chislo){
int kol = 0;
for (int i = 0; i < massiv.length; i ++){
char[] chars = ("" + massiv[i]).toCharArray();
for (int j = 0; j < chars.length; j ++){
if (chars [j] == chislo){
kol = kol + 1;
}
}
}
int [] result = new int [kol];
int index = 0;
for (int i = 0; i < massiv.length; i ++){
char[] chars = ("" + massiv[i]).toCharArray();
for (int j = 0; j < chars.length; j ++){
if (chars [j] == chislo){
result [index] = massiv[i];
index++;
}
}
}
return result ;
}
}
| true
|
09eb0ffd57bd84b8cab3ef2d79bb4006e54dc563
|
Java
|
xrqing/now-server
|
/server-admin-api/src/main/java/com/admin/security/component/DynamicSecurityService.java
|
UTF-8
| 379
| 1.820313
| 2
|
[] |
no_license
|
package com.admin.security.component;
import org.springframework.security.access.ConfigAttribute;
import java.util.Map;
/**
* @Description: 动态权限相关业务类
* @auther: xrq
* @date: 2020/9/10 21:06
*/
public interface DynamicSecurityService {
/**
* 加载资源ANT通配符和资源对应MAP
*/
Map<String, ConfigAttribute> loadDataSource();
}
| true
|
fc9db2ece322c0bb8ef5cddbafad9da7a2260ad6
|
Java
|
alengorospe/INTROSE-Yellow-Team
|
/Chopsticks and Spoon Iteration 2/src/java/Bean/IngredientRestockLogBean.java
|
UTF-8
| 1,877
| 2.21875
| 2
|
[] |
no_license
|
/*
* 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 Bean;
/**
*
* @author Keiko Nagano
*/
public class IngredientRestockLogBean {
private int i_restock_id;
private int i_restock_userid;
private int i_restock_ingredient;
private double restock_weight;
private double restock_cost;
private String restock_datetime;
private String restock_source;
public int getI_restock_id() {
return i_restock_id;
}
public int getI_restock_ingredient() {
return i_restock_ingredient;
}
public int getI_restock_userid() {
return i_restock_userid;
}
public double getRestock_cost() {
return restock_cost;
}
public String getRestock_datetime() {
return restock_datetime;
}
public String getRestock_source() {
return restock_source;
}
public double getRestock_weight() {
return restock_weight;
}
public void setI_restock_id(int i_restock_id) {
this.i_restock_id = i_restock_id;
}
public void setI_restock_ingredient(int i_restock_ingredient) {
this.i_restock_ingredient = i_restock_ingredient;
}
public void setI_restock_userid(int i_restock_userid) {
this.i_restock_userid = i_restock_userid;
}
public void setRestock_cost(double restock_cost) {
this.restock_cost = restock_cost;
}
public void setRestock_datetime(String restock_datetime) {
this.restock_datetime = restock_datetime;
}
public void setRestock_source(String restock_source) {
this.restock_source = restock_source;
}
public void setRestock_weight(double restock_weight) {
this.restock_weight = restock_weight;
}
}
| true
|
71926a2bdd7e52d6d1dc40f3b2282d06d29bda31
|
Java
|
msafari18/Stackoverflow
|
/src/Userz.java
|
UTF-8
| 478
| 2.0625
| 2
|
[] |
no_license
|
import java.io.Serializable;
import java.util.ArrayList;
public class Userz implements Serializable{
String name;
String username;
String email;
String pass;
boolean isLogin;
public ArrayList<String> interest ;
public Userz(String name, String username, String email, String pass,ArrayList i) {
// TODO Auto-generated constructor stub
this.name = name;
this.username = username;
this.email = email;
this.pass = pass;
this.interest = i ;
}
}
| true
|
76fcc1434f6b5171071c72912f6b343ccfc39b4a
|
Java
|
Phantoms007/zhihuAPK
|
/src/main/java/com/zhihu/android/base/mvvm/recyclerView/SwipeViewHolder.java
|
UTF-8
| 1,951
| 1.765625
| 2
|
[] |
no_license
|
package com.zhihu.android.base.mvvm.recyclerView;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;
import com.zhihu.android.base.mvvm.AbstractC17304b;
import java8.util.C32474u;
import java8.util.Optional;
import java8.util.p2234b.AbstractC32235e;
/* renamed from: com.zhihu.android.base.mvvm.recyclerView.p */
/* compiled from: SwipeViewHolder */
public class SwipeViewHolder extends RecyclerView.ViewHolder {
/* renamed from: a */
private BaseSwipeWrapChildViewModel f60966a;
/* renamed from: b */
private final ViewDataBinding f60967b;
public SwipeViewHolder(ViewDataBinding viewDataBinding) {
super(viewDataBinding.mo5929g());
this.f60967b = viewDataBinding;
}
/* renamed from: a */
public void mo84360a(BaseSwipeWrapChildViewModel eVar) {
this.f60966a = eVar;
this.f60967b.mo5921a(eVar.provideBindingName(), (Object) eVar);
this.f60967b.mo5923b();
}
/* renamed from: a */
public void mo84359a(BaseRecyclerParentViewModel cVar) {
if (!C32474u.m150251c(cVar)) {
cVar.findAllVM(AbstractC17304b.class).mo131135c(new AbstractC32235e() {
/* class com.zhihu.android.base.mvvm.recyclerView.$$Lambda$p$s9eyfIuqLwa0r947aLScbErFDhw */
@Override // java8.util.p2234b.AbstractC32235e
public final void accept(Object obj) {
SwipeViewHolder.lambda$s9eyfIuqLwa0r947aLScbErFDhw(SwipeViewHolder.this, (AbstractC17304b) obj);
}
});
}
}
/* access modifiers changed from: private */
/* renamed from: a */
public /* synthetic */ void m86974a(AbstractC17304b bVar) {
this.f60967b.mo5921a(bVar.provideBindingName(), (Object) bVar);
}
/* renamed from: a */
public Optional<BaseSwipeWrapChildViewModel> mo84358a() {
return Optional.m150255b(this.f60966a);
}
}
| true
|
cdb10a21efb33dd430d2f2df55191c4f07020a47
|
Java
|
searleser97/HeartPreventSpring
|
/HPWS/src/main/java/com/san/guiText/GuiTextRestController.java
|
UTF-8
| 1,572
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package com.san.guiText;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@RestController
@RequestMapping("/guiText")
public class GuiTextRestController {
@Autowired
private GuiTextService guiTextService;
/*
**Return a listing of all the resources
*/
@RequestMapping(method = RequestMethod.GET)
public List<GuiText> getAll() {
return guiTextService.getAll();
}
/*
**Return one resource
*/
@RequestMapping("/{id}")
public GuiText getOne(@PathVariable Integer id) {
return guiTextService.getOne(id);
}
/*
**Store a newly created resource in storage.
*/
@RequestMapping(method = RequestMethod.POST)
public void add(@RequestBody GuiText guiText) {
guiTextService.add(guiText);
}
/*
**Update the specified resource in storage.
*/
@RequestMapping(method = RequestMethod.PUT)
public void update(@RequestBody GuiText guiText) {
guiTextService.update(guiText);
}
/*
**Remove the specified resource from storage.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable Integer id) {
guiTextService.delete(id);
}
}
| true
|
e0379bf23dddc84024cb0eb5c3a0714920e4b8e7
|
Java
|
Mareckyb/ProjektBaza
|
/src/main/java/com/example/projektbaza/enums/Priority.java
|
UTF-8
| 83
| 1.710938
| 2
|
[] |
no_license
|
package com.example.projektbaza.enums;
public enum Priority {
HIGH, MEDIUM, LOW
}
| true
|
f59b888552fce667f167867606e2827e00b40af5
|
Java
|
kyungsikjeung/TaskAgile
|
/src/main/java/com/taskagile/domain/common/model/user/UserRegisteredEventHandler.java
|
UTF-8
| 645
| 2.140625
| 2
|
[] |
no_license
|
package com.taskagile.domain.common.model.user;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import com.taskagile.domain.model.user.events.UserRegisteredEvent;
@Component
public class UserRegisteredEventHandler {
private final static Logger log = LoggerFactory.getLogger(UserRegisteredEventHandler.class);
@EventListener(UserRegisteredEventHandler.class)
public void handleEvent(UserRegisteredEvent event) {
log.debug("Handling `{}` registration evnet", event.getUser().getEmailAddress());
}
}
| true
|
2d8d8b06fae8ee4b5584f922637085f4893d9d25
|
Java
|
Gtrakas1/JAC444
|
/jaclab2-tester/testHangman.java
|
UTF-8
| 566
| 2.0625
| 2
|
[] |
no_license
|
/********************************************
* Workshop # 2
* Course:<JAC44>- 5
* Last Name:<Trakas>
* First Name<George>
* ID: <108459173>
* Section: <SCC>
* This assignment represents my own work in accordance with
* Seneca Academic Policy
* George Trakas
*
***********************************************/
package tester;
import java.io.IOException;
import com.trakas.classes.HangMan;
public class testHangman {
public static void main(String args[]) throws IOException {
HangMan hang=new HangMan();
hang.displayHangMan();
}
}
| true
|
403bf256ba13a6412f27144e555e4968f019fde9
|
Java
|
MrDok/fileReader
|
/src/com/company/tools/FileReader.java
|
UTF-8
| 2,321
| 3.21875
| 3
|
[] |
no_license
|
package com.company.tools;
import java.io.*;
/**
* @author dokuchaev on 30.01.2017.
*/
public class FileReader{
private File file;
private final int BUFFER_SIZE = 80000;
private InputStream inputStream;
public static final String TEXT_EXTENSION = ".txt";
public FileReader(File file) throws FileNotFoundException{
this.file = file;
inputStream = new BufferedInputStream(new FileInputStream(file));
}
public FileReader(String fileName) throws FileNotFoundException{
this.file = new File(fileName);
inputStream = new BufferedInputStream(new FileInputStream(file));
}
public File getFile(){
return file;
}
public void setFile(File file){
this.file = file;
}
/**
* Reading bytes
* @return
* @throws IOException
*/
public byte[] read() throws IOException{
byte[] buffer = new byte[BUFFER_SIZE];
if (inputStream.available() > 0){
inputStream.read(buffer);
return buffer;
}
return null;
}
/**
* Check if file contains not read bytes
* @return
*/
public boolean available(){
try{
if (inputStream.available() > 0)
return true;
}catch (IOException e){
return false;
}
return false;
}
public void close() throws IOException{
inputStream.close();
}
/**
*Gets all files with .txt extension
*
* @param fileName
* @param extension
* @return
*/
public static File[] getFiles(String fileName, final String extension) {
File directory = new File(fileName);
if (directory.isDirectory()) {
File[] result = directory.listFiles((dir, name) -> name.endsWith(extension));
if (result != null && result.length > 0) {
return result;
} else {
return new File[0];
}
}else{
if (directory.isFile()) {
String path = directory.getPath();
if (path.endsWith(extension)) return new File[]{new File(fileName)};
}
}
return new File[0];
}
}
| true
|
e506f2d16e662c1ec42be634a0a375d1c34cd73c
|
Java
|
martenhernebring/oop
|
/se/hernebring/shapes/triangle/TriangleShapeDemo.java
|
UTF-8
| 246
| 2.65625
| 3
|
[] |
no_license
|
package se.hernebring.shapes.triangle;
import se.hernebring.shapes.Shape;
public class TriangleShapeDemo {
public static void main(String[] args) {
Shape t = new TriangleShape(10, 20);
System.out.println(t);
}
}
| true
|
1e20200e88c5304ddba837d70f9c5a65f2f0d553
|
Java
|
wing1993/MyRepository
|
/Taoism/src/com/df/dao/impl/BaseDAOSupport.java
|
UTF-8
| 1,595
| 2.171875
| 2
|
[] |
no_license
|
package com.df.dao.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.df.dao.pojo.User;
public class BaseDAOSupport {
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/*@SuppressWarnings("unchecked")
public List<Object[]> queryByPage(String sql, int from, int length)throws Exception {
List<Object[]> objectList = new ArrayList<Object[]>();
objectList = sessionFactory.getCurrentSession().createQuery(sql)
.setFirstResult(from).setMaxResults(length).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
return objectList;
}*/
public int queryResultsCount(String sql) throws Exception {
// 查询总记录数
Long resultCount = (Long) sessionFactory.getCurrentSession()
.createQuery(sql).uniqueResult();
return resultCount.intValue();
}
@SuppressWarnings("unchecked")
public List<Object[]> queryByPage_1(String sql, int from, int length)throws Exception {
List<Object[]> objectList = new ArrayList<Object[]>();
objectList = sessionFactory.getCurrentSession().createQuery(sql)
.setFirstResult(from).setMaxResults(length).list();
return objectList;
}
}
| true
|
ae58bab730cfa61bcec7cd82b3997966a6c89a1c
|
Java
|
pjsqwerty/DimpleBlog
|
/src/main/java/com/dimple/project/system/mapper/CarouselMapper.java
|
UTF-8
| 1,150
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.dimple.project.system.mapper;
import com.dimple.project.system.domain.Carousel;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @className: ConfigMapper
* @description: 参数配置 数据层
* @author: Dimple
* @date: 11/02/19
*/
public interface CarouselMapper {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
Carousel selectCarouselById(Long id);
/**
* 通过实体作为筛选条件查询
*
* @param carousel 实例对象
* @return 对象列表
*/
List<Carousel> selectCarouselList(Carousel carousel);
/**
* 新增数据
*
* @param carousel 实例对象
* @return 影响行数
*/
int insertCarousel(Carousel carousel);
/**
* 修改数据
*
* @param carousel 实例对象
* @return 影响行数
*/
int updateCarousel(Carousel carousel);
/**
* 通过主键删除数据
*
* @param id 主键
* @return 影响行数
*/
int deleteCarouselById(@Param("id") Long id, @Param("username") String username);
}
| true
|
ce1aee0c19be35add7e7a5114627fd9c943e53d1
|
Java
|
Stalf/droid-wars-prototype
|
/core/src/com/droidwars/game/screens/MainMenuScreen.java
|
UTF-8
| 3,264
| 2.359375
| 2
|
[] |
no_license
|
package com.droidwars.game.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.droidwars.game.DroidWarsGame;
import com.droidwars.game.Resources;
import com.droidwars.game.background.BackgroundFXRenderer;
public class MainMenuScreen extends DefaultScreen implements InputProcessor {
final BackgroundFXRenderer backgroundFX;
Sprite titleSprite;
Sprite startButtonSprite;
SpriteBatch titleBatch;
BoundingBox collisionStart = new BoundingBox();
public MainMenuScreen(Game game) {
super(game);
Gdx.input.setInputProcessor(this);
backgroundFX = new BackgroundFXRenderer();
titleBatch = new SpriteBatch();
titleBatch.getProjectionMatrix().setToOrtho2D(0, 0, 800, 480);
titleSprite = Resources.getInstance().title;
titleSprite.setPosition(144, 320);
startButtonSprite = Resources.getInstance().start;
startButtonSprite.setPosition(336, 200);
float[] vertices = startButtonSprite.getVertices();
collisionStart.set(new Vector3(vertices[0], vertices[1], -10), new Vector3(vertices[10], vertices[11], 10));
}
@Override
public void show() {
}
@Override
public void render(float delta) {
// Очищаем экран и устанавливаем цвет фона черным
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
backgroundFX.render();
titleBatch.begin();
titleSprite.draw(titleBatch);
startButtonSprite.draw(titleBatch);
titleBatch.end();
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
titleBatch.getProjectionMatrix().set(cam.combined);
}
@Override
public void hide() {
}
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
Ray collisionRay = cam.getPickRay(x, y);
if (Intersector.intersectRayBoundsFast(collisionRay, collisionStart)) {
game.setScreen(new GameScreen(game));
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
}
| true
|
f29e08575e81cacfce9a1a9955e9d9220ee51c5b
|
Java
|
jcalisto/SD3
|
/A36-Komparator-SD_P2/mediator-ws/src/main/java/org/komparator/mediator/ws/MediatorPortImpl.java
|
UTF-8
| 14,473
| 2.171875
| 2
|
[] |
no_license
|
package org.komparator.mediator.ws;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jws.WebService;
import org.komparator.mediator.domain.Cart;
import org.komparator.mediator.domain.CartItem;
import org.komparator.mediator.domain.Item;
import org.komparator.mediator.domain.ItemId;
import org.komparator.mediator.domain.Mediator;
import org.komparator.supplier.ws.BadProductId_Exception;
import org.komparator.supplier.ws.BadQuantity_Exception;
import org.komparator.supplier.ws.BadText_Exception;
import org.komparator.supplier.ws.InsufficientQuantity_Exception;
import org.komparator.supplier.ws.ProductView;
import org.komparator.supplier.ws.cli.SupplierClient;
import org.komparator.supplier.ws.cli.SupplierClientException;
import pt.ulisboa.tecnico.sdis.ws.cli.CreditCardClient;
import pt.ulisboa.tecnico.sdis.ws.cli.CreditCardClientException;
import pt.ulisboa.tecnico.sdis.ws.uddi.UDDINamingException;
import pt.ulisboa.tecnico.sdis.ws.uddi.UDDIRecord;
@WebService(
endpointInterface = "org.komparator.mediator.ws.MediatorPortType",
wsdlLocation = "mediator.wsdl",
name = "Mediator",
portName = "MediatorPort",
targetNamespace = "http://ws.mediator.komparator.org/",
serviceName = "MediatorService"
)
public class MediatorPortImpl implements MediatorPortType{
// end point manager
private MediatorEndpointManager endpointManager;
//private ArrayList<SupplierClient> listSuppliers=new ArrayList<SupplierClient>();
private List<SupplierClient> listSuppliers=new ArrayList<SupplierClient>();
private AtomicInteger purchaseIdCounter = new AtomicInteger(0);
private static final String A36_SUPPLIER="A36_Supplier";
public MediatorPortImpl(MediatorEndpointManager endpointManager) {
this.endpointManager = endpointManager;
}
// Main operations -------------------------------------------------------
//Clear system state
@Override
public synchronized void clear() {
ping("Hello"); //Actualizar lista de suppliers
for(SupplierClient supplierClient : listSuppliers)
supplierClient.clear();
Mediator mediator = Mediator.getInstance();
mediator.reset();
listSuppliers.clear();
}
public List<UDDIRecord> findSuppliers(){
List<UDDIRecord> supplierClientsRecords =new ArrayList<UDDIRecord>();
try {
supplierClientsRecords=(List<UDDIRecord>)endpointManager.getUddiNaming().listRecords(A36_SUPPLIER+"%");
} catch (UDDINamingException e) {
System.out.println("Error in find Suppliers");
}
return supplierClientsRecords;
}
//Find productId in every supplier
@Override
public synchronized List<ItemView> getItems(String productId) throws InvalidItemId_Exception {
if(productId == null || productId.trim().equals(""))
InvalidItemId_ExceptionThrow("Error itemId\n");
ping("Hello"); //Atualizar lista de suppliers
List<ItemView> itemList=new ArrayList<ItemView>();
try{
for(SupplierClient cl:listSuppliers){
ProductView productView= cl.getProduct(productId); //Check if suppliers has the product
if(productView!=null){
ItemView item=newProdToItemView(productView, cl.getName());
itemList.add(item);
}
}
}catch(BadProductId_Exception e){
InvalidItemId_ExceptionThrow("Error itemId\n");
}
itemList.sort(new Comparator<ItemView>(){ //Sort List by price
public int compare(ItemView i1, ItemView i2){
return i1.getPrice() - i2.getPrice();
}
});
return itemList;
}
//List carts in mediator
@Override
public synchronized List<CartView> listCarts() {
Mediator mediator=Mediator.getInstance();
ArrayList<CartView> cartViewList=new ArrayList<>();
for(Cart cart:mediator.getArrayCarts()){
CartView cartView=newCartView(cart);
cartViewList.add(cartView);
}
return cartViewList;
}
@Override
public synchronized List<ItemView> searchItems(String descText) throws InvalidText_Exception{
ping("Hello"); //Actualizar lista de suppliers
List<ItemView> items = new ArrayList<ItemView>();
for(SupplierClient supplierClient : listSuppliers){ //Percorrer Lista de Suppliers
try {
List<ProductView> products = supplierClient.searchProducts(descText); //Produtos de um Supplier com a descricao
for(ProductView p : products){
items.add(newProdToItemView(p, supplierClient.getName())); //Transformar produto em itemview
}
}
catch(BadText_Exception e){
throwInvalidTextException("Invalid Description on search items");
}
}
items.sort(new Comparator<ItemView>(){ //Sort List by ID and Price
@Override
public int compare(ItemView item1, ItemView item2){
int value = item1.getItemId().getProductId().compareTo(item2.getItemId().getProductId());
if(value == 0)
return item1.getPrice() - item2.getPrice();
return value;
}
});
return items;
}
//buy products in the cart
@Override
public synchronized ShoppingResultView buyCart(String cartId, String creditCardNr)
throws EmptyCart_Exception, InvalidCartId_Exception, InvalidCreditCard_Exception{
try{
if (cartId==null||cartId.trim().equals("")){
InvalidCartId_ExceptionThrow("Invalid cartId");
}
if (creditCardNr==null||creditCardNr.trim().equals("")){
CreditCardClientExceptionThrow("Invalid creditCardNr");
}
Mediator mediator=Mediator.getInstance();
int totalPrice=0;
List<CartItemView> purchasedItems=new ArrayList<CartItemView>();
List<CartItemView> droppedItems=new ArrayList<CartItemView>();
CreditCardClient client =new CreditCardClient("http://ws.sd.rnl.tecnico.ulisboa.pt:8080/cc"); //comunicate with bank
Result result=Result.COMPLETE;
int purchaseId = purchaseIdCounter.incrementAndGet(); //create ID
if(!client.validateNumber(creditCardNr)){ //if credit card not valid throw exception
CreditCardClientExceptionThrow("Error with creditCart");
}
Cart cart=mediator.getCart(cartId);
if (cart==null){
InvalidCartId_ExceptionThrow("Invalid cartId"); //if cart null throws exception
}
if (cart.getCartItems().size()==0){
EmptyCart_ExceptionThrow("Empty Cart"); //if cart is empty then throws exception
}
for(CartItem cartItem: cart.getCartItems()){
String supplierID=cartItem.getSupplier();
CartItemView view=newCartItemView(cartItem);
try{
SupplierClient supplierClient = new SupplierClient(this.endpointManager.getUddiNaming().getUDDIUrl(),supplierID);
if(supplierClient.getWsURL() == null)
InvalidCartId_ExceptionThrow("CartId com SupplierID errado");
supplierClient.buyProduct(cartItem.getproductId(), cartItem.getQuantity()); //try buy products
purchasedItems.add(view);//add to purchased if all is ok
totalPrice+=cartItem.getPrice()*cartItem.getQuantity();//add to total ammount
}catch (BadProductId_Exception e){
droppedItems.add(view);
result=Result.PARTIAL;
} catch (BadQuantity_Exception e) {
droppedItems.add(view);
result=Result.PARTIAL;
} catch (InsufficientQuantity_Exception e) {
droppedItems.add(view);
result=Result.PARTIAL;
}catch(SupplierClientException e){
droppedItems.add(view);
result=Result.PARTIAL;
}
}
if (purchasedItems.size()==0){
result=Result.EMPTY;
}
ShoppingResultView shop=newShowResultView(Integer.toString(purchaseId),result,purchasedItems,droppedItems,totalPrice);// create ShoppingResultView with all the necessary arguments
mediator = Mediator.getInstance();
mediator.addShoppingResult(shop);//add to list in mediator
return shop;
}catch( CreditCardClientException e){
CreditCardClientExceptionThrow("Error with your credit card");
}
return null;
}
//add items to the cart
@Override
public synchronized void addToCart(String cartId, ItemIdView itemId, int itemQty) throws InvalidCartId_Exception,
InvalidItemId_Exception, InvalidQuantity_Exception, NotEnoughItems_Exception {
ping("Hello");
try{
if(cartId==null || cartId.trim().equals("")){
invalidCarIdExceptionThrow("Invalid car arguments");
}
if(itemId==null || itemId.getProductId()==null || itemId.getSupplierId()==null){
InvalidItemId_ExceptionThrow("Invalid car arguments");
}
if(itemQty<=0){
InvalidQuantity_ExceptionThrow("Invalid quantity");
}
Mediator mediator=Mediator.getInstance();
String supplierID=itemId.getSupplierId(); //get supplier
SupplierClient supplierClient = new SupplierClient(this.endpointManager.getUddiNaming().getUDDIUrl(),supplierID);
if(supplierClient.getWsURL()==null)
InvalidItemId_ExceptionThrow("Invalid SupplierId");
ProductView p= supplierClient.getProduct(itemId.getProductId());
if(p==null)
InvalidItemId_ExceptionThrow("Invalid ProductId");
if (itemQty>p.getQuantity()){// verify if quantity is acceptable
NotEnoughItems_ExceptionThrow("Quantity is higher than quantity available");
}
String desc=supplierClient.getProduct(itemId.getProductId()).getDesc();// get description
int price=supplierClient.getProduct(itemId.getProductId()).getPrice(); //get price
ItemId itemId2=new ItemId(itemId.getProductId(),itemId.getSupplierId());
Item item=new Item(itemId2,desc,price);//create item
Cart cart=mediator.getCart(cartId);//check if cart exists
if (cart==null){
cart=new Cart(cartId);//create cart if it does not exists
CartItem cartItem=new CartItem(item, itemQty);
cart.addItem(cartItem);
mediator.addCart(cart);//add cart to list in mediator if does not exists
}
else{
CartItem cartItem=cart.getItem(item);
if(cart.getItem(item)==null){ //create item if it does not exists
cartItem=new CartItem(item, itemQty);
cart.addItem(cartItem);
}
else{
cartItem.addQuantity(itemQty);
}
}
}catch(SupplierClientException e){
InvalidItemId_ExceptionThrow("Error in Supplier");
} catch (BadProductId_Exception e) {
InvalidItemId_ExceptionThrow("Bad Product Id");
}
}
@Override
public synchronized String ping(String message) {
String result = "";
for(UDDIRecord r: findSuppliers()){
SupplierClient supplierClient;
try {
supplierClient = new SupplierClient(r.getUrl());
supplierClient.setUddiUrl(endpointManager.getUddiNaming().getUDDIUrl());
supplierClient.setName(r.getOrgName());
listSuppliers.add(supplierClient); //Found supplier, add it to list of suppliers
result += "\n" + supplierClient.ping(message);
} catch (SupplierClientException e) {
System.out.println("Error in suplierClient");
}
}
return result;
}
@Override
public synchronized List<ShoppingResultView> shopHistory() {
Mediator mediator= Mediator.getInstance();
return mediator.getArrayPurchases();
}
// View helpers -----------------------------------------------------
//Create ItemView from Item
private ItemView newItemView(Item item) {
ItemView view = new ItemView();
ItemIdView id=newItemIdView(item.getItemId());
view.setItemId(id);
view.setDesc(item.getDesc());
view.setPrice(item.getPrice());
return view;
}
//Create temIdView from ItemId
private ItemIdView newItemIdView(ItemId item){
ItemIdView view=new ItemIdView();
view.setProductId(item.getProductId());
view.setSupplierId(item.getSupplierId());
return view;
}
//Create CartItemView from CartItem
private CartItemView newCartItemView(CartItem cartItem){
CartItemView view= new CartItemView();
ItemView viewItem = newItemView(cartItem.getItem());
view.setItem(viewItem);
view.setQuantity(cartItem.getQuantity());
return view;
}
//Create CartView from Cart
private CartView newCartView(Cart cart){
CartView view= new CartView();
view.setCartId(cart.getCartId());;
for(CartItem item: cart.getCartItems()){
CartItemView itemView=newCartItemView(item);
view.getItems().add(itemView);
}
return view;
}
//Create new ItemView from ProductView
private ItemView newProdToItemView(ProductView p, String supplierId){
ItemView item = new ItemView();
item.setDesc(p.getDesc());
ItemIdView itemIdView= new ItemIdView();
itemIdView.setProductId(p.getId());
itemIdView.setSupplierId(supplierId);
item.setItemId(itemIdView);
item.setPrice(p.getPrice());
return item;
}
//Create ShoppingResultView
private ShoppingResultView newShowResultView(String id,Result result,List<CartItemView> purchasedItems,List<CartItemView> droppedItems,int totalPrice){
ShoppingResultView view=new ShoppingResultView();
view.setId(id);
view.setResult(result);
view.setTotalPrice(totalPrice);
for(CartItemView c: purchasedItems){
view.getPurchasedItems().add(c);
}
for(CartItemView c2: droppedItems){
view.getDroppedItems().add(c2);
}
return view;
}
// Exception helpers -----------------------------------------------------
private InvalidCreditCard_Exception CreditCardClientExceptionThrow(String msg) throws InvalidCreditCard_Exception{
throw new InvalidCreditCard_Exception(msg, null);
}
private InvalidCartId_Exception InvalidCartId_ExceptionThrow(String msg) throws InvalidCartId_Exception{
throw new InvalidCartId_Exception(msg, null);
}
private EmptyCart_Exception EmptyCart_ExceptionThrow(String msg) throws EmptyCart_Exception{
throw new EmptyCart_Exception(msg, null);
}
public InvalidText_Exception throwInvalidTextException(String message) throws InvalidText_Exception{
InvalidText faultInfo = new InvalidText();
faultInfo.setMessage(message);
throw new InvalidText_Exception("Invalid Text: ", faultInfo);
}
private InvalidCartId_Exception invalidCarIdExceptionThrow(String msg) throws InvalidCartId_Exception{
throw new InvalidCartId_Exception(msg,null);
}
private InvalidItemId_Exception InvalidItemId_ExceptionThrow(String msg) throws InvalidItemId_Exception{
throw new InvalidItemId_Exception(msg,null);
}
private InvalidQuantity_Exception InvalidQuantity_ExceptionThrow(String msg) throws InvalidQuantity_Exception{
throw new InvalidQuantity_Exception(msg,null);
}
private NotEnoughItems_Exception NotEnoughItems_ExceptionThrow(String msg) throws InvalidQuantity_Exception{
throw new InvalidQuantity_Exception(msg,null);
}
}
| true
|
64dc85afe7c29e0878b7f52918c1257ecd10ac48
|
Java
|
sobachan117/SampleCalculator
|
/app/src/main/java/com/example/samplecalculator/CalculatorState.java
|
UTF-8
| 4,166
| 2.890625
| 3
|
[] |
no_license
|
package com.example.samplecalculator;
import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
public class CalculatorState {
@NonNull
private final List<CalcComponent> mCalcHistoryList;
CalculatorState() {
mCalcHistoryList = new ArrayList<>();
}
CalculatorState calc(@NonNull CalcComponent calcComponent) {
CalcType type = calcComponent.getType();
CalcType lastType = getLastCalcComponent().getType();
if (type.equals(CalcType.AllCancel)) {
mCalcHistoryList.clear();
} else if (type.isOperator() && lastType.isOperator()) {
// replace component if the last type is operator and this type too.
mCalcHistoryList.remove(mCalcHistoryList.size() - 1);
mCalcHistoryList.add(calcComponent);
} else {
mCalcHistoryList.add(calcComponent);
}
return this;
}
@NonNull
String getCalcResult() {
int displayValue;
CalcType lastType = getLastCalcComponent().getType();
if (CalcType.Number.equals(lastType)) {
displayValue = getNextInputValue();
} else {
displayValue = calculateAll();
}
return String.valueOf(displayValue);
}
@NonNull
String getCalcHistory() {
StringBuilder stringBuilder = new StringBuilder();
for (CalcComponent calcComponent : mCalcHistoryList) {
stringBuilder.append(calcComponent.getDisplayName());
}
return stringBuilder.toString();
}
void clear() {
mCalcHistoryList.clear();
}
private CalcComponent getLastCalcComponent() {
if (mCalcHistoryList.isEmpty()) {
return new CalcComponent(CalcType.Number, "0", 0);
} else {
return mCalcHistoryList.get(mCalcHistoryList.size() - 1);
}
}
private int getNextInputValue() {
int value = 0;
int digit = 0;
for (int i = mCalcHistoryList.size() -1; 0 <= i; i--) {
CalcComponent component = mCalcHistoryList.get(i);
if (!(CalcType.Number.equals(component.getType()))) {
break;
}
int nextValue = Integer.valueOf(component.getDisplayName());
if (digit == 0) {
value = nextValue;
} else {
value = value + nextValue * (int) Math.pow(10, digit);
}
digit++;
}
return value;
}
private int calculateAll() {
int result = 0;
int next = 0;
CalcType operator = CalcType.AllCancel;
for (CalcComponent component : mCalcHistoryList) {
CalcType type = component.getType();
switch (type) {
case Number:
next = next * 10 + Integer.valueOf(component.getDisplayName());
break;
case Decimal:
case Plus:
case Minus:
case Divide:
case Multiply:
case Calculate:
case AllCancel:
result = calcWithOperator(operator, result, next);
next = 0;
operator = type;
break;
default:
break;
}
}
return result;
}
private int calcWithOperator(@NonNull CalcType buttonType,
int prevInputValue, int nextInputValue) {
switch (buttonType) {
case Plus:
prevInputValue += nextInputValue;
break;
case Minus:
prevInputValue -= nextInputValue;
break;
case Multiply:
prevInputValue *= nextInputValue;
break;
case Divide:
if (nextInputValue != 0) {
prevInputValue /= nextInputValue;
}
break;
default:
prevInputValue = nextInputValue;
break;
}
return prevInputValue;
}
}
| true
|
75af77f7620d9700a0d6e721ad7719dc4c9388af
|
Java
|
infosiftr/sdc
|
/catalog-be/src/test/java/org/openecomp/sdc/be/exception/SdcActionExceptionTest.java
|
UTF-8
| 506
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.openecomp.sdc.be.exception;
import org.junit.Test;
import org.openecomp.sdc.be.dao.api.ActionStatus;
public class SdcActionExceptionTest {
private SdcActionException createTestSubject() {
return new SdcActionException(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED);
}
@Test
public void testGetActionStatus() throws Exception {
SdcActionException testSubject;
ActionStatus result;
// default test
testSubject = createTestSubject();
result = testSubject.getActionStatus();
}
}
| true
|
5470457db063ed519d63c717501c70decaaa68cf
|
Java
|
ahmadsayed/VisionDoubleWeb
|
/src/main/java/com/ibm/mea/build/web/rest/FrameResource.java
|
UTF-8
| 3,201
| 2.359375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.ibm.mea.build.web.rest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.BodyPartEntity;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.FormDataParam;
import com.ibm.bluemix.services.business.logic.impl.cloudant.VisionDoubleEvent;
import com.ibm.bluemix.services.business.logic.impl.vision_double.MultipleFrameUploader;
@Path("frame")
public class FrameResource {
@Path("/offline-upload")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFiles(final FormDataMultiPart multiPart, @FormDataParam("cameraId") String cameraId, @FormDataParam("eventTime") String evtTime) {
Map<String, File> tmpFiles = new HashMap<String, File>();
List<FormDataBodyPart> bodyParts = multiPart.getFields("file");
for (int i = 0; i < bodyParts.size(); i++) {
BodyPartEntity bodyPartEntity = (BodyPartEntity) bodyParts.get(i).getEntity();
String fileName = bodyParts.get(i).getContentDisposition().getFileName();
try {
tmpFiles.put(fileName, this.createTmpFileForInputStream(bodyPartEntity.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
// event with exception will not be added to the list of events
}
}
MultipleFrameUploader frameUploader = new MultipleFrameUploader(tmpFiles, cameraId, evtTime);
frameUploader.start();
return Response.ok().build();
}
@POST
@Path("/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFrame(@FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition fileMetaData,
@FormDataParam("cameraId") String cameraId, @FormDataParam("eventTime") String evtTime)
{
VisionDoubleEvent event;
try {
File frameFile = this.createTmpFileForInputStream(fileInputStream);
FrameHandler frameHandler = new FrameHandler();
if(evtTime == null)
{
SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
evtTime = sdfTime.format(new Date());
}
event = frameHandler.handleFile(frameFile, fileMetaData.getFileName(), cameraId, evtTime);
return Response.ok(event).build();
} catch (Exception e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
}
private File createTmpFileForInputStream(InputStream fileInputStream) throws IOException {
File tmpFile = File.createTempFile("vision-", ".jpg");
tmpFile.deleteOnExit();
Files.copy(fileInputStream, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return tmpFile;
}
}
| true
|
3116799475e6f56b89deb709713e867930202cf7
|
Java
|
carsonsanders/sem
|
/src/main/java/com/napier/sem/Country.java
|
UTF-8
| 5,250
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.napier.sem;
import java.sql.*;
import java.util.ArrayList;
public class Country {
private String code;
private String name;
private String continent;
private String region;
private int population;
private String capital;
private ArrayList<Country> countryList = new ArrayList<Country>();
//Default constructor
public Country() {
}
//Accessor methods for properties
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public double getPopulation() {
return population;
}
public void setPopulation(int population){
this.population = population;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public ArrayList<Country> getCountryList() {
return countryList;
}
public void setCountryList(ArrayList<Country> countryList) {
this.countryList = countryList;
}
/**
* @param inThe : different categories of reports (world,continent or region)
* @param name : name of region or continent (required if either of those categories are chosen)
*
* @return A list of countries using the specified parameters
*/
public ArrayList<Country> getCountries(String inThe, String name) {
countryList.clear();
if(inThe=="world"&& (name==null)) {
try
{
// Create an SQL statement
Statement stmt = App.con.createStatement();
// Query to select all countries
String query = "SELECT * FROM country " +
"ORDER BY population DESC";
// Execute SQL statement
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
//Add country to countrylist
countryList.add(newCountry(rs));
}
return countryList;
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.out.println("Failed to extract data");
return null;
}
}
//if parameters are region and name is not null
else if(inThe=="continent" && !(name==null)) {
try {
// Create an SQL statement
Statement stmt = App.con.createStatement();
// Query to select all countries
String query = "SELECT * FROM country " +
"WHERE country.Continent ='" + name + "'" +
"ORDER BY population DESC";
// Execute SQL statement
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//Add country to countrylist
countryList.add(newCountry(rs));
}
return countryList;
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Failed to extract data");
return null;
}
}
//if parameters are region and name is not null
else if(inThe=="region" && !(name==null)){
try
{
// Create an SQL statement
Statement stmt = App.con.createStatement();
// Query to select all countries
String query = "SELECT * FROM country " +
"WHERE country.Region ='" + name + "'" +
"ORDER BY population DESC";
// Execute SQL statement
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
//Add country to countrylist
countryList.add(newCountry(rs));
}
return countryList;
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.out.println("Failed to extract data");
return null;
}
}
return null;
}
//Returns country object created from result set data
public Country newCountry(ResultSet rs) throws SQLException {
Country cout = new Country();
cout.setCode(rs.getString("Code"));
cout.setName(rs.getString("Name"));
cout.setContinent(rs.getString("Continent"));
cout.setRegion(rs.getString("Region"));
cout.setPopulation(rs.getInt("Population"));
cout.setCapital(rs.getString("Capital"));
return cout;
}
}
| true
|
ec5beca544423672ff04ffaf4cadb78aa51e0f41
|
Java
|
LiuinStein/CILManagement-Server
|
/src/main/java/cn/opencil/controller/authorization/AuthUserController.java
|
UTF-8
| 2,785
| 2.296875
| 2
|
[] |
no_license
|
package cn.opencil.controller.authorization;
import cn.opencil.exception.SimpleHttpException;
import cn.opencil.po.RBACUserRole;
import cn.opencil.service.RBACUserRoleService;
import cn.opencil.service.ValidationService;
import cn.opencil.validation.group.RegisterValidation;
import cn.opencil.validation.group.database.DatabaseRoleValidation;
import cn.opencil.validation.group.database.DatabaseUserValidation;
import cn.opencil.vo.RestfulResult;
import com.alibaba.fastjson.JSONObject;
import com.shaoqunliu.validation.exception.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
@RestController
@RequestMapping("/v1/auth/user")
public class AuthUserController {
private final RBACUserRoleService userRoleService;
private final ValidationService validationService;
@Autowired
public AuthUserController(RBACUserRoleService userRoleService, ValidationService validationService) {
this.userRoleService = userRoleService;
this.validationService = validationService;
}
/**
* Assign a new role to somebody
*/
@RequestMapping(value = "/role/", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.CREATED)
public RestfulResult assignRoleToUser(@RequestBody JSONObject input) throws ValidationException, SimpleHttpException {
RBACUserRole userRole = validationService.validate(input.toJavaObject(RBACUserRole.class),
RegisterValidation.class, DatabaseRoleValidation.class, DatabaseUserValidation.class);
if (!userRoleService.assignRoleToUser(userRole)) {
throw new SimpleHttpException(500, "database access error", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new RestfulResult(0, "role assign successfully", new HashMap<>());
}
/**
* Take back a role from someone
*/
@RequestMapping(value = "/role/", method = RequestMethod.DELETE, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.NO_CONTENT)
public void revokeRoleFormUser(@RequestBody JSONObject input) throws ValidationException, SimpleHttpException {
RBACUserRole userRole = validationService.validate(input.toJavaObject(RBACUserRole.class), RegisterValidation.class);
if (userRole.getUserId().equals(10001L)) {
throw new SimpleHttpException(400, "10001 is the default admin, we can not revoke permission from him", HttpStatus.BAD_REQUEST);
}
userRoleService.revokeRoleFromUser(userRole);
}
}
| true
|
c9874b8f12ae957783b1e060b75c011a2a988779
|
Java
|
bravesoftdz/BWC
|
/src/main/java/com/ric/bill/mm/impl/EolinkMngImpl.java
|
UTF-8
| 2,484
| 2.421875
| 2
|
[] |
no_license
|
package com.ric.bill.mm.impl;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ric.bill.dao.EolinkDAO;
import com.ric.bill.dao.EolinkToEolinkDAO;
import com.ric.bill.mm.EolinkMng;
import com.ric.bill.model.exs.Eolink;
@Service
@Slf4j
public class EolinkMngImpl implements EolinkMng {
@Autowired
private EolinkDAO eolinkDao;
@Autowired
private EolinkToEolinkDAO eolinkToEolinkDao;
/**
* Получить Внешний объект по GUID
* @param guid - GUID
* @return
*/
public Eolink getEolinkByGuid(String guid) {
return eolinkDao.getEolinkByGuid(guid);
}
/**
* Получить Внешние объекты, связанные с данным
* @param eolink - Внешний объект
* @return
*/
public List<Eolink> getLinkedEolink(Eolink eolink) {
return eolinkToEolinkDao.getLinkedEolink(eolink);
}
/**
* Получить Внешний объект по reu,kul,nd
* @param reu - REU из Квартплаты
* @param kul - KUL из Квартплаты
* @param nd - ND из Квартплаты
* @param kw - KW из Квартплаты
* @param entry - ENTRY из Квартплаты
* @param tp - тип объекта
*/
public Eolink getEolinkByReuKulNdTp(String reu, String kul, String nd,
String kw, String entry, String tp) {
return eolinkDao.getEolinkByReuKulNdTp(reu, kul, nd, kw, entry, tp);
}
/* Поменять статус "актив" всех дочерних объектов по типу
* @param - eolink - объект
* @param - tp - тип объекта
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor=Exception.class) //rollbackFor=Exception.class - означает, что все исключения, выбрасываемые данным методом, должны приводить к откату транзакции.
public void setChildActive(Eolink eolink, String tp, Integer status) {
eolink.getChild().stream().forEach(t-> {
t.setStatus(status);
});
}
}
| true
|
eba4a50a5d97bf6498c188eff20631ad973c901b
|
Java
|
saifulazad/BD-Sw-Firms
|
/app/src/main/java/com/jokerslab/android/bd_sw_firms/di/MainActivityComponent.java
|
UTF-8
| 458
| 1.78125
| 2
|
[] |
no_license
|
package com.jokerslab.android.bd_sw_firms.di;
import com.jokerslab.android.bd_sw_firms.MainActivity;
import dagger.Subcomponent;
import dagger.android.AndroidInjector;
/**
* Created by sayem on 9/26/2017.
*/
@Subcomponent(modules = MainActivityModule.class)
public interface MainActivityComponent extends AndroidInjector<MainActivity> {
@Subcomponent.Builder
public abstract class Builder extends AndroidInjector.Builder<MainActivity> {
}
}
| true
|
dfc9aab65c12bdc33d3500ddcd299d6572779aa1
|
Java
|
pa2020/pa2020-api
|
/src/main/java/fr/esgi/api/dto/request/AnalyzeRequestDto.java
|
UTF-8
| 1,575
| 2.21875
| 2
|
[] |
no_license
|
package fr.esgi.api.dto.request;
import fr.esgi.api.models.request.AnalyzeRequest;
import fr.esgi.api.models.request.Request;
import fr.esgi.api.repositories.request.AnalyzeRequestRepository;
import fr.esgi.api.repositories.request.RequestRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.Optional;
/**
* Created by Zakaria FAHRAOUI.
*/
@Component
@RequiredArgsConstructor
public class AnalyzeRequestDto implements IAnalyzeRequestDto {
private final AnalyzeRequestRepository analyzeRequestRepository;
private final RequestRepository requestRepository;
@Override
public AnalyzeRequest create(AnalyzeRequest analyzeRequest) {
Optional<Request> search = Optional.of(requestRepository.findById(analyzeRequest.getRequests().getRequest_id())).get();
Optional<AnalyzeRequest> search2 = Optional.of(analyzeRequestRepository.SearchById(analyzeRequest.getRequests().getRequest_id())).get();
if (analyzeRequest.getAnalyze_r_id() != null) {
// Cannot create Request with specified ID value
return null;
} else if (search2.isPresent()) {
throw new RuntimeException("Request_Id already linked for an Analyze_r_id! == > id = " + analyzeRequest.getRequests().getRequest_id());
} else if (search.isEmpty()) {
throw new RuntimeException("Request Id Introuvable! == > id = " + analyzeRequest.getRequests().getRequest_id());
} else {
return analyzeRequestRepository.save(analyzeRequest);
}
}
}
| true
|
f03a1b4c46554329bbf8b514120446eb16ebd439
|
Java
|
mmoayyed/java-identity-provider
|
/idp-profile-impl/src/main/java/net/shibboleth/idp/profile/impl/InitializeProfileRequestContext.java
|
UTF-8
| 5,417
| 1.820313
| 2
|
[] |
no_license
|
/*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.shibboleth.idp.profile.impl;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import org.opensaml.messaging.context.ScratchContext;
import org.opensaml.profile.context.ProfileRequestContext;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.idp.profile.AbstractProfileAction;
import net.shibboleth.idp.profile.ActionSupport;
import net.shibboleth.shared.primitive.StringSupport;
/**
* Action that creates a new {@link ProfileRequestContext} and binds it to the current conversation under the
* {@link ProfileRequestContext#BINDING_KEY} key, and sets the profile and logging IDs, if provided.
*
* <p>This is a native SWF action in order to access conversation scope.</p>
*
* <p>Optionally saves off query parameters from request into a {@link ScratchContext}.</p>
*
* @event {@link org.opensaml.profile.action.EventIds#PROCEED_EVENT_ID}
* @post RequestContext.getConversationScope().get(ProfileRequestContext.BINDING_KEY) != null
*/
@ThreadSafe
public final class InitializeProfileRequestContext extends AbstractProfileAction {
/** The profile ID to initialize the context to. */
@Nullable private String profileId;
/** Backup profile ID to populate as a legacy value. */
@Nullable private String legacyProfileId;
/** The logging ID to initialize the context to. */
@Nullable private String loggingId;
/** Whether this is a browser-based profile request. */
private boolean browserProfile;
/** Whether to capture and store off query parameters. */
private boolean captureQueryParameters;
/**
* Set the profile ID to populate into the context.
*
* @param id profile ID to populate into the context
*/
public void setProfileId(@Nullable final String id) {
checkSetterPreconditions();
profileId = StringSupport.trimOrNull(id);
}
/**
* Set the legacy/fallback profile ID to populate into the context.
*
* @param id legacy profile ID to populate into the context
*
* @since 4.2.0
*/
public void setLegacyProfileId(@Nullable final String id) {
checkSetterPreconditions();
legacyProfileId = StringSupport.trimOrNull(id);
}
/**
* Set the logging ID to populate into the context.
*
* @param id logging ID to populate into the context
*/
public void setLoggingId(@Nullable final String id) {
checkSetterPreconditions();
loggingId = StringSupport.trimOrNull(id);
}
/**
* Set whether the request is browser-based, defaults to false.
*
* @param browser flag to set
*/
public void setBrowserProfile(final boolean browser) {
checkSetterPreconditions();
browserProfile = browser;
}
/**
* Set whether to capture incoming query parameters in a {@link ScratchContext},
* defaults to false.
*
* @param flag flag to set
*
* @since 4.1.0
*/
public void setCaptureQueryParameters(final boolean flag) {
checkSetterPreconditions();
captureQueryParameters = flag;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
@Nonnull public Event execute(@Nonnull final RequestContext springRequestContext) {
// We have to override execute() because the profile request context doesn't exist yet.
checkComponentActive();
final ProfileRequestContext prc = new ProfileRequestContext();
if (profileId != null) {
prc.setProfileId(profileId);
}
if (legacyProfileId != null) {
prc.setLegacyProfileId(legacyProfileId);
}
if (loggingId != null) {
prc.setLoggingId(loggingId);
}
prc.setBrowserProfile(browserProfile);
springRequestContext.getConversationScope().put(ProfileRequestContext.BINDING_KEY, prc);
if (captureQueryParameters) {
final HttpServletRequest request = getHttpServletRequest();
if (request != null) {
((Map<Object,Object>) prc.getSubcontext(ScratchContext.class, true).getMap()).putAll(
request.getParameterMap());
}
}
return ActionSupport.buildProceedEvent(this);
}
}
| true
|
3c301d8d20af7af5859f3b2090416e585dbc9685
|
Java
|
FatLi1989/book-shop
|
/book-shop-user-centre/src/main/java/com/user/centre/mq/rocketmq/AddBonusConsumer.java
|
UTF-8
| 975
| 2.1875
| 2
|
[] |
no_license
|
package com.user.centre.mq.rocketmq;
import com.user.centre.model.dto.messaging.UserAddBonusMsgDTO;
import com.user.centre.serivce.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author novLi
* @date 2020年01月09日 13:48
*/
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "user-info-group", topic = "user-info-topic")
public class AddBonusConsumer implements RocketMQListener<UserAddBonusMsgDTO> {
@Autowired
private UserService userService;
@Override
public void onMessage(UserAddBonusMsgDTO message) {
log.info("用户添加积分消费开始");
message.setEvent("CONTRIBUTE");
message.setDescription("投稿加积分..");
userService.addBonus(message);
}
}
| true
|
f2befee094e4f3d858536e7d6417eb192ba6327d
|
Java
|
bzarnaudov/My-all-work
|
/16LinearDateStructures/src/all/BfsForAllDirectoriesOnHardDisk.java
|
UTF-8
| 1,811
| 3.234375
| 3
|
[] |
no_license
|
package all;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BfsForAllDirectoriesOnHardDisk {
public static void main(String[] args) {
PrintStream fileOutput = null;
String outputFile = "DirectoriesByBFS.txt";
String hardDiskLetter;
Scanner input = new Scanner(System.in);
System.out.print("Please enter path for directory , which you want to see details : ");
while (true) {
hardDiskLetter = input.nextLine();
if (chackingPath(hardDiskLetter)) {
break;
}
System.out.println("Invalid path, please enter valid path :");
}
File file = new File(hardDiskLetter);
Queue<File> queue = new LinkedList<File>();
queue.add(file);
try {
fileOutput = new PrintStream(outputFile, "windows-1251");
while (!queue.isEmpty()) {
file = queue.poll();
File[] listOfFiles = file.listFiles();
if(listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
System.out.println(listOfFiles[i]);
fileOutput.println(listOfFiles[i]);
queue.add(listOfFiles[i]);
}
}
}
}
} catch (FileNotFoundException fnfe) {
System.err.println(fnfe.getMessage());
} catch (UnsupportedEncodingException uee) {
System.err.println(uee.getMessage());
} finally {
if (null != fileOutput) {
fileOutput.close();
}
}
input.close();
}
private static boolean chackingPath(String pathName) {
try {
Path path = Paths.get(pathName);
path.toRealPath();
} catch (InvalidPathException | IOException e) {
return false;
}
return true;
}
}
| true
|
37ef462b2fe28f42121ae718a4ac2373af3bdc44
|
Java
|
venkateshpavuluri/organization
|
/SpringMvc/src/main/java/com/mnt/erp/bean/CapacityCategory.java
|
UTF-8
| 1,795
| 1.882813
| 2
|
[] |
no_license
|
/**
*
*/
package com.mnt.erp.bean;
/**
* @author anikesh
*
*/
public class CapacityCategory {
private int capcategoryId;
private String capcategory;
private String capcategorySearch;
private int aid;
private String operations;
private String basicSearchId;
private String xmlLabel;
private int capcategoryIdEdit;
private String capcategoryEdit;
public int getCapcategoryId() {
return capcategoryId;
}
public void setCapcategoryId(int capcategoryId) {
this.capcategoryId = capcategoryId;
}
public String getCapcategory() {
return capcategory;
}
public void setCapcategory(String capcategory) {
this.capcategory = capcategory;
}
public String getCapcategorySearch() {
return capcategorySearch;
}
public void setCapcategorySearch(String capcategorySearch) {
this.capcategorySearch = capcategorySearch;
}
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public int getCapcategoryIdEdit() {
return capcategoryIdEdit;
}
public void setCapcategoryIdEdit(int capcategoryIdEdit) {
this.capcategoryIdEdit = capcategoryIdEdit;
}
public String getCapcategoryEdit() {
return capcategoryEdit;
}
public void setCapcategoryEdit(String capcategoryEdit) {
this.capcategoryEdit = capcategoryEdit;
}
public String getOperations() {
return operations;
}
public void setOperations(String operations) {
this.operations = operations;
}
public String getBasicSearchId() {
return basicSearchId;
}
public void setBasicSearchId(String basicSearchId) {
this.basicSearchId = basicSearchId;
}
public String getXmlLabel() {
return xmlLabel;
}
public void setXmlLabel(String xmlLabel) {
this.xmlLabel = xmlLabel;
}
}
| true
|
0700aa65c4f2d6d2e71b7a702cf14810275e56de
|
Java
|
mkhassan/RoboResume2
|
/src/RoboApp.java
|
UTF-8
| 239
| 2.046875
| 2
|
[] |
no_license
|
public class RoboApp {
public static void main(String[] args) {
BuildResume myresume = new BuildResume();
myresume.setPerson();
myresume.setEducation();
myresume.setExperience();
myresume.setSkills();
}
}
| true
|
bfa91f62edd36f218d1282f7d2fdf6b0f3c686fa
|
Java
|
ivanetierra/nuwe-hackathon-back
|
/src/main/java/com/nuwe/repository/IUserRepository.java
|
UTF-8
| 361
| 2.03125
| 2
|
[] |
no_license
|
package com.nuwe.repository;
import com.nuwe.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface IUserRepository extends MongoRepository<User, String> {
User getUserById(String id);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
User getByEmail(String email);
}
| true
|
72633462ac7a6da60adbc115eb6906a9799f03fc
|
Java
|
Tencent/bk-base
|
/src/datahub/databus/databus-commons/src/main/java/com/tencent/bk/base/datahub/databus/commons/utils/LicenseChecker.java
|
UTF-8
| 4,518
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
/*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.bk.base.datahub.databus.commons.utils;
import com.tencent.bk.base.datahub.databus.commons.Consts;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LicenseChecker {
public static final Logger log = LoggerFactory.getLogger(LicenseChecker.class);
/**
* 检查license是否有效
*
* @return true/false
*/
public static boolean checkLicense(String certFile, String certServer, String platform) {
try {
String response = HttpUtils.postSSL(certServer, getBody(certFile, platform));
LogUtils.info(log, "license server: {}", response);
if (StringUtils.isNotBlank(response)) {
try {
CertResult certResult = JsonUtils.parseBean(response, CertResult.class);
if (certResult.status) {
if (certResult.result == 0) {
return true;
} else {
// 证书验证失败
LogUtils.error(LogUtils.ERR_PREFIX + LogUtils.CERT_ERR, log, certResult.message);
LogUtils.error(LogUtils.ERR_PREFIX + LogUtils.CERT_ERR, log, certResult.message_cn);
}
} else {
LogUtils.error(LogUtils.ERR_PREFIX + LogUtils.LICENSE_SERVER_ERR, log,
"failed to validate certificate with License Server!");
}
} catch (IOException e) {
LogUtils.warn(log, "exception during response handling... {}", e.getMessage());
}
}
return false;
} catch (Exception e) {
LogUtils.error(LogUtils.ERR_PREFIX + LogUtils.LICENSE_SERVER_ERR, log,
"Found exception during certificate validation.", e);
return false;
}
}
/**
* 构建请求参数
*
* @return json字符串的参数
* @throws Exception 异常
*/
public static Map<String, String> getBody(String certFile, String platform) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
byte[] encoded = Files.readAllBytes(Paths.get(certFile));
Map<String, String> body = new HashMap<>();
body.put("platform", platform);
body.put("time", dateFormat.format(new Date()));
body.put("certificate", new String(encoded, Consts.UTF8));
String request = JsonUtils.toJson(body);
LogUtils.info(log, "request\n {}", request);
return body;
}
private static class CertResult {
protected boolean status;
protected int result;
protected String message;
protected String message_cn;
}
}
| true
|
bc0819630b45e76140a8648b01213893400ad42c
|
Java
|
lopezruizjavier/feed-consumer
|
/server/src/main/java/com/sparta/feedconsumer/provider/repository/impl/ProviderRepositoryImpl.java
|
UTF-8
| 881
| 2.21875
| 2
|
[] |
no_license
|
package com.sparta.feedconsumer.provider.repository.impl;
import com.sparta.feedconsumer.provider.model.Provider;
import com.sparta.feedconsumer.provider.model.Record;
import com.sparta.feedconsumer.provider.repository.ProviderRepository;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class ProviderRepositoryImpl implements ProviderRepository {
private final Map<String, List<Record>> dataSource = Collections.synchronizedMap(new HashMap<>());
@Override
public int upsert(Provider provider) {
dataSource.computeIfAbsent(provider.getName(), $ -> new ArrayList<>()).addAll(provider.getRecords());
return provider.getRecords().size();
}
@Override
public List<Record> selectRecords(String providerName) {
return dataSource.computeIfAbsent(providerName, $ -> new ArrayList<>());
}
}
| true
|
220d35bcae6e00846832f235a99c8b47833303d4
|
Java
|
605774644/db-boot
|
/db-migrate/src/main/java/org/github/hoorf/dbboot/migrate/dialect/mysql/MysqlSQLBuilder.java
|
UTF-8
| 1,771
| 2.671875
| 3
|
[] |
no_license
|
package org.github.hoorf.dbboot.migrate.dialect.mysql;
import java.util.List;
import org.github.hoorf.dbboot.migrate.core.record.Column;
import org.github.hoorf.dbboot.migrate.core.sqlbuilder.AbstractMigrateSQLBuilder;
public class MysqlSQLBuilder extends AbstractMigrateSQLBuilder {
@Override
protected String buildInsertOrUpdateSQLInternal(String tableName, List<Column> columnList) {
StringBuilder labelHolder = new StringBuilder();
StringBuilder valueHolder = new StringBuilder();
for (Column column : columnList) {
labelHolder.append(quote(column.getName())).append(",");
valueHolder.append("?,");
}
labelHolder.setLength(labelHolder.length() - 1);
valueHolder.setLength(valueHolder.length() - 1);
return String.format("INSERT INTO %s(%s) VALUES(%s) %s ", quote(tableName), labelHolder, valueHolder, onDuplicateKeyUpdateString(columnList));
}
private String onDuplicateKeyUpdateString(List<Column> columnHolders) {
if (columnHolders == null || columnHolders.size() < 1) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(" ON DUPLICATE KEY UPDATE ");
boolean first = true;
for (Column column : columnHolders) {
if (!first) {
sb.append(",");
} else {
first = false;
}
sb.append(quote(column.getName()));
sb.append("=VALUES(");
sb.append(quote(column.getName()));
sb.append(")");
}
return sb.toString();
}
@Override
protected String getQuote() {
return "`";
}
@Override
public String getType() {
return "mysql";
}
}
| true
|
34de5bb0266b5edc3081b53d2f8e432db1fa024c
|
Java
|
TheDarkMystic/competitive-coding
|
/TwoPointers/removeDuplicatesFromSortedArray.java
|
UTF-8
| 1,071
| 3.234375
| 3
|
[] |
no_license
|
/*
* 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 interviewprep.TwoPointers;
/**
*
* @author jakadam
*/
import java.util.*;
public class removeDuplicatesFromSortedArray {
public int removeDuplicates(ArrayList<Integer> arr) {
int len=arr.size();
int wall=0;
for(int num: arr){ // for each number in array
if(wall<1 || arr.get(wall-1)!=num){
// wall<1 cause first ele will always be unique, so make if cond. true
// after 1st ele, if depends completly on "arr.get(wall-1)!=num"
//'wall-1' because we are doing wall++, so for correct comparison check previous
// of wall
arr.set(wall,num);
wall++;
}
}
return wall;
}
}
/*
Links-https://www.interviewbit.com/problems/remove-duplicates-from-sorted-array/
Notes-
Make a dry run of code.
*/
| true
|
de7dca4b045493cbf3dd1e959dd85fd95cc77758
|
Java
|
botija/testvr
|
/app/src/main/java/com/botijasoftware/utils/animation/Keyframe.java
|
UTF-8
| 713
| 2.78125
| 3
|
[] |
no_license
|
package com.botijasoftware.utils.animation;
import com.botijasoftware.utils.Vector3;
public class Keyframe {
public float time;
public Vector3 translate;
public float angle;
public Vector3 axis;
public Vector3 scale;
public Keyframe(float time) {
this.time = time;
}
public void setTranslate(float x, float y, float z) {
translate = new Vector3(x,y,z);
}
public void setScale(float x, float y, float z) {
scale = new Vector3(x,y,z);
}
public void setRotation(float angle, float x, float y, float z) {
this.angle = angle;
axis = new Vector3(x, y, z);
}
public void transformBone(Bone bone) {
bone.transmformMatrix(translate, axis, (float)(angle*Math.PI/180.0f), scale);
}
}
| true
|
2db1ddd524840407f5f71a24b522b16ac0791405
|
Java
|
scottTomaszewski/beta
|
/src/main/java/com/beta/UserPreviewEmail.java
|
UTF-8
| 302
| 1.992188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.beta;
import com.fasterxml.jackson.annotation.JsonProperty;
public class UserPreviewEmail {
private final String email;
public UserPreviewEmail(@JsonProperty("email") String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
| true
|
0119e975148935cda832606593437ab345583feb
|
Java
|
Allen-C-Chen/LMS-Admin
|
/src/main/java/com/smoothstack/lms/admin/controller/BookLoanAdminController.java
|
UTF-8
| 2,752
| 2.078125
| 2
|
[] |
no_license
|
package com.smoothstack.lms.admin.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.smoothstack.lms.admin.entity.BookLoan;
import com.smoothstack.lms.admin.service.BookLoanService;
@RestController
@RequestMapping("/lms/admin")
public class BookLoanAdminController {
@Autowired
private BookLoanService bookLoanService;
@GetMapping(value = "/loaned-books",
produces = {"application/json", "application/xml"})
public ResponseEntity<List<BookLoan>> getAllBookLoans() {
return bookLoanService.getAllBookLoans();
}
//borrower/{cardNo}/book
@GetMapping(
value = "/loaned-book/librarybranch/{libBranchId}/book/{bookId}/borrower/{cardNo}",
produces = {"application/json", "application/xml"})//R
public ResponseEntity<BookLoan> getBookLoanByID(@PathVariable Integer libBranchId,
@PathVariable Integer bookId,
@PathVariable Integer cardNo) {
return bookLoanService.getBookLoanById(libBranchId, bookId, cardNo);
}
@PutMapping(
value = "/loaned-book/librarybranch/{libBranchId}/book/{bookId}/borrower/{cardNo}/override/checkoutdate",
consumes = {"application/json", "application/xml"},
produces = {"application/json", "application/xml"}) //U
public ResponseEntity<BookLoan> overrideCheckOutDate(
@PathVariable Integer libBranchId,
@PathVariable Integer bookId,
@PathVariable Integer cardNo,
@RequestBody BookLoan bookLoanData) {
return bookLoanService.overrideCheckOutDate(
libBranchId, bookId, cardNo, bookLoanData);
}
// Create a new Note
@PostMapping(value = "/loaned-book",
consumes = {"application/json", "application/xml"},
produces = {"application/json", "application/xml"})//C
public ResponseEntity<BookLoan> createBookLoan(@Valid @RequestBody BookLoan bookLoan) {
return bookLoanService.createNewBookLoan(bookLoan);
}
@DeleteMapping(value = "/loaned-book/librarybranch/{libBranchId}/book/{bookId}/borrower/{cardNo}")
public ResponseEntity<BookLoan> deleteBookLoan(@PathVariable Integer libBranchId,
@PathVariable Integer bookId,
@PathVariable Integer cardNo) {
return bookLoanService.deleteBookLoan(libBranchId, bookId, cardNo);
}
}
| true
|
dee21bacb2fafe351252c1e47633d142dec90fd1
|
Java
|
infoshareacademy/jjdd5-jbusters
|
/web/src/main/java/com/infoshareacademy/jbusters/authentication/PasswordHashing.java
|
UTF-8
| 434
| 2.390625
| 2
|
[] |
no_license
|
package com.infoshareacademy.jbusters.authentication;
import org.mindrot.jbcrypt.BCrypt;
import javax.faces.bean.RequestScoped;
@RequestScoped
public class PasswordHashing {
public String generateHash(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
public boolean checkPassword(String password, String hashedPassword) {
return BCrypt.checkpw(password, hashedPassword);
}
}
| true
|
d8a8212920bd305005090ff19c95b9cc49c64375
|
Java
|
mtariqsiddiqui/PortletCode
|
/SadadServiceClient/src/main/java/com/sadad/ebpp/schema/lookup/_1/CriteriaType.java
|
UTF-8
| 2,841
| 2.015625
| 2
|
[] |
no_license
|
//
// Generated By:JAX-WS RI IBM 2.2.1-11/28/2011 08:28 AM(foreman)- (JAXB RI IBM 2.2.3-11/28/2011 06:21 AM(foreman)-)
//
package com.sadad.ebpp.schema.lookup._1;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* - the CriteriaKey should be one of the following strings
* "ServiceMsgType" to be used in MESSAGE_CODES Lookup.
* - the CriteriaValue should be on the following
* in case of CriteriaKey is "ServiceMsgType" the CriteriaValue Should be ["SOAP" or "XML"]
*
*
* <p>Java class for Criteria_Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Criteria_Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CriteriaKey" type="{http://www.sadad.com/scm/Common/System/1.0}C32_SType"/>
* <element name="CriteriaValue" type="{http://www.sadad.com/scm/Common/System/1.0}C32_SType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Criteria_Type", propOrder = {
"criteriaKey",
"criteriaValue"
})
public class CriteriaType
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlElement(name = "CriteriaKey", required = true)
protected String criteriaKey;
@XmlElement(name = "CriteriaValue", required = true)
protected String criteriaValue;
/**
* Gets the value of the criteriaKey property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCriteriaKey() {
return criteriaKey;
}
/**
* Sets the value of the criteriaKey property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCriteriaKey(String value) {
this.criteriaKey = value;
}
/**
* Gets the value of the criteriaValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCriteriaValue() {
return criteriaValue;
}
/**
* Sets the value of the criteriaValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCriteriaValue(String value) {
this.criteriaValue = value;
}
}
| true
|
44b4c08c0e11f34eb6feb44e4a5bf60776ee2b7e
|
Java
|
ppboucourt/api-sample
|
/src/main/java/co/tmunited/bluebook/domain/PatientResultDet.java
|
UTF-8
| 6,741
| 2.015625
| 2
|
[] |
no_license
|
package co.tmunited.bluebook.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A PatientResultDet.
*/
@Entity
@Table(name = "patient_result_det")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "patientresultdet")
public class PatientResultDet extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="patient_result_det_id_seq")
@SequenceGenerator(
name="patient_result_det_id_seq",
sequenceName="patient_result_det_id_seq",
allocationSize=20
)
private Long id;
@Column(name = "test_code")
private String testCode;
@Column(name = "test_name")
private String testName;
@Column(name = "result")
private String result;
@Column(name = "cut_off")
private String cutOff;
@Column(name = "units")
private String units;
@Column(name = "status")
private String status;
@Column(name = "comments")
private String comments;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
@JoinColumn(name = "patient_result_id", referencedColumnName = "id")
private PatientResult patientResult;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTestCode() {
return testCode;
}
public void setTestCode(String testCode) {
this.testCode = testCode;
}
public PatientResultDet testCode(String testCode) {
this.testCode = testCode;
return this;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public PatientResultDet testName(String testName) {
this.testName = testName;
return this;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public PatientResultDet result(String result) {
this.result = result;
return this;
}
public String getCutOff() {
return cutOff;
}
public void setCutOff(String cutOff) {
this.cutOff = cutOff;
}
public PatientResultDet cutOff(String cutOff) {
this.cutOff = cutOff;
return this;
}
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public PatientResultDet units(String units) {
this.units = units;
return this;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public PatientResultDet status(String status) {
this.status = status;
return this;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public PatientResultDet comments(String comments) {
this.comments = comments;
return this;
}
public PatientResult getPatientResult() {
return patientResult;
}
public void setPatientResult(PatientResult patientResult) {
this.patientResult = patientResult;
}
public PatientResultDet patientResult(PatientResult patientResult) {
this.patientResult = patientResult;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientResultDet patientResultDet = (PatientResultDet) o;
if (patientResultDet.id == null || id == null) {
return false;
}
return Objects.equals(id, patientResultDet.id);
}
public boolean equals(PatientResultDet patientResultDet) {
initObjects(patientResultDet);
if (this.testCode.contentEquals(patientResultDet.getTestCode()) &&
this.testName.contentEquals(patientResultDet.getTestName()) &&
this.result.contentEquals(patientResultDet.getResult()) &&
this.cutOff.contentEquals(patientResultDet.getCutOff()) &&
this.units.contentEquals(patientResultDet.getUnits()) &&
this.status.contentEquals(patientResultDet.getStatus()) &&
this.comments.contentEquals(patientResultDet.getComments())) {
return true;
} else {
return false;
}
}
private void initObjects(PatientResultDet patientResultDet) {
if (this.testCode == null) {
this.testCode = "";
}
if (this.testName == null) {
this.testName = "";
}
if (this.result == null) {
this.result = "";
}
if (this.cutOff == null) {
this.cutOff = "";
}
if (this.units == null) {
this.units = "";
}
if (this.status == null) {
this.status = "";
}
if (this.comments == null) {
this.comments = "";
}
if (patientResultDet.testCode == null) {
patientResultDet.testCode = "";
}
if (patientResultDet.testName == null) {
patientResultDet.testName = "";
}
if (patientResultDet.result == null) {
patientResultDet.result = "";
}
if (patientResultDet.cutOff == null) {
patientResultDet.cutOff = "";
}
if (patientResultDet.units == null) {
patientResultDet.units = "";
}
if (patientResultDet.status == null) {
patientResultDet.status = "";
}
if (patientResultDet.comments == null) {
patientResultDet.comments = "";
}
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "PatientResultDet{" +
"id=" + id +
", testCode='" + testCode + "'" +
", testName='" + testName + "'" +
", result='" + result + "'" +
", cutOff='" + cutOff + "'" +
", units='" + units + "'" +
", status='" + status + "'" +
", comments='" + comments + "'" +
'}';
}
}
| true
|
ff8d568b926c010a6cbaca8f43423cf9afd92f08
|
Java
|
MiguelProgrammer/spring-boot-ionic-backend
|
/src/main/java/com/estudandoemcasa/cursomg/repositories/EnderecoRepository.java
|
UTF-8
| 346
| 1.632813
| 2
|
[] |
no_license
|
package com.estudandoemcasa.cursomg.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.estudandoemcasa.cursomg.domain.Endereco;
/*
* Camada de Acesso a Dados
*/
@Repository
public interface EnderecoRepository extends JpaRepository<Endereco,Integer>{
}
| true
|
b611ddfc2bcc9f76dd6b3bde4f52225bbf734d4f
|
Java
|
swapnaray/MaveanProject
|
/src/main/java/temp/Runmode.java
|
UTF-8
| 632
| 2.375
| 2
|
[] |
no_license
|
package temp;
import com.qtpselenium.util.Xls_Reader;
public class Runmode {
public static void main(String[] args) {
String testName="LoginTest";
String sheetName="Testcases";
String path = System.getProperty("user.dir")+"\\src\\test\\resources\\Testcases.xlsx";
Xls_Reader xls = new Xls_Reader(path);
int rows = xls.getRowCount(sheetName);
for(int rNum=2;rNum<=rows;rNum++) {
String tName = xls.getCellData(sheetName, "TCID", rNum);
if(tName.equals(testName)) {
String runmode = xls.getCellData(sheetName, "Runmode", rNum);
System.out.println(runmode);
}
}
}
}
| true
|
17ef18ebdb191369dbb25230fde3a4e59ceb09d0
|
Java
|
harmansingh1699/ucciguserinterface
|
/src/main/java/Rav1.java
|
UTF-8
| 608
| 2.609375
| 3
|
[] |
no_license
|
public class Rav1 {
public static void main(String[] args) {
String cmd1 = "rundll32 url.dll,FileProtocolHandler " +"C:\\Documents and Settings\\developer\\Desktop\\id.val";
try {
Runtime.getRuntime().exec(cmd1);
} catch (Exception ex) {
if (ex.toString().contains("java.io.IOException: Cannot run program \"rundll32\"")) {
try {
Runtime rt = Runtime.getRuntime();
rt.exec("open " + "C:\\Documents and Settings\\developer\\Desktop\\id.val");
} catch (Exception as) {
as.printStackTrace();
}
} else {
System.out.println("mar gaye");
}
}
}
}
| true
|
2b55be8b62d7ac4994648c7ef1f8c47d09c2870b
|
Java
|
Austin-Chow/SamsungClock10.0.04.3
|
/sources/com/samsung/android/sdk/sgi/ui/SGWidgetCamera.java
|
UTF-8
| 8,976
| 2.09375
| 2
|
[] |
no_license
|
package com.samsung.android.sdk.sgi.ui;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PreviewCallback;
import android.os.Handler;
import android.util.Log;
import com.samsung.android.sdk.sgi.base.SGVector2f;
import com.samsung.android.sdk.sgi.render.SGIntProperty;
import com.samsung.android.sdk.sgi.render.SGResourceShaderProperty;
import com.samsung.android.sdk.sgi.render.SGShaderProgramProperty;
import com.samsung.android.sdk.sgi.render.SGShaderType;
import com.samsung.android.sdk.sgi.render.SGSurfaceTextureProperty;
import com.samsung.android.sdk.sgi.render.SGSurfaceTextureProperty.SurfaceTextureCallback;
public class SGWidgetCamera extends SGWidgetImage {
private static final int BACK_CAMERA_FACE = 1;
private static final String CAMERA_FACE_NAME = "SGCameraFace";
private static final String CAMERA_ORIENTATION_NAME = "SGCameraOrientation";
private static final String FRAGMENT_SHADER_NAME = "Camera.frag";
private static final int FRONT_CAMERA_FACE = 0;
private static final String SURFACE_TEXTURE_PROPERTY = "SGTextureVideo";
private static final String TAG = SGWidgetCamera.class.getName();
private static final String VERTEX_SHADER_NAME = "Camera.vert";
private static final String VIDEO_RECT_PROPERTY = "SGVideoRect";
private CameraSurfaceTextureCallback mCameraSurfaceTextureCallback;
private DisplayOrientation mDisplayOrientation;
private SGShaderProgramProperty mShaderProgram;
private SGSurfaceTextureProperty mSurfaceTextureProperty;
private SGWidgetDecorator mWidgetDecorator;
private static class CameraSurfaceTextureCallback implements PreviewCallback, SurfaceTextureCallback {
private Camera mCamera = null;
private volatile int mCurrentCamera = 0;
private Handler mHandler;
private volatile boolean mIsPreviewStart = false;
private SGWidgetDecorator mSelf;
private SurfaceTexture mSurfaceTexture = null;
private OnActiveCameraChangedListener onActiveCameraChangedListener;
private static class HandlerRunnable implements Runnable {
private int mFace;
private SGWidgetDecorator mWd;
public HandlerRunnable(SGWidgetDecorator aWd, int aFace) {
this.mWd = aWd;
this.mFace = aFace;
}
public void run() {
this.mWd.setProperty(SGWidgetCamera.CAMERA_FACE_NAME, new SGIntProperty(this.mFace));
}
}
public CameraSurfaceTextureCallback(SGWidgetDecorator aSelf, Handler aHandler, int cameraId) {
checkCameraId(cameraId);
this.mHandler = aHandler;
this.mCurrentCamera = cameraId;
this.mSelf = aSelf;
}
private void createCamera(int cameraId) {
if (this.mSurfaceTexture == null) {
throw new IllegalStateException("SurfaceTexture isn't ready");
}
try {
synchronized (this) {
this.mCamera = Camera.open(cameraId);
this.mCamera.setPreviewTexture(this.mSurfaceTexture);
this.mCamera.setOneShotPreviewCallback(this);
this.mCamera.startPreview();
}
} catch (Exception e) {
Log.e(SGWidgetCamera.TAG, "Create camera failed!" + e.getMessage());
}
Log.d("MyDebug", "finish");
}
private boolean destroyCamera() {
try {
synchronized (this) {
if (this.mCamera == null) {
return false;
}
this.mCamera.stopPreview();
this.mCamera.setOneShotPreviewCallback(null);
this.mCamera.release();
this.mCamera = null;
return true;
}
} catch (Exception e) {
Log.d(SGWidgetCamera.TAG, "Destroy camera failed!" + e.getMessage());
return false;
}
}
public void checkCameraId(int cameraId) {
if (cameraId >= Camera.getNumberOfCameras() || cameraId < 0) {
throw new IllegalArgumentException("invalid Camera ID");
}
}
public Camera getCamera() {
return this.mCamera;
}
public boolean isPreviewStarted() {
return this.mIsPreviewStart;
}
public void onPreviewFrame(byte[] data, Camera camera) {
int faceOrientation = 1;
this.mIsPreviewStart = true;
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(this.mCurrentCamera, info);
if (info.facing == 0) {
faceOrientation = 0;
}
this.mHandler.post(new HandlerRunnable(this.mSelf, faceOrientation));
if (this.onActiveCameraChangedListener != null) {
this.onActiveCameraChangedListener.onActiveCameraChanged();
this.onActiveCameraChangedListener = null;
}
}
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture) {
synchronized (this) {
this.mSurfaceTexture = surfaceTexture;
}
createCamera(this.mCurrentCamera);
}
public void onSurfaceTextureDestroy() {
destroyCamera();
synchronized (this) {
this.mSurfaceTexture = null;
}
}
public void setActiveCamera(int cameraId) {
checkCameraId(cameraId);
boolean destroied = false;
if (this.mCamera != null) {
if (cameraId != this.mCurrentCamera) {
destroied = destroyCamera();
} else {
return;
}
}
if (destroied) {
this.mCurrentCamera = cameraId;
createCamera(this.mCurrentCamera);
}
}
public void setActiveCameraChangedListener(OnActiveCameraChangedListener listener) {
this.onActiveCameraChangedListener = listener;
}
}
public enum DisplayOrientation {
LANDSCAPE,
PORTRAIT
}
public interface OnActiveCameraChangedListener {
void onActiveCameraChanged();
}
public SGWidgetCamera(SGVector2f size, int aCameraId) {
this(size, DisplayOrientation.LANDSCAPE, aCameraId);
}
public SGWidgetCamera(SGVector2f size, DisplayOrientation aDefaultOrientation, int aCameraId) {
super(size, -1);
this.mDisplayOrientation = DisplayOrientation.LANDSCAPE;
this.mDisplayOrientation = aDefaultOrientation;
this.mWidgetDecorator = new SGWidgetDecorator(this);
this.mCameraSurfaceTextureCallback = new CameraSurfaceTextureCallback(this.mWidgetDecorator, new Handler(), aCameraId);
this.mSurfaceTextureProperty = new SGSurfaceTextureProperty(this.mCameraSurfaceTextureCallback, VIDEO_RECT_PROPERTY);
this.mShaderProgram = new SGShaderProgramProperty(new SGResourceShaderProperty(SGShaderType.VERTEX, VERTEX_SHADER_NAME), new SGResourceShaderProperty(SGShaderType.FRAGMENT, FRAGMENT_SHADER_NAME));
SGIntProperty SGCameraOrientation = new SGIntProperty(aDefaultOrientation.ordinal());
SGIntProperty SGCameraFace = new SGIntProperty(aCameraId % 2 == 0 ? 0 : 1);
this.mWidgetDecorator.setProgramProperty(this.mShaderProgram);
this.mWidgetDecorator.setProperty(SURFACE_TEXTURE_PROPERTY, this.mSurfaceTextureProperty);
this.mWidgetDecorator.setProperty(CAMERA_FACE_NAME, SGCameraFace);
this.mWidgetDecorator.setProperty(CAMERA_ORIENTATION_NAME, SGCameraOrientation);
}
public final boolean canSwitchCamera() {
return this.mCameraSurfaceTextureCallback.isPreviewStarted();
}
public void finalize() {
super.finalize();
this.mCameraSurfaceTextureCallback.destroyCamera();
}
public final Camera getCamera() {
return this.mCameraSurfaceTextureCallback.getCamera();
}
public final boolean releaseCamera() {
return this.mCameraSurfaceTextureCallback.destroyCamera();
}
public final void setActiveCamera(int cameraId, OnActiveCameraChangedListener listener) {
this.mCameraSurfaceTextureCallback.setActiveCameraChangedListener(listener);
this.mCameraSurfaceTextureCallback.setActiveCamera(cameraId);
}
public void updateDisplayOrientation(DisplayOrientation aDisplayOrientation) {
if (this.mDisplayOrientation != aDisplayOrientation) {
this.mWidgetDecorator.setProperty(CAMERA_ORIENTATION_NAME, new SGIntProperty(aDisplayOrientation.ordinal()));
this.mDisplayOrientation = aDisplayOrientation;
}
}
}
| true
|
49739a7efa7bc39bf817ee11a1efac5e050f7d46
|
Java
|
ArchanaChillala/iwp-java-examples
|
/Wallet/src/Wallet.java
|
UTF-8
| 642
| 3.328125
| 3
|
[] |
no_license
|
public class Wallet {
private double balance;
public Wallet() {
balance = 0;
}
double getBalance() {
return balance;
}
boolean validateAndCredit(double amount) {
if (amount > 0) {
credit(amount);
return true;
}
return false;
}
private void credit(double amount) {
balance += amount;
}
boolean validateAndDebit(double amount) {
if (balance > amount) {
debit(amount);
return true;
}
return false;
}
private void debit(double amount) {
balance -= amount;
}
}
| true
|
7515a3fd7fe8ade642e5cf5cf504f981ac48e95d
|
Java
|
jiangdc/EasyStage
|
/core/src/com/ayocrazy/easystage/bean/ActorBean.java
|
UTF-8
| 1,846
| 2.1875
| 2
|
[] |
no_license
|
package com.ayocrazy.easystage.bean;
import com.ayocrazy.easystage.uimeta.MetaCheckBox;
import com.ayocrazy.easystage.uimeta.MetaTable;
import com.ayocrazy.easystage.uimeta.MetaText;
import com.ayocrazy.easystage.uimeta.MetaVector;
import java.io.Serializable;
/**
* Created by ayo on 2017/1/11.
*/
public class ActorBean implements Serializable {
@MetaText
private int childrenSize;
@MetaText
private String name, id, parentName;
@MetaVector(editable = true, size = 4, prefix = {'r', 'g', 'b', 'a'})
private float[] color;
@MetaCheckBox
private boolean visible, debug;
@MetaTable
private TransformBean transform;
public int getChildrenSize() {
return childrenSize;
}
public void setChildrenSize(int childrenSize) {
this.childrenSize = childrenSize;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public float[] getColor() {
return color;
}
public void setColor(float[] color) {
this.color = color;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public TransformBean getTransform() {
return transform;
}
public void setTransform(TransformBean transform) {
this.transform = transform;
}
}
| true
|
3b1394e82f3f10ab04a100221da247dabe713791
|
Java
|
Mkabaka/esa-servicekeeper
|
/servicekeeper-configsource/servicekeeper-configsource-file/src/main/java/io/esastack/servicekeeper/configsource/file/constant/ExternalConfigName.java
|
UTF-8
| 11,225
| 1.796875
| 2
|
[
"Apache-2.0",
"EPL-1.0",
"Classpath-exception-2.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-oracle-openjdk-exception-2.0",
"MPL-1.1",
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause",
"LGPL-2.1-only",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"CDDL-1.1",
"LicenseRef-scancode-unknown-license-reference",
"EPL-2.0",
"GPL-2.0-or-later",
"MIT",
"MPL-1.0"
] |
permissive
|
/*
* Copyright 2021 OPPO ESA Stack 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 io.esastack.servicekeeper.configsource.file.constant;
import esa.commons.StringUtils;
import io.esastack.servicekeeper.configsource.file.utils.GroupItemUtils;
import io.esastack.servicekeeper.configsource.utils.ClassConvertUtils;
import io.esastack.servicekeeper.core.configsource.ExternalConfig;
import io.esastack.servicekeeper.core.configsource.ExternalGroupConfig;
import io.esastack.servicekeeper.core.utils.ClassCastUtils;
import io.esastack.servicekeeper.core.utils.DurationUtils;
import io.esastack.servicekeeper.core.utils.ParamCheckUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public enum ExternalConfigName {
/**
* maxConcurrentLimit
*/
MAX_CONCURRENT_LIMIT("maxConcurrentLimit") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final int maxConcurrentLimit = Integer.parseInt(value);
ParamCheckUtils.notNegativeInt(maxConcurrentLimit,
this.buildErrorMsg("must not be an negative number", maxConcurrentLimit));
config.setMaxConcurrentLimit(maxConcurrentLimit);
}
},
/**
* limitForPeriod
*/
LIMIT_FOR_PERIOD("limitForPeriod") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final int limitForPeriod = Integer.parseInt(value);
ParamCheckUtils.positiveInt(limitForPeriod,
this.buildErrorMsg("must greater than 0", limitForPeriod));
config.setLimitForPeriod(Integer.valueOf(value));
}
},
/**
* limitRefreshPeriod
*/
LIMIT_REFRESH_PERIOD("limitRefreshPeriod") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setLimitRefreshPeriod(DurationUtils.parse(value));
}
},
/**
* failureRateThreshold
*/
FAILURE_RATE_THRESHOLD("failureRateThreshold") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final float failureRateThreshold = Float.parseFloat(value);
ParamCheckUtils.legalFailureThreshold(failureRateThreshold,
this.buildErrorMsg("must between [0, 100]", failureRateThreshold));
config.setFailureRateThreshold(Float.valueOf(value));
}
},
/**
* ringBufferSizeInClosedState
*/
RING_BUFFER_SIZE_IN_CLOSED_STATE("ringBufferSizeInClosedState") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final int ringBufferSizeInClosedState = Integer.parseInt(value);
ParamCheckUtils.positiveInt(ringBufferSizeInClosedState,
this.buildErrorMsg("must greater than 0", ringBufferSizeInClosedState));
config.setRingBufferSizeInClosedState(Integer.valueOf(value));
}
},
/**
* ringBufferSizeInHalfOpenState
*/
RING_BUFFER_SIZE_IN_HALF_OPEN_STATE("ringBufferSizeInHalfOpenState") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final int ringBufferSizeInHalfOpenState = Integer.parseInt(value);
ParamCheckUtils.positiveInt(ringBufferSizeInHalfOpenState,
this.buildErrorMsg("must greater than 0", ringBufferSizeInHalfOpenState));
config.setRingBufferSizeInHalfOpenState(Integer.valueOf(value));
}
},
/**
* waitDurationInOpenState
*/
WAIT_DURATION_IN_OPEN_STATE("waitDurationInOpenState") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setWaitDurationInOpenState(DurationUtils.parse(value));
}
},
/**
* ignoreExceptions
*/
IGNORE_EXCEPTIONS("ignoreExceptions") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setIgnoreExceptions(ClassCastUtils.cast(ClassConvertUtils.toClasses(value)));
}
},
/**
* maxSpendTimeMs
*/
MAX_SPEND_TIME_MS("maxSpendTimeMs") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final long maxSpendTimeMs = Long.parseLong(value);
ParamCheckUtils.positiveLong(maxSpendTimeMs,
this.buildErrorMsg("must greater than 0", maxSpendTimeMs));
config.setMaxSpendTimeMs(Long.valueOf(value));
}
},
/**
* forcedOpen
*/
FORCED_OPEN("forcedOpen") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setForcedDisabled(null);
config.setForcedOpen(Boolean.valueOf(value));
}
},
/**
* forcedDisabled
*/
FORCED_DISABLED("forcedDisabled") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setForcedOpen(null);
config.setForcedDisabled(Boolean.valueOf(value));
}
},
/**
* predicateStrategy
*/
PREDICATE_STRATEGY("predicateStrategy") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setPredicateStrategy(ClassCastUtils.cast(ClassConvertUtils.toClasses(value)[0]));
}
},
/**
* fallbackMethod
*/
FALLBACK_METHOD("fallbackMethod") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setFallbackMethodName(value);
}
},
/**
* fallbackClass
*/
FALLBACK_CLASS("fallbackClass") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setFallbackClass(ClassConvertUtils.toClasses(value)[0]);
}
},
/**
* fallbackValue
*/
FALLBACK_VALUE("fallbackValue") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setFallbackValue(value);
}
},
/**
* fallbackExceptionClass
*/
FALLBACK_EXCEPTION_CLASS("fallbackExceptionClass") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setFallbackExceptionClass(ClassCastUtils.cast(ClassConvertUtils.toClasses(value)[0]));
}
},
/**
* alsoApplyToBizException
*/
ALSO_APPLY_FALLBACK_TO_BIZ_EXCEPTION("alsoApplyFallbackToBizException") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setAlsoApplyFallbackToBizException(
Boolean.valueOf(value));
}
},
/**
* includeExceptions
*/
RETRY_INCLUDE_EXCEPTIONS("includeExceptions") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setIncludeExceptions(ClassCastUtils.cast(ClassConvertUtils.toClasses(value)));
}
},
/**
* excludeExceptions
*/
RETRY_EXCLUDE_EXCEPTIONS("excludeExceptions") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
config.setExcludeExceptions(ClassCastUtils.cast(ClassConvertUtils.toClasses(value)));
}
},
/**
* maxAttempts
*/
RETRY_MAX_ATTEMPTS("maxAttempts") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final int maxAttempts = Integer.parseInt(value);
ParamCheckUtils.notNegativeInt(maxAttempts,
this.buildErrorMsg("must not be an negative number", maxAttempts));
config.setMaxAttempts(maxAttempts);
}
},
/**
* delay
*/
RETRY_DELAY("delay") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final long delay = Long.parseLong(value);
ParamCheckUtils.notNegativeLong(delay,
this.buildErrorMsg("must not be an negative number", delay));
config.setDelay(delay);
}
},
/**
* maxDelay
*/
RETRY_MAX_DELAY("maxDelay") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final long maxDelay = Long.parseLong(value);
ParamCheckUtils.notNegativeLong(maxDelay,
this.buildErrorMsg("must not be an negative number", maxDelay));
config.setMaxDelay(maxDelay);
}
},
/**
* multiplier
*/
RETRY_MULTIPLIER("multiplier") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
final double multiplier = Double.parseDouble(value);
ParamCheckUtils.notNegativeDouble(multiplier,
this.buildErrorMsg("must not be an negative number", multiplier));
config.setMultiplier(multiplier);
}
},
/**
* items
*/
GROUP_ITEMS("items") {
@Override
public void applyConfigValue(ExternalConfig config, String value) {
if (!(config instanceof ExternalGroupConfig)) {
return;
}
if (StringUtils.isEmpty(value)) {
return;
}
ExternalGroupConfig groupConfig = (ExternalGroupConfig) config;
groupConfig.setItems(GroupItemUtils.parseToItems(value));
}
};
public static final Map<String, ExternalConfigName> CONFIG_NAME_MAP = new ConcurrentHashMap<>(values().length);
static {
Arrays.stream(values()).forEach((configName) -> CONFIG_NAME_MAP.putIfAbsent(configName.name, configName));
}
private final String name;
ExternalConfigName(String name) {
this.name = name;
}
public static ExternalConfigName getByName(String name) {
return CONFIG_NAME_MAP.get(name);
}
public String getName() {
return name;
}
public abstract void applyConfigValue(ExternalConfig config, String value);
/**
* build error message with a template
*
* @param message tips
* @param currentValue current value
* @return error msg
*/
protected String buildErrorMsg(String message, Object currentValue) {
return this.getName() + " " + message + " current value : " + currentValue;
}
@Override
public String toString() {
return name;
}
}
| true
|
7e5935a7c1ce46056615e24067338deccf3579b0
|
Java
|
Flaxen/IV1351-datalagring
|
/application/src/main/java/se/kth/iv1351/jdbcintro/view.java
|
UTF-8
| 3,963
| 2.453125
| 2
|
[
"MIT"
] |
permissive
|
/*
* The MIT License (MIT)
* Copyright (c) 2020 Leif Lindbäck
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction,including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so,subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.kth.iv1351.jdbcintro;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class view {
private static Connection createConnection() throws SQLException, ClassNotFoundException {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/soundgood",
"postgres", "example");
connection.setAutoCommit(false);
return connection;
}
public static void main(String[] args) {
int currentUser = 0;
try (Connection connection = createConnection()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connected to SGRSa1");
String input;
loop: while(true) {
System.out.print("soundgood rental system a1.4356$ ");
input = reader.readLine();
String[] ia = input.split(" ");
Controller controller = new Controller();
switch(ia[0]) {
case "exit":
break loop;
case "commands":
System.out.println("Commands: exit, login, list_available, list_rentals, rent, terminate");
break;
case "login":
if (ia.length > 1) {
currentUser = controller.login(Integer.parseInt(ia[1]), connection);
} else {
controller.login();
}
break;
case "list_available":
if(ia.length > 1) {
controller.listAvailable(connection, ia[1]);
} else {
controller.listAvailable(connection);
}
break;
case "list_rentals":
controller.listRentals(connection, currentUser);
break;
case "rent":
if (ia.length > 1) {
controller.rent(connection, currentUser, Integer.parseInt(ia[1]));
} else {
controller.rent();
}
break;
case "terminate":
if (ia.length > 1) {
controller.terminate(connection, currentUser, Integer.parseInt(ia[1]));
} else {
controller.terminate();
}
break;
default:
System.out.println("Invalid command, type 'commands' to list all commands");
break;
}
}
connection.close();
} catch (SQLException | ClassNotFoundException | IOException | NumberFormatException exc) {
exc.printStackTrace();
}
System.out.println("closing soundgood renting system a1.4356..");
}
}
| true
|
dd77b826b8e227e99084056df77546b749271592
|
Java
|
rengang66/quarkus-sample-gof23
|
/src/main/java/com/iiit/quarkus/sample/gof23/Gof23StructuralPatternSource.java
|
UTF-8
| 2,883
| 2
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.iiit.quarkus.sample.gof23;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.iiit.quarkus.sample.gof23.structuralpattern.adapter.AdapterClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.bridge.BridgeClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.composite.CompositeClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.decorator.DecoratorClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.facade.FacadeClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.flyweight.FlyweightClient;
import com.iiit.quarkus.sample.gof23.structuralpattern.proxy.ProxyClient;
@Path("/gof23")
public class Gof23StructuralPatternSource {
@Inject AdapterClient adapterClient;
@Inject BridgeClient bridgeClient;
@Inject CompositeClient compositeClient;
@Inject DecoratorClient decoratorClient;
@Inject FacadeClient facadeClient;
@Inject FlyweightClient flyweightClient;
@Inject ProxyClient proxyClient;
public Gof23StructuralPatternSource() {
}
@GET
@Path("/adapter")
@Produces(MediaType.TEXT_PLAIN)
public String adapterClient() {
adapterClient.run("adapterClient");
return "adapter is running OK;";
}
@GET
@Path("/bridge")
@Produces(MediaType.TEXT_PLAIN)
public String bridgeClient() {
bridgeClient.run("bridgeClient");
return "bridge is running OK;";
}
@GET
@Path("/composite")
@Produces(MediaType.TEXT_PLAIN)
public String compositeClient() {
compositeClient.run("compositeClient");
return "composite is running OK;";
}
@GET
@Path("/decorator")
@Produces(MediaType.TEXT_PLAIN)
public String decoratorClient() {
decoratorClient.run("decoratorClient");
return "decorator is running OK;";
}
@GET
@Path("/facade")
@Produces(MediaType.TEXT_PLAIN)
public String facadeClient() {
facadeClient.run("facadeClient");
return "facade is running OK;";
}
@GET
@Path("/flyweight")
@Produces(MediaType.TEXT_PLAIN)
public String flyweightClient() {
flyweightClient.run("flyweightClient");
return "flyweight is running OK;";
}
@GET
@Path("/proxy")
@Produces(MediaType.TEXT_PLAIN)
public String proxyClient() {
proxyClient.run("proxyClient");
return "proxy is running OK;";
}
}
| true
|
cbdcb3d718a59fa6049b96058f5098994929ccd0
|
Java
|
Cloudifacturing-eu/nexus-repository-cfg
|
/src/main/java/eu/cloudifacturing/www/repository/rest/internal/resources/doc/RepositoriesResourceDoc.java
|
UTF-8
| 698
| 2.21875
| 2
|
[] |
no_license
|
package eu.cloudifacturing.www.repository.rest.internal.resources.doc;
import eu.cloudifacturing.www.repository.rest.api.RepositoryXO;
import io.swagger.annotations.*;
import java.util.List;
@Api(value = "CFG Repositories")
public interface RepositoriesResourceDoc
{
@ApiOperation("List repositories")
List<RepositoryXO> getRepositories();
@ApiOperation("Get repository by id")
@ApiResponses(value = {
@ApiResponse(code = 403, message = "Insufficient permissions to get repository"),
@ApiResponse(code = 404, message = "Repository not found")
})
RepositoryXO getRepositoryById(@ApiParam(value = "Id of the repository to get") final String id);
}
| true
|
b3fbe77621eb1d90cc9471cf9d5afb01b582bf48
|
Java
|
artembilan/spring-integration-samples
|
/basic/barrier/src/main/java/org/springframework/integration/samples/barrier/Application.java
|
UTF-8
| 2,167
| 2.078125
| 2
|
[] |
no_license
|
/*
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.integration.samples.barrier;
import java.util.Collections;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;
/**
* @author Gary Russell
* @since 4.2
*/
@SpringBootApplication
@ImportResource("/META-INF/spring/integration/server-context.xml")
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext server = SpringApplication.run(Application.class, args);
runClient(args);
server.close();
}
static void runClient(String[] args) {
SpringApplication application = new SpringApplicationBuilder()
.web(WebApplicationType.NONE)
.bannerMode(Mode.OFF)
.application();
application.setSources(Collections.singleton("/META-INF/spring/integration/client-context.xml"));
ConfigurableApplicationContext client = application.run(args);
RequestGateway requestGateway = client.getBean("requestGateway", RequestGateway.class);
String request = "A,B,C";
System.out.println("\n\n++++++++++++ Sending: " + request + " ++++++++++++\n");
String reply = requestGateway.echo(request);
System.out.println("\n\n++++++++++++ Replied with: " + reply + " ++++++++++++\n");
client.close();
}
}
| true
|
70acf27c4dc64bb6b3f69d5423d2359bbdf7fe87
|
Java
|
HenryHernandes/unidad3
|
/Ejemplo02.java
|
UTF-8
| 276
| 2.8125
| 3
|
[] |
no_license
|
import java.util.*;
public class Ejemplo02{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("nota");
int nota = sc.nextInt();
if(nota>=7){
System.out.println("en hora buena");
System.out.println("haz aprobado");
}
}
}
| true
|
af8eb6f8ed97c08ed1780e4c092c3b7556a2b3e0
|
Java
|
wuha-io/suffixTree
|
/src/Main.java
|
UTF-8
| 191
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
import java.util.Map;
import java.util.Iterator;
class Main {
public static void main(String ...args) throws Exception {
Server server = new Server(3010);
server.start();
}
}
| true
|
f177fa5a9cf621d9b7a5a273de2cb0a10a5dae61
|
Java
|
elveahuang/platform
|
/platform-commons/commons-core/src/main/java/cn/elvea/platform/commons/core/data/mongodb/repository/BaseEntityRepository.java
|
UTF-8
| 660
| 1.789063
| 2
|
[] |
no_license
|
package cn.elvea.platform.commons.core.data.mongodb.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.Repository;
/**
* @param <T> 实体
* @param <K> 主键
* @author elvea
* @see MongoRepository
* @see PagingAndSortingRepository
* @see CrudRepository
* @see Repository
* @since 0.0.1
*/
@NoRepositoryBean
public interface BaseEntityRepository<T, K> extends MongoRepository<T, K> {
}
| true
|
2baab219484f4e6078f18f627f6b92b94527f017
|
Java
|
idSaid/BibalSpringMVC
|
/src/main/java/com/bibal/service/interfaces/LivreService.java
|
UTF-8
| 501
| 2.0625
| 2
|
[] |
no_license
|
package com.bibal.service.interfaces;
import java.util.List;
import com.bibal.metier.Livre;
public interface LivreService {
public Livre addLivre(String nom, String thematique, String ecrivain);
public List<Livre> findAll();
public Livre getById(Long id);
public List<Livre> searchByName(String nom);
public List<Livre> searchByAuthor(String author);
public List<Livre> searchByThematique(String thematique);
public void update(Long id, String nom, String thematique, String ecrivain);
}
| true
|
b1fed89e20935d9498e6d1b5a168ffba0fc0c862
|
Java
|
loop-study/JavaStudy06
|
/src/com/example/study/Car.java
|
UTF-8
| 446
| 3.140625
| 3
|
[] |
no_license
|
package com.example.study;
public class Car {
public String model;
public String color;
public String maxSpeed;
public Car() {
this("승용차", "검정", "200");
}
public Car(String model, String color, String maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
public void move() {
System.out.println(this.model + "가 이동중");
}
}
| true
|
485f9e1a39ea4533c779463a323faa6bdcbeee3d
|
Java
|
qiniulab/android-sdk-cronet
|
/library/src/androidTest/java/com/qiniu/android/common/AutoZoneTest.java
|
UTF-8
| 2,504
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package com.qiniu.android.common;
import android.test.AndroidTestCase;
import android.util.Log;
import com.qiniu.android.TestConfig;
import junit.framework.Assert;
import java.util.concurrent.CountDownLatch;
/**
* Created by long on 2016/9/30.
*/
public class AutoZoneTest extends AndroidTestCase {
private String ak = TestConfig.ak;
private String bkt = "javasdk";
public void testHttp() {
AutoZone zone = new AutoZone(null);
final CountDownLatch countDownLatch = new CountDownLatch(1);
zone.preQueryIndex(new AutoZone.ZoneIndex(ak, bkt), new Zone.QueryHandler() {
@Override
public void onSuccess() {
countDownLatch.countDown();
}
@Override
public void onFailure(int reason) {
countDownLatch.countDown();
fail();
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
ZoneInfo zoneInfo = zone.zoneInfo(ak, bkt);
assertTrue(zoneInfo.upDomainsList.contains("upload.qiniup.com"));
assertTrue(zoneInfo.upDomainsList.contains("up.qiniup.com"));
assertTrue(zoneInfo.upDomainsList.contains("upload-nb.qiniup.com"));
}
public void testHttpFail() {
AutoZone zone = new AutoZone(null);
ZoneInfo zoneInfo = zone.zoneInfo(ak + "_not_be_ak", bkt);
assertNull(zoneInfo);
}
public void testSplitE() {
String s1 = "bkt:key";
String s2 = "bkt";
Assert.assertEquals(s1.split(":")[0], s2.split(":")[0]);
}
public void testC1() {
AutoZone autoZone = new AutoZone(null);
final CountDownLatch countDownLatch = new CountDownLatch(1);
autoZone.preQueryIndex(new AutoZone.ZoneIndex(ak, bkt), new Zone.QueryHandler() {
@Override
public void onSuccess() {
countDownLatch.countDown();
}
@Override
public void onFailure(int reason) {
countDownLatch.countDown();
fail();
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
ZoneInfo info = autoZone.zoneInfo(ak, bkt);
Log.d("zone0: ", info.toString());
ZoneInfo info2 = autoZone.zoneInfo(ak, bkt);
Assert.assertSame(info, info2);
}
}
| true
|
131afa8b5d826dd748dc85df7c7e846c1267b1d6
|
Java
|
ledpear/algorithm
|
/BAEKJOON/10000~/10026_적록색약_java/Main.java
|
UTF-8
| 3,067
| 3.328125
| 3
|
[] |
no_license
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int size = Integer.parseInt(br.readLine());
ArrayList<String > matrix = new ArrayList<>();
for(int i = 0; i < size; ++i)
{
matrix.add(br.readLine());
}
Solution solution = new Solution();
Integer[] answer = solution.solution(size, matrix);
System.out.println(Integer.toString(answer[0]) + ' ' + Integer.toString(answer[1]));
}
}
class Solution {
Integer[] move_x = {1, -1, 0, 0};
Integer[] move_y = {0, 0, 1, -1};
boolean[][] visit;
int size;
ArrayList<String> matrix;
public Integer[] solution(int size, ArrayList<String> matrix){
Integer[] answer = new Integer[2];
this.size = size;
this.matrix = matrix;
int count = 0;
visit = new boolean[size][size];
for(int x = 0; x < size; ++x){
for(int y = 0; y < size; ++y){
if(!visit[x][y]){
++count;
Character[] checks = {matrix.get(x).charAt(y)};
BFS(x, y, checks);
}
}
}
answer[0] = count;
count = 0;
visit = new boolean[size][size];
for(int x = 0; x < size; ++x){
for(int y = 0; y < size; ++y){
if(!visit[x][y]){
++count;
Character[] checks;
if(matrix.get(x).charAt(y) == 'R' || matrix.get(x).charAt(y) == 'G'){
checks = new Character[]{'R', 'G'};
}
else{
checks = new Character[]{'B'};
}
BFS(x, y, checks);
}
}
}
answer[1] = count;
return answer;
}
public void BFS(int x, int y, Character[] checks){
Queue<int[]> queue = new LinkedList<>();
visit[x][y] = true;
int[] temp = new int[2];
temp[0] = x;
temp[1] = y;
queue.add(temp);
while(!queue.isEmpty()){
int[] now_pos = queue.poll();
for(int i = 0; i < 4; ++i){
int pos_x = now_pos[0] + move_x[i];
int pos_y = now_pos[1] + move_y[i];
if(pos_x >= 0 && pos_y >= 0 && pos_x < size && pos_y < size && !visit[pos_x][pos_y]){
for(Character check : checks){
if(matrix.get(pos_x).charAt(pos_y) == check){
visit[pos_x][pos_y] = true;
temp = new int[2];
temp[0] = pos_x;
temp[1] = pos_y;
queue.add(temp);
break;
}
}
}
}
}
}
}
| true
|
5c70d15f2a7ebb75596dfee37c70f48481f13731
|
Java
|
gaurabde/Projects
|
/CloudProject/Neocloud/RDSPushCode/src/Phase-1_Code/EbaySearch.java
|
UTF-8
| 2,344
| 2.421875
| 2
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
import com.ebay.services.client.ClientConfig;
import com.ebay.services.client.FindingServiceClientFactory;
import com.ebay.services.finding.Amount;
import com.ebay.services.finding.FindItemsByKeywordsRequest;
import com.ebay.services.finding.FindItemsByKeywordsResponse;
import com.ebay.services.finding.FindingServicePortType;
import com.ebay.services.finding.PaginationInput;
import com.ebay.services.finding.SearchItem;
public class EbaySearch
{
ArrayList<ResultItem> runEbaySearch (String keyword)
{
System.out.println("searching for: "+keyword);
ArrayList<ResultItem> jsp_result = new ArrayList<ResultItem>();
// initialize service end-point configuration
ClientConfig config = new ClientConfig();
// endpoint address can be overwritten here, by default, production address is used,
// to enable sandbox endpoint, just uncomment the following line
//config.setEndPointAddress("http://svcs.sandbox.ebay.com/services/search/FindingService/v1");
config.setApplicationId("AbhijitV-89b3-445e-b001-53c9adb2b8bc");
//create a service client
FindingServicePortType serviceClient = FindingServiceClientFactory.getServiceClient(config);
//create request object
FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();
//set request parameters
request.setKeywords(keyword);
PaginationInput pi = new PaginationInput();
pi.setEntriesPerPage(2);
request.setPaginationInput(pi);
//call service
FindItemsByKeywordsResponse result = serviceClient.findItemsByKeywords(request);
//output result
System.out.println("Ack = "+result.getAck());
System.out.println("Find " + result.getSearchResult().getCount() + " items." );
List<SearchItem> items = result.getSearchResult().getItem();
Amount a;
for(SearchItem item : items)
{
System.out.println(item.getTitle()+" ... "+item.getViewItemURL());
a = item.getSellingStatus().getConvertedCurrentPrice();
System.out.println(a.getValue());
ResultItem temp = new ResultItem(item.getTitle(), a.getValue(), item.getViewItemURL());
jsp_result.add(temp);
}
return jsp_result;
}
}
| true
|
7a28081ab3ce3fd4d1d2a561340a27cd1ee1b9f8
|
Java
|
meng0195/fp
|
/zndc/src/cn/com/bjggs/ctr/domain/SmartStatus.java
|
UTF-8
| 5,193
| 1.976563
| 2
|
[] |
no_license
|
package cn.com.bjggs.ctr.domain;
import org.nutz.dao.entity.annotation.Comment;
@Comment("仓房模式配置")
public class SmartStatus {
private int status_1;
private int status_2;
private int status_3;
private int status_4;
private int status_5;
private int status_6;
private int status_7;
private int status_8;
private String equip_1;
private String equip_2;
private String equip_3;
private String equip_4;
private String equip_5;
private String equip_6;
private String equip_7;
private String equipName_1;
private String equipName_2;
private String equipName_3;
private String equipName_4;
private String equipName_5;
private String equipName_6;
private String equipName_7;
private String houseNo;
private double[] param1;
private double[] param2;
public int getStatus_1() {
return status_1;
}
public void setStatus_1(int status_1) {
this.status_1 = status_1;
}
public int getStatus_2() {
return status_2;
}
public void setStatus_2(int status_2) {
this.status_2 = status_2;
}
public int getStatus_3() {
return status_3;
}
public void setStatus_3(int status_3) {
this.status_3 = status_3;
}
public int getStatus_4() {
return status_4;
}
public void setStatus_4(int status_4) {
this.status_4 = status_4;
}
public int getStatus_5() {
return status_5;
}
public void setStatus_5(int status_5) {
this.status_5 = status_5;
}
public int getStatus_6() {
return status_6;
}
public void setStatus_6(int status_6) {
this.status_6 = status_6;
}
public int getStatus_7() {
return status_7;
}
public void setStatus_7(int status_7) {
this.status_7 = status_7;
}
public int getStatus_8() {
return status_8;
}
public void setStatus_8(int status_8) {
this.status_8 = status_8;
}
public double[] getParam1() {
return param1;
}
public void setParam1(double[] param1) {
this.param1 = param1;
}
public double[] getParam2() {
return param2;
}
public void setParam2(double[] param2) {
this.param2 = param2;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getEquip_1() {
return equip_1;
}
public void setEquip_1(String equip_1) {
this.equip_1 = equip_1;
}
public String getEquip_2() {
return equip_2;
}
public void setEquip_2(String equip_2) {
this.equip_2 = equip_2;
}
public String getEquip_3() {
return equip_3;
}
public void setEquip_3(String equip_3) {
this.equip_3 = equip_3;
}
public String getEquip_4() {
return equip_4;
}
public void setEquip_4(String equip_4) {
this.equip_4 = equip_4;
}
public String getEquip_5() {
return equip_5;
}
public void setEquip_5(String equip_5) {
this.equip_5 = equip_5;
}
public String getEquip_6() {
return equip_6;
}
public void setEquip_6(String equip_6) {
this.equip_6 = equip_6;
}
public String getEquip_7() {
return equip_7;
}
public void setEquip_7(String equip_7) {
this.equip_7 = equip_7;
}
public String getEquipName_1() {
return equipName_1;
}
public void setEquipName_1(String equipName_1) {
this.equipName_1 = equipName_1;
}
public String getEquipName_2() {
return equipName_2;
}
public void setEquipName_2(String equipName_2) {
this.equipName_2 = equipName_2;
}
public String getEquipName_3() {
return equipName_3;
}
public void setEquipName_3(String equipName_3) {
this.equipName_3 = equipName_3;
}
public String getEquipName_4() {
return equipName_4;
}
public void setEquipName_4(String equipName_4) {
this.equipName_4 = equipName_4;
}
public String getEquipName_5() {
return equipName_5;
}
public void setEquipName_5(String equipName_5) {
this.equipName_5 = equipName_5;
}
public String getEquipName_6() {
return equipName_6;
}
public void setEquipName_6(String equipName_6) {
this.equipName_6 = equipName_6;
}
public String getEquipName_7() {
return equipName_7;
}
public void setEquipName_7(String equipName_7) {
this.equipName_7 = equipName_7;
}
public int getStatus(int i){
switch (i) {
case 0: return this.status_1;
case 1: return this.status_2;
case 2: return this.status_3;
case 3: return this.status_4;
case 4: return this.status_5;
case 5: return this.status_6;
case 6: return this.status_7;
case 7: return this.status_7;
default: return 0;
}
}
public String getEquips(int i){
switch (i) {
case 0: return this.equip_1;
case 1: return this.equip_2;
case 2: return this.equip_3;
case 3: return this.equip_4;
case 4: return this.equip_5;
case 5: return this.equip_6;
case 6: return this.equip_7;
default: return "";
}
}
public String getEquipNames(int i){
switch (i) {
case 0: return this.equipName_1;
case 1: return this.equipName_2;
case 2: return this.equipName_3;
case 3: return this.equipName_4;
case 4: return this.equipName_5;
case 5: return this.equipName_6;
case 6: return this.equipName_7;
default: return "";
}
}
}
| true
|
95d5e019dfa1cc7c9b203855eef572f1faff3aa8
|
Java
|
SpazNull/LightsOut
|
/GridLayoutFrame.java
|
UTF-8
| 3,439
| 3.125
| 3
|
[] |
no_license
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class GridLayoutFrame extends JFrame implements ActionListener
{
private final JButton[] buttons;
private static final String[] names = {"###", ".", "###", ".", ".", "###", "###", ".", "."};
//private boolean toggle = true;
private final Container container;
private final GridLayout gridLayout;
private boolean[] on = { true, false, true, false, false, true, true, false, false };
private boolean won;
// default constructor
public GridLayoutFrame()
{
super("Lights out!");
gridLayout = new GridLayout(3, 3, 5, 5);
container = getContentPane();
setLayout(gridLayout);
buttons = new JButton[names.length];
won = false;
for (int i = 0; i < names.length; i++)
{
buttons[i] = new JButton(names[i]);
buttons[i].addActionListener(this);// register listener
add(buttons[i]);// add button to the JFrame
}
// for button text, use the text data member!
}
// handle button events by toggling between layouts
@Override
public void actionPerformed(ActionEvent event)
{
Object src = event.getSource();
if (src == buttons[0])// if the top left button was clicked
{
on[0] = !on[0];// switching each boolean value to the opposite
on[1] = !on[1];
on[3] = !on[3];
}
else if (src == buttons[1])// if the top middle button was clicked
{
on[1] = !on[1];// switching each boolean value to the opposite
on[0] = !on[0];
on[2] = !on[2];
on[4] = !on[4];
}
else if (src == buttons[2])// if the top right button was clicked
{
on[2] = !on[2];// switching each boolean value to the opposite
on[1] = !on[1];
on[5] = !on[5];
}
else if (src == buttons[3])// if the left button was clicked
{
on[3] = !on[3];// switching each boolean value to the opposite
on[0] = !on[0];
on[4] = !on[4];
on[6] = !on[6];
}
else if (src == buttons[4])// if the middle button was clicked
{
on[4] = !on[4];// switching each boolean value to the opposite
on[1] = !on[1];
on[3] = !on[3];
on[5] = !on[5];
on[7] = !on[7];
}
else if (src == buttons[5])// if the right button was clicked
{
on[5] = !on[5];// switching each boolean value to the opposite
on[2] = !on[2];
on[4] = !on[4];
on[8] = !on[8];
}
else if (src == buttons[6])// if the bottom left button was clicked
{
on[6] = !on[6];// switching each boolean value to the opposite
on[3] = !on[3];
on[7] = !on[7];
}
else if (src == buttons[7])// if the bottom button was clicked
{
on[7] = !on[7];// switching each boolean value to the opposite
on[4] = !on[4];
on[6] = !on[6];
on[8] = !on[8];
}
else// if the bottom right button was clicked
{
on[8] = !on[8];// switching each boolean value to the opposite
on[5] = !on[5];
on[7] = !on[7];
}
// now, time to set each button's text to match its on/off value
won = true;
for (int i = 0; i < 9; i++)
{
if (on[i] == true)
buttons[i].setText("###");
else
{
buttons[i].setText(".");
won = false;
}
}
if (won == true)
{
JOptionPane.showMessageDialog(
null,
"You won!",
"Good job!",
JOptionPane.INFORMATION_MESSAGE);
dispose();
}
container.validate();// re-lay out the container
}
}// end class GridLayoutFrame
| true
|
3e17342e42652af233a246f2fe0f4e9942c30bc4
|
Java
|
szjdbf/springboot-demo
|
/src/main/java/com/zlf/demo/springbootdemo/config/log/BLJsonLayout.java
|
UTF-8
| 505
| 1.90625
| 2
|
[] |
no_license
|
package com.zlf.demo.springbootdemo.config.log;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.json.classic.JsonLayout;
import java.util.Map;
public class BLJsonLayout extends JsonLayout {
protected void addCustomDataToJsonMap(Map<String, Object> map, ILoggingEvent event) {
add("msg", this.includeFormattedMessage, event.getFormattedMessage(), map);
add("AppName", true, "blgroup-osp-social-api", map); //app
map.remove("message");
}
}
| true
|
f2f0c26460b9c60bdd1f1f4f8be5f6693256233f
|
Java
|
heyinlonga/DaProject
|
/app/src/main/java/software/ecenter/study/bean/MineBean/UpdataBean.java
|
UTF-8
| 1,638
| 2.078125
| 2
|
[] |
no_license
|
package software.ecenter.study.bean.MineBean;
import java.io.Serializable;
/**
* Created by Mike on 2018/4/25.
*/
public class UpdataBean implements Serializable {
private static final long serialVersionUID = -6953361436212641422L;
private String uploadId;
private String uploadTitle;
private String mainTitle;
private String subTitle;
private String uploadStatus;
private String uploadIntegral;
private String uploadTime;
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public void setUploadTime(String uploadTime) {
this.uploadTime = uploadTime;
}
public String getUploadTime() {
return uploadTime;
}
public String getUploadId() {
return uploadId;
}
public void setUploadId(String uploadId) {
this.uploadId = uploadId;
}
public String getUploadTitle() {
return uploadTitle;
}
public void setUploadTitle(String uploadTitle) {
this.uploadTitle = uploadTitle;
}
public String getUploadStatus() {
return uploadStatus;
}
public void setUploadStatus(String uploadStatus) {
this.uploadStatus = uploadStatus;
}
public String getUploadIntegral() {
return uploadIntegral;
}
public void setUploadIntegral(String uploadIntegral) {
this.uploadIntegral = uploadIntegral;
}
}
| true
|
9ca4a380e1cae34100bc4e8a6bb5a109c9fef4a5
|
Java
|
karanjatav/Cataloger
|
/app/src/main/java/com/example/darkknight/cataloger/Holder_Item.java
|
UTF-8
| 2,191
| 2.40625
| 2
|
[] |
no_license
|
package com.example.darkknight.cataloger;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import java.util.Objects;
/**
* Created by DARKKNIGHT on 2/12/2017.
*/
public class Holder_Item extends ChildViewHolder {
private TextView item_tv, itemQuantityUnit_tv, itemType_tv, itemPrice_tv;
LinearLayout items_ll;
public Holder_Item(View itemView) {
super(itemView);
items_ll = (LinearLayout) itemView.findViewById(R.id.items_xll);
item_tv = (TextView) itemView.findViewById(R.id.itemName_xtv);
itemQuantityUnit_tv = (TextView) itemView.findViewById(R.id.itemQuantityUnit_xtv);
itemType_tv = (TextView) itemView.findViewById(R.id.itemType_xtv);
itemPrice_tv = (TextView) itemView.findViewById(R.id.itemPrice_xtv);
}
public void attachChild(final Object_Items object_items) {
item_tv.setText(object_items.getItemName());
itemType_tv.setText(object_items.getItemType());
int k = object_items.getItemPrice();
String isAdded = object_items.getIsAdded();
if (Objects.equals(isAdded, "true")) {
Log.d("karan22", "item name:" + object_items.getItemName() + "-----item isAdded" + isAdded);
items_ll.setBackgroundColor(Color.parseColor("#fcd45d"));
} else {
Log.d("karan22", "item name:" + object_items.getItemName() + "-----item isAdded" + isAdded);
items_ll.setBackgroundColor(Color.WHITE);
}
if(object_items.getItemQuantityUnit().length()<=4){
itemQuantityUnit_tv.setText("/" + object_items.getItemQuantityUnit());
itemPrice_tv.setText(String.valueOf(k));
}
else if (object_items.getItemQuantityUnit().length()>4){
itemQuantityUnit_tv.setText("/" + object_items.getItemQuantityUnit());
itemQuantityUnit_tv.setTextSize(7);
itemPrice_tv.setText(String.valueOf(k));
itemPrice_tv.setTextSize(10);
}
}
}
| true
|
2f29af32d6e81e7a06a9b3454ea9f1dceebbed93
|
Java
|
FrankLi999/poc
|
/spring/cqrs/es-cqrs-axon/command-service/src/main/java/app/web/api/product/ProductWebApi.java
|
UTF-8
| 443
| 1.851563
| 2
|
[] |
no_license
|
package app.web.api.product;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.concurrent.CompletableFuture;
@RequestMapping(value = "/products")
public interface ProductWebApi {
@PostMapping
CompletableFuture<String> addProduct(@RequestBody AddProductRequest addProductRequest);
}
| true
|
df4cda8e11456f5888d4d4b893059c230a6d0894
|
Java
|
NeVeX/lending-club-android-investor-app
|
/app/src/main/java/com/mark/lendingclub/invest/config/UserInformation.java
|
UTF-8
| 1,408
| 2.15625
| 2
|
[] |
no_license
|
package com.mark.lendingclub.invest.config;
import com.mark.lendingclub.invest.api.util.ApiUtil;
/**
* Created by NeVeX on 10/1/2015.
*/
public class UserInformation {
private String userName;
private String password;
private String clientKey;
private String clientSecret;
private String base64Authentication;
private String lcKey;
private String lcInvestorId;
public UserInformation(String userName, String password) {
this(userName, password, null, null);
}
public UserInformation(String userName, String password, String clientKey, String clientSecret) {
this.userName = userName;
this.password = password;
this.clientKey = clientKey;
this.clientSecret = clientSecret;
this.base64Authentication = ApiUtil.encodeToBase64(userName, password);
lcKey = password;
lcInvestorId = userName;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getClientKey() {
return clientKey;
}
public String getClientSecret() {
return clientSecret;
}
public String getBase64Authentication() {
return base64Authentication;
}
public String getLcKey() {
return lcKey;
}
public String getLcInvestorId() {
return lcInvestorId;
}
}
| true
|
5953a0bacb0fd35d7a8da912eaad0d9a81434944
|
Java
|
togramago/compiler
|
/PreciousAnalysis/src/assignment/scope/Code.java
|
UTF-8
| 220
| 1.664063
| 2
|
[] |
no_license
|
package assignment.scope;
/**
* Instruction Codes for stack machine execution
*/
public enum Code {
ILOAD, ICONST, ISTORE, IADD, IMUL, ISUB, ILT, IAND, INOT, GOTO, IF_FALSE, INVOKEVIRTUAL, RETURN, PRINT, STOP
}
| true
|
3602955b7f563a7a1210cbaa672663d895b22e61
|
Java
|
45zz/2_laba_task
|
/src/com/company/Leg.java
|
UTF-8
| 447
| 2.953125
| 3
|
[] |
no_license
|
package com.company;
public class Leg extends Human {
int speed;
public Leg(String name, int age, char gender,int speed) {
super(name, age, gender);
this.speed=speed;
}
@Override
public String toString() {
return "Leg{" +
"speed=" + speed +
", name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
}
| true
|
8702451395cb821bd69f14b692bd2d5e35169d55
|
Java
|
alex859/battleship
|
/src/main/java/org/alex859/battleship/exceptions/UnrecognizedOrientationException.java
|
UTF-8
| 423
| 2.71875
| 3
|
[] |
no_license
|
package org.alex859.battleship.exceptions;
/**
* Exception thrown when we cannot recognize a cardinal point from the input string
* @author alex859
*
*/
public class UnrecognizedOrientationException extends RuntimeException{
private static final long serialVersionUID = 2320307146833023267L;
public UnrecognizedOrientationException(String str){
super("Letter "+str+" not recognized as a cardinal point.");
}
}
| true
|
fe7cdd370d4002355c13d0cf8d846d4abafb91bc
|
Java
|
poornaonline/AdSeekerAdvertisementEngine
|
/src/main/java/com/research/adseeker/OntologyResourse.java
|
UTF-8
| 7,620
| 2.078125
| 2
|
[] |
no_license
|
package com.research.adseeker;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.research.IO.AdSeekerOntology;
import com.research.IO.AdSeekerUpdatingOntology;
import com.research.ontology.OntologyRelationships;
import com.research.tweets.SingleTweetRelationshipAnalyzer;
import com.research.validation.JSONArrayExtended;
import com.research.validation.TweetMapper;
import com.research.validation.Validation;
@Path("ontology")
public class OntologyResourse {
@POST
@Path("/getrelationship")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response getRelationshipInJSON(String itemName) {
JSONObject returningJsonObject = new JSONObject();
OntologyRelationships or = new OntologyRelationships();
returningJsonObject = or.listOntologyRelationshipsInJson(itemName.trim(), AdSeekerOntology.getModel(), AdSeekerOntology.getOntologyURI());
return Response.status(200).entity(returningJsonObject).build();
}
@POST
@Path("/getontologydata")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response getOntologyDataInJSON(String ontClassName) {
JSONObject initialObject = new JSONObject();
String ontReadyStr = Validation.getSpaceReplacedWithUndescore(ontClassName);
OntClass ontClass = AdSeekerOntology.getReasonedModel().getOntClass(AdSeekerOntology.getOntologyURI() + ontReadyStr);
OntClass ontClass2 = AdSeekerUpdatingOntology.getReasonedModel().getOntClass(AdSeekerUpdatingOntology.getOntologyURI() + ontReadyStr);
JSONArray subClassJR = new JSONArray();
JSONArray individualJR = new JSONArray();
int httpResponseCode = 500;
if(ontClass == null)
{
initialObject.put("Error", "Mentioned object doesn't exist in Ontology");
}else {
Iterator<OntClass> ontClassIterator = ontClass.listSubClasses(true);
while(ontClassIterator.hasNext())
{
OntClass subclass = ontClassIterator.next();
subClassJR.add(subclass.getLocalName());
}
initialObject.put("subclasses", subClassJR.toJSONString());
ExtendedIterator<? extends OntResource> instanceIterator = ontClass.listInstances(true);
while(instanceIterator.hasNext())
{
Individual individual = (Individual) instanceIterator.next();
individualJR.add(individual.getLocalName());
}
initialObject.put("individuals", individualJR.toJSONString());
httpResponseCode = 200;
}
if(ontClass2 != null)
{
Iterator<OntClass> ontClass2Iterator = ontClass2.listSubClasses(true);
while(ontClass2Iterator.hasNext())
{
OntClass subclass = ontClass2Iterator.next();
if (!JSONArrayExtended.checkJSONArrayContained(subclass.getLocalName(), subClassJR))
{
subClassJR.add(subclass.getLocalName());
}
}
initialObject.put("subclasses", subClassJR.toJSONString());
ExtendedIterator<? extends OntResource> instanceIterator = ontClass2.listInstances(true);
while(instanceIterator.hasNext())
{
Individual individual = (Individual) instanceIterator.next();
System.err.println(individual.getLocalName());
if (!JSONArrayExtended.checkJSONArrayContained(individual.getLocalName(), individualJR))
{
individualJR.add(individual.getLocalName());
System.err.println(individual.getLocalName());
}
}
initialObject.put("individuals", individualJR.toJSONString());
}
System.err.println("Returning JSON Object -> " + initialObject.toJSONString());
return Response.status(httpResponseCode).entity(initialObject).build();
}
@POST
@Path("/getsuggestionrelationship")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response getSuggestionRelationships(String productTitle) {
JSONObject returningSuggestionObject = new JSONObject();
ArrayList<ArrayList<String>> titleRelationshipArrayList = new SingleTweetRelationshipAnalyzer().getTweetRelationshipArrayList(productTitle);
int relationshipNumber = 0;
for (ArrayList<String> relationshipArrayList : titleRelationshipArrayList) {
relationshipNumber++;
JSONArray relationshipJsonArray = new TweetMapper().mapArrayListToJsonArray(relationshipArrayList);
returningSuggestionObject.put(relationshipNumber, relationshipJsonArray.toJSONString());
}
return Response.status(200).entity(returningSuggestionObject).build();
}
@POST
@Path("/insertsubclass")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response insertSubClassToTheOntology(JSONObject classDetailsJO) {
String superClassName = Validation.pushInToOntologyReady((String) classDetailsJO.get("superClass"));
String newClassName = Validation.pushInToOntologyReady((String) classDetailsJO.get("newClass"));
int httpStatusCode = 0;
String httpStatusMessage = null;
OntModel model = AdSeekerUpdatingOntology.getModel();
OntClass superClass = model.getOntClass(AdSeekerUpdatingOntology.getOntologyURI() + superClassName);
OntClass subClass = model.createClass(AdSeekerUpdatingOntology.getOntologyURI() + newClassName);
superClass.addSubClass(subClass);
subClass.addSuperClass(superClass);
OutputStream out;
try {
PrintStream p= new PrintStream(AdSeekerUpdatingOntology.getOntologyFilePath());
model.write(p, "RDF/XML");//-ABBREV
p.close();
httpStatusMessage = "Successfully added an subclass to the ontology";
httpStatusCode = 200;
} catch (FileNotFoundException e) {
e.printStackTrace();
httpStatusMessage = "Error Occured";
httpStatusCode = 500;
}
return Response.status(httpStatusCode).entity(httpStatusMessage).build();
}
@POST
@Path("/insertindividual")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response insertIndividualToTheOntology(JSONObject newIndividualDataJO) {
String className = Validation.getSpecialCharRemovedOntoReadyString((String) newIndividualDataJO.get("class"));
String individualName = Validation.getSpecialCharRemovedOntoReadyString((String) newIndividualDataJO.get("individual"));
int httpStatusCode = 0;
String httpStatusMessage = null;
OntModel model = AdSeekerUpdatingOntology.getModel();
OntClass superClass = model.getOntClass(AdSeekerUpdatingOntology.getOntologyURI() + className);
Individual newIndividual = model.createIndividual(AdSeekerUpdatingOntology.getOntologyURI() + individualName, superClass);
OutputStream out;
try {
PrintStream p= new PrintStream(AdSeekerUpdatingOntology.getOntologyFilePath());
model.write(p, "RDF/XML");//-ABBREV
p.close();
httpStatusMessage = "Successfully added an individual to the ontology";
httpStatusCode = 200;
} catch (FileNotFoundException e) {
e.printStackTrace();
httpStatusMessage = "Error Occured while adding to the ontology";
httpStatusCode = 500;
}
return Response.status(httpStatusCode).entity(httpStatusMessage).build();
}
}
| true
|
7801b48e01ecf5b555b6388f608d059f64b6558a
|
Java
|
GitAmrita/AutolistApp
|
/app/src/main/java/carworld/autolist/Listener/OnSelectPriceRangeListener.java
|
UTF-8
| 188
| 1.921875
| 2
|
[] |
no_license
|
package carworld.autolist.Listener;
/**
* Created by amritachowdhury on 4/22/17.
*/
public interface OnSelectPriceRangeListener {
void getPriceRange(int minPrice, int maxPrice);
}
| true
|
8bd7cd1b25952f6ab656b1163aeae40eb649c31c
|
Java
|
nonetheless/FindMyFriend
|
/src/DataBase/DataService.java
|
UTF-8
| 1,131
| 1.992188
| 2
|
[] |
no_license
|
package DataBase;
import java.util.ArrayList;
import Dao.Record;
import Dao.Room;
import Dao.User;
public interface DataService {
public void runDataBase();
public boolean IsUserExist(String userID,String password);
public boolean checkUser(String ID);
public void writeUserPO(User up);
public void updateUserName(String ID,String name);
public void updatePassword(String ID,String password);
public void updateUserHead(String ID,String head);
//public void addNum(String ID);
//public void subNum(String ID);
public void writeChattingPO(Record cp);
public void writeRoomPO(Room rp);
public boolean isRoomExist(String roomID);
public ArrayList<String> getTwentyMess(String ID);
public ArrayList<String> showRoom();
public User getUserByID(String ID);
public void setStateIn(String ID);
public void setStateOut(String ID);
public void leave(String userID );
public void come(String userID,String roomID);
public ArrayList<String> searchRoomUser(String roomID);
public void deleteRoom(String ID);
public ArrayList<String> getRoomName();
public int getPNumByID(String ID);
}
| true
|
e8315e1c170890825141cee38151b8232427fe6d
|
Java
|
lampapos/FBPGraph
|
/src/main/java/edu/kpi/fbp/gui/panels/DescriptionTab.java
|
UTF-8
| 1,375
| 3.125
| 3
|
[] |
no_license
|
package edu.kpi.fbp.gui.panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import edu.kpi.fbp.gui.primitives.Node;
/** Component description. */
public class DescriptionTab {
/** Panel for text area with component description. */
private final JPanel descriptionPanel;
/** {@link DescriptionTab}. */
public DescriptionTab() {
descriptionPanel = new JPanel();
descriptionPanel.setBackground(Color.white);
descriptionPanel.setLayout(new BorderLayout());
descriptionPanel.setMaximumSize(new Dimension(150, Integer.MAX_VALUE));
createDescription(null);
}
/** @return JPanel with component description. */
public JPanel getDescriptionPanel() {
return descriptionPanel;
}
/** Read description from node and place it to text area.
* @param node - last choosed node
*/
public void createDescription(final Node node) {
descriptionPanel.removeAll();
final JTextArea textArea = new JTextArea("");
textArea.setEditable(false);
textArea.setLineWrap(true);
if (node != null) {
textArea.setText(node.getDescription());
} else {
textArea.setText("Nothing choose.");
}
descriptionPanel.add(textArea, BorderLayout.CENTER);
descriptionPanel.revalidate();
descriptionPanel.repaint();
}
}
| true
|
3492d5e10c503128305a47c25959b8b162e1add8
|
Java
|
poolgiancarlos2012/RPT
|
/src/model/vo/ClienteVO.java
|
UTF-8
| 564
| 2.640625
| 3
|
[] |
no_license
|
package model.vo;
public class ClienteVO{
private String CODIGO_CLIENTE;
private String CLIENTE;
// public ClienteVO(String CODIGO_CLIENTE,String CLIENTE){
// this.CODIGO_CLIENTE = CODIGO_CLIENTE;
// this.CLIENTE = CLIENTE;
// }
//
public String getCODIGO_CLIENTE() {
return CODIGO_CLIENTE;
}
public void setCODIGO_CLIENTE(String CODIGO_CLIENTE) {
this.CODIGO_CLIENTE = CODIGO_CLIENTE;
}
public String getCLIENTE() {
return CLIENTE;
}
public void setCLIENTE(String CLIENTE) {
this.CLIENTE = CLIENTE;
}
}
| true
|
9a17fc2565e010681dc379a23914c130f3d3036d
|
Java
|
kxk2907/C-Code
|
/practice/dcn/TCPClient.java
|
UTF-8
| 821
| 3.03125
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class TCPClient {
public static void main(String args[]) throws IOException {
while(true) {
String sentence, modifiedSent;
BufferedReader b1 = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("joplin.cs.rit.edu",4444);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = b1.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSent = inFromServer.readLine();
System.out.println("Output : " + modifiedSent);
clientSocket.close();
}
}
}
| true
|
03ea733301c9cf30def0b7351037705bda1289ae
|
Java
|
rLadia-demo/AttacknidPatch
|
/decompiled_src/Procyon/org/anddev/andengine/extension/physics/box2d/PhysicsConnector.java
|
UTF-8
| 3,998
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.anddev.andengine.extension.physics.box2d;
import org.anddev.andengine.engine.handler.*;
import org.anddev.andengine.extension.physics.box2d.util.constants.*;
import com.badlogic.gdx.physics.box2d.*;
import org.anddev.andengine.entity.shape.*;
import org.anddev.andengine.util.*;
import com.badlogic.gdx.math.*;
public class PhysicsConnector implements IUpdateHandler, PhysicsConstants
{
protected final Body mBody;
protected final float mPixelToMeterRatio;
protected final Shape mShape;
protected final float mShapeHalfBaseHeight;
protected final float mShapeHalfBaseWidth;
protected boolean mUpdateAngularVelocity;
protected boolean mUpdateLinearVelocity;
protected boolean mUpdatePosition;
protected boolean mUpdateRotation;
public PhysicsConnector(final Shape shape, final Body body) {
this(shape, body, true, true, true, true);
}
public PhysicsConnector(final Shape shape, final Body body, final float n) {
this(shape, body, true, true, true, true, n);
}
public PhysicsConnector(final Shape shape, final Body body, final boolean b, final boolean b2, final boolean b3, final boolean b4) {
this(shape, body, b, b2, b3, b4, 32.0f);
}
public PhysicsConnector(final Shape mShape, final Body mBody, final boolean mUpdatePosition, final boolean mUpdateRotation, final boolean mUpdateLinearVelocity, final boolean mUpdateAngularVelocity, final float mPixelToMeterRatio) {
super();
this.mShape = mShape;
this.mBody = mBody;
this.mUpdatePosition = mUpdatePosition;
this.mUpdateRotation = mUpdateRotation;
this.mUpdateLinearVelocity = mUpdateLinearVelocity;
this.mUpdateAngularVelocity = mUpdateAngularVelocity;
this.mPixelToMeterRatio = mPixelToMeterRatio;
this.mShapeHalfBaseWidth = 0.5f * mShape.getBaseWidth();
this.mShapeHalfBaseHeight = 0.5f * mShape.getBaseHeight();
}
public Body getBody() {
return this.mBody;
}
public Shape getShape() {
return this.mShape;
}
public boolean isUpdateAngularVelocity() {
return this.mUpdateAngularVelocity;
}
public boolean isUpdateLinearVelocity() {
return this.mUpdateLinearVelocity;
}
public boolean isUpdatePosition() {
return this.mUpdatePosition;
}
public boolean isUpdateRotation() {
return this.mUpdateRotation;
}
@Override
public void onUpdate(final float n) {
final Shape mShape = this.mShape;
final Body mBody = this.mBody;
if (this.mUpdatePosition) {
final Vector2 position = mBody.getPosition();
final float mPixelToMeterRatio = this.mPixelToMeterRatio;
mShape.setPosition(mPixelToMeterRatio * position.x - this.mShapeHalfBaseWidth, mPixelToMeterRatio * position.y - this.mShapeHalfBaseHeight);
}
if (this.mUpdateRotation) {
mShape.setRotation(MathUtils.radToDeg(mBody.getAngle()));
}
if (this.mUpdateLinearVelocity) {
final Vector2 linearVelocity = mBody.getLinearVelocity();
mShape.setVelocity(linearVelocity.x, linearVelocity.y);
}
if (this.mUpdateAngularVelocity) {
mShape.setAngularVelocity(mBody.getAngularVelocity());
}
}
@Override
public void reset() {
}
public void setUpdateAngularVelocity(final boolean mUpdateAngularVelocity) {
this.mUpdateAngularVelocity = mUpdateAngularVelocity;
}
public void setUpdateLinearVelocity(final boolean mUpdateLinearVelocity) {
this.mUpdateLinearVelocity = mUpdateLinearVelocity;
}
public void setUpdatePosition(final boolean mUpdatePosition) {
this.mUpdatePosition = mUpdatePosition;
}
public void setUpdateRotation(final boolean mUpdateRotation) {
this.mUpdateRotation = mUpdateRotation;
}
}
| true
|
2bc8abdebb681b8d4c2d455ba572677f9be5f9ba
|
Java
|
CrazyZM/Toolkit
|
/toolkitlibrary/src/main/java/com/android/toolkitlibrary/network/base/FFActivity.java
|
UTF-8
| 2,977
| 2.1875
| 2
|
[] |
no_license
|
package com.android.toolkitlibrary.network.base;
import android.app.Activity;
import com.android.toolkitlibrary.network.http.FFNetWorkCallBack;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
public interface FFActivity {
public final static ArrayList<Activity> allActivities = new ArrayList<Activity>();
public final static ArrayList<Activity> transactionActivities = new ArrayList<Activity>();
/**
* 判断当前activity是否finish了
*
* @return
*/
boolean getDestroyed();
/**
* 显示吐司
* @param msg
*/
void showToast(Object msg);
void removeAllMenu();
/**
* 显示ProgressDialog
*
* @param word
*/
void showProgressDialog(String word);
/**
* 使ProgressDialog消失
*/
void dismissProgressDialog();
/**
* 使用logUtil打日志
*
* @param log
*/
void d(String log);
/**
* 使用logUtil打日志
*
* @param log
*/
void e(String log);
/**
* 使用logUtil打日志
*
* @param log
*/
void i(String log);
/**
* 获得ContentView
*
* @return
*/
int getContentViewId();
/**
* findView
*/
void findView();
/**
* 初始化所有View
*/
void initView();
/**
* 设置监听
*/
void setListener();
/**
* Create之后执行
*/
void afterCreate();
/**
* 异步网络请求post
*
* @param url
* @param words 要在ProgressDialog显示的文字
* @param clazz 请求获取的结果类型
* @param callBack
* @param param K,V,K,V...
*/
<T> void post(String url, String words, Class<T> clazz, FFNetWorkCallBack<T> callBack,
Object... param);
/**
* 异步网络上传文件
* @param url
* @param words 要在ProgressDialog显示的文字
* @param clazz 请求获取的结果类型
* @param callBack
* @param param K,V,K,V...
*/
<T> void postFile(String url, String words, Map<String, File> files, Class<T> clazz, FFNetWorkCallBack<T> callBack,
Object... param);
/**
* 异步网络请求get
*
* @param url
* @param words 要在ProgressDialog显示的文字
* @param clazz 请求获取的结果类型
* @param callBack
* @param param
*/
<T> void get(String url, String words, Class<T> clazz, FFNetWorkCallBack<T> callBack,
Object... param);
/**
* 开启事务 完成后回到开始时的Activity
*
* @param containThis 完成时是否关闭当前Activity true为关闭
*/
public void startTransaction(boolean containThis);
/**
* 结束事务
*
* @param finishThis 结束事务时是否关闭当前activity
*/
public void endTransaction(boolean finishThis);
}
| true
|
966b5cea870476060f681f20c356da88f430968f
|
Java
|
gitping/DesignPatterns
|
/suixingouShop/modify1.1.0/.svn/pristine/fc/fc5e8e5a4f256fcc6fae43366364ed56a639420f.svn-base
|
UTF-8
| 3,252
| 1.53125
| 2
|
[] |
no_license
|
package com.yto.suixingouuser.activity.helper.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yto.suixingouuser.model.UserInfo;
import com.yto.suixingouuser.model.VersionBean;
import com.yto.zhang.util.modle.AppVersionResJo;
import com.yto.zhang.util.modle.ShopExpressOrderResJo;
/**
* @author Administrator
*
*/
public class FConstants {
public static int LIST_POSITION=0;
public static float phoneDensity = 0;
/**frame*/
/**更新变量*/
public static VersionBean welcomA_vb = new VersionBean();
public static AppVersionResJo appVerRes = new AppVersionResJo();
public final static String phoneNumkey = "phoneNumKey";
public final static String userPassKey = "userPassKey";
public static boolean isLogin = false;
/** 保存用户的登录信息 */
public static UserInfo userInfo = new UserInfo();
/** Json解析错误 */
public final static int JSONERROR = -1;
/** 网络请求失败 */
public final static int FAILUREERROR = -2;
/** 实体数据不对 */
public final static int BEANERROR = -3;
/**数据处理的方式不对*/
public final static int PARSEERROR = -5;
/** 请求成功 */
public final static int SUCCESS = 200;
/** 数据位0但是有num字段 */
public final static List<ShopExpressOrderResJo> NODATA = new ArrayList<ShopExpressOrderResJo>();
/**状态不等200*/
public final static int FAIL = -4;
/** 请求密钥 */
public static final String APP_KEY = "";
/** 请求密钥 */
// public static String UUID = "836";
public static String UUID = "100";
/** zl测试*/
public final static int MYTEST=-101;
public static final Map<String,Double> map=new HashMap<String, Double>();
public static final int waitcount=0;
/**消息推送间隔 */
public final static int MESSAGEPUSH = 10000;
public static String MAC=null;
// public static final String APP_KEY = MD5Utils.MD5("taozapp2013");
// public static GPSBaiduEntity gpsBE = new GPSBaiduEntity();
/**消息地址*/
public final static String MSGURL = "";
// public final static String BASEURL = "http://192.168.5.64:8080/server/remote/remote-service.action";
// public final static String BASEURL = "http://192.168.5.26:11000/web_1/remote/remote-service.action";//测试地址
// public final static String BASEURL = "http://192.168.5.99:11000/interface_1/remote/remote-service.action";//隆勇地址
// public final static String BASEURL = "http://192.168.5.171:11000/web_1/remote/remote-service.action";// jz测试地址
// public final static String BASEURL = "http://192.168.5.231:11000/web_1/remote/remote-service.action";//测试地址
// public final static String GOODSURL="http://192.168.5.231:11000/web_1/remote/remote-service.action";//商品信息地址
// public final static String BASEURL = "http://192.168.5.147:11000/web_1/remote/remote-service.action";//测试地址
// public final static String BASEURL = "http://192.168.5.26:11000/web_2/remote/remote-service.action";//测试地址
public final static String BASEURL ="http://int.sxgou.cn/remote/remote-service.action";//隆勇生产
// public final static String BASEURL ="http://192.168.5.26:11000/interface_2/remote/remote-service.action";
public static void clear(){
}
}
| true
|
1372685c1b22df47b9deea90978588d00b9697f5
|
Java
|
hupulin/joyProperty
|
/common-library/src/main/java/com/jinyi/ihome/module/newshop/PayInfo.java
|
UTF-8
| 917
| 2.1875
| 2
|
[] |
no_license
|
package com.jinyi.ihome.module.newshop;
import java.util.List;
/**
* Created by xz on 2017/1/10.
*/
public class PayInfo {
private String name;
private String money;
private List<PayOlderTo>payPartners;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public List<PayOlderTo> getPayPartners() {
return payPartners;
}
public void setPayPartners(List<PayOlderTo> payPartners) {
this.payPartners = payPartners;
}
@Override
public String toString() {
return "PayInfo{" +
"name='" + name + '\'' +
", money='" + money + '\'' +
", payPartners=" + payPartners +
'}';
}
}
| true
|
f207cb28a20c910dc42d559089bf3f700dc2e4d4
|
Java
|
mariateseiko/WebTech1
|
/src/by/bsuir/lab1/bean/Response.java
|
UTF-8
| 327
| 2.140625
| 2
|
[] |
no_license
|
package by.bsuir.lab1.bean;
/**
* A response for {@link by.bsuir.lab1.bean.Request}
*/
public class Response {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| true
|
8c94e6e987eb5d47b6ef7ee76b404759caad48d7
|
Java
|
eva-xuyen/excalibur
|
/fortress/container-impl/src/java/org/apache/avalon/fortress/impl/role/ConfigurableRoleManager.java
|
UTF-8
| 4,264
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avalon.fortress.impl.role;
import org.apache.avalon.fortress.RoleManager;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
/**
* Configurable RoleManager implementation. It populates the RoleManager
* from a configuration hierarchy. This is based on the DefaultRoleManager
* in the org.apache.avalon.component package.
*
* @author <a href="mailto:dev@avalon.apache.org">Avalon Development Team</a>
* @version CVS $Revision: 1.13 $ $Date: 2004/02/28 15:16:25 $
* @since 4.1
*/
public class ConfigurableRoleManager
extends AbstractRoleManager
implements Configurable
{
/**
* Default constructor--this RoleManager has no parent.
*/
public ConfigurableRoleManager()
{
super( null, null );
}
/**
* Alternate constructor--this RoleManager has the specified
* classloader.
*
* @param loader The <code>ClassLoader</code> used to resolve class names.
*/
public ConfigurableRoleManager( final ClassLoader loader )
{
super( null, loader );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent.
*
* @param parent The parent <code>RoleManager</code>.
*/
public ConfigurableRoleManager( final RoleManager parent )
{
super( parent, null );
}
/**
* Alternate constructor--this RoleManager has the specified
* parent and a classloader.
*
* @param parent The parent <code>RoleManager</code>.
* @param loader the classloader
*/
public ConfigurableRoleManager( final RoleManager parent, final ClassLoader loader )
{
super( parent, loader );
}
/**
* Reads a configuration object and creates the role, shorthand,
* and class name mapping.
*
* @param configuration The configuration object.
* @throws ConfigurationException if the configuration is malformed
*/
public final void configure( final Configuration configuration )
throws ConfigurationException
{
final Configuration[] roles = configuration.getChildren( "role" );
for ( int i = 0; i < roles.length; i++ )
{
final String role = roles[i].getAttribute( "name" );
final Configuration[] components = roles[i].getChildren( "component" );
for ( int j = 0; j < components.length; j++ )
{
final String shorthand = components[j].getAttribute( "shorthand" );
final String className =
components[j].getAttribute( "class", null );
final String handlerClassName =
components[j].getAttribute( "handler",
org.apache.avalon.fortress.impl.handler.PerThreadComponentHandler.class.getName() );
if ( ! addRole( shorthand, role, className, handlerClassName ) )
{
final String message = "Skipping invalid entry:\n\tRole: " + role +
"\n\tShorthand: " + shorthand +
"\n\tClass Name: " + className +
"\n\tHandler Class: " + handlerClassName;
getLogger().error( message );
}
}
}
}
}
| true
|