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
63ef911add43abfc008b31d162f201c5c97c9a56
Java
aksingla009/RoomPOCinJAVAContactsApp
/app/src/main/java/com/db/roompoc/contactmanager/db/ContactsAppDB.java
UTF-8
329
1.960938
2
[]
no_license
package com.db.roompoc.contactmanager.db; import androidx.room.Database; import androidx.room.RoomDatabase; import com.db.roompoc.contactmanager.db.entity.Contact; @Database(entities = {Contact.class}, version = 1) public abstract class ContactsAppDB extends RoomDatabase { public abstract ContactDAO getContactDAO(); }
true
42c4f428ba3fdc4504d540e47e4ec0c3525c8085
Java
kevenyang/SwipeExpandableListView
/app/src/main/java/com/example/root/testswipeexpandablelistview/ViewUtil.java
UTF-8
701
2.46875
2
[]
no_license
package com.example.root.testswipeexpandablelistview; import android.view.View; import android.view.ViewGroup; /** * Created by hxyan_000 on 2016/7/2. */ public class ViewUtil { public static void setEntireViewClickable(View view, boolean clickable) { if (view == null) { return; } view.setClickable(clickable); if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup)view; for (int i = 0; i < viewGroup.getChildCount(); i++) { View childView = viewGroup.getChildAt(i); setEntireViewClickable(childView, clickable); } } } }
true
de1922894e666a6218b3a1c8058dca78df6a66e3
Java
landfill-eforms/landfill-web-app
/server/src/main/java/org/lacitysan/landfill/server/persistence/entity/report/ScheduledReportQuery.java
UTF-8
1,126
2.03125
2
[]
no_license
package org.lacitysan.landfill.server.persistence.entity.report; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.lacitysan.landfill.server.persistence.entity.scheduled.ScheduledReport; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * @author Alvin Quach */ @Entity @Table(name="dbo.ScheduledReportQueries") @PrimaryKeyJoinColumn(name="ReportQueryFK") @JsonInclude(Include.NON_NULL) public class ScheduledReportQuery extends ReportQuery { @JsonIgnore @Cascade(CascadeType.ALL) @ManyToOne @JoinColumn(name="ScheduledReportFK") private ScheduledReport scheduledReport; public ScheduledReport getScheduledReport() { return scheduledReport; } public void setScheduledReport(ScheduledReport scheduledReport) { this.scheduledReport = scheduledReport; } }
true
1c72b7f8452622dc2b5d7efad526a145ca0c1c6a
Java
xxadi/mednisoa
/src/main/java/com/medsys/nis/maintain/service/LoginService.java
UTF-8
206
1.570313
2
[]
no_license
package com.medsys.nis.maintain.service; import com.medsys.nis.maintain.bean.User; /** * Created by Super on 2020/8/10. */ public interface LoginService { User getUserByName(String getMapByName); }
true
af22bcd7a75b41b5c6e09405801870656d096242
Java
allenkkl1998/PlatiniumProject
/FioreFlowershopSystem/src/Domain/Promotion.java
UTF-8
4,857
2.046875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Domain; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; /** * * @author AL */ @Entity @Table(name = "PROMOTION") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Promotion.findAll", query = "SELECT p FROM Promotion p") , @NamedQuery(name = "Promotion.findByPromotionname", query = "SELECT p FROM Promotion p WHERE p.promotionname = :promotionname") , @NamedQuery(name = "Promotion.findByPromotionmonth", query = "SELECT p FROM Promotion p WHERE p.promotionmonth = :promotionmonth") , @NamedQuery(name = "Promotion.findByPromotiondetail", query = "SELECT p FROM Promotion p WHERE p.promotiondetail = :promotiondetail") , @NamedQuery(name = "Promotion.findByPromotiontc", query = "SELECT p FROM Promotion p WHERE p.promotiontc = :promotiontc")}) public class Promotion implements Serializable { @Transient private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "PROMOTIONNAME") private String promotionname; @Column(name = "PROMOTIONMONTH") private String promotionmonth; @Column(name = "PROMOTIONDETAIL") private String promotiondetail; @Column(name = "PROMOTIONTC") private String promotiontc; public Promotion() { } public Promotion(String promotionname) { this.promotionname = promotionname; } public Promotion(String promotionname,String promotionmonth,String promotiondetail,String promotiontc) { this.promotionname = promotionname; this.promotionmonth = promotionmonth; this.promotiondetail = promotiondetail; this.promotiontc = promotiontc; } public String getPromotionname() { return promotionname; } public void setPromotionname(String promotionname) { String oldPromotionname = this.promotionname; this.promotionname = promotionname; changeSupport.firePropertyChange("promotionname", oldPromotionname, promotionname); } public String getPromotionmonth() { return promotionmonth; } public void setPromotionmonth(String promotionmonth) { String oldPromotionmonth = this.promotionmonth; this.promotionmonth = promotionmonth; changeSupport.firePropertyChange("promotionmonth", oldPromotionmonth, promotionmonth); } public String getPromotiondetail() { return promotiondetail; } public void setPromotiondetail(String promotiondetail) { String oldPromotiondetail = this.promotiondetail; this.promotiondetail = promotiondetail; changeSupport.firePropertyChange("promotiondetail", oldPromotiondetail, promotiondetail); } public String getPromotiontc() { return promotiontc; } public void setPromotiontc(String promotiontc) { String oldPromotiontc = this.promotiontc; this.promotiontc = promotiontc; changeSupport.firePropertyChange("promotiontc", oldPromotiontc, promotiontc); } @Override public int hashCode() { int hash = 0; hash += (promotionname != null ? promotionname.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Promotion)) { return false; } Promotion other = (Promotion) object; if ((this.promotionname == null && other.promotionname != null) || (this.promotionname != null && !this.promotionname.equals(other.promotionname))) { return false; } return true; } @Override public String toString() { return "Domain.Promotion[ promotionname=" + promotionname + " ]"; } public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } }
true
26e84c7dc6c17c9a7f7388bd1edcdd4bbab11ccc
Java
IngevanZetten/Schoolreview
/Datalayer/BeoordelingDAO.java
UTF-8
2,919
2.875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Datalayer; import Model.Beoordeling; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; /** * Klasse die zorgt voor de opdrachten naar de database die horen bij het object * Beoordeling. * * @author Inge */ public class BeoordelingDAO { dbConnector dbConnector = new dbConnector(); /** * Voegt een beoordeling toe aan de database. * * @param beoordeling Beoordeling object die toegevoegd moet worden aan de * database */ public boolean voegBeoordelingToe(Beoordeling beoordeling) { Connection conn = null; Beoordeling rprt = beoordeling; String categorie = rprt.getBeoordelingscategorie(); double score = rprt.getScore(); String school = rprt.getSchoolnaam(); try { conn = dbConnector.connect(); Statement statement = conn.createStatement(); String sql = "INSERT INTO beoordeling (beoordelingscategorie, sterscore, schoolnaam) VALUES('" + categorie + "'," + score + ",'" + school + "')"; statement.executeUpdate(sql); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Haalt gemiddelde scores per beoordelingscategorie op uit de database en * zet deze in een hashmap. * * @param schoolnaam Naam van de school waarvan de gemiddelde scores per * categorie gevraagd worden. * @return HashMap String, Double. HashMap die alle categorieën en * bijbehorende gemiddelde scores bevat die opgehaald zijn uit de database. */ public HashMap<String, Double> geefScores(String schoolnaam) { Connection conn = null; ResultSet resultSet; HashMap<String, Double> scores = new HashMap<>(); try { conn = dbConnector.connect(); Statement statement = conn.createStatement(); String sql = "SELECT beoordelingscategorie, AVG(sterscore) FROM `beoordeling` WHERE schoolnaam = '" + schoolnaam + "'" + " GROUP BY beoordelingscategorie"; if (statement.execute(sql)) { resultSet = statement.getResultSet(); while (resultSet.next()) { String cat = resultSet.getString("beoordelingscategorie"); double gemscore = resultSet.getDouble("AVG(sterscore)"); scores.put(cat, gemscore); } } } catch (Exception e) { e.printStackTrace(); } return scores; } }
true
89cb8a889467ad239337e7f5b0e8fbfa9850b465
Java
leaderrun-wms/event-model
/src/main/java/com/leaderrun/eventmodel/so/v1/SOReceived.java
UTF-8
379
1.773438
2
[]
no_license
package com.leaderrun.eventmodel.so.v1; import java.util.Date; import lombok.Data; /** * 从货代收到一个SO同步报文 * * @author kmtong * */ @Data public class SOReceived { final public static String TYPE = "so.received"; final public static String VERSION = "1.0"; final String customerCode; final String so; final Date receivedAt; final byte[] raw; }
true
6722c6af158ba5527193f0e4cf5dcc7c8555f916
Java
dbrack/yass
/java/yass/main/ch/softappeal/yass/transport/PathSerializer.java
UTF-8
708
2.359375
2
[ "BSD-3-Clause" ]
permissive
package ch.softappeal.yass.transport; import ch.softappeal.yass.serialize.Reader; import ch.softappeal.yass.serialize.Serializer; import ch.softappeal.yass.serialize.Writer; /** * Writes path as an {@link Integer}. */ public final class PathSerializer implements Serializer { public static final Integer DEFAULT = 0; private PathSerializer() { // disable } @Override public Object read(final Reader reader) throws Exception { return reader.readInt(); } @Override public void write(final Object value, final Writer writer) throws Exception { writer.writeInt((Integer)value); } public static final Serializer INSTANCE = new PathSerializer(); }
true
d49e6da5a3b653f6f7f206f45ccb44c833ed4111
Java
yyh910214/timetable
/temp/timetable/src/main/java/com/naver/timetable/dao/UrlDAO.java
UTF-8
726
1.679688
2
[]
no_license
/* * @(#)UrlDAO.java $version 2014. 8. 6. * * Copyright 2007 NHN Corp. All rights Reserved. * NAVER Corp. PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.naver.timetable.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.ibatis.SqlMapClientTemplate; import org.springframework.stereotype.Repository; /** * @author younghan */ @Repository public class UrlDAO { @Autowired @Qualifier("hufsCubrid") SqlMapClientTemplate hufsCubrid; public List<String> getAllParam() { return hufsCubrid.queryForList("getAllParam"); } }
true
b73c9bc64f6abfef4a965fb8844fd89f1cf8820e
Java
it-academy-osh/JavaTutorials
/src/com/company/ArrayExplanation.java
UTF-8
834
3.578125
4
[]
no_license
package com.company; import java.io.*; import java.util.*; public class ArrayExplanation { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 7; i++){ numbers.add(i); } for (int i: numbers) { System.out.print(i + " "); } for (int i = 0; i < numbers.size(); i++) { if (i == numbers.size() - 1) { i = 0; } else if(numbers.size() == 1){ break; } else{ numbers.remove(i); System.out.println("\ndeleted: " + numbers.get(i)); } } System.out.println(); for (int i: numbers) { System.out.print(i + " "); } } }
true
0c157857450ff6f30e7376a041cd828a5281725c
Java
K56Flex/StopApp
/app/src/main/java/com/sscience/stopapp/util/ShortcutsManager.java
UTF-8
3,535
2.296875
2
[]
no_license
package com.sscience.stopapp.util; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutInfo; import android.content.pm.ShortcutManager; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Icon; import android.os.Build; import com.science.myloggerlibrary.MyLogger; import com.sscience.stopapp.activity.ShortcutActivity; import com.sscience.stopapp.bean.AppInfo; import java.util.ArrayList; import java.util.List; import static com.sscience.stopapp.activity.ShortcutActivity.EXTRA_PACKAGE_NAME; /** * @author SScience * @description * @email chentushen.science@gmail.com * @data 2017/2/7 */ public class ShortcutsManager { private Context mContext; private ShortcutManager mShortcutManager; public ShortcutsManager(Context context) { mContext = context; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { mShortcutManager = context.getSystemService(ShortcutManager.class); } } public void addShortcut(AppInfo appInfo) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { List<ShortcutInfo> shortcutList = mShortcutManager.getDynamicShortcuts(); if (shortcutList.size() == 3) { ShortcutInfo shortcutInfo = shortcutList.get(1); removeShortcut(shortcutInfo.getId()); shortcutList.remove(shortcutInfo); MyLogger.e("shortcut最多显示4个"); } for (ShortcutInfo info : shortcutList) { if (appInfo.getAppPackageName().equals(info.getId())) { MyLogger.e("已经存在的shortcut:" + info.getId()); return; } } ShortcutInfo shortcut = new ShortcutInfo.Builder(mContext, appInfo.getAppPackageName()) .setShortLabel(appInfo.getAppName()) .setIcon(Icon.createWithBitmap(((BitmapDrawable) appInfo.getAppIcon()).getBitmap())) .setIntent( new Intent(ShortcutActivity.OPEN_APP_SHORTCUT) .putExtra(EXTRA_PACKAGE_NAME, appInfo.getAppPackageName()) // this dynamic shortcut set up a back stack using Intents, when pressing back, will go to MainActivity // the last Intent is what the shortcut really opened // new Intent[]{ // new Intent(Intent.ACTION_MAIN, Uri.EMPTY, mContext, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK), // new Intent(AppListActivity.ACTION_OPEN_DYNAMIC) // // intent's action must be set // } ) .build(); shortcutList.add(shortcut); mShortcutManager.setDynamicShortcuts(shortcutList); } } public void disableShortcut(String shortcutID) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { List<String> list = new ArrayList<>(); list.add(shortcutID); mShortcutManager.disableShortcuts(list); } } public void removeShortcut(String shortcutID) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { List<String> list = new ArrayList<>(); list.add(shortcutID); mShortcutManager.removeDynamicShortcuts(list); } } }
true
aae778ba84b92ab3cb5d9601a87b71bf02246ce5
Java
servicecatalog/development
/oscm-domainobjects/javasrc/org/oscm/domobjects/ModifiedUdaData.java
UTF-8
2,232
1.875
2
[ "Apache-2.0", "EPL-1.0", "BSD-3-Clause", "W3C", "LGPL-3.0-only", "CPL-1.0", "CDDL-1.1", "BSD-2-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.1-or-later", "CDDL-1.0", "Apache-1.1", "MIT", "LicenseRef-scancode-unknown-license-reference", "W3C-19980720", "LGPL-2.1-only", "...
permissive
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: 2013-12-5 * *******************************************************************************/ package org.oscm.domobjects; import javax.persistence.*; import org.oscm.domobjects.converters.METConverter; import org.oscm.domobjects.enums.ModifiedEntityType; /** * Data container for the domain object <code>ModifiedUda</code>. * * @author Zhou */ @Embeddable public class ModifiedUdaData extends DomainDataContainer { private static final long serialVersionUID = -4968210541500748628L; @Column(nullable = false) private long targetObjectKey; private String value; @Convert( converter=METConverter.class ) @Column(nullable = false) private ModifiedEntityType targetObjectType; @Column(nullable = false) private long subscriptionKey; @Column(nullable = false) private boolean encrypted; public long getTargetObjectKey() { return targetObjectKey; } public void setTargetObjectKey(long targetObjectKey) { this.targetObjectKey = targetObjectKey; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public ModifiedEntityType getTargetObjectType() { return targetObjectType; } public void setTargetObjectType(ModifiedEntityType targetObjectType) { this.targetObjectType = targetObjectType; } public long getSubscriptionKey() { return subscriptionKey; } public void setSubscriptionKey(long subscriptionKey) { this.subscriptionKey = subscriptionKey; } public boolean isEncrypted() { return encrypted; } public void setEncrypted(boolean encrypted) { this.encrypted = encrypted; } }
true
49cbd6990714baee360e0ab36bd99d91a176c1b2
Java
kjrsoftwareservices/clms
/src/com/Ntranga/core/CLMS/entities/TimeRuleWorkDayStatus.java
UTF-8
5,907
1.992188
2
[]
no_license
package com.Ntranga.core.CLMS.entities; // Generated 25 Jul, 2016 12:05:41 PM by Hibernate Tools 3.6.0 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * TimeRuleWorkDayStatus generated by hbm2java */ @SuppressWarnings("serial") @Entity @Table(name="time_rule_work_day_status" ) public class TimeRuleWorkDayStatus implements java.io.Serializable { private Integer dayStatusId; private TimeRulesDetails timeRulesDetails; private String fromHours; private String toHours; private String statusDescription; private String statusCode; private String isActive; private int customerId; private int companyId; private Date transactionDate; private int sequenceId; private int createdBy; private Date createdDate; private int modifiedBy; private Date modifiedDate; public TimeRuleWorkDayStatus() { } public TimeRuleWorkDayStatus(TimeRulesDetails timeRulesDetails, String fromHours, String toHours, String statusDescription, String statusCode, String isActive, int customerId, int companyId, Date transactionDate, int sequenceId, int createdBy, Date createdDate, int modifiedBy, Date modifiedDate) { this.timeRulesDetails = timeRulesDetails; this.fromHours = fromHours; this.toHours = toHours; this.statusDescription = statusDescription; this.statusCode = statusCode; this.isActive = isActive; this.customerId = customerId; this.companyId = companyId; this.transactionDate = transactionDate; this.sequenceId = sequenceId; this.createdBy = createdBy; this.createdDate = createdDate; this.modifiedBy = modifiedBy; this.modifiedDate = modifiedDate; } @Id @GeneratedValue(strategy=IDENTITY) @Column(name="Day_Status_Id", unique=true, nullable=false) public Integer getDayStatusId() { return this.dayStatusId; } public void setDayStatusId(Integer dayStatusId) { this.dayStatusId = dayStatusId; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="Time_Rule_Id", nullable=false) public TimeRulesDetails getTimeRulesDetails() { return this.timeRulesDetails; } public void setTimeRulesDetails(TimeRulesDetails timeRulesDetails) { this.timeRulesDetails = timeRulesDetails; } @Column(name="From_Hours", nullable=false, length=45) public String getFromHours() { return this.fromHours; } public void setFromHours(String fromHours) { this.fromHours = fromHours; } @Column(name="To_Hours", nullable=false, length=45) public String getToHours() { return this.toHours; } public void setToHours(String toHours) { this.toHours = toHours; } @Column(name="Status_Description", nullable=false, length=45) public String getStatusDescription() { return this.statusDescription; } public void setStatusDescription(String statusDescription) { this.statusDescription = statusDescription; } @Column(name="Status_Code", nullable=false, length=45) public String getStatusCode() { return this.statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } @Column(name="Is_Active", nullable=false, length=2) public String getIsActive() { return this.isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } @Column(name="Customer_Id", nullable=false) public int getCustomerId() { return this.customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } @Column(name="Company_Id", nullable=false) public int getCompanyId() { return this.companyId; } public void setCompanyId(int companyId) { this.companyId = companyId; } @Temporal(TemporalType.DATE) @Column(name="Transaction_Date", nullable=false, length=10) public Date getTransactionDate() { return this.transactionDate; } public void setTransactionDate(Date transactionDate) { this.transactionDate = transactionDate; } @Column(name="Sequence_Id", nullable=false) public int getSequenceId() { return this.sequenceId; } public void setSequenceId(int sequenceId) { this.sequenceId = sequenceId; } @Column(name="Created_By", nullable=false) public int getCreatedBy() { return this.createdBy; } public void setCreatedBy(int createdBy) { this.createdBy = createdBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name="Created_Date", nullable=false, length=19) public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Column(name="Modified_By", nullable=false) public int getModifiedBy() { return this.modifiedBy; } public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name="Modified_Date", nullable=false, length=19) public Date getModifiedDate() { return this.modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } }
true
1606e30a8f08c7b6d233180acf80269cddd8b13b
Java
Claymoreman/SpringBoot-thymeleaf-BootStrap-
/src/main/java/com/nuc/zbd1913041440_exp_6/service/impl/ZbdUserServiceImpl.java
UTF-8
1,309
2.03125
2
[]
no_license
package com.nuc.zbd1913041440_exp_6.service.impl; import com.nuc.zbd1913041440_exp_6.entity.zbdUser; import com.nuc.zbd1913041440_exp_6.mapper.zbdUserMapper; import com.nuc.zbd1913041440_exp_6.service.zbdUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ZbdUserServiceImpl implements zbdUserService { @Autowired zbdUserMapper userMapper; @Override public zbdUser login(String userName, String password) { return userMapper.login(userName,password); } @Override public Integer register(String userName, String password, Integer status) { return userMapper.register(userName,password,status); } @Override public List<zbdUser> findAllUsers() { return userMapper.findAllUsers(); } @Override public boolean addUser(zbdUser zbdUser) { return userMapper.addUser(zbdUser); } @Override public Integer delUser(Integer id) { return userMapper.delUser(id); } @Override public Integer setUser(zbdUser zbdUser) { return userMapper.setUser(zbdUser); } @Override public List<zbdUser> findUser(String text) { return userMapper.findUser(text); } }
true
692d4e90b79dc123a123f19b2304c58797d8d332
Java
pharosnet/vertx-pg-dal
/src/main/java/org/pharosnet/vertx/pg/dal/core/ExecBatchBuilder.java
UTF-8
231
1.734375
2
[ "Apache-2.0" ]
permissive
package org.pharosnet.vertx.pg.dal.core; import io.vertx.sqlclient.Tuple; import java.util.List; public interface ExecBatchBuilder<T> { String query(); List<Tuple> args(); ExecBatchBuilder build(List<T> rows); }
true
036d54a4e6ed08c19b96d1b531f9a9c8574d2359
Java
BinSlashBash/xcrumby
/src/com/google/android/gms/internal/jw.java
UTF-8
981
1.695313
2
[]
no_license
package com.google.android.gms.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; public final class jw implements SafeParcelable { public static final Parcelable.Creator<jw> CREATOR = new jx(); String adq; String description; private final int xH; jw() { this.xH = 1; } jw(int paramInt, String paramString1, String paramString2) { this.xH = paramInt; this.adq = paramString1; this.description = paramString2; } public int describeContents() { return 0; } public int getVersionCode() { return this.xH; } public void writeToParcel(Parcel paramParcel, int paramInt) { jx.a(this, paramParcel, paramInt); } } /* Location: /home/dev/Downloads/apk/dex2jar-2.0/crumby-dex2jar.jar!/com/google/android/gms/internal/jw.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
4f30fa2a31062ac41dcfd6a7a3770f1eb0f2c173
Java
MrX13415/amplifire
/AudioPlayer/src/net/icelane/amplifire/player/listener/PlaylistIndexChangeEvent.java
UTF-8
671
2.40625
2
[ "MIT" ]
permissive
package net.icelane.amplifire.player.listener; import net.icelane.amplifire.player.AudioPlaylist; /** * amplifier - Audio-Player Project * * @author Oliver Daus * */ public class PlaylistIndexChangeEvent extends PlaylistEvent{ protected int previousIndex; protected int newIndex; public PlaylistIndexChangeEvent(AudioPlaylist source, int previousIndex, int newIndex) { super(source, null); this.previousIndex = previousIndex; this.newIndex = newIndex; } public int getPriorIndex() { return previousIndex; } public int getNewIndex() { return newIndex; } }
true
aa72e4d6a30d1ddc4a4a2bf97dc76d4e6cc28cb8
Java
SamuelOsuna/reservasGraphql
/src/main/java/com/samuel/reservasServidorGraphql/dao/KeyDao.java
UTF-8
291
1.585938
2
[]
no_license
package com.samuel.reservasServidorGraphql.dao; import com.samuel.reservasServidorGraphql.model.Key; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface KeyDao extends JpaRepository<Key, Integer> { }
true
e07b80774becf160062495b207bfeb6b80556044
Java
RomaniEzzatYoussef/Exercises
/Kevin_G_Exercises/Chapter_03_Selections/Programming_Exercise_31.java
UTF-8
971
4.25
4
[]
no_license
package Chapter_03_Selections; import java.util.Scanner; /** * Financials: currency exchange * Write a program that prompts the user to enter the exchange rate from currency in U.S. dollars to Chinese RMB. * Prompt the user to enter 0 to convert from U.S. dollars to Chinese RMB and 1 to convert from Chinese RMB and U.S. dollars. * Prompt the user to enter the amount in U.S. dollars or Chinese RMB to convert it to Chinese RMB or U.S. dollars, respectively. * * 08/06/2016 * @author kevgu * */ public class Programming_Exercise_31 { public static void main(String[] args) { Scanner input = new Scanner(System.in); double currency; int exchange; System.out.print("Enter the currency amount: "); currency = input.nextDouble(); System.out.print("Enter the type of exchange 0 || 1"); exchange = input.nextInt(); if (exchange == 0) System.out.print(currency * 8); else System.out.print(currency / 8); input.close(); } }
true
0869ad40552e4a6ed5ef32e242cca704b1a3ae1f
Java
MewX/kantv-decompiled-v3.1.2
/sources/org/seamless/util/RandomToken.java
UTF-8
1,063
3.015625
3
[]
no_license
package org.seamless.util; import java.security.SecureRandom; import java.util.Random; public class RandomToken { protected final Random random; public RandomToken() { try { this.random = SecureRandom.getInstance("SHA1PRNG", "SUN"); this.random.nextBytes(new byte[1]); } catch (Exception e) { throw new RuntimeException(e); } } public String generate() { String str = null; while (true) { if (str != null && str.length() != 0) { return str; } long nextLong = this.random.nextLong(); if (nextLong < 0) { nextLong = -nextLong; } long nextLong2 = this.random.nextLong(); if (nextLong2 < 0) { nextLong2 = -nextLong2; } StringBuilder sb = new StringBuilder(); sb.append(Long.toString(nextLong, 36)); sb.append(Long.toString(nextLong2, 36)); str = sb.toString(); } } }
true
20a59f85efd2d1bbb40bf18e064af8816533eb9f
Java
soakaqua/petSittingV6
/src/main/java/petSitting/frontBoot/controller/SitterController3.java
UTF-8
1,427
1.726563
2
[]
no_license
package petSitting.frontBoot.controller; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import petSitting.frontBoot.model.Annonce; import petSitting.frontBoot.model.Compte; import petSitting.frontBoot.model.Reponse; import petSitting.frontBoot.model.ReponsePK; import petSitting.frontBoot.model.Sitter; import petSitting.frontBoot.repositories.AnnonceRepository; import petSitting.frontBoot.repositories.CompteRepository; import petSitting.frontBoot.repositories.ReponseRepository; import petSitting.frontBoot.services.ReponseService; import petSitting.frontBoot.services.SitterService; @Controller public class SitterController3 { @GetMapping("sitter/ficheSitter") // a changer a prés par post pour que je puisse voir l erreur par get/ce qu'on ecrit sur le navigateur , c'est l'url appelé sur le front public String afficherProfilSitter(Model model) { return "/auth/sitter/ficheSitter";// le nom de la jsp } }
true
efefb040ebaf0ddfe7f8c7b700ea940d5a911653
Java
lm-pn/dip107p-md01-gp
/RecursiveQuicksort.java
UTF-8
787
3.265625
3
[ "BSD-2-Clause" ]
permissive
import java.util.Random; class RecursiveQuicksort implements Sorter { private Random rand = new Random(); public int[] sort (int []array){ quickSort(array, 0, array.length-1); return array; } public void quickSort(int a[], int I, int r){ int m = a[randomNumber(I, r)]; int i = I; int j = r; int prev = 0; do { while (a[i] < m){ i++; } while (a[j] > m){ j--; } if (i <= j){ prev = a[i]; a[i] = a[j]; a[j] = prev; i++; j--; } } while(i <= j); if (j > I) { quickSort(a, I, j); } if (r > i){ quickSort(a, i, r); } } public int randomNumber(int min, int max){ return rand.nextInt(max+1-min)+min; } public ArrayWindow sort(ArrayWindow window) { return new ArrayWindow(sort(window.getArray())); } }
true
9fa75fd75f4b05100fd5bea3a547cea05153ac5b
Java
cckmit/material
/material/src/main/java/com/crledu/auto/material/bigdata/biz/domain/BigdataDomain.java
UTF-8
1,266
2.421875
2
[]
no_license
package com.crledu.auto.material.bigdata.biz.domain; /** ************************************************************ * @Description: 需要文件进行保存的业务数据 * @Version: v1.1.1 ************************************************************ * @CopyrightBy: 创享源信息技术有限公司 * @author: wenyi * @Date: 2020/11/18 13:56 ************************************************************ * @ModifiedBy: [name] on [time] ************************************************************ **/ public class BigdataDomain { /** * 对应的导入记录 */ private Long importId; /** * 需要保存的样本数据 */ private Object data; /** * 文件保存地址 */ private String path; protected BigdataDomain(Long importId, Object data) { this.importId = importId; this.data = data; } public static BigdataDomain getInstance(Long importId, Object data){ return new BigdataDomain(importId, data); } public Object getData() { return data; } public Long getImportId() { return importId; } public String getPath() { return path; } public void save(String path){ this.path = path; } }
true
794844edaa6b1ab6aedc91b12e9ddbd000e7414b
Java
jamesdinht/CECS277-Project-Inheritance
/GeometricObjectTester.java
UTF-8
2,736
3.953125
4
[]
no_license
/* James Dinh * 02/07/15 * Purpose: Demonstrate polymorphism with geometric objects * Input: Attributes of different geometric objects * Output: Object's state and measurements */ import java.util.ArrayList; public class GeometricObjectTester { public static void main(String[] arghs) { ArrayList<GeometricObject> geomObjs = new ArrayList<GeometricObject>(); // Create 12 objects. 3 shapes, 4 constructors each GeometricObject circle = new Circle(12); GeometricObject defaultCircle = new Circle(); GeometricObject square = new Rectangle(15, 15); GeometricObject defaultTriangle = new Triangle(); GeometricObject defaultRectangle = new Rectangle(); GeometricObject rightTriangle = new Triangle(3, 4, 5); GeometricObject pie = new Circle("green", false, 3.14); GeometricObject colorRect = new Rectangle("pink", true); GeometricObject rect = new Rectangle("blue", false, 4, 6); GeometricObject colorTriangle = new Triangle("red", false); GeometricObject coloredCircle = new Circle("magenta", true); GeometricObject triangle = new Triangle("purple", true, 3, 4, 5); // Method testing for each shape Circle cCircle = (Circle) circle; cCircle.setRadius(2); System.out.println("white, unfilled circle's diameter after: " + cCircle.getDiameter()); Rectangle rectDefault = (Rectangle) defaultRectangle; rectDefault.setHeight(3); rectDefault.setWidth(4); System.out.println("defaultRectangle's height and width after: " + rectDefault.getHeight() + ", " + rectDefault.getWidth()); Triangle halfRectangle = (Triangle) colorTriangle; halfRectangle.setSides(3, 6, 5); // input validation halfRectangle.setSide1(6); halfRectangle.setSide2(3); halfRectangle.setSide3(1); System.out.println("colorTriangle's side1, side2, and side3 after: " + halfRectangle.getSide1() + ", " + halfRectangle.getSide2() + ", " + halfRectangle.getSide3()); // Add shapes to list geomObjs.add(circle); geomObjs.add(defaultCircle); geomObjs.add(square); geomObjs.add(defaultTriangle); geomObjs.add(defaultRectangle); geomObjs.add(rightTriangle); geomObjs.add(pie); geomObjs.add(colorRect); geomObjs.add(rect); geomObjs.add(colorTriangle); geomObjs.add(coloredCircle); geomObjs.add(triangle); // loop for polymorphism for (GeometricObject geoObj : geomObjs) { System.out.println(geoObj.toString()); System.out.println("Perimeter: " + geoObj.getPerimeter() + "\nArea: " + geoObj.getArea() + "\n"); } // Test max() GeometricObject.max(circle, pie); GeometricObject.max(square, rect); GeometricObject.max(triangle, rightTriangle); } }
true
6b453851001e0560724991ea3549fd13320d27bf
Java
JianChi8/BuddhismNetworkRadio
/app/src/main/java/com/jianchi/fsp/buddhismnetworkradio/activity/Mp3ManagerActivity.java
UTF-8
4,711
2.234375
2
[]
no_license
package com.jianchi.fsp.buddhismnetworkradio.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListView; import com.jianchi.fsp.buddhismnetworkradio.BApplication; import com.jianchi.fsp.buddhismnetworkradio.R; import com.jianchi.fsp.buddhismnetworkradio.adapter.Mp3ManagerAdapter; import com.jianchi.fsp.buddhismnetworkradio.db.Mp3RecDBManager; import com.jianchi.fsp.buddhismnetworkradio.mp3.Mp3Program; import java.util.ArrayList; import java.util.List; public class Mp3ManagerActivity extends AppCompatActivity { ExpandableListView lv; BApplication app; Mp3ManagerAdapter mp3ManagerAdapter; List<Mp3Program> mp3Programs; List<Mp3Program> checkedMpsPrograms; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mp3_manager); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //获取自定义APP,APP内存在着数据,若为旋转屏幕,此处记录以前的内容 app = (BApplication)getApplication(); Mp3RecDBManager db = new Mp3RecDBManager(); mp3Programs = db.getAllMp3Rec(); checkedMpsPrograms = new ArrayList<>(); for(Mp3Program p : mp3Programs) checkedMpsPrograms.add(p); lv = (ExpandableListView) findViewById(R.id.lv_mp3); lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Mp3Program mp3Program = (Mp3Program) v.getTag(); Mp3Program mp = checkMp3Program(mp3Program); if(mp==null){ checkedMpsPrograms.add(mp3Program); } else { checkedMpsPrograms.remove(mp); } mp3ManagerAdapter.notifyDataSetChanged(); return false; } }); mp3ManagerAdapter = new Mp3ManagerAdapter(this, checkedMpsPrograms); lv.setAdapter(mp3ManagerAdapter); } private Mp3Program checkMp3Program(Mp3Program mp3Program){ for(Mp3Program mp : checkedMpsPrograms){ if(mp.id.equals(mp3Program.id)) return mp; } return null; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.manager, 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_save) { save(); return true; } return super.onOptionsItemSelected(item); } private void save(){ List<Mp3Program> delMp3Programs = new ArrayList<Mp3Program>(); List<Mp3Program> addMpsPrograms = new ArrayList<Mp3Program>(); boolean found = false; for(Mp3Program mp : checkedMpsPrograms){ found = false; for(Mp3Program mp2 : mp3Programs){ if(mp.id.equals(mp2.id)){ found=true; break; } } if(!found){ addMpsPrograms.add(mp); } } for(Mp3Program mp : mp3Programs){ found = false; for(Mp3Program mp2 : checkedMpsPrograms){ if(mp.id.equals(mp2.id)){ found=true; break; } } if(!found){ delMp3Programs.add(mp); } } if(addMpsPrograms.size()>0 || delMp3Programs.size()>0) { Mp3RecDBManager db = new Mp3RecDBManager(); if (addMpsPrograms.size() > 0) db.addMp3s(addMpsPrograms); if (delMp3Programs.size() > 0) { for(Mp3Program mp3Program : delMp3Programs) db.delMp3(mp3Program); } setResult(RESULT_OK); } else { setResult(RESULT_CANCELED); } finish(); } }
true
6b928b09306367d6d5bd25c9d1e75078a155a179
Java
phillco/Disasteroids
/Disasteroids/tags/1.0_examw/src/Ship.java
UTF-8
6,581
2.6875
3
[]
no_license
/* * DISASTEROIDS * by Phillip Cohen and Andy Kooiman * * APCS 1, 2006 to 2007, Period 3 * Version - 1.0 Final (exam release) * * Run Running.class to start */ import java.awt.*; import java.util.ArrayList; import java.util.Random; import java.util.LinkedList; public class Ship { public final static double BOO = 50; private double x,y; private double dx,dy; private boolean forward = false, backwards = false, left = false, right = false; private double origin_x, origin_y; private double angle; private Graphics g; private int timeTillNextShot=0; private Color myColor; private int invincibilityCount; private Color myInvicibleColor; private int livesLeft; private boolean invulFlash; private MisileManager manager; private int score=0; private int maxShots=10; public Ship(int x, int y, Graphics g, Color c, int lives) { this.x=x; this.y=y; this.origin_x=x; this.origin_y=y; this.g=g; invulFlash = true; angle=Math.PI/2; dx=0; dy=0; livesLeft=lives; myColor=c; double fadePct = 0.3; myInvicibleColor = new Color((int)(myColor.getRed() * fadePct), (int)(myColor.getGreen() * fadePct), (int)(myColor.getBlue() * fadePct)); manager=new MisileManager(); invincibilityCount=200; } private void draw() { // Set our color if(cannotDie()) g.setColor(myInvicibleColor); else g.setColor(myColor); // Flash when invunerable if( (cannotDie() && (invulFlash = !invulFlash) == true) || ! (cannotDie())) { // Draw the ship and pointer blob g.fillOval((int)x,(int)y,20,20); g.setColor(Color.white); g.fillOval((int)(x+10*Math.cos(angle))+7,(int)(y-10*Math.sin(angle))+7,5,5); } // g.setAlpha(1); /* if(cannotDie()) { //dims the ship if it cannot die float[] hsbVals={0f,0f,0f}; hsbVals=Color.RGBtoHSB(myColor.getRed(), myColor.getGreen(), myColor.getBlue(), hsbVals); g.setColor(Color.getHSBColor(hsbVals[0], hsbVals[1], hsbVals[2]-.5f)); } else g.setColor(myColor); g.fillOval((int)x,(int)y,20,20); g.setColor(Color.red); g.fillOval((int)(x+10*Math.cos(angle))+7,(int)(y-10*Math.sin(angle))+7,5,5); */ } public void forward() { // dx+=Math.cos(angle)/20; // dy-=Math.sin(angle)/20; forward = true; } public void backwards() { // dx-=Math.cos(angle)/20; // dy+=Math.sin(angle)/20; backwards = true; } public void left() {//angle+=Math.PI/20; left = true;} public void right() {//angle-=Math.PI/20; right = true;} public void unforward() { forward = false; } public void unbackwards() { backwards = false; } public void unleft() { left = false; } public void unright() { right = false; } public void act() { if(forward) { dx+=Math.cos(angle)/BOO; dy-=Math.sin(angle)/BOO; } if(backwards) { dx-=Math.cos(angle)/BOO; dy+=Math.sin(angle)/BOO; } if(left) angle+=Math.PI/BOO; if(right) angle-=Math.PI/BOO; manager.act(); if(livesLeft<0) return; timeTillNextShot--; invincibilityCount--; move(); checkBounce(); checkCollision(); draw(); if(!(Math.abs(dx) < 0.1 && Math.abs(dy) < 0.15)) { Random rand=RandNumGen.getParticleInstance(); for(int i = 0; i < 3; i++) ParticleManager.createParticle( x + rand.nextInt(16)-8 + dx, y + rand.nextInt(16)-8 + dy, rand.nextInt(4) + 3, myColor, rand.nextDouble()*2.0 - 1 , rand.nextDouble()*2.0 - 1, 30, 10); } } public void fullRight() {angle=0;} public void fullLeft() {angle=Math.PI;} public void fullUp() {angle=Math.PI/2;} public void fullDown() {angle=Math.PI*3/2;} public void allStop() {dx=dy=0;} private void checkBounce() { if(x<0) x+=799; if(y<0) y+=799; if(x>800) x-=799; if(y>800) y-=799; } private void checkCollision() { Ship other; if((other=AsteroidsFrame.getShip())==this) other=AsteroidsFrame.getShip2(); if(other == null) return; LinkedList<Misile> enemyMisiles= other.getMisileManager().getMisiles(); for(Misile m: enemyMisiles) { if(Math.pow(x-m.getX(),2)+Math.pow(y-m.getY(),2)<400) if(looseLife()) { m.explode(); score-=5000; other.score+=5000; other.livesLeft++; } } } private void move() { x+=dx; y+=dy; dx *= .999; dy *= .999; } public int getX() {return (int)x;} public int getY() {return (int)y;} public void shoot(boolean useSound) { if(livesLeft<0) return; timeTillNextShot=15; manager.addMisile((int)x+10,(int)y+10,angle,dx,dy, myColor); if(useSound) Driver_Sound.click(); } public void setMaxShots(int newMax) {maxShots=newMax;} public boolean canShoot() { return(manager.getNumLivingMisiles()<maxShots && timeTillNextShot<1 && invincibilityCount<400 && livesLeft>=0); } public Color getColor() {return myColor;}//if you can't figure out what this does you're retarded public void setInvincibilityCount(int num) {invincibilityCount=num;} public boolean looseLife() { if(cannotDie()) return false;//died too soon, second chance timeTillNextShot=0; // berserk(); livesLeft--; setInvincibilityCount(300); Driver_Sound.bleargh(); // Disabled, very sensitiuve to lag --> desync // x = origin_x; // y = origin_y; // dx = 0.0; // dy = 0.0; // angle=Math.PI/2; Random rand=RandNumGen.getParticleInstance(); for(int i = 0; i < 80; i++) ParticleManager.createParticle( x + rand.nextInt(16)-8 + dx, y + rand.nextInt(16)-8 + dy, rand.nextDouble()*9.0+0.2, myColor, rand.nextDouble()*6.0 - 3 +dx/8, rand.nextDouble()*6.0 - 3+dy/8, 150, 20); return true; } public boolean cannotDie() {return invincibilityCount>0;} public MisileManager getMisileManager() {return manager;} public void increaseScore(int points) {score+=points;} public int getScore() {return score;} public void addLife() { if(livesLeft>=0) livesLeft++; } public int score() {return score;} public int livesLeft() {return livesLeft;} public void berserk() { if(!canShoot()) return; double angleBefore=angle; Driver_Sound.kablooie(); for(double ang=0; ang<=2*Math.PI; ang+=Math.PI/10) { shoot(false); angle=angleBefore+ang; } angle=angleBefore+.1; timeTillNextShot=100; } }
true
181f88e7b702e1b9bd4a812d6cf8148a056327fe
Java
movomoto/core-ng-project
/core-ng/src/main/java/core/framework/impl/log/stat/Stat.java
UTF-8
3,620
2.5
2
[ "Apache-2.0" ]
permissive
package core.framework.impl.log.stat; import core.framework.util.ASCII; import core.framework.util.Lists; import core.framework.util.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @author neo */ public class Stat { public final List<Metrics> metrics = Lists.newArrayList(); private final Logger logger = LoggerFactory.getLogger(Stat.class); private final OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); private final ThreadMXBean thread = ManagementFactory.getThreadMXBean(); private final MemoryMXBean memory = ManagementFactory.getMemoryMXBean(); private final List<GCStat> gcStats = Lists.newArrayList(); public Stat() { List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean bean : beans) { String name = garbageCollectorName(bean.getName()); gcStats.add(new GCStat(name, bean)); } } public Map<String, Double> collect() { Map<String, Double> stats = Maps.newLinkedHashMap(); stats.put("sys_load_avg", os.getSystemLoadAverage()); stats.put("thread_count", (double) thread.getThreadCount()); MemoryUsage usage = memory.getHeapMemoryUsage(); stats.put("jvm_heap_used", (double) usage.getUsed()); stats.put("jvm_heap_max", (double) usage.getMax()); for (GCStat gcStat : gcStats) { long count = gcStat.count(); long elapsedTime = gcStat.elapsedTime(); stats.put("jvm_gc_" + gcStat.name + "_count", (double) count); stats.put("jvm_gc_" + gcStat.name + "_total_elapsed", (double) elapsedTime); } collectMetrics(stats); return stats; } private void collectMetrics(Map<String, Double> stats) { for (Metrics metrics : metrics) { try { metrics.collect(stats); } catch (Throwable e) { logger.warn("failed to collect metrics, metrics={}, error={}", metrics.getClass().getCanonicalName(), e.getMessage(), e); } } } final String garbageCollectorName(String name) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); if (ch == ' ') builder.append('_'); else builder.append(ASCII.toLowerCase(ch)); } return builder.toString(); } static class GCStat { final String name; final GarbageCollectorMXBean bean; long previousCount; long previousElapsedTime; GCStat(String name, GarbageCollectorMXBean bean) { this.name = name; this.bean = bean; } long count() { long previous = previousCount; long current = bean.getCollectionCount(); previousCount = current; return current - previous; } long elapsedTime() { long previous = previousElapsedTime; long current = bean.getCollectionTime(); previousElapsedTime = current; return TimeUnit.NANOSECONDS.convert(current - previous, TimeUnit.MILLISECONDS); } } }
true
21748eed84f6fb3f870958e5805cf375fa0d243e
Java
Ideamaxwu/biggy
/release_src/src/main/java/com/helpal/datar/rbiggy/engines/storage/StorageEngineFactory.java
UTF-8
568
2.53125
3
[]
no_license
package com.helpal.datar.rbiggy.engines.storage; import com.helpal.datar.rbiggy.bEngines.StorageEngineOracle; import com.helpal.datar.rbiggy.engines.storage.HBase.StorageEngineHBase; /** * * StorageEngine Factory * */ public class StorageEngineFactory { public IStorageEngine getStorageEngine(String engineName){ switch(engineName){ case "HBase": return new StorageEngineHBase(); default: System.out.println("NO customized StorageEngine or UNAVAILABLE customized StorageEngine as " + engineName +"!"); return new StorageEngineOracle(); } } }
true
f6dc8c69ebe6c48788cec962c57548fd634f93ea
Java
hevayo/module-ballerina-xmldata
/native/src/main/java/io/ballerina/stdlib/xmldata/JsonToXml.java
UTF-8
9,221
1.90625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 io.ballerina.stdlib.xmldata; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.utils.XmlUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BRefValue; import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BXml; import io.ballerina.runtime.api.values.BXmlItem; import io.ballerina.runtime.api.values.BXmlQName; import io.ballerina.stdlib.xmldata.utils.Constants; import io.ballerina.stdlib.xmldata.utils.XmlDataUtils; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; /** * Common utility methods used for JSON manipulation. * * @since 1.0 */ @SuppressWarnings("unchecked") public class JsonToXml { private static final String XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; private static final String XSI_PREFIX = "xsi"; private static final String NIL = "nil"; /** * Converts a JSON to the corresponding XML representation. * * @param json JSON record object * @param options option details * @return XML object that construct from JSON */ public static Object fromJson(Object json, BMap<BString, BString> options) { try { String attributePrefix = (options.get(StringUtils.fromString(Constants.OPTIONS_ATTRIBUTE_PREFIX))). getValue(); String arrayEntryTag = (options.get(StringUtils.fromString(Constants.OPTIONS_ARRAY_ENTRY_TAG))). getValue(); return convertToXML(json, attributePrefix, arrayEntryTag); } catch (Exception e) { return XmlDataUtils.getError(e.getMessage()); } } /** * Converts given JSON object to the corresponding XML. * * @param json JSON object to get the corresponding XML * @param attributePrefix String prefix used for attributes * @param arrayEntryTag String used as the tag in the arrays * @return BXml XML representation of the given JSON object */ public static BXml convertToXML(Object json, String attributePrefix, String arrayEntryTag) { if (json == null) { return null; } List<BXml> xmlElemList = traverseTree(json, attributePrefix, arrayEntryTag); if (xmlElemList.size() == 1) { return xmlElemList.get(0); } else { ArrayList<BXml> seq = new ArrayList<>(xmlElemList); return ValueCreator.createXmlSequence(seq); } } // Private methods /** * Traverse a JSON root node and produces the corresponding XML items. * * @param json to be traversed * @param attributePrefix String prefix used for attributes * @param arrayEntryTag String used as the tag in the arrays * @return List of XML items generated during the traversal. */ private static List<BXml> traverseTree(Object json, String attributePrefix, String arrayEntryTag) { List<BXml> xmlArray = new ArrayList<>(); if (!(json instanceof BRefValue)) { BXml xml = (BXml) XmlUtils.parse(json.toString()); xmlArray.add(xml); } else { traverseJsonNode(json, null, null, xmlArray, attributePrefix, arrayEntryTag); } return xmlArray; } /** * Traverse a JSON node ad produces the corresponding xml items. * * @param json to be traversed * @param nodeName name of the current traversing node * @param parentElement parent element of the current node * @param xmlElemList List of XML items generated * @param attributePrefix String prefix used for attributes * @param arrayEntryTag String used as the tag in the arrays * @return List of XML items generated during the traversal. */ @SuppressWarnings("rawtypes") private static BXmlItem traverseJsonNode(Object json, String nodeName, BXmlItem parentElement, List<BXml> xmlElemList, String attributePrefix, String arrayEntryTag) { BXmlItem currentRoot = null; if (nodeName != null) { // Extract attributes and set to the immediate parent. if (nodeName.startsWith(attributePrefix)) { if (json instanceof BRefValue) { throw XmlDataUtils.getError("attribute cannot be an object or array"); } if (parentElement != null) { String attributeKey = nodeName.substring(1); parentElement.setAttribute(attributeKey, null, null, json.toString()); } return parentElement; } // Validate whether the tag name is an XML supported qualified name, according to the XML recommendation. XmlUtils.validateXmlName(nodeName); BXmlQName tagName = ValueCreator.createXmlQName(StringUtils.fromString(nodeName)); currentRoot = (BXmlItem) ValueCreator.createXmlValue(tagName, (BString) null); } if (json == null) { currentRoot.setAttribute(NIL, XSI_NAMESPACE, XSI_PREFIX, "true"); } else { BMap<BString, Object> map; Type type = TypeUtils.getType(json); switch (type.getTag()) { case TypeTags.MAP_TAG: if (((MapType) type).getConstrainedType().getTag() != TypeTags.JSON_TAG) { throw XmlDataUtils.getError("error in converting map<non-json> to xml"); } setCurrentRoot(json, nodeName, xmlElemList, attributePrefix, arrayEntryTag, currentRoot); break; case TypeTags.JSON_TAG: setCurrentRoot(json, nodeName, xmlElemList, attributePrefix, arrayEntryTag, currentRoot); break; case TypeTags.ARRAY_TAG: BArray array = (BArray) json; for (int i = 0; i < array.size(); i++) { currentRoot = traverseJsonNode(array.getRefValue(i), arrayEntryTag, currentRoot, xmlElemList, attributePrefix, arrayEntryTag); if (nodeName == null) { // Outermost array xmlElemList.add(currentRoot); currentRoot = null; } } break; case TypeTags.INT_TAG: case TypeTags.FLOAT_TAG: case TypeTags.DECIMAL_TAG: case TypeTags.STRING_TAG: case TypeTags.BOOLEAN_TAG: if (currentRoot == null) { throw XmlDataUtils.getError("error in converting json to xml"); } BXml text = ValueCreator.createXmlText(json.toString()); addChildElem(currentRoot, text); break; default: throw XmlDataUtils.getError("error in converting JSON to XML"); } } // Set the current constructed root the parent element if (parentElement != null) { addChildElem(parentElement, currentRoot); currentRoot = parentElement; } return currentRoot; } private static void setCurrentRoot(Object json, String nodeName, List<BXml> xmlElemList, String attributePrefix, String arrayEntryTag, BXmlItem currentRoot) { BMap<BString, Object> map = (BMap) json; for (Entry<BString, Object> entry : map.entrySet()) { currentRoot = traverseJsonNode(entry.getValue(), entry.getKey().getValue(), currentRoot, xmlElemList, attributePrefix, arrayEntryTag); if (nodeName == null) { // Outermost object xmlElemList.add(currentRoot); currentRoot = null; } } } private static void addChildElem(BXmlItem currentRoot, BXml child) { currentRoot.getChildrenSeq().getChildrenList().add(child); } }
true
25bb5d4538afd1fc1c26b10063893718483ff483
Java
cosai/EONS
/src/simulator/RRouting.java
UTF-8
1,386
2.59375
3
[]
no_license
package simulator; /* * NOT USED * May need to be revised again * May not be working as expected */ public class RRouting extends SRouting { int contactLimit=7; public RRouting(Air a,double prob,double alpha,double wantedProb,double idleparam){ super(a, prob, alpha, wantedProb, 1,idleparam,0); contactLimit=(int)idleparam; if(getSender().getEncounterLimit() != contactLimit){ getSender().setEncounterLimit(contactLimit); } if(getReceiver().getEncounterLimit() != contactLimit) { getReceiver().setEncounterLimit(contactLimit); } } public static double f(int encountern){ if(encountern >= 5){ return 0.5; } return 1-0.1*encountern; } public void send(String time){ if(getAlpha()== -1 && getWantedProb() == -1){ super.send(time); return; } Node s=getSender(); Node r=getReceiver(); sendToReceiver(s,r,time); sendToReceiver(r,s,time); } public void sendToReceiver(Node s,Node r,String time){ double oldp=getProb(); double newprob=0; int timeconv=Integer.parseInt(time); s.setEncounterLimit(contactLimit); boolean b=s.enqueueAgain(r.getId(), timeconv); Encounter e=null; if(!b){ e=new Encounter(s.getId(),r.getId(),timeconv); e.incEncounterCount(); s.addEncounter(e); } newprob=f(e.getEncounterCount()); setProb(newprob); if(readytosend()){ communicate(s,r,time); } } }
true
76ee57c9f7795ba46a1d7fa8f1b6939b87768db7
Java
SanchoGGP/ggp-base
/src/org/ggp/base/player/request/grammar/StartRequest.java
UTF-8
2,751
2.390625
2
[ "BSD-3-Clause" ]
permissive
package org.ggp.base.player.request.grammar; import org.ggp.base.player.event.PlayerTimeEvent; import org.ggp.base.player.gamer.Gamer; import org.ggp.base.player.gamer.event.GamerNewMatchEvent; import org.ggp.base.player.gamer.event.GamerUnrecognizedMatchEvent; import org.ggp.base.player.gamer.exception.MetaGamingException; import org.ggp.base.util.game.Game; import org.ggp.base.util.gdl.grammar.GdlConstant; import org.ggp.base.util.logging.GamerLogger; import org.ggp.base.util.match.Match; public final class StartRequest extends Request { private final Game game; private final Gamer gamer; private final String matchId; private final int playClock; private final GdlConstant roleName; private final int startClock; public StartRequest(Gamer gamer, String matchId, GdlConstant roleName, Game theGame, int startClock, int playClock) { this.gamer = gamer; this.matchId = matchId; this.roleName = roleName; this.game = theGame; this.startClock = startClock; this.playClock = playClock; } @Override public String getMatchId() { return matchId; } @Override public String process(long receptionTime) { // Ensure that we aren't already playing a match. If we are, // ignore the message, saying that we're busy. if (gamer.getMatch() != null) { GamerLogger .logError("GamePlayer", "Got start message while already busy playing a game: ignoring."); gamer.notifyObservers(new GamerUnrecognizedMatchEvent(matchId)); return "busy"; } // Create the new match, and handle all of the associated logistics // in the gamer to indicate that we're starting a new match. Match match = new Match(matchId, -1, startClock, playClock, 0, game); gamer.setMatch(match); gamer.setRoleName(roleName); gamer.notifyObservers(new GamerNewMatchEvent(match, roleName)); // Finally, have the gamer begin metagaming. try { gamer.notifyObservers(new PlayerTimeEvent(gamer.getMatch().getStartClock() * 1000)); gamer.metaGame(gamer.getMatch().getStartClock() * 1000 + receptionTime); } catch (MetaGamingException e) { GamerLogger.logStackTrace("GamePlayer", e); // Upon encountering an uncaught exception during metagaming, // assume that indicates that we aren't actually able to play // right now, and tell the server that we're busy. gamer.setMatch(null); gamer.setRoleName(null); return "busy"; } return "ready"; } @Override public String toString() { return "start"; } }
true
20b7f6b68af839fad0886d336311db34f4ff2a3b
Java
zxcinsomniazxc/ExamenLolitaGopershteyn
/app/src/main/java/com/example/examenlolitagopershteyn/MainActivityNew.java
UTF-8
1,008
1.898438
2
[]
no_license
package com.example.examenlolitagopershteyn; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivityNew extends AppCompatActivity { LoginResponse loginResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_new); Intent intent = getIntent(); if (intent.getExtras() != null) { loginResponse = (LoginResponse) intent.getSerializableExtra("data"); } } }
true
610dff60b22c364be1bddcaf516389e255ccc34b
Java
KimJye/algorithm
/2019_algorithm/backjoon/src/function/P1065.java
UTF-8
1,911
3.953125
4
[]
no_license
package function; import java.util.Scanner; /* * Date: 2019. 01. 17 * Author: KimJye | https://github.com/KimJye * Solution URL: https://github.com/KimJye/algorithm * Problem URL : https://www.acmicpc.net/problem/1065 * Title : 한수 * description : 어떤 양의 정수 X의 자리수가 등차수열을 이룬다면, 그 수를 한수라고 한다. 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. N이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오. 입력 : 첫째 줄에 1,000보다 작거나 같은 자연수 N이 주어진다. 출력 : 첫째 줄에 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력한다. * solution : 함수 문제 규칙을 보아하니, 한수는 한자리수 와 두자리수 그리고 세자리에서 등차 수열인 수다. */ public class P1065 { static int checkSequence(int i){ int n1 = i/100%10; //100의 자리 int n2 = i/10%10; //10의 자리 int n3 = i%10; //1의 자리 //검사 if(n2 * 2 == ( n1 + n3)){ return 1; } return 0; } static int getHanSu(int n){ int result = 0; if(n<100){//한자리수 또는 두자리수 return n; }else{// 세자리수 result = 99;//세자리수면 기본 99개 for(int i=100;i<=n; ++i){ result += checkSequence(i);//등차수열 검사 } if(n==1000) result--; } return result; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); System.out.println(getHanSu(n)); } }
true
1455df5d792b1e73f56f741c97f657f46d4cb917
Java
muneeswaranb/java8
/src/com/bsj/hacker/samples/PalindromCounter.java
UTF-8
1,324
3.75
4
[]
no_license
package com.bsj.hacker.samples; public class PalindromCounter { /* * Complete the 'countPalindromes' function below. * * The function is expected to return an INTEGER. * The function accepts STRING s as parameter. */ /*public static int count = 0; public static int countPalindromes(String s) { for(int i = 0; i < s.length() ; i++){ //expand(s,i,i); expand(s,i,i+1); } return count; } public static void expand(String s , int left, int right){ while(left >= 0 && right < s.length() && (s.charAt(left) == s.charAt(right))){ count++; left--; right++; } }*/ public static int count = 0; public static int countPalindromes(String s) { for(int i=0;i<s.length();i++){ for(int j=0;j+i+1<s.length()&&i-j>=0;j++){ if(s.charAt(1+j+1)!=s.charAt(i-j)) break; else { System.out.println(s.substring(i-j,i+j+1)); count++; } } } return count; } public static void main(String[] args) { PalindromCounter counter=new PalindromCounter(); System.out.println("Count of mom : "+countPalindromes("mom")); } }
true
d366957ef4248c4956621dc8214647b28a923e40
Java
RevivalModdingTeam/Recrafted
/src/main/java/toma/config/ConfigLoader.java
UTF-8
4,014
2.359375
2
[]
no_license
package toma.config; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.minecraft.client.Minecraft; import net.minecraft.server.MinecraftServer; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.server.ServerLifecycleHooks; import toma.config.datatypes.ConfigObject; import toma.config.test.ConfigImplementation; import toma.config.util.ConfigUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; public class ConfigLoader { public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); public static void loadFor(Dist dist) { switch (dist) { case CLIENT: loadClient(); break; case DEDICATED_SERVER: loadServer(); break; default: throw new IllegalArgumentException("Unknown dist: " + dist); } } private static void loadClient() { Minecraft mc = Minecraft.getInstance(); File configDir = new File(mc.gameDir, "config"); if(!configDir.exists()) { return; } load(configDir); } private static void loadServer() { MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); File configDir = new File(server.getDataDirectory(), "config"); if(!configDir.exists()) { return; } load(configDir); } private static void load(File configDir) { File[] configs = configDir.listFiles(); try { for (Map.Entry<String, ConfigObject> entry : Config.CONFIGS.entrySet()) { Config.log.debug("Loading config for {} mod", entry.getKey()); ConfigObject configObject = entry.getValue(); String fileName = entry.getKey() + ".json"; File modCfg = new File(configDir, fileName); boolean update = true; if(!ConfigUtils.findAndRun(fileName, configs, (mod, file) -> file.getName().equalsIgnoreCase(mod), file -> {})) { try { update = false; modCfg.createNewFile(); JsonObject object = new JsonObject(); configObject.save(object); ConfigUtils.dispatchConfigEvent(entry.getKey(), configObject); FileWriter writer = new FileWriter(modCfg); writer.write(GSON.toJson(object)); writer.close(); } catch (IOException e) { Config.log.error("Couldn't create config file for {} mod!", entry.getKey()); continue; } } if(update) { String content = ConfigUtils.readFileToString(modCfg); JsonObject object = new JsonParser().parse(content).getAsJsonObject(); try { configObject.load(object); ConfigUtils.dispatchConfigEvent(entry.getKey(), configObject); } catch (Exception e) { Config.log.fatal("Couldn't load config for {} mod, using defaults", entry.getKey()); } JsonObject saved = new JsonObject(); configObject.save(saved); FileWriter writer = new FileWriter(modCfg); writer.write(GSON.toJson(saved)); writer.close(); } Config.log.info("Loaded mod config [{}]", entry.getKey()); } } catch (Exception e) { Config.log.fatal("Exception occurred during config load - {}", e.toString()); Config.log.fatal("Shutting down..."); e.printStackTrace(); throw new IllegalStateException("Fatal error occurred during config load"); } } }
true
a04b4e1c2fcec80c26cb9610e634639fcc208f10
Java
sunkuet02/document-signer
/modules/SignServer-Server/src/main/java/org/signserver/server/GlobalConfigSampleAccounter.java
UTF-8
9,492
1.9375
2
[]
no_license
/************************************************************************* * * * SignServer: The OpenSource Automated Signing Server * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.signserver.server; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.naming.NamingException; import org.apache.log4j.Logger; import org.signserver.common.GlobalConfiguration; import org.signserver.common.ProcessRequest; import org.signserver.common.ProcessResponse; import org.signserver.common.RequestContext; import org.signserver.common.ServiceLocator; import org.signserver.ejb.interfaces.IGlobalConfigurationSession; /** * Sample accounter for demonstration purposes only which holds accounts in * the global configuration. * <p> * The accounter has two global configuration properties: * </p> * <ul> * <li> * <b>GLOBALCONFIGSAMPLEACCOUNTER_USERS</b> = Mapping from credential to * account number (Required).<br/> * Ex: user1,password:account1; user2,password2:account2 * </li> * <li><b>GLOBALCONFIGSAMPLEACCOUNTER_ACCOUNTS</b> = Map from account * number to balance (Required)<br/> * Ex: account1:14375; account2:12 * </li> * </ul> * <p> * Note: This accounter is not safe for use in production as concurrent * requests can overwrite the balance. Instead an accounter using a real * database should be used. * </p> * * @author Markus Kilås * @version $Id: GlobalConfigSampleAccounter.java 5901 2015-03-17 15:28:29Z netmackan $ */ public class GlobalConfigSampleAccounter implements IAccounter { /** Logger for this class. */ private static final Logger LOG = Logger.getLogger(GlobalConfigSampleAccounter.class); // Global configuration properties public static final String GLOBALCONFIGSAMPLEACCOUNTER_ACCOUNTS = "GLOBALCONFIGSAMPLEACCOUNTER_ACCOUNTS"; public static final String GLOBALCONFIGSAMPLEACCOUNTER_USERS = "GLOBALCONFIGSAMPLEACCOUNTER_USERS"; private IGlobalConfigurationSession gCSession; @Override public void init(final Properties props) { // This accounter does not use any worker properties } @Override public boolean purchase(final IClientCredential credential, final ProcessRequest request, final ProcessResponse response, final RequestContext context) throws AccounterException { if (LOG.isDebugEnabled()) { LOG.debug("purchase called for " + (String) context.get(RequestContext.TRANSACTION_ID)); } try { // Read global configuration values final GlobalConfiguration config = getGlobalConfigurationSession().getGlobalConfiguration(); final String usersMapping = config.getProperty(GlobalConfiguration.SCOPE_GLOBAL, GLOBALCONFIGSAMPLEACCOUNTER_USERS); final String accountsMapping = config.getProperty(GlobalConfiguration.SCOPE_GLOBAL, GLOBALCONFIGSAMPLEACCOUNTER_ACCOUNTS); // Parse users "table" final Map<String, String> usersTable = parseCredentialMapping(usersMapping); // Parse accounts "table" final Map<String, Integer> accountsTable = parseAccountMapping(accountsMapping); // Get username (or certificate serial number) from request final String key; if (credential instanceof CertificateClientCredential) { final CertificateClientCredential certCred = (CertificateClientCredential) credential; key = certCred.getSerialNumber() + "," + certCred.getIssuerDN(); } else if (credential instanceof UsernamePasswordClientCredential) { final UsernamePasswordClientCredential passCred = (UsernamePasswordClientCredential) credential; key = passCred.getUsername() + "," + passCred.getPassword(); } else if (credential == null) { if (LOG.isDebugEnabled()) { LOG.debug("No credential"); } key = null; } else { if (LOG.isDebugEnabled()) { LOG.debug("Unknown credential type: " + credential.getClass().getName()); } key = null; } // Get account final String accountNo = usersTable.get(key); // No account for user given the credential supplied if (accountNo == null) { return false; } // Get current balance Integer balance = accountsTable.get(accountNo); // No account if (balance == null) { return false; } // Purchase balance -= 1; accountsTable.put(accountNo, balance); // No funds if (balance < 0) { // Purchase not granted return false; } // Store the new balance getGlobalConfigurationSession().setProperty( GlobalConfiguration.SCOPE_GLOBAL, GLOBALCONFIGSAMPLEACCOUNTER_ACCOUNTS, storeAccountMapping(accountsTable)); // Purchase granted return true; } catch (NamingException ex) { throw new AccounterException( "Unable to connect to accounter internal database", ex); } } private IGlobalConfigurationSession getGlobalConfigurationSession() throws NamingException { if (gCSession == null) { gCSession = ServiceLocator.getInstance().lookupLocal( IGlobalConfigurationSession.class); } return gCSession; } private Map<String, String> parseCredentialMapping(String mapping) { if (mapping == null) { return Collections.emptyMap(); } final String[] entries = mapping.split(";"); final Map<String, String> result = new HashMap<String, String>(); for (String entry : entries) { final String[] keyvalue = entry.trim().split(":"); if (keyvalue.length == 2) { result.put(keyvalue[0].trim(), keyvalue[1].trim()); } } if (LOG.isDebugEnabled()) { final StringBuilder str = new StringBuilder(); str.append("Credential mapping: "); str.append("\n"); for (Map.Entry<String, String> entry : result.entrySet()) { str.append("\""); str.append(entry.getKey()); str.append("\""); str.append(" --> "); str.append("\""); str.append(entry.getValue()); str.append("\""); str.append("\n"); } LOG.debug(str.toString()); } return result; } private Map<String, Integer> parseAccountMapping(String mapping) { if (mapping == null) { return Collections.emptyMap(); } final String[] entries = mapping.split(";"); final Map<String, Integer> result = new HashMap<String, Integer>(); for (String entry : entries) { final String[] keyvalue = entry.trim().split(":"); if (keyvalue.length == 2) { result.put(keyvalue[0].trim(), Integer.parseInt(keyvalue[1].trim())); } } if (LOG.isDebugEnabled()) { final StringBuilder str = new StringBuilder(); str.append("Accounts: "); str.append("\n"); for (Map.Entry<String, Integer> entry : result.entrySet()) { str.append("\""); str.append(entry.getKey()); str.append("\""); str.append(" --> "); str.append(entry.getValue()); str.append("\n"); } LOG.debug(str.toString()); } return result; } private String storeAccountMapping(Map<String, Integer> mapping) { if (mapping == null) { return ""; } StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Integer> entry : mapping.entrySet()) { sb.append(entry.getKey()); sb.append(":"); sb.append(entry.getValue()); sb.append(";"); } return sb.toString(); } }
true
56bda1961c732f7586dc86898dbab6b8886f6cb5
Java
MatejTymes/ZeroD
/src/test-integration/java/zerod/beta/agent/dao/AgentDaoTestBase.java
UTF-8
9,751
2.125
2
[ "Apache-2.0" ]
permissive
package zerod.beta.agent.dao; import org.junit.Test; import zerod.beta.agent.domain.Agent; import zerod.beta.agent.domain.AgentId; import zerod.beta.agent.domain.Health; import zerod.beta.common.Clock; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional; import java.util.Set; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static java.util.stream.Collectors.toSet; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static zerod.beta.agent.domain.Health.noHealth; import static zerod.test.Condition.otherThan; import static zerod.test.Random.*; import static zerod.test.matcher.OptionalMatcher.isNotPresent; import static zerod.test.matcher.OptionalMatcher.isPresent; public abstract class AgentDaoTestBase { private Clock clock = new Clock(); private AgentDao dao = getDao(); @Test public void shouldFindNoAgentsInEmptyDb() { assertThat(dao.findAgent(randomAgentId()), isNotPresent()); assertThat(dao.findLiveAgents(), is(empty())); assertThat(dao.findDeadAgents(), is(empty())); assertThat(dao.findStaleLiveAgents(clock.now()), is(empty())); } @Test public void shouldBeAbleToRegisterAnAgent() { AgentId agentId = randomAgentId(); Health health = randomHealth(); // When ZonedDateTime timeBeforeRegistration = clock.now(); dao.registerAgentHealth(agentId, health); ZonedDateTime timeAfterRegistration = clock.now(); // Then Optional<Agent> foundAgent = dao.findAgent(agentId); assertThat(foundAgent, isPresent()); assertThat(foundAgent.get(), equalTo(new Agent(agentId, health, foundAgent.get().lastUpdatedAt))); // todo: add ZonedDateTime matcher ZonedDateTime storedUpdateTime = foundAgent.get().lastUpdatedAt; assertThat(storedUpdateTime.isEqual(timeBeforeRegistration) || storedUpdateTime.isAfter(timeBeforeRegistration), equalTo(true)); assertThat(storedUpdateTime.isEqual(timeAfterRegistration) || storedUpdateTime.isBefore(timeAfterRegistration), equalTo(true)); } @Test public void shouldBeAbleToFindLiveAgent() { AgentId agentId = randomAgentId(); // When Health health = randomLiveHealth(); dao.registerAgentHealth(agentId, health); // Then List<Agent> liveAgents = newArrayList(dao.findLiveAgents()); assertThat(liveAgents, hasSize(1)); Agent foundAgent = liveAgents.get(0); assertThat(foundAgent, equalTo(new Agent(agentId, health, foundAgent.lastUpdatedAt))); Set<Agent> deadAgents = dao.findDeadAgents(); assertThat(deadAgents, is(empty())); } @Test public void shouldBeAbleToFindDeadAgent() { AgentId agentId = randomAgentId(); // When Health health = noHealth(); dao.registerAgentHealth(agentId, health); // Then Set<Agent> liveAgents = dao.findLiveAgents(); assertThat(liveAgents, is(empty())); List<Agent> deadAgents = newArrayList(dao.findDeadAgents()); assertThat(deadAgents, hasSize(1)); Agent foundAgent = deadAgents.get(0); assertThat(foundAgent, equalTo(new Agent(agentId, health, foundAgent.lastUpdatedAt))); } @Test public void shouldUpdateHealthIfNotUpdatedSinceDate() { AgentId agentId = randomAgentId(); Health initialHealth = randomLiveHealth(); dao.registerAgentHealth(agentId, initialHealth); Agent originalAgent = dao.findAgent(agentId).get(); Health newHealth = randomHealth(otherThan(initialHealth)); waitForMs(10); // When dao.updateAgentsHealth(agentId, originalAgent.health, newHealth, originalAgent.lastUpdatedAt); // Then Agent updatedAgent = dao.findAgent(agentId).get(); assertThat(updatedAgent.lastUpdatedAt.isAfter(originalAgent.lastUpdatedAt), is(true)); assertThat(updatedAgent.health, equalTo(newHealth)); assertThat(updatedAgent.id, equalTo(agentId)); } @Test public void shouldUpdateHealthIfNotUpdatedSinceDate2() { AgentId agentId = randomAgentId(); dao.registerAgentHealth(agentId, randomLiveHealth()); Agent originalAgent = dao.findAgent(agentId).get(); Health newHealth = randomHealth(otherThan(randomLiveHealth())); waitForMs(10); // When dao.updateAgentsHealth(agentId, originalAgent.health, newHealth, originalAgent.lastUpdatedAt.plusSeconds(randomInt(1, 100))); // Then Agent updatedAgent = dao.findAgent(agentId).get(); assertThat(updatedAgent.health, equalTo(newHealth)); assertThat(updatedAgent.lastUpdatedAt.isAfter(originalAgent.lastUpdatedAt), is(true)); assertThat(updatedAgent.id, equalTo(agentId)); } @Test public void shouldNotUpdateHealthIfUpdatedSinceDate() { AgentId agentId = randomAgentId(); Health initialHealth = randomLiveHealth(); dao.registerAgentHealth(agentId, initialHealth); Agent originalAgent = dao.findAgent(agentId).get(); Health newHealth = randomHealth(otherThan(initialHealth)); waitForMs(10); // When dao.updateAgentsHealth(agentId, originalAgent.health, newHealth, originalAgent.lastUpdatedAt.minusSeconds(randomInt(1, 100))); // Then Agent updatedAgent = dao.findAgent(agentId).get(); assertThat(updatedAgent.health, equalTo(originalAgent.health)); assertThat(updatedAgent.lastUpdatedAt.isEqual(originalAgent.lastUpdatedAt), is(true)); assertThat(updatedAgent.id, equalTo(agentId)); } @Test public void shouldNotUpdateHealthIfExpetedHealthDoesntMatch() { AgentId agentId = randomAgentId(); dao.registerAgentHealth(agentId, randomLiveHealth()); Agent originalAgent = dao.findAgent(agentId).get(); Health newHealth = randomHealth(otherThan(randomLiveHealth())); waitForMs(10); // When dao.updateAgentsHealth(agentId, randomHealth(otherThan(originalAgent.health)), newHealth, originalAgent.lastUpdatedAt); // Then Agent updatedAgent = dao.findAgent(agentId).get(); assertThat(updatedAgent.health, equalTo(originalAgent.health)); assertThat(updatedAgent.lastUpdatedAt.isEqual(originalAgent.lastUpdatedAt), is(true)); assertThat(updatedAgent.id, equalTo(agentId)); } @Test public void shouldEvaluateAgentsStalenessIfItAlive() { AgentId agentId = randomAgentId(); dao.registerAgentHealth(agentId, randomHealth()); Agent storedAgent = dao.findAgent(agentId).get(); // When & Then assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt.minusSeconds(1)), is(empty())); assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt).stream().map(Agent::id).collect(toSet()), equalTo(newHashSet(agentId))); assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt.plusSeconds(1)).stream().map(Agent::id).collect(toSet()), equalTo(newHashSet(agentId))); } @Test public void shouldNotEvaluateAgentsStalenessIfItDead() { AgentId agentId = randomAgentId(); dao.registerAgentHealth(agentId, noHealth()); Agent storedAgent = dao.findAgent(agentId).get(); // When & Then assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt.minusSeconds(1)), is(empty())); assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt), is(empty())); assertThat(dao.findStaleLiveAgents(storedAgent.lastUpdatedAt.plusSeconds(1)), is(empty())); } @Test public void shouldFindStaleAgents() { AgentId agentId1 = randomAgentId(); AgentId agentId2 = randomAgentId(otherThan(agentId1)); AgentId agentId3 = randomAgentId(otherThan(agentId1, agentId2)); AgentId agentId4 = randomAgentId(otherThan(agentId1, agentId2, agentId3)); AgentId agentId5 = randomAgentId(otherThan(agentId1, agentId2, agentId3, agentId4)); AgentId agentId6 = randomAgentId(otherThan(agentId1, agentId2, agentId3, agentId4, agentId5)); Health deadlyHealth = noHealth(); Health liveHealth = randomLiveHealth(); Health otherLiveHealth = randomLiveHealth(otherThan(liveHealth)); dao.registerAgentHealth(agentId1, liveHealth); dao.registerAgentHealth(agentId3, liveHealth); dao.registerAgentHealth(agentId6, liveHealth); waitForMs(10); dao.registerAgentHealth(agentId2, deadlyHealth); waitForMs(10); dao.updateAgentsHealth(agentId3, liveHealth, otherLiveHealth, clock.now()); waitForMs(10); ZonedDateTime cutoutTime = clock.now(); waitForMs(10); dao.registerAgentHealth(agentId4, liveHealth); waitForMs(10); dao.registerAgentHealth(agentId5, deadlyHealth); waitForMs(10); dao.updateAgentsHealth(agentId6, liveHealth, otherLiveHealth, clock.now()); // When Set<Agent> staleAgents = dao.findStaleLiveAgents(cutoutTime); // Then assertThat(staleAgents.stream().map(Agent::id).collect(toSet()), equalTo(newHashSet(agentId1, agentId3))); } private void waitForMs(long durationInMs) { try { Thread.sleep(durationInMs); } catch (InterruptedException e) { throw new RuntimeException(e); } } protected abstract AgentDao getDao(); }
true
eca6e136127586e38b9bae808a4868169dc6760e
Java
leosimas/movies-app
/app/src/main/java/br/com/android/estudos/moviesapp/data/MoviesDbHelper.java
UTF-8
1,546
2.4375
2
[ "MIT" ]
permissive
package br.com.android.estudos.moviesapp.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import br.com.android.estudos.moviesapp.data.MoviesContract.MovieEntry; /** * Created by Dustin on 02/09/2016. */ public class MoviesDbHelper extends SQLiteOpenHelper { static final int DATABASE_VERSION = 1; static final String DATABASE_NAME = "movies.db"; public MoviesDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { final String SQL_CREATE_MOVIES_TABLE = "CREATE TABLE " + MovieEntry.TABLE_NAME + " ( "+ MovieEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MovieEntry.COLUMN_SERVER_ID + " INTEGER , " + MovieEntry.COLUMN_ORIGINAL_TITLE + " TEXT NOT NULL, " + MovieEntry.COLUMN_OVERVIEW + " TEXT NOT NULL, " + MovieEntry.COLUMN_POSTER_PATH + " TEXT NOT NULL, " + MovieEntry.COLUMN_RELEASE_DATE + " INTEGER, " + MovieEntry.COLUMN_VOTE_AVERAGE + " REAL, " + "UNIQUE ( "+ MovieEntry.COLUMN_SERVER_ID + " ) ON CONFLICT REPLACE " + " )"; db.execSQL( SQL_CREATE_MOVIES_TABLE ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL( "DROP TABLE IF EXISTS " + MovieEntry.TABLE_NAME ); onCreate( db ); } }
true
5c484f1f4bc3d9e71373431b483a36c3f976b148
Java
pushya/YellowPages
/Account.java
UTF-8
3,580
2.921875
3
[]
no_license
import java.lang.*; import java.sql.*; public class Account extends DataObject { private String Username,Name,PhoneNo,Address; private char[] Password,RePassword; public Account(String UN,char[] Pswd,char[] RePswd,String N,String PhoneNo,String Address,String Message){ Username = UN; Password = Pswd; RePassword = RePswd; Name = N; PhoneNo = this.PhoneNo; Address = this.Address; setMessage(Message); } public Account(String UN,char[] Pswd){ Username = UN; Password = Pswd; } public boolean signUp(){ boolean flag = !Username.equals("")&&!Password.equals("")&&!RePassword.equals("")&&Password.equals(RePassword); try{ if(flag){ DBConnection DB = new DBConnection(); Connection DBConn = DB.openConnection(); Statement stmt = DBConn.createStatement(); System.out.println(DBConn); String SQL_Command = "SELECT Username FROM Account WHERE Username = '"+Username+"'"; ResultSet Rset = stmt.executeQuery(SQL_Command); flag = flag && !Rset.next(); if(flag){ SQL_Command = "INSERT INTO Account(Username,Password,Name,PhoneNo,Address,Message) VALUES('"+Username+"','"+Password+"','"+Name+"','"+PhoneNo+"','"+Address+"','"+getMessage()+"')"; stmt.executeUpdate(SQL_Command); } stmt.close(); DB.closeConnection(); } } catch(java.sql.SQLException e){ flag = false; System.out.println("SQLException: "+ e); while(e!=null){ System.out.println("SQLState: "+ e.getSQLState()); System.out.println("Message: "+e.getMessage()); System.out.println("Vendor: "+e.getErrorCode()); e = e.getNextException(); System.out.println(""); } } catch(java.lang.Exception e) { flag = false; System.out.println("Exception: "+e); e.printStackTrace(); } return flag; } public boolean userSignin(){ boolean flag = true; try{ if(flag){ DBConnection DB = new DBConnection(); Connection DBConn = DB.openConnection(); Statement stmt = DBConn.createStatement(); System.out.println(DBConn); String SQL_Command = "SELECT Name FROM Account WHERE Username = '"+Username+"' AND Password = '"+Password+"'"; ResultSet Rset = stmt.executeQuery(SQL_Command); if(Rset.next()) flag = true; else flag = false; stmt.close(); DB.closeConnection(); } } catch(java.sql.SQLException e){ flag = false; System.out.println("SQLException: "+ e); while(e!=null){ System.out.println("SQLState: "+ e.getSQLState()); System.out.println("Message: "+e.getMessage()); System.out.println("Vendor: "+e.getErrorCode()); e = e.getNextException(); System.out.println(""); } }catch(java.lang.Exception e){ flag = false; System.out.println("Exception: "+e); e.printStackTrace(); } return flag; } }
true
0bdfdfd2a467d7b44e9e80c25c4069200093e167
Java
VincentCWP/ala_ssm
/src/main/java/com/java/controller/SessionController.java
UTF-8
541
2.328125
2
[]
no_license
package com.java.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class SessionController { // 点击退出,立即让session中的信息失效,返回登录界面 @RequestMapping("/sessionInvalidate") public String sessionInvalidate(HttpServletRequest request) { // 让session中的信息失效 request.getSession().invalidate(); return "login.jsp"; } }
true
fe85f7ee81758643f98a0aa94676bc5167fd91bc
Java
sakkumaayi/Training
/junk/src/junk/Counter.java
UTF-8
988
3.234375
3
[]
no_license
package junk; public class Counter{ private static int count=0; private int nonStaticcount=0; public void incrementCounter(){ count++; nonStaticcount++; } public int getCount(){ return count; } public int getNonStaticcount(){ return nonStaticcount; } public static void main(String args[]){ Counter countObj1 = new Counter(); Counter countObj2 = new Counter(); countObj1.incrementCounter(); System.out.println("Static count for Obj1: "+countObj1.getCount()); System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount()); countObj2.incrementCounter(); System.out.println("Static count for Obj1: "+countObj1.getCount()); System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount()); countObj2.incrementCounter(); System.out.println("Static count for Obj2: "+countObj2.getCount()); System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount()); } }
true
50cac3bfb8ea6303c5dcaa5ccbb1e29d673de794
Java
pointware/problem-solving
/src/test/java/com/pointware/leetcode/MinimumPathSumTest.java
UTF-8
675
2.546875
3
[]
no_license
package com.pointware.leetcode; import com.pointware.TestCase; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MinimumPathSumTest implements TestCase { @Test @Override public void basicTest() { int result = new MinimumPathSum().minPathSum(new int[][]{ {1,3,1}, {1,5,1}, {4,2,1} }); assertEquals(7, result); } @Test public void failedTimeLimitExceeded(){ int result = new MinimumPathSum().dp(new int[][]{ {1,3,1}, {1,5,1}, {4,2,1} }); assertEquals(7, result); } }
true
69e9b3d9b121df2d4a66d3a27ded3f244534be84
Java
sangjiexun/gaishou
/src/main/java/vn/bananavietnam/ict/common/util/XmlConfigFunction.java
UTF-8
2,129
2.515625
3
[]
no_license
package vn.bananavietnam.ict.common.util; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import vn.bananavietnam.ict.common.component.XmlConfig; /** * Define all functions for read file xml * * @author PhongBui * */ public class XmlConfigFunction { /** global object {XmlConfig} */ private static XmlConfig xmlConfig; private static String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePathTmp) { filePath = filePathTmp; } /** * Initialize XmlConfig object */ public void initXmlConfig() { try { File xmlFile = new File(getFilePath()); // Check the time the file was last modified if (xmlConfig != null && xmlFile.lastModified() == xmlConfig.getLastModified()) { return; } xmlConfig = new XmlConfig(); xmlConfig.setLastModified(xmlFile.lastModified()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); // Return new NodeList object containing all the matched xmlConfig tag. NodeList nodes = doc.getElementsByTagName("xmlConfig"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Element element = (Element) node; NodeList mode_name = element.getElementsByTagName("app_name"); for (int j = 0; j < mode_name.getLength(); j++) { xmlConfig.mode.put(getValue("app_name", element, j), getValue("screen_id", element, j)); } } } catch (Exception e) { e.printStackTrace(); } } private String getValue(String tag, Element element, int index) { NodeList nodes = element.getElementsByTagName(tag).item(index).getChildNodes(); Node node = (Node) nodes.item(0); return node.getNodeValue(); } public String[] getScreenList(String app_name) { initXmlConfig(); return xmlConfig.getScreenList(app_name); } }
true
0edd0a721424ac85023f610682ee1c1180e80eb7
Java
ajou-jipjung/plaemo
/app/src/main/java/com/po771/plaemo/SplashActivity.java
UTF-8
9,517
2.109375
2
[]
no_license
package com.po771.plaemo; import android.Manifest; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.po771.plaemo.DB.BaseHelper; import com.po771.plaemo.item.Item_book; import com.po771.plaemo.item.Item_folder; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class SplashActivity extends AppCompatActivity { // DataManager dataManager; long startTime; long endTime; private final int PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startTime = System.currentTimeMillis(); if(request()){ initThing(); endTime = System.currentTimeMillis(); long delayMax = 2000; long delayTime = endTime - startTime; if (delayMax > delayTime) { try { Thread.sleep(delayMax - delayTime); } catch (InterruptedException e) { } } Intent intent = new Intent(this, PlaemoMainFolderActivity.class); startActivity(intent); finish(); } } private boolean request(){ int permssionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); if (permssionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); return false; } else{ return true; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { initThing(); endTime = System.currentTimeMillis(); long delayMax = 2000; long delayTime = endTime - startTime; if (delayMax > delayTime) { try { Thread.sleep(delayMax - delayTime); } catch (InterruptedException e) { } } Intent intent = new Intent(this, PlaemoMainFolderActivity.class); startActivity(intent); finish(); } else { finish(); } return; } } } private void initThing(){ BaseHelper baseHelper = BaseHelper.getInstance(this); if(baseHelper.initDB()){ Item_folder folder = new Item_folder(); folder.setBook_id(-1);//더미값 folder.setFolder_name("전체"); baseHelper.insertFolder(folder); folder.setBook_id(-2);//더미값 folder.setFolder_name("즐겨찾기"); baseHelper.insertFolder(folder); // // //여기서부턴 더미 // folder.setBook_id(1); // folder.setFolder_name("집교1"); // baseHelper.insertFolder(folder); // // folder.setBook_id(1); // folder.setFolder_name("집교2"); // baseHelper.insertFolder(folder); // // folder.setBook_id(2); // folder.setFolder_name("집교1"); // baseHelper.insertFolder(folder); // // folder.setBook_id(2); // folder.setFolder_name("집교2"); // baseHelper.insertFolder(folder); // // folder.setBook_id(2); // folder.setFolder_name("HCI"); // baseHelper.insertFolder(folder); // // folder.setBook_id(3); // folder.setFolder_name("집교1"); // baseHelper.insertFolder(folder); // // folder.setBook_id(3); // folder.setFolder_name("HCI"); // baseHelper.insertFolder(folder); // // folder.setBook_id(4); // folder.setFolder_name("집교1"); // baseHelper.insertFolder(folder); // // folder.setBook_id(4); // folder.setFolder_name("집교2"); // baseHelper.insertFolder(folder); // // folder.setBook_id(4); // folder.setFolder_name("HCI"); // baseHelper.insertFolder(folder); // // Item_book item_book= new Item_book(); // item_book.setBook_name("집교책1"); // item_book.setBook_uri("책 위치"); // item_book.setCurrent_page(20); // item_book.setTotal_page(100); // item_book.setBook_info("책1"); // item_book.setBook_star(1); // item_book.setFolder("집교1/집교2"); // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.book1); // saveToInternalStorage(bitmap,"1"); // baseHelper.insertBook(item_book); // // item_book.setBook_name("집교책2"); // item_book.setBook_uri("책 위치2"); // item_book.setCurrent_page(40); // item_book.setTotal_page(100); // item_book.setBook_info("책2"); // item_book.setBook_star(1); // item_book.setFolder("집교1/집교2/HCI"); // bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.book2); // saveToInternalStorage(bitmap,"2"); // baseHelper.insertBook(item_book); // // item_book.setBook_name("집교책3"); // item_book.setBook_uri("책 위치3"); // item_book.setCurrent_page(99); // item_book.setTotal_page(100); // item_book.setBook_info("책3"); // item_book.setBook_star(1); // item_book.setFolder("집교1/HCI"); // bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.book3); // saveToInternalStorage(bitmap,"3"); // baseHelper.insertBook(item_book); // // item_book.setBook_name("집교책4"); // item_book.setBook_uri("책 위치4"); // item_book.setCurrent_page(99); // item_book.setTotal_page(200); // item_book.setBook_info("책4"); // item_book.setBook_star(1); // item_book.setFolder("집교1/집교2/HCI"); // bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.book4); // saveToInternalStorage(bitmap,"4"); // baseHelper.insertBook(item_book); } AlarmLoader alarmLoader = AlarmLoader.getInstance(this); alarmLoader.initAlarm(baseHelper.getAllalarm()); } // private String saveToInternalStorage(Bitmap bitmapImage,String fileName) { // DisplayMetrics displaymetrics = new DisplayMetrics(); // getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); // int layoutwidth = displaymetrics.widthPixels / 3; // // Bitmap resized = resizeBitmapImage(bitmapImage,layoutwidth); // // // ContextWrapper cw = new ContextWrapper(getApplicationContext()); // // path to /data/data/yourapp/app_data/imageDir // File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); // // Create imageDir // File mypath = new File(directory, fileName + ".jpg"); // // FileOutputStream fos = null; // try { // fos = new FileOutputStream(mypath); // // Use the compress method on the BitMap object to write image to the OutputStream // resized.compress(Bitmap.CompressFormat.JPEG, 100, fos); // } catch (Exception e) { // e.printStackTrace(); // } finally { // try { // fos.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // return directory.getAbsolutePath(); // } public Bitmap resizeBitmapImage(Bitmap source, int maxResolution) { int width = source.getWidth(); int height = source.getHeight(); int newWidth = width; int newHeight = height; float rate = 0.0f; if(width > height) { if(maxResolution < width) { rate = maxResolution / (float) width; newHeight = (int) (height * rate); newWidth = maxResolution; } } else { if(maxResolution < height) { rate = maxResolution / (float) height; newWidth = (int) (width * rate); newHeight = maxResolution; } } return Bitmap.createScaledBitmap(source, newWidth, newHeight, true); } }
true
dc5130a1333c52829bb7ff7efee36f7b81d20ba3
Java
RegisDeVallis/World-Time-Alarm
/src/gnu/kawa/xml/MakeText.java
UTF-8
3,730
1.921875
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package gnu.kawa.xml; import gnu.bytecode.ClassType; import gnu.bytecode.CodeAttr; import gnu.bytecode.Type; import gnu.bytecode.Variable; import gnu.expr.ApplyExp; import gnu.expr.Compilation; import gnu.expr.ConsumerTarget; import gnu.expr.Expression; import gnu.expr.QuoteExp; import gnu.expr.Target; import gnu.mapping.CallContext; import gnu.mapping.Values; import gnu.xml.NodeTree; import gnu.xml.TextUtils; import gnu.xml.XMLFilter; // Referenced classes of package gnu.kawa.xml: // NodeConstructor, KText public class MakeText extends NodeConstructor { public static final MakeText makeText = new MakeText(); public MakeText() { } public static void text$X(Object obj, CallContext callcontext) { gnu.lists.Consumer consumer; XMLFilter xmlfilter; if (obj == null || (obj instanceof Values) && ((Values)obj).isEmpty()) { return; } consumer = callcontext.consumer; xmlfilter = NodeConstructor.pushNodeContext(callcontext); TextUtils.textValue(obj, xmlfilter); NodeConstructor.popNodeContext(consumer, callcontext); return; Exception exception; exception; NodeConstructor.popNodeContext(consumer, callcontext); throw exception; } public void apply(CallContext callcontext) { text$X(callcontext.getNextArg(null), callcontext); } public Object apply1(Object obj) { if (obj == null || (obj instanceof Values) && ((Values)obj).isEmpty()) { return obj; } else { NodeTree nodetree = new NodeTree(); TextUtils.textValue(obj, new XMLFilter(nodetree)); return KText.make(nodetree); } } public void compile(ApplyExp applyexp, Compilation compilation, Target target) { ApplyExp.compile(applyexp, compilation, target); } public void compileToNode(ApplyExp applyexp, Compilation compilation, ConsumerTarget consumertarget) { label0: { CodeAttr codeattr = compilation.getCode(); Expression expression = applyexp.getArgs()[0]; Variable variable = consumertarget.getConsumerVariable(); if (expression instanceof QuoteExp) { Object obj = ((QuoteExp)expression).getValue(); if (obj instanceof String) { String s = (String)obj; String s1 = CodeAttr.calculateSplit(s); int i = s1.length(); ClassType classtype = (ClassType)variable.getType(); Type atype[] = new Type[1]; atype[0] = Type.string_type; gnu.bytecode.Method method = classtype.getMethod("write", atype); int j = 0; for (int k = 0; k < i; k++) { codeattr.emitLoad(variable); int l = j + s1.charAt(k); codeattr.emitPushString(s.substring(j, l)); codeattr.emitInvoke(method); j = l; } break label0; } } expression.compile(compilation, Target.pushObject); codeattr.emitLoad(variable); codeattr.emitInvokeStatic(ClassType.make("gnu.xml.TextUtils").getDeclaredMethod("textValue", 2)); } } public int numArgs() { return 4097; } }
true
0bc6926dfbe0b36a24e53357926b8eb1e6ee112a
Java
sarashawky/Flicker
/app/src/main/java/com/example/android/flickr/MainActivity.java
UTF-8
3,868
2.09375
2
[]
no_license
package com.example.android.flickr; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private final String image_titles[] = { "R18_4489", "Buizerd", "_MG_7157F_Heron", "Snowy Owl", "Fly past", "Gull over Hollow Pond", "Incoming", "Raspberry Pi Trailcam", "Eye-to-Eye: Choco Toucan (Ramphastos brevis)", "Two Colorful Macaws", "Carpe Diem", "Two Colorful Macaws", "Can't you see I'm busy", "Birds at Balatonf u00fcred", "Jay", "Jay", "Marsh Tit (Poecile palustris)", "CS-20181124-10", "CS-20181124-32", "CS-20181124-36" }; private final String image_ids[] = { "https://farm5.staticflickr.com//4806//45421765694_ceb7d6d37b_b.jpg", "https://farm5.staticflickr.com//4835//46145461211_1a857dedf7_b.jpg", "https://farm5.staticflickr.com//4837//46145400621_816ca54622_b.jpg", "https://farm5.staticflickr.com//4827//46095068002_cd132fdf0b_b.jpg", "https://farm5.staticflickr.com//4834//31206370127_5f1258f5ae_b.jpg", "https://farm5.staticflickr.com//4872//44328763800_f5c5224f10_b.jpg", "https://farm5.staticflickr.com//4906//46095222142_322c3a1aff_b.jpg", "https://farm5.staticflickr.com//4868//45233723965_53eee1cf29_b.jpg", "https://farm5.staticflickr.com//4810//46095203652_c4042620a0_b.jpg", "https://farm5.staticflickr.com//4845//44328725800_47c3a12ab0_b.jpg", "https://farm5.staticflickr.com//4814//46145326691_6246260561_b.jpg", "https://farm5.staticflickr.com//4838//46095166672_40ba3449b6_b.jpg", "https://farm5.staticflickr.com//4823//46145299381_856d1cf2c6_b.jpg", "https://farm5.staticflickr.com//4844//44328664770_6bfd18d0c2_b.jpg", "https://farm5.staticflickr.com//4870//46145243511_ed5d166534_b.jpg", "https://farm5.staticflickr.com//4842//31206226797_07274354cf_b.jpg", "https://farm5.staticflickr.com//4881//45421537414_20532f7307_b.jpg", "https://farm5.staticflickr.com///4875//45233616435_6e24dce36b_b.jpg", "https://farm5.staticflickr.com//4902//45233614625_2994298e4c_b.jpg", "https://farm5.staticflickr.com//4810//45233613305_1668f4b403_b.jpg" }; SwipeRefreshLayout swiper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycleView); recyclerView.setHasFixedSize(true); swiper= (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),1); recyclerView.setLayoutManager(layoutManager); ArrayList<Item> createLists = prepareData(); MyAdapter adapter = new MyAdapter(getApplicationContext(), createLists,swiper); recyclerView.setAdapter(adapter); } private ArrayList<Item> prepareData(){ ArrayList<Item> theimage = new ArrayList<>(); for(int i = 0; i< image_titles.length; i++){ Item createList = new Item(); createList.setImage_title(image_titles[i]); createList.setImage_id(image_ids[i]); theimage.add(createList); } return theimage; } }
true
b6634cc3c83e3934fb4e2b7d20f5b454f9c43bff
Java
GalalMagdySafwat/buildItBigger
/JokeLib/src/main/java/com/example/jokelib/MyClass.java
UTF-8
632
2.96875
3
[]
no_license
package com.example.jokelib; import java.util.Random; public class MyClass { public static String[] jokes = {"Q: Can Bees fly in the rain? A: Not without their yellow jackets.", "Q: What is a Queens favorite kind of precipitation? A: Reign!", "Q: What is the Mexican weather report? A: Chili today and hot tamale.", "Q. What is the biggest lie in the entire universe? A. I have read and agree to the Terms & Conditions." }; public String getJoke() { Random random = new Random(); int randomN = random.nextInt(jokes.length); return jokes[randomN]; } }
true
b5f60a3839f15c6f3cb6d8b4b1f9a2f939abb40d
Java
AndreSchuchmann/My-Stuff
/Uni/Kniffel/src/ergebnisse/SummeOben.java
UTF-8
1,261
3.34375
3
[]
no_license
package ergebnisse; import logic.*; /** * * @author Katharina, Ali, Fritz and Andr� * * Berechnet die Summe Oben, das hei�t das Programm rechnet die oben erzielten Punkte zusammen * */ public class SummeOben extends Ergebnis { protected int wert; /** * */ public SummeOben(int wert) { this.wert=wert; oben=true; } /** * Berechnet die moeglichen Punkte, die dieser Wurf geben wuerde */ @Override public int punkteBerechnen(Wurf wurf) { int zusammen=0; for(Wuerfel w: wurf.getAlleWuerfel()){ if(w.getAugenzahl()==wert){ zusammen = zusammen + w.getAugenzahl(); } } return zusammen; } /** * @return true wenn der Wurf die Bedingung erfuellt */ @Override public boolean ueberpruefen(Wurf wurf) { if(gestrichen||summe!=0){ return false; } for(Wuerfel w : wurf.getAlleWuerfel()){ if(w.getAugenzahl()==wert){ return true; } } return false; } public int getWert(){ return wert; } public String getName(){ return this.wert+"er"; } }
true
40ee32251fa33c1ca567dbb1db0076b36066b1d2
Java
aradzimski/Ticket-Machine
/app/src/main/java/com/example/ticket_machine/MainActivity.java
UTF-8
8,592
2.0625
2
[]
no_license
package com.example.ticket_machine; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.drawerlayout.widget.DrawerLayout; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.example.ticket_machine.tools.SharedPreferenceConfig; import com.google.android.material.navigation.NavigationView; /** * This is the main class of the application, a navigation menu is implemented here. * MainActivity class extends the AppCompatActivity class. */ public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration; private SharedPreferenceConfig preferenceConfig; private NavigationView navigationView; private DrawerLayout drawer; private String role_none,role_customer,role_bodyguard,role_admin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); preferenceConfig = new SharedPreferenceConfig(getApplicationContext()); drawer = findViewById(R.id.drawer_layout); navigationView = findViewById(R.id.nav_view); /** * Get role name from resources. */ role_none = getResources().getString(R.string.role_none); role_customer = getResources().getString(R.string.role_customer); role_bodyguard = getResources().getString(R.string.role_bodyguard); role_admin = getResources().getString(R.string.role_admin); /** * Show proper item in navigation menu, depends on user permissions level. */ showedMenuItem(); /** * Passing each menu ID as a set of Ids because each * menu should be considered as top level destinations. */ mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.nav_home, R.id.nav_register, R.id.nav_login, R.id.nav_events, R.id.nav_tickets, R.id.nav_accounts, R.id.nav_scanner, R.id.nav_events_manage) .setDrawerLayout(drawer) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration); NavigationUI.setupWithNavController(navigationView, navController); Menu nav_menu = navigationView.getMenu(); nav_menu.findItem(R.id.nav_tickets).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Context context = getApplicationContext(); Intent intent = new Intent(context, TicketsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } }); nav_menu.findItem(R.id.nav_scanner).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Context context = getApplicationContext(); Intent intent = new Intent(context, ScannerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } }); } /** * Method is implemented because we want show proper elements in navigation menu when user come back to main activity. * For that we use showedMenuItem() method which show proper item in navigation menu, depends on user permissions level. */ @Override protected void onResume() { super.onResume(); showedMenuItem(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.action_logout : String permission_level = preferenceConfig.LoadUserRole(); if(permission_level.equals(role_none)){ Toast.makeText(this,getResources().getString(R.string.can_not_logout),Toast.LENGTH_SHORT).show(); }else{ preferenceConfig.SaveUserRole(role_none); moveToNewActivity(); Toast.makeText(this,getResources().getString(R.string.success_logout),Toast.LENGTH_SHORT).show(); } return true; case R.id.action_settings : Toast.makeText(this,getResources().getString(R.string.text_testtings),Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } /** * To show only base element from navigation menu before login to app ! */ private void itemBeforeLogin(Menu nav) { nav.findItem(R.id.nav_events_manage).setVisible(false); nav.findItem(R.id.nav_scanner).setVisible(false); nav.findItem(R.id.nav_accounts).setVisible(false); nav.findItem(R.id.nav_tickets).setVisible(false); nav.findItem(R.id.nav_events).setVisible(false); nav.findItem(R.id.nav_register).setVisible(true); nav.findItem(R.id.nav_login).setVisible(true); } /** * To hide all element from navigation menu after login to app, * in another method we set the specific navigation item depend on permission level. * @param nav */ private void itemAfterLogin(Menu nav){ nav.findItem(R.id.nav_register).setVisible(false); nav.findItem(R.id.nav_login).setVisible(false); nav.findItem(R.id.nav_events_manage).setVisible(false); nav.findItem(R.id.nav_scanner).setVisible(false); nav.findItem(R.id.nav_accounts).setVisible(false); nav.findItem(R.id.nav_tickets).setVisible(false); nav.findItem(R.id.nav_events).setVisible(false); } /** * This method determines which element from navigation menu will by shown for specific user, * of course it depends on user permission level. */ public void showedMenuItem(){ String permission_level = preferenceConfig.LoadUserRole(); Menu nav_Menu = navigationView.getMenu(); if(permission_level.equals(role_customer)){ itemAfterLogin(nav_Menu); nav_Menu.findItem(R.id.nav_tickets).setVisible(true); nav_Menu.findItem(R.id.nav_events).setVisible(true); }else if(permission_level.equals(role_bodyguard)){ itemAfterLogin(nav_Menu); nav_Menu.findItem(R.id.nav_scanner).setVisible(true); }else if(permission_level.equals(role_admin)){ itemAfterLogin(nav_Menu); nav_Menu.findItem(R.id.nav_events_manage).setVisible(true); nav_Menu.findItem(R.id.nav_scanner).setVisible(true); nav_Menu.findItem(R.id.nav_accounts).setVisible(true); nav_Menu.findItem(R.id.nav_tickets).setVisible(true); nav_Menu.findItem(R.id.nav_events).setVisible(true); }else{ itemBeforeLogin(nav_Menu); } } /** * The task of this method is to transfer us to another activity and finish the old activity. * In this case it is used when user use logout operation. */ private void moveToNewActivity () { Intent i = new Intent(this, MainActivity.class); startActivity(i); finish(); (this).overridePendingTransition(0, 0); } }
true
275dfdcab2af720b584249122d9508f79fd99764
Java
lazyplus/826Code
/src/LBP.java
UTF-8
36,006
1.984375
2
[]
no_license
/*********************************************************************** PEGASUS: Peta-Scale Graph Mining System Copyright (c) 2010 U Kang and Christos Faloutsos All Rights Reserved You may use this code without fee, for educational and research purposes. Any for-profit use requires written consent of the copyright holders. ------------------------------------------------------------------------- File: LinearBP.java - Linearized Belief Propagation Version: 0.9 Author Email: U Kang(ukang@cs.cmu.edu), Christos Faloutsos(christos@cs.cmu.edu) ***********************************************************************/ import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Partitioner; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; // y = y + ax class SaxpyTextoutput extends Configured implements Tool { // //////////////////////////////////////////////////////////////////// // STAGE 1: make initial pagerank vector // //////////////////////////////////////////////////////////////////// // MapStage1: public static class MapStage1 extends MapReduceBase implements Mapper<LongWritable, Text, IntWritable, DoubleWritable> { private final IntWritable from_node_int = new IntWritable(); private boolean isYpath = false; private boolean isXpath = false; private double a; @Override public void configure(JobConf job) { String y_path = job.get("y_path"); String x_path = job.get("x_path"); a = Double.parseDouble(job.get("a")); String input_file = job.get("map.input.file"); if (input_file.contains(y_path)) isYpath = true; else if (input_file.contains(x_path)) isXpath = true; System.out.println("SaxpyTextoutput.MapStage1: map.input.file = " + input_file + ", isYpath=" + isYpath + ", isXpath=" + isXpath + ", a=" + a); } @Override public void map(final LongWritable key, final Text value, final OutputCollector<IntWritable, DoubleWritable> output, final Reporter reporter) throws IOException { String line_text = value.toString(); int tabpos = line_text.indexOf("\t"); int out_key = Integer.parseInt(line_text.substring(0, tabpos)); double out_val = 0; if (line_text.charAt(tabpos + 1) == 'v') { out_val = Double.parseDouble(line_text.substring(tabpos + 2)); } else { out_val = Double.parseDouble(line_text.substring(tabpos + 1)); } if (isYpath) { output.collect(new IntWritable(out_key), new DoubleWritable( out_val)); } else if (isXpath) { output.collect(new IntWritable(out_key), new DoubleWritable(a * out_val)); } } } // RedStage1 public static class RedStage1 extends MapReduceBase implements Reducer<IntWritable, DoubleWritable, IntWritable, Text> { @Override public void reduce(final IntWritable key, final Iterator<DoubleWritable> values, final OutputCollector<IntWritable, Text> output, final Reporter reporter) throws IOException { int i = 0; double val_double[] = new double[2]; val_double[0] = 0; val_double[1] = 0; while (values.hasNext()) { val_double[i] = values.next().get(); i++; } double result = val_double[0] + val_double[1]; if (result != 0) output.collect(key, new Text("v" + result)); } } // //////////////////////////////////////////////////////////////////// // command line interface // //////////////////////////////////////////////////////////////////// protected int nreducers = 1; // Main entry point. public static void main(final String[] args) throws Exception { final int result = ToolRunner.run(new Configuration(), new SaxpyTextoutput(), args); System.exit(result); } // Print the command-line usage text. protected static int printUsage() { System.out .println("SaxpyTextoutput <# of reducers> <y_path> <x_path> <a>"); // ToolRunner.printGenericCommandUsage(System.out); return -1; } // submit the map/reduce job. @Override public int run(final String[] args) throws Exception { if (args.length != 4) { return printUsage(); } int ret_val = 0; nreducers = Integer.parseInt(args[0]); Path y_path = new Path(args[1]); Path x_path = new Path(args[2]); double param_a = Double.parseDouble(args[3]); System.out .println("\n-----===[PEGASUS: A Peta-Scale Graph Mining System]===-----\n"); System.out.println("[PEGASUS] Computing SaxpyTextoutput. y_path=" + y_path.toString() + ", x_path=" + x_path.toString() + ", a=" + param_a + "\n"); final FileSystem fs = FileSystem.get(getConf()); Path saxpy_output = new Path("saxpy_output"); if (y_path.toString().equals("saxpy_output")) { System.out .println("saxpy(): output path name is same as the input path name: changing the output path name to saxpy_output1"); saxpy_output = new Path("saxpy_output1"); ret_val = 1; } fs.delete(saxpy_output); JobClient.runJob(configSaxpyTextoutput(y_path, x_path, saxpy_output, param_a)); System.out .println("\n[PEGASUS] SaxpyTextoutput computed. Output is saved in HDFS " + saxpy_output.toString() + "\n"); return ret_val; // return value : 1 (output path is saxpy_output1) // 0 (output path is saxpy_output) } // Configure SaxpyTextoutput protected JobConf configSaxpyTextoutput(Path py, Path px, Path saxpy_output, double a) throws Exception { final JobConf conf = new JobConf(getConf(), SaxpyTextoutput.class); conf.set("y_path", py.toString()); conf.set("x_path", px.toString()); conf.set("a", "" + a); conf.setJobName("SaxpyTextoutput"); conf.setMapperClass(SaxpyTextoutput.MapStage1.class); conf.setReducerClass(SaxpyTextoutput.RedStage1.class); FileInputFormat.setInputPaths(conf, py, px); FileOutputFormat.setOutputPath(conf, saxpy_output); conf.setNumReduceTasks(nreducers); conf.setOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(DoubleWritable.class); conf.setOutputValueClass(Text.class); return conf; } } class DegDist extends Configured implements Tool { // InOutDeg : single-count reciprocal edges. InPlusOutDeg: double-count // reciprocal edges static int InDeg = 1, OutDeg = 2, InOutDeg = 3, InPlusOutDeg = 4; // //////////////////////////////////////////////////////////////////// // PASS 1: group by node id. // Input : edge list // Output : key(node_id), value(degree) // //////////////////////////////////////////////////////////////////// public static class MapPass1 extends MapReduceBase implements Mapper<LongWritable, Text, IntWritable, IntWritable> { int deg_type = 0; @Override public void configure(JobConf job) { deg_type = Integer.parseInt(job.get("deg_type")); System.out.println("MapPass1 : configure is called. degtype = " + deg_type); } @Override public void map(final LongWritable key, final Text value, final OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException { String line_text = value.toString(); if (line_text.startsWith("#") || line_text.length() == 0) // ignore // comments // in // edge // file return; String[] line = line_text.split("\t"); IntWritable one_int = new IntWritable(1); if (deg_type == OutDeg) { IntWritable key_node_int = new IntWritable(); key_node_int.set(Integer.parseInt(line[0])); output.collect(key_node_int, one_int); } else if (deg_type == InDeg) { output.collect(new IntWritable(Integer.parseInt(line[1])), one_int); } else if (deg_type == InOutDeg) { // emit both IntWritable from_node_int = new IntWritable( Integer.parseInt(line[0])); IntWritable to_node_int = new IntWritable( Integer.parseInt(line[1])); output.collect(from_node_int, to_node_int); output.collect(to_node_int, from_node_int); } else if (deg_type == InPlusOutDeg) { // emit both IntWritable from_node_int = new IntWritable( Integer.parseInt(line[0])); IntWritable to_node_int = new IntWritable( Integer.parseInt(line[1])); output.collect(from_node_int, one_int); output.collect(to_node_int, one_int); } } } public static class RedPass1 extends MapReduceBase implements Reducer<IntWritable, IntWritable, IntWritable, IntWritable> { int deg_type = 0; @Override public void configure(JobConf job) { deg_type = Integer.parseInt(job.get("deg_type")); System.out.println("RedPass1 : configure is called. degtype = " + deg_type); } @Override public void reduce(final IntWritable key, final Iterator<IntWritable> values, OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException { int degree = 0; if (deg_type != InOutDeg) { while (values.hasNext()) { int cur_degree = values.next().get(); degree += cur_degree; } output.collect(key, new IntWritable(degree)); } else if (deg_type == InOutDeg) { Set<Integer> outEdgeSet = new TreeSet<Integer>(); while (values.hasNext()) { int cur_outedge = values.next().get(); outEdgeSet.add(cur_outedge); } output.collect(key, new IntWritable(outEdgeSet.size())); } } } // ////////////////////////////////////////////////////////////////////////////////////////////// // PASS 2: group by degree // Input : key(node id), value(degree) // Output : key(degree), value(count) // ////////////////////////////////////////////////////////////////////////////////////////////// public static class MapPass2 extends MapReduceBase implements Mapper<LongWritable, Text, IntWritable, IntWritable> { @Override public void map(final LongWritable key, final Text value, final OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException { String[] line = value.toString().split("\t"); output.collect(new IntWritable(Integer.parseInt(line[1])), new IntWritable(1)); } } public static class RedPass2 extends MapReduceBase implements Reducer<IntWritable, IntWritable, IntWritable, IntWritable> { @Override public void reduce(final IntWritable key, final Iterator<IntWritable> values, final OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException { int count = 0; while (values.hasNext()) { int cur_count = values.next().get(); count += cur_count; } output.collect(key, new IntWritable(count)); } } // //////////////////////////////////////////////////////////////////// // command line interface // //////////////////////////////////////////////////////////////////// protected Path edge_path = null; protected Path node_deg_path = null; protected Path deg_count_path = null; protected int nreducer = 1; protected int deg_type; // Main entry point. public static void main(final String[] args) throws Exception { final int result = ToolRunner.run(new Configuration(), new DegDist(), args); System.exit(result); } // Print the command-line usage text. protected static int printUsage() { System.out .println("DegDist <edge_path> <node_deg_path> <deg_count_path> <in or out or inout or inpout> <# of reducer>"); ToolRunner.printGenericCommandUsage(System.out); return -1; } // submit the map/reduce job. @Override public int run(final String[] args) throws Exception { if (args.length != 5) { return printUsage(); } edge_path = new Path(args[0]); node_deg_path = new Path(args[1]); deg_count_path = new Path(args[2]); String deg_type_str = "In"; deg_type = InDeg; if (args[3].compareTo("out") == 0) { deg_type = OutDeg; deg_type_str = "Out"; } else if (args[3].compareTo("inout") == 0) { deg_type = InOutDeg; deg_type_str = "InOut"; } else if (args[3].compareTo("inpout") == 0) { deg_type = InPlusOutDeg; deg_type_str = "InPlusOut"; } nreducer = Integer.parseInt(args[4]); System.out .println("\n-----===[PEGASUS: A Peta-Scale Graph Mining System]===-----\n"); System.out .println("[PEGASUS] Computing degree distribution. Degree type = " + deg_type_str + "\n"); // run job JobClient.runJob(configPass1()); JobClient.runJob(configPass2()); System.out.println("\n[PEGASUS] Degree distribution computed."); System.out.println("[PEGASUS] (NodeId, Degree) is saved in HDFS " + args[1] + ", (Degree, Count) is saved in HDFS " + args[2] + "\n"); return 0; } // Configure pass1 protected JobConf configPass1() throws Exception { final JobConf conf = new JobConf(getConf(), DegDist.class); conf.set("deg_type", "" + deg_type); conf.setJobName("DegDist_pass1"); conf.setMapperClass(MapPass1.class); conf.setReducerClass(RedPass1.class); if (deg_type != InOutDeg) { conf.setCombinerClass(RedPass1.class); } FileSystem fs = FileSystem.get(getConf()); fs.delete(node_deg_path); FileInputFormat.setInputPaths(conf, edge_path); FileOutputFormat.setOutputPath(conf, node_deg_path); conf.setNumReduceTasks(nreducer); conf.setOutputKeyClass(IntWritable.class); conf.setOutputValueClass(IntWritable.class); return conf; } // Configure pass2 protected JobConf configPass2() throws Exception { final JobConf conf = new JobConf(getConf(), DegDist.class); conf.setJobName("DegDist_pass2"); conf.setMapperClass(MapPass2.class); conf.setReducerClass(RedPass2.class); conf.setCombinerClass(RedPass2.class); FileSystem fs = FileSystem.get(getConf()); fs.delete(deg_count_path); FileInputFormat.setInputPaths(conf, node_deg_path); FileOutputFormat.setOutputPath(conf, deg_count_path); conf.setNumReduceTasks(nreducer); conf.setOutputKeyClass(IntWritable.class); conf.setOutputValueClass(IntWritable.class); return conf; } } class MatvecNaiveSecondarySort extends Configured implements Tool { // Comparator class that uses only the first token for the comparison. // MyValueGroupingComparator and MyPartition are used for secondary-sort for // building N. // reference: src/examples/org/apache/hadoop/examples/SecondarySort.java public static class MyValueGroupingComparator implements RawComparator<Text> { @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return WritableComparator.compareBytes(b1, s1, Integer.SIZE / 8, b2, s2, Integer.SIZE / 8); } @Override public int compare(Text t1, Text t2) { String str1 = t1.toString(); String str2 = t2.toString(); int pos1 = str1.indexOf("\t"); int pos2 = str2.indexOf("\t"); long l = (Long.parseLong(str1.substring(0, pos1))); long r = (Long.parseLong(str2.substring(0, pos2))); return l == r ? 0 : (l < r ? -1 : 1); } } public static class MyKeyComparator implements RawComparator<Text> { @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return WritableComparator.compareBytes(b1, s1, Integer.SIZE / 8, b2, s2, Integer.SIZE / 8); } @Override public int compare(Text t1, Text t2) { String str1 = t1.toString(); String str2 = t2.toString(); int pos1 = str1.indexOf("\t"); int pos2 = str2.indexOf("\t"); long l = (Long.parseLong(str1.substring(0, pos1))); long r = (Long.parseLong(str2.substring(0, pos2))); if (l != r) return (l < r ? -1 : 1); l = Long.parseLong(str1.substring(pos1 + 1)); r = Long.parseLong(str2.substring(pos2 + 1)); return l == r ? 0 : (l < r ? -1 : 1); } } // Partitioner class that uses only the first token for the partition. // MyValueGroupingComparator and MyPartition are used for secondary-sort for // building N. public static class MyPartition<V2> implements Partitioner<Text, V2> { @Override public void configure(JobConf job) { } @Override public int getPartition(Text key, V2 value, int numReduceTasks) { // System.out.println("[DEBUG] getPartition. key=" + key ); String[] tokens = key.toString().split("\t"); int partition = (int) (Long.parseLong(tokens[0])) % numReduceTasks; return partition; } } // //////////////////////////////////////////////////////////////////// // PASS 1: Hash join using Vector.rowid == Matrix.colid // //////////////////////////////////////////////////////////////////// public static class MapPass1 extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> { int makesym = 0; int transpose = 0; int ignore_weights = 0; @Override public void configure(JobConf job) { makesym = Integer.parseInt(job.get("makesym")); transpose = Integer.parseInt(job.get("transpose")); ignore_weights = Integer.parseInt(job.get("ignore_weights")); String input_file = job.get("map.input.file"); System.out.println("MatvecNaiveSecondarySort.MapPass1: makesym = " + makesym); System.out.println("input_file = " + input_file); } @Override public void map(final LongWritable key, final Text value, final OutputCollector<Text, Text> output, final Reporter reporter) throws IOException { String line_text = value.toString(); if (line_text.startsWith("#")) // ignore comments in edge file return; final String[] line = line_text.split("\t"); // System.out.println("[DEBUG] line_text=[" + line_text + "]"); if (line.length == 2 || ignore_weights == 1) { // vector : ROWID // VALUE('vNNNN') if (line[1].charAt(0) == 'v') { // vector : ROWID VALUE('vNNNN') String key_str = line[0] + "\t0"; // System.out.println("[DEBUG] MapPass1 key=[" + key_str + // "], value=[" + line[1] + "]"); output.collect(new Text(key_str), new Text(line[1])); } else { // edge : ROWID COLID if (transpose == 0) { // System.out.println("[DEBUG] MapPass1 key=[" + line[1] // + "\t1], value=[" + line[0] + "]"); output.collect(new Text(line[1] + "\t1"), new Text( line[0])); if (makesym == 1) output.collect(new Text(line[0] + "\t1"), new Text( line[1])); } else { output.collect(new Text(line[0] + "\t1"), new Text( line[1])); if (makesym == 1) output.collect(new Text(line[1] + "\t1"), new Text( line[0])); } } } else if (line.length == 3) { // edge: ROWID COLID VALUE if (transpose == 0) { String key_str = line[1] + "\t1"; String value_str = line[0] + "\t" + line[2]; // System.out.println("[DEBUG] MapPass1 key=[" + key_str + // "], value=[" + value_str + "]"); output.collect(new Text(key_str), new Text(value_str)); if (makesym == 1) output.collect(new Text(line[0] + "\t1"), new Text( line[1] + "\t" + line[2])); } else { output.collect(new Text(line[0] + "\t1"), new Text(line[1] + "\t" + line[2])); if (makesym == 1) output.collect(new Text(line[1] + "\t1"), new Text( line[0] + "\t" + line[2])); } } } } public static class RedPass1 extends MapReduceBase implements Reducer<Text, Text, LongWritable, DoubleWritable> { @Override public void reduce(final Text key, final Iterator<Text> values, final OutputCollector<LongWritable, DoubleWritable> output, final Reporter reporter) throws IOException { // int i; double vector_val = 0; boolean isValReceived = false; while (values.hasNext()) { String line_text = values.next().toString(); // System.out.println("[DEBUG] RedPass1. Key=[" + key + // "], val=[" + line_text + "]"); if (isValReceived == false) { if (line_text.charAt(0) == 'v') { vector_val = Double.parseDouble(line_text.substring(1)); // System.out.println("[DEBUG] RedPass1. HAPPY EVENT Key=[" // + key + "], val=[" + line_text + "]"); } else { return; // System.out.println("[DEBUG] RedPass1. FATAL ERROR Key=[" // + key + "], val=[" + line_text + "]"); // vector_val = Double.parseDouble( line_text ); } isValReceived = true; } else { String[] tokens = line_text.split("\t"); if (tokens.length == 1) { // edge : ROWID // System.out.println("[DEBUG] RedPass1. outputting key=[" // + tokens[0] + "], val=[" + vector_val + "]"); output.collect( new LongWritable(Long.parseLong(tokens[0])), new DoubleWritable(vector_val)); } else { // edge : ROWID VALUE output.collect( new LongWritable(Long.parseLong(tokens[0])), new DoubleWritable(vector_val * Double.parseDouble(tokens[1]))); } } } } } // //////////////////////////////////////////////////////////////////// // PASS 2: merge partial multiplication results // //////////////////////////////////////////////////////////////////// public static class MapPass2 extends MapReduceBase implements Mapper<LongWritable, Text, LongWritable, Text> { private final LongWritable from_node_int = new LongWritable(); @Override public void map(final LongWritable key, final Text value, final OutputCollector<LongWritable, Text> output, final Reporter reporter) throws IOException { String line_text = value.toString(); if (line_text.startsWith("#")) // ignore comments in edge file return; final String[] line = line_text.split("\t"); from_node_int.set(Long.parseLong(line[0])); output.collect(from_node_int, new Text("v" + Double.parseDouble(line[1]))); } } public static class RedPass2 extends MapReduceBase implements Reducer<LongWritable, Text, LongWritable, Text> { @Override public void reduce(final LongWritable key, final Iterator<Text> values, final OutputCollector<LongWritable, Text> output, final Reporter reporter) throws IOException { double next_rank = 0; while (values.hasNext()) { String cur_value_str = values.next().toString(); next_rank += Double.parseDouble(cur_value_str.substring(1)); } output.collect(key, new Text("v" + next_rank)); } } // //////////////////////////////////////////////////////////////////// // command line interface // //////////////////////////////////////////////////////////////////// protected Path edge_path = null; protected Path tempmv_path = null; protected Path output_path = null; protected Path vector_path = null; protected int number_nodes = 0; protected int nreducer = 1; int makesym = 0; int transpose = 0; int ignore_weights = 0; // Main entry point. public static void main(final String[] args) throws Exception { final int result = ToolRunner.run(new Configuration(), new MatvecNaiveSecondarySort(), args); System.exit(result); } // matrix-vecotr multiplication with secondary sort public static void MatvecNaiveSS(Configuration conf, int nreducer, String mat_path, String vec_path, String out_path, int transpose, int makesym) throws Exception { System.out.println("Running MatvecNaiveSS: mat_path=" + mat_path + ", vec_path=" + vec_path); int ignore_weights = 0; String[] args = new String[8]; args[0] = new String("" + mat_path); args[1] = new String("temp_matvecnaive_ss" + vec_path); args[2] = new String(out_path); args[3] = new String("" + nreducer); if (makesym == 1) args[4] = "makesym"; else args[4] = "nosym"; args[5] = new String(vec_path); args[6] = new String("" + transpose); args[7] = new String("" + ignore_weights); ToolRunner.run(conf, new MatvecNaiveSecondarySort(), args); System.out.println("Done MatvecNaiveSS. Output is saved in HDFS " + out_path); return; } // Print the command-line usage text. protected static int printUsage() { System.out .println("MatvecNaiveSecondarySort <edge_path> <tempmv_path> <output_path> <# of reducers> <makesym or nosym> <vector path>"); ToolRunner.printGenericCommandUsage(System.out); return -1; } // submit the map/reduce job. @Override public int run(final String[] args) throws Exception { if (args.length < 5) { return printUsage(); } edge_path = new Path(args[0]); tempmv_path = new Path(args[1]); output_path = new Path(args[2]); nreducer = Integer.parseInt(args[3]); if (args[4].equals("makesym")) makesym = 1; if (args.length > 5) vector_path = new Path(args[5]); if (args.length > 6) transpose = Integer.parseInt(args[6]); if (args.length > 7) ignore_weights = Integer.parseInt(args[7]); final FileSystem fs = FileSystem.get(getConf()); fs.delete(tempmv_path); fs.delete(output_path); System.out.println("Starting MatvecNaiveSecondarySort. tempmv_path=" + args[1] + ", transpose=" + transpose); JobClient.runJob(configPass1()); JobClient.runJob(configPass2()); fs.delete(tempmv_path); System.out.println("Done. output is saved in HDFS " + args[2]); return 0; } // Configure pass1 protected JobConf configPass1() throws Exception { final JobConf conf = new JobConf(getConf(), MatvecNaiveSecondarySort.class); conf.set("number_nodes", "" + number_nodes); conf.set("makesym", "" + makesym); conf.set("transpose", "" + transpose); conf.set("ignore_weights", "" + ignore_weights); conf.setJobName("MatvecNaiveSecondarySort_pass1"); System.out.println("Configuring MatvecNaiveSecondarySort. makesym=" + makesym); conf.setMapperClass(MapPass1.class); conf.setReducerClass(RedPass1.class); conf.setPartitionerClass(MyPartition.class); conf.setOutputValueGroupingComparator(MyValueGroupingComparator.class); // conf.setOutputKeyComparatorClass(MyKeyComparator.class); if (vector_path == null) FileInputFormat.setInputPaths(conf, edge_path); else FileInputFormat.setInputPaths(conf, edge_path, vector_path); FileOutputFormat.setOutputPath(conf, tempmv_path); conf.setNumReduceTasks(nreducer); conf.setOutputKeyClass(LongWritable.class); conf.setOutputValueClass(DoubleWritable.class); conf.setMapOutputKeyClass(Text.class); conf.setMapOutputValueClass(Text.class); return conf; } // Configure pass2 protected JobConf configPass2() throws Exception { final JobConf conf = new JobConf(getConf(), MatvecNaiveSecondarySort.class); conf.set("number_nodes", "" + number_nodes); conf.setJobName("MatvecNaive_pass2"); conf.setMapperClass(MapPass2.class); conf.setReducerClass(RedPass2.class); conf.setCombinerClass(RedPass2.class); FileInputFormat.setInputPaths(conf, tempmv_path); FileOutputFormat.setOutputPath(conf, output_path); conf.setNumReduceTasks(nreducer); conf.setOutputKeyClass(LongWritable.class); // conf.setMapOutputValueClass(DoubleWritable.class); conf.setOutputValueClass(Text.class); return conf; } } public class LBP extends Configured implements Tool { public static class MapComputeM extends MapReduceBase implements Mapper<LongWritable, Text, LongWritable, Text> { double c = 1; double a = 1; boolean isDeg = false; @Override public void configure(JobConf job) { c = Double.parseDouble(job.get("c")); a = Double.parseDouble(job.get("a")); String input_file = job.get("map.input.file"); if (input_file.indexOf("dd_node_deg") >= 0) isDeg = true; System.out.println("[MapComputeM] c = " + c + ", a = " + a + ", input_file = " + input_file + ", isDeg = " + isDeg); } @Override public void map(final LongWritable key, final Text value, final OutputCollector<LongWritable, Text> output, final Reporter reporter) throws IOException { String line_text = value.toString(); if (line_text.startsWith("#")) // ignore comments in edge file return; final String[] tokens = line_text.split("\t"); if (tokens.length < 2) return; if (isDeg == true) { double deg = -1 * a * Double.parseDouble(tokens[1]); output.collect(new LongWritable(Long.parseLong(tokens[0])), new Text("" + tokens[0] + "\t" + deg)); } else { if (tokens.length == 2) { output.collect(new LongWritable(Long.parseLong(tokens[0])), new Text("" + tokens[1] + "\t" + c)); } } } } public static class MapInitPrior extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> { @Override public void map(final LongWritable key, final Text value, final OutputCollector<Text, Text> output, final Reporter reporter) throws IOException { String line_text = value.toString(); if (line_text.startsWith("#")) // ignore comments in edge file return; final String[] tokens = line_text.split("\t"); if (tokens.length < 2) return; double prior_val = Double.parseDouble(tokens[1].substring(1)) - 0.5; output.collect(new Text(tokens[0]), new Text("v" + prior_val)); } } protected static void copyToLocalFile(Configuration conf, Path hdfs_path, Path local_path) throws Exception { FileSystem fs = FileSystem.get(conf); // read the result fs.copyToLocalFile(hdfs_path, local_path); } // //////////////////////////////////////////////////////////////////// // command line interface // //////////////////////////////////////////////////////////////////// String edge_path_str = null; String prior_path_str = null; String output_path_str = null; protected Path edge_path = null; protected Path prior_path = null; protected Path message_cur_path = new Path("bp_message_cur"); protected Path message_next_path = new Path("bp_message_next"); protected Path error_check_path = new Path("bp_error_check"); protected Path error_check_sum_path = new Path("bp_error_check_sum"); protected Path output_path = null; protected long number_edges = 0; protected int max_iter = 32; protected int nreducers = 1; protected int nstate = 2; String edge_potential_str = ""; FileSystem fs; double hh = 0.0001; protected String local_output_path = "lbp_local"; int number_nodes = 0; double a = 0; double c = 0; // Main entry point. public static void main(final String[] args) throws Exception { final int result = ToolRunner.run(new Configuration(), new LBP(), args); System.exit(result); } // Print the command-line usage text. protected static int printUsage() { System.out .println("LinearBP <edge_path> <prior_path> <output_path> <# of nodes> <# of reducer> <max iteration> <L1 or L2>"); ToolRunner.printGenericCommandUsage(System.out); return -1; } public static Path SaxpyTextoutput(Configuration conf, int nreducer, String py_name, String px_name, String outpath_name, double a) throws Exception { // System.out.println("Running Saxpy: py=" + py.getName() + ", px=" + // px.getName() + ", a=" +a); String[] args = new String[4]; args[0] = new String("" + nreducer); args[1] = new String(py_name); args[2] = new String(px_name); args[3] = new String("" + a); int saxpy_result = ToolRunner.run(conf, new SaxpyTextoutput(), args); // Path ret_path = null; Path out_path = new Path(outpath_name); FileSystem fs = FileSystem.get(conf); fs.delete(out_path, true); if (saxpy_result == 1) fs.rename(new Path("saxpy_output1"), out_path); else fs.rename(new Path("saxpy_output"), out_path); return out_path; } // submit the map/reduce job. @Override public int run(String[] args) throws Exception { if (args.length != 7) { for (String a : args) { System.out.println(a); } System.out.println("args num: " + args.length); return printUsage(); } edge_path_str = args[0]; prior_path_str = args[1]; output_path_str = args[2]; edge_path = new Path(edge_path_str); prior_path = new Path(prior_path_str); output_path = new Path(output_path_str); Path vector_path = new Path("lbp_cur_vector"); number_nodes = Integer.parseInt(args[3]); nreducers = Integer.parseInt(args[4]); nreducers = 1; max_iter = Integer.parseInt(args[5]); String hh_method = args[6]; System.out.println("edge_path=" + args[0] + ", prior_path=" + args[1] + ", output_path=" + args[2] + ", nreducers=" + nreducers + ", maxiter=" + max_iter + ", hh_method=" + hh_method); fs = FileSystem.get(getConf()); int cur_iter = 1; // Step 1. compute h_h System.out .println("####################################################"); System.out.println("Step 1. Computing h_h"); // (1.1) compute degree args = new String[5]; args[0] = edge_path_str; args[1] = "dd_node_deg"; args[2] = "dd_deg_count"; args[3] = "in"; args[4] = new String("" + nreducers); ToolRunner.run(getConf(), new DegDist(), args); if (hh_method.startsWith("PRE")) { hh = Double.parseDouble(hh_method.substring(3)); } double temp_denom = (1 - 4 * hh * hh); a = 4 * hh * hh / temp_denom; c = 2 * hh / temp_denom; System.out.println("h_h = " + hh + ", a = " + a + ", c = " + c); // Step 2. Init prior // Input: prior_path // Output: vector_path System.out .println("####################################################"); System.out.println("Step 2. computing initial vector"); JobClient.runJob(configInitPrior(prior_path, vector_path)); // Step 2. compute M = cA - aD System.out .println("####################################################"); System.out.println("Step 3. Computing M = cA - aD"); Path m_path = new Path("lbp_m_path"); JobClient.runJob(configComputeM(edge_path, new Path("dd_node_deg"), m_path, c, a)); for (int i = cur_iter; i <= max_iter; i++) { System.out.println(" *** ITERATION " + (i) + "/" + max_iter + " ***"); MatvecNaiveSecondarySort.MatvecNaiveSS(getConf(), nreducers, "lbp_m_path", "lbp_cur_vector", "mv_output", 0, 0); Path temp_output_path = new Path("lbp_temp_output"); if (i == 1) SaxpyTextoutput(getConf(), nreducers, "lbp_cur_vector", "mv_output", "lbp_temp_output", 1.0); else SaxpyTextoutput(getConf(), nreducers, output_path_str, "mv_output", "lbp_temp_output", 1.0); // rotate directory fs.delete(output_path); fs.rename(temp_output_path, output_path); fs.delete(vector_path); fs.rename(new Path("mv_output"), vector_path); } System.out .println("Linear BP finished. The belief vector is in the HDFS " + output_path_str); return 0; } protected JobConf configInitPrior(Path prior_path, Path init_vector_path) throws Exception { final JobConf conf = new JobConf(getConf(), LBP.class); conf.setJobName("LBP_InitPrior"); conf.setMapperClass(MapInitPrior.class); FileSystem fs = FileSystem.get(getConf()); fs.delete(init_vector_path); FileInputFormat.setInputPaths(conf, prior_path); FileOutputFormat.setOutputPath(conf, init_vector_path); conf.setNumReduceTasks(0); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(Text.class); return conf; } protected JobConf configComputeM(Path edge_path, Path d_path, Path m_path, double c, double a) throws Exception { final JobConf conf = new JobConf(getConf(), LBP.class); conf.set("c", "" + c); conf.set("a", "" + a); conf.setJobName("LBP_ComputeMin"); conf.setMapperClass(MapComputeM.class); FileSystem fs = FileSystem.get(getConf()); fs.delete(m_path); FileInputFormat.setInputPaths(conf, edge_path, d_path); FileOutputFormat.setOutputPath(conf, m_path); conf.setNumReduceTasks(0); conf.setOutputKeyClass(LongWritable.class); conf.setOutputValueClass(Text.class); return conf; } }
true
a284b58266c4fe811e47806aa9466dd6485052d0
Java
mostafaozman/Java
/TrafficSim/Road.Java
UTF-8
813
3.40625
3
[]
no_license
import java.awt.Color; import java.awt.Graphics; import java.lang.reflect.Array; import java.util.ArrayList; import javax.swing.JPanel; public class Road extends JPanel { final int LANE_HEIGHT = 120; ArrayList<Vehicle> cars = new ArrayList<Vehicle>(); public Road() { super(); } public void addCar(Vehicle v) { cars.add(v); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); for (int a = LANE_HEIGHT; a < LANE_HEIGHT * 4; a = a + LANE_HEIGHT) // which lane { for (int b = 0; b < getWidth(); b = b + 40) // which line { g.fillRect(b, a, 30, 5); } } // Draw cars for (int a = 0; a < cars.size(); a ++) { cars.get(a).paintMe(g); } } }
true
ad209c070bf62c59ecd371cdbf312d90edde7777
Java
sunilv123/jwt-auth-service
/src/main/java/net/sunil/bean/LoginBean.java
UTF-8
474
1.828125
2
[ "MIT" ]
permissive
package net.sunil.bean; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty.Access; import lombok.Getter; import lombok.Setter; @Setter @Getter public class LoginBean { private Long id; private Long authorId; private String name; private String userName; @JsonProperty(access = Access.WRITE_ONLY) private String password; private String email; private String mobile; private String token; }
true
5340968399dcc9192d012075a9647c2968bee61a
Java
bolyachevets/Space-Shooter
/model/HandleFrames.java
UTF-8
1,545
2.671875
3
[]
no_license
package ca.ubc.cpsc210.spaceinvaders.model; import javax.imageio.ImageIO; import java.awt.*; import java.io.IOException; import java.net.URL; /** * Created by andre on 2017-01-21. */ public class HandleFrames { /* private String[] imgFileNames = { "smallfighter0001.png", "smallfighter0002.png", "smallfighter0003.png", "smallfighter0004.png", "smallfighter0005.png", "smallfighter0006.png", "smallfighter0007.png", "smallfighter0008.png", "smallfighter0009.png", "smallfighter0010.png", "smallfighter0011.png"};*/ private String[] imgFileNames = { "smallfighter0001.png", "smallfighter0011.png"}; private Image[] imgFrames; // array of Images to be animated private final int frameRate = 5; /** Helper method to load all image frames, with the same height and width */ public void loadImages() { int numFrames = imgFileNames.length; imgFrames = new Image[numFrames]; // allocate the array URL imgUrl = null; for (int i = 0; i < numFrames; ++i) { imgUrl = getClass().getClassLoader().getResource(imgFileNames[i]); try { imgFrames[i] = ImageIO.read(imgUrl); // load image via URL } catch (IOException ex) { ex.printStackTrace(); } } } public Image getImgFrames(int i) { return imgFrames[i]; } public int imgFramesSize() { return imgFrames.length; } }
true
20f7634faa669c677f4147c92b412a4978926cd7
Java
TeamEntership/NAEM
/src/main/java/com/entership/naem/naemMain.java
UTF-8
1,751
1.929688
2
[]
no_license
package com.entership.naem; import net.minecraft.creativetab.CreativeTabs; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.relauncher.Side; import com.entership.naem.blocks.naemBlocks; import com.entership.naem.handler.naemCreativeTab; import com.entership.naem.items.naemItems; import com.entership.naem.network.CommonProxy; @Mod( modid = Data.MODID, version = Data.VERSION, name = Data.NAME, acceptedMinecraftVersions = Data.MCVERSIONS) public class naemMain { // CreativeTab public static CreativeTabs naemtabitems = new naemCreativeTab(CreativeTabs.getNextID(), "naemtabitems", 1); public static CreativeTabs naemtabblocks = new naemCreativeTab(CreativeTabs.getNextID(), "naemtabblocks", 0); @SidedProxy(clientSide = Data.CLIENTPROXY, serverSide = Data.COMMONPROXY) public static CommonProxy proxy; @Instance(Data.MODID) public static naemMain instance; @EventHandler public void preinit(FMLPreInitializationEvent event) { //PacketHandler //reg Fluids //init blocks naemBlocks.init(); naemItems.init(); //init items } @EventHandler public void init(FMLInitializationEvent event) { if (event.getSide() == Side.CLIENT) { naemBlocks.initItemModel(); naemItems.initItemModel(); } //recipes } @EventHandler public void postinit(FMLPostInitializationEvent event) { } }
true
04b9f0140fd0414860432ad139bdaacc12e91ecf
Java
apoclyps/Job-Seeker
/Server/RhieHorn/src/uk/co/kyleharrison/jobseeker/utils/PostcodeUtil.java
UTF-8
3,568
2.34375
2
[]
no_license
package uk.co.kyleharrison.jobseeker.utils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONArray; public class PostcodeUtil { public static void main(String [] argruments){ String requestURL ="http://api.indeed.com/ads/apisearch?publisher=8188725749639977&q=java&l=dundee&sort=&format=json&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=u&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2"; String targetURL = "http://maps.googleapis.com/maps/api/geocode/json"; String urlParameters = ""; String jsonString =""; try { URL url = new URL(requestURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line.toString()); jsonString += line; } reader.close(); } catch (MalformedURLException e) { // ... } catch (IOException e) { // ... } JsonParser jsp = JsonParser.getInstance(); //jsp.parseResults(jsonString); /* JSONObject json = (JSONObject) JsonSerializer.toJSON( jsonString ); JSONArray pilot = json.getJSONArray("results"); JSONObject obj = (JSONObject) pilot.getJSONObject(0); System.out.println("Results "+ obj.get("jobtitle")); */ /* JSONObject res = new JSONObject(city); JSONArray mapsData = res.getJSONArray("results"); JSONObject test1 = mapsData.getJSONObject(0); JSONArray jArr = test1.getJSONArray("address_components"); for(int i=0;i<jArr.length();i++){ if (jArr.getJSONObject(i).getJSONArray("types").getString(0).equals("locality")){ city = jArr.getJSONObject(i).getString("long_name"); } } */ } public static String excutePost(String targetURL, String urlParameters) { URL url; HttpURLConnection connection = null; try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches (false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream ( connection.getOutputStream ()); wr.writeBytes (urlParameters); wr.flush (); wr.close (); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if(connection != null) { connection.disconnect(); } } } }
true
c23142ad56c1347e8376c58ce47cdd1a6ef911b2
Java
telendt/transactions-statistics
/src/main/java/com/n26/rest/StatisticsResponse.java
UTF-8
1,623
2.46875
2
[]
no_license
package com.n26.rest; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.n26.stats.StatisticsSummary; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.function.BiFunction; import java.util.function.Supplier; public class StatisticsResponse { private final StatisticsSummary<BigDecimal> summary; private final int scale; private final RoundingMode roundingMode; StatisticsResponse(StatisticsSummary<BigDecimal> summary, int scale, RoundingMode roundingMode) { this.summary = summary; this.scale = scale; this.roundingMode = roundingMode; } @JsonIgnore private BigDecimal rounded(BiFunction<Integer, RoundingMode, BigDecimal> fun) { return getCount() > 0 ? fun.apply(scale, roundingMode) : BigDecimal.ZERO.setScale(scale, roundingMode); } @JsonIgnore private BigDecimal rounded(Supplier<BigDecimal> supplier) { return rounded((s, r) -> supplier.get().setScale(s, r)); } @JsonProperty("sum") public BigDecimal getSum() { return rounded(summary::getSum); } @JsonProperty("avg") public BigDecimal getAvg() { return rounded((s, r) -> getSum().divide(BigDecimal.valueOf(getCount()), s, r)); } @JsonProperty("max") public BigDecimal getMax() { return rounded(summary::getMax); } @JsonProperty("min") public BigDecimal getMin() { return rounded(summary::getMin); } @JsonProperty("count") public long getCount() { return summary.getCount(); } }
true
74f4423250bfdcb43b83e592e88fde2941f27189
Java
sergderevyanko/bustrackerapp
/src/main/java/com/infragps/gpstracker/client/model/Tracker.java
UTF-8
1,625
2
2
[]
no_license
package com.infragps.gpstracker.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.SerializedName; import java.util.Date; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Created by sergey.derevyanko on 08.12.16. */ @JsonIgnoreProperties({ "updated_at", "created_at"}) public class Tracker { private int id; @JsonProperty("route_number") private String routeNumber; @JsonProperty("tracker_id") private int trackerId; private Date createdAt; private Date updatedAt; public Tracker() { } public Tracker(int id, String routeNumber) { this.id = id; this.routeNumber = routeNumber; } @ApiModelProperty public int getId() { return id; } public void setId(int id) { this.id = id; } @ApiModelProperty public String getRouteNumber() { return routeNumber; } public void setRouteNumber(String routeNumber) { this.routeNumber = routeNumber; } @ApiModelProperty public int getTrackerId() { return trackerId; } public void setTrackerId(int trackerId) { this.trackerId = trackerId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
true
c70635aabacd5eee28c45b811311e68a4ae4f9ac
Java
leehongsen/graduation
/src/main/java/com/example/graduation/service/impl/GoodsServiceImpl.java
UTF-8
2,012
2.140625
2
[]
no_license
package com.example.graduation.service.impl; import com.example.graduation.dao.TFoodsMapper; import com.example.graduation.pojo.TFoods; import com.example.graduation.pojo.TGoods; import com.example.graduation.service.GoodsService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.util.StringUtil; import javax.annotation.Resource; import java.util.List; @Service("goodsService") public class GoodsServiceImpl extends BaseService<TGoods> implements GoodsService { @Resource private TFoodsMapper tFoodsMapper; @Override public List<TGoods> getGoodsBySeller(Integer id) { Example example = new Example(TGoods.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("businessId",id); return mapper.selectByExample(example); } @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class}) public void delGoods(Integer id) { TFoods key=new TFoods(); key.setGoodsId(id); tFoodsMapper.deleteByPrimaryKey(key); mapper.deleteByPrimaryKey(id); } @Override public PageInfo<TGoods> selectByPage(TGoods goods, int start, int length) { int page = start/length+1; Example example = new Example(TGoods.class); Example.Criteria criteria = example.createCriteria(); if (StringUtil.isNotEmpty(goods.getName())) { criteria.andLike("name", "%" + goods.getName() + "%"); } if (goods.getId() != null) { criteria.andEqualTo("id", goods.getId()); } //分页查询 PageHelper.startPage(page, length); List<TGoods> list = selectByExample(example); return new PageInfo<>(list); } }
true
3ff93c9357ffd917724970b69dd484b7c6e1c079
Java
liuwenhaha/Slam-Dunk-Android
/src/it/unibo/slam/matcher/MatchHypothesis.java
UTF-8
786
2.609375
3
[ "Apache-2.0" ]
permissive
package it.unibo.slam.matcher; import java.util.Comparator; /** * Match hypothesis struct. */ public class MatchHypothesis { /** * Query descriptor index. */ public int queryIdx; /** * Train descriptor index. */ public int trainIdx; /** * Train image index. */ public int imgIdx; /** * Match ratio. */ public float ratio; /** * Comparator based on the ratio value. */ public static Comparator<MatchHypothesis> RATIO_COMPARATOR = new Comparator<MatchHypothesis>() { @Override public int compare(MatchHypothesis lhs, MatchHypothesis rhs) { return (lhs.ratio < rhs.ratio) ? -1 : ((lhs.ratio == rhs.ratio) ? 0 : 1); } }; }
true
3b54f7a144e600719ef7cbbbe17bcdd6eb9ac5ca
Java
TermanEmil/TodoistExtension
/app/src/main/java/com/university/unicornslayer/todoistextension/data/network/AppApiHelper.java
UTF-8
3,434
2.3125
2
[]
no_license
package com.university.unicornslayer.todoistextension.data.network; import android.util.Log; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseListener; import com.university.unicornslayer.todoistextension.utils.todoist_common.TodoistItemsUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.HttpURLConnection; import javax.inject.Inject; import okhttp3.Response; public class AppApiHelper implements ApiHelper { private static final String url = "https://todoist.com/api/v7/sync"; private static final String tokenValidationTag = "token-validation"; private static final String getAllItemsTag = "get-all-items"; private String token = null; @Inject public AppApiHelper() { } @Override public void setToken(String token) { this.token = token; } @Override public void validateToken(final TokenValidationListener listener) { AndroidNetworking .post(url) .addBodyParameter("token", token) .setTag(tokenValidationTag) .build() .getAsOkHttpResponse(new OkHttpResponseListener() { @Override public void onResponse(Response response) { switch (response.code()) { case HttpURLConnection.HTTP_OK: listener.onResponse(true); break; case HttpURLConnection.HTTP_FORBIDDEN: listener.onResponse(false); break; default: listener.onError(response.code()); } } @Override public void onError(ANError anError) { listener.onError(anError.getErrorCode()); } }); } @Override public void cancelTokenValiation() { AndroidNetworking.cancel(tokenValidationTag); } @Override public void getAllItems(final GetAllItemsListener listener) { if (token == null) { Log.e("AppApiHelper", "Token was not set"); return; } AndroidNetworking .post(url) .addBodyParameter("token", token) .addBodyParameter("resource_types", "[\"items\"]") .addBodyParameter("sync_token", "*") .setTag(getAllItemsTag) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("items"); listener.onResponse(TodoistItemsUtils.extractItems(jsonArray)); } catch (JSONException e) { listener.onError(-1); } } @Override public void onError(ANError anError) { listener.onError(anError.getErrorCode()); } }); } @Override public void cancelGetAllItems() { AndroidNetworking.cancel(getAllItemsTag); } }
true
1cd56153de7b9748e28c836c9a57ecc0e5861332
Java
marinionut/campus-borrow
/app/src/main/java/com/sac/campusborrow/activities/DashboardActivity.java
UTF-8
2,374
2.40625
2
[]
no_license
package com.sac.campusborrow.activities; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.sac.campusborrow.R; import com.sac.campusborrow.fragments.FragmentFour; import com.sac.campusborrow.fragments.FragmentOne; import com.sac.campusborrow.fragments.FragmentThree; import com.sac.campusborrow.fragments.FragmentTwo; import java.util.ArrayList; import java.util.List; /** * Created by ionut on 1/15/2018. */ public class DashboardActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new FragmentOne(), "Objects"); adapter.addFragment(new FragmentTwo(), "Requests"); adapter.addFragment(new FragmentThree(), "My objects"); adapter.addFragment(new FragmentFour(), "Users"); viewPager.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } // Adapter for the viewpager using FragmentPagerAdapter public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
true
4ad7a8f839c4fa8b37f701d2d2d9848133245c8e
Java
STAMP-project/dspot-experiments
/benchmark/training/org/eclipse/jetty/http2/client/AsyncIOTest.java
UTF-8
8,662
1.992188
2
[]
no_license
/** * */ /** * ======================================================================== */ /** * Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd. */ /** * ------------------------------------------------------------------------ */ /** * All rights reserved. This program and the accompanying materials */ /** * are made available under the terms of the Eclipse Public License v1.0 */ /** * and Apache License v2.0 which accompanies this distribution. */ /** * */ /** * The Eclipse Public License is available at */ /** * http://www.eclipse.org/legal/epl-v10.html */ /** * */ /** * The Apache License v2.0 is available at */ /** * http://www.opensource.org/licenses/apache2.0.php */ /** * */ /** * You may elect to redistribute this code under either of these licenses. */ /** * ======================================================================== */ /** * */ package org.eclipse.jetty.http2.client; import Callback.NOOP; import MetaData.Request; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.AsyncContext; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.http2.api.Stream; import org.eclipse.jetty.http2.frames.HeadersFrame; import org.eclipse.jetty.util.FuturePromise; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class AsyncIOTest extends AbstractTest { @Test public void testLastContentAvailableBeforeService() throws Exception { start(new HttpServlet() { @Override protected void service(final HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Wait for the data to fully arrive. AsyncIOTest.sleep(1000); final AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); request.getInputStream().setReadListener(new AsyncIOTest.EmptyReadListener() { @Override public void onDataAvailable() throws IOException { ServletInputStream input = request.getInputStream(); while (input.isReady()) { int read = input.read(); if (read < 0) break; } if (input.isFinished()) asyncContext.complete(); } }); } }); Session session = newClient(new Session.Listener.Adapter()); HttpFields fields = new HttpFields(); MetaData.Request metaData = newRequest("GET", fields); HeadersFrame frame = new HeadersFrame(metaData, null, false); final CountDownLatch latch = new CountDownLatch(1); FuturePromise<Stream> promise = new FuturePromise(); session.newStream(frame, promise, new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { if (frame.isEndStream()) latch.countDown(); } }); Stream stream = promise.get(5, TimeUnit.SECONDS); stream.data(new org.eclipse.jetty.http2.frames.DataFrame(stream.getId(), ByteBuffer.allocate(16), true), NOOP); Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test public void testLastContentAvailableAfterServiceReturns() throws Exception { start(new HttpServlet() { @Override protected void service(final HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); request.getInputStream().setReadListener(new AsyncIOTest.EmptyReadListener() { @Override public void onDataAvailable() throws IOException { ServletInputStream input = request.getInputStream(); while (input.isReady()) { int read = input.read(); if (read < 0) break; } if (input.isFinished()) asyncContext.complete(); } }); } }); Session session = newClient(new Session.Listener.Adapter()); HttpFields fields = new HttpFields(); MetaData.Request metaData = newRequest("GET", fields); HeadersFrame frame = new HeadersFrame(metaData, null, false); final CountDownLatch latch = new CountDownLatch(1); FuturePromise<Stream> promise = new FuturePromise(); session.newStream(frame, promise, new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { if (frame.isEndStream()) latch.countDown(); } }); Stream stream = promise.get(5, TimeUnit.SECONDS); // Wait until service() returns. Thread.sleep(1000); stream.data(new org.eclipse.jetty.http2.frames.DataFrame(stream.getId(), ByteBuffer.allocate(16), true), NOOP); Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test public void testSomeContentAvailableAfterServiceReturns() throws Exception { final AtomicInteger count = new AtomicInteger(); start(new HttpServlet() { @Override protected void service(final HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(0); request.getInputStream().setReadListener(new AsyncIOTest.EmptyReadListener() { @Override public void onDataAvailable() throws IOException { count.incrementAndGet(); ServletInputStream input = request.getInputStream(); while (input.isReady()) { int read = input.read(); if (read < 0) break; } if (input.isFinished()) asyncContext.complete(); } }); } }); Session session = newClient(new Session.Listener.Adapter()); HttpFields fields = new HttpFields(); MetaData.Request metaData = newRequest("GET", fields); HeadersFrame frame = new HeadersFrame(metaData, null, false); final CountDownLatch latch = new CountDownLatch(1); FuturePromise<Stream> promise = new FuturePromise(); session.newStream(frame, promise, new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { if (frame.isEndStream()) latch.countDown(); } }); Stream stream = promise.get(5, TimeUnit.SECONDS); // Wait until service() returns. Thread.sleep(1000); stream.data(new org.eclipse.jetty.http2.frames.DataFrame(stream.getId(), ByteBuffer.allocate(1), false), NOOP); // Wait until onDataAvailable() returns. Thread.sleep(1000); stream.data(new org.eclipse.jetty.http2.frames.DataFrame(stream.getId(), ByteBuffer.allocate(1), true), NOOP); Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS)); // Make sure onDataAvailable() has been called twice Assertions.assertEquals(2, count.get()); } private static class EmptyReadListener implements ReadListener { @Override public void onDataAvailable() throws IOException { } @Override public void onAllDataRead() throws IOException { } @Override public void onError(Throwable t) { } } }
true
df354f96411a6caccff7d993c4dae95ea5385ea5
Java
jarviscanada/jarvis_data_eng_talha
/practice/src/test/java/ca/jrvs/practice/codingChallenge/ValidAnagramTest.java
UTF-8
1,207
2.46875
2
[]
no_license
package ca.jrvs.practice.codingChallenge; import org.junit.Test; import static org.junit.Assert.*; public class ValidAnagramTest { ValidAnagram validAnagram = new ValidAnagram(); @Test public void anagramTest() { assertEquals(validAnagram.anagramWithSorting("anagram", "nagaram"), true); assertEquals(validAnagram.anagramWithArray("anagram", "nagaram"), true); assertEquals(validAnagram.anagramWithMaps("anagram", "nagaram"), true); assertEquals(validAnagram.anagramWithSorting("schoolmaster", "theclassroom"), true); assertEquals(validAnagram.anagramWithArray("schoolmaster", "theclassroom"), true); assertEquals(validAnagram.anagramWithMaps("schoolmaster", "theclassroom"), true); assertEquals(validAnagram.anagramWithSorting("rat", "car"), false); assertEquals(validAnagram.anagramWithArray("rat", "car"), false); assertEquals(validAnagram.anagramWithMaps("rat", "car"), false); assertEquals(validAnagram.anagramWithSorting("rat", "rata"), false); assertEquals(validAnagram.anagramWithArray("rat", "rata"), false); assertEquals(validAnagram.anagramWithMaps("rat", "rata"), false); } }
true
2e952cce6d53b806b4da3c515645f6819afce67f
Java
Jiaray/AppBaby
/app/src/main/java/com/app/AppBabySH/ProfileFragment.java
UTF-8
10,758
1.867188
2
[]
no_license
package com.app.AppBabySH; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import com.app.AppBabySH.activity.LoginActivity; import com.app.AppBabySH.activity.MainTabActivity; import com.app.AppBabySH.base.BaseFragment; import com.app.Common.ImageLoader; import com.app.Common.UserMstr; import com.app.Common.WebService; import org.json.JSONArray; public class ProfileFragment extends BaseFragment { final private String TAG = "profile"; private MainTabActivity main; private View rootView; private GlobalVar centerV; private LayoutInflater _inflater; private AlertDialog.Builder alertD; private LinearLayout mLyRegOther, mLySet, mLyFavChannel; private ImageView mImgPic; private TableLayout mTblPersonalInfo; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { _inflater = inflater; rootView = inflater.inflate(R.layout.profile_fragment, container, false); if(UserMstr.userData.getUserName().equals("guest")){ final AlertDialog mutiItemDialogLogin = createLoginDialog(); mutiItemDialogLogin.show(); }else{ initView(); } return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //共用宣告 centerV = (GlobalVar) rootView.getContext().getApplicationContext(); main = (MainTabActivity) getActivity(); main.setSoftInputMode("adjustPan"); // 判斷網路 if (WebService.isConnected(getActivity()) && !UserMstr.userData.getUserName().equals("guest")) getData(); } // 初始化 private void initView() { mTblPersonalInfo = (TableLayout) rootView.findViewById(R.id.tblProfilePersonalInfo); mTblPersonalInfo.removeAllViews(); mLyRegOther = (LinearLayout) rootView.findViewById(R.id.lyProfileRegOther); mLySet = (LinearLayout) rootView.findViewById(R.id.lyProfileSet); mLyFavChannel = (LinearLayout) rootView.findViewById(R.id.lyProfileFavChannel); mImgPic = (ImageView) rootView.findViewById(R.id.imgProfilePic); mLyRegOther.setOnClickListener(new onClick()); mLySet.setOnClickListener(new onClick()); mLyFavChannel.setOnClickListener(new onClick()); ImageLoader.getInstance().DisplayRoundedCornerImage( UserMstr.userData.getBaseInfoAry().optJSONObject(0).optString("USER_AVATAR"), mImgPic); } // 提示登入選單 public AlertDialog createLoginDialog() { final String[] items = {"我已经有帐户,我需要登录", "没有帐户,需要注册", "取消"}; alertD = new AlertDialog.Builder(getActivity()); alertD.setTitle("当前您并未登录宝贝通,部分功能需要登录后可用。"); //設定對話框內的項目 alertD.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { main.mTabHost.setCurrentTab(1); switch (which) { case 0: centerV.loginAgain = true; UserMstr.userData = null; Intent intent = new Intent(); intent.setClass(getActivity(), LoginActivity.class); startActivity(intent); break; case 1: AccountRegistFragment regF = new AccountRegistFragment(); main.OpenBottom(regF); break; case 2: break; } } }); return alertD.create(); } // 取得數據 private void getData() { DisplayLoadingDiaLog("资料读取中,请稍后..."); if (UserMstr.userData.getBaseInfoAry().optJSONObject(0).optString("USER_TYPE").equals("P")) { WebService.GetParentChilds(null, UserMstr.userData.getBaseInfoAry().optJSONObject(0).optString("USER_TYPE_ID"), new WebService.WebCallback() { @Override public void CompleteCallback(String id, Object obj) { CancelDiaLog(); try { if (obj == null) { DisplayOKDiaLog("取得资讯错误!"); return; }else if (obj.equals("Success! No Data Return!")) { DisplayOKDiaLog("读取完成,无资料返回!"); return; } JSONArray json = (JSONArray) obj; if (json.length() == 0) { DisplayOKDiaLog("没有任何资讯!"); return; } int i = -1; while (++i < json.length()) { View mVPersonalInfoItem = _inflater.inflate(R.layout.profile_personalinfo_item, null); TextView mTxtRelationship = (TextView) mVPersonalInfoItem.findViewById(R.id.txtProfilPersonalRelationship); TextView mTxtSchool = (TextView) mVPersonalInfoItem.findViewById(R.id.txtProfilPersonalSchool); mTxtRelationship.setText(json.optJSONObject(i).optString("STUDENT_NAME") + " 的 " + json.optJSONObject(i).optString("STUDENT_RELATION")); mTxtSchool.setText(json.optJSONObject(i).optString("SCHOOL_NAME")); mTblPersonalInfo.addView(mVPersonalInfoItem); mVPersonalInfoItem.setOnClickListener(new onPersonalItemClick(json.optJSONObject(i).optString("SCHOOL_ID"), json.optJSONObject(i).optString("STUDENT_ID"))); } } catch (Exception e) { DisplayOKDiaLog("GetParentChilds 取得资讯失败!e:" + e); e.printStackTrace(); } } }); } else { WebService.GetTeacherTeaching(null, UserMstr.userData.getBaseInfoAry().optJSONObject(0).optString("USER_TYPE_ID"), new WebService.WebCallback() { @Override public void CompleteCallback(String id, Object obj) { CancelDiaLog(); try { if (obj == null) { DisplayOKDiaLog("取得资讯错误!"); return; }else if (obj.equals("Success! No Data Return!")) { DisplayOKDiaLog("读取完成,无资料返回!"); return; } JSONArray json = (JSONArray) obj; if (json.length() == 0) { DisplayOKDiaLog("没有任何资讯!"); return; } int i = -1; while (++i < json.length()) { View mVPersonalInfoItem = _inflater.inflate(R.layout.profile_personalinfo_item, null); TextView mTxtRelationship = (TextView) mVPersonalInfoItem.findViewById(R.id.txtProfilPersonalRelationship); TextView mTxtSchool = (TextView) mVPersonalInfoItem.findViewById(R.id.txtProfilPersonalSchool); ImageView mImgNext = (ImageView) mVPersonalInfoItem.findViewById(R.id.imgProfilePersonalNext); mTxtRelationship.setText(json.optJSONObject(i).optString("SCHOOL_NAME") + " - " + json.optJSONObject(i).optString("CLASS_NAME")); mTxtSchool.setVisibility(View.GONE); mImgNext.setVisibility(View.GONE); mTblPersonalInfo.addView(mVPersonalInfoItem); } } catch (Exception e) { DisplayOKDiaLog("GetTeacherTeaching 取得资讯失败!e:" + e); e.printStackTrace(); } } }); } } class onClick implements View.OnClickListener { @Override public void onClick(View v) { // 判斷網路 if (!WebService.isConnected(getActivity())) return; switch (v.getId()) { case R.id.lyProfileRegOther: AccountRegistFragment regF = new AccountRegistFragment(); main.OpenBottom(regF); break; case R.id.lyProfileSet: SetMenuFragment setF = new SetMenuFragment(); setF.onCallBack = new SetMenuFragment.CallBack() { @Override public void onBack() { try { ImageLoader.getInstance().DisplayRoundedCornerImage( UserMstr.userData.getBaseInfoAry().optJSONObject(0).optString("USER_AVATAR"), mImgPic); } catch (Exception e) { e.printStackTrace(); } } }; main.OpenBottom(setF); break; case R.id.lyProfileFavChannel: SetFavChannelFragment setFCF = new SetFavChannelFragment(); main.OpenBottom(setFCF); break; } } } private class onPersonalItemClick implements View.OnClickListener { private String schollID, studentID; public onPersonalItemClick(String $schollID, String $studentID) { schollID = $schollID; studentID = $studentID; } @Override public void onClick(View v) { // 判斷網路 if (!WebService.isConnected(getActivity())) return; SetHistoryFragment setHistoryF = new SetHistoryFragment(); setHistoryF.School_ID = schollID; setHistoryF.Student_ID = studentID; main.OpenBottom(setHistoryF); } } }
true
1149148d334d11a391447bf35cc779e282601e3f
Java
nanepifanio/Java-e-POO
/NetBeansProjects/People/src/people/Niver.java
UTF-8
90
1.765625
2
[ "MIT" ]
permissive
package people; public interface Niver { public abstract void fazerAniversario(); }
true
9577ea3d5f0b584447ef2233f55f8f3952c3a4a3
Java
stareart/bd
/bigdata/src/main/java/com/hym/hadoop/hdfs/work2/Compress.java
UTF-8
2,884
2.71875
3
[]
no_license
package com.hym.hadoop.hdfs.work2; import com.hym.hadoop.hdfs.HdfsFileSystem; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.util.ReflectionUtils; import java.io.*; public class Compress { public static void main(String[] args) throws ClassNotFoundException { String localPath ="D:\\hadoopSpace\\bigdata\\src\\main\\sources\\data\\sogou.50w.utf8"; //压缩类 String codecDefault = "org.apache.hadoop.io.compress.DefaultCodec"; String codecGz = "org.apache.hadoop.io.compress.GzipCodec"; String codecBZ = "org.apache.hadoop.io.compress.BZip2Codec"; String targetPathDefault = "/data/hdfs/sogou.50w.utf8.default"; String targetPathGz = "/data/hdfs/sogou.50w.utf8.Gz"; String targetPathBZ = "/data/hdfs/sogou.50w.utf8.BZ"; compress(localPath,targetPathDefault,codecDefault); compress(localPath,targetPathGz,codecGz); compress(localPath,targetPathBZ,codecBZ); } private static void compress(String localPath,String targetPath,String compressClass){ System.out.println("开始压缩上传文件到HDFS,源文件文件:"+localPath +"\t采用 ["+compressClass+"] 方法进行压缩," +"上传到目标路径:"+targetPath); InputStream inputStream = null; FileSystem fileSystem = null; FSDataOutputStream fsDataOutputStream =null; CompressionOutputStream outputStream=null; try{ // 构造压缩类 Class<?> cclass = Class.forName(compressClass); Configuration conf = new Configuration(); CompressionCodec compressionCodec = (CompressionCodec) ReflectionUtils.newInstance(cclass, conf); inputStream = new BufferedInputStream(new FileInputStream(localPath)); fileSystem = HdfsFileSystem.getFileSystem(); fsDataOutputStream = fileSystem.create(new Path(targetPath)); outputStream = compressionCodec.createOutputStream(fsDataOutputStream); IOUtils.copyBytes(inputStream,outputStream,4096,false); }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { try{ inputStream.close(); fsDataOutputStream.close(); outputStream.close(); }catch (Exception e){ } } System.out.println("完成压缩上传!"); } }
true
81b0a75c918e896d0155403a18b33c0f4fdfed9b
Java
kangbogg/MultilevelList
/app/src/main/java/com/example/day0927/MyExpandableListAdapter.java
UTF-8
4,693
2.625
3
[]
no_license
package com.example.day0927; import android.content.Context; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListAdapter; import android.widget.TextView; public class MyExpandableListAdapter implements ExpandableListAdapter { //数据 private String[] group; private String[][] child; private Context context; private GroupViewHolder groupViewHolder; private ChildViewHolder childViewHolder; public MyExpandableListAdapter(String[] group, String[][] child, Context context) { this.group = group; this.child = child; this.context = context; } @Override public void registerDataSetObserver(DataSetObserver observer) { } @Override public void unregisterDataSetObserver(DataSetObserver observer) { } /*** * 一级列表个数 * @return */ @Override public int getGroupCount() { return group.length; } /*** * 每个二级列表的个数 * @param groupPosition * @return */ @Override public int getChildrenCount(int groupPosition) { return child.length; } /*** * 一级列表中单个item * @param groupPosition * @return */ @Override public Object getGroup(int groupPosition) { return group[groupPosition]; } /*** * 二级列表中单个item * @param groupPosition * @param childPosition * @return */ @Override public Object getChild(int groupPosition, int childPosition) { return child[groupPosition][childPosition]; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } /*** * 每个item的id是否固定,一般为true * @return */ @Override public boolean hasStableIds() { return true; } /*** * 填充一级列表 * @param groupPosition * @param isExpanded 是否展开 * @param convertView * @param parent * @return */ @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.level_1_list_layout, null); groupViewHolder = new GroupViewHolder(); groupViewHolder.tv_group = convertView.findViewById(R.id.tv_group); convertView.setTag(groupViewHolder); } else { groupViewHolder = (GroupViewHolder) convertView.getTag(); } //设置显示数据 groupViewHolder.tv_group.setText(group[groupPosition]); return convertView; } /*** * 填充二级列表 * @param groupPosition * @param childPosition * @param isLastChild * @param convertView * @param parent * @return */ @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.level_2_list_layout, null); childViewHolder = new ChildViewHolder(); childViewHolder.tv_child = convertView.findViewById(R.id.tv_child); convertView.setTag(childViewHolder); } else { childViewHolder = (ChildViewHolder) convertView.getTag(); } childViewHolder.tv_child.setText(child[groupPosition][childPosition]); return convertView; } /*** * 二级列表中每个能否被选中,如果有点击事件一定要设为true * @param groupPosition * @param childPosition * @return */ @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEmpty() { return false; } @Override public void onGroupExpanded(int groupPosition) { } @Override public void onGroupCollapsed(int groupPosition) { } @Override public long getCombinedChildId(long groupId, long childId) { return 0; } @Override public long getCombinedGroupId(long groupId) { return 0; } class GroupViewHolder { TextView tv_group; } class ChildViewHolder { TextView tv_child; } }
true
8589b13a2aa7bf3133caa2332b9610bf2bdfe3ae
Java
Nonudian/PacMan
/PacMan/src/View/GameView.java
UTF-8
9,745
2.671875
3
[]
no_license
package View; import Util.*; import Model.Entity.*; import Controller.Game; import Model.Entity.Ghost.Ghost; import Model.Tile.*; import static Util.GumType.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.layout.TilePane; import javafx.scene.paint.Color; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.stage.WindowEvent; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.geometry.Pos; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; public class GameView extends Application { private Game game; private Observer observer; private TilePane board; private TilePane gridTiles; private BorderPane rootPane; private Stage stage; private void initObservable() { this.observer = (Observable o, Object arg) -> { Platform.runLater(() -> { if (!this.game.isFinished()) { this.drawGame(); this.display(); } }); }; this.game.addObserver(this.observer); this.game.start(); } private void drawGame() { Tile[][] grid = this.game.getTiles(); this.gridTiles = new TilePane(); for (int y = 0; y < this.game.getDimension(); y++) { for (int x = 0; x < this.game.getDimension(); x++) { Tile tile = grid[x][y]; StackPane pane = new StackPane(); Rectangle rect = new Rectangle(30, 30); pane.getChildren().add(rect); if (tile instanceof Lane) { if (tile instanceof Gate) { rect.setFill(Color.WHITE); } else if (tile instanceof GhostLane) { if (tile instanceof GhostDoor) { rect.setFill(Color.GREY); } else { rect.setFill(Color.BLUE); } } else { rect.setFill(Color.BLACK); } Lane lane = ((Lane) tile); GumType type = lane.getState(); if (type != EMPTY) { Circle gum = new Circle(15, 15, 5, Color.WHITE); switch (type) { case INVERTED: gum.setFill(Color.GREENYELLOW); case SUPER: gum.setRadius(10); break; } pane.getChildren().add(gum); gum.requestFocus(); } // at start, entities spawn on EMPTY Lanes Entity entity = lane.getEntity(); if (entity != null) { if (entity instanceof PacMan) { int startingAngle; switch (entity.getDirection()) { case LEFT: startingAngle = 225; break; case UP: startingAngle = 135; break; case RIGHT: startingAngle = 45; break; case DOWN: startingAngle = 315; break; default: startingAngle = 45; } Arc pacman = new Arc(0, 0, 10, 10, startingAngle, 270); pacman.setType(ArcType.ROUND); pacman.setFill(entity.getColor()); pane.getChildren().add(pacman); pacman.requestFocus(); } else if (entity instanceof Ghost) { Rectangle ghost = new Rectangle(15, 15); ghost.setFill(entity.getColor()); pane.getChildren().add(ghost); ghost.requestFocus(); } } } else { rect.setFill(Color.DARKBLUE); } this.gridTiles.getChildren().add(pane); } } this.drawBoard(); this.rootPane = new BorderPane(); this.rootPane.setTop(this.board); this.rootPane.setBottom(this.gridTiles); } private void drawBoard() { this.board = new TilePane(); int rectHeight = this.game.getDimension() * 30 / 3; // [SCORES] VBox scoresBox = new VBox(); // best score Rectangle bestScoreRect = new Rectangle(rectHeight, 20); Text bestScore = new Text(27, 27, "BEST: " + String.valueOf(this.game.getBestScore())); bestScore.setFill(Color.WHITE); // score Rectangle scoreRect = new Rectangle(rectHeight, 40); Text score = new Text(27, 27, String.valueOf(this.game.getScore())); score.setFill(Color.WHITE); try { String fontFile = "./src/Assets/Fonts/emulogic.ttf"; InputStream fontBestScore = new FileInputStream(fontFile); InputStream fontScore = new FileInputStream(fontFile); bestScore.setFont(Font.loadFont(fontBestScore, 9)); score.setFont(Font.loadFont(fontScore, 18)); } catch (FileNotFoundException ex) { Logger.getLogger(GameView.class.getName()).log(Level.SEVERE, null, ex); } StackPane bestScorePane = new StackPane(bestScoreRect, bestScore); bestScorePane.setAlignment(Pos.BOTTOM_CENTER); StackPane scorePane = new StackPane(scoreRect, score); scoresBox.getChildren().addAll(bestScorePane, scorePane); // [BANNER] StackPane bannerPane = new StackPane(); ImageView imageView = new ImageView("/Assets/Images/Pac_Man_Logo.png"); Rectangle bannerRect = new Rectangle(rectHeight, 60); bannerPane.getChildren().addAll(bannerRect, imageView); // [GAME INFO] VBox gameBox = new VBox(); // level Rectangle levelRect = new Rectangle(rectHeight, 20); Text level = new Text(27, 27, "LVL: " + this.game.getLevel()); level.setFill(Color.WHITE); try { String fontFile = "./src/Assets/Fonts/emulogic.ttf"; InputStream fontLevel = new FileInputStream(fontFile); level.setFont(Font.loadFont(fontLevel, 9)); } catch (FileNotFoundException ex) { Logger.getLogger(GameView.class.getName()).log(Level.SEVERE, null, ex); } StackPane levelPane = new StackPane(levelRect, level); levelPane.setAlignment(Pos.BOTTOM_CENTER); // lives Rectangle livesRect = new Rectangle(rectHeight, 40); TilePane lives = new TilePane(); for (int i = 0; i < this.game.getPacMan().getRemainingLives(); i++) { Arc pacmanLife = new Arc(0, 0, 10, 10, 45, 270); pacmanLife.setType(ArcType.ROUND); pacmanLife.setFill(Color.YELLOW); lives.getChildren().add(pacmanLife); } lives.setAlignment(Pos.CENTER); StackPane livesPane = new StackPane(livesRect, lives); gameBox.getChildren().addAll(levelPane, livesPane); this.board.setMaxSize(this.game.getDimension() * 30, 60); this.board.getChildren().addAll(scoresBox, bannerPane, gameBox); } private void display() { int sceneHeight = this.game.getDimension() * 30; int sceneWidth = this.game.getDimension() * 30 + 60; Scene scene = new Scene(this.rootPane, sceneHeight, sceneWidth); scene.setOnKeyReleased((event) -> { switch (event.getCode()) { case UP: case DOWN: case LEFT: case RIGHT: this.game.updatePacManDirection(Direction.get(event.getCode())); } }); Image icon = new Image(getClass().getResourceAsStream("/Assets/Images/Pac_Man_Icon.png")); this.stage.getIcons().add(icon); this.stage.setScene(scene); this.stage.setResizable(false); this.stage.sizeToScene(); this.stage.centerOnScreen(); this.stage.setTitle("Pac-Man Game"); this.stage.show(); } @Override public void start(Stage primaryStage) throws Exception { this.game = new Game(); this.stage = primaryStage; this.stage.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, event -> { this.game.stop(); this.stage.close(); }); this.drawGame(); this.display(); this.initObservable(); } public static void main(String[] args) { launch(args); } }
true
822a7afecc250ad242f229325eb8fcacc0460082
Java
kate-young/Java-MineSweeper
/src/main/java/mines/UI.java
UTF-8
669
2.59375
3
[]
no_license
package mines; import javax.swing.*; public class UI { static final int MINES = 20; public static void createAndShowGUI() { JFrame frame = new JFrame("MineSweeper"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Board board = new Board(); board.addMines(200); BoardView boardView = new BoardView(); frame.add(boardView.getPanel()); frame.pack(); frame.setVisible(true); } public static void main(String args[]) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
true
666a66107968ab89718b5a49ca502c8697092cfc
Java
ilovepumpkin/waterbear
/waterbear_core/src/org/waterbear/core/widgets/evo/EvoFileInput.java
UTF-8
2,186
2.015625
2
[]
no_license
package org.waterbear.core.widgets.evo; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.assertEquals; import net.sf.sahi.client.BrowserCondition; import net.sf.sahi.client.ElementStub; import net.sf.sahi.client.ExecutionException; import org.waterbear.core.widgets.dijit.DojoWidget; public class EvoFileInput extends DojoWidget { public EvoFileInput(ElementStub es, Object[] stateValues) { super(es, stateValues); // TODO Auto-generated constructor stub } public void upload(String filePath, int waitTime, boolean isAutoUpload) { ElementStub fileEs = getBrowser().file(0).in(es); final String setFileSahiScript = "_sahi._setFile(" + fileEs + ", '" + filePath + "', 'FileUploadHandler')"; log.info(setFileSahiScript); getBrowser().execute(setFileSahiScript); StringBuffer mainJS = new StringBuffer(); mainJS.append("var $fileinput=dijit.getEnclosingWidget(" + fileEs + ");"); String changeTypeScript = "$fileinput.fileInput.type='text';"; /* * This code is for IE8, but actually IE8 is already not supported by * our products. Not sure if IE9 or IE10 need this code. * * if * (getBrowser().isIE()) { changeTypeScript = fileEs + ".outerHTML=" + * fileEs + * ".outerHTML.replace(/type=file/,'type=text');$fileinput.fileInput=" + * getBrowser().textbox(0).in(es) + ";"; } */ mainJS.append(changeTypeScript); mainJS.append("$fileinput.fileInput.value=\"" + filePath + "\";"); if (!isAutoUpload) { mainJS.append("_sahi._blur($fileinput.fileInput);"); } else { mainJS.append("$fileinput.uploadFile();"); } log.info(mainJS); getBrowser().execute(mainJS.toString()); //The following code takes long time - uncomment them unless they are really needed. // BrowserCondition cond = new BrowserCondition(getBrowser()) { // public boolean test() throws ExecutionException { // return !getBrowser().file(0).in(es).exists(); // } // }; // getBrowser().waitFor(cond, waitTime); // // assertFalse(getBrowser().file(0).in(es).exists()); // assertFalse(getBrowser().span("/progressIcon.*/").in(es).exists()); } }
true
bfc4f0c9348632ae4180419965a10f8ea615ae87
Java
helobinvn/gooddata-java
/gooddata-java-model/src/main/java/com/gooddata/sdk/model/project/ProjectValidationResultStringParam.java
UTF-8
1,634
2.109375
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2004-2019, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.sdk.model.project; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonTypeName; import com.gooddata.sdk.common.util.GoodDataToStringBuilder; @JsonTypeName("common") @JsonIgnoreProperties(ignoreUnknown = true) public class ProjectValidationResultStringParam extends ProjectValidationResultParam { private final String value; ProjectValidationResultStringParam(String value) { this.value = value; } // TODO is there some BUG in jackson preventing use the contructor as creator? @JsonCreator private static ProjectValidationResultStringParam create(String value) { return new ProjectValidationResultStringParam(value); } public String getValue() { return value; } @Override public String toString() { return GoodDataToStringBuilder.defaultToString(this); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ProjectValidationResultStringParam that = (ProjectValidationResultStringParam) o; return value != null ? value.equals(that.value) : that.value == null; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } }
true
e2e3724d8c09500b5fb53993fdfa9c7ace34f51c
Java
strawhat925/own-warehouse-parent
/own-warehouse-common/src/main/java/code/warehouse/common/validator/group/Group.java
UTF-8
383
2
2
[]
no_license
package code.warehouse.common.validator.group; import javax.validation.GroupSequence; /** * 定义校验顺序,如果AddGroup组失败,则UpdateGroup组不会再校验 * package code.warehouse.common.validator.group * * @author zli [liz@yyft.com] * @version v1.0 * @create 2017-05-15 15:37 **/ @GroupSequence({ AddGroup.class, UpdateGroup.class }) public interface Group { }
true
f3ff98b3ee86948b3d7f9a7340596658a5e483b0
Java
JoaquinGonzales/ApiAutomation
/src/test/java/BodyTestWithSimpleMap.java
UTF-8
1,755
2.390625
2
[]
no_license
import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; import static Entities.User.ID; import static Entities.User.LOGIN; public class BodyTestWithSimpleMap extends BaseClass { @BeforeMethod public void setUp() { client = HttpClientBuilder.create().build(); } @AfterMethod public void clseResources() throws IOException { client.close(); response.close(); } @Test public void getBodyforGetUserLogin() throws IOException { HttpGet get = new HttpGet(BASE_ENDPOINT+"/users/JoaquinGonzales"); response = client.execute(get); String jsonBody = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = new JSONObject(jsonBody); String actualLoginValue = (String)getValueFor(jsonObject, LOGIN); Assert.assertEquals(actualLoginValue,"JoaquinGonzales"); } @Test public void getBodyforGetUserId() throws IOException { HttpGet get = new HttpGet(BASE_ENDPOINT+"/users/JoaquinGonzales"); response = client.execute(get); String jsonBody = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = new JSONObject(jsonBody); Integer actualLoginValue = (Integer)getValueFor(jsonObject, ID); Assert.assertEquals(actualLoginValue,Integer.valueOf(13631159)); } private Object getValueFor(JSONObject jsonObject, String login) { return jsonObject.get(login); } }
true
ded67e52575de3715d2ad22a0882351cf64916d2
Java
mouhamedahed/KINDERGARTEN-PI-DEV
/PIDEV-Kindergarten/src/main/java/tn/esprit/spring/entity/Niveau.java
UTF-8
66
1.695313
2
[]
no_license
package tn.esprit.spring.entity; public enum Niveau { N1,N2,N3 }
true
19b67948753e44f0255116e65253672e9b5b99ce
Java
caipengbo/Coding-Interviews
/src/problem/P55_1TreeDepth.java
UTF-8
578
3.5
4
[]
no_license
package problem; import util.TreeNode; /** * Title: 55.1 二叉树的深度 * Desc: 输入一棵二叉树,求该树的深度。 * 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 * Created by Myth on 7/1/2019 */ public class P55_1TreeDepth { public int getTreeDepth(TreeNode root) { if (root == null) return 0; int leftDepth = getTreeDepth(root.left); int rightDepth = getTreeDepth(root.right); return Math.max(leftDepth, rightDepth)+1; } }
true
6a6b9004732dfe37fad7c0f78e43ff72eaf54e59
Java
SasankB/CommControl
/mobile/src/main/java/com/android/tinku/commcontrol/UdpService.java
UTF-8
3,149
2.125
2
[ "MIT" ]
permissive
package com.android.tinku.commcontrol; import android.app.IntentService; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ProxyInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.support.annotation.Nullable; import android.text.format.Formatter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.Inet4Address; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class UdpService extends IntentService { public static boolean Started = false; public UdpService() { super("UdpService"); } @Override protected void onHandleIntent(@Nullable Intent intent) { try { if (android.os.Debug.isDebuggerConnected()) { android.os.Debug.waitForDebugger(); } SharedPreferences Prefs = getSharedPreferences(ApplicationConstants.ApplicationPrefs, Context.MODE_PRIVATE); DatagramSocket s = new DatagramSocket(); //String local_ip=InetAddress.getLocalHost().getHostAddress(); //String local_ip = "192.168.43.103"; String local_ip = GetIPAddress(); String[] ip_component = local_ip.split("\\."); String broadcast=ip_component[0]+"."+ip_component[1]+"."+ip_component[2]+"."+"255"; InetAddress local = InetAddress.getByName(broadcast); while (true) { Started = true; String data = Prefs.getString(ApplicationConstants.DirectionKey,""); if (data != "") { String messageStr = data; int server_port = 55555; try { int msg_length = messageStr.length(); byte[] message = messageStr.getBytes(); DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port); p.setData(message); s.send(p); System.out.println(" pressed in service "); }catch (SocketException e) { e.printStackTrace(); }catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } } } catch (Exception ex ) { System.out.println(ex); } } private String GetIPAddress() { WifiManager mgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); int ip = mgr.getConnectionInfo().getIpAddress(); //String ipaddres = Inet4Address(); return String.format("%d.%d.%d.%d",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff),(ip >> 24 & 0xff)); } }
true
48631ae9959f1330d9d42e89ccb8b360112bb0c7
Java
narfman0/GDXWorld
/src/main/java/com/blastedstudios/gdxworld/util/FileUtil.java
UTF-8
1,328
2.71875
3
[ "Beerware" ]
permissive
package com.blastedstudios.gdxworld.util; import java.io.File; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; public class FileUtil { public static final FileHandle ROOT_DIRECTORY = Gdx.files.internal("").isDirectory() ? Gdx.files.internal("") : Gdx.files.internal("."); public static FileHandle find(String name){ return find(ROOT_DIRECTORY, name); } /** * Recursively find file in directory */ public static FileHandle find(FileHandle path, String name){ FileHandle full = Gdx.files.internal(name); if(full.exists()) return full; if(path.name().equals(name)) return path; else if(path.isDirectory()) for(FileHandle childHandle : path.list()){ FileHandle found = find(childHandle, name); if(found != null) return found; } return null; } public static String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) ext = s.substring(i+1).toLowerCase(); return ext; } public static ISerializer getSerializer(FileHandle selectedFile){ for(ISerializer serializer : PluginUtil.getPlugins(ISerializer.class)) if(serializer.getFileFilter().accept(selectedFile.file())) return serializer; return null; } }
true
b230285e9e689ac3a77e234c2cfd4c4564ac466b
Java
liumihust/TurboStream
/jstorm-master/jstorm-core/src/main/java/com/alibaba/jstorm/task/execute/spout/SingleThreadSpoutExecutors.java
UTF-8
2,898
1.703125
2
[ "Apache-2.0" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.jstorm.task.execute.spout; import backtype.storm.task.TopologyContext; import backtype.storm.utils.DisruptorQueue; import com.alibaba.jstorm.client.ConfigExtension; import com.alibaba.jstorm.metric.JStormMetricsReporter; import com.alibaba.jstorm.task.Task; import com.alibaba.jstorm.task.TaskBaseMetric; import com.alibaba.jstorm.task.TaskStatus; import com.alibaba.jstorm.task.TaskTransfer; import com.alibaba.jstorm.task.acker.Acker; import com.alibaba.jstorm.task.comm.TaskSendTargets; import com.alibaba.jstorm.task.comm.TupleInfo; import com.alibaba.jstorm.task.error.ITaskReportErr; import com.alibaba.jstorm.utils.RotatingMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * spout executor * <p/> * All spout actions will be done here * * @author yannian/Longda */ public class SingleThreadSpoutExecutors extends SpoutExecutors { private static Logger LOG = LoggerFactory.getLogger(SingleThreadSpoutExecutors.class); public SingleThreadSpoutExecutors(Task task) { super(task); } @Override public void mkPending() { // sending Tuple's TimeCacheMap if (ConfigExtension.isTaskBatchTuple(storm_conf)) { pending = new RotatingMap<Long, TupleInfo>(Acker.TIMEOUT_BUCKET_NUM, null, false); }else { pending = new RotatingMap<Long, TupleInfo>(Acker.TIMEOUT_BUCKET_NUM, null, true); } } @Override public String getThreadName() { return idStr + "-" + SingleThreadSpoutExecutors.class.getSimpleName(); } @Override public void run() { if (isFinishInit == false ) { initWrapper(); } executeEvent(); super.nextTuple(); /* processControlEvent();*/ controlQueue.consumeBatch(this); } private void executeEvent() { try { exeQueue.consumeBatch(this); } catch (Exception e) { if (taskStatus.isShutdown() == false) { LOG.error("Actor occur unknow exception ", e); } } } }
true
9bff1dab7c1a4e9b4ac964a4280a8fd02559adfb
Java
claireedgcumbe/thesis
/code/src/minicon/MDWithoutExistentialCheck.java
UTF-8
3,799
3.015625
3
[]
no_license
//import java.lang.*; package minicon; import java.util.Vector; //note, need to find out exactly how we can assign to static variables public class MDWithoutExistentialCheck extends MD{ //the purpose of this class is to allow us to keep track of //what's being done in our algorithm public MDWithoutExistentialCheck(Query a_query, View a_view){ super(a_query, a_view); } public boolean addMapping(Mapping amap){//, View a_view){ //this function returns true if adding the mapping suceeded //false if it fails. A mapping fails if what it was mapped to //was previously mapped from something else //returns true if it succeeds, or if the variable was already //mapped to the same thing int mapping_size = mapping.size(); //boolean used = false; if (!_view.variableIsDistinguished(amap.mapping) && _query.variableIsDistinguished(amap.variable)){ //we must make sure that we don't map head variables to non head- variables return false; } for (int i = 0; i < mapping_size ;i++){ if ((((Mapping)mapping.elementAt(i)).variable.equals(amap.variable)) && ((Mapping)mapping.elementAt(i)).mapping.equals(amap.mapping)){ //Prego! It's in there return true; } if (((Mapping)mapping.elementAt(i)).variable.equals(amap.variable) && ((Mapping)mapping.elementAt(i)).variable.equals(amap.variable)){ //at this point, if it is not the case that both of them are //head variables, we need to return false, otherwise we need //to add an equality and return true. We don't need to check //the rest of the variables, because they will have already been //checked and added into the equality. if (!(_view.variableIsDistinguished(((Mapping)mapping.elementAt(i)).mapping) && _view.variableIsDistinguished(amap.mapping))){ //in this case, we can't map the variables because they //both need to be distinguished return false; } else { //we need to add the equality and then return true; it's fine addEquality(((Mapping)mapping.elementAt(i)).mapping,amap.mapping); mapping.addElement(new Mapping(amap)); return true; } } //end if we need to check on the mapping... //note, i need to figure out what to do if the mapping has a problem //because it is mapping the same thing to different vars; clearly this //is something that needs to be checked in the equalities; i'll deal //with that later. Possibly the right thing to do is to check and see if //that's the case, and then add it to the equalities if it is, and then //check the head thingy later.... I think that's the right thing to do. }//end for //at this point, we know that we need to add the mapping to the end, so add it. //at this point we still need to check to see //if we need to add an equality IPValue temp = mappingToVariable(amap.mapping); if (temp != null){ //if this is the case, then it was already mapped to something. //so we must add an equality _view_equalities.addEquality(amap.variable, temp); } mapping.addElement(new Mapping(amap)); //copy it over to avoid problems return true; } }
true
b3c24150f017e810b7a0378aad9f1882a0c139d5
Java
lizhiying61f/PhotoAlbum
/app/src/main/java/com/zhiyingli/photoalbum/AppUtils.java
UTF-8
393
2.03125
2
[]
no_license
package com.zhiyingli.photoalbum; import android.app.Application; /** * Created by zhiyingli on 2016/11/21. */ public class AppUtils { private static Application mApplication; private AppUtils(){} public static void init(Application application){ mApplication = application; } public static Application getApplication(){ return mApplication; } }
true
6ee3fa0f0e5399ebbc965cdca17c4ac5c4992de1
Java
yujin-hong/EHU-interior
/app/src/main/java/com/yujinhong/myapplication2/ui/designreq/DesignreqViewModel.java
UTF-8
471
2.09375
2
[]
no_license
package com.yujinhong.myapplication2.ui.designreq; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class DesignreqViewModel extends ViewModel { private MutableLiveData<String> mText; public DesignreqViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is designreq fragment"); } public LiveData<String> getText() { return mText; } }
true
6cd869833de6f77e398b80ef8c1a4abaceac8db4
Java
hyarthi/project-red
/src/java/org.openntf.red.main/src/org/openntf/red/impl/ViewEntryCollection.java
UTF-8
7,260
1.976563
2
[ "Apache-2.0" ]
permissive
/** * */ package org.openntf.red.impl; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; import org.openntf.red.Database; import org.openntf.red.Session; import org.openntf.red.View; import org.openntf.red.ViewEntry; /** * @author Vladimir Kornienko * */ public class ViewEntryCollection extends Base<org.openntf.red.View> implements org.openntf.red.ViewEntryCollection { /** Logger object. */ private static final Logger log = Logger.getLogger(ViewEntryCollection.class.getName()); /** Back-end object used to manipulate data. */ @SuppressWarnings("rawtypes") private org.openntf.red.nsf.endpoint.ViewEntryCollection beObject; /** * Default constructor. * * @param prnt * Parent view. * @param _beObject * Back-end object. * @since 0.4.0 */ @SuppressWarnings("rawtypes") protected ViewEntryCollection(View prnt, org.openntf.red.nsf.endpoint.ViewEntryCollection _beObject) { super(prnt, Base.NOTES_VECOLL); beObject = _beObject; } /** * Not implemented yet. */ @Override public boolean isDead() { // TODO Auto-generated method stub return false; } /** * Not implemented yet. */ @Override public Iterator<ViewEntry> iterator() { // TODO Auto-generated method stub return null; } /** * Returns the ancestor database. * * @return Ancestor database. * @since 0.4.0 */ @Override public Database getAncestorDatabase() { return parent.getAncestorDatabase(); } /** * Returns the ancestor session. * * @return Ancestor session * @since 0.4.0 */ @Override public Session getAncestorSession() { return parent.getAncestorSession(); } /** * Not implemented yet. */ @Override public void addEntry(Object obh) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void addEntry(Object obj, boolean checkDups) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public org.openntf.red.ViewEntryCollection cloneCollection() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public boolean contains(int noteid) { // TODO Auto-generated method stub return false; } /** * Not implemented yet. */ @Override public boolean contains(String noteid) { // TODO Auto-generated method stub return false; } /** * Not implemented yet. */ @Override public void deleteEntry(lotus.domino.ViewEntry entry) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void FTSearch(String query) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void FTSearch(String query, int maxDocs) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public int getCount() { // TODO Auto-generated method stub return 0; } /** * Not implemented yet. */ @Override public ViewEntry getEntry(Object entry) { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @SuppressWarnings("rawtypes") @Override public ViewEntry getFirstEntry() { org.openntf.red.nsf.endpoint.ViewEntry entry = beObject.getFirstEntry(); if (null == entry) return null; // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getLastEntry() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getNextEntry() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getNextEntry(lotus.domino.ViewEntry entry) { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getNthEntry(int n) { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public View getParent() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getPrevEntry() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public ViewEntry getPrevEntry(lotus.domino.ViewEntry entry) { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public String getQuery() { // TODO Auto-generated method stub return null; } /** * Not implemented yet. */ @Override public void intersect(int noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void intersect(String noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void markAllRead() { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void markAllRead(String userName) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void markAllUnread() { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void markAllUnread(String userName) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void merge(int noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void merge(String noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void putAllInFolder(String folderName) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void putAllInFolder(String folderName, boolean createOnFail) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void removeAll(boolean force) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void removeAllFromFolder(String folderName) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void stampAll(String itemName, Object value) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void subtract(int noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void subtract(String noteid) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void updateAll() { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void stampAll(Map<String, Object> map) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public boolean contains(lotus.domino.Base obj) { // TODO Auto-generated method stub return false; } /** * Not implemented yet. */ @Override public void intersect(lotus.domino.Base obj) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void merge(lotus.domino.Base obj) { // TODO Auto-generated method stub } /** * Not implemented yet. */ @Override public void subtract(lotus.domino.Base obj) { // TODO Auto-generated method stub } }
true
eb0b9f402e2cae22a6fb1d6ab55c95d658371edd
Java
ligaosheng/petition-system-server
/src/main/java/com/example/sens/config/annotation/SystemLog.java
UTF-8
441
2.40625
2
[]
no_license
package com.example.sens.config.annotation; import com.example.sens.enums.LogTypeEnum; import java.lang.annotation.*; /** * 系统日志自定义注解 * @author liuyanzhao */ @Target({ElementType.PARAMETER, ElementType.METHOD})//作用于参数或方法上 @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SystemLog { /** * 日志类型 * @return */ LogTypeEnum type(); }
true
205eb70e685e720d392aed7c6eff23bc92688b68
Java
MonsterDruide1/WeddingPlanner
/WeddingPlanner/app/src/main/java/de/tenolo/weddingplanner/Gaesteliste.java
UTF-8
4,226
2.265625
2
[]
no_license
package de.tenolo.weddingplanner; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import static de.tenolo.weddingplanner.TischordnungNames.loadOrdered; import static de.tenolo.weddingplanner.TischordnungNames.prefs; import static de.tenolo.weddingplanner.TischordnungNames.saveOrdered; public class Gaesteliste extends AppCompatActivity { private RelativeLayout layout; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Methoden methoden = new Methoden(); methoden.onCreateFillIn(this,"Gästeliste",R.layout.gaesteliste); layout = findViewById(R.id.gaesteliste_main); prefs = getSharedPreferences("Prefs",MODE_PRIVATE); generateLayout(); } private void generateLayout(){ String[] list = (loadOrdered("gaesteliste")!=null) ? (loadOrdered("gaesteliste")) : new String[0]; String[] listtest = new String[list.length+1]; listtest[0] = "REMOVE ME"; System.arraycopy(list, 0, listtest, 1, list.length); ShowTischordnungAsList.generateList(listtest,layout,this); layout.removeViews(0,2); } public static void append(String name){ String[] listOld = (loadOrdered("gaesteliste")!=null) ? (loadOrdered("gaesteliste")) : new String[0]; String[] listNew = new String[listOld.length+1]; System.arraycopy(listOld, 0, listNew, 0, listOld.length); listNew[listNew.length-1]=name; saveOrdered("gaesteliste",listNew); } public static void remove(String name){ String[] listOld = loadOrdered("gaesteliste"); String[] listNew = new String[listOld.length-1]; int substract = 0; for(int i=0;i<listOld.length;i++){ if(!listOld[i].equals(name)){ listNew[i+substract] = listOld[i]; } else { substract = -1; } } saveOrdered("gaesteliste",listNew); } public void listeAdd(View view){ final Context context = this; final EditText input = new EditText(context); input.setSingleLine(); input.setImeOptions(EditorInfo.IME_ACTION_DONE); final AlertDialog builder = new AlertDialog.Builder(context) .setTitle("Wer soll zur Gästeliste hinzugefügt werden?") .setView(input) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String editable = input.getText().toString(); Gaesteliste.append(editable); layout.removeAllViews(); generateLayout(); } }) .setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {} }).create(); input.setOnEditorActionListener( new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { builder.getButton(DialogInterface.BUTTON_POSITIVE).performClick(); return true; } return false; } }); builder.show(); } }
true
a71a7908e1e61b62fd84f98b948af7da19175d8f
Java
djm3lman/Web_Video_Player
/projekt_tjee-ejb/src/java/projekt/ws/DataAccessSOAP.java
UTF-8
1,404
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projekt.ws; import javax.ejb.EJB; import javax.jws.WebService; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebParam; import projekt.controler.Controler; /** * * @author student */ @WebService(serviceName = "DataAccessSOAP") @Stateless() public class DataAccessSOAP { @EJB private Controler controler; @WebMethod(operationName = "showFilmList") public String showFilmList(){ return controler.getFilmListHTML(); } @WebMethod(operationName = "addFilm") public boolean addFilm(@WebParam(name = "name") String name, @WebParam(name = "data") byte[] data){ return controler.addFilm(name, data); } @WebMethod(operationName = "deleteFilm") public boolean deleteFilm(@WebParam(name = "filmId") String filmId){ return controler.deleteFilm(filmId); } @WebMethod(operationName = "getFilmData") public String getFilmData(@WebParam(name = "filmId") String filmId){ return controler.getFilmData(filmId); } @WebMethod(operationName = "getFilmName") public String getFilmName(@WebParam(name = "filmId") String filmId){ return controler.getFilmName(filmId); } }
true
e596b858e8fa83a9224d67e8723104cd01dd0f27
Java
KDavis13/CursoJava
/ap-java/Teoria/java/unidad 5-Paso de parametros-Inmutabilidad/exemples/Tema5/src/recursivitat/TestFactorial.java
ISO-8859-2
387
3.5625
4
[]
no_license
package recursivitat; public class TestFactorial { public static void main(String[] args) { long resultat = fact(Integer.valueOf(args[0])); System.out.println("El factorial de " + args[0] + " s: " + resultat ); } /* * Funci recursiva */ private static long fact(int num) { if (num == 0) { return 1; } else { return num * fact(num - 1); } } }
true
730f7b73621bbc85a2b5574a9fae52645a68b052
Java
jview/gae-ssh
/gae-ssh-lib/test/org/esblink/test/testCodeTableBiz.java
UTF-8
1,458
1.9375
2
[]
no_license
package org.esblink.test; import java.util.List; import org.esblink.module.basedata.biz.ICodeTableBiz; import org.esblink.module.basedata.biz.impl.CodeTableBizImpl; import org.esblink.module.basedata.domain.CodeTable; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; public class testCodeTableBiz { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); private ICodeTableBiz codeTableBiz; @Before public void setUp() { helper.setUp(); this.codeTableBiz = new CodeTableBizImpl(); } @After public void tearDown() { helper.tearDown(); } @Test public void testInfo(){ System.out.println("----------aaa"); } @Test public void testSave(){ CodeTable ct = new CodeTable(); ct.setCode("test"); ct.setCodeType("test"); ct.setIfDel(0l); ct.setStatus(1l); ct.setCname("test2"); ct.setDisplay(1l); ct.setEname("test2"); this.codeTableBiz.saveCodeTable(ct); } @Test public void testCodeTableAll(){ List list=this.codeTableBiz.codeTableAll(); System.out.println("----------"+list.size()); } }
true
bfd142114d1d62bd9d512bebd83961a964941576
Java
romello98/KotShare
/app/src/main/java/com/example/kotshare/data_access/services/ServicesConfiguration.java
UTF-8
1,403
2.5
2
[]
no_license
package com.example.kotshare.data_access.services; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ServicesConfiguration { private static final String BASE_URL = "https://kotshare.azurewebsites.net/"; private static ServicesConfiguration servicesConfiguration; private Token token; private Retrofit retrofit; private ServicesConfiguration() { setToken(null); } private void buildRetrofit() { OkHttpClient httpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient(token); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); retrofit = new Retrofit.Builder() .baseUrl(ServicesConfiguration.BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient) .build(); } public void setToken(Token token) { this.token = token; buildRetrofit(); } public static ServicesConfiguration getInstance() { if(servicesConfiguration == null) servicesConfiguration = new ServicesConfiguration(); return servicesConfiguration; } public Retrofit getRetrofit() { return retrofit; } }
true
8a8438bfbf9a7158b7640d168ce9852c09f7af8d
Java
cchaniotaki/university
/DesignPatterns/exercise1/Organizer.java
UTF-8
357
2.625
3
[]
no_license
package exercise1; /** * Author: Christina Chaniotaki */ import java.util.Observable; import java.util.Observer; public class Organizer implements Observer { public Organizer() { } @Override // enimeronei otan ginete kapoio update! public void update(Observable o, Object arg) { System.out.println("Time changed from Organizer"); } }
true
7639f8f509ec3f271e5215634d7a9c12db8be117
Java
Marthgun/Portfolio.io
/CollegeCost.java
UTF-8
8,182
3.53125
4
[]
no_license
/* ********************* Ryan Gray Java Programming CIS-2323 Prof Branstool ********************* Write an application that prompts a user for a child's current age and the estimated college costs for that child at age 18. Continue to reprompt a user who enters an age value greater than 18. Display the amount that the user needs to save each year util the child turns 18, assuming that no interest is earned on the money. For this application, you can assume that integer division provides a sufficient answer. */ package currentage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.Scanner; /** * * @author Meow */ public class CollegeCost { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { test(); do { intro(); redo(); }while (again); pressKey(0); } private static void test() { String name1 = "Jordan"; String name2 = "Jore"; int a = name1.compareTo(name2); System.out.println(a); } private static void intro() throws IOException { Scanner scan = new Scanner(System.in); String usrAge; String schType; int intType; int convertAge; System.out.print(askUsrAge); usrAge = scan.nextLine(); convertAge = Integer.parseInt(usrAge); System.out.print(schoolType); schType = scan.nextLine().toLowerCase(); intType = typeOfSchool(schType); tuitionCalc(convertAge, intType); } private static int typeOfSchool(String type) throws IOException { int temp = 0; if (type.equals("low")) { System.out.println(LOWappFee); System.out.println(LOWentExamFee); System.out.println(LOWtuitionFee); System.out.println(LOWbookCost); System.out.println(miscCost); System.out.print(total + LOWlowTotal + " and " +HIGHlowTotal + ".\n"); System.out.print(inflation); pressKey(1); temp = 1; } if (type.equals("mid")) { System.out.println(MIDappFee); System.out.println(MIDentExamFee); System.out.println(MIDtuitionFee); System.out.println(MIDbookCost); System.out.println(miscCost); System.out.print(total + LOWmidTotal + " and " +HIGHmidTotal + ".\n"); System.out.print(inflation); pressKey(1); temp = 2; } if (type.equals("high")) { System.out.println(HGHappFee); System.out.println(HGHentExamFee); System.out.println(HGHtuitionFee); System.out.println(HGHbookCost); System.out.println(miscCost); System.out.print(total + LOWhighTotal + " and " +HIGHhighTotal + ".\n"); System.out.print(inflation); pressKey(1); temp = 3; } return temp; } private static void tuitionCalc(int age, int iType) { DecimalFormat df = new DecimalFormat("#.00"); int untilEnroll = (18 - age); double[] dArr = new double[untilEnroll]; double[] dArr2 = new double[untilEnroll]; double low = 0; double high = 0; double tempLow = 0; double tempHigh = 0; if (iType == 0) System.out.println("oops"); if(iType == 1) { low = LLT; high = HLT; } if (iType == 2) { low = LMT; high = HMT; } if (iType == 3) { low = HLT; high = HHT; } System.out.println("There are " + untilEnroll + " years until your child should enroll in college."); for (int i = 0; i < untilEnroll; i++) { tempLow = low * inflate; dArr[i] = low + tempLow; tempHigh = high * inflate; dArr2[i] = high + tempHigh; if (i > 0) { low = dArr[i]; high = dArr2[i]; } System.out.println((i + 1) + " Year(s) from now" + " tuition and expenses will be approx between " + df.format(low) + " and " + df.format(high)); } System.out.print("\n\nIn " + untilEnroll + " year(s), you should expect to pay between " + "$"+df.format(dArr[untilEnroll-1]) + " and " + "$" + df.format(dArr2[untilEnroll-1]) + "\nfor tuition and expenses.\n" ); System.out.println(keepInMind); } private static void redo() { Scanner scan = new Scanner(System.in); System.out.print(doOver); String yesORno = scan.nextLine().toLowerCase(); if (yesORno.equals("yes") || yesORno.equals("y")) again = true; else again = false; } private static void pressKey(int x) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); if (x == 0) System.out.println(pressKeyExit); else System.out.println(pressKeyContinue); br.readLine(); } private static boolean again; private static final String pressKeyExit = "Press any key to exit..."; private static final String pressKeyContinue = "Press any key to continue..."; private static final String doOver = "\nWould you like to start over?\nType {Yes} or {No} without brackets:\n>"; private static final String askUsrAge = "\nWhat is the current age of the child?\n" + "If the child is younger than one year, type '0', otherwise enter\n" + "an integer value representing age, i.e. '1', '2', '3', etc.\n>"; private static final String schoolType = "\nGuesstimate the type of college you intend for your child," + "\nThere is the low end 2 year college, the State University, \nor the Ivy League. " + "Keep in mind these are approximations, \nType {low}, {mid}, or {high} without brackets\n>"; private static final String LOWappFee = "\nApplication fees average approx. $50 per school."; private static final String MIDappFee = "\nApplication fees average approx. $65 per school."; private static final String HGHappFee = "\nApplication fees average approx. $75 per school."; private static final String LOWentExamFee = "Entrance exams cost about $100 per examination."; private static final String MIDentExamFee = "Entrance exams cost about $150 per examination."; private static final String HGHentExamFee = "Entrance exams cost about $200 per examination."; private static final String LOWtuitionFee = "Tuition may cost around $5,000 per academic year (nine months)."; private static final String MIDtuitionFee = "Tuition may cost around $15,000 per academic year (nine months)."; private static final String HGHtuitionFee = "Tuition may cost around $30,000 per academic year (nine months)."; private static final String LOWbookCost = "Materials and books may cost upwards of $500 per academic year."; private static final String MIDbookCost = "Materials and books may cost upwards of $750 per academic year."; private static final String HGHbookCost = "Materials and books may cost upwards of $1,000 per academic year."; private static final String miscCost = "Many other variables are involved, such as travel, food, housing, \n" + "clothing and personal expenses that need to be accounted for \ndepending on type of school and location."; private static final String total = "As of this year you could expect to pay between, "; private static final String LOWlowTotal = "5,650"; private static final String HIGHlowTotal = "11,300"; private static final String LOWmidTotal = "15,915"; private static final String HIGHmidTotal = "31,830"; private static final String LOWhighTotal = "31,275"; private static final String HIGHhighTotal = "62,550"; private static final String inflation = "We can speculate based on current tuition inflation rates that tuition will increase " + "\nfrom 3% to 7% per year. Using the average of these two numbers, we can calculate the project " + "\nincrease in tuition from now until your child turns 18, the typical age of enrollment into college.\n\n"; private static final String keepInMind = "Keep in mind these represent averages based on known inflation\n" + "and these figures do not include expenses mentioned earlier, such as travel, housing, clothing, etc."; private static final double LLT = 5650; private static final double HLT = 11300; private static final double LMT = 15915; private static final double HMT = 31830; private static final double LHT = 31275; private static final double HHT = 62550; private static final double inflate = 0.07; }
true
694b26fa0acb213c0bc1e3bdfe07019430755b68
Java
hzllblzjily/nettyexp
/src/main/java/com/hongbao/nettyexp/codec/CustomEncoder.java
UTF-8
1,310
1.960938
2
[]
no_license
/** * */ package com.hongbao.nettyexp.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.Schema; import com.dyuproject.protostuff.runtime.RuntimeSchema; import com.hongbao.nettyexp.Request; /** * @author hzllb * * 2016年1月29日 */ public class CustomEncoder extends MessageToByteEncoder<Serializable>{ /* (non-Javadoc) * @see io.netty.handler.codec.MessageToByteEncoder#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf) */ @Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { // TODO Auto-generated method stub //序列化 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(msg); byte[] byteArray = byteArrayOutputStream.toByteArray(); out.writeInt(byteArray.length); out.writeBytes(byteArray); } }
true
0b438a32eeb3e745cf22470a737e0939a3cd2add
Java
HeHeHa/Discovery
/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/monitor/OpenTelemetryStrategyTracer.java
UTF-8
2,089
1.84375
2
[ "Apache-2.0" ]
permissive
package com.nepxion.discovery.plugin.strategy.opentelemetry.monitor; /** * <p>Title: Nepxion Discovery</p> * <p>Description: Nepxion Discovery</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import com.nepxion.discovery.common.constant.DiscoveryConstant; import com.nepxion.discovery.plugin.strategy.constant.StrategyConstant; import com.nepxion.discovery.plugin.strategy.monitor.AbstractStrategyTracer; public class OpenTelemetryStrategyTracer extends AbstractStrategyTracer<Span> { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") protected Boolean tracerExceptionDetailOutputEnabled; @Autowired private Tracer tracer; @Override protected Span buildSpan() { return tracer.spanBuilder(tracerSpanValue).startSpan(); } @Override protected void outputSpan(Span span, String key, String value) { span.setAttribute(key, value); } @Override protected void errorSpan(Span span, Throwable e) { span.setAttribute(DiscoveryConstant.EVENT, DiscoveryConstant.ERROR); if (tracerExceptionDetailOutputEnabled) { span.setAttribute(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); } else { span.recordException(e); } } @Override protected void finishSpan(Span span) { span.end(); } // Never used probably @Override protected Span getActiveSpan() { return null; } @Override protected String toTraceId(Span span) { return span.getSpanContext().getTraceIdAsHexString(); } @Override protected String toSpanId(Span span) { return span.getSpanContext().getSpanIdAsHexString(); } }
true
24b3918ef5b26bf438a7c0edf795a6a6b7ef96ab
Java
yashpshah/VehicleManagementSystem
/AutomobileIndustry/src/com/util/DatabaseConnection.java
UTF-8
497
2.609375
3
[]
no_license
package com.util; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseConnection { public static Connection createConnection(){ Connection conn = null; String dbUrl = "jdbc:mysql://localhost:3306/automobile"; String username = "root"; String password = ""; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(dbUrl, username,password); } catch (Exception e) { e.printStackTrace(); } return conn; } }
true
bd9d62dea989ceccec6a5148d772b676b8ec0d22
Java
woodscpp/SpringBootLearn
/schedule-task/src/main/java/com/woods/www/scheduletask/quartz/SimpleJob.java
UTF-8
388
2.046875
2
[]
no_license
package com.woods.www.scheduletask.quartz; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.util.Date; /** * @author: woods * @date: 2019/12/7 * @description: */ @Component @Slf4j public class SimpleJob { public void sayHello(){ log.info("simple job>>>{}, Thread>>>{}", new Date(), Thread.currentThread().getId()); } }
true
7f1be4a6d2e016cc3c6697235a33cf57f055f9eb
Java
damogui/testtt
/gsb/gsb-test/src/test/java/com/gongsibao/panda/supplier/igirl/workspace/ic/IcExLogWorkspaceTest.java
UTF-8
3,864
1.835938
2
[]
no_license
package com.gongsibao.panda.supplier.igirl.workspace.ic; import com.gongsibao.entity.igirl.ic.ex.baseinfo.IcExLog; import com.gongsibao.igirl.ic.web.IcExLogListPart; import org.junit.Before; import org.junit.Test; import org.netsharp.core.MtableManager; import org.netsharp.meta.base.WorkspaceCreationBase; import org.netsharp.organization.dic.OperationTypes; import org.netsharp.organization.entity.OperationType; import org.netsharp.panda.controls.ControlTypes; import org.netsharp.panda.dic.DatagridAlign; import org.netsharp.panda.dic.OrderbyMode; import org.netsharp.panda.entity.*; import org.netsharp.panda.plugin.entity.PToolbar; import org.netsharp.panda.plugin.entity.PToolbarItem; import org.netsharp.resourcenode.entity.ResourceNode; /** * @ClassName: IcExLogWorkspaceTest * @Description: 工商日志 * @author: 周瑞帆 * @date: 2018.4.3 * */ public class IcExLogWorkspaceTest extends WorkspaceCreationBase{ public static final String trademarkToolbarPath = "/igirl/tm/toolbar"; @Before public void setup() { super.setup(); urlList = "/igirl/ic/IcExLog/all/list"; urlForm = "/igirl/IcExLog/form"; entity = IcExLog.class; meta = MtableManager.getMtable(entity); resourceNodeCode = "IGRIL_IC_STATE_IcExLog"; listPartName = meta.getName(); listToolbarPath="/igirl/state/IcExLog/list"; listPartImportJs = "/gsb/igirl/js/icexlog.list.part.js"; listPartServiceController = IcExLogListPart.class.getName(); listPartJsController = IcExLogListPart.class.getName(); } public static final String icFormToolbarPath = "/igirl/ic/toolbar"; /*按钮*/ @Test public void fromToolbar() { ResourceNode node = this.resourceService.byCode(resourceNodeCode); OperationType ot1 = operationTypeService.byCode(OperationTypes.add); PToolbar toolbar = new PToolbar(); { toolbar.toNew(); toolbar.setPath(listToolbarPath); toolbar.setName("工具栏"); toolbar.setResourceNode(node); } PToolbarItem item = new PToolbarItem(); /*{ item.toNew(); item.setCode("remove"); item.setIcon("fa fa-trash-o"); item.setName("删除"); item.setCommand(null); item.setOperationType(ot1); item.setSeq(4000); item.setCommand("{controller}.remove();"); toolbar.getItems().add(item); }*/ toolbarService.save(toolbar); } /*首页显示表格*/ @Override protected PDatagrid createDatagrid(ResourceNode node) { PDatagrid datagrid = super.createDatagrid(node); PDatagridColumn column = null; column = addColumn(datagrid, "title", "标题", ControlTypes.TEXT_BOX, 300); column.setAlign(DatagridAlign.CENTER); column = addColumn(datagrid, "content", "内容", ControlTypes.TEXT_BOX, 300); column.setAlign(DatagridAlign.CENTER); column = addColumn(datagrid, "companyName", "公司名称", ControlTypes.TEXT_BOX, 300); column.setAlign(DatagridAlign.CENTER); column = addColumn(datagrid, "corpRegStatue", "状态", ControlTypes.ENUM_BOX, 300); column.setAlign(DatagridAlign.CENTER); column = addColumn(datagrid, "createTime", "时间", ControlTypes.TEXT_BOX, 300); column.setAlign(DatagridAlign.CENTER); column.setOrderbyMode(OrderbyMode.DESC); return datagrid; } @Override protected PQueryProject createQueryProject(ResourceNode node) { PQueryProject queryProject = super.createQueryProject(node); queryProject.toNew(); addQueryItem(queryProject, "title", "标题", ControlTypes.TEXT_BOX); addQueryItem(queryProject, "content", "内容", ControlTypes.TEXT_BOX); addQueryItem(queryProject, "companyName", "公司名称", ControlTypes.TEXT_BOX); return queryProject; } @Override protected void doOperation() { ResourceNode node = this.getResourceNode(); operationService.addOperation(node,OperationTypes.view); operationService.addOperation(node,OperationTypes.add); operationService.addOperation(node,OperationTypes.update); } }
true
8f389c087532627fe93e597dcf9c0a0f7eaa817d
Java
dannuclear/webService
/src/main/java/ru/mephi3/domain/Report.java
UTF-8
911
1.875
2
[]
no_license
package ru.mephi3.domain; import com.vladmihalcea.hibernate.type.json.JsonBinaryType; import lombok.*; import org.hibernate.annotations.*; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; import java.sql.Blob; import java.util.HashMap; import java.util.Map; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "REPORT") @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) public class Report { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "NAME") private String name; @Column(name = "file_name") private String fileName; @Type(type = "jsonb") @Column(name = "parameters") private Map<String, Object> params; @Transient private boolean existsSource; @Transient private boolean existsCompiled; }
true
69e506dc2d2979fa5db37e9bfb9e9f7c0074188c
Java
RimiDev/MaxBook
/src/main/java/com/rimidev/backing/SurveyBacking.java
UTF-8
3,606
2.53125
3
[]
no_license
package com.rimidev.backing; import com.rimidev.maxbook.controller.ClientJpaController; import com.rimidev.maxbook.controller.SurveyJpaController; import com.rimidev.maxbook.entities.Survey; import java.io.Serializable; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import javax.inject.Inject; import org.primefaces.model.chart.Axis; import org.primefaces.model.chart.AxisType; import org.primefaces.model.chart.BarChartModel; import org.primefaces.model.chart.ChartSeries; /** * Backing Bean to aid with the survey section of the home page * * @author Philippe Langlois-Pedroso */ @Named("surveyBacking") @RequestScoped public class SurveyBacking implements Serializable { @Inject private SurveyJpaController surveyJpaController; private Survey survey; private String answer; private BarChartModel barModel; private int questionId = 1; private Logger logger = Logger.getLogger(ClientJpaController.class.getName()); @PostConstruct public void init(){ getSurvey(); createBarModel(); logger.info("BAR MODEL: " +barModel.getTitle()); } public BarChartModel getBarModel(){ return barModel; } /** * Survey created if it does not exist. * * @return */ public Survey getSurvey() { if (survey == null) { logger.info("survey was null"); survey = surveyJpaController.findSurvey(questionId); } return survey; } /** * Save the survey answer to the db * * @returns * @throws Exception */ public void submit() throws Exception{ logger.info("SUBMIT : " +survey.getQuestion()); switch(answer){ case "1": survey.setCount1(survey.getCount1() +1); break; case "2": survey.setCount2(survey.getCount2() +1); break; case "3": survey.setCount3(survey.getCount3() +1); break; case "4": survey.setCount4(survey.getCount4() +1); break; } surveyJpaController.edit(survey); } public String getAnswer() { logger.info("getAnswer() : " +answer); return answer; } public void setAnswer(String answer) { this.answer = answer; logger.info("setAnswer() : " +this.answer); } private BarChartModel initBarModel(){ BarChartModel barModel = new BarChartModel(); ChartSeries results = new ChartSeries(); results.setLabel("Results"); results.set(survey.getOption1(), survey.getCount1()); results.set(survey.getOption2(), survey.getCount2()); results.set(survey.getOption3(), survey.getCount3()); results.set(survey.getOption4(), survey.getCount4()); barModel.addSeries(results); return barModel; } private BarChartModel createBarModel(){ barModel = initBarModel(); barModel.setTitle(survey.getQuestion()); barModel.setLegendPosition("ne"); Axis xAxis = barModel.getAxis(AxisType.X); xAxis.setLabel("Options"); Axis yAxis = barModel.getAxis(AxisType.Y); yAxis.setLabel("Responses"); yAxis.setMin(0); yAxis.setMax(20); return barModel; } }
true
a6844f8352bf38cca23b34123a8fa7c2863c7ccb
Java
henglovejia/BetterCoder
/app/src/main/java/club/bettercoder/main/SplashActivity.java
UTF-8
2,115
2.203125
2
[]
no_license
package club.bettercoder.main; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Window; import android.view.WindowManager; import club.bettercoder.R; import club.bettercoder.base.BaseActivity; import club.bettercoder.login.LoginActivity; import static club.bettercoder.base.BaseContent.WX_CODE_PREF; import static club.bettercoder.base.BaseContent.WX_CODE_PREF_KEY; public class SplashActivity extends BaseActivity { private static final int SPLASH_TIME = 2000; private static final int HAS_LOGIN = 0; private static final int NEED_LOGIN = 1; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Intent intent = null; switch (msg.what) { case HAS_LOGIN: intent = new Intent(SplashActivity.this,MainActivity.class); break; case NEED_LOGIN: intent = new Intent(SplashActivity.this,LoginActivity.class); break; } startActivity(intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { finish(); return; } setContentView(R.layout.module_activity_splash); hideTitleBar(); String wx_code = getSharedPreferences(WX_CODE_PREF,0).getString(WX_CODE_PREF_KEY,null); if(wx_code == null){ mHandler.sendEmptyMessage(NEED_LOGIN); }else { mHandler.sendEmptyMessageDelayed(HAS_LOGIN,SPLASH_TIME); } } @Override protected void initView() { } }
true
d8084e1c1bc3b216e8806797095640a254ea9c7d
Java
lynnbeirlip/TestRepository2020
/GitHubScripts/src/practiceSwitchWindowsandiFrames/switchingiFrames.java
UTF-8
1,743
2.625
3
[]
no_license
package practiceSwitchWindowsandiFrames; import org.testng.annotations.AfterMethod; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class switchingiFrames { public static void main(String[] args) { // TODO Auto-generated method stub WebDriver driver; System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe"); driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; driver.get("https://demoqa.com/iframe-practice-page/"); driver.manage().window().maximize(); //Switch by frame index driver.switchTo().frame(0); System.out.println("The webpage has switched to iframe0 by index"); //Switch by frame name driver.get("https://demoqa.com/iframe-practice-page/"); js.executeScript("window.scrollBy(0,1000)"); driver.switchTo().frame("iframe1"); System.out.println("The webpage has switched to iframe1 by name"); driver.manage().window().maximize(); //Switch by frame id driver.switchTo().parentFrame(); driver.switchTo().frame("IF2"); System.out.println("The webpage has switched to iframe2 by id"); //Switch by xPath driver.switchTo().parentFrame(); driver.switchTo().frame(driver.findElement(By.xpath(".//*[@id='IF2']"))); System.out.println("The webpage has switched to iframe1 by xPath"); //Switch by frame name driver.switchTo().parentFrame(); driver.switchTo().frame(driver.findElement(By.name("iframe2"))); System.out.println("The webpage has switched to iframe2 by name"); driver.close(); } @AfterMethod public void tearDown() throws Exception { Thread.sleep(10000); } }
true
1e1499283c377876f3dcc16415b5865ee17ba818
Java
zazacaca32/DevilCraft-LavaMod
/net/minecraft/client/addon/lavamobs/render/RenderCrazyMonkey.java
UTF-8
1,257
2.21875
2
[]
no_license
package net.minecraft.client.addon.lavamobs.render; import net.minecraft.client.addon.lavamobs.entity.EntityCrazyMonkey; import net.minecraft.client.addon.lavamobs.model.ModelCrazyMonkey; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; public class RenderCrazyMonkey extends RenderLiving { protected ModelBiped model; public RenderCrazyMonkey(ModelCrazyMonkey modelBiped, float f) { super(modelBiped, f); this.setRenderPassModel(new ModelCrazyMonkey()); } public void renderMan(EntityCrazyMonkey entity, double par2, double par4, double par6, float par8, float par9) { super.doRenderLiving(entity, par2, par4, par6, par8, par9); } public void doRenderLiving(EntityLiving par1EntityLiving, double par2, double par4, double par6, float par8, float par9) { this.renderMan((EntityCrazyMonkey)par1EntityLiving, par2, par4, par6, par8, par9); } public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) { this.renderMan((EntityCrazyMonkey)par1Entity, par2, par4, par6, par8, par9); } }
true