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
e9d3e62cf1aacab741745dc453c4ebdf3f4bfee0
Java
konexios/moonstone
/acs-client/src/main/java/moonstone/acs/client/api/UserApi.java
UTF-8
5,966
1.8125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright (c) 2018 Arrow Electronics, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License 2.0 * which accompanies this distribution, and is available at * http://apache.org/licenses/LICENSE-2.0 * * Contributors: * Arrow Electronics, Inc. *******************************************************************************/ package moonstone.acs.client.api; import java.net.URI; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.utils.URIBuilder; import com.fasterxml.jackson.core.type.TypeReference; import moonstone.acs.JsonUtils; import moonstone.acs.client.api.ApiConfig; import moonstone.acs.client.model.HidModel; import moonstone.acs.client.model.PagingResultModel; import moonstone.acs.client.model.PasswordModel; import moonstone.acs.client.model.StatusMessagesModel; import moonstone.acs.client.model.UserAppAuthenticationModel; import moonstone.acs.client.model.UserAuthenticationModel; import moonstone.acs.client.model.UserModel; import moonstone.acs.client.search.UserSearchCriteria; public final class UserApi extends AcsApiAbstract { private static final String USERS_ROOT_URL = WEB_SERVICE_ROOT_URL + "/users"; // instantiation is expensive for these objects private TypeReference<PagingResultModel<UserModel>> userModelTypeRef; UserApi(ApiConfig apiConfig) { super(apiConfig); } public UserModel authenticate(String username, String password) { String method = "authenticate"; try { URI uri = buildUri(USERS_ROOT_URL + "/auth"); UserAuthenticationModel model = new UserAuthenticationModel().withUsername(username).withPassword(password); UserModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), UserModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public UserModel authenticate2(String username, String password, String applicationCode) { String method = "authenticate"; try { URI uri = buildUri(USERS_ROOT_URL + "/auth2"); UserAppAuthenticationModel model = (UserAppAuthenticationModel) new UserAppAuthenticationModel() .withUsername(username).withPassword(password); model.setApplicationCode(applicationCode); UserModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), UserModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public UserModel findByHid(String hid) { String method = "findByHid"; try { URI uri = buildUri(USERS_ROOT_URL + "/" + hid); UserModel result = execute(new HttpGet(uri), UserModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public UserModel findByLogin(String username) { String method = "findByLogin"; try { URI uri = new URIBuilder(buildUri(USERS_ROOT_URL) + "/logins").addParameter("login", username).build(); UserModel result = execute(new HttpGet(uri), UserModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public PagingResultModel<UserModel> findByCriteria(UserSearchCriteria criteria) { String method = "findByCriteria"; try { URI uri = buildUri(USERS_ROOT_URL, criteria); PagingResultModel<UserModel> result = execute(new HttpGet(uri), getUserModelTypeRef()); log(method, result); return result; } catch (Throwable t) { throw handleException(t); } } public PasswordModel resetPassword(String hid) { String method = "resetPassword"; try { URI uri = buildUri(USERS_ROOT_URL + "/" + hid + "/reset-password"); PasswordModel result = execute(new HttpPost(uri), PasswordModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public StatusMessagesModel setNewPassword(String hid, PasswordModel model) { String method = "setNewPassword"; try { URI uri = buildUri(USERS_ROOT_URL + "/" + hid + "/set-new-password"); StatusMessagesModel result = execute(new HttpPost(uri), StatusMessagesModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public HidModel createUser(UserModel model) { String method = "createUser"; try { URI uri = buildUri(USERS_ROOT_URL); HidModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), HidModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } public HidModel updateUser(String hid, UserModel model) { String method = "updateUser"; try { URI uri = buildUri(USERS_ROOT_URL + "/" + hid); HidModel result = execute(new HttpPut(uri), JsonUtils.toJson(model), HidModel.class); if (result != null && isDebugEnabled()) logDebug(method, "result: %s", JsonUtils.toJson(result)); return result; } catch (Throwable t) { throw handleException(t); } } synchronized TypeReference<PagingResultModel<UserModel>> getUserModelTypeRef() { return userModelTypeRef != null ? userModelTypeRef : (userModelTypeRef = new TypeReference<PagingResultModel<UserModel>>() { }); } }
true
5a76dd8bbc53cc75ac81aa808777235c2ea1e592
Java
ysumut/LMS
/src/java/entity/Student.java
UTF-8
1,165
2.75
3
[]
no_license
package entity; import java.util.List; public class Student extends User { private int semester, registration_year; private List<String> departments; private String departments_str; public Student() { } public Student(int userId, String full_name, String email, int semester, int registration_year) { super(userId, full_name, email, "student"); this.semester = semester; this.registration_year = registration_year; } public int getSemester() { return semester; } public void setSemester(int semester) { this.semester = semester; } public int getRegistration_year() { return registration_year; } public void setRegistration_year(int registration_year) { this.registration_year = registration_year; } public List<String> getDepartments() { return departments; } public void setDepartments(List<String> departments) { this.departments = departments; this.departments_str = String.join(", ", departments); } public String getDepartments_str() { return departments_str; } }
true
f1e87fe667b46e85c8e43bfba476d25c9adde703
Java
rensusoft/HCTMS
/src/com/rensu/education/hctms/score/dao/StuScoDao.java
UTF-8
2,028
1.914063
2
[]
no_license
package com.rensu.education.hctms.score.dao; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.rensu.education.hctms.core.dao.BaseDao; import com.rensu.education.hctms.score.bean.StuSco; import configuration.mapper.StuScoMapper; @Repository("stuScoDao") public class StuScoDao extends BaseDao<StuSco> { Logger log = Logger.getLogger(StuScoDao.class); @Autowired private StuScoMapper<StuSco> stuScoMapper; @Override public int add(StuSco stuSco) { return stuScoMapper.add(stuSco); }; @Override public int update(StuSco stuSco) { return stuScoMapper.update(stuSco); }; @Override public int delete(StuSco stuSco) { return stuScoMapper.delete(stuSco); }; @Override public StuSco selectOne(int id) { return stuScoMapper.selectOne(id); }; @Override public List<StuSco> selectList(StuSco stuSco) { return stuScoMapper.selectList(stuSco); }; @Override public List<StuSco> selectPage(RowBounds rowBounds, StuSco stuSco) { return stuScoMapper.selectPage(rowBounds, stuSco); }; @Override public int selectCount(StuSco stuSco) { return stuScoMapper.selectCount(stuSco); }; @Override public int getSequence() { return stuScoMapper.getSequence(); } public int insertWithList(List<StuSco> list) { return stuScoMapper.insertWithList(list); } public int updateByAuthIdAndSubjectId(StuSco stuSco) { return stuScoMapper.updateByAuthIdAndSubjectId(stuSco); } public List<StuSco> selectPageWithUserInfo(RowBounds rowBounds, StuSco stuSco) { return stuScoMapper.selectPageWithUserInfo(rowBounds, stuSco); } public List<StuSco> selectAll() { return stuScoMapper.selectAll(); } public int selectPageWithUserInfoCount() { return stuScoMapper.selectPageWithUserInfoCount(); } }
true
e189ff1025704cfa89b5442e1ae97082773b7ddc
Java
duongnv1996/chotviet-ship
/app/src/main/java/com/skynet/chovietship/utils/AlarmUtils.java
UTF-8
1,739
2.234375
2
[]
no_license
package com.skynet.chovietship.utils; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import java.util.Calendar; /** * Created by framgia on 23/05/2017. */ public class AlarmUtils { private static int INDEX = 1; public static void create(Context context, String hour,String tite,String content) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour.split(":")[0])); // For 1 PM or 2 PM calendar.set(Calendar.MINUTE, Integer.parseInt(hour.split(":")[1])); calendar.set(Calendar.SECOND, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, SchedulingService.class); intent.putExtra("type", INDEX); intent.putExtra("title", tite); intent.putExtra("content", content); PendingIntent pendingIntent = PendingIntent.getService(context, INDEX, intent, PendingIntent.FLAG_UPDATE_CURRENT); INDEX++; alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); // alarmManager // .setAlarmClock(new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), pendingIntent), pendingIntent); // NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // notificationManager.notify(3, CommomUtils.createNotificationWithMsgStick(context, "vinenglish Trip", "Hệ thống đã ghi nhận chuyến đi đặt trước của bạn!")); } }
true
eb1d97932b8378524390db257f0691ce8b02d557
Java
andyjduncan/spring-data-commons
/src/main/java/org/springframework/data/config/AuditingHandlerBeanDefinitionParser.java
UTF-8
3,282
1.734375
2
[]
no_license
/* * Copyright 2012-2013 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 * * 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.springframework.data.config; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.*; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.aop.target.LazyInitTargetSource; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.data.auditing.AuditingHandler; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * {@link BeanDefinitionParser} that parses an {@link AuditingHandler} {@link BeanDefinition} * * @author Oliver Gierke * @since 1.5 */ public class AuditingHandlerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { private static final String AUDITOR_AWARE_REF = "auditor-aware-ref"; /* * (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#getBeanClass(org.w3c.dom.Element) */ @Override protected Class<?> getBeanClass(Element element) { return AuditingHandler.class; } /* * (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#shouldGenerateId() */ @Override protected boolean shouldGenerateId() { return true; } /* * (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#doParse(org.w3c.dom.Element, org.springframework.beans.factory.support.BeanDefinitionBuilder) */ @Override protected void doParse(Element element, BeanDefinitionBuilder builder) { String auditorAwareRef = element.getAttribute(AUDITOR_AWARE_REF); if (StringUtils.hasText(auditorAwareRef)) { builder.addPropertyValue("auditorAware", createLazyInitTargetSourceBeanDefinition(auditorAwareRef)); } ParsingUtils.setPropertyValue(builder, element, "set-dates", "dateTimeForNow"); ParsingUtils.setPropertyReference(builder, element, "date-time-provider-ref", "dateTimeProvider"); ParsingUtils.setPropertyValue(builder, element, "modify-on-creation", "modifyOnCreation"); } private BeanDefinition createLazyInitTargetSourceBeanDefinition(String auditorAwareRef) { BeanDefinitionBuilder targetSourceBuilder = rootBeanDefinition(LazyInitTargetSource.class); targetSourceBuilder.addPropertyValue("targetBeanName", auditorAwareRef); BeanDefinitionBuilder builder = rootBeanDefinition(ProxyFactoryBean.class); builder.addPropertyValue("targetSource", targetSourceBuilder.getBeanDefinition()); return builder.getBeanDefinition(); } }
true
fc65d0cab90250788aadcf0d607831ab77efac35
Java
yu-yurkov/RoomDB
/app/src/main/java/com/example/hp/roomdb/MainActivity.java
UTF-8
1,964
2.328125
2
[]
no_license
package com.example.hp.roomdb; import android.arch.persistence.room.Room; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { FloatingActionButton fab; private static final String TAG = "MainActivity"; RecyclerView recyclerView; RecyclerView.Adapter adapter; //ArrayList<Shop> shops; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Log.d(TAG, "onClick: pressed!"); startActivity(new Intent(MainActivity.this, AddShop.class)); } }); // shops = new ArrayList<>(); // // for (int i = 0; i < 10 ; i++) { // Shop shop = new Shop("addr "+i,"title","tel","name","time"); // shops.add(shop); // } AppDatabase db = Room.databaseBuilder(this.getApplicationContext(),AppDatabase.class, "production") .allowMainThreadQueries() .build(); List<Shop> shops = db.shopDao().getAllShops(); recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new AddShopAdapter(shops); recyclerView.setAdapter(adapter); } }
true
7fe2d9726431648e74eb8db3ce176457888b841d
Java
bananasik/recipe_book
/RecipeCollection/app/src/main/java/Model/Section.java
UTF-8
300
2.484375
2
[]
no_license
package Model; /** * Created by Олег on 16.02.2016. */ public class Section { public int id; public String name; public Section(String _name){ id = 0; name = _name; } public Section(int _id, String _name){ id = _id; name = _name; } }
true
de34b3cf65a627a90708fabe48265f6be8178d7f
Java
VitaliiBashta/L2Jts
/gameserver/src/main/java/org/mmocore/gameserver/model/entity/residence/Castle.java
UTF-8
27,070
1.617188
2
[]
no_license
package org.mmocore.gameserver.model.entity.residence; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import org.mmocore.commons.database.dao.JdbcEntityState; import org.mmocore.commons.database.dbutils.DbUtils; import org.mmocore.gameserver.GameServer; import org.mmocore.gameserver.data.xml.holder.ResidenceHolder; import org.mmocore.gameserver.database.DatabaseFactory; import org.mmocore.gameserver.database.dao.impl.CastleDAO; import org.mmocore.gameserver.database.dao.impl.CastleHiredGuardDAO; import org.mmocore.gameserver.database.dao.impl.ClanDataDAO; import org.mmocore.gameserver.listeners.impl.OnCastleDataLoaded; import org.mmocore.gameserver.manager.CastleManorManager; import org.mmocore.gameserver.model.Manor; import org.mmocore.gameserver.model.entity.SevenSigns; import org.mmocore.gameserver.model.pledge.Clan; import org.mmocore.gameserver.network.lineage.components.CustomMessage; import org.mmocore.gameserver.network.lineage.components.NpcString; import org.mmocore.gameserver.object.Player; import org.mmocore.gameserver.object.components.items.ItemInstance; import org.mmocore.gameserver.object.components.items.warehouse.Warehouse; import org.mmocore.gameserver.templates.StatsSet; import org.mmocore.gameserver.templates.item.ItemTemplate; import org.mmocore.gameserver.templates.item.support.MerchantGuard; import org.mmocore.gameserver.templates.manor.CropProcure; import org.mmocore.gameserver.templates.manor.SeedProduction; import org.mmocore.gameserver.utils.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.CopyOnWriteArraySet; @SuppressWarnings("unchecked") public class Castle extends Residence { private static final Logger _log = LoggerFactory.getLogger(Castle.class); private static final String CASTLE_MANOR_DELETE_PRODUCTION = "DELETE FROM castle_manor_production WHERE castle_id=?;"; private static final String CASTLE_MANOR_DELETE_PRODUCTION_PERIOD = "DELETE FROM castle_manor_production WHERE castle_id=? AND period=?;"; private static final String CASTLE_MANOR_DELETE_PROCURE = "DELETE FROM castle_manor_procure WHERE castle_id=?;"; private static final String CASTLE_MANOR_DELETE_PROCURE_PERIOD = "DELETE FROM castle_manor_procure WHERE castle_id=? AND period=?;"; private static final String CASTLE_UPDATE_CROP = "UPDATE castle_manor_procure SET can_buy=? WHERE crop_id=? AND castle_id=? AND period=?"; private static final String CASTLE_UPDATE_SEED = "UPDATE castle_manor_production SET can_produce=? WHERE seed_id=? AND castle_id=? AND period=?"; private final TIntObjectMap<MerchantGuard> merchantGuards = new TIntObjectHashMap<>(); private final Map<Integer, List> relatedFortresses = new ConcurrentSkipListMap<>(); private final NpcString _npcStringName; private final Set<ItemInstance> _spawnMerchantTickets = new CopyOnWriteArraySet<>(); private Dominion dominion; private List<CropProcure> _procure; private List<SeedProduction> _production; private List<CropProcure> _procureNext; private List<SeedProduction> _productionNext; private boolean _isNextPeriodApproved; private int _TaxPercent; private double _TaxRate; private long _treasury; private long _collectedShops; private long _collectedSeed; public Castle(final StatsSet set) { super(set); _npcStringName = NpcString.valueOf(1001000 + _id); } @Override public void init() { super.init(); for (final Map.Entry<Integer, List> entry : relatedFortresses.entrySet()) { relatedFortresses.remove(entry.getKey()); final List<Integer> list = entry.getValue(); final List<Fortress> list2 = new ArrayList<>(list.size()); for (final int i : list) { final Fortress fortress = ResidenceHolder.getInstance().getResidence(Fortress.class, i); if (fortress == null) { continue; } list2.add(fortress); fortress.addRelatedCastle(this); } relatedFortresses.put(entry.getKey(), list2); } } // This method sets the castle owner; null here means give it back to NPC @Override public void changeOwner(final Clan newOwner) { // Если клан уже владел каким-либо замком/крепостью, отбираем его. if (newOwner != null) { if (newOwner.getHasFortress() != 0) { final Fortress oldFortress = ResidenceHolder.getInstance().getResidence(Fortress.class, newOwner.getHasFortress()); if (oldFortress != null) { oldFortress.changeOwner(null); } } if (newOwner.getCastle() != 0) { final Castle oldCastle = ResidenceHolder.getInstance().getResidence(Castle.class, newOwner.getCastle()); if (oldCastle != null) { oldCastle.changeOwner(null); } } } Clan oldOwner = null; // Если этим замком уже кто-то владел, отбираем у него замок if (getOwnerId() > 0 && (newOwner == null || newOwner.getClanId() != getOwnerId())) { // Удаляем замковые скилы у старого владельца removeSkills(); getDominion().changeOwner(null); getDominion().removeSkills(); // Убираем налог setTaxPercent(null, 0); oldOwner = getOwner(); if (oldOwner != null) { // Переносим сокровищницу в вархауз старого владельца final long amount = getTreasury(); if (amount > 0) { final Warehouse warehouse = oldOwner.getWarehouse(); if (warehouse != null) { warehouse.addItem(ItemTemplate.ITEM_ID_ADENA, amount); addToTreasuryNoTax(-amount, false, false); Log.add(getName() + '|' + -amount + "|Castle:changeOwner", "treasury"); } } // Проверяем членов старого клана владельца, снимаем короны замков и корону лорда с лидера for (final Player clanMember : oldOwner.getOnlineMembers(0)) { if (clanMember != null && clanMember.getInventory() != null) { clanMember.getInventory().validateItems(); } } // Отнимаем замок у старого владельца oldOwner.setHasCastle(0); } } // Выдаем замок новому владельцу if (newOwner != null) { newOwner.setHasCastle(getId()); } // Сохраняем в базу updateOwnerInDB(newOwner); // Выдаем замковые скилы новому владельцу rewardSkills(); update(); } // This method loads castle @Override protected void loadData() { _TaxPercent = 0; _TaxRate = 0; _treasury = 0; _procure = new ArrayList<>(); _production = new ArrayList<>(); _procureNext = new ArrayList<>(); _productionNext = new ArrayList<>(); _isNextPeriodApproved = false; owner = ClanDataDAO.getInstance().getOwner(this); CastleDAO.getInstance().select(this); CastleHiredGuardDAO.getInstance().load(this); GameServer.getInstance().globalListeners().onAction(OnCastleDataLoaded.class, l -> l.onLoad(getId())); } private void updateOwnerInDB(final Clan clan) { owner = clan; // Update owner id property Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement("UPDATE clan_data SET hasCastle=0 WHERE hasCastle=? LIMIT 1"); statement.setInt(1, getId()); statement.execute(); DbUtils.close(statement); if (clan != null) { statement = con.prepareStatement("UPDATE clan_data SET hasCastle=? WHERE clan_id=? LIMIT 1"); statement.setInt(1, getId()); statement.setInt(2, getOwnerId()); statement.execute(); clan.broadcastClanStatus(true, false, false); } } catch (Exception e) { _log.error("", e); } finally { DbUtils.closeQuietly(con, statement); } } public int getTaxPercent() { // Если печатью SEAL_STRIFE владеют DUSK то налог можно выставлять не более 5% if (_TaxPercent > 5 && SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE) == SevenSigns.CABAL_DUSK) { _TaxPercent = 5; } return _TaxPercent; } public void setTaxPercent(final int p) { _TaxPercent = Math.min(Math.max(0, p), 100); _TaxRate = _TaxPercent / 100.0; } public int getTaxPercent0() { return _TaxPercent; } public long getCollectedShops() { return _collectedShops; } public void setCollectedShops(final long value) { _collectedShops = value; } public long getCollectedSeed() { return _collectedSeed; } public void setCollectedSeed(final long value) { _collectedSeed = value; } /** * Add amount to castle instance's treasury (warehouse). */ public void addToTreasury(long amount, final boolean shop, final boolean seed) { if (getOwnerId() <= 0) { return; } if (amount == 0) { return; } if (amount > 1 && _id != 5 && _id != 8) // If current castle instance is not Aden or Rune { final Castle royal = ResidenceHolder.getInstance().getResidence(Castle.class, _id >= 7 ? 8 : 5); if (royal != null) { final long royalTax = (long) (amount * royal.getTaxRate()); // Find out what royal castle gets from the current castle instance's income if (royal.getOwnerId() > 0) { royal.addToTreasury(royalTax, shop, seed); // Only bother to really add the tax to the treasury if not npc owned if (_id == 5) { Log.add("Aden|" + royalTax + "|Castle:adenTax", "treasury"); } else if (_id == 8) { Log.add("Rune|" + royalTax + "|Castle:runeTax", "treasury"); } } amount -= royalTax; // Subtract royal castle income from current castle instance's income } } addToTreasuryNoTax(amount, shop, seed); } // This method add to the treasury /** * Add amount to castle instance's treasury (warehouse), no tax paying. */ public void addToTreasuryNoTax(final long amount, final boolean shop, final boolean seed) { if (getOwnerId() <= 0) { return; } if (amount == 0) { return; } // Add to the current treasury total. Use "-" to substract from treasury _treasury = Math.addExact(_treasury, amount); if (shop) { _collectedShops += amount; } if (seed) { _collectedSeed += amount; } setJdbcState(JdbcEntityState.UPDATED); update(); } public int getCropRewardType(final int crop) { int rw = 0; for (final CropProcure cp : _procure) { if (cp.getId() == crop) { rw = cp.getReward(); } } return rw; } // This method updates the castle tax rate public void setTaxPercent(final Player activeChar, final int taxPercent) { setTaxPercent(taxPercent); setJdbcState(JdbcEntityState.UPDATED); update(); if (activeChar != null) { activeChar.sendMessage(new CustomMessage("org.mmocore.gameserver.model.entity.Castle.OutOfControl.CastleTaxChangetTo").addString(getName()).addNumber(taxPercent)); } } public double getTaxRate() { // Если печатью SEAL_STRIFE владеют DUSK то налог можно выставлять не более 5% if (_TaxRate > 0.05 && SevenSigns.getInstance().getSealOwner(SevenSigns.SEAL_STRIFE) == SevenSigns.CABAL_DUSK) { _TaxRate = 0.05; } return _TaxRate; } public long getTreasury() { return _treasury; } public void setTreasury(final long t) { _treasury = t; } public List<SeedProduction> getSeedProduction(final int period) { return period == CastleManorManager.PERIOD_CURRENT ? _production : _productionNext; } public List<CropProcure> getCropProcure(final int period) { return period == CastleManorManager.PERIOD_CURRENT ? _procure : _procureNext; } public void setSeedProduction(final List<SeedProduction> seed, final int period) { if (period == CastleManorManager.PERIOD_CURRENT) { _production = seed; } else { _productionNext = seed; } } public void setCropProcure(final List<CropProcure> crop, final int period) { if (period == CastleManorManager.PERIOD_CURRENT) { _procure = crop; } else { _procureNext = crop; } } public synchronized SeedProduction getSeed(final int seedId, final int period) { for (final SeedProduction seed : getSeedProduction(period)) { if (seed.getId() == seedId) { return seed; } } return null; } public synchronized CropProcure getCrop(final int cropId, final int period) { for (final CropProcure crop : getCropProcure(period)) { if (crop.getId() == cropId) { return crop; } } return null; } public long getManorCost(final int period) { final List<CropProcure> procure; final List<SeedProduction> production; if (period == CastleManorManager.PERIOD_CURRENT) { procure = _procure; production = _production; } else { procure = _procureNext; production = _productionNext; } long total = 0; if (production != null) { for (final SeedProduction seed : production) { total += Manor.getInstance().getSeedBuyPrice(seed.getId()) * seed.getStartProduce(); } } if (procure != null) { for (final CropProcure crop : procure) { total += crop.getPrice() * crop.getStartAmount(); } } return total; } // Save manor production data public void saveSeedData() { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION); statement.setInt(1, getId()); statement.execute(); DbUtils.close(statement); if (_production != null) { int count = 0; String query = "INSERT INTO castle_manor_production VALUES "; final String[] values = new String[_production.size()]; for (final SeedProduction s : _production) { values[count] = "(" + getId() + ',' + s.getId() + ',' + s.getCanProduce() + ',' + s.getStartProduce() + ',' + s.getPrice() + ',' + CastleManorManager.PERIOD_CURRENT + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += "," + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } if (_productionNext != null) { int count = 0; String query = "INSERT INTO castle_manor_production VALUES "; final String[] values = new String[_productionNext.size()]; for (final SeedProduction s : _productionNext) { values[count] = "(" + getId() + ',' + s.getId() + ',' + s.getCanProduce() + ',' + s.getStartProduce() + ',' + s.getPrice() + ',' + CastleManorManager.PERIOD_NEXT + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += ',' + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } } catch (final Exception e) { _log.error("Error adding seed production data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } // Save manor production data for specified period public void saveSeedData(final int period) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_MANOR_DELETE_PRODUCTION_PERIOD); statement.setInt(1, getId()); statement.setInt(2, period); statement.execute(); DbUtils.close(statement); List<SeedProduction> prod = null; prod = getSeedProduction(period); if (prod != null) { int count = 0; String query = "INSERT INTO castle_manor_production VALUES "; final String[] values = new String[prod.size()]; for (final SeedProduction s : prod) { values[count] = "(" + getId() + ',' + s.getId() + ',' + s.getCanProduce() + ',' + s.getStartProduce() + ',' + s.getPrice() + ',' + period + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += "," + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } } catch (final Exception e) { _log.error("Error adding seed production data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } // Save crop procure data public void saveCropData() { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE); statement.setInt(1, getId()); statement.execute(); DbUtils.close(statement); if (_procure != null) { int count = 0; String query = "INSERT INTO castle_manor_procure VALUES "; final String[] values = new String[_procure.size()]; for (final CropProcure cp : _procure) { values[count] = "(" + getId() + ',' + cp.getId() + ',' + cp.getAmount() + ',' + cp.getStartAmount() + ',' + cp.getPrice() + ',' + cp.getReward() + ',' + CastleManorManager.PERIOD_CURRENT + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += "," + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } if (_procureNext != null) { int count = 0; String query = "INSERT INTO castle_manor_procure VALUES "; final String[] values = new String[_procureNext.size()]; for (final CropProcure cp : _procureNext) { values[count] = "(" + getId() + ',' + cp.getId() + ',' + cp.getAmount() + ',' + cp.getStartAmount() + ',' + cp.getPrice() + ',' + cp.getReward() + ',' + CastleManorManager.PERIOD_NEXT + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += "," + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } } catch (final Exception e) { _log.error("Error adding crop data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } // Save crop procure data for specified period public void saveCropData(final int period) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_MANOR_DELETE_PROCURE_PERIOD); statement.setInt(1, getId()); statement.setInt(2, period); statement.execute(); DbUtils.close(statement); List<CropProcure> proc = null; proc = getCropProcure(period); if (proc != null) { int count = 0; String query = "INSERT INTO castle_manor_procure VALUES "; final String[] values = new String[proc.size()]; for (final CropProcure cp : proc) { values[count] = "(" + getId() + ',' + cp.getId() + ',' + cp.getAmount() + ',' + cp.getStartAmount() + ',' + cp.getPrice() + ',' + cp.getReward() + ',' + period + ')'; count++; } if (values.length > 0) { query += values[0]; for (int i = 1; i < values.length; i++) { query += "," + values[i]; } statement = con.prepareStatement(query); statement.execute(); DbUtils.close(statement); } } } catch (final Exception e) { _log.error("Error adding crop data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } public void updateCrop(final int cropId, final long amount, final int period) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_UPDATE_CROP); statement.setLong(1, amount); statement.setInt(2, cropId); statement.setInt(3, getId()); statement.setInt(4, period); statement.execute(); } catch (final Exception e) { _log.error("Error adding crop data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } public void updateSeed(final int seedId, final long amount, final int period) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con.prepareStatement(CASTLE_UPDATE_SEED); statement.setLong(1, amount); statement.setInt(2, seedId); statement.setInt(3, getId()); statement.setInt(4, period); statement.execute(); } catch (final Exception e) { _log.error("Error adding seed production data for castle " + getName() + '!', e); } finally { DbUtils.closeQuietly(con, statement); } } public boolean isNextPeriodApproved() { return _isNextPeriodApproved; } public void setNextPeriodApproved(final boolean val) { _isNextPeriodApproved = val; } public Dominion getDominion() { return dominion; } public void setDominion(final Dominion dominion) { this.dominion = dominion; } public void addRelatedFortress(final int type, final int fortress) { List<Integer> fortresses = relatedFortresses.computeIfAbsent(type, k -> new ArrayList<>()); fortresses.add(fortress); } public int getDomainFortressContract() { final List<Fortress> list = relatedFortresses.get(Fortress.DOMAIN); if (list == null) { return 0; } for (final Fortress f : list) { if (f.getContractState() == Fortress.CONTRACT_WITH_CASTLE && f.getCastleId() == getId()) { return f.getId(); } } return 0; } @Override public void update() { CastleDAO.getInstance().update(this); } public NpcString getNpcStringName() { return _npcStringName; } public Map<Integer, List> getRelatedFortresses() { return relatedFortresses; } public void addMerchantGuard(final MerchantGuard merchantGuard) { merchantGuards.put(merchantGuard.getItemId(), merchantGuard); } public MerchantGuard getMerchantGuard(final int itemId) { return merchantGuards.get(itemId); } public TIntObjectMap<MerchantGuard> getMerchantGuards() { return merchantGuards; } public Set<ItemInstance> getSpawnMerchantTickets() { return _spawnMerchantTickets; } @Deprecated public int getRewardCount() { return 0; } @Deprecated public void setRewardCount(final int rewardCount) { } @Override @Deprecated public void startCycleTask() { } }
true
8da3e4aaf89a721cf9ad5f8a7c16488ddb2b5e1f
Java
dc2586515515/webservice
/src/main/java/com/dc/springboot/webservice/service/impl/DemoServiceImpl.java
UTF-8
766
2.40625
2
[]
no_license
package com.dc.springboot.webservice.service.impl; import com.dc.springboot.webservice.service.DemoService; import org.springframework.scheduling.annotation.Async; import javax.jws.WebService; import java.util.Date; /** * @Description * @Author DC * @Date 2019-10-31 */ @WebService(serviceName = "DemoService", // 与接口中指定的name一致 targetNamespace = "http://service.webservice.springboot.dc.com", //与接口中的命名空间一致,一般是接口的包名倒 endpointInterface = "com.dc.springboot.webservice.service.DemoService" // 接口地址 ) public class DemoServiceImpl implements DemoService { @Override public String sayHello(String user) { return user+",现在时间:"+"("+new Date()+")"; } }
true
b5260eb067c6936d55c5104a29418dae43054b03
Java
perryhau/hades
/hades/com.bj58.spat.hades/src/main/java/com/bj58/spat/hades/bind/BindAndValidate.java
UTF-8
3,167
2.171875
2
[]
no_license
/* * Copyright Beijing 58 Information Technology Co.,Ltd. * * 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 com.bj58.spat.hades.bind; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import com.bj58.spat.hades.BeatContext; import com.bj58.spat.hades.binder.BindingResult; import com.bj58.spat.hades.binder.RequestBinder; import com.bj58.spat.hades.utils.BeanUtils; /** * 用于初始化绑定和校验工具并且完成绑定操作。 * 目前使用的校验工具为JSR303的参考实现Hibernate Validator。 * * @author Service Platform Architecture Team (spat@58.com) * */ public class BindAndValidate { private static Validator validator; static{ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); if(validator == null) validator = factory.getValidator(); } /** * 根据beat信息绑定一个目标对象 */ private static ObjectBindResult bind(Object target, BeatContext beat){ RequestBinder binder = new RequestBinder(target); binder.bind(beat.getRequest()); BindingResult r = binder.getBindingResult(); return new ObjectBindResult(r); } /** * 根据beat信息,和目标对象的类型,绑定一个目标对象 * @param targetType * @param beat * @return * @throws Exception */ public static ObjectBindResult bind(Class<?> targetType, BeatContext beat) throws Exception{ Object target = BeanUtils.instantiateClass(targetType); return bind(target, beat); } /** * 校验一个目标对象 * @param <T> * @param target * @return */ public static <T> ObjectBindResult validate(T target){; //javax.validation.ValidatorFactory. Set<ConstraintViolation<T>> constraintViolations = validator.validate(target); List<CheckedError> errors = new ArrayList<CheckedError>(); for(ConstraintViolation<T> constraintViolation : constraintViolations) { CheckedError error = new CheckedError(CheckedError.ErrorType.VALIDATE, constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage()); errors.add(error); } return new ObjectBindResult(target, errors); } }
true
12675e477a4889f6992c0f2a2acb7877ef12f8ff
Java
sumitsaiwal/LAPS_Servlet
/src/controller/viewsubleave.java
UTF-8
2,098
2.140625
2
[]
no_license
package controller; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.LeaveForm; import dao.LeaveFormSql; /** * Servlet implementation class viewsubleave */ @WebServlet("/viewsubleave") public class viewsubleave extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public viewsubleave() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } private void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String logid = request.getSession().getAttribute("logid").toString(); LeaveFormSql lf = new LeaveFormSql(); try{ ArrayList<LeaveForm> list = lf.getStaffLeave(logid); if(null!=list&&list.size()>0) { request.setAttribute("list",list); RequestDispatcher rd= request.getRequestDispatcher("subordinatehistory.jsp"); rd.forward(request, response); }else { String no = "No Record!"; request.setAttribute("norecord",no); RequestDispatcher rd= request.getRequestDispatcher("subordinatehistory.jsp"); rd.forward(request, response); } }catch(Exception e) { String error = "Woooppp...something wrong!"; request.setAttribute("error",error); RequestDispatcher rd= request.getRequestDispatcher("/bridge"); rd.forward(request, response); } } }
true
81f130fca7659fd83253f8e6f9de12d23b83a438
Java
devmpv/wady
/core/src/main/java/com/mpv/game/world/GameObj.java
UTF-8
6,137
1.851563
2
[]
no_license
package com.mpv.game.world; import static com.mpv.data.Const.STEP; import static com.mpv.data.Sounds.ID.*; import java.util.HashSet; import box2dLight.ConeLight; import box2dLight.RayHandler; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.World; import com.mpv.data.Assets; import com.mpv.data.Const; import com.mpv.data.Sounds; import com.mpv.data.GVars; import com.mpv.game.Collisions; import com.mpv.game.actors.Player; import com.mpv.ui.stages.GameUIStage; public class GameObj { public static final int ACTIVE = 0; public static final int PAUSE = 1; public static final int OVER = 2; public static final int FINISH = 3; public static int state = FINISH; // Delta time accumulator private float accumulator = 0; // Map data MapProperties mapProps; private float startTime; private float timeBonus; private int bonusCount; private int totalCoins; private final int[] points = new int[3]; // private int collectedCoins; public static int mapIndex = -1; private static GameObj instance; public static Body start, key, lock; private static final HashSet<Body> bodyTrash = new HashSet<>(); public static GameObj get() { if (instance == null) { instance = new GameObj(); } return instance; } public void loadWorld() { if (GVars.world != null) { GVars.world.dispose(); GVars.world = null; } GVars.world = new World(new Vector2(0, -9.8f), true); GVars.world.setContactListener(new Collisions()); collectedCoins = 0; mapProps = Assets.map.getProperties(); startTime = Float.parseFloat((String) mapProps.get("startTime")); timeBonus = Float.parseFloat((String) mapProps.get("timeBonus")); bonusCount = Integer.parseInt((String) mapProps.get("bonusCount")); totalCoins = Integer.parseInt((String) mapProps.get("coinsCount")); points[0] = Integer.parseInt((String) mapProps.get("points1")); points[1] = Integer.parseInt((String) mapProps.get("points2")); points[2] = Integer.parseInt((String) mapProps.get("points3")); MapManager.get().generate(); Player.get().createBody(); // Light if (GVars.rayHandler != null) GVars.rayHandler.dispose(); GVars.rayHandler = new RayHandler(GVars.world); GVars.sceneryLight = new ConeLight(GVars.rayHandler, 24, new Color(0.72f, 0.72f, 0.0f, 1f), Const.VIEWPORT_METERS / 3.2f, Const.BLOCK_SIZE, Const.BLOCK_SIZE, 0f, 180f); GVars.sceneryLight.attachToBody(Player.get().body, 0f, 0f); GVars.playerLight = new ConeLight(GVars.rayHandler, 24, new Color(0.72f, 0.72f, 0.72f, 1f), Const.VIEWPORT_METERS, Const.BLOCK_SIZE, Const.BLOCK_SIZE, 90f, 30f); GVars.playerLight.setSoft(true); // GVars.playerLight.setStaticLight(true); } public float getTimeBonus() { return timeBonus; } public int getBonusCount() { return bonusCount; } public int getTotalCoins() { return totalCoins; } public void gameStart() { GameTimer.get().setTimer(startTime); Player.get().resetGame(); state = ACTIVE; Player.state = Player.S_IDLE; Sounds.play(START); } public void gamePause() { state = PAUSE; Player.state = Player.S_FALL; } public void gameResume() { if (state != PAUSE) { loadWorld(); gameStart(); } else { state = ACTIVE; } } public void gameFinish() { state = FINISH; Player.state = Player.S_INVISIBLE; GameUIStage.get().gameFinish(); } public void gameOver() { state = OVER; Player.state = Player.S_INVISIBLE; GameUIStage.get().gameOver(); } public void gameUpdate(float delta) { if (state != ACTIVE) { return; } GameTimer.get().update(delta); worldUpdate(delta); } public float getMapLimit() { return startTime; } public void worldUpdate(float delta) { // No interpolation accumulator += delta; while (accumulator >= STEP) { update(STEP); accumulator -= STEP; } /* * if (accumulator >= STEP / 2f) { Player.get().interpolate(accumulator); } */ } private void update(float value) { Player.get().applyForces(); GVars.world.step(value, Const.BOX_VELOCITY_ITERATIONS, Const.BOX_POSITION_ITERATIONS); Player.get().update(); } public static void captureKey() { MapManager.get().removeItem((Position) key.getUserData()); bodyTrash.add(key); key = null; Sounds.play(KEY); } public void clearBodies() { for (Body body : bodyTrash) { // Unlocking door here. Not the best place if (body == lock) { lock = null; start.setActive(true); } GVars.world.destroyBody(body); } bodyTrash.clear(); } public void collectTime(Body body) { MapManager.get().removeItem((Position) body.getUserData()); bodyTrash.add(body); Sounds.play(GET_BATTERY); GameTimer.get().addSeconds(10); } public void collectDiamond(Body body) { MapManager.get().removeItem((Position) body.getUserData()); bodyTrash.add(body); Sounds.play(GET_DIAMOND); collectedCoins++; } public int getPoints(int index) { return points[index]; } public int getCoinCount() { return collectedCoins; } public static void captureLock() { MapManager.get().removeItem((Position) lock.getUserData()); MapManager.get().unlockExit(); bodyTrash.add(lock); Sounds.play(LOCK); } }
true
dfdb5237bfa21417238d160e0f9d96c53944f09f
Java
CSC207-TLI-TBTEENS/ftms-tbteens-api
/src/main/java/com/ftms/ftmsapi/controller/TaskController.java
UTF-8
4,603
2.5
2
[]
no_license
package com.ftms.ftmsapi.controller; import javax.persistence.EntityNotFoundException; import javax.validation.Valid; import com.ftms.ftmsapi.model.*; import com.ftms.ftmsapi.payload.ApiResponse; import com.ftms.ftmsapi.repository.PartRequestRepository; import com.ftms.ftmsapi.repository.TaskRepository; import com.ftms.ftmsapi.repository.TimesheetRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api") public class TaskController { @Autowired TimesheetRepository timesheetRepository; @Autowired TaskRepository taskRepository; @Autowired PartRequestRepository partRequestRepository; @GetMapping("tasks/{ID}") public ResponseEntity getTaskByID(@PathVariable Long ID) { try { return new ResponseEntity<Object>(taskRepository.getOne(ID), HttpStatus.OK); } catch (EntityNotFoundException error) { return new ResponseEntity<Object>(new ApiResponse(false, "Task not found."), HttpStatus.BAD_REQUEST); } } @GetMapping("/timesheets/{timesheet_id}/tasks") public ResponseEntity getTasksByTimesheetID(@PathVariable Long timesheet_id) { try { Timesheet timesheet = timesheetRepository.getOne(timesheet_id); List<Task> tasks = taskRepository.findByTimesheet(timesheet); return new ResponseEntity<Object>(tasks, HttpStatus.OK); } catch (EntityNotFoundException e) { return new ResponseEntity<Object>(new ApiResponse(false, "Timesheet not found!"), HttpStatus.BAD_REQUEST); } } @PostMapping("/timesheets/{timesheet_id}/tasks") public ResponseEntity createTask(@Valid @RequestBody Task task, @PathVariable Long timesheet_id){ try { Timesheet timesheet = timesheetRepository.getOne(timesheet_id); task.setTimesheet(timesheet); // Set the timesheet to the correct one. Task createdTask = taskRepository.save(task); return new ResponseEntity<Object>(createdTask, HttpStatus.OK); } catch (EntityNotFoundException e) { return new ResponseEntity<Object>(new ApiResponse(false, "Something went wrong! Please try again!"), HttpStatus.BAD_REQUEST); // Return error message. } } @GetMapping("") public List<Task> getAllTasks(){ return taskRepository.findAll(); } @PutMapping("/tasks/{id}") public ResponseEntity editTask(@PathVariable Long id, @Valid @RequestBody Task task){ try { Task taskToEdit = taskRepository.getOne(id); taskToEdit.setName(task.getName()); taskToEdit.setDescription(task.getDescription()); // Consider changing to taskRepository.update(id) taskRepository.save(taskToEdit); return new ResponseEntity<Object>(new ApiResponse(true, "Task updated successfully!"), HttpStatus.ACCEPTED); } catch (EntityNotFoundException e) { // Consider sending HTTP Response instead return new ResponseEntity<Object>(new ApiResponse(false, "Cannot find the task specified."), HttpStatus.BAD_REQUEST); } } @DeleteMapping("/tasks/{id}") public ResponseEntity<HttpStatus> deleteTask(@PathVariable long id){ try{ Task task = taskRepository.getOne(id); taskRepository.delete(task); return new ResponseEntity<>(HttpStatus.ACCEPTED); } catch (EntityNotFoundException e){ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @PostMapping("tasks/parts") public ResponseEntity createPartRequest(@Valid @RequestBody PartRequest partRequest) { System.out.println("error"); try { PartRequest newRequest = partRequestRepository.save(partRequest); return new ResponseEntity<Object>(newRequest, HttpStatus.ACCEPTED); } catch (Exception error) { error.printStackTrace(); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } } // @GetMapping("/tasksById/{id}") // public Optional<Task> getTaskById(@PathVariable long id){ // return taskRepository.findById(id); // } }
true
7758e237540ac42151b4b4c35bd9c521f83a4bc0
Java
haiZhaoChen/zczwandroid
/app/src/main/java/org/bigdata/zczw/jPush/MyReceiver.java
UTF-8
2,574
2.265625
2
[ "Apache-2.0" ]
permissive
package org.bigdata.zczw.jPush; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.bigdata.zczw.activity.CheckListActivity; import org.bigdata.zczw.activity.MainActivity; import org.bigdata.zczw.activity.StartActivity; import java.util.List; import cn.jpush.android.api.JPushInterface; /** * 自定义接收器 * * 如果不定义这个 Receiver,则: * 1) 默认用户会打开主界面 * 2) 接收不到自定义消息 */ public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); processCustomMessage(context,bundle); boolean back = isBackground(context); if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { if (back) {//系统没有启动; //启动app Intent i = new Intent(context, StartActivity.class); i.putExtras(bundle); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP ); context.startActivity(i); }else{ //跳到主Activity Intent i = new Intent(context, CheckListActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP ); context.startActivity(i); } } } // //send msg to MainActivity private void processCustomMessage(Context context, Bundle bundle) { String extras = bundle.getString(JPushInterface.EXTRA_EXTRA); Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION); msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras); context.sendBroadcast(msgIntent); } public static boolean isBackground(Context context) { ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager .getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equals(context.getPackageName())) { /* BACKGROUND=400 EMPTY=500 FOREGROUND=100 GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200 */ if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } else { Log.i(context.getPackageName(), "处于前台" + appProcess.processName); return false; } } } return false; } }
true
c2c7fa1dd554afaad8f27381acbcdbabdbe30a25
Java
imappu/IdealPortal
/AppointmentPortal/src/com/application/entity/Patient.java
UTF-8
2,636
2.59375
3
[]
no_license
package com.application.entity; import javax.persistence.*; import com.application.interfaces.IPatient; /** * Entity class for Patient registration details with getters ,setters and constructor definitions. * @author Apparay Shakapure <AS052304> * @version 1.0 *@since 1.0 */ @NamedNativeQueries({ @NamedNativeQuery(name = "findpatient", query = "select * from patiententity s where s.contact = :contact and s.password = :password", resultClass = Patient.class) , @NamedNativeQuery(name = "findcontact", query = "select * from patiententity s where s.contact = :contact", resultClass = Patient.class) } ) @Entity @Table(name = "patiententity") public class Patient implements IPatient{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "firstname") private String FirstName; @Column(name = "lastname") private String LastName; @Column(name = "password") private String Password; @Column(name = "contact", unique = true) private String Contact; @Column(name = "email", unique = true) private String Email; @Column(name = "dob") private String dob; @Column(name = "gender") private String Gender; @Column(name = "address") private String Address; public Patient(String firstName, String lastName, String password, String contact, String email, String dob, String gender, String address) { super(); FirstName = firstName; LastName = lastName; Password = password; Contact = contact; Email = email; this.dob = dob; Gender = gender; Address = address; } public Patient() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return FirstName; } public void setFirstName(String firstName) { FirstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public String getContact() { return Contact; } public void setContact(String contact) { Contact = contact; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } public String getGender() { return Gender; } public void setGender(String gender) { Gender = gender; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } }
true
91174cad885bd6dad1959ad5faffe44996bba759
Java
msegeya/MobileBankingSystemProject
/src/com/MobileBankingSystem/customer/Customer_Nonmember.java
UTF-8
417
2.453125
2
[]
no_license
package com.MobileBankingSystem.customer; public class Customer_Nonmember extends Customer{ private static String c_phone; public Customer_Nonmember(String banking_id, String banking_pwd) { super(c_phone, banking_pwd); // TODO Auto-generated constructor stub } public String getC_phone() { return c_phone; } public void setC_phone(String c_phone) { this.c_phone = c_phone; } }
true
db4dbb1e841c20bff7a4334177c6d217501155f1
Java
JKAK47/robust-demo
/dubbo-provide-demo/src/main/java/com/toby/provider/ApplicationProperties.java
UTF-8
629
2.0625
2
[]
no_license
package com.toby.provider; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; @ConfigurationProperties(prefix = "feichao.info") /** 加载外部配置 注解*/ @Component @Validated /** 触发Bean校验 注解*/ @Data /** 省略 setter 、getter 方法 注解*/ public class ApplicationProperties { @NotBlank(message = "名字不能为空,请注意检查,参考值为:肥朝。") private String name; }
true
2735330e631df7179cbc91c4028110ed00c4a976
Java
BalajiStark/html
/loop.java
UTF-8
347
2.84375
3
[]
no_license
import java.util.*; public class loop { public static void main(String[] args) { Scanner in=new Scanner(System.in); int[] a=new int[args.length]; int n=args.length,sum=0; for(int i=0;i<n;i++) { a[i]=Integer.parseInt(args[i]); sum=sum+a[i]; } System.out.println(sum); } }
true
ff2dc2c8c4dc23ddca20f0fdf610a1fbb9e48e93
Java
tinvukhac/asterixdb
/asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/input/record/reader/hdfs/parquet/ParquetReadSupport.java
UTF-8
4,114
1.734375
2
[ "MIT", "BSD-3-Clause", "PostgreSQL", "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.asterix.external.input.record.reader.hdfs.parquet; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.asterix.external.util.ExternalDataConstants; import org.apache.asterix.external.util.HDFSUtils; import org.apache.asterix.om.types.ARecordType; import org.apache.asterix.runtime.projection.FunctionCallInformation; import org.apache.hadoop.conf.Configuration; import org.apache.hyracks.api.exceptions.Warning; import org.apache.hyracks.data.std.api.IValueReference; import org.apache.parquet.hadoop.api.InitContext; import org.apache.parquet.hadoop.api.ReadSupport; import org.apache.parquet.io.api.GroupConverter; import org.apache.parquet.io.api.RecordMaterializer; import org.apache.parquet.schema.MessageType; public class ParquetReadSupport extends ReadSupport<IValueReference> { @Override public ReadContext init(InitContext context) { MessageType requestedSchema = getRequestedSchema(context); return new ReadContext(requestedSchema, Collections.emptyMap()); } @Override public RecordMaterializer<IValueReference> prepareForRead(Configuration configuration, Map<String, String> keyValueMetaData, MessageType fileSchema, ReadContext readContext) { return new ADMRecordMaterializer(readContext); } private static MessageType getRequestedSchema(InitContext context) { Configuration configuration = context.getConfiguration(); MessageType fileSchema = context.getFileSchema(); boolean shouldWarn = configuration.getBoolean(ExternalDataConstants.KEY_HADOOP_ASTERIX_WARNINGS_ENABLED, false); AsterixTypeToParquetTypeVisitor visitor = new AsterixTypeToParquetTypeVisitor(shouldWarn); try { ARecordType expectedType = HDFSUtils.getExpectedType(configuration); Map<String, FunctionCallInformation> functionCallInformationMap = HDFSUtils.getFunctionCallInformationMap(configuration); MessageType requestedType = visitor.clipType(expectedType, fileSchema, functionCallInformationMap); List<Warning> warnings = visitor.getWarnings(); if (shouldWarn && !warnings.isEmpty()) { //New warnings were created, set the warnings in hadoop configuration to be reported HDFSUtils.setWarnings(warnings, configuration); //Update the reported warnings so that we do not report the same warning again HDFSUtils.setFunctionCallInformationMap(functionCallInformationMap, configuration); } return requestedType; } catch (IOException e) { throw new IllegalStateException(e); } } private static class ADMRecordMaterializer extends RecordMaterializer<IValueReference> { private final RootConverter rootConverter; public ADMRecordMaterializer(ReadContext readContext) { rootConverter = new RootConverter(readContext.getRequestedSchema()); } @Override public IValueReference getCurrentRecord() { return rootConverter.getRecord(); } @Override public GroupConverter getRootConverter() { return rootConverter; } } }
true
b98828c62eeb7758064fe8b496837675fab26b8e
Java
COSMEcontrol/miniblas-android
/app/src/main/java/com/miniblas/persistence/SharedPreferencesSettingStorage.java
UTF-8
2,290
2.21875
2
[]
no_license
package com.miniblas.persistence; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.miniblas.model.MiniBlasProfile; /** * * @author A. Azuara */ public class SharedPreferencesSettingStorage implements SettingStorage{ //editor de preferencias private SharedPreferences preferencias; private SharedPreferences.Editor editor; public static final String PREF_AUTOCONEXION = "PREF_AUTOCONEXION"; public static final String PREF_AUTOCONEXION_ID_PROFILE = "bagPref"; public static final String PREF_DEFAULT_PORT = "porPref"; public static final String PREF_DEFAULT_PASS = "passPref"; public static final String PREF_TERMINAL = "PREF_TERMINAL"; public SharedPreferencesSettingStorage(Context ctx){ preferencias = PreferenceManager.getDefaultSharedPreferences(ctx); editor = preferencias.edit(); } @Override public boolean getPrefAutoConexion(){ return preferencias.getBoolean(PREF_AUTOCONEXION, false); } @Override public int getPrefAutoConexionIdProfile(){ return Integer.valueOf(preferencias.getString(PREF_AUTOCONEXION_ID_PROFILE, "0")); } @Override public void setPrefAutoConexion(boolean _autoConexion){ editor.putBoolean(PREF_AUTOCONEXION, _autoConexion); editor.commit(); } @Override public void setPrefAutoConexionIdProfile(int _ip){ editor.putString(PREF_AUTOCONEXION_ID_PROFILE, String.valueOf(_ip)); editor.commit(); } // @Override // public void setPrefDefaultPort(int _port) { // editor.putInt(PREF_DEFAULT_PORT,_port); // editor.commit(); // } // // @Override // public void setPrefDefaultIp(String _ip) { // editor.putString(PREF_DEFAULT_IP, _ip); // editor.commit(); // // } @Override public int getPrefDefaultPort(){ return Integer.valueOf(preferencias.getString(PREF_DEFAULT_PORT, String.valueOf(MiniBlasProfile.PUERTO_POR_DEFECTO))); } @Override public String getPrefDefaultPassword(){ return preferencias.getString(PREF_DEFAULT_PASS, MiniBlasProfile.CONTRASEÑA_POR_DEFECTO); } @Override public boolean getPrefTerminal(){ return preferencias.getBoolean(PREF_TERMINAL, false); } @Override public void setPrefTerminal(boolean _pref){ editor.putBoolean(PREF_TERMINAL, _pref); editor.commit(); } }
true
4af3d81f81c44cc8f18c018f970ecfda62060db3
Java
jrtkcoder/spring_boot_app01
/src/main/java/com/briup/apps/app01/web/UserController.java
UTF-8
4,366
2.40625
2
[]
no_license
package com.briup.apps.app01.web; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.briup.apps.app01.bean.User; import com.briup.apps.app01.view.UserView; import com.fasterxml.jackson.annotation.JsonRawValue; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.ObjectMapper; @RestController @CrossOrigin @RequestMapping(path={"/users"}) public class UserController { /** * 参数写在URL中 * 可以匹配url为 http://localhost:8080/users/findById/1001 * */ @GetMapping(path={"/findById/{id}"}) public String allUsers(@PathVariable long id) { return "this is users, id :"+id; } /** * 参数获取 * */ @PostMapping(path = "/saveUser", consumes = "application/json") public String saveUser(@RequestBody User user,@RequestParam int id) { System.out.println("id:"+id); System.out.println("user:"+user); return ""; } /** * c参数获取 * */ @PostMapping(path = "/addUser") @ResponseBody public String addUser(@ModelAttribute User user) { System.out.println("addUser:"+user); return "success"; } /** * 获取cookie * */ @GetMapping(path = "/getCookie") public String getCookie(@CookieValue("JSESSIONID") String cookie , HttpServletRequest request) { System.out.println("cookie:"+cookie); Cookie[] cookies = request.getCookies(); if(cookies!=null) { for(Cookie c :cookies) { System.out.println(c.getName()+":"+c.getValue()); } } return ""; } /** * 设置cookie * */ @GetMapping(path = "/setCookie") public String setCookie(HttpSession session) { User user = new User(1001L, "terry"); session.setAttribute("user", user); return "登录成功!"; } @GetMapping(path="/getUsers") @JsonRawValue public List<User> getUsers() { List<User> list = new ArrayList<>(); User user1 = new User(1001L, "中文"); list.add(user1); list.add(new User(1002L, "terry")); return list ; } /** * * */ @GetMapping(path="/getUserJson") //@JsonView(UserView.Detail.class) @JsonRawValue public User getUser() { User user = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //初始化对象 Date birth = sdf.parse("1991-10-1"); user = new User(1001L, "terry","男",birth); //设置集合 List<String> ls = new ArrayList<>(); for(int i=1;i<10;i++) { ls.add("1889682792"+i); } user.setPhones(ls); } catch (Exception e) { e.printStackTrace(); } return user; } /** * 文件上传 * */ @PostMapping("/form") public String handleFormUpload(@RequestParam("name") String name, @RequestParam("picture") MultipartFile file, HttpServletRequest request) { String realPath = request.getServletContext().getRealPath("/"); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); System.out.println(file.getContentType()); System.out.println(bytes); File out = new File(realPath+"a.doc"); if(!out.exists()) { out.createNewFile(); } FileCopyUtils.copy(bytes,out ); } catch (IOException e) { e.printStackTrace(); return "redirect:uploadFailure"; } return "redirect:uploadSuccess"; } return "redirect:uploadFailure"; } }
true
3d82d185831b5b399528d1752b840b5378ebfec0
Java
Emn98/D0010E_lab_5
/lab5/src/lab5/deds/View.java
UTF-8
683
3.03125
3
[]
no_license
package lab5.deds; import java.util.Observable; import java.util.Observer; import lab5.snabbköp.state.SnabbköpState; /** * * A general class for the view. * * @author Isak Lundmark, Emil Nyberg and Karl Näslund. * */ public class View implements Observer { private State state; /** * Creates a view for a sate. * * @param state to create a view for. */ public View(State state) { this.state = state; } /** * Creates an update method for inheritance. * */ public void update(Observable o, Object arg) { } /** * Gets a state * * @return the viewable state. */ public State getState() { return state; } }
true
f01fe00be14bf1a8c0c2662156327cc9ad4c14de
Java
labourel/vector
/src/main/java/ArrayVector.java
UTF-8
1,565
3.15625
3
[]
no_license
/** * Created by Arnaud Labourel on 15/10/2018. */ public class ArrayVector implements Vector { private static final int DEFAULT_CAPACITY = 10000; private final int[] array; private int size; public ArrayVector() { this(DEFAULT_CAPACITY); } public ArrayVector(int capacity) { assert capacity >= 0; this.size = 0; array = new int[capacity]; for(int index = 0; index<array.length; index++){ array[index] = -1; } } @Override public String toString() { return "ArrayVector{}"; } @Override public int[] toArray() { return new int[0]; } @Override public int length() { return 0; } @Override public int get(int index) { return 0; } @Override public boolean set(int index, int value) { return false; } @Override public void resize(int size) { } @Override public boolean add(int value) { return false; } @Override public boolean fillFromStandardInput() { return false; } @Override public int indexOf(int value) { return 0; } @Override public boolean remove(int index) { return false; } @Override public boolean isSorted() { return false; } @Override public Vector mergeSorted(Vector vector) { return null; } @Override public boolean insertSorted(int value) { return false; } @Override public void sort() { } }
true
44420794f7d933986b709bb2aa099b7fe2a17e92
Java
Dobby233Liu/canvas
/src/main/java/grondag/canvas/light/LightSmoother.java
UTF-8
6,855
2.0625
2
[ "Apache-2.0" ]
permissive
package grondag.canvas.light; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BlockRenderView; import grondag.canvas.chunk.FastRenderRegion; import grondag.fermion.position.PackedBlockPos; // TODO: look at VoxelShapes.method_1080 as a way to not propagate thru slabs // Also BlockState.hasSidedTransparency seems promising public class LightSmoother { public static final int OPAQUE = -1; private static final int BLUR_RADIUS = 2; private static final int MARGIN = BLUR_RADIUS + 2; private static final int POS_DIAMETER = 16 + MARGIN * 2; private static final int POS_COUNT = POS_DIAMETER * POS_DIAMETER * POS_DIAMETER; private static final int Y_INC = POS_DIAMETER; private static final int Z_INC = POS_DIAMETER * POS_DIAMETER; private static class Helper { private final BlockPos.Mutable smoothPos = new BlockPos.Mutable(); private final int a[] = new int[POS_COUNT]; private final int b[] = new int[POS_COUNT]; private final int c[] = new int[POS_COUNT]; } private static final ThreadLocal<Helper> helpers = ThreadLocal.withInitial(Helper::new); public static void computeSmoothedBrightness(BlockPos chunkOrigin, BlockRenderView blockViewIn, Long2IntOpenHashMap output) { final Helper help = helpers.get(); final BlockPos.Mutable smoothPos = help.smoothPos; final int[] sky = help.a; final int[] block = help.b; final int minX = chunkOrigin.getX() - MARGIN; final int minY = chunkOrigin.getY() - MARGIN; final int minZ = chunkOrigin.getZ() - MARGIN; final FastRenderRegion view = (FastRenderRegion) blockViewIn; for(int x = 0; x < POS_DIAMETER; x++) { for(int y = 0; y < POS_DIAMETER; y++) { for(int z = 0; z < POS_DIAMETER; z++) { final int bx = x + minX; final int by = y + minY; final int bz = z + minZ; smoothPos.set(bx, by, bz); final BlockState state = view.getBlockState(bx, by, bz); //PERF: consider packed pos // don't use cache here because we are populating the cache final int packedLight = view.directBrightness(smoothPos); //PERF: use cache final boolean opaque = state.isFullOpaque(view, smoothPos); // // subtractedCache.put(packedPos, (short) subtracted); final int i = index(x, y , z); if(opaque) { block[i] = OPAQUE; sky[i] = OPAQUE; } else if(packedLight == 0) { block[i] = 0; sky[i] = 0; } else { block[i] = (packedLight & 0xFF); sky[i] = ((packedLight >>> 16) & 0xFF); } } } } final int[] work = help.c; smooth(BLUR_RADIUS + 1, block, work); smooth(BLUR_RADIUS, work, block); // smooth(1, block, work); // float[] swap = block; // block = work; // work = swap; smooth(BLUR_RADIUS + 1, sky, work); smooth(BLUR_RADIUS, work, sky); // smooth(1, sky, work); // swap = sky; // sky = work; // work = swap; final int limit = 16 + MARGIN + 1; for(int x = MARGIN - 2; x < limit; x++) { for(int y = MARGIN - 2; y < limit; y++) { for(int z = MARGIN - 2; z < limit; z++) { final long packedPos = PackedBlockPos.pack(x + minX, y + minY, z + minZ); final int i = index(x, y , z); final int b = MathHelper.clamp(((block[i]) * 104 + 51) / 100, 0, 240); final int k = MathHelper.clamp(((sky[i]) * 104 + 51) / 100, 0, 240); output.put(packedPos, ((b + 2) & 0b11111100) | (((k + 2) & 0b11111100) << 16)); } } } } private static int index(int x, int y, int z) { return x + y * Y_INC + z * Z_INC; } private static final int INNER_DIST = 28966; // fractional part of 0xFFFF private static final int OUTER_DIST = (0xFFFF - INNER_DIST) / 2; private static final int INNER_PLUS = INNER_DIST + OUTER_DIST; private static void smooth(int margin, int[] src, int[] dest) { final int xBase = MARGIN - margin; final int xLimit = POS_DIAMETER - MARGIN + margin; final int yBase = xBase * Y_INC; final int yLimit = xLimit * Y_INC; final int zBase = xBase * Z_INC; final int zLimit = xLimit * Z_INC; // X PASS for(int x = xBase; x < xLimit; x++) { for(int y = yBase; y < yLimit; y += Y_INC) { for(int z = zBase; z < zLimit; z += Z_INC) { final int i = x + y + z; final int c = src[i]; if(c == OPAQUE) { dest[i] = OPAQUE; continue; } // int a = src[index(x + 1, y, z)]; // int b = src[index(x - 1, y, z)]; final int a = src[i + 1]; final int b = src[i - 1]; if(a == OPAQUE) { if(b == OPAQUE) { dest[i] = c; } else { dest[i] = (b * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16 ; } } else if(b == OPAQUE) { dest[i] = (a * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16; } else { dest[i] = (a * OUTER_DIST + b * OUTER_DIST + c * INNER_DIST + 0x7FFF) >> 16; } } } } // Y PASS for(int x = xBase; x < xLimit; x++) { for(int y = yBase; y < yLimit; y += Y_INC) { for(int z = zBase; z < zLimit; z += Z_INC) { final int i = x + y + z; // Note arrays are swapped here final int c = dest[i]; if(c == OPAQUE) { src[i] = OPAQUE; continue; } // int a = dest[index(x, y - 1, z)]; // int b = dest[index(x, y + 1, z)]; final int a = dest[i + Y_INC]; final int b = dest[i - Y_INC]; if(a == OPAQUE) { if(b == OPAQUE) { src[i] = c; } else { src[i] = (b * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16; } } else if(b == OPAQUE) { src[i] = (a * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16; } else { src[i] = (a * OUTER_DIST + b * OUTER_DIST + c * INNER_DIST + 0x7FFF) >> 16; } } } } // Z PASS for(int x = xBase; x < xLimit; x++) { for(int y = yBase; y < yLimit; y += Y_INC) { for(int z = zBase; z < zLimit; z += Z_INC) { final int i = x + y + z; // Arrays are swapped back to original roles here final int c = src[i]; if(c == OPAQUE) { dest[i] = OPAQUE; continue; } // int a = src[index(x, y, z - 1)]; // int b = src[index(x, y, z + 1)]; final int a = src[i + Z_INC]; final int b = src[i - Z_INC]; if(a == OPAQUE) { if(b == OPAQUE) { dest[i] = c; } else { dest[i] = (b * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16; } } else if(b == OPAQUE) { dest[i] = (a * OUTER_DIST + c * INNER_PLUS + 0x7FFF) >> 16; } else { dest[i] = (a * OUTER_DIST + b * OUTER_DIST + c * INNER_DIST + 0x7FFF) >> 16; } } } } } }
true
9376a46d86c7b36b0c232e31dadb1fc15a94e46d
Java
devshah2/6024-2018
/src/org/usfirst/frc/team6024/robot/subsystems/DriveSubsystem.java
UTF-8
6,946
2.15625
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package org.usfirst.frc.team6024.robot.subsystems; import org.usfirst.frc.team6024.robot.OI; import org.usfirst.frc.team6024.robot.RobotMap; import org.usfirst.frc.team6024.robot.Sensors; import org.usfirst.frc.team6024.robot.commands.DefaultDriveCommand; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * An example subsystem. You can replace me with your own Subsystem. */ public class DriveSubsystem extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. VictorSP fl, fr, bl, br; public DriveSubsystem() { fl = new VictorSP(RobotMap.LFmotor); fr = new VictorSP(RobotMap.RFmotor); bl = new VictorSP(RobotMap.LBmotor); br = new VictorSP(RobotMap.RBmotor); fl.setInverted(true); bl.setInverted(true); } public void initDefaultCommand() { // Set the default command for a subsystem here. setDefaultCommand(new DefaultDriveCommand()); } public void move(double left, double right) { fl.set(left); fr.set(right); bl.set(left); br.set(right); } public void driveTeleop() { double yaxis = OI.driveStick.getY(); double zaxis = OI.driveStick.getZ(); boolean boost = OI.driveStick.getRawButton(2); boolean trigger = OI.driveStick.getRawButton(1); if(trigger) { move(0, 0); }else if(Math.abs(zaxis) > 0.3 || Math.abs(yaxis) > 0.25) { if(Math.abs(zaxis) > Math.abs(yaxis)) move(-(zaxis - Math.signum(zaxis)*0.175)*0.55, (zaxis-Math.signum(zaxis)*0.175)*0.55); else { if(boost) move(yaxis*0.8, yaxis*0.8); else move(yaxis*0.6, yaxis*0.6); } }else { move(0, 0); } } double angleOffset = 0; double errorSum = 0; int timeCount = 0; public void drivePIDEncoders() { //put failsafe here double yaxis = OI.driveStick.getY(); double zaxis = OI.driveStick.getZ(); double xaxis = OI.driveStick.getX(); boolean boost = OI.driveStick.getRawButton(2); boolean trigger = OI.driveStick.getRawButton(1); boolean leftPivot = OI.driveStick.getRawButton(3); boolean rightPivot = OI.driveStick.getRawButton(4); double boostMult = trigger?0.25:(boost?0.8:0.55); if(leftPivot){ if(zaxis > 0.2) move(-zaxis*boostMult*0.8, zaxis*boostMult*0.2); else if(zaxis < -0.2) move(-zaxis*boostMult*0.2, zaxis*boostMult*0.8); else move(0, 0); timeCount = 0; }else if(rightPivot){ if(zaxis > 0.2) move(-zaxis*boostMult*0.2, zaxis*boostMult*0.8); else if(zaxis < -0.2) move(-zaxis*boostMult*0.8, zaxis*boostMult*0.2); else move(0, 0); timeCount = 0; }else if(Math.abs(zaxis) > 0.3 || Math.abs(yaxis) > 0.25) { if(Math.abs(zaxis) > Math.abs(yaxis)) { move(-(zaxis - Math.signum(zaxis)*0.175)*boostMult*0.8, (zaxis-Math.signum(zaxis)*0.175)*boostMult*0.8); timeCount = 0; }else if(xaxis > 0.5 || xaxis < -0.5) { double steeringMult = Math.pow(1 + Math.abs(xaxis)*1.0 - 0.5, Math.signum(xaxis)); double leftSpeed = yaxis*boostMult*steeringMult; double rightSpeed = yaxis*boostMult/steeringMult; move(leftSpeed, rightSpeed); timeCount = 0; }else { double leftSpeed = yaxis*boostMult; double rightSpeed = yaxis*boostMult; if(timeCount > 4) { double ratio = (Sensors.rightE.getRate() + 0.00000000000001)/Sensors.leftE.getRate(); leftSpeed *= ratio; rightSpeed /= ratio; } move(leftSpeed, rightSpeed); timeCount++; } }else { move(0, 0); timeCount = 0; } } public void drivePID() { if(Sensors.navx.isConnected() == false) { //driveTeleop(); //return; errorSum = 0; } double yaxis = OI.driveStick.getY(); double zaxis = OI.driveStick.getZ(); double xaxis = OI.driveStick.getX(); boolean boost = OI.driveStick.getRawButton(1); boolean trigger = OI.driveStick.getRawButton(2); boolean leftPivot = OI.driveStick.getRawButton(3); boolean rightPivot = OI.driveStick.getRawButton(4); double boostMult = trigger?0.3:(boost?0.85:0.7); double curAngle = Sensors.navx.getFusedHeading(); if(leftPivot){ if(zaxis > 0.2) move(-zaxis*boostMult*0.8, zaxis*boostMult*0.2); else if(zaxis < -0.2) move(-zaxis*boostMult*0.2, zaxis*boostMult*0.8); else move(0, 0); angleOffset = Sensors.navx.getFusedHeading(); errorSum = 0; timeCount = 0; }else if(rightPivot){ if(zaxis > 0.2) move(-zaxis*boostMult*0.2, zaxis*boostMult*0.8); else if(zaxis < -0.2) move(-zaxis*boostMult*0.8, zaxis*boostMult*0.2); else move(0, 0); angleOffset = Sensors.navx.getFusedHeading(); errorSum = 0; timeCount = 0; }else if(Math.abs(zaxis) > 0.3 || Math.abs(yaxis) > 0.25) { if(Math.abs(zaxis) > Math.abs(yaxis)) { move(-(zaxis - Math.signum(zaxis)*0.175)*boostMult*0.8, (zaxis-Math.signum(zaxis)*0.175)*boostMult*0.8); angleOffset = curAngle; errorSum = 0; timeCount = 0; }else if(xaxis > 0.5 || xaxis < -0.5) { double steeringMult = Math.pow(1 + Math.abs(xaxis)*1.0 - 0.5, Math.signum(xaxis)); double leftSpeed = yaxis*boostMult*steeringMult;//*Math.min(1, timeCount/30.000); double rightSpeed = yaxis*boostMult/steeringMult;//*Math.min(1, timeCount/30.000); move(leftSpeed, rightSpeed); angleOffset = curAngle; timeCount = 0; errorSum =0; }else { if(timeCount <= 10) angleOffset = curAngle; double angDiff = Sensors.findHeading(angleOffset, curAngle); errorSum += angDiff*0.05; double pidMult = Math.pow(angDiff/35.00 + errorSum/35.00 + 1, Math.signum(-yaxis)); double leftSpeed = yaxis*boostMult*pidMult;//*Math.min(1, timeCount/30.000); double rightSpeed = yaxis*boostMult/pidMult;//*Math.min(1, timeCount/30.00); move(leftSpeed, rightSpeed); timeCount++; } }else { move(0, 0); angleOffset = curAngle; errorSum = 0; timeCount = 0; } SmartDashboard.putNumber("angleOffset", angleOffset); SmartDashboard.putNumber("angdiff", Sensors.findHeading(angleOffset, curAngle)); } public double movePID(double speed, double initialAngle, double curError) { speed *= -1; double curAngle = Sensors.navx.getFusedHeading(); double angDiff = Sensors.findHeading(initialAngle, curAngle); double pidMult = Math.pow((angDiff/35.00) + (curError/40.00) + 1, Math.signum(-speed)); double leftSpeed = speed*pidMult; double rightSpeed = speed/pidMult; move(leftSpeed, rightSpeed); return curError + angDiff*0.03; } }
true
e11a678efdc7a12b0f1f5b240697b58d5366d0ba
Java
huiwen/IS306-BrainJuice
/BrainJuice/src/com/example/brainjuice/entity/UserMgr.java
UTF-8
1,276
3.109375
3
[]
no_license
package com.example.brainjuice.entity; import java.util.ArrayList; public class UserMgr { ArrayList<User> userList; public UserMgr(){ userList = new ArrayList<User>(); userList.add(new User("JonathanTan", "1234", "child", "jonathantan@gmail.com", "minion")); userList.add(new User("MelissaTan", "1234", "adult", "melissatan@gmail.com", "melissa")); userList.add(new User("JackyWong", "1234", "adult", "jackywong@gmail.com", "minion")); userList.add(new User("JudyChoo", "1234", "child", "judychoo@gmail.com", "melissa")); } //register for new user. public void add(String username, String password, String userType, String email, String profile){ userList.add(new User(username, password, userType, email, profile)); } //Test the username and password put in by user. if can login, return userType; if cannot login, return null. public String login(String testedUsername, String testedPassword){ for(User user: userList){ if(user.getUsername().equals(testedUsername) && user.getPassword().equals(testedPassword)){ return user.getUserType(); } } return null; } //retrieve the User object for a specific username public User retrieveUser(String username){ for(User user: userList){ if(user.getUsername().equals(username)){ return user; } } return null; } }
true
c7229d7156c2b9b14922c7d669f4c35e16e8d623
Java
Ohyaelim/study_api2
/src/main/java/sm/chromeScreentime/task/dto/UserDTO.java
UTF-8
902
2.109375
2
[]
no_license
package sm.chromeScreentime.task.dto; import lombok.Getter; import lombok.Setter; import sm.chromeScreentime.task.entity.User; import java.util.ArrayList; @Getter @Setter public class UserDTO { private String userId; private String username; private ArrayList<String> ent; private ArrayList<String> prod; private ArrayList<String> sns; private ArrayList<String> shop; private ArrayList<String> edu; private ArrayList<String> business; private ArrayList<String> etc; public UserDTO(User entity){ this.userId = entity.getUserId(); this.username = entity.getUsername(); this.ent = entity.getEnt(); this.prod = entity.getProd(); this.sns = entity.getSns(); this.shop = entity.getShop(); this.edu = entity.getEdu(); this.business = entity.getBusiness(); this.etc = entity.getEtc(); } }
true
b07bc55f837a6f6545028a4a176bc314b9a370a1
Java
AlexSimoesQA/desafio-getnet-api
/src/main/java/br/com/getnet/api/core/Constants.java
UTF-8
263
1.5625
2
[]
no_license
package br.com.getnet.api.core; import io.restassured.http.ContentType; public interface Constants { String APP_BASE_URL = "https://reqres.in/api/"; Integer APP_PORT = 80; ContentType APP_CONTENT_TYPE = ContentType.JSON; Long MAX_TIMEOUT = 10000L; }
true
42d88839a4698671e033f51dfad9abbbe8660deb
Java
S3b97/AndroidVintedExamen
/app/src/main/java/com/example/vintedexamenseca/retrofit/VintedApiInterface.java
UTF-8
410
1.828125
2
[]
no_license
package com.example.vintedexamenseca.retrofit; import com.example.vintedexamenseca.beans.Prenda; import com.example.vintedexamenseca.beans.Usuario; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Field; import retrofit2.http.GET; import retrofit2.http.POST; public interface VintedApiInterface { @GET("prendas") Call<List<Prenda>> getPrendas(); }
true
9e56c93f37dd5e98b4dc92a6793a16cc488ac597
Java
krishanwegile/MvvmwithRecycler
/app/src/main/java/com/mvvmwithrecylerview/RecyclerWithMvvmActivity.java
UTF-8
2,091
2.171875
2
[]
no_license
package com.mvvmwithrecylerview; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.mvvmwithrecylerview.adapter.MvvmRecyclerAdapterWithBinding; import com.mvvmwithrecylerview.model.UserDataModel; import com.mvvmwithrecylerview.viewModel.UserViewDataModel; import java.util.ArrayList; public class RecyclerWithMvvmActivity extends AppCompatActivity { private RecyclerView recyclerView; private MvvmRecyclerAdapterWithBinding mvvmRecyclerAdapterWithBinding; ArrayList<UserViewDataModel> userViewDataModels = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mvvm_recyler_activity); setData(); } void setData() { UserDataModel userData = new UserDataModel(); userData.setDesc("itiskrishan@gmail.com"); userData.setName("Krishan Mohan Verma"); UserViewDataModel userDataModel = new UserViewDataModel(userData); userViewDataModels.add(userDataModel); UserDataModel userData1 = new UserDataModel(); userData1.setDesc("itisksn@gmail.com"); userData1.setName("ksn verma"); UserViewDataModel userDataModel1 = new UserViewDataModel(userData1); userViewDataModels.add(userDataModel1); UserDataModel userData2 = new UserDataModel(); userData2.setDesc("Ahaan"); userData2.setName("Paras verma"); UserViewDataModel userDataModel2 = new UserViewDataModel(userData2); userViewDataModels.add(userDataModel2); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); mvvmRecyclerAdapterWithBinding = new MvvmRecyclerAdapterWithBinding(userViewDataModels); recyclerView.setAdapter(mvvmRecyclerAdapterWithBinding); mvvmRecyclerAdapterWithBinding.notifyDataSetChanged(); } }
true
637a2e6f6fc2bc0c819ee282a12693cf967264ff
Java
sunce2019/myGitHub
/pay/src/main/java/com/pay/controller/AlipayController.java
UTF-8
8,744
1.734375
2
[]
no_license
package com.pay.controller; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.pay.bank.CCB; import com.pay.bank.ICBC; import com.pay.dao.BaseDao; import com.pay.dao.MemberDao; import com.pay.enums.PayState; import com.pay.enums.PayTran; import com.pay.handleBusiness.Base; import com.pay.handleBusiness.SuBao; import com.pay.model.ArrivalAccount; import com.pay.model.Bank; import com.pay.model.BankBase; import com.pay.model.Business; import com.pay.model.CloudFlasHover; import com.pay.model.Customer; import com.pay.model.PayOrder; import com.pay.model.Users; import com.pay.model.WechatCode; import com.pay.payAssist.ToolKit; import com.pay.service.BusinessService; import com.pay.service.PayOrderService; import com.pay.util.Encryption; import com.pay.util.ReturnBan; import com.pay.util.StringUtils; import com.pay.vo.BankVo; import net.sf.json.JSONObject; /** * @author star * @version 创建时间:2019年4月17日下午3:48:37 */ @Controller @RequestMapping("/alipay") public class AlipayController extends BaseController { private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("busi1"); @Value("#{configProperties['zb.addMoney']}") private String addMoney; @Value("#{configProperties['zb.checkAccount']}") private String checkAccount; @Autowired private PayOrderService payOrderService; @Autowired private SuBao suBao; @Autowired private BaseDao<ArrivalAccount> arrivalAccountDao; @Autowired private BaseDao<Bank> bankDao; @Autowired private MemberDao memberDao; @Autowired private BaseDao<Customer> customerDao; @Autowired private BaseDao<PayOrder> payOrderDao; @Autowired private ICBC icbc; @Autowired private CCB ccb; @Autowired private BusinessService businessService; @RequestMapping("/req") public String req(Model model, String u) { if (StringUtils.isBlank(u)) return ""; model.addAttribute("username", u); return "alipay"; } /** * 速宝支付 创建订单 * * @param model * @param u * @param payUserName * @param price * @return */ @RequestMapping("/deposit") public String deposit(Model model, String u, String n) { if (StringUtils.isBlank(u) || StringUtils.isBlank(n)) return ""; try { model.addAttribute("u", u); model.addAttribute("n", n); } catch (Exception e) { e.printStackTrace(); } return "alipay"; } /** * 速宝支付 创建订单 * * @param model * @param u * @param payUserName * @param price * @return */ @RequestMapping("/WXDeposit") public String WXDeposit(Model model, String u, String n) { if (StringUtils.isBlank(u) || StringUtils.isBlank(n)) return ""; try { model.addAttribute("u", u); model.addAttribute("n", n); } catch (Exception e) { e.printStackTrace(); } return "weChat"; } /** * 支付宝转银行卡 消息通知回调 * * @param model * @param u * @param payUserName * @param price * @return */ @RequestMapping("/depositCallBack") @ResponseBody public String depositCallBack(Model model, String time, String content, String machine_num, String name, String cardnum, Double amount, HttpServletRequest request, String typeName, String bankType) { try { logger.info("支付宝转银行卡 消息通知回调:time=" + time + ",content=" + content + ",machine_num=" + machine_num + ",name=" + name + ",cardnum=" + cardnum + ",amount=" + amount); BankVo bankVo = new BankVo(cardnum, StringUtils.SDF.parse(time), name, machine_num, amount); Calendar beforeTime = Calendar.getInstance(); beforeTime.setTime(bankVo.getTime()); beforeTime.add(Calendar.MINUTE, -30);// 10分钟之前的时间 Date beforeD = beforeTime.getTime(); DetachedCriteria dc = getBanck(bankVo, beforeD, typeName, name, bankType); List<PayOrder> list = payOrderDao.findList(dc); if (list.size() == 1) { logger.info("匹配成功:" + bankVo.toString()); Business business = businessService.getBusiness( new Business(list.get(0).getUid(), list.get(0).getOrderType(), list.get(0).getCustomer_id())); String ip = getClientIP(request); if (business == null || !business.getCallbackip().contains(ip)) { logger.info("商户不存在或者,ip不在白名单内"); logger.info("list.get(0).getUid()=" + list.get(0).getUid()); logger.info("数据库IP=" + business.getCallbackip() + "====requestIP=" + ip); return "11"; } ReturnBan eb = payOrderService.upperScore(list.get(0).getId(), new Users("自动上分"), false, 0d); if (eb.isState()) { arrivalAccountDao.save(new ArrivalAccount(list.get(0).getId(), bankVo.getCardNo(), new Date(), 1, "自动匹配成功单号:" + list.get(0).getOrderNumber(), bankVo.getPrice())); return "00"; } else { return "22"; } } else if (list.size() > 1) { logger.info("匹配失败大于等于2条数据:" + bankVo.toString()); for (PayOrder p : list) payOrderService.updatePayOrder(p, "金额相同"); arrivalAccountDao.save( new ArrivalAccount(0, bankVo.getCardNo(), new Date(), 2, "10分钟内多条相同存款订单", bankVo.getPrice())); return "33"; } else { logger.info("匹配失败:" + bankVo.toString()); arrivalAccountDao .save(new ArrivalAccount(0, bankVo.getCardNo(), new Date(), 2, "匹配失败", bankVo.getPrice())); return "44"; } } catch (Exception e) { e.printStackTrace(); } return "55"; } private DetachedCriteria getBanck(BankVo bankVo, Date beforeD, String typeName, String name, String bankType) { Class classs = null; if (bankType.equals(PayTran.ZFB_BANK.getCode()) || bankType.equals(PayTran.WX_BANK.getCode())) { classs = Bank.class; } else if (bankType.equals(PayTran.YSF.getCode())) { classs = CloudFlasHover.class; } else if (bankType.equals(PayTran.WX_MD.getCode())) { classs = WechatCode.class; } DetachedCriteria bankdc = DetachedCriteria.forClass(classs); bankdc.add(Restrictions.like("tail", "%" + bankVo.getCardNo() + "%")); List<BankBase> banklist = bankDao.findBankBaseList(bankdc); String cardNo = ""; if (banklist.size() == 0) { bankdc = DetachedCriteria.forClass(classs); bankdc.add(Restrictions.like("cardNo", "%" + bankVo.getCardNo() + "%")); banklist = bankDao.findBankBaseList(bankdc); if (banklist.size() > 0) { cardNo = banklist.get(0).getCardNo(); } else { logger.info("没有 匹配到银行卡:" + bankVo.getCardNo()); } } else { cardNo = banklist.get(0).getCardNo(); } DetachedCriteria dc = DetachedCriteria.forClass(PayOrder.class); dc.add(Restrictions.eq("realprice", Double.parseDouble(StringUtils.df.format(bankVo.getPrice())))); dc.add(Restrictions.eq("cardNo", cardNo)); dc.add(Restrictions.ge("addTime", beforeD)); // 大于等于 dc.add(Restrictions.le("addTime", bankVo.getTime())); // 小于等于 dc.add(Restrictions.eq("flag", PayState.INIT.getCode())); if (!StringUtils.isBlank(bankType)) dc.add(Restrictions.eq("orderType", PayTran.getText(bankType))); if (!StringUtils.isBlank(typeName)) dc.add(Restrictions.eq("customer_name", typeName)); if (!StringUtils.isBlank(name)) dc.add(Restrictions.eq("depositorName", name)); dc.addOrder(Order.asc("addTime")); return dc; } private com.pay.bank.BankBase getBankType(String content) { if (content.contains("【工商银行】")) { return icbc; } else if (content.contains("[建设银行]")) { return ccb; } return null; } private boolean queryLoginName(String u) throws Exception { Map<String, String> map = new TreeMap<String, String>(); map.put("app_id", "1543495534070"); map.put("account", u); String p = Base.getMapParam(map); p += "&sign=" + Encryption.sign(p + "&key=2609e6e3fa144cea9da2347375bfd952", "GB2312").toLowerCase(); String resultJsonStr = ToolKit.request(checkAccount, p); logger.info("查询中博账号是否存在返回:" + resultJsonStr); if (StringUtils.isBlank(resultJsonStr)) return false; JSONObject resultJsonObj = JSONObject.fromObject(resultJsonStr); if (resultJsonObj.getString("status").equals("true")) return true; return false; } }
true
1da0c0cf3fd3763acbcc8d67e5d540fb9176cba9
Java
Naveen-Banagani/Ryanair-Test
/src/test/java/pages/FlightsBookingPaymentPage.java
UTF-8
6,638
1.890625
2
[]
no_license
package pages; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import junit.framework.Assert; import utils.ExplicitWait; import utils.LogUtils; import utils.ScrollUtils; import java.util.List; import static utils.GlobalConstants.EXPLICIT_SLEEP_TIMEOUT_MILLIS; /*** * This class describes Flights Booking Payment Page PageFactory is used for * Page Object It adds lazy evaluation which means that Page Element is * initialized only when it's called by method instead of instant initialization * when object of page is created */ public class FlightsBookingPaymentPage extends BasePage { @FindBy(xpath = "//input[@type='tel']") private WebElement mobileNumber; @FindBy(xpath = "(//input[@name='undefined'])[2]") private WebElement cardNumber; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[1]/div[2]/card-details[1]/form[1]/expiry-date[1]/div[1]/span[2]/div[1]/ry-dropdown[1]/div[1]/button[1]") private WebElement expiryMonthDropdown; @FindBy(xpath = "//div[contains(text(),'June')]") private WebElement expiryMonthDropDownList; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[1]/div[2]/card-details[1]/form[1]/expiry-date[1]/div[1]/span[2]/div[2]/ry-dropdown[1]/div[1]/button[1]") private WebElement expiryYearDropdown; @FindBy(xpath = "//div[contains(text(),'2024')]") private WebElement expiryYearDropDownList; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[1]/div[2]/card-details[1]/form[1]/verification-code[1]/div[1]/span[1]/ry-input-d[1]/div[1]/input[1]") private WebElement securityCode; @FindBy(xpath = "(//input[@name='undefined'])[4]") private WebElement cardHolderName; @FindBy(xpath = "(//input[@name='undefined'])[5]") private WebElement addressLine1; @FindBy(xpath = "(//input[@name='undefined'])[7]") private WebElement city; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[2]/billing-address[1]/address-form[1]/form[1]/ry-autocomplete[1]/div[1]/div[1]/div[1]/input[1]") private WebElement countryDropDown; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[2]/billing-address[1]/address-form[1]/form[1]/ry-autocomplete[1]/div[1]/div[1]/div[1]/input[1]") private WebElement countrylist; @FindBy(xpath = "//body/app-root[1]/ng-component[1]/ry-spinner[1]/div[1]/payment-form[1]/form[1]/div[5]/payment-methods[1]/div[1]/div[1]/ry-tabs[1]/div[2]/div[1]/add-method-modal[1]/form[1]/div[1]/div[1]/div[2]/billing-address[1]/address-form[1]/form[1]/ry-input-d[4]/div[1]/input[1]") private WebElement zipCode; @FindBy(xpath = "//terms-and-conditions/div/div/ry-checkbox/label/div/div") private WebElement termsCheckBox; @FindBy(xpath = "//button[contains(text(),'Pay now')]") private WebElement payNowButton; @FindBy(xpath = "//div[3]/div/ry-checkbox/label/div/div") private WebElement insuranceCheckBox; @FindBy(xpath = "//span[contains(text(),'Select a currency')]") private WebElement currencyDropDown; @FindBy(xpath = "(//ry-dropdown-item[@class='ng-star-inserted'])[1]") private WebElement selectCurrency; @FindBy(xpath = "//div[contains(text(),'Transaction could not be processed.')]") private WebElement paymentErrorMessage; public void fillMobileNumber(String phoneNumber) { LogUtils.logInfo(String.format("Fill 'Phone number' with '%s'", phoneNumber)); this.mobileNumber.sendKeys(phoneNumber); } public void fillCardNumber(String cardNumber) { LogUtils.logInfo(String.format("Fill 'Card number' with '%s'", cardNumber)); this.cardNumber.sendKeys(cardNumber); } public void chooseExpiryMonth() { LogUtils.logInfo("Open 'Expiry Month' dropdown"); expiryMonthDropdown.click(); expiryMonthDropDownList.click(); } public void chooseExpiryYear() { LogUtils.logInfo("Open 'Expiry Year' dropdown"); expiryYearDropdown.click(); expiryYearDropDownList.click(); } public void fillSecurityCode(String code) { LogUtils.logInfo(String.format("Fill 'Security code' with '%s'", code)); securityCode.sendKeys(code); } public void fillCardHolderName(String holderName) { LogUtils.logInfo(String.format("Fill 'Card Holder Name' with '%s'", holderName)); cardHolderName.sendKeys(holderName); } public void fillAddress(String address) { LogUtils.logInfo(String.format("Fill 'Address Line 1' with '%s'", address)); addressLine1.sendKeys(address); } public void fillCity(String city) { LogUtils.logInfo(String.format("Fill 'City' with '%s'", city)); this.city.sendKeys(city); } public void acceptTerms() { LogUtils.logInfo("Accept General terms"); termsCheckBox.click(); } public void clickCurrencyDropDown() { LogUtils.logInfo("Select Currency"); currencyDropDown.click(); selectCurrency.click(); } public void clickPayNowButton() { LogUtils.logInfo("Click 'Pay Now' button"); payNowButton.click(); } public void countryDropDown() { LogUtils.logInfo("click on country dropdown"); countrylist.sendKeys("Ireland"); countrylist.sendKeys(Keys.ENTER); } public void zipCode() { LogUtils.logInfo("Enter Zip Code"); zipCode.clear(); zipCode.sendKeys("H91ET22"); } public void InsuranceCheckBox() throws InterruptedException { LogUtils.logInfo("Insurance CheckBox"); Thread.sleep(3000); insuranceCheckBox.click(); } public void payNowButton() { LogUtils.logInfo("Click on PayNow Button"); payNowButton.click(); } public void waitUntilPaymentErrorIsDisplayed() { ExplicitWait.visibilityOfElement(paymentErrorMessage); String message = paymentErrorMessage.getText(); System.out.println(message); Assert.assertEquals( "Transaction could not be processed. Your payment was not authorised therefore we could not complete your booking. Please ensure that the information was correct and try again or use a new payment card.", message); } }
true
e8c74bfd3b3da879e1cd84348ee4c40c2e0ae42e
Java
bunnykillher/eureka_webservicess
/src/test/Testtest.java
UTF-8
1,120
2.28125
2
[]
no_license
package test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import dao.EmployeeDAO; import dao.FoodDAO; import dao.FoodOrderDAO; import dao.StallDAO; import model.Employee; import model.Food; import model.FoodOrder; import model.Modifier; import model.ModifierSection; import model.Stall; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Testtest { public static void main(String[] args) { // TODO Auto-generated method stub // EmployeeDAO employeeDAO = new EmployeeDAO(); // Employee employee = // employeeDAO.getEmployeeByEmail("chris.cheng.2013@sis.smu.edu.sg"); // FoodOrderDAO foodOrderDAO = new FoodOrderDAO(); // List<FoodOrder> foodOrderList = // foodOrderDAO.getFoodOrderSet(employee); // for(FoodOrder foodOrder : foodOrderList){ // System.out.println(foodOrder.getCreateDate()); // } FoodDAO foodDAO = new FoodDAO(); Food food = foodDAO.getFood(157); Set<ModifierSection> modifierSection = food.getModifierSectionList(); System.out.println(modifierSection.size()); } }
true
9161d9f6469c3721985f39b1119f6b144f9f96ce
Java
kranthi117/deployment
/src/main/java/deployment/mvc/DiagramController.java
UTF-8
354
1.898438
2
[ "MIT" ]
permissive
package deployment.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class DiagramController { @RequestMapping("/diagram") public String diagram(Model model) { model.addAttribute("servers", "ser"); return "diagram"; } }
true
a1fd73f4ad7ffc86eabc0a8a62e815c46426cc4a
Java
jtrentes/jtr_test
/src/main/java/big/web/controllers/MyClass57DetailController.java
UTF-8
3,158
2.125
2
[]
no_license
package big.web.controllers; import org.springframework.web.bind.annotation.RequestMethod; import big.services.MyClass57Service; import big.web.controllers.validator.MyClass57Validator; import big.domain.MyClass57; import org.springframework.web.bind.support.SessionStatus; import big.domain.MyClass37; import java.util.List; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.validation.BindingResult; import big.services.MyClass37Service; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.annotation.ModelAttribute; @Controller @SessionAttributes(types = MyClass57.class) public class MyClass57DetailController { @Autowired private MyClass37Service myClass37Service; @Autowired private MyClass57Service myClass57Service; @RequestMapping(value = "/myclass57/edit/cancel", method = RequestMethod.GET) public String cancel (SessionStatus session) { session.setComplete(); return "redirect:/myclass57/edit"; } @RequestMapping(value = "/myclass57/detail/{myClass57Id}") public String details (@PathVariable(value = "myClass57Id") Long myClass57Id, Model model) { MyClass57 myClass57 = this.myClass57Service.findById(myClass57Id); model.addAttribute(myClass57); return "myclass57/detail"; } @RequestMapping(value = "/myclass57/edit/{myClass57Id}", method = RequestMethod.GET) public String edit (@PathVariable(value = "myClass57Id") Long myClass57Id, Model model) { MyClass57 myClass57 = this.myClass57Service.findById(myClass57Id); model.addAttribute(myClass57); return "myclass57/edit"; } @ModelAttribute(value = "myclass37s") public List<MyClass37> getMyClass37s () { return this.myClass37Service.findAll(); } @InitBinder public void initBinder (WebDataBinder binder) { binder.setDisallowedFields("id"); binder.setValidator(new MyClass57Validator()); } @RequestMapping(value = "/myclass57/edit", method = RequestMethod.GET) public MyClass57 newMyClass57 (Model model) { if(model != null && model.asMap().get("myclass57") == null) { return new MyClass57(); } return (MyClass57) model.asMap().get("myclass57"); } @RequestMapping(value = {"/myclass57/edit", "/myclass57/edit/{myclass57Id}"}, method = {RequestMethod.POST, RequestMethod.PUT}) public String save (@Validated @ModelAttribute MyClass57 MyClass57, BindingResult result, SessionStatus session) { if(result.hasErrors()) { return "myclass57/edit"; } if (MyClass57.getMyclass37()!=null && MyClass57.getMyclass37().getId()!=null && MyClass57.getMyclass37().getId() == 0) MyClass57.setMyclass37(null); this.myClass57Service.save(MyClass57); session.setComplete(); return "redirect:/myclass57/list"; } }
true
42b3be67a4a7ec2661bfc6e78a0aa746978ec471
Java
yes-jyomi/JAVA2019
/1학기/190320/src/d0402.java
UTF-8
756
2.6875
3
[]
no_license
public class d0402 { public static void main(String[] args) { String threec[] = {"강지민", "강혜정", "김가영", "김나영", "김선옥", "김수진", "류정민", "박교령", "서남경", "오승연", "원예린", "원채린", "이서현", "이채린", "이현수", "임현진", "장유경", "장원이", "한다연"}; String fourc[] = {"강은서", "곽가연", "김민지", "김봄이", "김소현", "김채민", "남정윤", "박서연", "서혜림", "신채린", "양수빈", "엄하늘", "원채연", "윤수빈", "", "임태희", "전은정", "정유경", "함지현"}; for (String name : threec) { System.out.println(name); } System.out.println("==="); for (String name : fourc) { System.out.println(name); } } }
true
34cb9f633f1ab7819e4ff7c3c88f85d38325f223
Java
HammerCloth/EmpCRUD
/src/com/syx/ssm/controller/EmpControl.java
UTF-8
3,120
2.21875
2
[]
no_license
package com.syx.ssm.controller; import com.syx.ssm.Service.EmpService; import com.syx.ssm.bean.Dept; import com.syx.ssm.bean.Emp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author:syx * @date:2021/7/1 17:03 * @version:v1.0 */ @Controller public class EmpControl { @Autowired private EmpService service; @RequestMapping(value = "/emps", method = RequestMethod.GET) public String getAllEmps(Map<String, Object> map) { List<Emp> allEmp = service.getAllEmp(); map.put("empList", allEmp); return "list"; } @RequestMapping(value = "emp/{eid}", method = RequestMethod.GET) public String toUpdate(@PathVariable("eid") String eid, Map<String, Object> map) { // 所有的部门信息 List<Dept> allDept = service.getAllDept(); // 获取存储性别的集合 Map<String, String> sex = new HashMap<>(); sex.put("0", "女"); sex.put("1", "男"); // 要修改的员工信息 Emp emp = service.getEmpByEid(eid); map.put("emp", emp); map.put("allDept", allDept); map.put("sex", sex); return "update"; } @RequestMapping(value = "delemp/{eid}", method = RequestMethod.GET) public String toDelete(@PathVariable("eid") String eid, Map<String, Object> map){ // 获取存储性别的集合 Map<String, String> sex = new HashMap<>(); sex.put("0", "女"); sex.put("1", "男"); // 获取员工信息 Emp emp = service.getEmpByEid(eid); map.put("emp", emp); map.put("sex", sex); return "delete"; } @RequestMapping(value = "/emp", method = RequestMethod.PUT) public String updateEmp(Emp emp) { service.updateEmp(emp); return "redirect:/emps"; } @RequestMapping(value = "/emps",method = RequestMethod.DELETE) public String deleteMore(String eid){ service.deleteEmp(eid); return "redirect:/emps"; } @RequestMapping(value = "/emp",method = RequestMethod.DELETE) public String deleteEmp(String eid){ service.deleteEmp(eid); return "redirect:/emps"; } @RequestMapping(value = "addemp" ,method = RequestMethod.GET) public String toAdd(Map<String, Object> map){ // 所有的部门信息 List<Dept> allDept = service.getAllDept(); // 获取存储性别的集合 Map<String, String> sex = new HashMap<>(); sex.put("0", "女"); sex.put("1", "男"); // 获取员工信息 map.put("allDept", allDept); map.put("sex", sex); return "add"; } @RequestMapping(value = "/emp",method = RequestMethod.POST) public String add(Emp emp){ service.addEmp(emp); return "redirect:/emps"; } }
true
59f09bcb252cc7e4f3c2545e9d3366888c2d72ee
Java
jersonk/AmassWareHouse1
/app/src/main/java/com/amassfreight/domain/ImageData.java
UTF-8
1,136
2.234375
2
[]
no_license
package com.amassfreight.domain; import android.graphics.Bitmap; public class ImageData { private Bitmap data; private String path; private String url; private String fileUploadId; private String imageDesc; public String getImageDesc() { return imageDesc; } public void setImageDesc(String imageDesc) { this.imageDesc = imageDesc; } public String getFileUploadId() { return fileUploadId; } public void setFileUploadId(String fileUploadId) { this.fileUploadId = fileUploadId; } private boolean downloading; public boolean isDownloading() { return downloading; } public void setDownloading(boolean downloading) { this.downloading = downloading; } private String imageId; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Bitmap getData() { return data; } public void setData(Bitmap data) { this.data = data; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
true
118ac6ba70e82b898feea2db81dc7ca06a5d1ca3
Java
cnlybig/jinxi-server
/src/main/java/com/jinxi/star/jxserver/dao/LoginDao.java
UTF-8
1,070
1.921875
2
[]
no_license
package com.jinxi.star.jxserver.dao; import com.github.pagehelper.Page; import com.jinxi.star.jxserver.entity.LoginInfo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; /** * 公共接口 数据调用 * * @author: Shiz * @date: 2020/6/30 13:14 */ @Mapper @Component public interface LoginDao { int isAdminUser(@Param("userName") String userName,@Param("password")String password); /** * 根据openId获取用户信息 * * @param openId * @return */ LoginInfo getUserByOpenId(@Param("openId") String openId); /** * 根据userId获取用户信息 * * @param userId * @return */ LoginInfo getUserByUserId(@Param("userId") String userId); /** * 根据openId更新登陆时间 * @param openId */ void updateLoginTime(@Param("openId") String openId); void register(@Param("loginInfo") LoginInfo loginInfo); Page<LoginInfo> listUsers(@Param("userName")String userName); }
true
52bab1260f83b537630a96ae61fce99dfaf100e7
Java
giovannidelfino/java-practice
/src/day08_casting_conditionals/IfElseWithVariables.java
UTF-8
479
4.125
4
[]
no_license
package day08_casting_conditionals; public class IfElseWithVariables { public static void main(String[] args) { int temperature = 65; if(temperature >= 65) { System.out.println("It is a nice day! Lets code java"); }else { System.out.println("Stay home and code java"); } int teamAScore = 6; int teamBScore = 5; if(teamAScore > teamBScore) { System.out.println("Team A won. Go Team A!"); }else { System.out.println("Go Teams!"); } } }
true
5af0d6162e3795e61b602cb1eb715bc4022e0d97
Java
Sahibdeep26/COMP-380_Assignment-4
/Rule.java
UTF-8
389
3.421875
3
[]
no_license
/* DO NOT EDIT THIS CLASS * * A simple class representing a Rule. * A rule is composed of an Atom as its head, * and a conjunction of Atoms as its body. * e.g. h <- b1 & b2 */ public class Rule { Atom head; Atom[] body; public Rule(Atom h, Atom[] b) { head = h; body = b; } public Atom getHead() { return head; } public Atom[] getBody() { return body; } }
true
c91724ce2f570d906402a3da9ca57b435159d6d2
Java
RemyCo/Robot_ProSE
/app/src/main/java/fr/eseo/i2/prose/ea1/whereisrob/communication/DispatcherAndroid.java
UTF-8
3,789
2.390625
2
[]
no_license
/** * @file DispatcherAndroid.java * * @brief La classe DispatcherAndroid permet de donner les bon ordre à GUIActivity en fonction * des messages reçus de RobSoft. * * @author Timothée GIRARD * * @copyright 2019 ProseA1 * 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 fr.eseo.i2.prose.ea1.whereisrob.communication; import android.app.Activity; import android.graphics.Point; import android.util.Log; import com.whereisrob.whereisrob.R; import java.util.StringTokenizer; import fr.eseo.i2.prose.ea1.whereisrob.gui.GUIActivity; import fr.eseo.i2.prose.ea1.whereisrob.model.ModelSingleton; /** * La classe DispatcherAndroid permet de donner les bon ordre à GUIActivity en fonction * * des messages reçus de RobSoft. */ public class DispatcherAndroid { private static final String TAG = "Debug"; private GUIActivity guiActivity; /** * Constructeur de la classse * * @param activity Paramètre utilisé pour appeler des méthodes de GUIActivity */ public DispatcherAndroid(Activity activity) { this.guiActivity = (GUIActivity) activity; } /** * Permet d’appeler les bonnes méthodes de GUIActivity * en fonctions des données reçues de RobSoft * * @param message Le message à dispatcher */ public void dispatch(String message) { try { if(message.contains(Protocol.cpu)) { guiActivity.setCPU(Integer.parseInt(message.substring(4))); } else if(message.contains(Protocol.ram)) { guiActivity.setRAM(Integer.parseInt(message.substring(4))); } else if(message.contains(Protocol.pwmLeft) && message.contains(Protocol.pwmRight)) { StringTokenizer stringTokenizer = new StringTokenizer(message , ";"); guiActivity.setWheelsPower(Integer.parseInt(stringTokenizer.nextToken().substring(3)), Integer.parseInt(stringTokenizer.nextToken().substring(3))); } else if(message.contains(Protocol.positionX) && message.contains(Protocol.positionY) && guiActivity.myBooleanVisible == false ) { StringTokenizer stringTokenizer = new StringTokenizer(message , ";"); Point position = new Point(Integer.parseInt(stringTokenizer.nextToken().substring(3)), Integer.parseInt(stringTokenizer.nextToken().substring(3))); guiActivity.setCurrentPosition(position); ModelSingleton.getInstance().getCartographer().setCurrentPosition(position); } else if(message.contains(Protocol.endTest)) { guiActivity.showConfirmDialogEndTest(guiActivity.getString(R.string.endTest)); guiActivity.setStartButtonVisible(true); } } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "Impossible to dispatch !\n" + e.getMessage()); } } } // End of class
true
1b6b3d64d19dceb04e6f73c16ab56e16a8bb80ea
Java
PhanThiQuynhLinh/DeliveryFood
/src/action/TrangChuAction.java
UTF-8
2,162
2.28125
2
[]
no_license
package action; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import form.TrangChuForm; import model.bean.KhuVuc; import model.bo.KhachHangBo; import model.bo.KhuVucBo; import model.bo.MonAnBo; import model.bo.NhaHangBo; public class TrangChuAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { TrangChuForm trangChuForm = (TrangChuForm) form; HttpSession session = request.getSession(); String email = (String) session.getAttribute("emailKhachHang"); // if(email == null) { // return mapping.findForward("dangNhapLai"); // } KhachHangBo khachHangBo = new KhachHangBo(); trangChuForm.setEmail(email); trangChuForm.setDiemTichLuy(khachHangBo.diemTichLuy(email)); khachHangBo.capNhatDiemTichLuy(email, khachHangBo.diemTichLuy(email)); trangChuForm.setTenKhachHang(khachHangBo.tenKhachHang(email)); trangChuForm.setKhachHang(khachHangBo.thongTinKhachHang(email)); System.out.println("aaaaa"); if("Hiển Thị".equals(trangChuForm.getSubmit())) { if(trangChuForm.getMaKhuVuc() == null || trangChuForm.getMaKhuVuc().length() == 0) { return mapping.findForward("chuaChonKhuVuc"); } return mapping.findForward("hienThiNhaHangTrongKhuVuc"); }else { System.out.println("bbbbb"); KhuVucBo khuVucBo = new KhuVucBo(); ArrayList<KhuVuc> danhSachKhuVuc = khuVucBo.hienThiDanhSachKhuVuc(); trangChuForm.setDanhSachKhuVuc(danhSachKhuVuc); NhaHangBo nhaHangBo = new NhaHangBo(); trangChuForm.setSoLuongNhaHang(nhaHangBo.tinhSoLuongNhaHang()); MonAnBo monAnBo = new MonAnBo(); trangChuForm.setSoLuongMonAn(monAnBo.tinhSoLuongMonAn()); trangChuForm.setSoLuongKhachHang(khachHangBo.tinhSoLuongKhachHang()); return mapping.findForward("hienThiTrangChu"); } } }
true
7b2e690149e3e5aaca096a4cf51662c2f2579a80
Java
Aqueelmiq/Hangman
/oldfiles/src/AMDWApplicationClass.java
UTF-8
283
2.03125
2
[]
no_license
/* * CS - 201 Final Project * Hangman Game * Created by Aqueel Miqdad, Dominik Wegiel * Executes the Menu and starts the application */ public class AMDWApplicationClass { public static void main(String[] args) { //Execute Menu AMDWMenu menu = new AMDWMenu(); menu.mainMenu(); } }
true
b24e405ce87c432f13426fa931e53fc0e69dfcac
Java
SilverYar/2019-highload-dht
/src/main/java/ru/mail/polis/service/yaroslav/AsyncHttpService.java
UTF-8
9,009
2.0625
2
[ "Apache-2.0" ]
permissive
package ru.mail.polis.service.yaroslav; import com.google.common.util.concurrent.ThreadFactoryBuilder; import one.nio.http.HttpServer; import one.nio.http.HttpServerConfig; import one.nio.http.HttpSession; import one.nio.http.Path; import one.nio.http.Response; import one.nio.http.Request; import one.nio.net.Socket; import one.nio.server.AcceptorConfig; import org.jetbrains.annotations.NotNull; import ru.mail.polis.Record; import ru.mail.polis.dao.DAO; import ru.mail.polis.dao.DAORocksDB; import ru.mail.polis.service.Service; import java.net.http.HttpClient; import java.net.http.HttpClient.Version; import java.net.http.HttpClient.Redirect; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.HashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; public class AsyncHttpService extends HttpServer implements Service { @NotNull private final DAORocksDB dao; @NotNull private final Executor workerThreads; private final Node nodes; private final Coordinators clusterCoordinator; private static final Logger logger = Logger.getLogger(AsyncHttpService.class.getName()); /** * Create the HTTP Cluster server. * * @param config HTTP server configurations * @param dao to initialize the DAO instance within the server * @param nodes to represent cluster nodes * @param clusterClients initialized cluster clients */ public AsyncHttpService( final HttpServerConfig config, @NotNull final DAO dao, @NotNull final Node nodes, @NotNull final Map<String, HttpClient> clusterClients) throws IOException { super(config); this.dao = (DAORocksDB) dao; this.workerThreads = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder().setNameFormat("worker").build()); this.nodes = nodes; this.clusterCoordinator = new Coordinators(nodes, clusterClients, dao); } /** * Create the HTTP server. * * @param port to accept HTTP connections * @param dao to initialize the DAO instance within the server * @return config */ public static Service create( final int port, @NotNull final DAO dao, @NotNull final Node nodes) throws IOException { final var acceptor = new AcceptorConfig(); final var config = new HttpServerConfig(); final String localhost = "http://localhost:"; acceptor.port = port; config.acceptors = new AcceptorConfig[]{acceptor}; config.maxWorkers = Runtime.getRuntime().availableProcessors(); config.queueTime = 10; final Map<String, HttpClient> clusterClients = new HashMap<>(); for (final Integer it : nodes.getPorts()) { if (!nodes.getId().equals(localhost + it) && !clusterClients.containsKey(localhost + it)) { final HttpClient client = HttpClient.newBuilder() .version(Version.HTTP_2) .followRedirects(Redirect.NEVER) .build(); clusterClients.put(localhost + it, client); } } return new AsyncHttpService(config, dao, nodes, clusterClients); } @Override public HttpSession createSession(final Socket socket) { return new StreamStorageSession(socket, this); } /** * Serve requests for status. * * @return status */ @Path("/v0/status") public Response status() { return Response.ok("OK"); } private void entity(@NotNull final Request request, final HttpSession session) throws IOException { if (request.getURI().equals("/v0/entity")) { session.sendError(Response.BAD_REQUEST, "No specified parameters"); return; } final String id = request.getParameter("id="); if (id.isEmpty()) { session.sendError(Response.BAD_REQUEST, "Id is not specified"); return; } boolean proxied = false; if (request.getHeader("PROXY_HEADER") != null) { proxied = true; } final boolean proxiedF = proxied; if (proxied || nodes.getNodes().size() > 1) { clusterCoordinator.coordinateRequest(proxiedF, request, session); } else { final var key = ByteBuffer.wrap(id.getBytes(StandardCharsets.UTF_8)); executeAsyncRequest(request, key, session); } } private void executeAsyncRequest(final Request request, final ByteBuffer key, final HttpSession session) throws IOException { switch (request.getMethod()) { case Request.METHOD_GET: executeAsync(session, () -> getMethodWrapper(key)); return; case Request.METHOD_PUT: executeAsync(session, () -> putMethodWrapper(key, request)); return; case Request.METHOD_DELETE: executeAsync(session, () -> deleteMethodWrapper(key)); return; default: session.sendError(Response.METHOD_NOT_ALLOWED, "Wrong method"); return; } } @Override public void handleDefault( @NotNull final Request request, @NotNull final HttpSession session) throws IOException { switch (request.getPath()) { case "/v0/entity": entity(request, session); break; case "/v0/entities": entities(request, session); break; default: session.sendError(Response.BAD_REQUEST, "Wrong path"); break; } } private void executeAsync( @NotNull final HttpSession session, @NotNull final Action action) throws IOException { workerThreads.execute(() -> { try { session.sendResponse(action.act()); } catch (IOException e) { try { session.sendError(Response.INTERNAL_ERROR, e.getMessage()); } catch (IOException ex) { logger.log(Level.SEVERE,"Exception while processing request: ", e); } } }); } @FunctionalInterface interface Action { Response act() throws IOException; } private void entities( @NotNull final Request request, @NotNull final HttpSession session) throws IOException { final String start = request.getParameter("start="); if (start == null || start.isEmpty()) { session.sendError(Response.BAD_REQUEST, "No start"); return; } if (request.getMethod() != Request.METHOD_GET) { session.sendError(Response.METHOD_NOT_ALLOWED, "Wrong method"); return; } String end = request.getParameter("end="); if (end != null && end.isEmpty()) { end = null; } try { final Iterator<Record> records = dao.range(ByteBuffer.wrap(start.getBytes(StandardCharsets.UTF_8)), end == null ? null : ByteBuffer.wrap(end.getBytes(StandardCharsets.UTF_8))); ((StreamStorageSession) session).stream(records); } catch (IOException e) { session.sendError(Response.INTERNAL_ERROR, e.getMessage()); } } @NotNull private Response getMethodWrapper(final ByteBuffer key) throws IOException { try { final byte[] res = copyAndExtractFromByteBuffer(key); return new Response(Response.OK, res); } catch (NoSuchElementException exp) { return new Response(Response.NOT_FOUND, Response.EMPTY); } } private byte[] copyAndExtractFromByteBuffer(@NotNull final ByteBuffer key) throws IOException { final ByteBuffer dct = dao.get(key).duplicate(); final byte[] res = new byte[dct.remaining()]; dct.get(res); return res; } @NotNull private Response putMethodWrapper(final ByteBuffer key, final Request request) throws IOException { dao.upsert(key, ByteBuffer.wrap(request.getBody())); return new Response(Response.CREATED, Response.EMPTY); } @NotNull private Response deleteMethodWrapper(final ByteBuffer key) throws IOException { dao.remove(key); return new Response(Response.ACCEPTED, Response.EMPTY); } }
true
f2478f8d940268cb2322d2ed3ed0bb811e01cf84
Java
gvenkatesh4/javabasicsprograms
/java basics/src/cocubesprograms1/Sumofdivisibleby3and5.java
UTF-8
288
2.921875
3
[]
no_license
package cocubesprograms1; public class Sumofdivisibleby3and5 { public static void main(String[] args) { int ha =1; int sa = 5; int sum = 0; for(int i =ha;i<=sa;i++) { if(i%3==0||i%5==0) { sum = sum+i; } } System.out.println(sum); } }
true
5065d8f7363145a1cd24e03f5700371bf148430a
Java
makotogo/SimpleCursorAdapterExample
/app/src/main/java/com/makotogo/mobile/learn/simplecursoradapterexample/Person.java
UTF-8
2,878
2.71875
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Makoto Consulting Group, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.makotogo.mobile.learn.simplecursoradapterexample; import java.util.Date; public class Person { public enum EyeColor { BLACK, BROWN, BLUE, GREEN, HAZEL, GOLD, UNKNOWN } public enum Gender { MALE, FEMALE, UNKNOWN } public Person(String lastName, String firstName, int age, EyeColor eyeColor, Gender gender) { this.lastName = lastName; this.firstName = firstName; this.age = age; this.eyeColor = eyeColor; this.gender = gender; } //************************************ //* D B - S P E C F I C S T U F F * //************************************ private Long mId; private Date mWhenCreated; public Long getId() { return mId; } public void setId(Long id) { this.mId = id; } public Date getWhenCreated() { return mWhenCreated; } public void setWhenCreated(Date whenCreated) { this.mWhenCreated = whenCreated; } //*********************** //* A T T R I B U T E S * //*********************** private String lastName; private String firstName; private int age; private EyeColor eyeColor; private Gender gender; public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public EyeColor getEyeColor() { return eyeColor; } public void setEyeColor(EyeColor eyeColor) { this.eyeColor = eyeColor; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @Override public String toString() { return "Person [id=" + mId + ", lastName=" + lastName + ", firstName=" + firstName + ", age=" + age + ", height=" + ", eyeColor=" + eyeColor + ", gender=" + gender + ", whenCreated = " + mWhenCreated + "]"; } }
true
17f759c125803b59a6f8780db83d1f0d49eec0c8
Java
anandsnair/Projects
/HackerRank/src/com/datastructures/linkedlist/InsertNodeAtPosition.java
UTF-8
1,701
3.6875
4
[]
no_license
package com.datastructures.linkedlist; public class InsertNodeAtPosition { public static void main(String[] args) { Node node = new Node(); node.setData(1); node.setNext(null); InsertNodeAtPosition insertNode = new InsertNodeAtPosition(); Node head = insertNode.InsertNth(node, 2, 0); insertNode.printAllNodes(head); head = insertNode.insertNodeAtTheTail(head, 5); insertNode.printAllNodes(head); } public void printAllNodes(Node head) { while(head != null) { System.out.println(head.data); head = head.next; } } Node InsertNth(Node head, int data, int position) { Node insertNode = new Node(); insertNode.data = data; int currentPosition = 0; if(head != null && position !=0) { Node prevNode = head; Node currentNode = head; while(currentPosition < position) { prevNode = currentNode; currentNode = currentNode.next; ++currentPosition; } prevNode.next = insertNode; insertNode.next = currentNode; } else { insertNode.next = head; head = insertNode; } return head; } Node findNodeLocationToInsert(Node head, int position, int currentPosition) { if(currentPosition == position) { return head; } else { return findNodeLocationToInsert(head.next, position, ++currentPosition); } } public Node insertNodeAtTheTail(Node head, int data) { Node currentNode = head; Node newNode = new Node(); newNode.data = data; if(head != null) { while(currentNode.next!= null) { currentNode = currentNode.next; } currentNode.next = newNode; } else { head = newNode; } return head; } }
true
522cf9b3d8f1a6bc4748759b520d18aa675e29be
Java
gremic6611/haiku
/src/main/java/smg/emgem/haiku/service/HaikuServiceImpl.java
UTF-8
12,854
2.34375
2
[]
no_license
package smg.emgem.haiku.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Service; import smg.emgem.haiku.api.Noun; import smg.emgem.haiku.api.Word; @Service public class HaikuServiceImpl implements HaikuService { @Autowired ResourceLoader loader; Logger log = LoggerFactory.getLogger(HaikuServiceImpl.class); HttpClient client = HttpClientBuilder.create().build(); String externalUID = null;//default val private Map<String, List<Word>> wordSet = null; private Map<String, List<String>> adjectiveMap = null; @Override public String getGeneratedHaiku() { try { if (wordSet==null) initSlovakWordSet(); String result, pattern; int randomSeed = Double.valueOf(Math.random()*1000).intValue(); if (randomSeed%2 == 0) { result= load_ANVR_but_NV_Line(); pattern = "ANVR but NV"; } else if (randomSeed%3 == 0) { result= load_NV_but_ANV_Line(); pattern = "NV_but_ANV"; } else if (randomSeed%5 == 0) { result = load_NV_NV_ANV_Line(); pattern = "NV_NV_ANV"; } else if (randomSeed%7 == 0) { result= load_C2_ANVR_Line(); pattern = "C2_ANVR"; } else if (randomSeed%11 == 0) { result= load_C1_ANV_Line(); pattern = "C1_ANV"; } else { result= load_ANV_ANVR_Line(); pattern = "ANV_ANVR"; } result = result.substring(0,1).toUpperCase()+result.substring(1); log.info(String.format("Creating pattern %s wordweave: %s", pattern, result)); return result; } catch (IOException e) { log.error(e.getMessage()); return null; } } protected String load_ANV_ANVR_Line() throws IOException { //pattern a n v , a n v r String result = createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+ ", "+ createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+ " "+ getRndWord("r").getValue()+ "."; return result; } protected String load_ANVR_but_NV_Line() throws IOException { //pattern a n v r ,but n v String result = createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+" "+ getRndWord("r").getValue()+ ", ale "+ getRndWord("n").getValue()+ " "+ changeVerbSufix(getRndWord("v"))+ "."; return result; } protected String load_NV_but_ANV_Line() throws IOException { //pattern n v ,but a n v String result = getRndWord("n").getValue() + " " + changeVerbSufix(getRndWord("v")) + ", zatial čo "+ createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+ "."; return result; } protected String load_NV_NV_ANV_Line() throws IOException { // pattern nv - nv - anv. String result = getRndWord("n").getValue() + " " + changeVerbSufix(getRndWord("v")) + " - " + getRndWord("n").getValue() + " " + changeVerbSufix(getRndWord("v")) + " - " + createAdjectiveGender(getRndWord("a"), getRndWord("n")) + " " + changeVerbSufix(getRndWord("v")) + "."; return result; } protected String load_C1_ANV_Line() throws IOException { // pattern constant - anv. String citation = createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+ "\" ."; return "Múdry muž povedal: \""+citation.substring(0, 1).toUpperCase() + citation.substring(1); } protected String load_C2_ANVR_Line() throws IOException { // pattern constant - anvr. String result = "Každý vie, že "+ createAdjectiveGender(getRndWord("a"), getRndWord("n"))+ " "+ changeVerbSufix(getRndWord("v"))+" "+ getRndWord("r").getValue() + "."; return result; } private Word getRndWord(String type) { if (wordSet==null) initSlovakWordSet(); List<Word> subset = wordSet.get(type); if (subset == null) throw new RuntimeException("Invalid word type "+type); int radomIndex = Double.valueOf(Math.random()*subset.size()).intValue(); return subset.get(radomIndex); } private void initExternalUID() { try { HttpResponse response = client.execute(new HttpGet("http://slovniky.korpus.sk/?d=noundb")); String responseStr = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8")); String uidField = "<input type=\"hidden\" name=\"c\" value=\""; if (responseStr.contains(uidField)) { int uidIndex = responseStr.indexOf(uidField)+uidField.length(); externalUID = responseStr.substring(uidIndex, uidIndex+4); } } catch (Exception e) { } } private void initSlovakWordSet() { log.info("Initializing slovak word database"); wordSet = new HashMap<>(); wordSet.put("a", new ArrayList<Word>()); wordSet.put("n", new ArrayList<Word>()); wordSet.put("v", new ArrayList<Word>()); wordSet.put("r", new ArrayList<Word>()); Pattern wordPattern = Pattern.compile("(\\d+\\s(\\w)\\s)"); try { Resource resource = loader.getResource("classpath:static/wordb/wordDb.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream())); String line = reader.readLine(); while (line != null) { int labelIndex = Math.min(line.indexOf(";"), line.indexOf("␞")); if (labelIndex != -1) { Matcher matcher = wordPattern.matcher(line); if (matcher.find()) { String start = line.substring(0, labelIndex); String prefix = matcher.group(0); String category = prefix.contains("a") ? "a" : prefix.contains("n") ? "n" : prefix.contains("v") ? "v": "r"; Word word; if ("n".equals(category)) {//getting gender int rod=0; try { rod = Integer.valueOf(prefix.substring(0, prefix.length()-3)); } catch (Exception e) { log.warn("Cannot parse noun input for "+line); } word = new Noun(start.substring(prefix.length()), rod); } else { word = new Word(start.substring(prefix.length())); } wordSet.get(category).add(word); } } line = reader.readLine(); } } catch (IOException e) { log.error("Problem reading word database:", e.getMessage()); } } private void initAdjectiveMap() { adjectiveMap = new HashMap<>(); adjectiveMap.put("ý", Arrays.asList("ý", "á", "é")); adjectiveMap.put("y", Arrays.asList("y", "a", "e")); adjectiveMap.put("i", Arrays.asList("i", "a", "e")); adjectiveMap.put("í", Arrays.asList("í", "ia", "ie")); adjectiveMap.put("á", Arrays.asList("ý", "á", "é")); adjectiveMap.put("a", Arrays.asList("y", "a", "e")); adjectiveMap.put("é", Arrays.asList("ý", "á", "é")); adjectiveMap.put("e", Arrays.asList("y", "a", "e")); } // sets of rules to change from neutral to nominativ private String changeVerbSufix(Word verb) { String neutral = verb.getValue(); neutral = neutral.trim(); log.info("Default neutral:" + neutral); String postfix = ""; String prefix = ""; if (neutral.endsWith(" sa")) { neutral = neutral.substring(0, neutral.indexOf(" sa")); prefix = " sa "; log.info("Changed neutral to:" + neutral); } if (neutral.endsWith(" si")) { neutral = neutral.substring(0, neutral.indexOf(" si")); prefix = " si "; log.info("Changed neutral to:" + neutral); } if (neutral.contains(" ")) { postfix = neutral.substring(neutral.indexOf(" ")); log.info("Postfix changed to:" + postfix); neutral = neutral.substring(0, neutral.indexOf(" ")); } if (neutral.endsWith("ovať")) { return prefix + neutral.replace("ovať", "uje") + postfix; } if (neutral.endsWith("aviť")) { return prefix + neutral.replace("aviť", "avuje") + postfix; } if (neutral.endsWith("jiť")) { return prefix + neutral.replace("jiť", "juje") + postfix; } if (neutral.endsWith("núť")) { return prefix + neutral.replace("núť", "ne") + postfix; } if (neutral.endsWith("nuť")) { return prefix + neutral.replace("nuť", "ne") + postfix; } if (neutral.endsWith("návať")) { return prefix + neutral.replace("návať", "náva") + postfix; } if (neutral.endsWith("diť")) { return prefix + neutral.replace("diť", "di") + postfix; } if (neutral.endsWith("rieť")) { return prefix + neutral.replace("rieť", "rie") + postfix; } if (neutral.endsWith("cať")) { return prefix + neutral.replace("cať", "ciať") + postfix; } if (neutral.endsWith("čať")) { return prefix + neutral.replace("čať", "čína") + postfix; } if (neutral.endsWith("brať")) { return prefix + neutral.replace("brať", "berie") + postfix; } if (neutral.endsWith("rať")) { return prefix + neutral.replace("rať", "rá") + postfix; } if (neutral.endsWith("žať")) { return prefix + neutral.replace("žať", "ží") + postfix; } if (neutral.endsWith("ať")) { return prefix + neutral.replace("ať", "a") + postfix; } if (neutral.endsWith("ieť")) { return prefix + neutral.replace("ieť", "í") + postfix; } if (neutral.endsWith("iť")) { return prefix + neutral.replace("iť", "í") + postfix; } return prefix + neutral + postfix; } private String createAdjectiveGender(Word adjective, Word noun) { int gender= 0; try { Noun castNoun = (Noun)noun; gender=castNoun.getGender(); log.debug("Orginal gender info for: "+noun.getValue() +" is "+castNoun.getGender()); } catch (Exception e) { //gulp } if (gender == 0) gender=findGenderExternally(noun.getValue()); if (gender > 0) return changeAdjectiveGender(adjective.getValue(), noun.getValue(), gender); return adjective+" "+noun; } private int findGenderExternally(String noun){ int result = 0; //not found String word = noun.trim(); String[] mulitword= word.split(" "); if (mulitword.length>1) { for (String part:mulitword) { result = findGenderSingleWord(noun, part); if (result > 0) break; //no need to continue } word = mulitword[mulitword.length-1]; } else { result = findGenderSingleWord(noun, word); } return result; } private int findGenderSingleWord(String noun, String word) { HttpResponse response; int result = 0; //not found log.info("Input: "+noun+" - Finding gender for "+word); try { URIBuilder builder = new URIBuilder("http://slovniky.korpus.sk/?s=exact&d=noundb&ie=utf-8&oe=utf-8"); builder.addParameter("w", word); if (externalUID==null) initExternalUID(); builder.addParameter("c", externalUID); response = client.execute(new HttpGet(builder.toString())); String responseStr = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8")); //refreash UID String uidField = "<input type=\"hidden\" name=\"c\" value=\""; if (responseStr.contains(uidField)) { int uidIndex = responseStr.indexOf(uidField)+uidField.length(); externalUID = responseStr.substring(uidIndex, uidIndex+4); } if (responseStr.contains("<b class=\"b0\">"+word+"</b><br>")) { String rod = responseStr.substring(responseStr.indexOf("<b class=\"b0\">"+word+"</b><br>")+14+word.length()+9); rod=rod.substring(0, rod.indexOf("rod")); log.info("Gender found as "+rod); if (rod.contains("stredn")) return 3; if (rod.contains("ensk")) return 2; if (rod.contains("mu")) return 1; } else { initExternalUID(); } } catch (Exception e) { log.error("Error connecting to external dictionary "+e.getMessage()); } return result; } private String changeAdjectiveGender(String adjective, String noun, int gender) { if (adjectiveMap == null) initAdjectiveMap(); adjective = adjective.trim(); String adjectiveEnding = adjective.substring(adjective.length()-1); log.debug("Morphing "+adjective+ " ending with "+adjectiveEnding+ " to gender "+gender); List<String> properReplaceList = adjectiveMap.get(adjectiveEnding); if (properReplaceList != null) { adjective = adjective.substring(0, adjective.length()-1)+properReplaceList.get(gender-1); } String result = adjective+" "+noun; log.info("Morphing ended with "+result); return result; } }
true
2dca92e50ffdd39eb739838c5867bbe1667d9266
Java
rodya-mirov/robodorf
/src/main/java/io/github/rodyamirov/symbols/SymbolValue.java
UTF-8
1,432
3
3
[]
no_license
package io.github.rodyamirov.symbols; import io.github.rodyamirov.exceptions.TypeCheckException; import java.util.Objects; /** * Created by richard.rast on 12/27/16. */ public class SymbolValue<T> { public final TypeSpec typeSpec; public final T value; private SymbolValue(TypeSpec typeSpec, T value) { this.typeSpec = typeSpec; this.value = value; } @Override public boolean equals(Object o) { if (o == null || !(o instanceof SymbolValue)) { return false; } SymbolValue other = (SymbolValue)o; return Objects.equals(this.typeSpec, other.typeSpec) && Objects.equals(this.value, other.value); } @Override public int hashCode() { return 43 * Objects.hashCode(value) + typeSpec.hashCode(); } public static SymbolValue make(TypeSpec typeSpec, Object value) { Class desiredClass = typeSpec.getValueClass(); if (value == null) { if (typeSpec.acceptsNullValues()){ return new SymbolValue(typeSpec, null); } else { throw TypeCheckException.nullNotAllowed(typeSpec); } } else if (desiredClass.isInstance(value)) { return new SymbolValue<>(typeSpec, desiredClass.cast(value)); } else { throw TypeCheckException.wrongValueClass(value.getClass(), desiredClass); } } }
true
284faf235f98bc53417e08f7d1a33391f651b6f9
Java
stanciusebastian/MovieBooking
/src/main/java/com/example/moviebookingws/io/repositories/UserRepository.java
UTF-8
333
1.890625
2
[]
no_license
package com.example.moviebookingws.io.repositories; import com.example.moviebookingws.io.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<UserEntity,Long> { UserEntity findByEmail(String email); UserEntity findByUserId(String userId); }
true
42d0d13bce0cd5004fc5257d52731be39d884ef0
Java
wchb2015/algorithm_and_leetcode
/src/main/java/com/wchb/leetcode/S435.java
UTF-8
1,728
3.328125
3
[]
no_license
package com.wchb.leetcode; import java.util.Arrays; /** * @date 7/26/18 2:37 PM */ public class S435 { //T: O(n^2); public int eraseOverlapIntervals(Interval[] intervals) { Arrays.sort(intervals, (i1, i2) -> i1.start - i2.start); int n = intervals.length; if (n <= 1) return 0; int[] mem = new int[n]; Arrays.fill(mem, 1); for (int i = 1; i < n; i++) { for (int j = i - 1; j >= 0; j--) { if (isNonOverlapping(intervals[j], intervals[i])) { mem[i] = Math.max(mem[i], mem[j] + 1); } } } Arrays.sort(mem); return n - mem[n - 1]; // System.out.println(Arrays.toString(mem)); } private boolean isNonOverlapping(Interval i1, Interval i2) { return i2.start >= i1.end; } /************************************************************/ //贪心算法:按照区间的结尾排序,每次选择结尾最早的,且和前一个区间不重叠的区间 //T:o(n); public int eraseOverlapIntervalsV2(Interval[] intervals) { Arrays.sort(intervals, (i1, i2) -> i1.end - i2.end); int n = intervals.length; if (n <= 1) return 0; int res = 1; int pre = 0; for (int i = 1; i < n; i++) { if (intervals[i].start >= intervals[pre].end) { res++; pre = i; } } return n - res; } public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } }
true
2e6a6406c20bae9b087a88bb058a68a7d01d03e0
Java
yurkesh/PZCS2
/src/edu/kpi/nesteruk/pzcs/graph/mutating/SplitBranchMutator.java
UTF-8
357
1.984375
2
[]
no_license
package edu.kpi.nesteruk.pzcs.graph.mutating; import edu.kpi.nesteruk.pzcs.model.tasks.TasksGraph; import org.jgrapht.Graph; import java.util.Set; /** * Created by Yurii on 2017-01-09. */ public class SplitBranchMutator implements GraphMutator<TasksGraph> { @Override public TasksGraph mutate(TasksGraph graph) { return null; } }
true
2603f564d6cdc2cd978247a3ca853a4013b63e72
Java
JonathanLoiseau/LastClimb
/src/main/java/com/last_climb/climb/controller/SecteurCreationController.java
UTF-8
971
2.21875
2
[]
no_license
package com.last_climb.climb.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import com.last_climb.climb.model.form.CreationVoieForm; import com.last_climb.climb.model.form.VoiesForm; @Controller public class SecteurCreationController { @GetMapping("/secteur_creation") public String displayControllerVoiesCreation(Model model, HttpSession session) { model.addAttribute("creationvoieform", new CreationVoieForm()); return "secteur_creation"; } @PostMapping("/secteur_creation") public String displayControllerVoiesCreationPost(CreationVoieForm crea, Model model, HttpSession session) { model.addAttribute("voiesform", crea); model.addAttribute("voie", new VoiesForm()); session.setAttribute("secteur", crea); return "voie_creation"; } }
true
d5f2ba9968822f91ebc94c1d87251bf918b1a724
Java
github4n/cloud
/common-service/payment-service-project/payment-service-interface/src/main/java/com/iot/payment/enums/RefundStatus.java
UTF-8
533
2.34375
2
[]
no_license
package com.iot.payment.enums; public enum RefundStatus { /** 未退款*/ NO_REFUND(0,"no refund"), /** 退款中*/ IN_REFUND(1,"refunding"), /** 退款成功*/ REFUND_SUCCESS(2,"already refund"), /** 退款失败*/ REFUND_FAIL(3,"refund fail"), ; /** 编码*/ private int code; /** 描述*/ private String desc; private RefundStatus(int code, String desc) { this.code = code; this.desc = desc; } public int getCode() { return code; } public String getDesc() { return desc; } }
true
55c94367848eeaecee7fd355dda21b81baf83ec6
Java
echofoo/Java-Notes
/LeetCodeSolutions/src/code_07_dp/Code_188_BestTimeToBuyAndSellStockIV.java
UTF-8
2,435
3.875
4
[]
no_license
package code_07_dp; import org.junit.Test; /** * 188. Best Time to Buy and Sell Stock IV * * Say you have an array for which the ith element is the price of a given stock on day i. * Design an algorithm to find the maximum profit. You may complete at most k transactions. * * Example 1: Input: [2,4,1], k = 2 Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. Example 2: Input: [3,2,6,5,0,3], k = 2 Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. */ public class Code_188_BestTimeToBuyAndSellStockIV { public int maxProfit(int k, int[] prices) { int n=prices.length; if(k<=0){ return 0; } if(k>=n/2){ return maxProfit(prices); } //buy[i]表示完成第i笔交易的买入动作时的最大收益 //sell[i]表示完成第i笔交易的卖出动作时的最大收益 int[] buy=new int[k+1]; int[] sell=new int[k+1]; for(int i=0;i<k+1;i++){ buy[i]=Integer.MIN_VALUE; } //buy[i] = max(buy[i], sell[i-1]-prices)[先要买入,然后才能卖出,i>=1] //第i次买入动作的最大收益=max{第i次买入动作是的最大收益,第(i-1)次卖出动作的最大收益-今天买入} //sell[i] = max(sell[i], buy[i]+prices) //第i次卖出动作的最大收益=max{第i次卖出动作的最大收益,第i次买入动作的最大收益+今天卖出} for(int price: prices){ for(int i=k;i>=1;i--){ buy[i]=Math.max(buy[i],sell[i-1]-price); sell[i]=Math.max(sell[i],buy[i]+price); } } return sell[k]; } //k>=n/2,只要有利润,就可以买入 private int maxProfit(int[] prices){ int n=prices.length; if(n<=1){ return 0; } int res=0; for(int i=1;i<n;i++){ if(prices[i]>prices[i-1]){ res+=(prices[i]-prices[i-1]); } } return res; } @Test public void test(){ //int[] nums={3,2,6,5,0,3}; //int[] nums={2,4,1}; // int[] nums={3,3,5,0,0,3,1,4}; int[] nums={6,1,6,4,3,0,2}; int k = 1; System.out.println(maxProfit(k,nums)); } }
true
72292c86ba45f22b57dbd73524f0cd64d91d3ee0
Java
Praveen-Varma/staedi
/src/test/java/io/xlate/edi/internal/stream/validation/ValueSetTester.java
UTF-8
961
2.140625
2
[ "Apache-2.0" ]
permissive
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; interface ValueSetTester { default Set<String> setOf() { return Collections.emptySet(); } default Set<String> setOf(String... values) { return new HashSet<>(Arrays.asList(values)); } default void assertHasError(ElementValidator v, Dialect dialect, EDISimpleType element, CharSequence value, EDIStreamValidationError expected) { List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, value, errors); assertTrue(errors.contains(expected)); } }
true
3f6eaeb4162c854ed11a09e87fcde81a8870cde5
Java
dwifdji/real-project
/win-back/winback-core/core-commons/src/main/java/com/winback/core/commons/constants/SystemSiteEnum.java
UTF-8
739
2.75
3
[]
no_license
package com.winback.core.commons.constants; public class SystemSiteEnum { public enum CaseSiteType{ CASE_PHASE("1", "案件阶段"), CAPITAL_USES("2", "资金用途"); private String type; private String typeDesc; CaseSiteType(String type, String typeDesc) { this.type = type; this.typeDesc = typeDesc; } public static String getDescByType(String type) { CaseSiteType[] values = CaseSiteType.values(); for (CaseSiteType caseSiteType:values) { if(caseSiteType.type.equals(type)) { return caseSiteType.typeDesc; } } return null; } } }
true
d034dba716a150c9978ae15bcf19cf7ef616fd62
Java
888xin/cbs.api
/cbs.api.content.dao/src/main/java/com/lifeix/cbs/content/dao/frontpage/impl/FrontPageAdDaoImpl.java
UTF-8
4,485
2.0625
2
[]
no_license
package com.lifeix.cbs.content.dao.frontpage.impl; import com.lifeix.cbs.content.dao.ContentDaoSupport; import com.lifeix.cbs.content.dao.frontpage.FrontPageAdDao; import com.lifeix.cbs.content.dto.frontpage.FrontPage; import com.lifeix.framework.memcache.MultiCacheResult; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by lhx on 15-11-27 下午3:05 * * @Description */ @Repository("frontPageAdDao") public class FrontPageAdDaoImpl extends ContentDaoSupport implements FrontPageAdDao { @Override public Long insert(FrontPage frontPage) { if (sqlSession.insert("FrontPageAdMapper.insert", frontPage) > 0) { memcacheService.set(getCacheId(frontPage.getId()), frontPage); return frontPage.getId(); } return -1L; } @Override public Map<Long, FrontPage> findByIds(List<Long> ids) { Map<Long, FrontPage> ret = new HashMap<Long, FrontPage>(); if (ids == null || ids.size() == 0) { return ret; } MultiCacheResult cacheResult = memcacheService.getMulti(getMultiCacheId(ids)); Collection<String> noCached = cacheResult.getMissIds(); Map<String, Object> cacheDatas = cacheResult.getCacheData(); for (String key : cacheDatas.keySet()) { Object obj = cacheDatas.get(key); if (obj != null) { try { ret.put(Long.valueOf(revertCacheId(key)), (FrontPage) obj); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } if (noCached.size() > 0) { Map<Long, FrontPage> frontPageMap = sqlSession.selectMap("FrontPageAdMapper.findMapByIds", revertMultiCacheId(noCached), "id"); Collection<Long> keys = frontPageMap.keySet(); for (Long fId : keys) { FrontPage frontPage = frontPageMap.get(fId); if (frontPage != null) { ret.put(fId, frontPage); memcacheService.set(getCacheId(fId), frontPage); } } } return ret; } @Override public FrontPage findById(Long fId) { String cacheKey = getCacheId(fId); FrontPage frontPage = memcacheService.get(cacheKey); if (frontPage == null) { frontPage = sqlSession.selectOne("FrontPageAdMapper.findById", fId); if (frontPage != null) { memcacheService.set(cacheKey, frontPage); } } return frontPage; } @Override public List<FrontPage> findFrontPages(Long startId, Long endId, Integer limit,Integer type) { Map<String, Object> params = new HashMap<String, Object>(); params.put("type", type); params.put("startId", startId); params.put("endId", endId); params.put("limit", limit); return sqlSession.selectList("FrontPageAdMapper.findFrontPages", params); } @Override public List<FrontPage> findFrontPagesInner(Long startId, Long endId, Integer limit, Integer type, Integer status, Integer skip) { Map<String, Object> params = new HashMap<String, Object>(); params.put("type", type); params.put("startId", startId); params.put("endId", endId); params.put("limit", limit); params.put("status", status); params.put("skip", skip); return sqlSession.selectList("FrontPageAdMapper.findFrontPagesInner", params); } @Override public boolean editFrontPagesInner(Long id, Integer status) { memcacheService.delete(getCacheId(id)); Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); params.put("status", status); return sqlSession.update("FrontPageAdMapper.editFrontPagesInner", params) > 0; } @Override public Integer findFrontPagesCount(Integer type, Integer status) { Map<String, Object> params = new HashMap<String, Object>(); params.put("type", type); params.put("status", status); return sqlSession.selectOne("FrontPageAdMapper.findFrontPagesCount", params); } @Override public FrontPage findByContentId(Long contentId) { return sqlSession.selectOne("FrontPageAdMapper.findByContentId", contentId); } }
true
0e4aa3087a7100edd2cc690616d5f953761c89f0
Java
yookore/android-v1
/app/src/main/java/com/yookos/mobileapp/RecommendFriends.java
UTF-8
3,786
1.992188
2
[]
no_license
package com.yookos.mobileapp; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; 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.ListView; import com.yookos.mobileapp.adapter.RecommendedFriednsAdapter; import com.yookos.mobileapp.models.RecommendFriendsItem; import java.util.ArrayList; public class RecommendFriends extends ActionBarActivity { Toolbar toolbar; ArrayList<RecommendFriendsItem> friends; RecommendFriendsItem frienditem; ListView friendslist; RecommendedFriednsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recommend_friends); setToolbar(); friends = new ArrayList<RecommendFriendsItem>(); friendslist = (ListView) findViewById(R.id.friendslist); Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; Cursor people = getContentResolver().query(uri, projection, null, null, null); int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int indexEmail = people.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS); people.moveToFirst(); do { frienditem = new RecommendFriendsItem(); String name = people.getString(indexName); String number = people.getString(indexNumber); String email = people.getString(indexEmail); Log.d("name",name+" : "+number+" - "+email); frienditem.setName(name); frienditem.setEmail(email); frienditem.setNumber(number); frienditem.setState(false); friends.add(frienditem); // Do work... } while (people.moveToNext()); adapter = new RecommendedFriednsAdapter(getApplicationContext(), friends); friendslist.setAdapter(adapter); } public void setToolbar(){ toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.app_bar); toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_recommend_friends, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_skip) { Intent intent = new Intent(RecommendFriends.this, StreamActivity.class); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } }
true
193c14f8a514d6df4a537ef2c2b823d20c007cbf
Java
thorbenprimke/defunct-fitness-app
/app/src/main/java/com/femlite/app/di/ActivityComponent.java
UTF-8
1,840
2.15625
2
[]
no_license
package com.femlite.app.di; import android.app.Activity; import com.femlite.app.ExerciseListActivity; import com.femlite.app.FemliteBaseActivity; import com.femlite.app.FemliteDrawerActivity; import com.femlite.app.FoodTrackerAddFoodActivity; import com.femlite.app.FoodTrackerMainActivity; import com.femlite.app.RecipeIdeasActivity; import com.femlite.app.WorkoutDetailActivity; import com.femlite.app.WorkoutMainActivity; import com.femlite.app.views.ExerciseItemView; import dagger.Component; /** * A base component for activities. It uses the {@link PerActivity} scope. Any components that * extend this component must also annotate it with {@link PerActivity}. * * Note: Any instances provided via {@link Module}s are only available to be injected * into any objects within the same {@link Component} level / {@link Scope}. If any instances should * be available to sub-graphs / other scopes, they need to be exposed within the component. * In order to expose at least the same instances as the parent/dependent component, this interface * extends {@link ApplicationComponent} in order to inherit all of its exposed instances. */ @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent extends ApplicationComponent { Activity activity(); void inject(WorkoutMainActivity workoutMainActivity); void inject(FoodTrackerMainActivity foodTrackerMainActivity); void inject(FoodTrackerAddFoodActivity foodTrackerAddFoodActivity); void inject(FemliteDrawerActivity femliteDrawerActivity); void inject(WorkoutDetailActivity workoutDetailActivity); void inject(ExerciseListActivity exerciseListActivity); void inject(RecipeIdeasActivity recipeIdeasActivity); void inject(ExerciseItemView exerciseItemView); }
true
38b87edecb8620f4dff286bd88e858766b850087
Java
qwe00921/switchui
/packages/platform/Tauren/Tauren/src/com/motorola/mmsp/render/MotoInteractionSet.java
UTF-8
2,073
2.5
2
[]
no_license
package com.motorola.mmsp.render; import java.util.ArrayList; import com.motorola.mmsp.render.resloader.MotoResLoader.ResOutputInfo; import com.motorola.mmsp.render.util.MotoMathUtil; public class MotoInteractionSet { private ArrayList<MotoInteraction> mInteractions = new ArrayList<MotoInteraction>(); private int mId; private ArrayList<MotoInteraction> mHandleEventInteractions = new ArrayList<MotoInteraction>(); public MotoInteractionSet(MotoAttributeArray attr, ResOutputInfo resInfo) { String id = (String)attr.getValue("id"); if (id != null) { mId = MotoMathUtil.parseInt(id); } } public void setId(int id) { mId = id; } public int getId() { return mId; } public void addInteraction(MotoInteraction interaction) { mInteractions.add(interaction); } public void removeInteraction(MotoInteraction interaction) { mInteractions.remove(interaction); } public void removeInteraction(int index) { mInteractions.remove(index); } public void removeAll() { mInteractions.clear(); } public MotoInteraction getInteractionAt(int index) { if (index <= mInteractions.size()) { return mInteractions.get(index); } return null; } public int getInteractionCount() { return mInteractions.size(); } public boolean isInterceptEvent(MotoInteractionEvent event, boolean isProvioursIntercepted) { int size = mInteractions.size(); for (int i=0; i<size; i++) { MotoInteraction child = mInteractions.get(i); if (child.isInterceptEvent(event, isProvioursIntercepted)) { return true; } } return false; } public ArrayList<MotoInteraction> handleEventInteractions(MotoInteractionEvent event, boolean isProvioursIntercepted) { mHandleEventInteractions.clear(); int size = mInteractions.size(); for (int i=0; i<size; i++) { MotoInteraction child = mInteractions.get(i); if (child.isHandleEvent(event, isProvioursIntercepted)) { mHandleEventInteractions.add(child); } } return mHandleEventInteractions; } }
true
92f940b4f1086bff8a8a54811e9a3fba8fa40075
Java
SiddharthaNG447/Core_Java
/charat2.java
UTF-8
709
3.109375
3
[]
no_license
package Strings; import java.util.Scanner; public class charat2 { public static void main(String[] args) throws Numberexceeds{ // TODO Auto-generated method stub String s="htderabad"; Scanner sc=new Scanner(System.in); System.out.println("enter index"); try { int index=sc.nextInt(); char []ch=s.toCharArray(); if(index<0||index>ch.length) throw new Numberexceeds("pls enter range number"); System.out.println(ch[index]); } catch(Exception e) {System.out.println(e);} } } class Numberexceeds extends Exception { Numberexceeds(String s) { super(s); } }
true
a192055a754a44cb52859acebf2d8b81135f1523
Java
luguumur/courtdecision
/src/main/java/mn/mcs/electronics/court/model/YearSelectionModel.java
UTF-8
1,155
2.328125
2
[]
no_license
package mn.mcs.electronics.court.model; import java.io.Serializable; import java.util.Calendar; import java.util.List; import org.apache.tapestry5.OptionGroupModel; import org.apache.tapestry5.OptionModel; import org.apache.tapestry5.internal.OptionModelImpl; import org.apache.tapestry5.ioc.internal.util.CollectionFactory; import org.apache.tapestry5.util.AbstractSelectModel; public class YearSelectionModel extends AbstractSelectModel implements Serializable { private static final long serialVersionUID = 1438843132757579237L; private final List<OptionModel> options = CollectionFactory.newList(); public YearSelectionModel(Integer oldYear) { Calendar cal = Calendar.getInstance(); if(oldYear==null){ oldYear = cal.get(Calendar.YEAR); } Integer currentYear = cal.get(Calendar.YEAR) + 1; for(int i = oldYear; i<= currentYear ; i++) options.add(new OptionModelImpl(Integer.toString(i),(i))); } public List<OptionGroupModel> getOptionGroups() { // TODO Auto-generated method stub return null; } public List<OptionModel> getOptions() { // TODO Auto-generated method stub return options; } }
true
df3ca02c68a5a33b2d0e0d68ad10a1248a0d3a40
Java
kien1501/javacore
/src/javacore1/HomeWork11.java
UTF-8
438
3.234375
3
[]
no_license
package javacore1; import java.util.Scanner; public class HomeWork11 { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.print("Nhập vào số a = "); int a =sc.nextInt(); System.out.print("Nhập vào số b = "); int b = sc.nextInt(); System.out.println("Tổng a + b là "+(a+b)); System.out.print("Tích a x b là "+(a*b)); } }
true
835b6c9d63143448a106320069110c12f544a8f9
Java
christwei/testCode
/UtilityTest/src/com/loop/LoopTest.java
UTF-8
833
3.4375
3
[]
no_license
package com.loop; public class LoopTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub testLoop (); } /** * 循环测试. */ public static void testLoop () { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { System.out.println(i+"X" + j + "="+i*j); } } System.out.println(""); System.out.println("------------------------九九乘法-----------------------------"); for (int i = 1; i <= 9; i++) { for (int j = i; j<=9; j++) { /*if (j == 6) { break; }*/ System.out.println(i+"X" + j + "="+i*j); } } } }
true
79af02c1c3d6e48cec2f1d95b5ddabb2cf592127
Java
RyanDur/LearninWithMyCoach
/MyPoint/src/test/StrongPointTest.java
UTF-8
722
2.84375
3
[]
no_license
import org.junit.Test; import java.awt.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: Thoughtworks * Date: 10/11/12 * Time: 9:46 PM * To change this template use File | Settings | File Templates. */ public class StrongPointTest { @Test public void testGetPoint() throws Exception { StrongPoint strongPoint = new StrongPoint(1,1); System.out.println(strongPoint.getPoint()); Point point1 = strongPoint.getPoint(); point1.setLocation(2,2); System.out.println(point1); System.out.println(strongPoint.getPoint()); assertFalse(point1.equals(strongPoint.getPoint())); } }
true
aed02f87589db1fc8609ca584ed94159aa5ebfe6
Java
uttsow/Design-Patterns
/Visitor Pattern/troubleShootSearch/src/troubleshootsearch/driver/Driver.java
UTF-8
2,734
2.921875
3
[]
no_license
package troubleshootsearch.driver; import troubleshootsearch.util.FileProcessor; import troubleshootsearch.util.MyLogger; import troubleshootsearch.util.Results; import troubleshootsearch.visitable.MyArrayList; import troubleshootsearch.visitable.MyTree; import troubleshootsearch.visitor.ArrayPopulatorVisitor; import troubleshootsearch.visitor.ExactMatch; import troubleshootsearch.visitor.SemanticMatch; import troubleshootsearch.visitor.StemMatch; import troubleshootsearch.visitor.VisitorI; import troubleshootsearch.visitor.TreePopulatorVisitor; public class Driver{ public static void main(String[] args) { /* * As the build.xml specifies the arguments as argX, in case the * argument value is not given java takes the default value specified in * build.xml. To avoid that, below condition is used */ if (args.length != 5 || args[0].equals("${arg0}") || args[1].equals("${arg1}") || args[2].equals("${arg2}") || args[3].equals("${arg3}") || args[4].equals("${arg4}")){ System.err.println("Error: Incorrect number of arguments. Program accepts 5 arguments."); System.exit(1); } //Set the debug level int level = Integer.parseInt(args[4]); MyLogger.setDebugValue(level); //Create file processor FileProcessor fp; //Create all the visitors VisitorI arrayListPopulator = new ArrayPopulatorVisitor(); VisitorI exactMatch = new ExactMatch(); VisitorI treePopulator = new TreePopulatorVisitor(); VisitorI stemMatch = new StemMatch(); VisitorI semanticMatch = new SemanticMatch(new FileProcessor(args[3])); //Create the Elements MyArrayList list; MyTree tree; //Start file processor and read file size //Step 1. Open technicalInfo file and populate MyArrayList and MyTree element fp = new FileProcessor(args[2]); list = new MyArrayList(fp); tree = new MyTree(fp); // Populate array and tree list.accept(arrayListPopulator); tree.accept(treePopulator); // Step 2. Open userInput file and process it line by line fp = new FileProcessor(args[0]); list.setFileProcessor(fp); tree.setFileProcessor(fp); //All element accepts the different visitors and goes throuh visit list.accept(exactMatch); tree.accept(stemMatch); list.accept(semanticMatch); //Printing result to stdout and file Results result = new Results(fp,((ExactMatch)exactMatch).getExactMatchResult(), ((StemMatch)stemMatch).getStemMatchResult(), ((SemanticMatch)semanticMatch).getSemanticMatchResult()); result.putToArray(); result.writeToFile(args[1]); } }
true
1fea1a058de62074b5ff6cab3ff2be04656d6a69
Java
helmutsiegel/profile
/service/src/test/java/org/helmut/profile/rest/service/CvServiceTest.java
UTF-8
4,171
2.046875
2
[]
no_license
package org.helmut.profile.rest.service; import org.helmut.profile.business.bc.CvBC; import org.helmut.profile.common.model.CertificationTO; import org.helmut.profile.common.model.CvTO; import org.helmut.profile.common.model.ExperienceTO; import org.helmut.profile.common.model.LanguageTO; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.Collections; import java.util.List; import static org.helmut.profile.rest.service.Constants.CURRENT_USER_EMAIL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class CvServiceTest { @Mock private CvBC cvBC; @Mock private HttpHeaders httpHeaders; @InjectMocks private CvService cvService; @Test @DisplayName("Get cv by email") public void getByEmail() { //setup String email = "email@mail.com"; CvTO cvTO = new CvTO(); //test call doReturn(cvTO).when(cvBC).getByEmail(email); //asserts assertSame(cvService.getByEmail(email), cvTO); } @Test @DisplayName("Update cv") public void updateCV() { CvTO cvTO = new CvTO(); Response response = cvService.updateCV(cvTO); verify(cvBC, times(1)).update(cvTO); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @Test @DisplayName("Update experiences") void updateExperiences() { //setup String email = "email@mail.com"; List<ExperienceTO> experiencesToUpdate = Collections.singletonList(new ExperienceTO()); List<ExperienceTO> updatedExperiences = Collections.singletonList(new ExperienceTO()); doReturn(email).when(httpHeaders).getHeaderString(CURRENT_USER_EMAIL); doReturn(updatedExperiences).when(cvBC).updateExperiences(experiencesToUpdate, email); //Test call Response response = cvService.updateExperiences(experiencesToUpdate); //asserts verify(cvBC, times(1)).updateExperiences(experiencesToUpdate, email); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); assertSame(response.getEntity(), updatedExperiences); } @Test @DisplayName("Update certifications") void updateCertifications() { //setup String email = "email@mail.com"; List<CertificationTO> certificationsToUpdate = Collections.singletonList(new CertificationTO()); List<CertificationTO> updatedCertifications = Collections.singletonList(new CertificationTO()); doReturn(email).when(httpHeaders).getHeaderString(CURRENT_USER_EMAIL); doReturn(updatedCertifications).when(cvBC).updateCertifications(certificationsToUpdate, email); //Test call Response response = cvService.updateCertifications(certificationsToUpdate); //asserts verify(cvBC, times(1)).updateCertifications(certificationsToUpdate, email); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); assertSame(response.getEntity(), updatedCertifications); } @Test void updateLanguages() { //setup String email = "email@mail.com"; List<LanguageTO> languagesToUpdate = Collections.singletonList(new LanguageTO()); List<LanguageTO> updatedLanguages = Collections.singletonList(new LanguageTO()); doReturn(email).when(httpHeaders).getHeaderString(CURRENT_USER_EMAIL); doReturn(updatedLanguages).when(cvBC).updateLanguages(languagesToUpdate, email); //Test call Response response = cvService.updateLanguages(languagesToUpdate); //asserts verify(cvBC, times(1)).updateLanguages(languagesToUpdate, email); assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); assertSame(response.getEntity(), updatedLanguages); } }
true
ff6b9f31dcdb5ae4f83996ec56dc2cec3bc3ce20
Java
galiosmax/Computer-Graphics
/Raytracing/src/main/java/ru/nsu/fit/g16203/galios/raytracing/scene/Quadrangle.java
UTF-8
1,647
3.09375
3
[]
no_license
package ru.nsu.fit.g16203.galios.raytracing.scene; import javafx.geometry.Point3D; import javafx.util.Pair; import ru.nsu.fit.g16203.galios.raytracing.matrix.Vector; public class Quadrangle extends Figure { private Point3D first; private Point3D second; private Point3D third; private Point3D fourth; private Triangle triangleFirst; private Triangle triangleSecond; public Quadrangle(Point3D first, Point3D second, Point3D third, Point3D fourth) { super(); this.type = FigureType.QUADRANGLE; this.first = first; this.second = second; this.third = third; this.fourth = fourth; triangleFirst = new Triangle(second, third, first); triangleSecond = new Triangle(first, third, fourth); calculatePoints(); } private void calculatePoints() { points.add(first); points.add(second); points.add(third); points.add(fourth); segments.add(new Pair<>(first, second)); segments.add(new Pair<>(second, third)); segments.add(new Pair<>(third, fourth)); segments.add(new Pair<>(fourth, first)); } @Override Pair<Point3D, Vector> intersect(Point3D from, Vector vector) { Pair<Point3D, Vector> intersection = triangleFirst.intersect(from, vector); if (intersection != null && intersection.getKey() != null) { return intersection; } intersection = triangleSecond.intersect(from, vector); if (intersection != null && intersection.getKey() != null) { return intersection; } return null; } }
true
845e676e60d06f3a03d90fa173f2f4c03b75bc74
Java
jpcastillo23/MysqlLiteAntlr
/src/Mitable.java
UTF-8
437
2.3125
2
[]
no_license
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import net.sf.json.*; public class Mitable implements java.io.Serializable { private String name = null; public Mitable(String nombre){ this.name = nombre; } public String toString(){ return name; } }
true
d45583a769affa57e616c530813cfcf9abaa192f
Java
jmgodino/remoting
/PdfServiceImpl/src/main/java/es/gob/catastro/service/rmi/pdf/server/translet/CatastroUriResolver.java
UTF-8
1,378
2.125
2
[]
no_license
package es.gob.catastro.service.rmi.pdf.server.translet; import java.io.IOException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOURIResolver; import org.apache.fop.apps.FopFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class CatastroUriResolver implements URIResolver { private static final Logger log = LoggerFactory .getLogger(CatastroUriResolver.class); public CatastroUriResolver() { } public Source resolve(String href, String base) throws TransformerException { log.debug("Resolviendo desde classpath: {}", href); GraphResourceManager mgr = GraphResourceManager .getGraphResourceManager(); if (mgr.isResourceRegistered(href)) { return new StreamSource(mgr.getResource(href)); } else { try { return new StreamSource(mgr.registerResource(href)); } catch (IOException e) { // En caso de no encontrarse el recurso en el classpath, sera FOP el que lo busque. return null; } } } public static void resolve(FopFactory fopFactory) { FOURIResolver fopUriResolver = (FOURIResolver) fopFactory .getURIResolver(); log.debug("Registrando resolver del Catastro"); fopUriResolver.setCustomURIResolver(new CatastroUriResolver()); } }
true
9cf9efb80ff64f4c01083942c06662285fbb153d
Java
438972218/ztb-server
/workflow-service/src/test/java/com/xdcplus/workflow/service/ProcessServiceTest.java
UTF-8
929
1.835938
2
[]
no_license
package com.xdcplus.workflow.service; import com.xdcplus.workflow.WorkflowServiceApplicationTests; import com.xdcplus.workflow.common.pojo.dto.ProcessDTO; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * 流程业务层接口测试 * * @author Rong.Jia * @date 2021/06/18 */ class ProcessServiceTest extends WorkflowServiceApplicationTests { @Autowired private ProcessService processService; @Test void saveProcess() { ProcessDTO processDTO = new ProcessDTO(); processDTO.setDescription("请假"); processDTO.setCreatedUser("admin"); processDTO.setName("请假流程"); System.out.println(processService.saveProcess(processDTO)); } @Test void updateProcess() { } @Test void deleteProcess() { } @Test void findProcess() { } @Test void findOne() { } }
true
5d18d72f69ccd835a07c8d06f7ae9f6ea1bdff7e
Java
xuewanyan/mmp
/mmp_boot/src/test/java/cn/com/yitong/ares/genericity/Message.java
UTF-8
533
2.703125
3
[]
no_license
package cn.com.yitong.ares.genericity; import org.apache.commons.collections4.ListUtils; public class Message<T> { private T info; public void run(Message<? super Integer> msg){ System.out.println(msg.getInfo()); } public T getInfo() { return info; } public void setInfo(T info) { this.info = info; } public static void main(String[] args) { Message<Integer> message = new Message<Integer>(); message.setInfo(1111); message.run(message); } }
true
6ce8b3d88b26ddd7fdf5a183a5373faabd48910c
Java
diegobravo8702/adn-scanner
/src/main/java/com/bravo/meli/adn/negocio/interfaces/Analizable.java
UTF-8
362
2.359375
2
[]
no_license
package com.bravo.meli.adn.negocio.interfaces; import java.util.regex.Pattern; import com.bravo.meli.adn.negocio.excepciones.DatosInvalidosException; public interface Analizable { public static final Pattern patronMutante = Pattern.compile("a{4}|t{4}|g{4}|c{4}", Pattern.CASE_INSENSITIVE); boolean isMutant(String[] adn) throws DatosInvalidosException; }
true
af5d2878dc8dc2f43cbb49568c107d3a3cbb66a8
Java
williamzhang11/fastCode
/src/main/java/com/xiu/fastCode/string/validpalindromeii/Solution.java
UTF-8
939
3.46875
3
[]
no_license
package com.xiu.fastCode.string.validpalindromeii; public class Solution { public boolean validPalindrome(String s) { int left = 0; int right = s.length() - 1; while (left <= right) { if(s.charAt(left) != s.charAt(right)) { return deleteJuge(s, left+1, right)|| deleteJuge(s, left, right-1); }else { left ++; right --; } } return true; } public Boolean deleteJuge(String s, int start , int end) { while(start<=end) { if(s.charAt(start)!=s.charAt(end)) { return false; } else { end--; start++; } } return true; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.validPalindrome("abc")); } }
true
7ae65242a86dcbbc64df2f2721c65cbb77a68820
Java
swapnilpatil427/AlphaFitness
/app/src/main/java/com/example/swapn/alphafitness/database/MyDbHelper.java
UTF-8
14,139
2.40625
2
[]
no_license
package com.example.swapn.alphafitness.database; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.example.swapn.alphafitness.common.Util; import com.example.swapn.alphafitness.database.Tables.UserTracking; import com.example.swapn.alphafitness.database.Tables.WorkoutTracking; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Created by swapn on 10/25/2016. */ public class MyDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "AlphaFitness"; private static final int DATABASE_VERSION = 4; private static MyDbHelper sInstance; Util u = new Util(); public static synchronized MyDbHelper getInstance(Context context) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. // See this article for more information: http://bit.ly/6LRzfx if (sInstance == null) { sInstance = new MyDbHelper(context.getApplicationContext()); } return sInstance; } public MyDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { UserTracking.onCreate(db); WorkoutTracking.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { UserTracking.onUpgrade(db, oldVersion, newVersion); WorkoutTracking.onUpgrade(db, oldVersion, newVersion); } /** * Inserts a new entry in the database, if there is no entry for the given * date yet. Steps should be the current number of steps and it's negative * value will be used as offset for the new date. Also adds 'steps' steps to * the previous day, if there is an entry for that date. * <p/> * This method does nothing if there is already an entry for 'date' - use * {@link #updateSteps} in this case. * <p/> * To restore data from a backup, use {@link #insertDayFromBackup} * * @param date the date in ms since 1970 * @param steps the current step value to be used as negative offset for the * new day; must be >= 0 */ public void insertNewDay(UserTracking user) { SQLiteDatabase db = getWritableDatabase(); try { ContentValues values = user.getContent(); long rowInserted = db.insert(UserTracking.USER_TRACKING_TABLE, null, values); if(rowInserted != -1) Log.d("Inserted", "I"); else Log.d("Inserted", "NOT"); // getAllSteps(u.getStringDate(new Date())); } catch (Exception e) { Log.e("Error", e.getMessage()); } finally { db.close(); } } public void updateWorkoutSteps(int workout_id, int count, String username) { try { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(WorkoutTracking.KEY_STEPS, count); int rows = db.update(WorkoutTracking.USER_WORKOUT_TABLE, values, WorkoutTracking.KEY_WORKOUTID + " = " + workout_id + " and " + WorkoutTracking.KEY_STEPS + "<>" + count + " and " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'" , null); db.close(); } catch (Exception e) { Log.e("Database", "Error Updating steps"); } } public void updateWorkoutEndTime(int workout_id, String username) { try { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(WorkoutTracking.KEY_WORKOUT_END, u.getStringDate(new Date())); db.update(WorkoutTracking.USER_WORKOUT_TABLE, values, WorkoutTracking.KEY_WORKOUTID + " = " + workout_id + " and " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'", null); db.close(); } catch (Exception e ) { Log.e("Database", "Error Updating End time"); } } public int insertNewWorkout(String username) { try { SQLiteDatabase db = getWritableDatabase(); int workoutid = this.getWorkoutCount() + 1; final ContentValues values = new ContentValues(); // Note that ID is NOT included here values.put(WorkoutTracking.KEY_WORKOUTID, workoutid); values.put(WorkoutTracking.KEY_WORKOUT_START, u.getStringDate(new Date())); values.put(WorkoutTracking.KEY_USERNAME, username); // values.put(WorkoutTracking.KEY_WORKOUT_END, u.getStringDate(new Date())); values.put(WorkoutTracking.KEY_STEPS, 0); long rowInserted = db.insertOrThrow(WorkoutTracking.USER_WORKOUT_TABLE, null, values); db.close(); if(rowInserted != -1) { Log.d("Inserted", "I"); return workoutid; } else { Log.d("Inserted", "NOT"); return 0; } } catch (Exception e) { Log.e("Error", "Inserting new workout" + e.getMessage()); } finally { } return 0; } public int getWorkoutCount() { try { String selectQuery = "SELECT * FROM " + WorkoutTracking.USER_WORKOUT_TABLE; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor != null) { return cursor.getCount(); } } catch (Exception e) { return 0; } return 0; } public long getTimeDifferenceforCurrentWorkout (int workout_id, String username) throws ParseException { String selectQuery = "SELECT * FROM " + WorkoutTracking.USER_WORKOUT_TABLE + " where " + WorkoutTracking.KEY_WORKOUTID + "=" + workout_id + " AND " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'"; SQLiteDatabase db = this.getReadableDatabase(); try { Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToNext()) { SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startDate = outputFormat.parse(cursor.getString((cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUT_START)))); Date endDate = outputFormat.parse(u.getStringDate(new Date())); return endDate.getTime() - startDate.getTime(); } } catch (Exception e) { Log.e("Exception", "Exception in getTimeDifferenceforCurrentWorkout" + e.getMessage()); } return 0; } public int getStepsforCurrentWorkout (int workout_id, String username ) { String selectQuery = "SELECT * FROM " + WorkoutTracking.USER_WORKOUT_TABLE + " where " + WorkoutTracking.KEY_WORKOUTID + "=" + workout_id + " AND " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'"; SQLiteDatabase db = this.getReadableDatabase(); try { Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToNext()) { return Integer.parseInt(cursor.getString(cursor.getColumnIndex(UserTracking.KEY_STEPS))); } } catch(Exception e) { Log.e("Excpetion", "Exception in getStepsforCurrentWorkout"); } return 0; } public ArrayList<WorkoutTracking> getWeekWorkouts(String username) { ArrayList<WorkoutTracking> array = new ArrayList<WorkoutTracking>(); Date d = u.firstDayOfWeek(new Date()); String daystart = u.editTime(u.getStringDate(d), "00:00:00"); String dayend = u.editTime(u.getStringDate(new Date()), "23:59:59"); String selectQuery = "SELECT * FROM " + WorkoutTracking.USER_WORKOUT_TABLE + " where " + WorkoutTracking.KEY_WORKOUT_START + ">='" + daystart + "' AND " + WorkoutTracking.KEY_WORKOUT_START + "<='" + dayend + "' AND " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); while(cursor.moveToNext()) { WorkoutTracking w = new WorkoutTracking(); w.setWorkout_id(cursor.getInt(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUTID))); w.setWorkout_start(cursor.getString(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUT_START))); w.setWorkout_end(cursor.getString(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUT_END))); w.setSteps(cursor.getInt(cursor.getColumnIndex(WorkoutTracking.KEY_STEPS))); array.add(w); } if(array.size() != 0) return array; else { return null; } } public ArrayList<UserTracking> getAllStep(int workout_id, String user) { ArrayList<UserTracking> array = new ArrayList<UserTracking>(); String selectQuery = "SELECT * FROM " + UserTracking.USER_TRACKING_TABLE + " where " + UserTracking.KEY_WORKOUTID + " = " + workout_id + " and " + UserTracking.KEY_USERID + " = '" + user + "' ORDER BY " + UserTracking.KEY_STEPS; SQLiteDatabase db = this.getReadableDatabase(); try { Cursor cursor = db.rawQuery(selectQuery, null); while (cursor.moveToNext()) { UserTracking w = new UserTracking(); w.setWorkout_id(workout_id); w.setLatitude(cursor.getDouble(cursor.getColumnIndex(UserTracking.KEY_LATITUDE))); w.setLongitude(cursor.getDouble(cursor.getColumnIndex(UserTracking.KEY_LONGITUDE))); w.setSteps(cursor.getString(cursor.getColumnIndex(UserTracking.KEY_STEPS))); w.setDate(Util.stringToDate(cursor.getString(cursor.getColumnIndex(UserTracking.KEY_DAY)))); w.setUser_id(user); array.add(w); } } catch (Exception e) { Log.e("Exception", "Exception in getAllStep" + e.getMessage()); } if(array.size() != 0) return array; else { return null; } } public ArrayList<WorkoutTracking> getAllWorkout (String username) { ArrayList<WorkoutTracking> array = new ArrayList<WorkoutTracking>(); String selectQuery = "SELECT * FROM " + WorkoutTracking.USER_WORKOUT_TABLE + " where " + WorkoutTracking.KEY_USERNAME + " = '" + username + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); while(cursor.moveToNext()) { WorkoutTracking w = new WorkoutTracking(); w.setWorkout_id(cursor.getInt(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUTID))); w.setWorkout_start(cursor.getString(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUT_START))); w.setWorkout_end(cursor.getString(cursor.getColumnIndex(WorkoutTracking.KEY_WORKOUT_END))); w.setSteps(cursor.getInt(cursor.getColumnIndex(WorkoutTracking.KEY_STEPS))); array.add(w); } if(array.size() != 0) return array; else { return null; } } public boolean insertOrUpdateDayCount(UserTracking user) { int counter = ExistsDayTracking(user.getDate()); Log.d("Count", Integer.toString(counter)); if(counter == 0) { user.setSteps(user.getSteps()); insertNewDay(user); return true; } else { updateUserDaySteps(user.getDate(), user.getSteps()); return false; } } public void updateUserDaySteps(String day, String counter) { SQLiteDatabase db = getWritableDatabase(); try { ContentValues newValues = new ContentValues(); newValues.put(UserTracking.KEY_STEPS, counter); db.update(UserTracking.USER_TRACKING_TABLE, newValues, UserTracking.KEY_DAY +"='" + day + "'" , null); } finally { db.close(); } } public Cursor getDataBetweenDates(String daystart, String dayend) { String selectQuery = "SELECT * FROM " + UserTracking.USER_TRACKING_TABLE + " where " + UserTracking.KEY_DAY + ">='" + daystart + "' AND " + UserTracking.KEY_DAY + "<='" + dayend + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); return cursor; } public void getAllSteps(String day) { String dayend = u.editTime(day, "23:59:59");// "Thursday 10 Nov 2016 00:00:00";"thursday 10 nov 2016 23:59:59"; String daystart = u.editTime(day, "00:00:00");// "Thursday 10 Nov 2016 00:00:00"; Cursor cursor = this.getDataBetweenDates(daystart, dayend); while (cursor.moveToNext()) { } } public int ExistsDayTracking(String day) { String dayend = u.editTime(day, "23:59:59:000");// "Thursday 10 Nov 2016 00:00:00";"thursday 10 nov 2016 23:59:59"; String dayStart = u.editTime(day, "00:00:00:000");// "Thursday 10 Nov 2016 00:00:00"; String selectQuery = "SELECT * FROM " + UserTracking.USER_TRACKING_TABLE + " where " + UserTracking.KEY_DAY + ">='" + dayStart + "' AND " + UserTracking.KEY_DAY + "<='" + dayend + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.getCount() > 0) { return cursor.getCount(); } return 0; } }
true
eea93a23fe76707644341c34806318c6ed116edf
Java
MisterMaurya/netflix-eureka-naming-server
/src/main/java/io/ppro/netflixeurekanamingserver/NetflixEurekaNamingServerApplication.java
UTF-8
549
1.539063
2
[]
no_license
package io.ppro.netflixeurekanamingserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /*** * @author Pawan Maurya * @since Aug 07, 2021 */ @SpringBootApplication // To Enable Eureka Server @EnableEurekaServer public class NetflixEurekaNamingServerApplication { public static void main(String[] args) { SpringApplication.run(NetflixEurekaNamingServerApplication.class, args); } }
true
7a236db7a439bde0bf35c58556a42cc6983ca2c4
Java
alvgomper1/APIUNI
/apiuni/src/main/java/com/apiuni/apiuni/servicio/AsignaturaService.java
UTF-8
1,416
2.296875
2
[]
no_license
package com.apiuni.apiuni.servicio; import java.util.Collection; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.apiuni.apiuni.modelo.Asignatura; import com.apiuni.apiuni.repositorio.AsignaturaRepository; @Service public class AsignaturaService { @Autowired private AsignaturaRepository asignaturarepository; public Asignatura findById(long id) { return this.asignaturarepository.findById(id).orElse(null); } public boolean existen(List<Asignatura> asignaturas) { Collection<Asignatura> a = (Collection<Asignatura>) asignaturarepository.findAll(); if (a.containsAll(asignaturas)) { return true; } else { return false; } } public List<Asignatura> findAllAsignaturas (){ return (List<Asignatura>) this.asignaturarepository.findAll(); } public long saveId(Asignatura d) { return this.asignaturarepository.save(d).getId(); } public boolean eliminaAsignaturaPorId(Long idAsignatura) { try{ this.asignaturarepository.deleteById(idAsignatura); return true; }catch(Exception err){ return false; } } public void saveAll(Set<Asignatura> asignaturas) { this.asignaturarepository.saveAll(asignaturas); } public Asignatura findAleatorio() { return this.asignaturarepository.findAleatorio(); } }
true
0189329645ec926522d5e064b429eb6bf27b747c
Java
warfu/JAVA-Note-LJK
/06_框架编程/SSH_基于注解的配置/SqlserverConfiguration.java
UTF-8
2,154
2.09375
2
[]
no_license
@Configuration @MapperScan(value = "com.newings.dao.sqlserver", sqlSessionFactoryRef = "scmSqlSessionFactory") @PropertySource("classpath:config.properties") public class SqlserverConfiguration { @NotNull @Value("${database.scm.username}") private String username; @NotNull @Value("${database.scm.password}") private String password; @NotNull @Value("${database.scm.url}") private String url; @NotNull @Value("${database.scm.driverClassName}") private String driverClassName; @Bean(name = "scmDataSource") // @ConfigurationProperties(prefix = "database.scm") public DataSource scmDataSource() { return DataSourceBuilder.create().driverClassName(driverClassName).username(username) .password(password).url(url).build(); } /** * sqlserver sessionFactory. * * @return sessionFactory * @throws Exception 异常 */ @Bean(name = "scmSqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(scmDataSource()); Interceptor[] plugins = {sqlserverPageHelper()}; sessionFactory.setPlugins(plugins); return sessionFactory.getObject(); } /** * sqlserver分页插件. * * @return 分页插件 */ @Bean(name = "sqlserverPageHelper") @ConfigurationProperties public PageHelper sqlserverPageHelper() { final PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("dialect", "sqlserver"); properties.setProperty("reasonable", "true"); properties.setProperty("rowBoundsWithCount", "true"); pageHelper.setProperties(properties); return pageHelper; } /** * sqlserver transactionManager. * * @return transactionManager */ @Bean(name = "scmTransactionManager") public DataSourceTransactionManager scmTransactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(scmDataSource()); return dataSourceTransactionManager; } }
true
4697920a118b60aea24afd30befbbc9eda519cd5
Java
RafaelSantosBraz/Programacao2
/NetBeansProjects/ProgramacaoII/src/refrigerantes/Main.java
UTF-8
862
2.984375
3
[]
no_license
package refrigerantes; public class Main { public static void main(String[] args) { FabricaRefrigelixInc fabrica = new FabricaRefrigelixInc(); Refrigerante refrigelix = fabrica.factoryMethod(); refrigelix.setNome("Refrigerante Refrigelix"); refrigelix.setConteudo(2000); refrigelix.setSabor("Tamarindo"); refrigelix.setComposicao("Tamarindo, água, açucar e gás Carbônico"); refrigelix.setInformacaoNutricional("Kcal: 800"); System.out.println("Nome: " + refrigelix.getNome() + "\nConteúdo: " + refrigelix.getConteudo() + "ml" + "\nSabor: " + refrigelix.getSabor() + "\nComposição: " + refrigelix.getComposicao() + "\nInformação Nutricional: " + refrigelix.getInformacaoNutricional()); } }
true
3eb080bd936e0358189fce15618695ada22231a6
Java
dakshay27/WeHearOX
/src/main/java/com/wehear/ox/ResultCompletionHandler.java
UTF-8
176
1.53125
2
[]
no_license
package com.wehear.ox; import org.json.JSONObject; public interface ResultCompletionHandler { void onResult(boolean success, JSONObject response, Exception exception); }
true
ab8fd9d8fb4e9c3a9d48a04c2ed6d3fa19b3abb6
Java
knoppixmeister/ASyncTaskLoaderWithSupportLibrary
/src/com/blundell/asynctaskloader/ui/loader/AppListLoader.java
UTF-8
4,782
2.359375
2
[]
no_license
package com.blundell.asynctaskloader.ui.loader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.blundell.asynctaskloader.domain.AppEntry; import com.blundell.asynctaskloader.receiver.PackageIntentReceiver; import com.blundell.asynctaskloader.util.Comparator; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.support.v4.content.AsyncTaskLoader; public class AppListLoader extends AsyncTaskLoader<List<AppEntry>> { InterestingConfigChanges lastConfig = new InterestingConfigChanges(); public final PackageManager pm; List<AppEntry> apps; PackageIntentReceiver packageObserver; public AppListLoader(Context context) { super(context); // Retrieve the package manager for later use; note we don't // use 'context' directly but instead the safe global application // context returned by getContext(). pm = getContext().getPackageManager(); } @Override protected void onStartLoading() { super.onStartLoading(); // AsyncTaskLoader doesnt start unless you forceLoad http://code.google.com/p/android/issues/detail?id=14944 if(apps != null){ deliverResult(apps); } if(takeContentChanged() || apps == null){ forceLoad(); } } /** * This is where the bulk of the work. This function is called in a background thread * and should generate a new set of data to be published by the loader. */ @Override public List<AppEntry> loadInBackground() { // Retrieve all known applications List<ApplicationInfo> apps = pm.getInstalledApplications( PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS); if(apps == null){ apps = new ArrayList<ApplicationInfo>(); } final Context context = getContext(); // Create corresponding array of entries and load their labels List<AppEntry> entries = new ArrayList<AppEntry>(apps.size()); for (ApplicationInfo applicationInfo : apps) { AppEntry entry = new AppEntry(this, applicationInfo); entry.loadLabel(context); entries.add(entry); } Collections.sort(entries, Comparator.ALPHA_COMPARATOR); return entries; } /** * Called when there is new data to deliver to the client. The super class * will take care of delivering it; the implementation just adds a little more logic */ @Override public void deliverResult(List<AppEntry> apps) { if(isReset()){ // An async query came in while the loader is stopped. We don't need the result if(apps != null){ onReleaseResources(apps); } } List<AppEntry> oldApps = this.apps; this.apps = apps; if(isStarted()){ // If the loader is currently started, we can immediately deliver a result super.deliverResult(apps); } // At this point we can release the resources associated with 'oldApps' if needed; // now that the new result is delivered we know that it is no longer in use if(oldApps != null){ onReleaseResources(oldApps); } } @Override protected void onStopLoading() { // Attempts to cancel the current load task if possible cancelLoad(); } @Override public void onCanceled(List<AppEntry> apps) { super.onCanceled(apps); // At this point we can release the resources associated with 'apps' if needed onReleaseResources(apps); } /** * Handles request to completely reset the loader */ @Override protected void onReset() { super.onReset(); // ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'apps' if needed if(apps != null){ onReleaseResources(apps); apps = null; } // Stop monitoring for changes if(packageObserver != null){ getContext().unregisterReceiver(packageObserver); packageObserver = null; } } /** * Helper function to take care of releasing resources associated with an actively loaded data set */ private void onReleaseResources(List<AppEntry> apps){ // For a simple list there is nothing to do // but for a Cursor we would close it here } public static class InterestingConfigChanges { final Configuration lastConfiguration = new Configuration(); int lastDensity; protected boolean applyNewConfig(Resources res){ int configChanges = lastConfiguration.updateFrom(res.getConfiguration()); boolean densityChanged = lastDensity != res.getDisplayMetrics().densityDpi; if(densityChanged || (configChanges & (ActivityInfo.CONFIG_LOCALE|ActivityInfo.CONFIG_UI_MODE|ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0){ lastDensity = res.getDisplayMetrics().densityDpi; return true; } return false; } } }
true
cbdb7f78d5fe4e15f2e4667f0336d3800869b306
Java
Jennifer-Yu/HW40
/SuperArray.java
UTF-8
5,031
3.96875
4
[]
no_license
//Team Praise be Arrays -- Jennifer Yu, Jackson Deysine //APCS1 pd9 //HW40 -- Array of Grade 316 //2015-12-02 /***************************** * SKELETON for * class SuperArray -- A wrapper class for an array. * Maintains functionality: * access value at index * overwrite value at index * Adds functionality to std Java array: * resizability * ability to print meaningfully *****************************/ public class SuperArray { //~~~~~INSTANCE VARS~~~~~ //underlying container, or "core" of this data structure: private int[] _data; //position of last meaningful value private int _lastPos; //size of this instance of SuperArray private int _size; //~~~~~METHODS~~~~~ //default constructor – initializes 10-item array public SuperArray() { //_data = new int[10]; //all zeros _data = new int[] {1,0,2,0,4,0,6,0,8,0}; //easy test case _lastPos = -1; _size = 0; } //output array in [a,b,c] format, eg // {1,2,3}.toString() -> "[1,2,3]" public String toString() { String retStr = "["; //beginning of string for (int x = 0; x < _data.length; x++) { retStr += _data[x]; //adds each element to string if (x != _data.length - 1) { retStr += ","; //stops the last comma } } retStr += "]"; //end of string return retStr; //return string } //double capacity of this SuperArray private void expand() { int[] newData = new int[_data.length * 2]; //initializes a new array with double capacity for (int x = 0; x < _data.length; x++) { newData[x] = _data[x]; //inserts everything into the new array } _data = newData; //replaces the original array with the new array } //accessor -- return value at specified index public int get( int index ) { return _data[index]; //returns value at specifed index } //mutator -- set value at index to newVal, // return old value at index public int set( int index, int newVal ) { int oldVal = _data[index]; //stores the old value to be returned _data[index] = newVal; //puts new value into the index of the new array return oldVal; //returns old value } public int remove( int index ) { int[] newData = new int[_data.length-1]; //initializes a new array int oldVal = _data[index]; //stores the old value to be returned for (int x = 0; x < index; x++) { newData[x] = _data[x]; //inserts everything up to the index into the new array } for (int x = index + 1; x < _data.length; x++) { newData[x-1] = _data[x]; //finishes filling in } _data = newData; //replaces the original array with the new array return oldVal; //returns what you removed } public void add(int value) { //adds value at the end int[] newData = new int[_data.length+1]; //initializes a new larger array for (int x = 0; x < _data.length-1; x++) { newData[x] = _data[x]; //inserts everything in the new array } newData[_data.length] = value; //adds the value _data = newData; //replaces the original array with the new array } public void add(int index, int value) { //adds value at an index int[] newData = new int[_data.length+1]; //initializes a new larger array for (int x = 0; x < index; x++) { newData[x] = _data[x]; //inserts everything up to the index into the new array } newData[index] = value; //adds the value at specified index for (int x = index; x < _data.length; x++) { newData[x+1] = _data[x]; //finishes filling in } _data = newData; //replaces the original array with the new array }//end add(third one) public int leftJustify() { int[] newData = new int[_data.length]; //initializes a new array int y = 0; //to skip 0s by setting a separate counter for the new array for (int x = 0; x < _data.length; x++) { if (_data[x] != 0) { //if its not zero, significant newData[y] = _data[x]; y += 1; } } _data = newData; //replaces the original array with the new array return y; //how many spaces } //main method for testing public static void main( String[] args ) { //*****INSERT ADEQUATE TEST CALLS HERE***** SuperArray myArray = new SuperArray(); myArray.set(6,333); myArray.add(100); myArray.add(2,10000); //myArray.expand(); //System.out.println(myArray.get(6)); //myArray.remove(6); //myArray.leftJustify(); System.out.println(myArray); }//end main }//end class
true
5258f0a9d73042baeef996f7e1362b5b0d100fe1
Java
sanlaba08/BigCoachNBA
/src/main/java/com/utn/BigCoachNBA/projections/SquadStatsProjection.java
UTF-8
298
1.78125
2
[]
no_license
package com.utn.BigCoachNBA.projections; public interface SquadStatsProjection { String getPlayer_name(); String getPlayer_surname(); String getPosition(); Integer getPoints(); Integer getBounces(); Integer getAssists(); Integer getMinutes(); Integer getFouls(); }
true
3fabd730d0c1c3e0f2a0a66b9f48f30f814d04da
Java
h-rshada/YDAcademy
/app/src/main/java/com/ydacademy/dell/Yashodeep2/AchieversDescription.java
UTF-8
3,049
1.882813
2
[]
no_license
package com.ydacademy.dell.Yashodeep2; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; public class AchieversDescription extends AppCompatActivity { /*@InjectView(R.id.profile_image) ImageView imageProfile;*/ /* @InjectView(R.id.txtId) TextView txtId;*/ @InjectView(R.id.txtName) TextView txtName; @InjectView(R.id.txtClass) TextView txtClass; @InjectView(R.id.txtDesc1) TextView txtDescription; @InjectView(R.id.txtDesc2) TextView txtDescription1; TextView textView; @InjectView(R.id.img_back) ImageView imageback; /*@InjectView(R.id.btn_director) AppCompatButton btn_director;*/ Toolbar toolbar; /* @InjectView(R.id.progress) ProgressBar progressBar;*/ String id, name, desc, url, class1; String[] a; String desc1 = "1", desc2 = "2"; // DataStudent arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_achievers_description); ButterKnife.inject(this); // id = getIntent().getStringExtra("Id"); toolbar = (Toolbar) findViewById(R.id.toolbar1); setSupportActionBar(toolbar); name = getIntent().getStringExtra("Name"); class1 = getIntent().getStringExtra("Class"); desc = getIntent().getStringExtra("Desc"); a = desc.split("\\$"); desc1 = a[0]; desc2 = a[1]; url = getIntent().getStringExtra("Url"); txtName.setText(name); // txtId.setText(id); txtClass.setText(class1); txtDescription.setText(desc1); txtDescription1.setText(desc2); /*Glide.with(AchieversDescription.this).load(url).asBitmap().override(600, 600) .placeholder(null).listener(new RequestListener<String, Bitmap>() { @Override public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) { progressBar.setVisibility(View.VISIBLE); return false; } @Override public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) { progressBar.setVisibility(View.GONE); return false; } }).error(null) .into(imageProfile); } */ } @OnClick({R.id.img_back}) /* , R.id.fab*/ public void onClick(View view) { switch (view.getId()) { case R.id.img_back: Intent intent = new Intent(AchieversDescription.this, OurAchievers.class); startActivity(intent); break; } } }
true
a2c8f7ca9c6296666bb311abdd4469a3868c3877
Java
ZeynepSulukcu/ProjectDecember
/src/test/java/utilities/ElementsClass.java
UTF-8
1,309
2.796875
3
[]
no_license
package utilities; import org.openqa.selenium.*; import java.util.ArrayList; import java.util.List; import static utilities.ElementClass.$; public class ElementsClass { public static ElementsClass $$(By by){ return new ElementsClass(by); } private WebDriver driver; private List<WebElement> elements; private By by; private ElementsClass(){ this.driver = Driver.getDriver(); } private ElementsClass(By by){ this(); this.by = by; elements = driver.findElements(by); } public List<WebElement> getElements(){ return elements; } public int size(){ return elements.size(); } public ElementsClass filterByText(String text){ List<WebElement> e = new ArrayList<>(); for (WebElement element : elements) { if (element.getText().toLowerCase().contains(text.toLowerCase())) e.add(element); } elements = e; return this; } public ElementsClass filterWithText(String text){ List<WebElement> e = new ArrayList<>(); for (WebElement element : elements) { if (element.getText().toLowerCase().equalsIgnoreCase(text)) e.add(element); } elements = e; return this; } }
true
a0eb90961b3f1220588d722e81b2b8c5810a3dc8
Java
yangziwen/patchmaker-java8
/src/main/java/net/yangziwen/patchmaker/patch/registry/mvn/MvnHbmXmlRegistry.java
UTF-8
1,013
2.3125
2
[]
no_license
package net.yangziwen.patchmaker.patch.registry.mvn; import java.io.File; import java.util.Map; import net.yangziwen.patchmaker.patch.registry.AbstractRegistry; public class MvnHbmXmlRegistry extends AbstractRegistry { private static final String PACKAGE_PREFIX = "/src/main/java/"; public MvnHbmXmlRegistry(){ super(HBM_XML_FILTER); } @Override protected boolean fillFileMapping(String srcPath, String patchRootPath, Map<File, File> fileMapping) { int prefixPos = srcPath.indexOf(PACKAGE_PREFIX); if(prefixPos == -1) { return false; } int packageStartPos = prefixPos + PACKAGE_PREFIX.length(); int packageEndPos = srcPath.lastIndexOf("/") + 1; String packagePath = srcPath.substring(packageStartPos, packageEndPos); String hbmXmlFileName = srcPath.substring(packageEndPos); String pkg = packagePath.replace("/", "."); String patchFilePath = patchRootPath + pkg + "/" + hbmXmlFileName; fileMapping.put(new File(srcPath), new File(patchFilePath)); return true; } }
true
8b730c514630e1e1d83f02789687dc9952a754c3
Java
daiyunhang/Java
/myjava/dd_07_03_猜游戏/src/dd_07_03_猜游戏/GuessLetterGame.java
GB18030
1,058
3.4375
3
[]
no_license
package dd_07_03_Ϸ; import java.util.Random; public class GuessLetterGame extends GuessGame{ public String suiji() { StringBuilder sb = new StringBuilder("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); for(int i=0; i<5; i++) { int j = new Random().nextInt(26); char t = sb.charAt(i); sb.setCharAt(i, sb.charAt(j)); sb.setCharAt(j, t); } String s = sb.substring(0,5); System.out.println(s); return s; } public void tiShi() { System.out.println("Ѿ5ظĴдĸ"); System.out.println("²5ĸ"); } public String biJiao(String c, String r) { int a = 0; int b = 0; for(int i=0; i<c.length(); i++) { for(int j=0; j<r.length(); j++) { //iλַjλַ if(c.charAt(i) == r.charAt(j)) { if(i==j) {//λ a++; }else { b++;//λò } //jλҵַͬ break; } } } return a+"A"+b+"B"; } public boolean caiDui(String result) { return "5A0B".equals(result); } }
true
06081540c8d492d577c03fd9ad6d8cfaee946887
Java
stevensimmons/restalm
/src/main/java/com/fissionworks/restalm/model/entity/AlmEntity.java
UTF-8
1,304
2.28125
2
[ "Apache-2.0" ]
permissive
package com.fissionworks.restalm.model.entity; import com.fissionworks.restalm.model.entity.base.GenericEntity; /** * Interface that describes methods common to/need for all ALM resource entity * objects. * * @since 1.0.0 * */ public interface AlmEntity { /** * Creates an {@link GenericEntity} object based on the currently populated * fields of this resource entity. * * @return An {@link GenericEntity} containing all currently populated * fields. * @since 1.0.0 */ GenericEntity createEntity(); /** * Returns the collection type string related to this entity used in ALM * rest URL's. * * @return the collection type string. * @since 1.0.0 */ String getEntityCollectionType(); /** * Returns the type string related to this entity used in ALM rest URL's. * * @return the type string. * @since 1.0.0 */ String getEntityType(); /** * get the id of this entity. * * @return The entity id. * @since 1.0.0 */ int getId(); /** * Populates the entity based on the fields/values contained in the provided * {@link GenericEntity}. * * @param entity * The {@link GenericEntity} to use to populate the resource * entity fields. * @since 1.0.0 */ void populateFields(final GenericEntity entity); }
true
ad96578dce32e3049f52b6b56d82df263f9a2a47
Java
artkostm/rxjdi
/src/test/java/test/main/HttpServer.java
UTF-8
378
2.09375
2
[]
no_license
package test.main; import by.artkostm.rxj.annotation.Inject; import by.artkostm.rxj.annotation.Singleton; import test.main.inner.HttpServerInitializer; @Singleton public class HttpServer { @Inject private HttpServerInitializer initializer; public void get() { System.out.println("TEST:"+initializer.getClass().getName()); } }
true
5c103a5981c92a1264036275aaa30459ef4fac1d
Java
goungoun/daon
/daon-core/src/main/java/daon/core/util/Utils.java
UTF-8
17,320
2.765625
3
[]
no_license
package daon.core.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import daon.core.config.POSTag; import daon.core.data.Eojeol; import daon.core.data.Morpheme; public class Utils { /** * http://jrgraphix.net/r/Unicode/AC00-D7AF */ //한글 시작 문자 public final static int KOR_START = 0xAC00; //한글 종료 문자 public final static int KOR_END = 0xD7A3; /** * http://jrgraphix.net/r/Unicode/3130-318F */ public final static int JAMO_START = 0x3130; public final static int JAMO_END = 0x318F; public final static int HANJA_START = 0x4E00; public final static int HANJA_END = 0x9FFF; public final static int INDEX_NOT_FOUND = -1; /** * 맨앞부터는 0,1,2 * 맨뒤부터는 -1,-2,-3 * * @param word word * @param idx decomposed index * @return decompose value */ public static char[] getCharAtDecompose(String word, int idx) { if (word == null) return new char[]{}; int len = word.length(); //마지막 문자 가져오기 if (idx <= -1) { idx = len + idx; if (idx < 0) { return new char[]{}; } } if (idx >= len) { return new char[]{}; } char c = word.charAt(idx); char[] lastchar = decompose(c); return lastchar; } public static char[] getFirstChar(String word) { return getCharAtDecompose(word, 0); } public static char[] getLastChar(String word) { return getCharAtDecompose(word, -1); } public static int indexOf(final char[] array, final char valueToFind) { if (array == null) { return INDEX_NOT_FOUND; } for (int i = 0; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** * @param c decomposed value * @param array match value's * @param findIdx 찾을 idx. 0 : 초성, 1 : 중성, 2 : 종성 * @return isMatch */ public static boolean isMatch(char[] c, char[] array, int findIdx) { boolean isMatched = false; int chk = findIdx < 1 ? 1 : findIdx; int len = c.length; if (len == 0) { return isMatched; } // 분리 내용이 있는 경우 있을 경우 if (len > chk) { int idx = indexOf(array, c[findIdx]); if (idx > -1) { isMatched = true; } } return isMatched; } public static boolean isMatch(char[] c, char[] choseong, char[] jungseong, char[] jongseong) { boolean isMatched = false; if (isMatch(c, choseong, 0) && isMatch(c, jungseong, 1) && isMatch(c, jongseong, 2)) { isMatched = true; } return isMatched; } public static boolean isMatch(char[] c, char[] choseong, char[] jungseong) { boolean isMatched = false; if (isMatch(c, choseong, 0) && isMatch(c, jungseong, 1)) { isMatched = true; } return isMatched; } public static boolean isMatch(char[] c, char choseong) { boolean isMatched = false; if (c[0] == choseong) { isMatched = true; } return isMatched; } public static boolean isMatch(char[] c, char choseong, char jungseong) { boolean isMatched = false; if ((c[0] == choseong) && (c[1] == jungseong)) { isMatched = true; } return isMatched; } public static boolean startsWith(String word, char[] choseong, char[] jungseong, char[] jongseong) { char[] c = getFirstChar(word); return isMatch(c, choseong, jungseong, jongseong); } public static boolean startsWith(String word, char[] choseong, char[] jungseong) { char[] c = getFirstChar(word); return isMatch(c, choseong, jungseong); } public static boolean startsWith(String word, String[] prefixes) { if (word == null) return false; for (final String searchString : prefixes) { if (word.startsWith(searchString)) { return true; } } return false; } public static boolean startsWith(String word, String prefix) { return startsWith(word, new String[]{prefix}); } public static boolean startsWithChoseong(String word, char[] choseong) { char[] c = getFirstChar(word); return isMatch(c, choseong, 0); } public static boolean startsWithChoseong(String word, char choseong) { return startsWithChoseong(word, new char[]{choseong}); } public static boolean startsWithChoseong(String word) { return startsWithChoseong(word, CHOSEONG); } public static boolean startsWithJongseong(String word, char[] jongseong) { boolean isMatched = false; char[] c = getFirstChar(word); //종성만 있는 경우 if (c.length == 1) { int idx = indexOf(jongseong, c[0]); if (idx > -1) { isMatched = true; } } return isMatched; } public static boolean startsWithJongseong(String word, char jongseong) { return startsWithJongseong(word, new char[]{jongseong}); } public static boolean startsWithJongseong(String word) { return startsWithJongseong(word, JONGSEONG); } public static boolean endWith(String word, String[] suffixes) { if (word == null) return false; for (final String searchString : suffixes) { if (word.startsWith(searchString)) { return true; } } return false; } public static boolean endWith(String word, String suffix) { return endWith(word, new String[]{suffix}); } public static boolean endWith(String word, char[] choseong, char[] jungseong, char[] jongseong) { char[] c = getLastChar(word); return isMatch(c, choseong, jungseong, jongseong); } public static boolean endWith(String word, char[] choseong, char[] jungseong) { char[] c = getLastChar(word); return isMatch(c, choseong, jungseong); } public static boolean endWithChoseong(String word, char[] choseong) { char[] c = getLastChar(word); return isMatch(c, choseong, 0); } public static boolean endWithChoseong(String word, char choseong) { return endWithChoseong(word, new char[]{choseong}); } public static boolean endWithJungseong(String word, char[] jungseong) { char[] c = getLastChar(word); return isMatch(c, jungseong, 1); } public static boolean endWithJungseong(String word, char jungseong) { return endWithJungseong(word, new char[]{jungseong}); } public static boolean endWithJongseong(String word, char[] jongseong) { char[] c = getLastChar(word); return isMatch(c, jongseong, 2); } public static boolean endWithJongseong(String word, char jongseong) { return endWithJongseong(word, new char[]{jongseong}); } public static boolean endWithNoJongseong(String word) { char[] lc = getLastChar(word); return isMatch(lc, NO_JONGSEONG, 2); } public static boolean isLength(String word, int len) { boolean is = false; if (word == null) return is; if (word.length() == len) { is = true; } return is; } public static final char EMPTY_JONGSEONG = '\0'; public static final char[] CHOSEONG = {'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'}; public static final char[] JUNGSEONG = {'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'}; public static final char[] JONGSEONG = {EMPTY_JONGSEONG, 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'}; public static final char[] NO_JONGSEONG = {EMPTY_JONGSEONG}; private static final Map<Character, Integer> CHOSEONG_MAP; private static final Map<Character, Integer> JUNGSEONG_MAP; private static final Map<Character, Integer> JONGSEONG_MAP; static { CHOSEONG_MAP = new HashMap<Character, Integer>(); for (int i = 0, len = CHOSEONG.length; i < len; i++) { char c = CHOSEONG[i]; CHOSEONG_MAP.put(c, i); } JUNGSEONG_MAP = new HashMap<Character, Integer>(); for (int i = 0, len = JUNGSEONG.length; i < len; i++) { char c = JUNGSEONG[i]; JUNGSEONG_MAP.put(c, i); } JONGSEONG_MAP = new HashMap<Character, Integer>(); for (int i = 0, len = JONGSEONG.length; i < len; i++) { char c = JONGSEONG[i]; JONGSEONG_MAP.put(c, i); } } private static final int JUNG_JONG = JUNGSEONG.length * JONGSEONG.length; /** * 한글 한글자를 초성/중성/종성의 배열로 만들어 반환한다. * * @param c 분리 할 한글 문자 * @return 초/중/종성 분리 된 char 배열 */ public static char[] decompose(char c) { char[] result = null; //한글이 아닌 경우 [0]에 그대로 리턴. 자음/모음만 있는 경우도 그대로 리턴 if (c < KOR_START || c > KOR_END) return new char[]{c}; c -= KOR_START; char choseong = CHOSEONG[c / JUNG_JONG]; c = (char) (c % JUNG_JONG); char jungseong = JUNGSEONG[c / JONGSEONG.length]; char jongseong = JONGSEONG[c % JONGSEONG.length]; if (jongseong != 0) { result = new char[]{choseong, jungseong, jongseong}; } else { result = new char[]{choseong, jungseong, EMPTY_JONGSEONG}; } return result; } public static char compound(char choseong, char jungseong) { return compound(choseong, jungseong, EMPTY_JONGSEONG); } public static char compound(char choseong, char jungseong, char jongseong) { int first = CHOSEONG_MAP.get(choseong); int middle = JUNGSEONG_MAP.get(jungseong); int last = JONGSEONG_MAP.get(jongseong); char c = (char) (KOR_START + (first * JUNG_JONG) + (middle * JONGSEONG.length) + last); return c; } public static long hashCode(String string){ long h = 98764321261L; int l = string.length(); char[] chars = string.toCharArray(); for (int i = 0; i < l; i++) { h = 31 * h + chars[i]; } return h; } public static boolean containsTag(long sourceBit, long targetBit){ boolean is = false; // 사전의 tag 정보와 포함여부 tag 의 교집합 구함. long result = sourceBit & targetBit; if(result > 0){ is = true; } return is; } public static boolean containsTag(long sourceBit, POSTag targetTag){ long targetBit = targetTag.getBit(); return containsTag(sourceBit, targetBit); } public static boolean containsTag(POSTag sourceTag, POSTag targetTag){ long sourceBit = sourceTag.getBit(); return containsTag(sourceBit, targetTag); } public static int getSeq(POSTag tag){ int seq = 0; if(tag == POSTag.SN){ seq = 1; }else if(tag == POSTag.SL || tag == POSTag.SH){ seq = 2; } return seq; } public static int getSeq(String tag){ return getSeq(POSTag.valueOf(tag)); } public static int getIdx(String tag){ return POSTag.valueOf(tag).getIdx(); } public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Performs the logic for the {@code split} and * {@code splitPreserveAllTokens} methods that do not return a * maximum array length. * * @param str the String to parse, may be {@code null} * @param separatorChar the separate character * @return an array of parsed Strings, {@code null} if null String input */ private static String[] split(final String str, final char separatorChar) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } final int len = str.length(); if (len == 0) { return EMPTY_STRING_ARRAY; } final List<String> list = new ArrayList<String>(); int i = 0, start = 0; boolean match = false; boolean lastMatch = false; while (i < len) { if (str.charAt(i) == separatorChar) { if (match) { list.add(str.substring(start, i)); match = false; lastMatch = true; } start = ++i; continue; } lastMatch = false; match = true; i++; } if (match && lastMatch) { list.add(str.substring(start, i)); } return list.toArray(new String[list.size()]); } /** * 어절 구분 : 줄바꿈 문자 * 어절-형태소 간 구분 : ' - ' * 형태소 간 구분 : 공백(스페이스) 문자 * 형태소 내 단어-태그 구분 : '/' * @param eojeols 파싱할 어절 문자열 * @return 분석 결과 * @throws Exception 파싱 실패 에러 */ public static List<Eojeol> parse(String eojeols) throws Exception{ if(eojeols == null || eojeols.isEmpty()){ throw new Exception("값이 없습니다."); } List<Eojeol> results = new ArrayList<>(); String[] lines = eojeols.split("\\n"); if(lines.length == 0){ throw new Exception("어절 구분 분석 결과가 없습니다. (어절 구분자 줄바꿈 문자)"); } for(int i=0, len = lines.length; i< len; i++){ String line = lines[i]; String[] surfaceAndMorphs = line.split("\\s+[-]\\s+"); if(surfaceAndMorphs.length == 0){ throw new Exception("어절-형태소 간 구분 값(' - ')이 없습니다."); } if(surfaceAndMorphs.length > 2){ throw new Exception("어절-형태소 간 구분 값(' - ')은 한개만 있어야 됩니다."); } String surface = surfaceAndMorphs[0]; String morph = surfaceAndMorphs[1]; Eojeol eojeol = new Eojeol(); eojeol.setSeq(i); eojeol.setSurface(surface); List<Morpheme> morphemes = parseMorpheme(morph); eojeol.setMorphemes(morphemes); results.add(eojeol); } return results; } public static List<Morpheme> parseMorpheme(String m) throws Exception { if(m == null || m.isEmpty()){ throw new Exception("값이 없습니다."); } List<Morpheme> results = new ArrayList<>(); String[] morphes = m.split("\\s+"); if(morphes.length == 0){ throw new Exception("형태소 간 구분자 ' '가 없습니다."); } for(int i=0, len = morphes.length; i < len; i++){ String morph = morphes[i]; //형태소 내 단어-태그 구분자 '/' 분리 String[] wordInfo = morph.split("[/](?=[A-Z]{2,3}$)"); if(wordInfo.length != 2){ throw new Exception("형태소 내 단어-태그 구분자('/')가 잘못 되었습니다."); } String word = wordInfo[0]; String tag = wordInfo[1]; try { tag = POSTag.valueOf(tag).getName(); }catch (Exception e){ throw new Exception(tag + " <= 태그값이 잘못되었습니다."); } Morpheme morpheme = new Morpheme(i, word, tag); results.add(morpheme); } if(results.size() == 0){ throw new Exception("형태소 구분 분석 결과가 없습니다. (형태소 구분자 공백 문자)"); } return results; } public static long makeTagBit(List<String> tags){ long bit = -1; if(tags != null && !tags.isEmpty()) { bit = 0; for (String tagName : tags) { POSTag tag = POSTag.valueOf(tagName); bit |= tag.getBit(); } } return bit; } public static long makeTagBit(String[] tags) { long bit = -1; if (tags != null && tags.length > 0) { bit = 0; for (String tagName : tags) { POSTag tag = POSTag.valueOf(tagName); bit |= tag.getBit(); } } return bit; } }
true
3b5b708104da05601d702afcb7099f9e57f3bde3
Java
ifpr-pgua-oo-tads-2018/aula5-1-gustaacamargo
/src/pizzapp/model/PizzaAtributoBusca.java
UTF-8
69
1.5
2
[]
no_license
package pizzapp.model; public enum PizzaAtributoBusca { SABOR }
true
f829790f14056e0c711d221bcd3ac1e240cf8612
Java
StanislavGS/Swift
/7_OOPPrinciples/Task2_UniversityManagement/src/Student.java
UTF-8
777
2.359375
2
[]
no_license
import java.util.Arrays; /* * 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. */ /** * * @author Stanislav Stanislavov */ public class Student extends Person { private String _facultyNumber; String getFacultyNumber() { return this._facultyNumber; } void setFacultyNumber(String _facultyNumber) { this._facultyNumber = _facultyNumber; } Student(String name,String phone,String facultyNumber,Disciplines disciplinesGlobal,String ...disciplines) { super(name,phone,disciplinesGlobal,disciplines); this._facultyNumber = facultyNumber; } }
true
49de8589bad1d124cf916a12e0d9f23fb0524923
Java
BestSolution-at/java2typescript
/tooling/at.bestsolution.typescript.service.spec/src-gen/at/bestsolution/typescript/service/spec/parser/antlr/internal/InternalTSSpecParser.java
UTF-8
110,548
1.59375
2
[]
no_license
package at.bestsolution.typescript.service.spec.parser.antlr.internal; import org.eclipse.xtext.*; import org.eclipse.xtext.parser.*; import org.eclipse.xtext.parser.impl.*; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.parser.antlr.AbstractInternalAntlrParser; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import org.eclipse.xtext.parser.antlr.XtextTokenStream.HiddenTokens; import org.eclipse.xtext.parser.antlr.AntlrDatatypeRuleToken; import at.bestsolution.typescript.service.spec.services.TSSpecGrammarAccess; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; @SuppressWarnings("all") public class InternalTSSpecParser extends AbstractInternalAntlrParser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "RULE_DOC", "RULE_ID", "RULE_STRING", "RULE_INT", "RULE_ML_COMMENT", "RULE_SL_COMMENT", "RULE_WS", "RULE_ANY_OTHER", "'package'", "'javatype'", "'cust'", "'extends'", "'{'", "'}'", "'enum'", "'('", "')'", "'alias'", "'as'", "'='", "'optional'", "'<'", "','", "'>'", "'[]'", "'command'", "'returns'", "'void'", "'event'", "'.'" }; public static final int RULE_STRING=6; public static final int RULE_SL_COMMENT=9; public static final int T__19=19; public static final int T__15=15; public static final int T__16=16; public static final int T__17=17; public static final int T__18=18; public static final int T__33=33; public static final int T__12=12; public static final int T__13=13; public static final int T__14=14; public static final int EOF=-1; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int RULE_ID=5; public static final int RULE_WS=10; public static final int RULE_ANY_OTHER=11; public static final int RULE_DOC=4; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int RULE_INT=7; public static final int T__29=29; public static final int T__22=22; public static final int RULE_ML_COMMENT=8; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__20=20; public static final int T__21=21; // delegates // delegators public InternalTSSpecParser(TokenStream input) { this(input, new RecognizerSharedState()); } public InternalTSSpecParser(TokenStream input, RecognizerSharedState state) { super(input, state); } public String[] getTokenNames() { return InternalTSSpecParser.tokenNames; } public String getGrammarFileName() { return "InternalTSSpec.g"; } private TSSpecGrammarAccess grammarAccess; public InternalTSSpecParser(TokenStream input, TSSpecGrammarAccess grammarAccess) { this(input); this.grammarAccess = grammarAccess; registerRules(grammarAccess.getGrammar()); } @Override protected String getFirstRuleName() { return "ServiceDefs"; } @Override protected TSSpecGrammarAccess getGrammarAccess() { return grammarAccess; } // $ANTLR start "entryRuleServiceDefs" // InternalTSSpec.g:67:1: entryRuleServiceDefs returns [EObject current=null] : iv_ruleServiceDefs= ruleServiceDefs EOF ; public final EObject entryRuleServiceDefs() throws RecognitionException { EObject current = null; EObject iv_ruleServiceDefs = null; try { // InternalTSSpec.g:68:2: (iv_ruleServiceDefs= ruleServiceDefs EOF ) // InternalTSSpec.g:69:2: iv_ruleServiceDefs= ruleServiceDefs EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefsRule()); } pushFollow(FOLLOW_1); iv_ruleServiceDefs=ruleServiceDefs(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleServiceDefs; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleServiceDefs" // $ANTLR start "ruleServiceDefs" // InternalTSSpec.g:76:1: ruleServiceDefs returns [EObject current=null] : (otherlv_0= 'package' ( (lv_packageName_1_0= ruleQualifiedName ) ) ( (lv_domainElements_2_0= ruleDomainElement ) )* ( (lv_serviceDefs_3_0= ruleServiceDef ) )* ) ; public final EObject ruleServiceDefs() throws RecognitionException { EObject current = null; Token otherlv_0=null; AntlrDatatypeRuleToken lv_packageName_1_0 = null; EObject lv_domainElements_2_0 = null; EObject lv_serviceDefs_3_0 = null; enterRule(); try { // InternalTSSpec.g:79:28: ( (otherlv_0= 'package' ( (lv_packageName_1_0= ruleQualifiedName ) ) ( (lv_domainElements_2_0= ruleDomainElement ) )* ( (lv_serviceDefs_3_0= ruleServiceDef ) )* ) ) // InternalTSSpec.g:80:1: (otherlv_0= 'package' ( (lv_packageName_1_0= ruleQualifiedName ) ) ( (lv_domainElements_2_0= ruleDomainElement ) )* ( (lv_serviceDefs_3_0= ruleServiceDef ) )* ) { // InternalTSSpec.g:80:1: (otherlv_0= 'package' ( (lv_packageName_1_0= ruleQualifiedName ) ) ( (lv_domainElements_2_0= ruleDomainElement ) )* ( (lv_serviceDefs_3_0= ruleServiceDef ) )* ) // InternalTSSpec.g:80:3: otherlv_0= 'package' ( (lv_packageName_1_0= ruleQualifiedName ) ) ( (lv_domainElements_2_0= ruleDomainElement ) )* ( (lv_serviceDefs_3_0= ruleServiceDef ) )* { otherlv_0=(Token)match(input,12,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_0, grammarAccess.getServiceDefsAccess().getPackageKeyword_0()); } // InternalTSSpec.g:84:1: ( (lv_packageName_1_0= ruleQualifiedName ) ) // InternalTSSpec.g:85:1: (lv_packageName_1_0= ruleQualifiedName ) { // InternalTSSpec.g:85:1: (lv_packageName_1_0= ruleQualifiedName ) // InternalTSSpec.g:86:3: lv_packageName_1_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefsAccess().getPackageNameQualifiedNameParserRuleCall_1_0()); } pushFollow(FOLLOW_4); lv_packageName_1_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getServiceDefsRule()); } set( current, "packageName", lv_packageName_1_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } // InternalTSSpec.g:102:2: ( (lv_domainElements_2_0= ruleDomainElement ) )* loop1: do { int alt1=2; int LA1_0 = input.LA(1); if ( (LA1_0==RULE_DOC||(LA1_0>=13 && LA1_0<=14)||LA1_0==18||LA1_0==21) ) { alt1=1; } switch (alt1) { case 1 : // InternalTSSpec.g:103:1: (lv_domainElements_2_0= ruleDomainElement ) { // InternalTSSpec.g:103:1: (lv_domainElements_2_0= ruleDomainElement ) // InternalTSSpec.g:104:3: lv_domainElements_2_0= ruleDomainElement { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefsAccess().getDomainElementsDomainElementParserRuleCall_2_0()); } pushFollow(FOLLOW_4); lv_domainElements_2_0=ruleDomainElement(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getServiceDefsRule()); } add( current, "domainElements", lv_domainElements_2_0, "at.bestsolution.typescript.service.spec.TSSpec.DomainElement"); afterParserOrEnumRuleCall(); } } } break; default : break loop1; } } while (true); // InternalTSSpec.g:120:3: ( (lv_serviceDefs_3_0= ruleServiceDef ) )* loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==RULE_ID) ) { alt2=1; } switch (alt2) { case 1 : // InternalTSSpec.g:121:1: (lv_serviceDefs_3_0= ruleServiceDef ) { // InternalTSSpec.g:121:1: (lv_serviceDefs_3_0= ruleServiceDef ) // InternalTSSpec.g:122:3: lv_serviceDefs_3_0= ruleServiceDef { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefsAccess().getServiceDefsServiceDefParserRuleCall_3_0()); } pushFollow(FOLLOW_5); lv_serviceDefs_3_0=ruleServiceDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getServiceDefsRule()); } add( current, "serviceDefs", lv_serviceDefs_3_0, "at.bestsolution.typescript.service.spec.TSSpec.ServiceDef"); afterParserOrEnumRuleCall(); } } } break; default : break loop2; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleServiceDefs" // $ANTLR start "entryRuleDomainElement" // InternalTSSpec.g:146:1: entryRuleDomainElement returns [EObject current=null] : iv_ruleDomainElement= ruleDomainElement EOF ; public final EObject entryRuleDomainElement() throws RecognitionException { EObject current = null; EObject iv_ruleDomainElement = null; try { // InternalTSSpec.g:147:2: (iv_ruleDomainElement= ruleDomainElement EOF ) // InternalTSSpec.g:148:2: iv_ruleDomainElement= ruleDomainElement EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementRule()); } pushFollow(FOLLOW_1); iv_ruleDomainElement=ruleDomainElement(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleDomainElement; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleDomainElement" // $ANTLR start "ruleDomainElement" // InternalTSSpec.g:155:1: ruleDomainElement returns [EObject current=null] : ( ( (lv_doc_0_0= RULE_DOC ) )* ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) ) ; public final EObject ruleDomainElement() throws RecognitionException { EObject current = null; Token lv_doc_0_0=null; Token otherlv_1=null; Token lv_cust_3_0=null; Token otherlv_5=null; Token otherlv_7=null; Token otherlv_9=null; Token lv_isEnum_10_0=null; Token otherlv_12=null; Token otherlv_14=null; Token otherlv_15=null; Token otherlv_17=null; AntlrDatatypeRuleToken lv_name_2_0 = null; AntlrDatatypeRuleToken lv_name_4_0 = null; EObject lv_attributes_8_0 = null; AntlrDatatypeRuleToken lv_name_11_0 = null; EObject lv_enumValues_13_0 = null; AntlrDatatypeRuleToken lv_name_16_0 = null; AntlrDatatypeRuleToken lv_realType_18_0 = null; enterRule(); try { // InternalTSSpec.g:158:28: ( ( ( (lv_doc_0_0= RULE_DOC ) )* ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) ) ) // InternalTSSpec.g:159:1: ( ( (lv_doc_0_0= RULE_DOC ) )* ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) ) { // InternalTSSpec.g:159:1: ( ( (lv_doc_0_0= RULE_DOC ) )* ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) ) // InternalTSSpec.g:159:2: ( (lv_doc_0_0= RULE_DOC ) )* ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) { // InternalTSSpec.g:159:2: ( (lv_doc_0_0= RULE_DOC ) )* loop3: do { int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0==RULE_DOC) ) { alt3=1; } switch (alt3) { case 1 : // InternalTSSpec.g:160:1: (lv_doc_0_0= RULE_DOC ) { // InternalTSSpec.g:160:1: (lv_doc_0_0= RULE_DOC ) // InternalTSSpec.g:161:3: lv_doc_0_0= RULE_DOC { lv_doc_0_0=(Token)match(input,RULE_DOC,FOLLOW_6); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_doc_0_0, grammarAccess.getDomainElementAccess().getDocDOCTerminalRuleCall_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getDomainElementRule()); } addWithLastConsumed( current, "doc", lv_doc_0_0, "at.bestsolution.typescript.service.spec.TSSpec.DOC"); } } } break; default : break loop3; } } while (true); // InternalTSSpec.g:177:3: ( (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) | ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) | ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) | (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) ) int alt7=4; switch ( input.LA(1) ) { case 13: { alt7=1; } break; case 14: { alt7=2; } break; case 18: { alt7=3; } break; case 21: { alt7=4; } break; default: if (state.backtracking>0) {state.failed=true; return current;} NoViableAltException nvae = new NoViableAltException("", 7, 0, input); throw nvae; } switch (alt7) { case 1 : // InternalTSSpec.g:177:4: (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) { // InternalTSSpec.g:177:4: (otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) ) // InternalTSSpec.g:177:6: otherlv_1= 'javatype' ( (lv_name_2_0= ruleQualifiedName ) ) { otherlv_1=(Token)match(input,13,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getDomainElementAccess().getJavatypeKeyword_1_0_0()); } // InternalTSSpec.g:181:1: ( (lv_name_2_0= ruleQualifiedName ) ) // InternalTSSpec.g:182:1: (lv_name_2_0= ruleQualifiedName ) { // InternalTSSpec.g:182:1: (lv_name_2_0= ruleQualifiedName ) // InternalTSSpec.g:183:3: lv_name_2_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getNameQualifiedNameParserRuleCall_1_0_1_0()); } pushFollow(FOLLOW_2); lv_name_2_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } set( current, "name", lv_name_2_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } } } break; case 2 : // InternalTSSpec.g:200:6: ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) { // InternalTSSpec.g:200:6: ( ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' ) // InternalTSSpec.g:200:7: ( (lv_cust_3_0= 'cust' ) ) ( (lv_name_4_0= ruleQualifiedName ) ) (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? otherlv_7= '{' ( (lv_attributes_8_0= ruleAttribute ) )* otherlv_9= '}' { // InternalTSSpec.g:200:7: ( (lv_cust_3_0= 'cust' ) ) // InternalTSSpec.g:201:1: (lv_cust_3_0= 'cust' ) { // InternalTSSpec.g:201:1: (lv_cust_3_0= 'cust' ) // InternalTSSpec.g:202:3: lv_cust_3_0= 'cust' { lv_cust_3_0=(Token)match(input,14,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_cust_3_0, grammarAccess.getDomainElementAccess().getCustCustKeyword_1_1_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getDomainElementRule()); } setWithLastConsumed(current, "cust", true, "cust"); } } } // InternalTSSpec.g:215:2: ( (lv_name_4_0= ruleQualifiedName ) ) // InternalTSSpec.g:216:1: (lv_name_4_0= ruleQualifiedName ) { // InternalTSSpec.g:216:1: (lv_name_4_0= ruleQualifiedName ) // InternalTSSpec.g:217:3: lv_name_4_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getNameQualifiedNameParserRuleCall_1_1_1_0()); } pushFollow(FOLLOW_7); lv_name_4_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } set( current, "name", lv_name_4_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } // InternalTSSpec.g:233:2: (otherlv_5= 'extends' ( ( ruleQualifiedName ) ) )? int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==15) ) { alt4=1; } switch (alt4) { case 1 : // InternalTSSpec.g:233:4: otherlv_5= 'extends' ( ( ruleQualifiedName ) ) { otherlv_5=(Token)match(input,15,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_5, grammarAccess.getDomainElementAccess().getExtendsKeyword_1_1_2_0()); } // InternalTSSpec.g:237:1: ( ( ruleQualifiedName ) ) // InternalTSSpec.g:238:1: ( ruleQualifiedName ) { // InternalTSSpec.g:238:1: ( ruleQualifiedName ) // InternalTSSpec.g:239:3: ruleQualifiedName { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getDomainElementRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getSuperTypeDomainElementCrossReference_1_1_2_1_0()); } pushFollow(FOLLOW_8); ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } } break; } otherlv_7=(Token)match(input,16,FOLLOW_9); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_7, grammarAccess.getDomainElementAccess().getLeftCurlyBracketKeyword_1_1_3()); } // InternalTSSpec.g:256:1: ( (lv_attributes_8_0= ruleAttribute ) )* loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( ((LA5_0>=RULE_DOC && LA5_0<=RULE_ID)||LA5_0==24) ) { alt5=1; } switch (alt5) { case 1 : // InternalTSSpec.g:257:1: (lv_attributes_8_0= ruleAttribute ) { // InternalTSSpec.g:257:1: (lv_attributes_8_0= ruleAttribute ) // InternalTSSpec.g:258:3: lv_attributes_8_0= ruleAttribute { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getAttributesAttributeParserRuleCall_1_1_4_0()); } pushFollow(FOLLOW_9); lv_attributes_8_0=ruleAttribute(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } add( current, "attributes", lv_attributes_8_0, "at.bestsolution.typescript.service.spec.TSSpec.Attribute"); afterParserOrEnumRuleCall(); } } } break; default : break loop5; } } while (true); otherlv_9=(Token)match(input,17,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_9, grammarAccess.getDomainElementAccess().getRightCurlyBracketKeyword_1_1_5()); } } } break; case 3 : // InternalTSSpec.g:279:6: ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) { // InternalTSSpec.g:279:6: ( ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' ) // InternalTSSpec.g:279:7: ( (lv_isEnum_10_0= 'enum' ) ) ( (lv_name_11_0= ruleQualifiedName ) ) otherlv_12= '(' ( (lv_enumValues_13_0= ruleEnumVal ) )* otherlv_14= ')' { // InternalTSSpec.g:279:7: ( (lv_isEnum_10_0= 'enum' ) ) // InternalTSSpec.g:280:1: (lv_isEnum_10_0= 'enum' ) { // InternalTSSpec.g:280:1: (lv_isEnum_10_0= 'enum' ) // InternalTSSpec.g:281:3: lv_isEnum_10_0= 'enum' { lv_isEnum_10_0=(Token)match(input,18,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_isEnum_10_0, grammarAccess.getDomainElementAccess().getIsEnumEnumKeyword_1_2_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getDomainElementRule()); } setWithLastConsumed(current, "isEnum", true, "enum"); } } } // InternalTSSpec.g:294:2: ( (lv_name_11_0= ruleQualifiedName ) ) // InternalTSSpec.g:295:1: (lv_name_11_0= ruleQualifiedName ) { // InternalTSSpec.g:295:1: (lv_name_11_0= ruleQualifiedName ) // InternalTSSpec.g:296:3: lv_name_11_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getNameQualifiedNameParserRuleCall_1_2_1_0()); } pushFollow(FOLLOW_10); lv_name_11_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } set( current, "name", lv_name_11_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } otherlv_12=(Token)match(input,19,FOLLOW_11); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_12, grammarAccess.getDomainElementAccess().getLeftParenthesisKeyword_1_2_2()); } // InternalTSSpec.g:316:1: ( (lv_enumValues_13_0= ruleEnumVal ) )* loop6: do { int alt6=2; int LA6_0 = input.LA(1); if ( ((LA6_0>=RULE_DOC && LA6_0<=RULE_ID)) ) { alt6=1; } switch (alt6) { case 1 : // InternalTSSpec.g:317:1: (lv_enumValues_13_0= ruleEnumVal ) { // InternalTSSpec.g:317:1: (lv_enumValues_13_0= ruleEnumVal ) // InternalTSSpec.g:318:3: lv_enumValues_13_0= ruleEnumVal { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getEnumValuesEnumValParserRuleCall_1_2_3_0()); } pushFollow(FOLLOW_11); lv_enumValues_13_0=ruleEnumVal(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } add( current, "enumValues", lv_enumValues_13_0, "at.bestsolution.typescript.service.spec.TSSpec.EnumVal"); afterParserOrEnumRuleCall(); } } } break; default : break loop6; } } while (true); otherlv_14=(Token)match(input,20,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_14, grammarAccess.getDomainElementAccess().getRightParenthesisKeyword_1_2_4()); } } } break; case 4 : // InternalTSSpec.g:339:6: (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) { // InternalTSSpec.g:339:6: (otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) ) // InternalTSSpec.g:339:8: otherlv_15= 'alias' ( (lv_name_16_0= ruleQualifiedName ) ) otherlv_17= 'as' ( (lv_realType_18_0= ruleQualifiedName ) ) { otherlv_15=(Token)match(input,21,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_15, grammarAccess.getDomainElementAccess().getAliasKeyword_1_3_0()); } // InternalTSSpec.g:343:1: ( (lv_name_16_0= ruleQualifiedName ) ) // InternalTSSpec.g:344:1: (lv_name_16_0= ruleQualifiedName ) { // InternalTSSpec.g:344:1: (lv_name_16_0= ruleQualifiedName ) // InternalTSSpec.g:345:3: lv_name_16_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getNameQualifiedNameParserRuleCall_1_3_1_0()); } pushFollow(FOLLOW_12); lv_name_16_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } set( current, "name", lv_name_16_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } otherlv_17=(Token)match(input,22,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_17, grammarAccess.getDomainElementAccess().getAsKeyword_1_3_2()); } // InternalTSSpec.g:365:1: ( (lv_realType_18_0= ruleQualifiedName ) ) // InternalTSSpec.g:366:1: (lv_realType_18_0= ruleQualifiedName ) { // InternalTSSpec.g:366:1: (lv_realType_18_0= ruleQualifiedName ) // InternalTSSpec.g:367:3: lv_realType_18_0= ruleQualifiedName { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getDomainElementAccess().getRealTypeQualifiedNameParserRuleCall_1_3_3_0()); } pushFollow(FOLLOW_2); lv_realType_18_0=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getDomainElementRule()); } set( current, "realType", lv_realType_18_0, "at.bestsolution.typescript.service.spec.TSSpec.QualifiedName"); afterParserOrEnumRuleCall(); } } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleDomainElement" // $ANTLR start "entryRuleEnumVal" // InternalTSSpec.g:391:1: entryRuleEnumVal returns [EObject current=null] : iv_ruleEnumVal= ruleEnumVal EOF ; public final EObject entryRuleEnumVal() throws RecognitionException { EObject current = null; EObject iv_ruleEnumVal = null; try { // InternalTSSpec.g:392:2: (iv_ruleEnumVal= ruleEnumVal EOF ) // InternalTSSpec.g:393:2: iv_ruleEnumVal= ruleEnumVal EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getEnumValRule()); } pushFollow(FOLLOW_1); iv_ruleEnumVal=ruleEnumVal(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleEnumVal; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleEnumVal" // $ANTLR start "ruleEnumVal" // InternalTSSpec.g:400:1: ruleEnumVal returns [EObject current=null] : ( ( (lv_doc_0_0= RULE_DOC ) )* ( (lv_name_1_0= RULE_ID ) ) otherlv_2= '=' ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) ) ; public final EObject ruleEnumVal() throws RecognitionException { EObject current = null; Token lv_doc_0_0=null; Token lv_name_1_0=null; Token otherlv_2=null; Token lv_value_3_1=null; Token lv_value_3_2=null; Token lv_intValue_4_0=null; enterRule(); try { // InternalTSSpec.g:403:28: ( ( ( (lv_doc_0_0= RULE_DOC ) )* ( (lv_name_1_0= RULE_ID ) ) otherlv_2= '=' ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) ) ) // InternalTSSpec.g:404:1: ( ( (lv_doc_0_0= RULE_DOC ) )* ( (lv_name_1_0= RULE_ID ) ) otherlv_2= '=' ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) ) { // InternalTSSpec.g:404:1: ( ( (lv_doc_0_0= RULE_DOC ) )* ( (lv_name_1_0= RULE_ID ) ) otherlv_2= '=' ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) ) // InternalTSSpec.g:404:2: ( (lv_doc_0_0= RULE_DOC ) )* ( (lv_name_1_0= RULE_ID ) ) otherlv_2= '=' ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) { // InternalTSSpec.g:404:2: ( (lv_doc_0_0= RULE_DOC ) )* loop8: do { int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0==RULE_DOC) ) { alt8=1; } switch (alt8) { case 1 : // InternalTSSpec.g:405:1: (lv_doc_0_0= RULE_DOC ) { // InternalTSSpec.g:405:1: (lv_doc_0_0= RULE_DOC ) // InternalTSSpec.g:406:3: lv_doc_0_0= RULE_DOC { lv_doc_0_0=(Token)match(input,RULE_DOC,FOLLOW_13); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_doc_0_0, grammarAccess.getEnumValAccess().getDocDOCTerminalRuleCall_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEnumValRule()); } addWithLastConsumed( current, "doc", lv_doc_0_0, "at.bestsolution.typescript.service.spec.TSSpec.DOC"); } } } break; default : break loop8; } } while (true); // InternalTSSpec.g:422:3: ( (lv_name_1_0= RULE_ID ) ) // InternalTSSpec.g:423:1: (lv_name_1_0= RULE_ID ) { // InternalTSSpec.g:423:1: (lv_name_1_0= RULE_ID ) // InternalTSSpec.g:424:3: lv_name_1_0= RULE_ID { lv_name_1_0=(Token)match(input,RULE_ID,FOLLOW_14); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_name_1_0, grammarAccess.getEnumValAccess().getNameIDTerminalRuleCall_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEnumValRule()); } setWithLastConsumed( current, "name", lv_name_1_0, "org.eclipse.xtext.common.Terminals.ID"); } } } otherlv_2=(Token)match(input,23,FOLLOW_15); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_2, grammarAccess.getEnumValAccess().getEqualsSignKeyword_2()); } // InternalTSSpec.g:444:1: ( ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) | ( (lv_intValue_4_0= RULE_INT ) ) ) int alt10=2; int LA10_0 = input.LA(1); if ( ((LA10_0>=RULE_ID && LA10_0<=RULE_STRING)) ) { alt10=1; } else if ( (LA10_0==RULE_INT) ) { alt10=2; } else { if (state.backtracking>0) {state.failed=true; return current;} NoViableAltException nvae = new NoViableAltException("", 10, 0, input); throw nvae; } switch (alt10) { case 1 : // InternalTSSpec.g:444:2: ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) { // InternalTSSpec.g:444:2: ( ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) ) // InternalTSSpec.g:445:1: ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) { // InternalTSSpec.g:445:1: ( (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) ) // InternalTSSpec.g:446:1: (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) { // InternalTSSpec.g:446:1: (lv_value_3_1= RULE_ID | lv_value_3_2= RULE_STRING ) int alt9=2; int LA9_0 = input.LA(1); if ( (LA9_0==RULE_ID) ) { alt9=1; } else if ( (LA9_0==RULE_STRING) ) { alt9=2; } else { if (state.backtracking>0) {state.failed=true; return current;} NoViableAltException nvae = new NoViableAltException("", 9, 0, input); throw nvae; } switch (alt9) { case 1 : // InternalTSSpec.g:447:3: lv_value_3_1= RULE_ID { lv_value_3_1=(Token)match(input,RULE_ID,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_value_3_1, grammarAccess.getEnumValAccess().getValueIDTerminalRuleCall_3_0_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEnumValRule()); } setWithLastConsumed( current, "value", lv_value_3_1, "org.eclipse.xtext.common.Terminals.ID"); } } break; case 2 : // InternalTSSpec.g:462:8: lv_value_3_2= RULE_STRING { lv_value_3_2=(Token)match(input,RULE_STRING,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_value_3_2, grammarAccess.getEnumValAccess().getValueSTRINGTerminalRuleCall_3_0_0_1()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEnumValRule()); } setWithLastConsumed( current, "value", lv_value_3_2, "org.eclipse.xtext.common.Terminals.STRING"); } } break; } } } } break; case 2 : // InternalTSSpec.g:481:6: ( (lv_intValue_4_0= RULE_INT ) ) { // InternalTSSpec.g:481:6: ( (lv_intValue_4_0= RULE_INT ) ) // InternalTSSpec.g:482:1: (lv_intValue_4_0= RULE_INT ) { // InternalTSSpec.g:482:1: (lv_intValue_4_0= RULE_INT ) // InternalTSSpec.g:483:3: lv_intValue_4_0= RULE_INT { lv_intValue_4_0=(Token)match(input,RULE_INT,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_intValue_4_0, grammarAccess.getEnumValAccess().getIntValueINTTerminalRuleCall_3_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEnumValRule()); } setWithLastConsumed( current, "intValue", lv_intValue_4_0, "org.eclipse.xtext.common.Terminals.INT"); } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleEnumVal" // $ANTLR start "entryRuleAttribute" // InternalTSSpec.g:507:1: entryRuleAttribute returns [EObject current=null] : iv_ruleAttribute= ruleAttribute EOF ; public final EObject entryRuleAttribute() throws RecognitionException { EObject current = null; EObject iv_ruleAttribute = null; try { // InternalTSSpec.g:508:2: (iv_ruleAttribute= ruleAttribute EOF ) // InternalTSSpec.g:509:2: iv_ruleAttribute= ruleAttribute EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getAttributeRule()); } pushFollow(FOLLOW_1); iv_ruleAttribute=ruleAttribute(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleAttribute; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleAttribute" // $ANTLR start "ruleAttribute" // InternalTSSpec.g:516:1: ruleAttribute returns [EObject current=null] : ( ( (lv_documentation_0_0= RULE_DOC ) )* ( (lv_optional_1_0= 'optional' ) )? ( (lv_type_2_0= ruleGenericTypeArgument ) ) ( (lv_name_3_0= RULE_ID ) ) (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? ) ; public final EObject ruleAttribute() throws RecognitionException { EObject current = null; Token lv_documentation_0_0=null; Token lv_optional_1_0=null; Token lv_name_3_0=null; Token otherlv_4=null; Token lv_value_5_0=null; EObject lv_type_2_0 = null; enterRule(); try { // InternalTSSpec.g:519:28: ( ( ( (lv_documentation_0_0= RULE_DOC ) )* ( (lv_optional_1_0= 'optional' ) )? ( (lv_type_2_0= ruleGenericTypeArgument ) ) ( (lv_name_3_0= RULE_ID ) ) (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? ) ) // InternalTSSpec.g:520:1: ( ( (lv_documentation_0_0= RULE_DOC ) )* ( (lv_optional_1_0= 'optional' ) )? ( (lv_type_2_0= ruleGenericTypeArgument ) ) ( (lv_name_3_0= RULE_ID ) ) (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? ) { // InternalTSSpec.g:520:1: ( ( (lv_documentation_0_0= RULE_DOC ) )* ( (lv_optional_1_0= 'optional' ) )? ( (lv_type_2_0= ruleGenericTypeArgument ) ) ( (lv_name_3_0= RULE_ID ) ) (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? ) // InternalTSSpec.g:520:2: ( (lv_documentation_0_0= RULE_DOC ) )* ( (lv_optional_1_0= 'optional' ) )? ( (lv_type_2_0= ruleGenericTypeArgument ) ) ( (lv_name_3_0= RULE_ID ) ) (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? { // InternalTSSpec.g:520:2: ( (lv_documentation_0_0= RULE_DOC ) )* loop11: do { int alt11=2; int LA11_0 = input.LA(1); if ( (LA11_0==RULE_DOC) ) { alt11=1; } switch (alt11) { case 1 : // InternalTSSpec.g:521:1: (lv_documentation_0_0= RULE_DOC ) { // InternalTSSpec.g:521:1: (lv_documentation_0_0= RULE_DOC ) // InternalTSSpec.g:522:3: lv_documentation_0_0= RULE_DOC { lv_documentation_0_0=(Token)match(input,RULE_DOC,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_documentation_0_0, grammarAccess.getAttributeAccess().getDocumentationDOCTerminalRuleCall_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getAttributeRule()); } addWithLastConsumed( current, "documentation", lv_documentation_0_0, "at.bestsolution.typescript.service.spec.TSSpec.DOC"); } } } break; default : break loop11; } } while (true); // InternalTSSpec.g:538:3: ( (lv_optional_1_0= 'optional' ) )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0==24) ) { alt12=1; } switch (alt12) { case 1 : // InternalTSSpec.g:539:1: (lv_optional_1_0= 'optional' ) { // InternalTSSpec.g:539:1: (lv_optional_1_0= 'optional' ) // InternalTSSpec.g:540:3: lv_optional_1_0= 'optional' { lv_optional_1_0=(Token)match(input,24,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_optional_1_0, grammarAccess.getAttributeAccess().getOptionalOptionalKeyword_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getAttributeRule()); } setWithLastConsumed(current, "optional", true, "optional"); } } } break; } // InternalTSSpec.g:553:3: ( (lv_type_2_0= ruleGenericTypeArgument ) ) // InternalTSSpec.g:554:1: (lv_type_2_0= ruleGenericTypeArgument ) { // InternalTSSpec.g:554:1: (lv_type_2_0= ruleGenericTypeArgument ) // InternalTSSpec.g:555:3: lv_type_2_0= ruleGenericTypeArgument { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getAttributeAccess().getTypeGenericTypeArgumentParserRuleCall_2_0()); } pushFollow(FOLLOW_3); lv_type_2_0=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getAttributeRule()); } set( current, "type", lv_type_2_0, "at.bestsolution.typescript.service.spec.TSSpec.GenericTypeArgument"); afterParserOrEnumRuleCall(); } } } // InternalTSSpec.g:571:2: ( (lv_name_3_0= RULE_ID ) ) // InternalTSSpec.g:572:1: (lv_name_3_0= RULE_ID ) { // InternalTSSpec.g:572:1: (lv_name_3_0= RULE_ID ) // InternalTSSpec.g:573:3: lv_name_3_0= RULE_ID { lv_name_3_0=(Token)match(input,RULE_ID,FOLLOW_17); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_name_3_0, grammarAccess.getAttributeAccess().getNameIDTerminalRuleCall_3_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getAttributeRule()); } setWithLastConsumed( current, "name", lv_name_3_0, "org.eclipse.xtext.common.Terminals.ID"); } } } // InternalTSSpec.g:589:2: (otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) )? int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0==23) ) { alt13=1; } switch (alt13) { case 1 : // InternalTSSpec.g:589:4: otherlv_4= '=' ( (lv_value_5_0= RULE_STRING ) ) { otherlv_4=(Token)match(input,23,FOLLOW_18); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_4, grammarAccess.getAttributeAccess().getEqualsSignKeyword_4_0()); } // InternalTSSpec.g:593:1: ( (lv_value_5_0= RULE_STRING ) ) // InternalTSSpec.g:594:1: (lv_value_5_0= RULE_STRING ) { // InternalTSSpec.g:594:1: (lv_value_5_0= RULE_STRING ) // InternalTSSpec.g:595:3: lv_value_5_0= RULE_STRING { lv_value_5_0=(Token)match(input,RULE_STRING,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_value_5_0, grammarAccess.getAttributeAccess().getValueSTRINGTerminalRuleCall_4_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getAttributeRule()); } setWithLastConsumed( current, "value", lv_value_5_0, "org.eclipse.xtext.common.Terminals.STRING"); } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleAttribute" // $ANTLR start "entryRuleGenericTypeArgument" // InternalTSSpec.g:619:1: entryRuleGenericTypeArgument returns [EObject current=null] : iv_ruleGenericTypeArgument= ruleGenericTypeArgument EOF ; public final EObject entryRuleGenericTypeArgument() throws RecognitionException { EObject current = null; EObject iv_ruleGenericTypeArgument = null; try { // InternalTSSpec.g:620:2: (iv_ruleGenericTypeArgument= ruleGenericTypeArgument EOF ) // InternalTSSpec.g:621:2: iv_ruleGenericTypeArgument= ruleGenericTypeArgument EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getGenericTypeArgumentRule()); } pushFollow(FOLLOW_1); iv_ruleGenericTypeArgument=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleGenericTypeArgument; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleGenericTypeArgument" // $ANTLR start "ruleGenericTypeArgument" // InternalTSSpec.g:628:1: ruleGenericTypeArgument returns [EObject current=null] : ( ( ( ruleQualifiedName ) ) (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? ( (lv_list_6_0= '[]' ) )? ) ; public final EObject ruleGenericTypeArgument() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_3=null; Token otherlv_5=null; Token lv_list_6_0=null; EObject lv_arguments_2_0 = null; EObject lv_arguments_4_0 = null; enterRule(); try { // InternalTSSpec.g:631:28: ( ( ( ( ruleQualifiedName ) ) (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? ( (lv_list_6_0= '[]' ) )? ) ) // InternalTSSpec.g:632:1: ( ( ( ruleQualifiedName ) ) (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? ( (lv_list_6_0= '[]' ) )? ) { // InternalTSSpec.g:632:1: ( ( ( ruleQualifiedName ) ) (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? ( (lv_list_6_0= '[]' ) )? ) // InternalTSSpec.g:632:2: ( ( ruleQualifiedName ) ) (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? ( (lv_list_6_0= '[]' ) )? { // InternalTSSpec.g:632:2: ( ( ruleQualifiedName ) ) // InternalTSSpec.g:633:1: ( ruleQualifiedName ) { // InternalTSSpec.g:633:1: ( ruleQualifiedName ) // InternalTSSpec.g:634:3: ruleQualifiedName { if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getGenericTypeArgumentRule()); } } if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getGenericTypeArgumentAccess().getTypeDomainElementCrossReference_0_0()); } pushFollow(FOLLOW_19); ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { afterParserOrEnumRuleCall(); } } } // InternalTSSpec.g:647:2: (otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' )? int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0==25) ) { alt15=1; } switch (alt15) { case 1 : // InternalTSSpec.g:647:4: otherlv_1= '<' ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* otherlv_5= '>' { otherlv_1=(Token)match(input,25,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getGenericTypeArgumentAccess().getLessThanSignKeyword_1_0()); } // InternalTSSpec.g:651:1: ( (lv_arguments_2_0= ruleGenericTypeArgument ) ) // InternalTSSpec.g:652:1: (lv_arguments_2_0= ruleGenericTypeArgument ) { // InternalTSSpec.g:652:1: (lv_arguments_2_0= ruleGenericTypeArgument ) // InternalTSSpec.g:653:3: lv_arguments_2_0= ruleGenericTypeArgument { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getGenericTypeArgumentAccess().getArgumentsGenericTypeArgumentParserRuleCall_1_1_0()); } pushFollow(FOLLOW_20); lv_arguments_2_0=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getGenericTypeArgumentRule()); } add( current, "arguments", lv_arguments_2_0, "at.bestsolution.typescript.service.spec.TSSpec.GenericTypeArgument"); afterParserOrEnumRuleCall(); } } } // InternalTSSpec.g:669:2: (otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) )* loop14: do { int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0==26) ) { alt14=1; } switch (alt14) { case 1 : // InternalTSSpec.g:669:4: otherlv_3= ',' ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) { otherlv_3=(Token)match(input,26,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_3, grammarAccess.getGenericTypeArgumentAccess().getCommaKeyword_1_2_0()); } // InternalTSSpec.g:673:1: ( (lv_arguments_4_0= ruleGenericTypeArgument ) ) // InternalTSSpec.g:674:1: (lv_arguments_4_0= ruleGenericTypeArgument ) { // InternalTSSpec.g:674:1: (lv_arguments_4_0= ruleGenericTypeArgument ) // InternalTSSpec.g:675:3: lv_arguments_4_0= ruleGenericTypeArgument { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getGenericTypeArgumentAccess().getArgumentsGenericTypeArgumentParserRuleCall_1_2_1_0()); } pushFollow(FOLLOW_20); lv_arguments_4_0=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getGenericTypeArgumentRule()); } add( current, "arguments", lv_arguments_4_0, "at.bestsolution.typescript.service.spec.TSSpec.GenericTypeArgument"); afterParserOrEnumRuleCall(); } } } } break; default : break loop14; } } while (true); otherlv_5=(Token)match(input,27,FOLLOW_21); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_5, grammarAccess.getGenericTypeArgumentAccess().getGreaterThanSignKeyword_1_3()); } } break; } // InternalTSSpec.g:695:3: ( (lv_list_6_0= '[]' ) )? int alt16=2; int LA16_0 = input.LA(1); if ( (LA16_0==28) ) { alt16=1; } switch (alt16) { case 1 : // InternalTSSpec.g:696:1: (lv_list_6_0= '[]' ) { // InternalTSSpec.g:696:1: (lv_list_6_0= '[]' ) // InternalTSSpec.g:697:3: lv_list_6_0= '[]' { lv_list_6_0=(Token)match(input,28,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_list_6_0, grammarAccess.getGenericTypeArgumentAccess().getListLeftSquareBracketRightSquareBracketKeyword_2_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getGenericTypeArgumentRule()); } setWithLastConsumed(current, "list", true, "[]"); } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleGenericTypeArgument" // $ANTLR start "entryRuleServiceDef" // InternalTSSpec.g:718:1: entryRuleServiceDef returns [EObject current=null] : iv_ruleServiceDef= ruleServiceDef EOF ; public final EObject entryRuleServiceDef() throws RecognitionException { EObject current = null; EObject iv_ruleServiceDef = null; try { // InternalTSSpec.g:719:2: (iv_ruleServiceDef= ruleServiceDef EOF ) // InternalTSSpec.g:720:2: iv_ruleServiceDef= ruleServiceDef EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefRule()); } pushFollow(FOLLOW_1); iv_ruleServiceDef=ruleServiceDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleServiceDef; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleServiceDef" // $ANTLR start "ruleServiceDef" // InternalTSSpec.g:727:1: ruleServiceDef returns [EObject current=null] : ( ( (lv_name_0_0= RULE_ID ) ) otherlv_1= '{' ( (lv_commandList_2_0= ruleCommandDef ) )* ( (lv_eventList_3_0= ruleEventDef ) )* otherlv_4= '}' ) ; public final EObject ruleServiceDef() throws RecognitionException { EObject current = null; Token lv_name_0_0=null; Token otherlv_1=null; Token otherlv_4=null; EObject lv_commandList_2_0 = null; EObject lv_eventList_3_0 = null; enterRule(); try { // InternalTSSpec.g:730:28: ( ( ( (lv_name_0_0= RULE_ID ) ) otherlv_1= '{' ( (lv_commandList_2_0= ruleCommandDef ) )* ( (lv_eventList_3_0= ruleEventDef ) )* otherlv_4= '}' ) ) // InternalTSSpec.g:731:1: ( ( (lv_name_0_0= RULE_ID ) ) otherlv_1= '{' ( (lv_commandList_2_0= ruleCommandDef ) )* ( (lv_eventList_3_0= ruleEventDef ) )* otherlv_4= '}' ) { // InternalTSSpec.g:731:1: ( ( (lv_name_0_0= RULE_ID ) ) otherlv_1= '{' ( (lv_commandList_2_0= ruleCommandDef ) )* ( (lv_eventList_3_0= ruleEventDef ) )* otherlv_4= '}' ) // InternalTSSpec.g:731:2: ( (lv_name_0_0= RULE_ID ) ) otherlv_1= '{' ( (lv_commandList_2_0= ruleCommandDef ) )* ( (lv_eventList_3_0= ruleEventDef ) )* otherlv_4= '}' { // InternalTSSpec.g:731:2: ( (lv_name_0_0= RULE_ID ) ) // InternalTSSpec.g:732:1: (lv_name_0_0= RULE_ID ) { // InternalTSSpec.g:732:1: (lv_name_0_0= RULE_ID ) // InternalTSSpec.g:733:3: lv_name_0_0= RULE_ID { lv_name_0_0=(Token)match(input,RULE_ID,FOLLOW_8); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_name_0_0, grammarAccess.getServiceDefAccess().getNameIDTerminalRuleCall_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getServiceDefRule()); } setWithLastConsumed( current, "name", lv_name_0_0, "org.eclipse.xtext.common.Terminals.ID"); } } } otherlv_1=(Token)match(input,16,FOLLOW_22); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getServiceDefAccess().getLeftCurlyBracketKeyword_1()); } // InternalTSSpec.g:753:1: ( (lv_commandList_2_0= ruleCommandDef ) )* loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( (LA17_0==29) ) { alt17=1; } switch (alt17) { case 1 : // InternalTSSpec.g:754:1: (lv_commandList_2_0= ruleCommandDef ) { // InternalTSSpec.g:754:1: (lv_commandList_2_0= ruleCommandDef ) // InternalTSSpec.g:755:3: lv_commandList_2_0= ruleCommandDef { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefAccess().getCommandListCommandDefParserRuleCall_2_0()); } pushFollow(FOLLOW_22); lv_commandList_2_0=ruleCommandDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getServiceDefRule()); } add( current, "commandList", lv_commandList_2_0, "at.bestsolution.typescript.service.spec.TSSpec.CommandDef"); afterParserOrEnumRuleCall(); } } } break; default : break loop17; } } while (true); // InternalTSSpec.g:771:3: ( (lv_eventList_3_0= ruleEventDef ) )* loop18: do { int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0==RULE_DOC||LA18_0==32) ) { alt18=1; } switch (alt18) { case 1 : // InternalTSSpec.g:772:1: (lv_eventList_3_0= ruleEventDef ) { // InternalTSSpec.g:772:1: (lv_eventList_3_0= ruleEventDef ) // InternalTSSpec.g:773:3: lv_eventList_3_0= ruleEventDef { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getServiceDefAccess().getEventListEventDefParserRuleCall_3_0()); } pushFollow(FOLLOW_23); lv_eventList_3_0=ruleEventDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getServiceDefRule()); } add( current, "eventList", lv_eventList_3_0, "at.bestsolution.typescript.service.spec.TSSpec.EventDef"); afterParserOrEnumRuleCall(); } } } break; default : break loop18; } } while (true); otherlv_4=(Token)match(input,17,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_4, grammarAccess.getServiceDefAccess().getRightCurlyBracketKeyword_4()); } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleServiceDef" // $ANTLR start "entryRuleCommandDef" // InternalTSSpec.g:801:1: entryRuleCommandDef returns [EObject current=null] : iv_ruleCommandDef= ruleCommandDef EOF ; public final EObject entryRuleCommandDef() throws RecognitionException { EObject current = null; EObject iv_ruleCommandDef = null; try { // InternalTSSpec.g:802:2: (iv_ruleCommandDef= ruleCommandDef EOF ) // InternalTSSpec.g:803:2: iv_ruleCommandDef= ruleCommandDef EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getCommandDefRule()); } pushFollow(FOLLOW_1); iv_ruleCommandDef=ruleCommandDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleCommandDef; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleCommandDef" // $ANTLR start "ruleCommandDef" // InternalTSSpec.g:810:1: ruleCommandDef returns [EObject current=null] : (otherlv_0= 'command' ( (lv_name_1_0= RULE_ID ) ) (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? otherlv_5= 'returns' (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) ) ; public final EObject ruleCommandDef() throws RecognitionException { EObject current = null; Token otherlv_0=null; Token lv_name_1_0=null; Token otherlv_2=null; Token otherlv_4=null; Token otherlv_5=null; Token otherlv_6=null; EObject lv_attributes_3_0 = null; EObject lv_returnVal_7_0 = null; enterRule(); try { // InternalTSSpec.g:813:28: ( (otherlv_0= 'command' ( (lv_name_1_0= RULE_ID ) ) (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? otherlv_5= 'returns' (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) ) ) // InternalTSSpec.g:814:1: (otherlv_0= 'command' ( (lv_name_1_0= RULE_ID ) ) (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? otherlv_5= 'returns' (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) ) { // InternalTSSpec.g:814:1: (otherlv_0= 'command' ( (lv_name_1_0= RULE_ID ) ) (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? otherlv_5= 'returns' (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) ) // InternalTSSpec.g:814:3: otherlv_0= 'command' ( (lv_name_1_0= RULE_ID ) ) (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? otherlv_5= 'returns' (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) { otherlv_0=(Token)match(input,29,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_0, grammarAccess.getCommandDefAccess().getCommandKeyword_0()); } // InternalTSSpec.g:818:1: ( (lv_name_1_0= RULE_ID ) ) // InternalTSSpec.g:819:1: (lv_name_1_0= RULE_ID ) { // InternalTSSpec.g:819:1: (lv_name_1_0= RULE_ID ) // InternalTSSpec.g:820:3: lv_name_1_0= RULE_ID { lv_name_1_0=(Token)match(input,RULE_ID,FOLLOW_24); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_name_1_0, grammarAccess.getCommandDefAccess().getNameIDTerminalRuleCall_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getCommandDefRule()); } setWithLastConsumed( current, "name", lv_name_1_0, "org.eclipse.xtext.common.Terminals.ID"); } } } // InternalTSSpec.g:836:2: (otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' )? int alt20=2; int LA20_0 = input.LA(1); if ( (LA20_0==19) ) { alt20=1; } switch (alt20) { case 1 : // InternalTSSpec.g:836:4: otherlv_2= '(' ( (lv_attributes_3_0= ruleAttribute ) )+ otherlv_4= ')' { otherlv_2=(Token)match(input,19,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_2, grammarAccess.getCommandDefAccess().getLeftParenthesisKeyword_2_0()); } // InternalTSSpec.g:840:1: ( (lv_attributes_3_0= ruleAttribute ) )+ int cnt19=0; loop19: do { int alt19=2; int LA19_0 = input.LA(1); if ( ((LA19_0>=RULE_DOC && LA19_0<=RULE_ID)||LA19_0==24) ) { alt19=1; } switch (alt19) { case 1 : // InternalTSSpec.g:841:1: (lv_attributes_3_0= ruleAttribute ) { // InternalTSSpec.g:841:1: (lv_attributes_3_0= ruleAttribute ) // InternalTSSpec.g:842:3: lv_attributes_3_0= ruleAttribute { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getCommandDefAccess().getAttributesAttributeParserRuleCall_2_1_0()); } pushFollow(FOLLOW_25); lv_attributes_3_0=ruleAttribute(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getCommandDefRule()); } add( current, "attributes", lv_attributes_3_0, "at.bestsolution.typescript.service.spec.TSSpec.Attribute"); afterParserOrEnumRuleCall(); } } } break; default : if ( cnt19 >= 1 ) break loop19; if (state.backtracking>0) {state.failed=true; return current;} EarlyExitException eee = new EarlyExitException(19, input); throw eee; } cnt19++; } while (true); otherlv_4=(Token)match(input,20,FOLLOW_26); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_4, grammarAccess.getCommandDefAccess().getRightParenthesisKeyword_2_2()); } } break; } otherlv_5=(Token)match(input,30,FOLLOW_27); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_5, grammarAccess.getCommandDefAccess().getReturnsKeyword_3()); } // InternalTSSpec.g:866:1: (otherlv_6= 'void' | ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) ) int alt21=2; int LA21_0 = input.LA(1); if ( (LA21_0==31) ) { alt21=1; } else if ( (LA21_0==RULE_ID) ) { alt21=2; } else { if (state.backtracking>0) {state.failed=true; return current;} NoViableAltException nvae = new NoViableAltException("", 21, 0, input); throw nvae; } switch (alt21) { case 1 : // InternalTSSpec.g:866:3: otherlv_6= 'void' { otherlv_6=(Token)match(input,31,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_6, grammarAccess.getCommandDefAccess().getVoidKeyword_4_0()); } } break; case 2 : // InternalTSSpec.g:871:6: ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) { // InternalTSSpec.g:871:6: ( (lv_returnVal_7_0= ruleGenericTypeArgument ) ) // InternalTSSpec.g:872:1: (lv_returnVal_7_0= ruleGenericTypeArgument ) { // InternalTSSpec.g:872:1: (lv_returnVal_7_0= ruleGenericTypeArgument ) // InternalTSSpec.g:873:3: lv_returnVal_7_0= ruleGenericTypeArgument { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getCommandDefAccess().getReturnValGenericTypeArgumentParserRuleCall_4_1_0()); } pushFollow(FOLLOW_2); lv_returnVal_7_0=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getCommandDefRule()); } set( current, "returnVal", lv_returnVal_7_0, "at.bestsolution.typescript.service.spec.TSSpec.GenericTypeArgument"); afterParserOrEnumRuleCall(); } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleCommandDef" // $ANTLR start "entryRuleEventDef" // InternalTSSpec.g:897:1: entryRuleEventDef returns [EObject current=null] : iv_ruleEventDef= ruleEventDef EOF ; public final EObject entryRuleEventDef() throws RecognitionException { EObject current = null; EObject iv_ruleEventDef = null; try { // InternalTSSpec.g:898:2: (iv_ruleEventDef= ruleEventDef EOF ) // InternalTSSpec.g:899:2: iv_ruleEventDef= ruleEventDef EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getEventDefRule()); } pushFollow(FOLLOW_1); iv_ruleEventDef=ruleEventDef(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleEventDef; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleEventDef" // $ANTLR start "ruleEventDef" // InternalTSSpec.g:906:1: ruleEventDef returns [EObject current=null] : ( ( (lv_documentation_0_0= RULE_DOC ) )* otherlv_1= 'event' ( (lv_name_2_0= RULE_ID ) ) ( (lv_type_3_0= ruleGenericTypeArgument ) ) ) ; public final EObject ruleEventDef() throws RecognitionException { EObject current = null; Token lv_documentation_0_0=null; Token otherlv_1=null; Token lv_name_2_0=null; EObject lv_type_3_0 = null; enterRule(); try { // InternalTSSpec.g:909:28: ( ( ( (lv_documentation_0_0= RULE_DOC ) )* otherlv_1= 'event' ( (lv_name_2_0= RULE_ID ) ) ( (lv_type_3_0= ruleGenericTypeArgument ) ) ) ) // InternalTSSpec.g:910:1: ( ( (lv_documentation_0_0= RULE_DOC ) )* otherlv_1= 'event' ( (lv_name_2_0= RULE_ID ) ) ( (lv_type_3_0= ruleGenericTypeArgument ) ) ) { // InternalTSSpec.g:910:1: ( ( (lv_documentation_0_0= RULE_DOC ) )* otherlv_1= 'event' ( (lv_name_2_0= RULE_ID ) ) ( (lv_type_3_0= ruleGenericTypeArgument ) ) ) // InternalTSSpec.g:910:2: ( (lv_documentation_0_0= RULE_DOC ) )* otherlv_1= 'event' ( (lv_name_2_0= RULE_ID ) ) ( (lv_type_3_0= ruleGenericTypeArgument ) ) { // InternalTSSpec.g:910:2: ( (lv_documentation_0_0= RULE_DOC ) )* loop22: do { int alt22=2; int LA22_0 = input.LA(1); if ( (LA22_0==RULE_DOC) ) { alt22=1; } switch (alt22) { case 1 : // InternalTSSpec.g:911:1: (lv_documentation_0_0= RULE_DOC ) { // InternalTSSpec.g:911:1: (lv_documentation_0_0= RULE_DOC ) // InternalTSSpec.g:912:3: lv_documentation_0_0= RULE_DOC { lv_documentation_0_0=(Token)match(input,RULE_DOC,FOLLOW_28); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_documentation_0_0, grammarAccess.getEventDefAccess().getDocumentationDOCTerminalRuleCall_0_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEventDefRule()); } addWithLastConsumed( current, "documentation", lv_documentation_0_0, "at.bestsolution.typescript.service.spec.TSSpec.DOC"); } } } break; default : break loop22; } } while (true); otherlv_1=(Token)match(input,32,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getEventDefAccess().getEventKeyword_1()); } // InternalTSSpec.g:932:1: ( (lv_name_2_0= RULE_ID ) ) // InternalTSSpec.g:933:1: (lv_name_2_0= RULE_ID ) { // InternalTSSpec.g:933:1: (lv_name_2_0= RULE_ID ) // InternalTSSpec.g:934:3: lv_name_2_0= RULE_ID { lv_name_2_0=(Token)match(input,RULE_ID,FOLLOW_16); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_name_2_0, grammarAccess.getEventDefAccess().getNameIDTerminalRuleCall_2_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getEventDefRule()); } setWithLastConsumed( current, "name", lv_name_2_0, "org.eclipse.xtext.common.Terminals.ID"); } } } // InternalTSSpec.g:950:2: ( (lv_type_3_0= ruleGenericTypeArgument ) ) // InternalTSSpec.g:951:1: (lv_type_3_0= ruleGenericTypeArgument ) { // InternalTSSpec.g:951:1: (lv_type_3_0= ruleGenericTypeArgument ) // InternalTSSpec.g:952:3: lv_type_3_0= ruleGenericTypeArgument { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getEventDefAccess().getTypeGenericTypeArgumentParserRuleCall_3_0()); } pushFollow(FOLLOW_2); lv_type_3_0=ruleGenericTypeArgument(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getEventDefRule()); } set( current, "type", lv_type_3_0, "at.bestsolution.typescript.service.spec.TSSpec.GenericTypeArgument"); afterParserOrEnumRuleCall(); } } } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleEventDef" // $ANTLR start "entryRuleQualifiedName" // InternalTSSpec.g:976:1: entryRuleQualifiedName returns [String current=null] : iv_ruleQualifiedName= ruleQualifiedName EOF ; public final String entryRuleQualifiedName() throws RecognitionException { String current = null; AntlrDatatypeRuleToken iv_ruleQualifiedName = null; try { // InternalTSSpec.g:977:2: (iv_ruleQualifiedName= ruleQualifiedName EOF ) // InternalTSSpec.g:978:2: iv_ruleQualifiedName= ruleQualifiedName EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getQualifiedNameRule()); } pushFollow(FOLLOW_1); iv_ruleQualifiedName=ruleQualifiedName(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleQualifiedName.getText(); } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "entryRuleQualifiedName" // $ANTLR start "ruleQualifiedName" // InternalTSSpec.g:985:1: ruleQualifiedName returns [AntlrDatatypeRuleToken current=new AntlrDatatypeRuleToken()] : (this_ID_0= RULE_ID ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* ) ; public final AntlrDatatypeRuleToken ruleQualifiedName() throws RecognitionException { AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken(); Token this_ID_0=null; Token kw=null; Token this_ID_2=null; enterRule(); try { // InternalTSSpec.g:988:28: ( (this_ID_0= RULE_ID ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* ) ) // InternalTSSpec.g:989:1: (this_ID_0= RULE_ID ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* ) { // InternalTSSpec.g:989:1: (this_ID_0= RULE_ID ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* ) // InternalTSSpec.g:989:6: this_ID_0= RULE_ID ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* { this_ID_0=(Token)match(input,RULE_ID,FOLLOW_29); if (state.failed) return current; if ( state.backtracking==0 ) { current.merge(this_ID_0); } if ( state.backtracking==0 ) { newLeafNode(this_ID_0, grammarAccess.getQualifiedNameAccess().getIDTerminalRuleCall_0()); } // InternalTSSpec.g:996:1: ( ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID )* loop23: do { int alt23=2; int LA23_0 = input.LA(1); if ( (LA23_0==33) && (synpred1_InternalTSSpec())) { alt23=1; } switch (alt23) { case 1 : // InternalTSSpec.g:996:2: ( ( '.' )=>kw= '.' ) this_ID_2= RULE_ID { // InternalTSSpec.g:996:2: ( ( '.' )=>kw= '.' ) // InternalTSSpec.g:996:3: ( '.' )=>kw= '.' { kw=(Token)match(input,33,FOLLOW_3); if (state.failed) return current; if ( state.backtracking==0 ) { current.merge(kw); newLeafNode(kw, grammarAccess.getQualifiedNameAccess().getFullStopKeyword_1_0()); } } this_ID_2=(Token)match(input,RULE_ID,FOLLOW_29); if (state.failed) return current; if ( state.backtracking==0 ) { current.merge(this_ID_2); } if ( state.backtracking==0 ) { newLeafNode(this_ID_2, grammarAccess.getQualifiedNameAccess().getIDTerminalRuleCall_1_1()); } } break; default : break loop23; } } while (true); } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } // $ANTLR end "ruleQualifiedName" // $ANTLR start synpred1_InternalTSSpec public final void synpred1_InternalTSSpec_fragment() throws RecognitionException { // InternalTSSpec.g:996:3: ( '.' ) // InternalTSSpec.g:997:2: '.' { match(input,33,FOLLOW_2); if (state.failed) return ; } } // $ANTLR end synpred1_InternalTSSpec // Delegated rules public final boolean synpred1_InternalTSSpec() { state.backtracking++; int start = input.mark(); try { synpred1_InternalTSSpec_fragment(); // can never throw exception } catch (RecognitionException re) { System.err.println("impossible: "+re); } boolean success = !state.failed; input.rewind(start); state.backtracking--; state.failed=false; return success; } public static final BitSet FOLLOW_1 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_2 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_3 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_4 = new BitSet(new long[]{0x0000000000246032L}); public static final BitSet FOLLOW_5 = new BitSet(new long[]{0x0000000000000022L}); public static final BitSet FOLLOW_6 = new BitSet(new long[]{0x0000000000246010L}); public static final BitSet FOLLOW_7 = new BitSet(new long[]{0x0000000000018000L}); public static final BitSet FOLLOW_8 = new BitSet(new long[]{0x0000000000010000L}); public static final BitSet FOLLOW_9 = new BitSet(new long[]{0x0000000001020030L}); public static final BitSet FOLLOW_10 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_11 = new BitSet(new long[]{0x0000000000100030L}); public static final BitSet FOLLOW_12 = new BitSet(new long[]{0x0000000000400000L}); public static final BitSet FOLLOW_13 = new BitSet(new long[]{0x0000000000000030L}); public static final BitSet FOLLOW_14 = new BitSet(new long[]{0x0000000000800000L}); public static final BitSet FOLLOW_15 = new BitSet(new long[]{0x00000000000000E0L}); public static final BitSet FOLLOW_16 = new BitSet(new long[]{0x0000000001000030L}); public static final BitSet FOLLOW_17 = new BitSet(new long[]{0x0000000000800002L}); public static final BitSet FOLLOW_18 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_19 = new BitSet(new long[]{0x0000000012000002L}); public static final BitSet FOLLOW_20 = new BitSet(new long[]{0x000000000C000000L}); public static final BitSet FOLLOW_21 = new BitSet(new long[]{0x0000000010000002L}); public static final BitSet FOLLOW_22 = new BitSet(new long[]{0x0000000120020010L}); public static final BitSet FOLLOW_23 = new BitSet(new long[]{0x0000000100020010L}); public static final BitSet FOLLOW_24 = new BitSet(new long[]{0x0000000040080000L}); public static final BitSet FOLLOW_25 = new BitSet(new long[]{0x0000000001100030L}); public static final BitSet FOLLOW_26 = new BitSet(new long[]{0x0000000040000000L}); public static final BitSet FOLLOW_27 = new BitSet(new long[]{0x0000000081000030L}); public static final BitSet FOLLOW_28 = new BitSet(new long[]{0x0000000100000010L}); public static final BitSet FOLLOW_29 = new BitSet(new long[]{0x0000000200000002L}); }
true
7ca9ca67377318e47a07d256505b9058748e47d8
Java
JohnVeZh/mgr
/src/main/java/cn/sparke/modules/system/log/controller/LoginLogController.java
UTF-8
1,826
1.992188
2
[]
no_license
package cn.sparke.modules.system.log.controller; import com.github.pagehelper.Page; import cn.sparke.core.common.constants.Const; import cn.sparke.core.common.controller.BaseController; import cn.sparke.core.modules.log.annotation.BussinessLog; import cn.sparke.core.modules.mybatis.bean.PageInfo; import cn.sparke.core.modules.shiro.annotation.Permission; import cn.sparke.modules.system.log.entity.LoginLog; import cn.sparke.modules.system.log.mapper.LoginLogMapper; import cn.sparke.modules.system.log.wrapper.LogWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * 日志管理的控制器 * * @author spark * @Date 2017年4月5日 19:45:36 */ @Controller @RequestMapping("/system/loginLog") public class LoginLogController extends BaseController { private static String PREFIX = "/system/log/"; @Autowired private LoginLogMapper loginLogMapper; /** * 跳转到日志管理的首页 */ @RequestMapping("") public String index() { return PREFIX + "login_log.html"; } /** * 查询登录日志列表 */ @RequestMapping("/list") @Permission(Const.ADMIN_NAME) @ResponseBody public Object list(LoginLog loginLog) { Page page = loginLogMapper.findList(loginLog); return new PageInfo<>((List<LoginLog>) new LogWrapper(page.getResult()).warp(), page.getTotal()); } /** * 清空日志 */ @BussinessLog("清空登录日志") @RequestMapping("/delLoginLog") @Permission(Const.ADMIN_NAME) @ResponseBody public Object delLog() { return super.SUCCESS_TIP; } }
true
7374489ecd54cdf02bfba8bd5632737312aa50fc
Java
Pratik32/GoogleDriveUpload
/src/main/drive/Uploader.java
UTF-8
9,541
2.984375
3
[]
no_license
package main.drive; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Created by ps on 29/11/17. * A simple uploader class that takes a folder/file as an argument * and uploads them to your google drive.Google drive's client library is not * used here as I feel they are very heavy and poorly documented. * Here we are straight-forward making http/https calls to specified endpoints * and getting the job done. */ public class Uploader { public static final String UPLOAD_URI="https://www.googleapis.com/upload/drive/v3/files/?uploadType=resumable"; public static final int OK=200; public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); Authenticator authenticator=new Authenticator(); Uploader uploader=new Uploader(); if(args.length==0){ return; } if(args[0].equals("-config")) { System.out.println("CLIENT ID:"); String id = sc.next(); System.out.println("CLIENT SECRET:"); String secret = sc.next(); Authenticator.setUserCredentials(id, secret); System.out.println("Credentials set successfully."); }else if(args[0].equals("-r")){ File file=new File(args[1]); if (file.exists()) { if (!file.isDirectory()) { System.out.println(file.getName() + " is not a directory"); uploader.usage(); return; } String accesstoken = authenticator.getAccessToken(); String dirname = file.getName(); String dirid = uploader.createFolder(accesstoken, "root", dirname); for (File f : file.listFiles()) { if (f.isDirectory()) { System.out.println(f.getName() + " is a directory."); uploader.usage(); return; } System.out.println("uploading " + f.getName() + "..."); String uploadurl = uploader.getLocationUrl(accesstoken, f, dirid); int status = uploader.upload(f, uploadurl, accesstoken); if (status == OK) { System.out.println("Uploaded."); } else { System.out.println("Error uploading file."); } } }else{ System.out.println(file.getName()+" Does not exists."); } }else{ for(String str:args){ File file=new File(str); if (file.exists()) { if (file.isDirectory()){ uploader.usage(); return; } System.out.println("uploading " + file.getName() + "..."); String accesscode = authenticator.getAccessToken(); String uploadurl = uploader.getLocationUrl(accesscode, file, "root"); int status = uploader.upload(file, uploadurl, accesscode); if (status == OK) { System.out.println("Uploaded."); } else { System.out.println("Error uploading file."); } }else{ System.out.println(file.getName()+" does not exists."); } } } } /* The 'Content-Type' header is optional,drive detects it automatically. */ private int upload(File file,String uploadurl,String accesscode){ HttpsURLConnection conn=null; int responsecode=-1; Map<String,String> headers=new HashMap<String, String>(); headers.put("Content-Type",getMIMEType(file)); headers.put("Content-Length",Integer.toString((int)file.length())); headers.put("Authorization","Bearer "+accesscode); conn=buildHttpsConnection(uploadurl,headers,"PUT",null,file); try { conn.connect(); responsecode=conn.getResponseCode(); }catch (IOException e){ } return responsecode; } /* Get the location url of given file,for uploading the data. */ private String getLocationUrl(String accesstoken,File file,String id){ String body="{\"name\": \""+file.getName()+"\",\"parents\": [\""+id+"\"]}"; //System.out.println(body); Map<String,String> headers=new HashMap<String, String>(); headers.put("Authorization","Bearer "+accesstoken); headers.put("X-Upload-Content-Type",getMIMEType(file)); headers.put("X-Upload-Content-Length",Integer.toString((int) file.length())); headers.put("Content-Type","application/json; charset=UTF-8"); headers.put("Content-Length",Integer.toString(body.length())); HttpsURLConnection conn=buildHttpsConnection(UPLOAD_URI,headers,"POST",body,null); try { conn.connect(); //System.out.println(conn.getResponseCode()); }catch (IOException e){ } String uploadurl=conn.getHeaderField("Location"); //System.out.println(uploadurl); return uploadurl; } private String createFolder(String accesstoken,String rootfolder,String foldername) throws IOException { String id=""; String body="{\"name\": \""+foldername+"\",\"mimeType\": \"application/vnd.google-apps.folder\",\"parents\": [\""+rootfolder+"\"]}"; //System.out.println(body); Map<String,String> headers=new HashMap<String, String>(); headers.put("Authorization","Bearer "+accesstoken); headers.put("Content-Length",Integer.toString(body.length())); headers.put("Content-Type","application/json; charset=UTF-8"); String url="https://www.googleapis.com/drive/v3/files"; HttpsURLConnection conn=buildHttpsConnection(url,headers,"POST",body,null); conn.connect(); //System.out.println(conn.getResponseCode()); BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream())); String temp[]=getValuesForKeys(reader,"id",null); id=temp[0]; return id; } public static String[] getValuesForKeys(BufferedReader reader, String key1,String key2) throws IOException { String str = null; String value1 = ""; String value2 = ""; while ((str = reader.readLine()) != null) { //System.out.println(str); if (key1!=null && str.contains("\"" + key1 + "\"")) { int start = str.indexOf(':'); int end=str.lastIndexOf("\""); value1 = str.substring(start + 3,end); }else if(key2!=null && str.contains("\""+key2+"\"")){ int temp=str.indexOf(':'); value2=str.substring(temp+3,str.length()-2); } } String[] tokens={value1,value2}; return tokens; } /* Build a Http/Https request with given 'url'.and headers in 'headers' map. 'body' and 'file' are optional arguments may not be present all the time. */ public static HttpsURLConnection buildHttpsConnection(String url,Map<String,String> headers,String method,String body,File file){ HttpsURLConnection conn=null; try { URL url1 = new URL(url); conn = (HttpsURLConnection)url1.openConnection(); conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); if (headers!=null) { for (Map.Entry<String, String> e : headers.entrySet()) { conn.setRequestProperty(e.getKey(), e.getValue()); } } if (body!=null) { OutputStream stream = conn.getOutputStream(); stream.write(body.getBytes()); stream.close(); } if (file!=null){ ByteArrayOutputStream stream=new ByteArrayOutputStream(); FileInputStream stream1=new FileInputStream(file); int temp; while((temp=stream1.read())!=-1){ stream.write((byte)temp); } OutputStream stream2=conn.getOutputStream(); stream2.write(stream.toByteArray()); stream2.close(); } }catch(IOException e){ } return conn; } private String getMIMEType(File file){ String type=""; try { InputStream is = new FileInputStream(file); type= URLConnection.guessContentTypeFromStream(is); if (type==null){ type=URLConnection.guessContentTypeFromName(file.getName()); } //System.out.println("Type:="+type); }catch (FileNotFoundException e){ } catch (IOException e) { e.printStackTrace(); } return type; } private void usage(){ System.out.println("Usage:\n"+"for uploading directories: java -jar uploader.jar " + "-r <dirname>\n"+"for uploading individual files: java -jar uploader.jar"+ "<file1> <file2> ... <fileN>"); } }
true
889fef56df78df47f9782c33cedcd7d60e934677
Java
zoumhussein/RooTrackerApp
/SVI-Tickets/src/main/java/fr/leburcom/svi/tickets/TicketStatus.java
UTF-8
137
1.65625
2
[]
no_license
package fr.leburcom.svi.tickets; public enum TicketStatus { OPEN, IN_DIAGNOSTIC, IN_DELIVERY, REJECTED, RESOLVED; }
true
88b96d74ff2fa3ef736d3d2bec9ad4b8f52b9580
Java
JimmyChavada/Computer-Science-2020
/Creating our own methods/src/AreaOfCircle.java
UTF-8
1,714
4.28125
4
[]
no_license
import javax.swing.JOptionPane; /** * */ /** * @author Jimmy Chavada * Date: oct 2020 * Description: Calculates the area of a circle * allows for us to not reuse the code, instead allows us to use the calcArea to bring * the code inside. upper case is always class, lower case is function. */ public class AreaOfCircle { public static double calcArea(double radius) { final double PI = 3.14259; // to make constant double area; area = PI * Math.pow(radius, 2); // calculates the area return area; // returns the area that is a double, therefore gives back double removes error } /** * @param args */ public static void main(String[] args) { // declare variables for radius and area double r, a; String unit = ""; // prompt user for radius // convert string into double (can use IO.java) r = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the radius for the first circle!")); unit = JOptionPane.showInputDialog(null, "Enter the unit of measurment for the radius"); // calculate user inputed radius for area of circle from the function made a = calcArea(r); // display the area of the circle JOptionPane.showMessageDialog(null, "The area of the first circle is " + a + unit + "^2"); // prompt for radius of another circle r = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the radius for the second circle!")); unit = JOptionPane.showInputDialog(null, "Enter the unit of measurment for the radius"); // calc the area of the second circle a = calcArea(r); // display the area of the second circle JOptionPane.showMessageDialog(null, "The area of the second circle is " + a + unit + "^2"); } }
true
75da82508a4bf7d0c8ae1e87d4b76721bd90fe06
Java
sunnnydaydev/DesignPatterns
/src/pattern_adapter/source/HomePowerSocket.java
UTF-8
225
2.328125
2
[]
no_license
package pattern_adapter.source; /** * Create by SunnyDay 2022/11/20 11:02:48 * 适配者 **/ public class HomePowerSocket { public void outPut(){ System.out.println("家庭电源插座输出220V电"); } }
true