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
19c577f795f0b835f0c91217eac5016c7b7feb52
Java
nckmml/ANXGallery
/src/ANXGallery/sources/com/miui/gallery/projection/ProjectionVideoController.java
UTF-8
7,892
1.992188
2
[]
no_license
package com.miui.gallery.projection; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import com.miui.gallery.R; import com.miui.gallery.projection.IConnectController; import com.miui.gallery.util.FormatUtil; import com.miui.gallery.util.Log; public class ProjectionVideoController extends RelativeLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, IConnectController.OnMediaPlayListener { /* access modifiers changed from: private */ public ConnectController mConnectControl; /* access modifiers changed from: private */ public boolean mDragging; private OnFinishListener mFinishListener; private Handler mHandler = new Handler() { public void handleMessage(Message message) { if (message.what == 100) { int access$000 = ProjectionVideoController.this.showProgress(); Log.i("RemoteVideoControl", "show progress %s pos %d", Boolean.valueOf(ProjectionVideoController.this.mDragging), Integer.valueOf(access$000)); if (!ProjectionVideoController.this.mDragging && ProjectionVideoController.this.mConnectControl.isPlaying()) { message = obtainMessage(100); removeMessages(100); sendMessageDelayed(message, (long) (1000 - (access$000 % 1000))); } } super.handleMessage(message); } }; private ImageView mIvPause; private LinearLayout mLayoutQuit; private SeekBar mSbSeek; private TextView mTvCurPos; private TextView mTvDuration; public interface OnFinishListener { void onFinish(); } public ProjectionVideoController(Context context) { super(context); } public ProjectionVideoController(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public ProjectionVideoController(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); } /* access modifiers changed from: private */ public int showProgress() { ConnectController connectController = this.mConnectControl; if (connectController == null || this.mDragging) { return 0; } int currentPosition = connectController.getCurrentPosition(); int duration = this.mConnectControl.getDuration(); updateStatus(); Log.v("RemoteVideoControl", "position %d, duration %d", Integer.valueOf(currentPosition), Integer.valueOf(duration)); if (duration == -1) { return 0; } SeekBar seekBar = this.mSbSeek; if (seekBar != null && duration > 0) { long j = (((long) currentPosition) * 100) / ((long) duration); seekBar.setProgress((int) j); Log.v("RemoteVideoControl", "seek set %d", Long.valueOf(j)); } if (duration == 0) { return currentPosition; } TextView textView = this.mTvDuration; if (textView != null) { textView.setText(FormatUtil.formatVideoDuration((long) (duration / 1000))); } TextView textView2 = this.mTvCurPos; if (textView2 != null) { textView2.setText(FormatUtil.formatVideoDuration((long) (currentPosition / 1000))); } return currentPosition; } /* access modifiers changed from: protected */ public void clearStatus() { TextView textView = this.mTvDuration; if (textView != null) { textView.setText(""); } TextView textView2 = this.mTvCurPos; if (textView2 != null) { textView2.setText(""); } SeekBar seekBar = this.mSbSeek; if (seekBar != null) { seekBar.setProgress(0); } updateStatus(); } /* access modifiers changed from: protected */ public int getPauseImageResId() { return R.drawable.projection_video_pause; } /* access modifiers changed from: protected */ public int getPlayImageResId() { return R.drawable.projection_video_play; } public void initView() { this.mConnectControl = ConnectControllerSingleton.getInstance(); this.mLayoutQuit = (LinearLayout) findViewById(R.id.layout_quit); this.mLayoutQuit.setOnClickListener(this); this.mIvPause = (ImageView) findViewById(R.id.iv_pause); this.mIvPause.setOnClickListener(this); this.mTvCurPos = (TextView) findViewById(R.id.tv_cur_time); this.mTvDuration = (TextView) findViewById(R.id.tv_duration); this.mSbSeek = (SeekBar) findViewById(R.id.sb_seek); this.mSbSeek.setOnSeekBarChangeListener(this); } public void onClick(View view) { if (view == this.mLayoutQuit) { stopPlay(); } else if (view == this.mIvPause) { if (this.mConnectControl.isPlaying()) { this.mConnectControl.pause(); } else { this.mConnectControl.resume(); } updateStatus(); } } /* access modifiers changed from: protected */ public void onDetachedFromWindow() { stopPlay(); super.onDetachedFromWindow(); } public void onLoading() { } public void onPaused() { updateStatus(); } public void onPlaying() { updateStatus(); } public void onProgressChanged(SeekBar seekBar, int i, boolean z) { if (seekBar == this.mSbSeek && z) { this.mConnectControl.getCurrentPosition(); long duration = (((long) this.mConnectControl.getDuration()) * ((long) i)) / 100; this.mConnectControl.seekTo((int) duration); TextView textView = this.mTvCurPos; if (textView != null) { textView.setText(FormatUtil.formatVideoDuration(duration / 1000)); } } } public void onStartTrackingTouch(SeekBar seekBar) { if (seekBar == this.mSbSeek) { this.mDragging = true; this.mConnectControl.pause(); updateStatus(); } } public void onStopTrackingTouch(SeekBar seekBar) { if (seekBar == this.mSbSeek) { this.mDragging = false; this.mConnectControl.resume(); updateStatus(); } } public void onStopped() { updateStatus(); stopPlay(); } public void setOnFinishListener(OnFinishListener onFinishListener) { this.mFinishListener = onFinishListener; } public void startPlay(String str, String str2) { clearStatus(); this.mConnectControl.playVideo(str, str2); this.mConnectControl.resume(); this.mConnectControl.registerMediaPlayListener(this); this.mHandler.removeMessages(100); this.mHandler.sendEmptyMessage(100); } public void stopPlay() { this.mConnectControl.stop(); this.mConnectControl.unregisterMediaPlayListener(this); clearStatus(); this.mHandler.removeMessages(100); OnFinishListener onFinishListener = this.mFinishListener; if (onFinishListener != null) { onFinishListener.onFinish(); } } public void updateStatus() { if (this.mConnectControl.isPlaying()) { this.mIvPause.setImageResource(getPauseImageResId()); this.mHandler.removeMessages(100); this.mHandler.sendEmptyMessage(100); return; } this.mIvPause.setImageResource(getPlayImageResId()); this.mHandler.removeMessages(100); } }
true
f22100a91c87dea467fe4b30ba0d3a09f244a588
Java
C41337/Minecraft-Brawl
/src/main/java/org/infernogames/mb/Managers/AbilityManager.java
UTF-8
889
2.90625
3
[ "MIT" ]
permissive
package org.infernogames.mb.Managers; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.infernogames.mb.Abilities.MBAbility; /** * * @author Paul, Breezeyboy * */ public class AbilityManager { private static List<MBAbility> abilities = new ArrayList<MBAbility>(); public static MBAbility getAbility(String name){ for(MBAbility ab : abilities){ if(ab.name().equalsIgnoreCase(name)){ return ab; } } return null; } public static boolean abilityRegistered(String name){ for(MBAbility ab : abilities){ if(ab.name().equalsIgnoreCase(name)){ return true; } } return false; } public static void registerAbility(MBAbility ab){ abilities.add(ab); Bukkit.getLogger().info("Registerd Ability: " + ab.name()); } }
true
f25fb2bdaa9caac4aad3b5a6727053b6bb2f8481
Java
Caerwent/SoukiAdventure
/app/src/main/java/com/souki/game/adventure/dialogs/GameDialogStep.java
UTF-8
612
2.671875
3
[ "Beerware" ]
permissive
package com.souki.game.adventure.dialogs; import java.util.ArrayList; /** * Created by vincent on 15/03/2017. */ public class GameDialogStep { public String speaker; public ArrayList<String> phrases; public GameDialogStep clone() { GameDialogStep clone = new GameDialogStep(); if (speaker != null) { clone.speaker = new String(speaker); } if (phrases != null) { clone.phrases = new ArrayList<>(); for (String phrase : phrases) { clone.phrases.add(phrase); } } return clone; } }
true
aa0e8a1098e834b2b8decb845e0f440a0061ba8b
Java
umlstudy/com.qualityeclipse.genealogy
/src/com/qualityeclipse/genealogy/commands/CreateNoteCommand.java
UTF-8
863
2.9375
3
[]
no_license
package com.qualityeclipse.genealogy.commands; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.commands.Command; import com.qualityeclipse.genealogy.model.*; /** * Command to add a note to the genealogy graph */ public class CreateNoteCommand extends Command { private final NoteContainer container; private final Note note; private final Rectangle box; public CreateNoteCommand(NoteContainer c, Note n, Rectangle box) { super("Create Note"); this.container = c; this.note = n; this.box = box; } /** * Add the note to the graph at the specified location */ public void execute() { if (box != null) { note.setLocation(box.x, box.y); note.setSize(box.width, box.height); } container.addNote(note); } /** * Remove the note from the graph */ public void undo() { container.removeNote(note); } }
true
eed6b74aca7817765de04bf5fc7dd9e9ceee7216
Java
OmarCardona03/LoginRest
/app/src/main/java/com/appdenuncia/entidades/Denuncia.java
UTF-8
3,873
2.1875
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 com.appdenuncia.entidades; import java.io.Serializable; import java.util.Date; /** * * @author omar */ public class Denuncia implements Serializable { private static final long serialVersionUID = 1L; private String idDenuncia; private String tipoDenuncia; private Date fechaDenuncia; private String direccion; private String descripcion; private String imagen; private Barrio idBarrio; private Ciudad idCiudad; private Departamento idDepartamento; private TipoEntidad idEntidad; private String correo; public Denuncia() { } public Denuncia(String idDenuncia) { this.idDenuncia = idDenuncia; } public Denuncia(String idDenuncia, String tipoDenuncia, Date fechaDenuncia, String direccion, String descripcion, String imagen) { this.idDenuncia = idDenuncia; this.tipoDenuncia = tipoDenuncia; this.fechaDenuncia = fechaDenuncia; this.direccion = direccion; this.descripcion = descripcion; this.imagen = imagen; } public String getIdDenuncia() { return idDenuncia; } public void setIdDenuncia(String idDenuncia) { this.idDenuncia = idDenuncia; } public String getTipoDenuncia() { return tipoDenuncia; } public void setTipoDenuncia(String tipoDenuncia) { this.tipoDenuncia = tipoDenuncia; } public Date getFechaDenuncia() { return fechaDenuncia; } public void setFechaDenuncia(Date fechaDenuncia) { this.fechaDenuncia = fechaDenuncia; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public Barrio getIdBarrio() { return idBarrio; } public void setIdBarrio(Barrio idBarrio) { this.idBarrio = idBarrio; } public Ciudad getIdCiudad() { return idCiudad; } public void setIdCiudad(Ciudad idCiudad) { this.idCiudad = idCiudad; } public Departamento getIdDepartamento() { return idDepartamento; } public void setIdDepartamento(Departamento idDepartamento) { this.idDepartamento = idDepartamento; } public TipoEntidad getIdEntidad() { return idEntidad; } public void setIdEntidad(TipoEntidad idEntidad) { this.idEntidad = idEntidad; } @Override public int hashCode() { int hash = 0; hash += (idDenuncia != null ? idDenuncia.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 Denuncia)) { return false; } Denuncia other = (Denuncia) object; if ((this.idDenuncia == null && other.idDenuncia != null) || (this.idDenuncia != null && !this.idDenuncia.equals(other.idDenuncia))) { return false; } return true; } @Override public String toString() { return "appdenuncias.entidades.Denuncia[ idDenuncia=" + idDenuncia + " ]"; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } }
true
1c2e5ad0df60925f1feac6f8e9b812945dc33a96
Java
AlexSamoylov/Production_system
/src/org/dnu/samoylov/model/PsEnumLabel.java
UTF-8
871
2.421875
2
[]
no_license
package org.dnu.samoylov.model; import org.dnu.samoylov.util.PsLabelHelper; import java.util.Arrays; import java.util.List; public class PsEnumLabel { private String prefix; private final List<String> names; public PsEnumLabel(String prefix, String... names) { this.names = Arrays.asList(names); this.prefix = prefix; } public String getPrefix() { return prefix; } public List<String> getNames() { return names; } public static PsEnumLabel create(String prefix, String... names) { return new PsEnumLabel(prefix, names); } List<PsLabel> equivalentLabels; public List<PsLabel> getEquivalentLabels() { if(equivalentLabels==null) { equivalentLabels = PsLabelHelper.getInstance().createLabelsFromEnum(this); } return equivalentLabels; } }
true
84649b43bec98a658ab711095c611b65050c405e
Java
jonananas/tdd-the-database
/src/test/java/se/jonananas/tdd/PersonRepositoryTest.java
UTF-8
535
2.4375
2
[]
no_license
package se.jonananas.tdd; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; public abstract class PersonRepositoryTest { @Test public void shouldStorePerson() throws Exception { Person person = Person.create(); repo().store(person); } @Test public void shouldFindPerson() throws Exception { Person person = Person.create(); repo().store(person); Person found = repo().findById(person.getId()); assertThat(found).isEqualTo(person); } protected abstract PersonRepository repo(); }
true
f554bb846a0980482b23a7e64f54e9ff90e30a96
Java
yz1201/itravel
/src/test/java/cn/dbdj1201/itravel/dao/impl/RouteDaoImplTest.java
UTF-8
513
1.976563
2
[]
no_license
package cn.dbdj1201.itravel.dao.impl; import cn.dbdj1201.itravel.domain.Route; import org.junit.Test; import static org.junit.Assert.*; /** * @author tyz1201 * @datetime 2020-02-24 15:27 **/ public class RouteDaoImplTest { @Test public void findByPage() { // RouteDaoImpl dao = new RouteDaoImpl(); // dao.findByPage(5, 1, 100).forEach(System.out::println); } @Test public void findTotalCount() { // System.out.println(new RouteDaoImpl().findTotalCount(5)); } }
true
64e283a815c210cf1200ea6f24cde85026e3c994
Java
jeremyDevwwm/hibernateTesting
/src/main/java/com/amiltone/hibernatetesting/entity/Person.java
UTF-8
875
2.328125
2
[]
no_license
package com.amiltone.hibernatetesting.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Table; import javax.persistence.Id; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "test_user") public class Person { @Id @GeneratedValue private int Id; private String firstname; private String name; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
8b75bb2207a65a0b845e87afb11453ff7a9b31a3
Java
aberu78/UdemyCodingExcercise
/Section4/Section4CodingExercise/src/DecimalComparator.java
UTF-8
397
3.203125
3
[]
no_license
public class DecimalComparator { public static boolean areEqualByThreeDecimalPlaces(double decimal1, double decimal2) { if (decimal1 == 0 && decimal2 == 0) return true; decimal1 = Math.round(decimal1 * 10000) / 10.0; decimal2 = Math.round(decimal2 * 10000) / 10.0; return decimal1 / decimal2 > 0 && (int) decimal1 % (int) decimal2 == 0; } }
true
890e036d2b6b640a4a5545b7388ad1b007b03f79
Java
anyedilong/hcplatform
/src/main/java/com/java/moudle/system/dto/LoginInfoDto.java
UTF-8
2,790
2.03125
2
[]
no_license
package com.java.moudle.system.dto; import java.io.Serializable; import com.java.moudle.system.domain.SysRole; import com.java.until.DictUtil; public class LoginInfoDto implements Serializable { private static final long serialVersionUID = 1L; private String id;//主键 private String username; private String password; private String phone; private String name; private String sfzh; private String custormerUrl; private String gx; private String authorities; private String orgName; /** 银行卡类型 字典表 */ private Integer bankCardType; private String bankCardTypeName; /** 银行卡号 */ private String bankCardNumber; private String isRealName;//0.未实名认证 1.身份证认证 2.银行卡认证 private SysRole role; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSfzh() { return sfzh; } public void setSfzh(String sfzh) { this.sfzh = sfzh; } public String getCustormerUrl() { return custormerUrl; } public void setCustormerUrl(String custormerUrl) { this.custormerUrl = custormerUrl; } public String getGx() { return gx; } public void setGx(String gx) { this.gx = gx; } public String getAuthorities() { return authorities; } public void setAuthorities(String authorities) { this.authorities = authorities; } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public SysRole getRole() { return role; } public void setRole(SysRole role) { this.role = role; } public Integer getBankCardType() { return bankCardType; } public void setBankCardType(Integer bankCardType) { this.bankCardTypeName = DictUtil.getDictValue("BankCardType", bankCardType+""); this.bankCardType = bankCardType; } public String getBankCardTypeName() { return bankCardTypeName; } public void setBankCardTypeName(String bankCardTypeName) { this.bankCardTypeName = bankCardTypeName; } public String getBankCardNumber() { return bankCardNumber; } public void setBankCardNumber(String bankCardNumber) { this.bankCardNumber = bankCardNumber; } public String getIsRealName() { return isRealName; } public void setIsRealName(String isRealName) { this.isRealName = isRealName; } }
true
94d9a0ef99f7e61e61878c8b4d76c3bb5f8fb5f7
Java
moshangguang/spring-boot-study
/spring-boot-helloworld/src/main/java/com/springboot/controller/HelloController.java
UTF-8
692
2.34375
2
[]
no_license
package com.springboot.controller; import com.springboot.entity.Worker; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.web.bind.annotation.*; @RestController public class HelloController { Counter helloCounter; public HelloController(MeterRegistry meterRegistry) { helloCounter = meterRegistry.counter("HelloController.hello.count"); } @RequestMapping("/hello") public String hello() { helloCounter.increment(); return "hello spring boot"; } @PostMapping("/worker") public Worker helloWorker(@RequestBody Worker worker) { return worker; } }
true
6df9b6c75d0cd0b0e153a6d3c780bfcba6a90cca
Java
miaoooooopasi/myblog
/src/main/java/com/leon/myblog/enity/Point.java
UTF-8
501
2.0625
2
[]
no_license
/** * Copyright 2020 bejson.com */ package com.leon.myblog.enity; /** * Auto-generated: 2020-04-21 11:47:48 * * @author bejson.com ([email protected]) * @website http://www.bejson.com/java2pojo/ */ public class Point { private String x; private String y; public String getX() { return x; } public void setX(String x) { this.x = x; } public String getY() { return y; } public void setY(String y) { this.y = y; } }
true
0aca1e284ea37210b31ab587855e77b2bfdbc4f8
Java
vsidarovich/ramp-up
/hadoop/1/src/main/java/com/epam/bigdata/Fourth.java
UTF-8
191
1.96875
2
[]
no_license
package com.epam.bigdata; /** * Created by cloudera on 2/11/16. */ public class Fourth { public static void main(String ...args){ System.out.println("Fourth is done"); } }
true
6f1675f8a8708ada4da784cd5e56d7b86ced1b8a
Java
qq850405/TestMySQL
/app/src/main/java/my/inclassi/testmysql/ViewFinishedStoreActivity.java
UTF-8
4,215
2.140625
2
[]
no_license
package my.inclassi.testmysql; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ViewFinishedStoreActivity extends AppCompatActivity { String url = "http://140.135.112.8/CollectionSystem/app/finishedStoreSearch.php"; String no, cat, proNo; String[] func; RequestQueue requestQueue; ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_finished_store); list = (ListView) findViewById(R.id.listView); requestQueue = Volley.newRequestQueue(getApplicationContext()); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { //處理JSONArray @Override public void onResponse(JSONObject response) { System.out.println(response.toString()); //使用Try Catch是因為getJSONArray有可能抓不到值 try { //透過response.getJSONArray()取得JSONArray JSONArray data = response.getJSONArray("data"); int flag = 0; //利用迴圈取得data[]內的資料 func = new String[data.length()]; for (int i = 0; i < data.length(); i++) { JSONObject jasonData = data.getJSONObject(i); //取得jasonData內的資料 String finishedStoreNo = jasonData.getString("finishedStoreNo"); String space = jasonData.getString("space"); String manuNo = jasonData.getString("manuNo"); func[i] = "test"; //if ((no.equals(finishedNo)&&!no.equals("")) ||((cat.equals(category) && !cat.equals("")) ||(proNo.equals(productNo) && !proNo.equals("")))) { func[i] = ( "成品倉號: " + space + "\n" + "製令號:" + manuNo ); Log.d("test1", func[i]); // Log.d("cate", cat); } int count = 0; String search[]; for (int i = 0; i < func.length; i++) { if (!func[i].equals("test")) { count++; } } int temp = 0; search = new String[count]; for (int i = 0; i < func.length; i++) { if (!func[i].equals("test")) { search[temp] = func[i]; temp++; Log.d("search",search[i]); } } ArrayAdapter adapter = new ArrayAdapter(ViewFinishedStoreActivity.this, android.R.layout.simple_list_item_1, search); list.setAdapter(adapter); } catch (JSONException e) { //錯誤處理 e.printStackTrace(); new AlertDialog.Builder(ViewFinishedStoreActivity.this) .setTitle("華新麗華員工系統") .setMessage(" " + e) .setPositiveButton("ok", null) .show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.append(error.getMessage()); } }); requestQueue.add(jsonObjectRequest); } }
true
db21fb5f6b8dd9dc51d2bc5af209f27625ddb95a
Java
locoabuelito/microservicios
/service-shopping/src/main/java/academy/digitallab/shopping/service/InvoiceServiceImpl.java
UTF-8
3,117
2.328125
2
[]
no_license
package academy.digitallab.shopping.service; import academy.digitallab.shopping.client.CustomerClient; import academy.digitallab.shopping.client.ProductsClient; import academy.digitallab.shopping.entity.Invoice; import academy.digitallab.shopping.entity.InvoiceItem; import academy.digitallab.shopping.model.Customer; import academy.digitallab.shopping.model.Products; import academy.digitallab.shopping.repository.InvoiceItemsRepository; import academy.digitallab.shopping.repository.InvoiceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class InvoiceServiceImpl implements InvoiceService{ @Autowired InvoiceRepository invoiceRepository; @Autowired InvoiceItemsRepository invoiceItemsRepository; @Autowired CustomerClient customerClient; @Autowired ProductsClient productsClient; @Override public List<Invoice> findInvoiceAll() { return invoiceRepository.findAll(); } @Override public Invoice createInvoice(Invoice invoice) { Invoice invoiceDB = invoiceRepository.findByNumberInvoice ( invoice.getNumberInvoice () ); if (invoiceDB !=null){ return invoiceDB; } invoice.setState("CREATED"); invoiceDB = invoiceRepository.save(invoice); invoiceDB.getItems().forEach( invoiceItem -> { productsClient.updateStockProducts( invoiceItem.getProductId(), invoiceItem.getQuantity() * -1); }); return invoiceDB; } @Override public Invoice updateInvoice(Invoice invoice) { Invoice invoiceDB = getInvoice(invoice.getId()); if (invoiceDB == null){ return null; } invoiceDB.setCustomerId(invoice.getCustomerId()); invoiceDB.setDescription(invoice.getDescription()); invoiceDB.setNumberInvoice(invoice.getNumberInvoice()); invoiceDB.getItems().clear(); invoiceDB.setItems(invoice.getItems()); return invoiceRepository.save(invoiceDB); } @Override public Invoice deleteInvoice(Invoice invoice) { Invoice invoiceDB = getInvoice(invoice.getId()); if (invoiceDB == null){ return null; } invoiceDB.setState("DELETED"); return invoiceRepository.save(invoiceDB); } @Override public Invoice getInvoice(Long id) { Invoice invoice = invoiceRepository.findById(id).orElse(null); if(invoice != null){ Customer customer = customerClient.getCustomer(invoice.getCustomerId()).getBody(); invoice.setCustomer(customer); List<InvoiceItem> items = invoice.getItems().stream().map(invoiceItem -> { Products products = productsClient.getProducts(invoiceItem.getProductId()).getBody(); invoiceItem.setProducts(products); return invoiceItem; }).collect(Collectors.toList()); invoice.setItems(items); } return invoice; } }
true
12cc8b15c77f454f83371b7d40a64f1fedc09a05
Java
chacanthus/ymt2-neo
/decompiled_java/com/badlogic/gdx/utils/XmlWriter.java
UTF-8
4,201
2.640625
3
[]
no_license
// 도박중독 예방 캠페인 // 당신 곁에 우리가 있어요! // 감당하기 힘든 어려움을 혼자 견디고 계신가요? // 무엇을 어떻게 해야 할지 막막한가요? // 당신의 이야기를 듣고 도움을 줄 수 있는 정보를 찾아 드립니다. // - 한국도박문제관리센터 (국번없이 1336, 24시간) // - KL중독관리센터 (전화상담 080-7575-535/545) // - 사행산업통합감독위원회 불법사행산업감시신고센터 (전화상담 1588-0112) // - 불법도박 등 범죄수익 신고 (지역번호 + 1301) package com.badlogic.gdx.utils; import java.io.IOException; import java.io.Writer; public class XmlWriter extends Writer { private String currentElement; public int indent; private boolean indentNextClose; private final Array stack; private final Writer writer; public XmlWriter(Writer writer) { super(); this.stack = new Array(); this.writer = writer; } public XmlWriter attribute(String name, Object value) throws IOException { String v0; if(this.currentElement == null) { throw new IllegalStateException(); } this.writer.write(32); this.writer.write(name); this.writer.write("=\""); Writer v1 = this.writer; if(value == null) { v0 = "null"; } else { v0 = value.toString(); } v1.write(v0); this.writer.write(34); return this; } public void close() throws IOException { while(this.stack.size != 0) { this.pop(); } this.writer.close(); } public XmlWriter element(String name) throws IOException { if(this.startElementContent()) { this.writer.write(10); } this.indent(); this.writer.write(60); this.writer.write(name); this.currentElement = name; return this; } public XmlWriter element(String name, Object text) throws IOException { return this.element(name).text(text).pop(); } public void flush() throws IOException { this.writer.flush(); } private void indent() throws IOException { int v0 = this.indent; if(this.currentElement != null) { ++v0; } int v1; for(v1 = 0; v1 < v0; ++v1) { this.writer.write(9); } } public XmlWriter pop() throws IOException { if(this.currentElement != null) { this.writer.write("/>\n"); this.currentElement = null; } else { this.indent = Math.max(this.indent - 1, 0); if(this.indentNextClose) { this.indent(); } this.writer.write("</"); this.writer.write(this.stack.pop()); this.writer.write(">\n"); } this.indentNextClose = true; return this; } private boolean startElementContent() throws IOException { boolean v0; if(this.currentElement == null) { v0 = false; } else { ++this.indent; this.stack.add(this.currentElement); this.currentElement = null; this.writer.write(">"); v0 = true; } return v0; } public XmlWriter text(Object text) throws IOException { boolean v1; String v0; int v3 = 10; this.startElementContent(); if(text == null) { v0 = "null"; } else { v0 = text.toString(); } if(v0.length() > 64) { v1 = true; } else { v1 = false; } this.indentNextClose = v1; if(this.indentNextClose) { this.writer.write(v3); this.indent(); } this.writer.write(v0); if(this.indentNextClose) { this.writer.write(v3); } return this; } public void write(char[] cbuf, int off, int len) throws IOException { this.startElementContent(); this.writer.write(cbuf, off, len); } }
true
f3ccf85d5d754a76e10c801bbfcf24aaff96eeb7
Java
kanghansung/About_Android-Studies-Projects-
/Project_SPOT/SPOT_AREA_CATEGORY/app/src/main/java/org/techtown/spot_area_category/FragmentTitleMenuBar.java
UTF-8
2,454
2.203125
2
[]
no_license
package org.techtown.spot_area_category; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class FragmentTitleMenuBar extends Fragment { private boolean isFragmentArea; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View fragmentTitleMenuBar = inflater.inflate(R.layout.fragment_menubar, container, false); final TextView txtBack = (TextView)fragmentTitleMenuBar.findViewById(R.id.txtBack); final Button btnSelectKind = (Button)fragmentTitleMenuBar.findViewById(R.id.btnSelectKind); final TextView txtSearch = (TextView)fragmentTitleMenuBar.findViewById(R.id.txtSearch); btnSelectKind.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(btnSelectKind.getText().equals("지역별 검색")) btnSelectKind.setText("카테고리별 검색"); else btnSelectKind.setText("지역별 검색"); switchFragmentAreaOrCategory(); } }); return fragmentTitleMenuBar; } public void switchFragmentAreaOrCategory(){ Fragment menubar; ListFragment listFragment; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if(isFragmentArea){ menubar = new FragmentAreaMenuBar(); listFragment = new FragmentAreaListView(); } else{ menubar = new FragmentCategoryMenuBar(); listFragment = new FragmentAreaListView(); //형틀로 임시방편으로해둠. } isFragmentArea = (isFragmentArea) ? false : true; fragmentTransaction.replace(R.id.fragmentMenuBar, menubar); fragmentTransaction.replace(R.id.fragmentFirstorAreaorCategory, listFragment); fragmentTransaction.commit(); } }
true
f6a8441ebc0cd0b67d216a8452d896f4ac8929bb
Java
Venkipullela/java_practice
/src/HotelManagementSystem/Level.java
UTF-8
243
2.421875
2
[]
no_license
package HotelManagementSystem; import java.util.ArrayList; import java.util.List; public class Level { Integer lvl; List<Room> rooms = new ArrayList<>(); public Integer addRooms(RoomType roomType) { return null; } }
true
9e8c211fb802320b7eb34abf7fdfe12ecf7bda60
Java
alexguo1980/bachelor
/bachelor_ip/bachelor-auth/src/main/java/org/bachelor/auth/service/impl/AuthRoleUserServiceImpl.java
UTF-8
10,238
2.140625
2
[ "Apache-2.0" ]
permissive
package org.bachelor.auth.service.impl; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.bachelor.auth.dao.IAuthRoleUserDao; import org.bachelor.auth.domain.AuthRoleUser; import org.bachelor.auth.domain.Role; import org.bachelor.auth.service.IAuthRoleUserService; import org.bachelor.auth.service.IRoleService; import org.bachelor.auth.vo.AuthRoleUserVo; import org.bachelor.org.domain.User; @Service public class AuthRoleUserServiceImpl implements IAuthRoleUserService { @Autowired private IAuthRoleUserDao aruDao = null; @Autowired private IRoleService roleServiceImpl = null; @Override public void add(AuthRoleUser aru) { // TODO Auto-generated method stub aruDao.save(aru); } @Override public void addOrUpdate(AuthRoleUser aru) { if (!StringUtils.isEmpty(aru.getId())) { aruDao.updateByAuthRoleUser(aru); } else { String roleIds[] = aru.getRoleIds().split(","); if (roleIds != null && roleIds.length > 0) { Role role; for (String roleId : roleIds) { role = new Role(); role.setId(roleId); AuthRoleUser saveAru = new AuthRoleUser(); saveAru.setRole(role); saveAru.setUser(aru.getUser()); aruDao.save(saveAru); } } } } @Override public void delete(AuthRoleUser aru) { aruDao.delete(aru); } @Override public void deleteById(String id) { // TODO Auto-generated method stub AuthRoleUser aru = new AuthRoleUser(); aru.setId(id); aruDao.delete(aru); } @Override public List<AuthRoleUserVo> findByExample(AuthRoleUserVo aruVo) { // TODO Auto-generated method stub return aruDao.findByExample(aruVo); } @Override public AuthRoleUser findById(String id) { // TODO Auto-generated method stub return aruDao.findById(id); } @Override public void update(AuthRoleUser aru) { // TODO Auto-generated method stub aruDao.update(aru); } @Override public List<AuthRoleUser> findAll() { // TODO Auto-generated method stub return aruDao.findAll(); } @Override public List<Role> findRolesByUserId(String userId) { // List<Role> role_list = aruDao.findByUserId(userId); // //过滤AuthFunction中不可见的权限对象 // if(role_list!=null && role_list.size()>0){ // for(Role role : role_list){ // if(role.getAuthFunctions()!=null && // role.getAuthFunctions().size()>0){ // List<AuthFunction> temp_list = new ArrayList<AuthFunction>(); // for(AuthFunction af : role.getAuthFunctions()){ // if(af.getVisible().equals("1")){ // temp_list.add(af); // } // } // role.setAuthFunctions(temp_list); // } // } // } return aruDao.findByUserId(userId); } @Override public List<AuthRoleUser> findListByExample(AuthRoleUser aru) { return aruDao.findListByExample(aru); } @Override public void batchDelete(String info) { // TODO Auto-generated method stub String deleteInfo[] = info.split(","); String dSQL[] = new String[deleteInfo.length]; int index = 0; for (String dInfo : deleteInfo) { dSQL[index] = "delete from T_bchlr_AUTH_ROLE_USER where id='" + dInfo + "'"; index++; } aruDao.batchDelete(dSQL); } /** * 取得指定角色包含的用户 如有重复用户则进行过滤。 * * @param roleIds * 角色Id数组 * @return 包含的用户列表 */ @Override public List<User> findUsersByRoleIds(String... roleIds) { if (roleIds == null || roleIds.length <= 0) { return null; } StringBuffer roleQuery = new StringBuffer(); int index = 0; for (String roleId : roleIds) { roleQuery.append("'").append(roleId).append("'"); if (index < (roleIds.length - 1)) { roleQuery.append(","); } index++; } return aruDao.findUsersByRoleIds(roleQuery.toString()); } /** * 判断当前用户是否具有指定的角色 如果参数是多个角色Id,那么当前用户只要具有其中一个角色就返回True,否则返回False。 * * @param userId * 用户Id * @param roleIds * 角色Id的数组 * @return */ @Override public boolean hasRoles(String userId, String... roleIds) { List<Role> roles = aruDao.findByUserId(userId); if (roles == null || roles.size() <= 0 || roleIds == null || roleIds.length <= 0) { return false; } for (Role role : roles) { for (String roleId : roleIds) { /** 判断传的roleIds中是否有相等的roleid **/ if (role.getId().equals(roleId)) { return true; } } } return false; } /** * * 取得指定角色和单位所包含的用户。 如有重复用户则进行过滤。 * 角色和单位应该以"#"区分,例如adminRole#0608000000,表示取得海淀供电公司的具有adminRole角色的人员. * * @param roleIds * 角色和单位ID的数组。 * 角色和单位应该以"#"区分,例如adminRole#0608000000,表示取得海淀供电公司的具有adminRole角色的人员 * 。 * @return 包含的用户列表 * * */ @Override public Set<User> findUsersByRoleIdAndOrgId(String... roleOrgIds) { Set<User> users = new HashSet<User>(); if (roleOrgIds != null && roleOrgIds.length > 0) { /** 根据角色,单位ID数组转换成查询条件 **/ List<User> tempUsers = aruDao.findUsersByRoleIdsAndOrgIds( splitArrayByRoleOrOrg("roles", roleOrgIds), splitArrayByRoleOrOrg("orgs", roleOrgIds)); users = new HashSet<User>(tempUsers); } return users; } /** * 取得指定角色和单位所包含的用户。 如有重复用户则进行过滤。 * 角色和单位应该以"#"区分,例如adminRole#0608000000,表示取得海淀供电公司的具有adminRole角色的人员。 * 如果不需要分单位,则传入参数时只要传入角色Id就可以。 * * @param roleIds * 角色和单位ID的数组。 * 角色和单位应该以"#"区分,例如adminRole#0608000000,表示取得海淀供电公司的具有adminRole角色的人员 * 。 * @return 包含的用户列表 */ @Override public Set<User> findUsersByRoleNameAndOrgId(String... roleOrgIds) { Set<User> users = new HashSet<User>(); if (roleOrgIds != null && roleOrgIds.length > 0) { /** 根据角色名称,单位ID数组转换成查询条件 **/ List<User> tempUsers = aruDao.findUsersByRoleNamesAndOrgIds( splitArrayByRoleOrOrg("roles", roleOrgIds), splitArrayByRoleOrOrg("orgs", roleOrgIds)); users = new HashSet<User>(tempUsers); } return users; } /** * 根据角色或者单位信息,拆分成相对应查询条件 * * @param roleIdsOrOrgIds * @return */ public String splitArrayByRoleOrOrg(String type, String... roleIdsOrOrgIds) { /** 角色数组 **/ String splitArray[] = new String[roleIdsOrOrgIds.length]; int index = 0; for (String ro : roleIdsOrOrgIds) { if ("roles".equals(type)) { /** 拆分角色数组 **/ splitArray[index] = StringUtils.substringBefore(ro, "#"); } if ("orgs".equals(type)) { /** RO字符串可能没有机构 **/ String tempArray[] = ro.split("#"); if (tempArray.length > 1) { /** 拆分单位数组 **/ splitArray[index] = StringUtils.substringAfterLast(ro, "#"); } } index++; } return splitRoleOrOrg(splitArray); } /** * 拆分角色或者单位数组 */ public String splitRoleOrOrg(String... roleIdsOrOrgIds) { String group = ""; if (roleIdsOrOrgIds != null && roleIdsOrOrgIds.length > 0) { int index = 0; for (String ro : roleIdsOrOrgIds) { if (ro != null && !"".equals(ro)) { group += "'" + ro + "'"; if (index < (roleIdsOrOrgIds.length - 1)) { group += ","; } } else { index++; if (index == (roleIdsOrOrgIds.length) && group.length() > 0) { group = group.substring(0, group.length() - 1); } } index++; } } return group; } @Override public List<User> findUserByOrgIdOrRoleName(String orgId, String roleName) { return aruDao.findUserByOrgIdOrRoleName(orgId, roleName); } @Override public void batchSaveRolesPersonal(List<AuthRoleUser> arus) { if (arus != null && arus.size() > 0) { Integer size = arus.size(); /** 导入值大于1000时,对数据进行分批批量插入 **/ if (size > 1000) { int countNumber = arus.size() / 1000; /** 分批批量进行插入 **/ for (int i = 0; i < countNumber; i++) { batchSave((i * 1000), ((i + 1) * 1000), arus); } /** 把得到余数也插入到数据库中 **/ if (arus.size() - (countNumber * 1000) > 0) { batchSave((countNumber * 1000), (arus.size()), arus); } } else if (size <= 1000) {// 导入值小于1000时,直接进行插入操作 batchSave(0, arus.size(), arus); } } } /** * 批量保存 startVal 开始下标值 endVal 结束下标值 afs 导入数据集合 */ public void batchSave(Integer startVal, Integer endVal, List<AuthRoleUser> arus) { StringBuilder sql; String iSQL[] = new String[endVal]; int index = 0; for (int i = startVal; i < endVal; i++) { AuthRoleUser aru = arus.get(i); sql = new StringBuilder(); sql.append("insert into T_bchlr_AUTH_ROLE_USER(ID,ROLE_ID,USER_ID)"); sql.append(" values(sys_guid(),'").append(aru.getRole().getId()); sql.append("','").append(aru.getUser().getId()).append("')"); iSQL[index] = sql.toString(); index++; } aruDao.batchSaveRolesPersonal(iSQL); } @Override public boolean removeUserFormRole(String roleName, String userId) { boolean delFlag = true; Role role = roleServiceImpl.findByName(roleName); /** 角色对象或者角色ID为空时,返回FLASE同时跳出方法体**/ if(role==null || StringUtils.isEmpty(role.getId())){ delFlag = false; return delFlag; } AuthRoleUser aru = aruDao.findByRoleIdAndUserId(role.getId(), userId); /** 角色映射对象或者角色映射ID为空时,返回FLASE同时跳出方法体**/ if(aru==null || StringUtils.isEmpty(aru.getId())){ delFlag = false; return delFlag; } /** 删除映射关系 **/ aruDao.delete(aru); return delFlag; } }
true
2e11eff0fa1b3a668f5edccec120b20474b40cb0
Java
svanacker/cen-info-web
/Bot/src/java/main/org/cen/cup/cup2011/device/gripper2011/Gripper2011Result.java
UTF-8
315
1.804688
2
[]
no_license
package org.cen.cup.cup2011.device.gripper2011; import org.cen.robot.device.RobotDeviceResult; import org.cen.robot.device.request.IRobotDeviceRequest; public abstract class Gripper2011Result extends RobotDeviceResult { public Gripper2011Result(IRobotDeviceRequest request) { super(request); } }
true
aa8523b3052510ae0271e59c5bbf4da9b60b6c2b
Java
MDeiml/LD39
/core/src/com/mdeiml/ld39/LD39Game.java
UTF-8
4,749
2.375
2
[]
no_license
package com.mdeiml.ld39; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.Box2D; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.physics.box2d.World; import java.util.ArrayList; public class LD39Game extends ApplicationAdapter { public static final float TILE_SIZE = 48; public static final float UPDATE_DELTA = 1/60f; private SpriteBatch batch; private OrthographicCamera camera; private ArrayList<Entity> entities; private Robot player; // Box2d private float unprocessed; private World world; private Box2DDebugRenderer debugRenderer; public Texture sprites; private TextureRegion batteryFull; private TextureRegion batteryEmpty; @Override public void create () { batch = new SpriteBatch(); camera = new OrthographicCamera(Gdx.graphics.getWidth() / TILE_SIZE, Gdx.graphics.getHeight() / TILE_SIZE); entities = new ArrayList<Entity>(); Box2D.init(); world = new World(new Vector2(0, 0), true); world.setContactListener(new ContactListener() { public void beginContact(Contact contact) { Entity a = (Entity)contact.getFixtureA().getBody().getUserData(); Entity b = (Entity)contact.getFixtureB().getBody().getUserData(); a.addTouchingEntity(b); b.addTouchingEntity(a); } public void endContact(Contact contact) { Entity a = (Entity)contact.getFixtureA().getBody().getUserData(); Entity b = (Entity)contact.getFixtureB().getBody().getUserData(); a.removeTouchingEntity(b); b.removeTouchingEntity(a); } public void postSolve(Contact contact, ContactImpulse impulse) {} public void preSolve(Contact contact, Manifold manifold) { if(!contact.getFixtureA().isSensor() && !contact.getFixtureB().isSensor() && contact.getFixtureA().getBody().getType() == BodyDef.BodyType.DynamicBody && contact.getFixtureB().getBody().getType() == BodyDef.BodyType.DynamicBody) { contact.getFixtureA().getBody().setLinearVelocity(new Vector2(0,0)); contact.getFixtureB().getBody().setLinearVelocity(new Vector2(0,0)); } } }); debugRenderer = new Box2DDebugRenderer(); sprites = new Texture("sprites.png"); batteryFull = new TextureRegion(sprites, 32, 0, 6, 64); batteryEmpty = new TextureRegion(sprites, 38, 0, 6, 64); Texture testTex = new Texture("badlogic.jpg"); player = new Robot(new Vector2(0,0), this, new TextureRegion(testTex)); new StandardEnemy(new Vector2(-3, 0), this); } @Override public void render () { // Update unprocessed += Gdx.graphics.getDeltaTime(); while(unprocessed >= UPDATE_DELTA) { int size = entities.size(); for(int i = 0; i < size; i++) { entities.get(i).update(); } for(int i = 0; i < entities.size(); i++) { if(entities.get(i).isDead()) { world.destroyBody(entities.get(i).getBody()); entities.remove(i); i--; } } world.step(UPDATE_DELTA, 6, 2); unprocessed -= UPDATE_DELTA; } // Render Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); debugRenderer.render(world, camera.combined); batch.setProjectionMatrix(camera.combined); batch.begin(); for(int i = entities.size()-1; i >= 0; i--) { entities.get(i).render(batch); } batch.draw(batteryEmpty, 0.5f-Gdx.graphics.getWidth()/TILE_SIZE/2, 1-Gdx.graphics.getHeight()/TILE_SIZE/2, 6/16f, 64/16f); float energy = player.getEnergy()/100; int batHeight = (int)(energy * batteryFull.getRegionHeight()); batch.draw( new TextureRegion(batteryFull, 0, batteryFull.getRegionHeight()-batHeight, 6, batHeight), 0.5f-Gdx.graphics.getWidth()/TILE_SIZE/2, 1-Gdx.graphics.getHeight()/TILE_SIZE/2, 6/16f, batHeight/16f ); batch.end(); } public World getWorld() { return world; } public void addEntity(Entity e) { entities.add(e); } public void wakeAll() { for(Entity e : entities) { e.getBody().setAwake(true); } } public Vector2 getMousePos() { Vector2 pos = new Vector2(Gdx.input.getX()-Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2-Gdx.input.getY()); pos.scl(1/TILE_SIZE); return pos; } public Robot getPlayer() { return player; } }
true
0e662d7cfbcbf28c73a58b63a4411b27e4140e43
Java
billydevInGitHub/33808
/33808Exp190/src/main/java/billydev/Test.java
UTF-8
533
2.109375
2
[]
no_license
package billydev; import reactor.core.publisher.Flux; import reactor.core.publisher.Hooks; import reactor.core.scheduler.Schedulers; import reactor.tools.agent.ReactorDebugAgent; public class Test { public static void main(String[] args) { ReactorDebugAgent.init(); Flux.range(0, 1) .single() .subscribe(System.out::println); Flux.range(0, 5) .single() // <-- Aha! .subscribeOn(Schedulers.parallel()) .block(); } }
true
a4b9987bf70f200accf48bfcb4fb781920c10cbf
Java
fatihaBenalia/orphelinat
/src/java/bean/Mere.java
UTF-8
1,673
2.125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bean; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Temporal; /** * * @author User */ @Entity public class Mere extends Personne { @OneToOne(mappedBy = "mere") private EtatSanteMere etatSanteMere; @OneToOne(mappedBy = "mere") private EtatEthique etatEthique; @OneToOne(mappedBy = "mere") private Dossier dossier; @Temporal(javax.persistence.TemporalType.DATE) private Date dateDeces; private String raisonDeces; @Temporal(javax.persistence.TemporalType.DATE) private Date dateNaissance; public Dossier getDossier() { return dossier; } public void setDossier(Dossier dossier) { this.dossier = dossier; } public Date getDateDeces() { return dateDeces; } public void setDateDeces(Date dateDeces) { this.dateDeces = dateDeces; } public String getRaisonDeces() { return raisonDeces; } public void setRaisonDeces(String raisonDeces) { this.raisonDeces = raisonDeces; } public Date getDateNaissance() { return dateNaissance; } public void setDateNaissance(Date dateNaissance) { this.dateNaissance = dateNaissance; } }
true
1963ac582cdffb9dac9212decf1db1e6121f406f
Java
HugoNikanor/cardboardGathering
/src/gamePieces/CardCollection.java
UTF-8
11,720
2.703125
3
[]
no_license
package gamePieces; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Random; import chat.ChatStream; import chat.MessageInfo; import database.CardChooser; import database.JSONCardReader; import exceptions.CardNotFoundException; import graphicsObjects.CardSelectionPane; import graphicsObjects.CardStackPane; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.transform.Rotate; import javafx.stage.Stage; /** * A collection of cards * Can hold about any number of cards * * TODO replace much if it's graphics with fxml files */ public class CardCollection implements Iterable<Card> { /** * The different types of collections */ public static enum CollectionTypes { DECK, GRAVEYARD, HAND, BATTLEFIELD, BATTLEFILED, OTHER } private Button getFromDeckBtn; private Button shuffleBtn; private CardStackPane cardStack; private Pane graphicPane; private ObjectProperty<Card> observableCard; private IntegerProperty observableCount; private List<Card> cards; /** The type of collection this is */ private CollectionTypes collection; /** * Create an empty collection * @param collection the type of collection this is */ public CardCollection( CollectionTypes collection ) { this.collection = collection; cards = Collections.synchronizedList(new ArrayList<Card>()); observableCard = new SimpleObjectProperty<Card>(); } /** * Create a collection with cards in it to start * @param collection the type of collection this is * @param jCardReader where the cards should be read from * @param cardIdCounter what id the next created card should have, make sure to incarment every time it is used * @param cardList String[] sent to the cardChooser to allow it to be read as a bad iterrator */ public CardCollection( CollectionTypes collection, JSONCardReader jCardReader, CardIdCounter counter, String[] cardList ) { this.collection = collection; cards = Collections.synchronizedList(new ArrayList<Card>()); try { CardChooser cardChooser = new CardChooser( cardList ); // Get all cards from the jCardChooser while( cardChooser.hasNext() ) { this.add( jCardReader.get( cardChooser.next(), counter.getCounterAndIncrament() ) ); } } catch (CardNotFoundException e) { e.printStackTrace(); } //TODO should this be done here? this.shuffleCards(); observableCard = new SimpleObjectProperty<Card>(); } public void addAll( Collection<Card> collection ) { cards.addAll( collection ); } public Pane getGraphics( boolean isLocal ) { if( graphicPane == null ) { graphicPane = new Pane(); cardStack = new CardStackPane( collection, Card.WIDTH, Card.HEIGHT ); if( isLocal ) { HBox buttonCont = new HBox(); buttonCont.getTransforms().add( new Rotate(90, 0, 0, 0, Rotate.Z_AXIS) ); buttonCont.setTranslateX( Card.WIDTH + 40 ); buttonCont.setMinHeight( 30 ); buttonCont.setMaxHeight( 30 ); buttonCont.setMinWidth( Card.HEIGHT ); buttonCont.setPrefHeight( 40 ); buttonCont.setPrefWidth( 100 ); getFromDeckBtn = new Button(); getFromDeckBtn.setText( "Get Card" ); getFromDeckBtn.setOnAction( new BtnHandler() ); getFromDeckBtn.setMaxSize( Double.MAX_VALUE, Double.MAX_VALUE ); shuffleBtn = new Button( "Shuffle" ); shuffleBtn.setOnAction( e -> { ChatStream.print( "Shuffling cards", MessageInfo.SYSTEM ); shuffleCards(); } ); shuffleBtn.setMaxSize( Double.MAX_VALUE, Double.MAX_VALUE ); HBox.setHgrow( getFromDeckBtn, Priority.ALWAYS ); HBox.setHgrow( shuffleBtn, Priority.ALWAYS ); cardStack.setOnMouseClicked( new DeckAreaHandler() ); buttonCont.getChildren().addAll( getFromDeckBtn, shuffleBtn ); graphicPane.getChildren().add( buttonCont ); } else { graphicPane.setRotate( 180d ); } graphicPane.getChildren().add( cardStack ); observableCount = new SimpleIntegerProperty(); observableCount.set( this.size() ); observableCount.addListener( (ov, oldVal, newVal) -> { System.out.println( "something changed" ); cardStack.setText( newVal.toString() ); } ); updateGraphicText(); } return graphicPane; } /** * This sets a null card to make sure that the value changed * catch a null pointer exception in it's listener */ private class BtnHandler implements EventHandler<ActionEvent> { @Override public void handle( ActionEvent e ) { // thread started because the cardSelectionPane locks up the thread it's // run on. And this is the main JavaFX thread new Thread(() -> { try { observableCard.set( null ); observableCard.set( CardSelectionPane.getCard( CardCollection.this, (Stage)graphicPane.getScene().getWindow() )); } catch( CardNotFoundException ex ) { //ex.printStackTrace(); ChatStream.print( "No cards in collection", MessageInfo.SYSTEM ); } }).start(); } } /** * This sets a null card to make sure that the value changed * catch a null pointer exception in it's listener */ private class DeckAreaHandler implements EventHandler<MouseEvent> { @Override public void handle( MouseEvent e ) { System.out.println( "deck area pressed" ); try { // The card should be removed from the collection when it's taken from here observableCard.set( null ); observableCard.set( getNextCard() ); } catch( CardNotFoundException ex ) { ChatStream.print( "No cards in collection", MessageInfo.SYSTEM ); } } } private void updateGraphicText() { if( cardStack != null ) { cardStack.setText( Integer.toString(cards.size()) ); } } @Override public Iterator<Card> iterator() { return cards.iterator(); } public int size() { return cards.size(); } private Card get( int index ) { return cards.get( index ); } private void set( int index, Card card ) { cards.set( index, card ); } private Card remove( int index ) { Card removedCard = cards.remove( index ); updateGraphicText(); return removedCard; } private boolean remove( Card card ) { boolean success = cards.remove( card ); updateGraphicText(); return success; } public int indexOf( Card card ) { return cards.indexOf( card ); } public boolean add( Card card ) { boolean success = cards.add( card ); updateGraphicText(); return success; } public void add( int index, Card card ) { cards.add( index, card ); updateGraphicText(); } /** * Places the cards in the collection in a random order */ public void shuffleCards() { Random rand = new Random(); Card tempCard; int cardIndex; int cardCount = this.size(); for(int i = 0; i < cardCount; i++) { cardIndex = rand.nextInt(this.size()); tempCard = this.get(cardIndex); this.set(cardIndex, this.get(i)); this.set(i, tempCard); } } /** * Observable card may be null, since it flashes past null to * make sure that the card is updated, <br> * This is a problem when trying to draw the same card twice * in a row. */ public ObjectProperty<Card> getObservableCardProperty() { return observableCard; } /** * Take (get and remove) the next card in the collection * @return the next card in the collection * @throws CardNotFoundException if there are no more cards in the collection * @see getNextCard */ public Card takeNextCard() throws CardNotFoundException { if(this.size() == 0) { throw new CardNotFoundException("No cards in collection"); } Card returnCard = this.get(this.size() - 1); this.remove(this.size() - 1); return returnCard; } /** * Take (get and remove) the card at cardIndex * @return the card it index cardIndex * @param cardIndex position of card to take * @throws CardNotFoundException if there is no card with that index * @see getCard */ public Card takeCard(int cardIndex) throws CardNotFoundException { Card returnCard; try { returnCard = this.get(cardIndex); } catch(IndexOutOfBoundsException e) { throw new CardNotFoundException("Index out of bounds"); } this.remove(cardIndex); return returnCard; } /** * Take (get and remove) the chosen card * @return The card given as indata, but it is also removed from the collection * @param card what card to take * @throws CardNotFoundException if the card is not in the collection */ public Card takeCard(Card card) throws CardNotFoundException { int cardIndex = this.indexOf(card); // ArrayList.indexOf returns '-1' if there is no such element if( cardIndex == -1 ) { throw new CardNotFoundException("No such card in collection"); } Card returnCard = this.get(cardIndex); this.remove(this.indexOf(card)); return returnCard; } /** * Take (get and remove) the card with the set cardId * @return the card with the choosen cardId * @param cardId the id of the card, note that the id is gotten by Card.getCardId() and not Card.getId() * @throws CardNotFoundException if there is no card with that id * @see getCard */ public Card takeCard( long cardId ) throws CardNotFoundException { for( Card temp : this ) { if( Objects.equals( temp.getCardId(), cardId ) ) { this.remove( temp ); return temp; } } throw new CardNotFoundException("No card with that id " + cardId); } /** * @return The next card in the collection * @throws CardNotFoundException if there are no more cards in the collection * @see takeNextCard */ public Card getNextCard() throws CardNotFoundException { if(this.size() == 0) { throw new CardNotFoundException("No cards in collection"); } Card returnCard = this.get(this.size() - 1); return returnCard; } /** * @return the card it index cardIndex * @param cardIndex position of card to take * @throws CardNotFoundException if there is no card with that index * @see getCard */ public Card getCard(int cardIndex) throws CardNotFoundException { if( cardIndex < 0 || cardIndex >= this.size() ) { throw new CardNotFoundException("Index out of bounds"); } Card returnCard = this.get(cardIndex); return returnCard; } /** * Checks if the card is present in the collection * @return the card entered * @param card card to check if it's in the collection * @throws CardNotFoundException if the card is not in the collection * @see takeCard */ public Card getCard( Card card ) throws CardNotFoundException { int cardIndex = this.indexOf(card); if( cardIndex == -1 ) { throw new CardNotFoundException("No such card in collection"); } Card returnCard = this.get(cardIndex); return returnCard; } /** * @return the card with the choosen cardId * @param cardId the id of the card, note that the id is gotten by Card.getCardId() and not Card.getId() * @throws CardNotFoundException if there is no card with that id * @see takeCard */ public synchronized Card getCard( long cardId ) throws CardNotFoundException { for( Card temp : this ) { if( Objects.equals( temp.getCardId(), cardId ) ) { return temp; } } throw new CardNotFoundException("No card with that id " + cardId); } /** * @return the collection */ public CollectionTypes getCollection() { return collection; } public List<Card> getAllCards() { return cards; } }
true
0da0e3414690a93db56136b10585a8e228783b6f
Java
shashikiranrp/load_ini
/src/main/java/org/kelvin/load_config/App.java
UTF-8
440
2.296875
2
[ "Apache-2.0" ]
permissive
package org.kelvin.load_config; /** * @author <a href="mailto:[email protected]">Shashikiran</a> */ public class App { public static void main(String[] args) { final String filePath = 0 == args.length ? "/Users/shasrp/test.ini" : args[0]; AppConfig config = AppConfig.load(filePath, false, "", "ubuntu", "production", "final"); System.out.println(config.get("one.f4")); System.out.println(config); } }
true
7083cca78908b56a110eda4408741b27edd789f3
Java
lancelee98/AttendanceSystem
/src/main/java/cn/stylefeng/guns/modular/classroom/controller/ClassroomController.java
UTF-8
2,892
2.109375
2
[ "Apache-2.0" ]
permissive
package cn.stylefeng.guns.modular.classroom.controller; import cn.stylefeng.roses.core.base.controller.BaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import cn.stylefeng.guns.core.log.LogObjectHolder; import org.springframework.web.bind.annotation.RequestParam; import cn.stylefeng.guns.modular.system.model.Classroom; import cn.stylefeng.guns.modular.classroom.service.IClassroomService; /** * 教室管理控制器 * * @author fengshuonan * @Date 2019-03-02 14:44:37 */ @Controller @RequestMapping("/classroom") public class ClassroomController extends BaseController { private String PREFIX = "/classroom/classroom/"; @Autowired private IClassroomService classroomService; /** * 跳转到教室管理首页 */ @RequestMapping("") public String index() { return PREFIX + "classroom.html"; } /** * 跳转到添加教室管理 */ @RequestMapping("/classroom_add") public String classroomAdd() { return PREFIX + "classroom_add.html"; } /** * 跳转到修改教室管理 */ @RequestMapping("/classroom_update/{classroomId}") public String classroomUpdate(@PathVariable Integer classroomId, Model model) { Classroom classroom = classroomService.selectById(classroomId); model.addAttribute("item",classroom); LogObjectHolder.me().set(classroom); return PREFIX + "classroom_edit.html"; } /** * 获取教室管理列表 */ @RequestMapping(value = "/list") @ResponseBody public Object list(String condition) { return classroomService.selectList(null); } /** * 新增教室管理 */ @RequestMapping(value = "/add") @ResponseBody public Object add(Classroom classroom) { classroomService.insert(classroom); return SUCCESS_TIP; } /** * 删除教室管理 */ @RequestMapping(value = "/delete") @ResponseBody public Object delete(@RequestParam Integer classroomId) { classroomService.deleteById(classroomId); return SUCCESS_TIP; } /** * 修改教室管理 */ @RequestMapping(value = "/update") @ResponseBody public Object update(Classroom classroom) { classroomService.updateById(classroom); return SUCCESS_TIP; } /** * 教室管理详情 */ @RequestMapping(value = "/detail/{classroomId}") @ResponseBody public Object detail(@PathVariable("classroomId") Integer classroomId) { return classroomService.selectById(classroomId); } }
true
6ca9512810e08b0b879f74f124a36842c67000fd
Java
adafruit/Bluefruit_LE_Connect_Android
/app/src/main/java/com/adafruit/bluefruit/le/connect/app/UartInterfaceActivity.java
UTF-8
6,070
2.21875
2
[ "MIT" ]
permissive
package com.adafruit.bluefruit.le.connect.app; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.adafruit.bluefruit.le.connect.ble.BleManager; import com.adafruit.bluefruit.le.connect.ble.BleUtils; import java.nio.charset.Charset; import java.util.Arrays; public class UartInterfaceActivity extends AppCompatActivity implements BleManager.BleManagerListener { // Log private final static String TAG = UartInterfaceActivity.class.getSimpleName(); // Service Constants public static final String UUID_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"; public static final String UUID_RX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"; public static final String UUID_TX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"; public static final String UUID_DFU = "00001530-1212-EFDE-1523-785FEABCD123"; public static final int kTxMaxCharacters = 20; // Data protected BleManager mBleManager; protected BluetoothGattService mUartService; private boolean isRxNotificationEnabled = false; // region Send Data to UART protected void sendData(String text) { final byte[] value = text.getBytes(Charset.forName("UTF-8")); sendData(value); } protected void sendData(byte[] data) { if (mUartService != null) { // Split the value into chunks (UART service has a maximum number of characters that can be written ) for (int i = 0; i < data.length; i += kTxMaxCharacters) { final byte[] chunk = Arrays.copyOfRange(data, i, Math.min(i + kTxMaxCharacters, data.length)); mBleManager.writeService(mUartService, UUID_TX, chunk); } } else { Log.w(TAG, "Uart Service not discovered. Unable to send data"); } } // Send data to UART and add a byte with a custom CRC protected void sendDataWithCRC(byte[] data) { // Calculate checksum byte checksum = 0; for (byte aData : data) { checksum += aData; } checksum = (byte) (~checksum); // Invert // Add crc to data byte dataCrc[] = new byte[data.length + 1]; System.arraycopy(data, 0, dataCrc, 0, data.length); dataCrc[data.length] = checksum; // Send it Log.d(TAG, "Send to UART: " + BleUtils.bytesToHexWithSpaces(dataCrc)); sendData(dataCrc); } // endregion // region SendDataWithCompletionHandler protected interface SendDataCompletionHandler { void sendDataResponse(String data); } final private Handler sendDataTimeoutHandler = new Handler(); private Runnable sendDataRunnable = null; private SendDataCompletionHandler sendDataCompletionHandler = null; protected void sendData(byte[] data, SendDataCompletionHandler completionHandler) { if (completionHandler == null) { sendData(data); return; } if (!isRxNotificationEnabled) { Log.w(TAG, "sendData warning: RX notification not enabled. completionHandler will not be executed"); } if (sendDataRunnable != null || sendDataCompletionHandler != null) { Log.d(TAG, "sendData error: waiting for a previous response"); return; } Log.d(TAG, "sendData"); sendDataCompletionHandler = completionHandler; sendDataRunnable = new Runnable() { @Override public void run() { Log.d(TAG, "sendData timeout"); final SendDataCompletionHandler dataCompletionHandler = sendDataCompletionHandler; UartInterfaceActivity.this.sendDataRunnable = null; UartInterfaceActivity.this.sendDataCompletionHandler = null; dataCompletionHandler.sendDataResponse(null); } }; sendDataTimeoutHandler.postDelayed(sendDataRunnable, 2 * 1000); sendData(data); } protected boolean isWaitingForSendDataResponse() { return sendDataRunnable != null; } // endregion // region BleManagerListener (used to implement sendData with completionHandler) @Override public void onConnected() { } @Override public void onConnecting() { } @Override public void onDisconnected() { } @Override public void onServicesDiscovered() { mUartService = mBleManager.getGattService(UUID_SERVICE); } protected void enableRxNotifications() { isRxNotificationEnabled = true; mBleManager.enableNotification(mUartService, UUID_RX, true); } @Override public void onDataAvailable(BluetoothGattCharacteristic characteristic) { // Check if there is a pending sendDataRunnable if (sendDataRunnable != null) { if (characteristic.getService().getUuid().toString().equalsIgnoreCase(UUID_SERVICE)) { if (characteristic.getUuid().toString().equalsIgnoreCase(UUID_RX)) { Log.d(TAG, "sendData received data"); sendDataTimeoutHandler.removeCallbacks(sendDataRunnable); sendDataRunnable = null; if (sendDataCompletionHandler != null) { final byte[] bytes = characteristic.getValue(); final String data = new String(bytes, Charset.forName("UTF-8")); final SendDataCompletionHandler dataCompletionHandler = sendDataCompletionHandler; sendDataCompletionHandler = null; dataCompletionHandler.sendDataResponse(data); } } } } } @Override public void onDataAvailable(BluetoothGattDescriptor descriptor) { } @Override public void onReadRemoteRssi(int rssi) { } // endregion }
true
458da4f60266b83d385ed8209f17e57eabb4b03a
Java
flbrino/pentaho-platform-plugin-reporting
/src/org/pentaho/reporting/platform/plugin/CacheManagerEndpoint.java
UTF-8
2,006
1.632813
2
[]
no_license
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License, version 2 as published by the Free Software * Foundation. * * You should have received a copy of the GNU General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/gpl-2.0.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * * Copyright 2006 - 2016 Pentaho Corporation. All rights reserved. */ package org.pentaho.reporting.platform.plugin; import org.pentaho.platform.api.engine.ICacheManager; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.reporting.engine.classic.core.cache.DataCacheFactory; import org.pentaho.reporting.platform.plugin.cache.IPluginCacheManager; import org.pentaho.reporting.platform.plugin.cache.IReportContentCache; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path( "/reporting/api/cache" ) public class CacheManagerEndpoint { @POST @Path( "clear" ) public Response clear() { try { final IPluginCacheManager iPluginCacheManager = PentahoSystem.get( IPluginCacheManager.class ); final IReportContentCache cache = iPluginCacheManager.getCache(); cache.cleanup(); final ICacheManager cacheManager = PentahoSystem.get( ICacheManager.class ); cacheManager.clearRegionCache( "report-dataset-cache" ); cacheManager.clearRegionCache( "report-output-handlers" ); DataCacheFactory.getCache().getCacheManager().clearAll(); return Response.ok().build(); } catch ( final Exception e ) { return Response.serverError().build(); } } }
true
499e572a459bc9997c2aa1faed37dfe789d640dd
Java
skyhuge/code4j
/src/main/java/io/pretty/spring/PropertyBindingPostProcessor.java
UTF-8
7,119
2.15625
2
[ "Apache-2.0" ]
permissive
package io.pretty.spring; import org.springframework.beans.BeanInstantiationException; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySources; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @Component public class PropertyBindingPostProcessor implements BeanPostProcessor, BeanFactoryAware,InitializingBean { private BeanFactory beanFactory; private PropertySources propertySources; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void afterPropertiesSet() throws Exception { if (this.propertySources == null) { this.propertySources = deducePropertySources(); } } private PropertySources deducePropertySources() { PropertySourcesPlaceholderConfigurer configurer = getSinglePropertySourcesPlaceholderConfigurer(); if (null != configurer){ return new FlatPropertySources(configurer.getAppliedPropertySources()); } return new MutablePropertySources(); } private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer() { // Take care not to cause early instantiation of all FactoryBeans if (this.beanFactory instanceof ListableBeanFactory) { ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory; Map<String, PropertySourcesPlaceholderConfigurer> beans = listableBeanFactory .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); if (beans.size() == 1) { return beans.values().iterator().next(); } if (beans.size() > 1) { System.out.println("Multiple PropertySourcesPlaceholderConfigurer " + "beans registered " + beans.keySet() + ", falling back to Environment"); } } return null; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { AutoConfigureProperties annotation = AnnotationUtils .findAnnotation(bean.getClass(), AutoConfigureProperties.class); if (annotation != null) { String prefix = annotation.prefix(); Map<String,String> map = getMapping(prefix); DataBinder<Object> dataBinder = new DataBinder<>(bean,prefix, map); try { dataBinder.doBind(); } catch (Exception e) { throw new BeanInstantiationException(bean.getClass(),e.getMessage()); } } return bean; } @SuppressWarnings("unchecked") private Map<String,String> getMapping(String prefix){ PropertySources sources = propertySources; FlatPropertySources ps = (FlatPropertySources) sources; Iterator<PropertySource<?>> iterator = ps.iterator(); Map<String,String> m = new HashMap<>(); while (iterator.hasNext()){ PropertySource<?> next = iterator.next(); Object source = next.getSource(); Map<String,String> map; if (source instanceof Map){ map = (Map<String,String>) source; for (String s : map.keySet()) { if (s.startsWith(prefix)){ m.put(s, map.get(s)); } } } } return m; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } private static class FlatPropertySources implements PropertySources { private PropertySources propertySources; FlatPropertySources(PropertySources propertySources) { this.propertySources = propertySources; } @Override public Iterator<PropertySource<?>> iterator() { MutablePropertySources result = getFlattened(); return result.iterator(); } @Override public boolean contains(String name) { return get(name) != null; } @Override public PropertySource<?> get(String name) { return getFlattened().get(name); } private MutablePropertySources getFlattened() { MutablePropertySources result = new MutablePropertySources(); for (PropertySource<?> propertySource : this.propertySources) { flattenPropertySources(propertySource, result); } return result; } private void flattenPropertySources(PropertySource<?> propertySource, MutablePropertySources result) { Object source = propertySource.getSource(); if (source instanceof ConfigurableEnvironment) { ConfigurableEnvironment environment = (ConfigurableEnvironment) source; for (PropertySource<?> childSource : environment.getPropertySources()) { flattenPropertySources(childSource, result); } } else { result.addLast(propertySource); } } } class DataBinder<T>{ private T target; private String prefix; private Map<String, String> map; public DataBinder(T target, String prefix, Map<String, String> map){ this.target = target; this.prefix = prefix; this.map = map; } private void doBind() throws Exception{ Method[] methods = target.getClass().getDeclaredMethods(); for (Method method : methods) { String name = method.getName(); if (name.startsWith("set")) {// javabean discriptor String s = name.substring(3, name.length()); for (Map.Entry<String, String> entry : map.entrySet()) { if (entry.getKey().toLowerCase().contains(s.toLowerCase())) { method.invoke(target,entry.getValue()); break; } } } } } } }
true
9032ffce23ad09787b624ae1c5500e965dc84633
Java
anhtuan2461996/C1219H1_Dinh_Vu_Anh_Tuan
/module2/src/B1_NgonNguJava/ThucHanh/ThucHanh_SoNguyenToBe100.java
UTF-8
397
3.015625
3
[]
no_license
package B1_NgonNguJava.ThucHanh; public class ThucHanh_SoNguyenToBe100 { public static void main(String[] args) { for (int i = 2;i<100;i++){ int dem =0; for (int j=2;j<i;j++){ if (i%j==0){ dem+=1; } } if (dem<1){ System.out.println(i); } } } }
true
c094138b0ea24287ffba7b3da91edeb187b2b075
Java
Tom9Polaris/June22
/app/src/main/java/com/example/administrator/myapplication001/MainActivity.java
UTF-8
2,130
2.296875
2
[]
no_license
package com.example.administrator.myapplication001; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { android.support.v7.app.ActionBar actionBar; private Button button1; private Button button2; private Button button3; private Button button4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionBar = getSupportActionBar(); button1 = (Button)findViewById(R.id.Button1); button2 = (Button)findViewById(R.id.Button2); button3 = (Button)findViewById(R.id.Button3); button4 = (Button)findViewById(R.id.Button4); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //actionBar.show(); showActionBar(view); } }); button2.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ //actionBar.hide(); hideActionBar(view); } }); button3.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intent = new Intent(MainActivity.this,MainActivity2.class); startActivity(intent); } }); button4.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intent = new Intent(MainActivity.this,MainActivity3.class); startActivity(intent); } }); } public void showActionBar(View source){ actionBar.show(); } public void hideActionBar(View source){ actionBar.hide(); } }
true
e3fbb5a270f16d140b0b69a8304449c92a7bad09
Java
alizhan1/Java_HW3
/src/main/java/space/harbour/java/hw3/MyHashMap.java
UTF-8
3,355
3.421875
3
[]
no_license
package space.harbour.java.hw3; import space.harbour.java.hw3.Element; import java.util.*; public class MyHashMap<K, V> { private final Integer bucket_size = 32; private List<Element> bucket[] = new ArrayList[bucket_size]; public MyHashMap() { for (int i = 0; i < bucket_size; i++) { bucket[i] = new ArrayList<Element>(); } } private int hashify(K key) { int hash = key.hashCode(); if (hash > 31) { hash = hash >> 27; } else if (hash < 0) { hash = -1*(hash) >> 27; } return hash; } public int size() { Integer size = 0; for (int i = 0; i < bucket_size; i++) { size += bucket[i].size(); } return size; } public void put(K key, V value) { int hash = hashify(key); Element element = new Element<K, V>(key, value); bucket[hash].add(element); } public void putAll(Map<K, V> m) { Set<K> keys = m.keySet(); for (K key : keys) { Element element = new Element<K, V>(key, m.get(key)); bucket[hashify(key)].add(element); } } public V remove(K key) { for (Element e : bucket[hashify(key)]) { if (e.key == key) { bucket[hashify(key)].remove(e); return (V) e.value; } } return null; } public V get(K key) { for (Element e : bucket[hashify(key)]) { if (e.key == key) { return (V) e.value; } } return null; } public boolean containsKey(K key) { for (Element e : bucket[hashify(key)]) { if (e.key == key) { return true; } } return false; } public boolean containsValue(V value) { for (int i = 0; i < bucket_size; i++) { for (Element e : bucket[i]) { if (e.value == value) { return true; } } } return false; } public boolean isEmpty() { for (int i = 0; i < bucket_size; i++) { if (bucket[i].size() > 0) { return false; } } return true; } public void clear() { for (int i = 0; i < bucket_size; i++) { bucket[i].clear(); } } public Set<K> keySet() { Set<K> keys = new HashSet<>(); for (int i = 0; i < bucket_size; i++) { for (Element e : bucket[i]) { keys.add((K) e.key); } } return keys; } public boolean replace(K key, V value) { for (int i = 0; i < bucket[hashify(key)].size(); i++) { if (bucket[hashify(key)].get(i).key == key && bucket[hashify(key)].get(i).value != null) { Element element = new Element<K, V>(key, value); bucket[hashify(key)].set(i, element); return true; } } return false; } public List<V> values() { List<V> values = new ArrayList<>(); for (int i = 0; i < bucket_size; i++) { for (Element e : bucket[i]) { values.add((V) e.value); } } return values; } }
true
a6e0e00c425e5b3b9496dbea324b621fdd1dcaaa
Java
onlyas/mybatis-generator-demo
/src/main/java/com/onlyas/app/config/LocalDateFormatConfig.java
UTF-8
1,153
2.25
2
[ "MIT" ]
permissive
package com.onlyas.app.config; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; @Configuration public class LocalDateFormatConfig { @Bean public Module jsonMapperJava8DateTimeModule() { SimpleModule module = new SimpleModule(); module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); module.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); return module; } }
true
0b6e7aec3ab951dbb845af3b868c6f4cd9f151c1
Java
moutainhigh/chongdao_app_user_client
/src/main/java/com/chongdao/client/entitys/coupon/CpnUser.java
UTF-8
2,056
1.9375
2
[]
no_license
package com.chongdao.client.entitys.coupon; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * @author fenglong * @date 2019-06-18 15:43 * 用户领取优惠券表类 */ @Entity @Getter @Setter @Table(name = "cpn_user") @DynamicUpdate public class CpnUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer userId; //用户ID private Integer cpnId; //优惠券ID private String shopId; private String cpnCode; //优惠券编码;可选 private String cpnBatchId; //优惠券批次ID private Integer cpnType; //优惠券类型 1现金券 2满减券 3折扣券 4店铺满减 5 公益券 private BigDecimal cpnValue; //面值 XX元/满XX元/XX折 private Integer cpnScopeType; //适用范围类型 1全场通用 2限品类 3限商品 private Integer userCpnState; //用户优惠券状态 0未使用 1已使用 2已过期 private Integer count; //优惠券数量 private Date useTime; //使用时间 private String useDesc; //使用说明 @JsonFormat(pattern = "yyyy-MM-dd") private Date validityStartDate; //有效期开始时间 @JsonFormat(pattern = "yyyy-MM-dd") private Date validityEndDate; //有效期结束时间 private Date gainDate; //领取时间 private String gainDesc; //获取说明 private Date createDate; //创建时间 private Date updateDate; //更新时间 private Integer isDelete; //是否删除 0否 1是 private Integer ruleType; @Transient private Integer enabled = 0; //是否可用 0否 1是 @Transient private Integer receive = 0; //是否领取 0否 1是 }
true
796f0d193319004fff9d5f92bc2bfd2104684e7d
Java
davidotb91/apiDeportes
/Desarrollo/sportManagerTest/Seguimiento/src/Entity/SeguimientoTesis.java
UTF-8
3,429
1.914063
2
[]
no_license
package Entity; // Generated 16/01/2015 11:00:47 PM by Hibernate Tools 3.4.0.CR1 import java.util.Date; import javax.persistence.Transient; import Entity.Docente; import Entity.Tema; /** * Seguimiento generated by hbm2java */ public class SeguimientoTesis implements java.io.Serializable { private int segId; private Tema tema; private Docente docente; private Date segFecha; private String segDocumento; private String segPathDocumento; private String segObservaciones; private Integer audUsuModi; private Integer audUsuCrea; private Date audFechaCrea; private Date audFechaModi; public SeguimientoTesis() { } public SeguimientoTesis(int segId, Tema tema, Docente docente, Date segFecha, String segDocumento, String segPathDocumento, String segObservaciones, Integer audUsuModi, Integer audUsuCrea, Date audFechaCrea, Date audFechaModi) { this.segId = segId; this.tema = tema; this.docente = docente; this.segFecha = segFecha; this.segDocumento = segDocumento; this.segPathDocumento = segPathDocumento; this.segObservaciones = segObservaciones; this.audUsuModi = audUsuModi; this.audUsuCrea = audUsuCrea; this.audFechaCrea = audFechaCrea; this.audFechaModi = audFechaModi; } @Transient private Integer position; public Integer getPosition() { return position; } public void setPosition(Integer position) { this.position = position; } public int getSegId() { return this.segId; } public void setSegId(int segId) { this.segId = segId; } public Tema getTema() { return this.tema; } public void setTema(Tema tema) { this.tema = tema; } public Docente getDocente() { return this.docente; } public void setDocente(Docente docente) { this.docente = docente; } public Date getSegFecha() { return this.segFecha; } public void setSegFecha(Date segFecha) { this.segFecha = segFecha; } public String getSegDocumento() { return this.segDocumento; } public void setSegDocumento(String segDocumento) { this.segDocumento = segDocumento; } public String getSegPathDocumento() { return this.segPathDocumento; } public void setSegPathDocumento(String segPathDocumento) { this.segPathDocumento = segPathDocumento; } public String getSegObservaciones() { return this.segObservaciones; } public void setSegObservaciones(String segObservaciones) { this.segObservaciones = segObservaciones; } public Integer getAudUsuModi() { return this.audUsuModi; } public void setAudUsuModi(Integer audUsuModi) { this.audUsuModi = audUsuModi; } public Integer getAudUsuCrea() { return this.audUsuCrea; } public void setAudUsuCrea(Integer audUsuCrea) { this.audUsuCrea = audUsuCrea; } public Date getAudFechaCrea() { return this.audFechaCrea; } public void setAudFechaCrea(Date audFechaCrea) { this.audFechaCrea = audFechaCrea; } public Date getAudFechaModi() { return this.audFechaModi; } public void setAudFechaModi(Date audFechaModi) { this.audFechaModi = audFechaModi; } @Override public String toString() { return this.segDocumento; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof SeguimientoTesis)) { return false; } if (obj == this) { return true; } return this.segId == ((SeguimientoTesis) obj).getSegId(); } }
true
0704a3c10e53d07d7c78e46f112815f586cb2504
Java
nlflint/CSC143
/Assignment8/src/Tokenizer/Tokens/OpenParenToken.java
UTF-8
120
1.945313
2
[]
no_license
package Tokenizer.Tokens; /** * Reprsents the open parentheses: "(" */ public class OpenParenToken extends Token { }
true
eeee09478d87fd7aded3b4c74d64cc9526da1ca3
Java
Kwongmingwei/FarisCare
/app/src/main/java/com/example/fariscare/RegisterPage.java
UTF-8
6,112
2.1875
2
[]
no_license
package com.example.fariscare; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class RegisterPage extends AppCompatActivity { EditText EnterEmail,EnterPassword,EnterName,ConfirmPassword,PhoneNo; Button RegisterButton; FirebaseAuth Auth; DatabaseReference databaseReference; Member member; String number; long maxid=0; private static final String TAG = "RegisterPage"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_page); EnterEmail=findViewById(R.id.EnterEmail); EnterName=findViewById(R.id.EnterName); EnterPassword=findViewById(R.id.EnterPassword); ConfirmPassword=findViewById(R.id.ConfirmPassword); RegisterButton=findViewById(R.id.RegisterButton); Auth = FirebaseAuth.getInstance(); databaseReference= FirebaseDatabase.getInstance().getReference().child("Member"); member = new Member(); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists()) { //Chris - To get the current number of users in the database. maxid=dataSnapshot.getChildrenCount(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); RegisterButton.setOnClickListener(new View.OnClickListener() { @SuppressLint("ShowToast") @Override public void onClick(View v) { String email, password, name, confirmPassword; email = EnterEmail.getText().toString(); password = EnterPassword.getText().toString(); name = EnterName.getText().toString(); confirmPassword = ConfirmPassword.getText().toString(); //Chris - Verification for inputs //Chris - Check for empty Inputs if (name.equals("")) { Log.v(TAG, "Name Required"); Toast.makeText(RegisterPage.this, "Name Required", Toast.LENGTH_SHORT).show(); return; } if (email.equals("")) { Log.v(TAG, "Email Required");//Chris - Check for empty Inputs Toast.makeText(RegisterPage.this, "Email Required", Toast.LENGTH_SHORT).show(); return; } if (password.equals(""))//Chris - Check for empty Inputs { Log.v(TAG, "Password Required"); Toast.makeText(RegisterPage.this, "Password Required", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6)//Chris - to check password hit the minimal characters of the password requirement { Log.v(TAG, "Password is must be at least contain 6 characters"); Toast.makeText(RegisterPage.this, "Password is must be at least contain 6 characters", Toast.LENGTH_SHORT).show(); return; } if (confirmPassword.equals(""))//Chris - Check for empty Inputs { Log.v(TAG, "Confirm Password"); Toast.makeText(RegisterPage.this, "Confirm Password", Toast.LENGTH_SHORT).show(); return; } if (!confirmPassword.equals(password))//Chris - To Confirm password { Log.v(TAG, "Password Do Not Match"); Toast.makeText(RegisterPage.this, "Password Do Not Match", Toast.LENGTH_SHORT).show(); return; } else { Auth.createUserWithEmailAndPassword(email, confirmPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { //Chris - check whether register of user is successful or not if (!task.isSuccessful()) { //Custom message if email is invaild Toast.makeText(RegisterPage.this, "The email is invaild", Toast.LENGTH_SHORT).show(); Log.v(TAG, "The email is invaild"); } else { //Chris - check whether register of user is successful or not Intent registerpt2 = new Intent(RegisterPage.this, RegisterPt2.class); registerpt2.putExtra("name", name); registerpt2.putExtra("email", email); registerpt2.putExtra("password", confirmPassword); startActivity(registerpt2); finish(); } } }); } } }); } }
true
3c058e8fc68a88d0de95d89627ce28d4a643bf6b
Java
Lihuanghe/CustomizeDNSHttpClient
/src/main/java/com/zyzx/CustomizeClientConnectionOperator.java
UTF-8
3,486
2.40625
2
[ "Apache-2.0" ]
permissive
package com.zyzx; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.conn.HttpInetSocketAddress; import org.apache.http.conn.OperatedClientConnection; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeSocketFactory; import org.apache.http.impl.conn.DefaultClientConnectionOperator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; public class CustomizeClientConnectionOperator extends DefaultClientConnectionOperator { private final Log log = LogFactory.getLog(CustomizeClientConnectionOperator.class); private final CustomizeNameService ns ; public CustomizeClientConnectionOperator(SchemeRegistry schemes,CustomizeNameService tns) { super(schemes); this.ns = tns; } protected InetAddress[] resolveHostname(String host) throws UnknownHostException { return this.ns.lookupAllHostAddr(host); } public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } if (conn.isOpen()) { throw new IllegalStateException("Connection must not be open"); } Scheme schm = this.schemeRegistry.getScheme(target.getSchemeName()); SchemeSocketFactory sf = schm.getSchemeSocketFactory(); InetAddress[] addresses = resolveHostname(target.getHostName()); int port = schm.resolvePort(target.getPort()); for (int i = 0; i < addresses.length; ++i) { InetAddress address = addresses[i]; boolean last = i == addresses.length - 1; Socket sock = sf.createSocket(params); conn.opening(sock, target); InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port); InetSocketAddress localAddress = null; if (local != null) { localAddress = new InetSocketAddress(local, 0); } if (log.isDebugEnabled()) log.debug("Connecting to host " + remoteAddress +" IP :" + address); try { Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params); if (sock != connsock) { sock = connsock; conn.opening(sock, target); } prepareSocket(sock, context, params); conn.openCompleted(sf.isSecure(sock), params); ns.moveToFirstInetAddress(target.getHostName(), i,addresses[i]); return; } catch (ConnectException ex) { if (last) throw new HttpHostConnectException(target, ex); } catch (ConnectTimeoutException ex) { if (last) { throw ex; } } if (log.isDebugEnabled()) log.debug("Connect to " + remoteAddress + " timed out. " + "Connection will be retried using another IP address"); } } }
true
ed5c4b60a2b1af3bcbc1de4f73b28c180fd1cfcf
Java
sanjaymurali/Plagiarizer
/src/main/resources/tests/QuickSorter.java
UTF-8
1,382
2.71875
3
[]
no_license
package hw; import ab; public class QuickSorter<T extends Comparable<T>> implements Sorter { public void quicksort(Comparable[] list, int left, int right) { if (right > left) { int pivotNewIndex = partition(list, left, right, right); quicksort(list, left, pivotNewIndex - 1); quicksort(list, pivotNewIndex + 1, right); } } public int partition(Comparable[] list, int left, int right, int pivotIndex) { Comparable pivotValue = list[pivotIndex]; Comparable temp = list[right]; list[right] = list[pivotIndex]; list[pivotIndex] = temp; int storeIndex = left; for (int i = left; i < right; i++) { if (list[i].compareTo(pivotValue) <= 0) { temp = list[storeIndex]; list[storeIndex] = list[i]; list[i] = temp; storeIndex++; } } temp = list[storeIndex]; list[storeIndex] = list[right]; list[right] = temp; return storeIndex; } @Override public void sort(Comparable[] list) { // TODO Auto-generated method stub T[] newlist = (T[]) list; quicksort(newlist, 0, list.length - 1); } public void justForTest() { } }
true
b4d91218d4f0866a2b587c1579ff3060ab18f3ad
Java
nguyencuong382/PE_Projects
/SE05630_CuongNM_SE1209_PRJ321/FinalQ2_SE05630/src/java/model/DummyDAO.java
UTF-8
1,966
2.921875
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 model; import context.DBContext; import entity.Dummy; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; /** * * @author Admin */ public class DummyDAO { public List<Dummy> list(String query) throws Exception { List<Dummy> dummies = new ArrayList<>(); Connection conn = new DBContext().getConnection(); PreparedStatement ps = conn .prepareStatement(query); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { Dummy d = new Dummy(); d.setDummyID(resultSet.getInt("DummyID")); d.setDummyName(resultSet.getString("DummyName")); dummies.add(d); } resultSet.close(); conn.close(); return dummies; } public List<Dummy> getAllDummies() throws Exception { String query = "select * from Dummy"; return list(query); } public Dummy getDummyById(int id) throws Exception { String query = "select * from Dummy where DummyID = " + id; return list(query).get(0); } public boolean updateDummy(int oldDummyId, String oldDummyName, int newDummyId, String newDummyName) throws Exception { String query = "UPDATE Dummy\n" + " SET DummyID = "+newDummyId+"\n" + " ,DummyName = '"+newDummyName+"'\n" + " WHERE DummyID = "+oldDummyId+" and DummyName = '"+oldDummyName+"'"; Connection conn = new DBContext().getConnection(); PreparedStatement ps = conn .prepareStatement(query); int n = ps.executeUpdate(); ps.close(); conn.close(); return n > 0; } }
true
2d5ab57c61db0e351eaffd79f436eb6d7c7b33a3
Java
UnsungHero0/portal
/src/main/java/vn/com/vndirect/domain/IfoCompanyProfileView.java
UTF-8
515
1.671875
2
[]
no_license
package vn.com.vndirect.domain; /** * IfoCompanyProfileView generated by MyEclipse - Hibernate Tools */ @SuppressWarnings("serial") public class IfoCompanyProfileView extends BaseBean implements java.io.Serializable { // Fields private IfoCompanyProfileViewId id; // Constructors /** default constructor */ public IfoCompanyProfileView() { } // Property accessors public IfoCompanyProfileViewId getId() { return this.id; } public void setId(IfoCompanyProfileViewId id) { this.id = id; } }
true
27169150d09d2af90200558caa6816f2376bee6b
Java
MaxChanger/OrderingOnline
/app/src/main/java/com/k/neleme/fragments/FirstFragment.java
UTF-8
831
2.03125
2
[]
no_license
package com.k.neleme.fragments; import android.os.Bundle; import com.k.neleme.MainActivity; import com.k.neleme.R; import com.k.neleme.Views.ListContainer; import com.k.neleme.adapters.FoodAdapter; import com.k.neleme.adapters.TypeAdapter; import com.shizhefei.fragment.LazyFragment; public class FirstFragment extends LazyFragment { private ListContainer listContainer; @Override protected void onCreateViewLazy(Bundle savedInstanceState) { super.onCreateViewLazy(savedInstanceState); setContentView(R.layout.fragment_first); listContainer = (ListContainer) findViewById(R.id.listcontainer); listContainer.setAddClick((MainActivity) getActivity()); } public FoodAdapter getFoodAdapter() { return listContainer.foodAdapter; } public TypeAdapter getTypeAdapter() { return listContainer.typeAdapter; } }
true
d44eab76abf02b78da9156325f5124cd3188f870
Java
ncpalmie/366-Database-Project
/src/main/java/csc366/jpademo/AuditRepository.java
UTF-8
1,248
2.34375
2
[ "Apache-2.0" ]
permissive
package csc366.jpademo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.repository.query.Param; @Repository public interface AuditRepository extends JpaRepository<Audit, Long>{ Audit findByAuditID(String auditID); // JPQL query @Query("from Audit o where o.auditID = :auditID") Audit findByAuditIDJpql(@Param("auditID") String auditID); @Query("select p from Audit p join p.store store where p.auditID = :id") Audit findByAuditIDWithStoreJpql(@Param("id") String id); @Query("select p from Audit p join p.regulator regulator where p.auditID = :id") Audit findByAuditIDWithRegulatorJpql(@Param("id") String id); // Native SQL query @Query(value = "select * from Audit as o where o.auditID = :auditID", nativeQuery = true) Audit findByAuditIDSql(@Param("auditID") String auditID); @Modifying @Query("update Audit o set o.auditID = :newAuditID where o.auditID = :oldAuditID") void updateID(@Param("oldAuditID") String oldAuditID, @Param("newAuditID") String newAuditID); }
true
fecf27a49891166a6e283a9a72d7c905e38ce2cf
Java
miguelvitores/HashCodePizza
/src/booksExample/LibraryLife.java
UTF-8
813
2.984375
3
[]
no_license
package booksExample; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class LibraryLife { public Library lib; public List<Integer> booksSentInOrder; public static HashMap<Integer, Integer> booksScanned; public LibraryLife(){ booksSentInOrder = new ArrayList<>(); booksScanned = new HashMap<>(); } public LibraryLife(Library lib) { this.lib = lib; booksSentInOrder = new ArrayList<>(); booksScanned = new HashMap<>(); } public boolean addBook(int idLib, int idBook){ boolean added = false; if( ! booksScanned.containsKey(idBook) ){ booksScanned.put(idBook, idLib); booksSentInOrder.add(idBook); added = true; } return added; } }
true
44ea0864e26fef3311a51594b7c6b13802b5a75d
Java
Crune/GaNaDa-Mart
/src/ganada/obj/common/BannerHTMLDao.java
UTF-8
518
2.046875
2
[]
no_license
package ganada.obj.common; import ganada.core.*; public class BannerHTMLDao extends DAO { private static BannerHTMLDao instance = new BannerHTMLDao(); public static BannerHTMLDao getInstance() { return instance; } private BannerHTMLDao() { } private static DBTable t; @Override protected DBTable gT() { if (t == null) { t = new DBTable(null, "BANNER", "CODE", "REG_DATE", ""); t.setCls("ganada.obj.common.BannerHTML"); } return t; } }
true
aca52024f7a981a8470334e72f118b52c16a0196
Java
guerethes/offdroid
/src/br/com/guerethes/orm/engine/ModelORMToSQL.java
UTF-8
1,908
2.671875
3
[]
no_license
package br.com.guerethes.orm.engine; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import br.com.guerethes.orm.engine.i.IModelORMDDL; import br.com.guerethes.orm.exception.NotEntityException; import br.com.guerethes.orm.reflection.EntityReflection; import br.com.guerethes.orm.reflection.FieldReflection; import br.com.guerethes.orm.util.StringUtil; public class ModelORMToSQL implements IModelORMDDL { private Class<?> targetClass; private String tableName; private List<java.lang.String> columns; public ModelORMToSQL(Class<?> targetClass) throws NotEntityException { super(); if (EntityReflection.isEntity(targetClass)) { this.targetClass = targetClass; this.tableName = EntityReflection.getTableName(this.targetClass); } else { throw new NotEntityException("A classe " + targetClass.toString() + " não corresponde a uma entidade mapeada válida!"); } } @Override public String createSQL() { List<Field> fields = EntityReflection.getEntityFields(targetClass); this.columns = new ArrayList<java.lang.String>(); for (Field field : fields) { String column = FieldReflection.getColumnNameDDL(this.targetClass, field); if (!column.equals("")) { this.columns.add(column); } } return StringUtil.createSQL(this.tableName, this.columns); } @Override public String createSQL(String table) { if ( table.equals(this.tableName) ) { List<Field> fields = EntityReflection.getEntityFields(targetClass); this.columns = new ArrayList<java.lang.String>(); for (Field field : fields) { String column = FieldReflection.getColumnNameDDL(this.targetClass, field); if (!column.equals("")) { this.columns.add(column); } } return StringUtil.createSQL(this.tableName, this.columns); } return null; } @Override public String dropSQL() { return StringUtil.dropSQL(this.tableName); } }
true
0ee1c245f5136614ff91b3ce914909395ab23b67
Java
DarthBoomerPlay/EazyNick
/src/net/dev/eazynick/listeners/PlayerNickListener.java
UTF-8
4,116
1.96875
2
[]
no_license
package net.dev.eazynick.listeners; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import net.dev.eazynick.EazyNick; import net.dev.eazynick.api.NickManager; import net.dev.eazynick.api.PlayerNickEvent; import net.dev.eazynick.hooks.LuckPermsHook; import net.dev.eazynick.hooks.TABHook; import net.dev.eazynick.utils.FileUtils; import net.dev.eazynick.utils.LanguageFileUtils; import net.dev.eazynick.utils.Utils; import me.clip.placeholderapi.PlaceholderAPI; public class PlayerNickListener implements Listener { @EventHandler(priority = EventPriority.HIGH) public void onPlayerNick(PlayerNickEvent e) { EazyNick eazyNick = EazyNick.getInstance(); Utils utils = eazyNick.getUtils(); FileUtils fileUtils = eazyNick.getFileUtils(); LanguageFileUtils languageFileUtils = eazyNick.getLanguageFileUtils(); if(!(e.isCancelled())) { Player p = e.getPlayer(); NickManager api = new NickManager(p); boolean changePrefixAndSuffix = fileUtils.getConfig().getBoolean("WorldsWithDisabledPrefixAndSuffix") || !(utils.getWorldsWithDisabledPrefixAndSuffix().contains(p.getWorld().getName().toUpperCase())); String nickName = e.getNickName(), tagPrefix = e.getTagPrefix(), tagSuffix = e.getTagSuffix(), chatPrefix = e.getChatPrefix(), chatSuffix = e.getChatSuffix(), tabPrefix = e.getTabPrefix(), tabSuffix = e.getTabSuffix(); utils.getCanUseNick().put(p.getUniqueId(), false); Bukkit.getScheduler().runTaskLater(eazyNick, new Runnable() { @Override public void run() { utils.getCanUseNick().put(p.getUniqueId(), true); } }, fileUtils.getConfig().getLong("Settings.NickDelay") * 20); if(fileUtils.getConfig().getBoolean("BungeeCord")) { String groupName = e.getGroupName(); if(!(e.isJoinNick())) { if(utils.ultraPermissionsStatus()) { if(utils.getOldUltraPermissionsGroups().containsKey(p.getUniqueId())) groupName = utils.getOldUltraPermissionsGroups().get(p.getUniqueId()).toString(); } if(utils.luckPermsStatus()) { if(utils.getOldLuckPermsGroups().containsKey(p.getUniqueId())) groupName = utils.getOldLuckPermsGroups().get(p.getUniqueId()); } if(utils.permissionsExStatus()) { if(utils.getOldPermissionsExGroups().containsKey(p.getUniqueId())) groupName = utils.getOldPermissionsExGroups().get(p.getUniqueId()).toString(); } } if(!(groupName.equals("NONE"))) eazyNick.getMySQLPlayerDataManager().insertData(p.getUniqueId(), groupName, chatPrefix, chatSuffix, tabPrefix, tabSuffix, tagPrefix, tagSuffix); } if(utils.placeholderAPIStatus()) { tagPrefix = PlaceholderAPI.setPlaceholders(p, tagPrefix); tagSuffix = PlaceholderAPI.setPlaceholders(p, tagSuffix); chatPrefix = PlaceholderAPI.setPlaceholders(p, chatPrefix); chatSuffix = PlaceholderAPI.setPlaceholders(p, chatSuffix); tabPrefix = PlaceholderAPI.setPlaceholders(p, tabPrefix); tabSuffix = PlaceholderAPI.setPlaceholders(p, tabSuffix); } if(changePrefixAndSuffix && utils.luckPermsStatus()) new LuckPermsHook(p).updateNodes(tagPrefix, tagSuffix, e.getGroupName()); if(changePrefixAndSuffix && utils.tabStatus() && fileUtils.getConfig().getBoolean("ChangeNameAndPrefixAndSuffixInTAB")) new TABHook(p).update(nickName, tabPrefix, tabSuffix, tagPrefix, tagSuffix); if(fileUtils.getConfig().getBoolean("LogNicknames")) eazyNick.getUtils().sendConsole("§a" + p.getName() + " §7(" + p.getUniqueId().toString() + ") §4set his nickname to §6" + nickName); api.nickPlayer(nickName, e.getSkinName()); if(changePrefixAndSuffix) api.updatePrefixSuffix(e.getTagPrefix(), e.getTagSuffix(), chatPrefix, chatSuffix, e.getTabPrefix(), e.getTabSuffix(), e.getSortID(), e.getGroupName()); if(!(e.isRenick())) p.sendMessage(utils.getPrefix() + languageFileUtils.getConfigString(p, "Messages." + (e.isJoinNick() ? "ActiveNick" : "Nick")).replace("%name%", nickName)); } } }
true
9aee1efedfa6ed7b12f27285ea211cd1d5d872eb
Java
closing/yczd
/yczd-api-aio/src/main/java/com/yczd/api/aio/RootController.java
UTF-8
643
1.890625
2
[]
no_license
package com.yczd.api.aio; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/") public class RootController { @GetMapping() public List<String> root() { List<String> links = new ArrayList<>(); links.add("/v1/stations/"); links.add("/v1/drivers/"); links.add("/v1/users/"); links.add("/v1/shops/"); links.add("/v1/orders/"); links.add("/v1/goods/"); links.add("/v1/logistics/"); return links; } }
true
880e6d5590773d60c87b9801803cf836658c3054
Java
pshirkey/dodah
/DodahFinder/src/com/dodah/service/Client.java
UTF-8
7,520
2.375
2
[]
no_license
package com.dodah.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class Client { private final String SERVER_URL = "http://10.0.2.2:8081/service/"; private final String client_key = "B902A730A4D211DFA5C53432E0D72085"; private String access_token = ""; private String errorMessage = ""; private final String RESULT = "result"; private final String SUCCESS = "success"; private final String RESPONSE = "response"; private final String STATUS = "status"; private final String ERROR_MESSAGE = "error_message"; /** * default ctor */ public Client() { } /** * ctor */ public Client(String access_token) { this.setAccess_token(access_token); } /** * access_token getter * * @return string */ public String getAccess_token() { return access_token; } /** * gets the error message for the last call * * @return string */ public String getErrorMessage() { return errorMessage; } /** * access_token setter * * @param access_token * the value for the access token */ public void setAccess_token(String access_token) { this.access_token = access_token; } /** * authenticates the current user * * @param email * email address for user * @param clearTextPassword * teh password in clear text * @return the access_token for this user */ public String Authenticate(String email, String clearTextPassword) { this.access_token = ""; this.errorMessage = ""; if (email != null && email.length() > 0 && clearTextPassword != null && clearTextPassword.length() > 0) { String md5Password = this.md5(clearTextPassword); HashMap<String, String> params = new HashMap<String, String>(); params.put("service_client", client_key); params.put("email", email); params.put("password", md5Password); JSONObject result = this.Call("authenticate", params); JSONObject response = this.getReponse(result); if (response != null) { try { this.access_token = response.getString("access_token"); } catch (JSONException e) { Log.i("DoDahService", e.getMessage()); this.access_token = ""; } } } return this.access_token; } /** * Makes the call to the server, returns the json array from the server * * @param method * method name to call on the server * @param parameters * hashmap of paramters * @return JSONArray */ private JSONObject Call(String method, HashMap<String, String> parameters) { String callUrl = this.BuildMethodCall(method, parameters); if (callUrl != "") { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object HttpPost httpget = new HttpPost(callUrl); HttpResponse response; try { response = httpclient.execute(httpget); // Examine the response status Log.i("DoDahService", response.getStatusLine().toString()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to worry about connection release if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); String result = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); Log.i("DoDahService", result); JSONObject json = new JSONObject(result); return json; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } /** * Builds the full url to the server with the parameters added * * @param method * the name of the method to call * @param parameters * the parameters to call it with * @return the full usrl string or "" */ private String BuildMethodCall(String method, HashMap<String, String> parameters) { if (method != null && method.length() > 0) { StringBuilder fullUrl = new StringBuilder(SERVER_URL); fullUrl.append(method); fullUrl.append("?client_key="); fullUrl.append(client_key); if (parameters != null && !parameters.isEmpty()) { Iterator<Entry<String, String>> iter = parameters.entrySet() .iterator(); while (iter.hasNext()) { Map.Entry pairs = iter.next(); fullUrl.append("&"); fullUrl.append(pairs.getKey()); fullUrl.append("="); fullUrl.append(pairs.getValue()); } } return fullUrl.toString(); } return ""; } /** * Converts the inputstream to a string for json parsing * * @param is * @return json string */ private static String convertStreamToString(InputStream is) { /* * To convert the InputStream to String we use the * BufferedReader.readLine() method. We iterate until the BufferedReader * return null which means there's no more data to read. Each line will * appended to a StringBuilder and returned as String. */ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /** * generates the md5 version of a string * * @param input * the string input * @return md5 string */ private String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { } return res; } /** * pulls the response object out and sets the error message if there is one * * @param callResult * the return from the call * @return JSONObject */ private JSONObject getReponse(JSONObject callResult) { this.errorMessage = ""; try { if (callResult != null) { JSONObject res = callResult.getJSONObject(RESULT); if (res != null) { if (res.getString(STATUS).equals(SUCCESS)) { return res.getJSONObject(RESPONSE); } else { this.errorMessage = res.getString(ERROR_MESSAGE); } } } } catch (JSONException e) { Log.i("DoDahService", e.getMessage()); } return null; } }
true
72d97d64c8b78f13bc12e1c7ea4c84ad0f8b5740
Java
wanan123033/muzhitui
/app/src/main/java/com/nevermore/muzhitui/module/bean/ProxyType.java
UTF-8
2,947
2.296875
2
[]
no_license
package com.nevermore.muzhitui.module.bean; import java.io.Serializable; import java.util.List; /** * Created by hehe on 2016/6/14. */ public class ProxyType { /** * phonetell : 8899009 * name : 宋广才 * state : 1 * province : 广东 * typeList : [{"amount":24000,"id":1,"price":80,"count":300,"name":"A级代理","rebate":6000},{"amount":20000,"id":2,"price":100,"count":200,"name":"B级代理","rebate":5000},{"amount":12000,"id":3,"price":120,"count":100,"name":"C级代理","rebate":3000}] * city : 深圳 */ private String phonetell; private String name; private String state; private String province; private String city; /** * amount : 24000.0 * id : 1 * price : 80.0 * count : 300 * name : A级代理 * rebate : 6000.0 */ private List<TypeListBean> typeList; public String getPhonetell() { return phonetell; } public void setPhonetell(String phonetell) { this.phonetell = phonetell; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public List<TypeListBean> getTypeList() { return typeList; } public void setTypeList(List<TypeListBean> typeList) { this.typeList = typeList; } public static class TypeListBean implements Serializable { private double amount; private int id; private double price; private int count; private String name; private double rebate; public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getRebate() { return rebate; } public void setRebate(double rebate) { this.rebate = rebate; } } }
true
2e52e8f9d8c7762c86bb4273053cb32fde19def8
Java
victropolis/project-euler-solved
/src/main/java/com/victropolis/euler/Problem447.java
UTF-8
818
2.6875
3
[]
no_license
package com.victropolis.euler; /** * Generated programatically by victropolis on 07/04/15. */ public class Problem447 extends BaseProblem { /* Description (from https://projecteuler.net/problem=447): For every integer n&gt;1, the family of functions fn,a,b is defined by fn,a,b(x)≡ax+b mod n for a,b,x integer and 0&lt;a&lt;n, 0≤b&lt;n, 0≤x&lt;n. We will call fn,a,b a retraction if fn,a,b(fn,a,b(x))≡fn,a,b(x) mod n for every 0≤x&lt;n. Let R(n) be the number of retractions for n. F(N)=∑R(n) for 2≤n≤N. F(107)≡638042271 (mod 1 000 000 007). Find F(1014) (mod 1 000 000 007). */ public static long solve(/* change signature to provide required inputs */) { throw new UnsupportedOperationException("Problem447 hasn't been solved yet."); } }
true
35856bebace14c06701cc7c1058c3f5c01972be3
Java
akaravi/Ntk.Android.CpanelBase
/api/src/main/java/ntk/base/api/news/interfase/INewsShareReciverCategory.java
UTF-8
2,411
1.914063
2
[]
no_license
package ntk.base.api.news.interfase; import java.util.Map; import io.reactivex.Observable; import ntk.base.api.news.model.NewsCountRequest; import ntk.base.api.news.model.NewsExportFileRequest; import ntk.base.api.news.model.NewsGetAllRequest; import ntk.base.api.news.model.NewsShareReciverCategoryAddRequest; import ntk.base.api.news.model.NewsShareReciverCategoryDeleteRequest; import ntk.base.api.news.model.NewsShareReciverCategoryEditRequest; import ntk.base.api.news.model.NewsShareReciverCategoryResponse; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.HeaderMap; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.PUT; public interface INewsShareReciverCategory { @POST("api/newsShareReciverCategory/getall/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> GetAll(@HeaderMap Map<String, String> headers, @Body NewsGetAllRequest request); @GET("api/newsShareReciverCategory/getviewmodel/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> GetViewModel(@HeaderMap Map<String, String> headers); @POST("api/newsShareReciverCategory/Add/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> Add(@HeaderMap Map<String, String> headers, @Body NewsShareReciverCategoryAddRequest request); @PUT("api/newsShareReciverCategory/Edit/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> Edit(@HeaderMap Map<String, String> headers, @Body NewsShareReciverCategoryEditRequest request); @DELETE("api/newsShareReciverCategory/Delete/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> Delete(@HeaderMap Map<String, String> headers, @Body NewsShareReciverCategoryDeleteRequest request); @POST("api/newsShareReciverCategory/ExportFile/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> ExportFile(@HeaderMap Map<String, String> headers, @Body NewsExportFileRequest request); @POST("api/newsShareReciverCategory/count/") @Headers({"content-type: application/json"}) Observable<NewsShareReciverCategoryResponse> Count(@HeaderMap Map<String, String> headers, @Body NewsCountRequest request); }
true
f413b2616e7cbe59762fa5254c2af8fbfe47aa05
Java
LaurentiuStoica94/Bancomat
/src/main/java/ClientNotification.java
UTF-8
839
2.984375
3
[]
no_license
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; public class ClientNotification { static Path fileName = Path.of("ClientNotifications.txt"); static boolean once = true; public static void sendNotification(int amount) { String content = String.format("The amount %s was withdrawn. If you do not recognize this operation please contact the bank %n", amount); try { if (once) { Files.writeString(fileName, String.format("This file contains client notifications:%n")); once = false; } Files.writeString(fileName, content, StandardOpenOption.APPEND); } catch (IOException e) { System.out.println("Notification was not successful"); } } }
true
8d23668ae9946a841ae0d59b6d8a6ff86709d8da
Java
xin923291020/University
/大三上/软件设计/Tutorial4/20142863_杨程鑫/test1/MainClass.java
UTF-8
252
2
2
[]
no_license
package test1; public class MainClass { public static void main(String args[]) throws Exception { PeopleFactory PF = (PeopleFactory)XMLPerson.getBean(); Man W = PF.produceMan(); W.Display(); Woman WM = PF.produceWoman(); WM.Display(); } }
true
9abe037ef1c435b9a44a6ab46ff651afed9fc92c
Java
tz1992/algorithm
/algorithm/src/algorithm/jingdong/Balls.java
UTF-8
504
3.34375
3
[]
no_license
package algorithm.jingdong; public class Balls { public int calcDistance(int A, int B, int C, int D) { int a=getDis(100); int b=getDis(B); int c=getDis(C); int d=getDis(D); return a+b+c+d; } private int getDis(int a) { int count=a; while(a/2!=0){ a=a/2; count=count+2*a; System.out.println(a); } return count; } public static void main(String[] args) { Balls balls=new Balls(); balls.getDis(100); } }
true
7b201cd253a5d45ac7f7067d191c2495952da139
Java
zhongxingyu/Seer
/Diff-Raw-Data/26/26_03b31eff41b927b6cba7123fb6babb592d39f85b/ResultMonitorFactory/26_03b31eff41b927b6cba7123fb6babb592d39f85b_ResultMonitorFactory_t.java
UTF-8
13,171
2.125
2
[]
no_license
package com.almende.eve.monitor; import java.io.IOException; import java.io.Serializable; import java.net.ProtocolException; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.almende.eve.agent.Agent; import com.almende.eve.agent.annotation.EventTriggered; import com.almende.eve.rpc.annotation.Access; import com.almende.eve.rpc.annotation.AccessType; import com.almende.eve.rpc.annotation.Name; import com.almende.eve.rpc.annotation.Required; import com.almende.eve.rpc.annotation.Sender; import com.almende.eve.rpc.jsonrpc.JSONRPC; import com.almende.eve.rpc.jsonrpc.JSONRPCException; import com.almende.eve.rpc.jsonrpc.JSONRequest; import com.almende.eve.rpc.jsonrpc.JSONResponse; import com.almende.eve.rpc.jsonrpc.jackson.JOM; import com.almende.util.AnnotationUtil; import com.almende.util.AnnotationUtil.AnnotatedClass; import com.almende.util.AnnotationUtil.AnnotatedMethod; import com.almende.util.NamespaceUtil; import com.almende.util.NamespaceUtil.CallTuple; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.type.TypeFactory; public class ResultMonitorFactory implements ResultMonitorFactoryInterface { private static final Logger LOG = Logger.getLogger(ResultMonitorFactory.class .getCanonicalName()); private Agent myAgent = null; private static final String MONITORS = "_monitors"; public ResultMonitorFactory(Agent agent) { this.myAgent = agent; } /** * Sets up a monitored RPC call subscription. Conveniency method, which can * also be expressed as: * new ResultMonitor(monitorId, getId(), * url,method,params).add(ResultMonitorConfigType * config).add(ResultMonitorConfigType config).store(); * * @param monitorId * @param url * @param method * @param params * @param callbackMethod * @param confs * @return */ public String create(String monitorId, URI url, String method, ObjectNode params, String callbackMethod, ResultMonitorConfigType... confs) { ResultMonitor old = getMonitorById(monitorId); if (old != null) { old.cancel(); } ResultMonitor monitor = new ResultMonitor(monitorId, myAgent.getId(), url, method, params, callbackMethod); for (ResultMonitorConfigType config : confs) { monitor.add(config); } return store(monitor); } /** * Gets an actual return value of this monitor subscription. If a cache is * available, * this will return the cached value if the maxAge filter allows this. * Otherwise it will run the actual RPC call (similar to "send"); * * @param monitorId * @param filterParms * @param returnType * @return * @throws JSONRPCException * @throws IOException */ public <T> T getResult(String monitorId, ObjectNode filterParms, Class<T> returnType) throws IOException, JSONRPCException { return getResult(monitorId, filterParms, JOM.getTypeFactory() .constructSimpleType(returnType, new JavaType[0])); } /** * Gets an actual return value of this monitor subscription. If a cache is * available, * this will return the cached value if the maxAge filter allows this. * Otherwise it will run the actual RPC call (similar to "send"); * * @param monitorId * @param filterParms * @param returnType * @return * @throws JSONRPCException * @throws IOException */ @SuppressWarnings("unchecked") public <T> T getResult(String monitorId, ObjectNode filterParms, JavaType returnType) throws JSONRPCException, IOException { T result = null; ResultMonitor monitor = getMonitorById(monitorId); if (monitor != null) { if (monitor.hasCache() && monitor.getCache() != null && monitor.getCache().filter(filterParms)) { result = (T) monitor.getCache().get(); } if (result == null) { result = myAgent.send(monitor.getUrl(), monitor.getMethod(), monitor.getParams(), returnType); if (monitor.hasCache()) { monitor.getCache().store(result); } } } else { LOG.severe("Failed to find monitor!" + monitorId); } return result; } /** * Cancels a running monitor subscription. * * @param monitorId */ public void cancel(String monitorId) { ResultMonitor monitor = getMonitorById(monitorId); if (monitor != null) { monitor.cancel(); delete(monitor.getId()); } else { LOG.warning("Trying to cancel non existing monitor:" + myAgent.getId() + "." + monitorId); } } @Access(AccessType.SELF) public final void doPoll(@Name("monitorId") String monitorId) throws JSONRPCException, IOException { ResultMonitor monitor = getMonitorById(monitorId); if (monitor != null) { Object result = myAgent.send(monitor.getUrl(), monitor.getMethod(), monitor.getParams(), TypeFactory.unknownType()); if (monitor.getCallbackMethod() != null) { ObjectNode params = JOM.createObjectNode(); params.put("result", JOM.getInstance().writeValueAsString(result)); myAgent.send(URI.create("local://" + myAgent.getId()), monitor.getCallbackMethod(), params); } if (monitor.hasCache()) { monitor.getCache().store(result); } } } private JsonNode lastRes = null; @Access(AccessType.SELF) public final void doPush(@Name("pushParams") ObjectNode pushParams, @Required(false) @Name("triggerParams") ObjectNode triggerParams) throws ProtocolException, JSONRPCException { String method = pushParams.get("method").textValue(); ObjectNode params = (ObjectNode) pushParams.get("params"); JSONResponse res = JSONRPC.invoke(myAgent, new JSONRequest(method, params), myAgent); JsonNode result = res.getResult(); if (pushParams.has("onChange") && pushParams.get("onChange").asBoolean()) { if (lastRes != null && lastRes.equals(result)) { return; } lastRes = result; } ObjectNode parms = JOM.createObjectNode(); parms.put("result", result); parms.put("monitorId", pushParams.get("monitorId").textValue()); parms.put("callbackParams", triggerParams == null ? pushParams : pushParams.putAll(triggerParams)); myAgent.send(URI.create(pushParams.get("url").textValue()), "monitor.callbackPush", parms); // TODO: If callback reports "old", unregisterPush(); } @Access(AccessType.PUBLIC) public final void callbackPush(@Name("result") Object result, @Name("monitorId") String monitorId, @Name("callbackParams") ObjectNode callbackParams) { try { ResultMonitor monitor = getMonitorById(monitorId); if (monitor != null) { if (monitor.getCallbackMethod() != null) { ObjectNode params = JOM.createObjectNode(); if (callbackParams != null) { params = callbackParams; } params.put("result", JOM.getInstance().writeValueAsString(result)); myAgent.send(URI.create("local://" + myAgent.getId()), monitor.getCallbackMethod(), params); } if (monitor.hasCache()) { monitor.getCache().store(result); } } else { LOG.severe("Couldn't find local monitor by id:" + monitorId); } } catch (Exception e) { LOG.log(Level.WARNING, "Couldn't run local callbackMethod for push!" + monitorId, e); } } @Access(AccessType.PUBLIC) public final void registerPush(@Name("pushId") String id, @Name("pushParams") ObjectNode pushParams, @Sender String senderUrl) { if (myAgent.getState().containsKey("_push_" + id)) { LOG.warning("reregistration of existing push, canceling old version."); try { unregisterPush(id); } catch (Exception e) { LOG.warning("Failed to unregister push:" + e); } } ObjectNode result = JOM.createObjectNode(); pushParams.put("url", senderUrl); ObjectNode wrapper = JOM.createObjectNode(); wrapper.put("pushParams", pushParams); LOG.info("Register Push:" + senderUrl + " id:" + id); if (pushParams.has("interval")) { int interval = pushParams.get("interval").intValue(); JSONRequest request = new JSONRequest("monitor.doPush", wrapper); result.put( "taskId", myAgent.getScheduler().createTask(request, interval, true, false)); } if (pushParams.has("onEvent") && pushParams.get("onEvent").asBoolean()) { // default String event = "change"; if (pushParams.has("event")) { // Event param overrules event = pushParams.get("event").textValue(); } else { AnnotatedClass ac = null; try { CallTuple res = NamespaceUtil.get(myAgent, pushParams.get("method").textValue()); ac = AnnotationUtil.get(res.getDestination().getClass()); for (AnnotatedMethod method : ac.getMethods(res .getMethodName())) { EventTriggered annotation = method .getAnnotation(EventTriggered.class); if (annotation != null) { // If no Event param, get it from annotation, else // use default. event = annotation.value(); } } } catch (Exception e) { LOG.log(Level.WARNING, "", e); } } try { result.put( "subscriptionId", myAgent.getEventsFactory().subscribe( myAgent.getFirstUrl(), event, "monitor.doPush", wrapper)); } catch (Exception e) { LOG.log(Level.WARNING, "Failed to register push Event", e); } } myAgent.getState().put("_push_" + id, result.toString()); } @Access(AccessType.PUBLIC) public final void unregisterPush(@Name("pushId") String id) throws JsonProcessingException, IOException { ObjectNode config = null; if (myAgent.getState() != null && myAgent.getState().containsKey("_push_" + id)) { config = (ObjectNode) JOM.getInstance().readTree( myAgent.getState().get("_push_" + id, String.class)); } if (config == null) { return; } if (config.has("taskId")) { String taskId = config.get("taskId").textValue(); myAgent.getScheduler().cancelTask(taskId); } if (config.has("subscriptionId")) { try { myAgent.getEventsFactory().unsubscribe(myAgent.getFirstUrl(), config.get("subscriptionId").textValue()); } catch (Exception e) { LOG.severe("Failed to unsubscribe push:" + e); } } } public String store(ResultMonitor monitor) { try { @SuppressWarnings("unchecked") HashMap<String, ResultMonitor> monitors = (HashMap<String, ResultMonitor>) myAgent .getState().get(MONITORS); HashMap<String, ResultMonitor> newmonitors = new HashMap<String, ResultMonitor>(); if (monitors != null) { newmonitors.putAll(monitors); } newmonitors.put(monitor.getId(), monitor); if (!myAgent.getState().putIfUnchanged(MONITORS, newmonitors, monitors)) { // recursive retry. store(monitor); } } catch (Exception e) { LOG.log(Level.WARNING, "Couldn't find monitors:" + myAgent.getId() + "." + monitor.getId(), e); } return monitor.getId(); } public void delete(String monitorId) { try { @SuppressWarnings("unchecked") Map<String, ResultMonitor> monitors = (Map<String, ResultMonitor>) myAgent .getState().get(MONITORS); Map<String, ResultMonitor> newmonitors = new HashMap<String, ResultMonitor>(); if (monitors != null) { newmonitors.putAll(monitors); } newmonitors.remove(monitorId); if (!myAgent.getState().putIfUnchanged(MONITORS, (Serializable) newmonitors, (Serializable) monitors)) { // recursive retry. delete(monitorId); } } catch (Exception e) { LOG.log(Level.WARNING, "Couldn't delete monitor:" + myAgent.getId() + "." + monitorId, e); } } public ResultMonitor getMonitorById(String monitorId) { try { @SuppressWarnings("unchecked") Map<String, ResultMonitor> monitors = (Map<String, ResultMonitor>) myAgent .getState().get(MONITORS); if (monitors == null) { monitors = new HashMap<String, ResultMonitor>(); } ResultMonitor result = monitors.get(monitorId); if (result != null) { result.init(); } return result; } catch (Exception e) { LOG.log(Level.WARNING, "Couldn't find monitor:" + myAgent.getId() + "." + monitorId, e); } return null; } public void cancelAll() { for (ResultMonitor monitor : getMonitors().values()) { delete(monitor.getId()); } } @Access(AccessType.PUBLIC) public Map<String, ResultMonitor> getMonitors() { try { @SuppressWarnings("unchecked") Map<String, ResultMonitor> monitors = (Map<String, ResultMonitor>) myAgent .getState().get(MONITORS); if (monitors == null) { monitors = new HashMap<String, ResultMonitor>(); } return monitors; } catch (Exception e) { LOG.log(Level.WARNING, "Couldn't find monitors.", e); } return null; } }
true
bf85ba70c2ac6c1b612ba9c8289525eb2a0fb38e
Java
pcelis2/WallBreakers
/Week_4/Implement_Queue_Using_Stack.java
UTF-8
1,328
4.0625
4
[]
no_license
import java.util.*; public class Implement_Queue_Using_Stack { public static void main(String[] args) { } class MyQueue { /** Initialize your data structure here. */ Stack<Integer> myStack; public MyQueue() { myStack = new Stack<Integer>(); } /** Push element x to the back of queue. */ public void push(int x) { Stack<Integer> tempStack = new Stack<Integer>(); while (!myStack.isEmpty()) { tempStack.push(myStack.pop()); } myStack.push(x); while (!tempStack.isEmpty()) { myStack.push(tempStack.pop()); } } /** Removes the element from in front of queue and returns that element. */ public int pop() { return myStack.pop(); } /** Get the front element. */ public int peek() { return myStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return myStack.isEmpty(); } } /** * Your MyQueue object will be instantiated and called as such: MyQueue obj = * new MyQueue(); obj.push(x); int param_2 = obj.pop(); int param_3 = * obj.peek(); boolean param_4 = obj.empty(); */ }
true
89886c7fb2a77f720f8b595bf1edc5bb17ca47ab
Java
ken60/HamburgSteakMOD
/src/main/java/hamburgsteakmod/registry/ModItems.java
UTF-8
1,475
2.3125
2
[]
no_license
package hamburgsteakmod.registry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import hamburgsteakmod.items.ItemDemiglaceSauce; import hamburgsteakmod.items.ItemEmptyCan; import hamburgsteakmod.items.ItemHamburgSteak; import hamburgsteakmod.items.ItemHamburgSteakSauce; import hamburgsteakmod.items.ItemRawHamburgSteak; import net.minecraft.item.Item; public class ModItems { public static Item hamburgSteak = new ItemHamburgSteak(5, false); public static Item hamburgSteakSauce = new ItemHamburgSteakSauce(10, false); public static Item rawHamburgSteak = new ItemRawHamburgSteak(0, false); public static Item demiglaceSauce = new ItemDemiglaceSauce(0, false); public static Item emptyCan = new ItemEmptyCan(); public static void RegisterItem() { GameRegistry.registerItem(hamburgSteak, "hamburgSteak"); GameRegistry.registerItem(hamburgSteakSauce, "hamburgSteakSauce"); GameRegistry.registerItem(rawHamburgSteak, "rawHamburgSteak"); GameRegistry.registerItem(demiglaceSauce, "demiglaceSauce"); GameRegistry.registerItem(emptyCan, "emptyCan"); } public static void SetLanguage() { LanguageRegistry.addName(hamburgSteak, "HamburgSteak"); LanguageRegistry.addName(hamburgSteakSauce, "HamburgSteak Sauce"); LanguageRegistry.addName(rawHamburgSteak, "Raw HamburgSteak"); LanguageRegistry.addName(demiglaceSauce, "Demiglace Sauce"); LanguageRegistry.addName(emptyCan, "Empty Can"); } }
true
7c61e5b1f3bd04aa93a19d28e543a154da6b388e
Java
xiazl/spring_security
/src/main/java/com/cims/business/card/entity/CardDisable.java
UTF-8
358
1.695313
2
[]
no_license
package com.cims.business.card.entity; import lombok.Getter; import lombok.Setter; import java.util.Date; @Setter @Getter public class CardDisable { private Long id; private String cardNo; private Integer disableType; private String comment; private Date disableDate; private Long createUserId; private Date createTime; }
true
1e43729ba228d4f6511ab19805ce930af1013318
Java
jexp/neo4j-ogm
/neo4j-ogm/src/main/java/org/neo4j/ogm/model/GraphModel.java
UTF-8
836
2.5625
3
[]
no_license
package org.neo4j.ogm.model; import java.util.HashMap; import java.util.Map; public class GraphModel { private final Map<Long, NodeModel> nodeMap = new HashMap<>(); private NodeModel[] nodes = new NodeModel[]{}; private RelationshipModel[] relationships = new RelationshipModel[]{}; public NodeModel[] getNodes() { return nodes; } public void setNodes(NodeModel[] nodes) { this.nodes = nodes; for (NodeModel node : nodes) { nodeMap.put(node.getId(), node); } } public RelationshipModel[] getRelationships() { return relationships; } public void setRelationships(RelationshipModel[] relationships) { this.relationships = relationships; } public NodeModel node(Long nodeId) { return nodeMap.get(nodeId); } }
true
022922a3a7121e01d69052ca2dc8129aa1ba4440
Java
gitzhang/sdetools
/ArcObjects/src/com/trgis/bmy/code/FormatString.java
UTF-8
221
2.34375
2
[]
no_license
package com.trgis.bmy.code; public class FormatString { public static String DString(int num) { if (num < 10) { return "0" + Integer.toString(num); } else { return Integer.toString(num); } } }
true
7c584f1e6b8c6520d3bfbec84ef2b822d5ec54c1
Java
ABHIJEET-YADAV/API-Checker
/src/test/java/com/qa/tests/GetAPITest.java
UTF-8
1,852
2.375
2
[]
no_license
package com.qa.tests; import java.io.IOException; import java.util.HashMap; import org.apache.http.Header; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.qa.base.Base; import com.qa.client.RestClient; public class GetAPITest extends Base{ Base testBase; String serviceUrl; String apiUrl; String url; RestClient restClient; CloseableHttpResponse closebaleHttpResponse; @BeforeMethod public void setUp() throws ClientProtocolException, IOException{ testBase = new Base(); serviceUrl = prop.getProperty("URL"); apiUrl = prop.getProperty("serviceURL"); url = serviceUrl + apiUrl; } @Test(priority=1) public void getAPITestWithoutHeaders() throws ClientProtocolException, IOException{ restClient = new RestClient(); closebaleHttpResponse = restClient.get(url); //a. Status Code: int statusCode = closebaleHttpResponse.getStatusLine().getStatusCode(); System.out.println("Status Code--->"+ statusCode); Assert.assertEquals(statusCode, RESPONSE_STATUS_CODE_200, "Status code is not 200"); //b. Json String: String responseString = EntityUtils.toString(closebaleHttpResponse.getEntity(), "UTF-8"); JSONObject responseJson = new JSONObject(responseString); System.out.println("Response JSON from API---> "+ responseJson); //c. All Headers Header[] headersArray = closebaleHttpResponse.getAllHeaders(); HashMap<String, String> allHeaders = new HashMap<String, String>(); for(Header header : headersArray){ allHeaders.put(header.getName(), header.getValue()); } System.out.println("Headers Array-->"+allHeaders); } }
true
817ff54d38c0919bd75172d0f9e4b556192502bf
Java
bangui/JBElec
/project/module2_3/backend/jbelec-backend/src/main/java/com/dmgroup/springboot/service/impl/StationServiceImpl.java
UTF-8
1,561
2.0625
2
[]
no_license
package com.dmgroup.springboot.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.dmgroup.springboot.pojo.Fiber; import com.dmgroup.springboot.pojo.Business; import com.dmgroup.springboot.pojo.Station; import com.dmgroup.springboot.dao.StationDao; import com.dmgroup.springboot.service.StationService; @Service("stationService") public class StationServiceImpl implements StationService { @Autowired private StationDao stationDao; @Override public List<Station> findAll() { return stationDao.findAll(); } @Override public void update(Station station) { stationDao.update(station); } @Override public void insert(Station station) { stationDao.insert(station); } @Override public void insertAll(List<Station> station) { stationDao.insertAll(station); } @Override public void remove(int STATION_ID) { stationDao.remove(STATION_ID); } @Override public List<Station> findByPage(Station station, Pageable pageable) { return stationDao.findByPage(station, pageable); } @Override public Station findOne(int STATION_ID) { return stationDao.findOne(STATION_ID); } @Override public List<Fiber> findFiber(int STATION_ID) { return stationDao.findFiber(STATION_ID); } @Override public List<Business> findBusiness(int STATION_ID) { return stationDao.findBusiness(STATION_ID); } }
true
06b621f4c66ade87c1432906e30cd885ddb1a491
Java
ccolorcat/VanGogh
/library/src/main/java/cc/colorcat/vangogh/SquareTransformation.java
UTF-8
1,192
2.359375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 cxx * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cc.colorcat.vangogh; import android.graphics.Bitmap; /** * Author: cxx * Date: 2017-08-08 * GitHub: https://github.com/ccolorcat */ public class SquareTransformation extends BaseTransformation { @Override public Bitmap transform(Bitmap source) { final int width = source.getWidth(), height = source.getHeight(); if (width == height) return source; final int side = Math.min(width, height); final int left = (width - side) >> 1; final int top = (height - side) >> 1; return Bitmap.createBitmap(source, left, top, side, side); } }
true
a137f631e1ac53c7a5febfb815316ae8cf3b3497
Java
onurerden/mkWS
/src/main/java/mkws/Model/MKMission.java
UTF-8
486
1.632813
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 mkws.Model; import java.sql.Timestamp; import java.util.ArrayList; /** * * @author oerden */ public class MKMission { public ArrayList<Waypoint> waypoints; public String name; public String comments; public Timestamp datetime; public int mkId; //0 for default }
true
26c4346fe73e4dc4aec69db1121c232fa4e44401
Java
pokeflutist78770/The_Legend_Of_Adlez
/src/gameObjects/Consumable.java
UTF-8
278
2.640625
3
[]
no_license
package gameObjects; /** * Consumable interface. This allows an item to become consumable, * where it can then be used on a specific CharacterClass with various * effects * @author Angel Aguayo */ public interface Consumable { boolean use(Creature person); }
true
caf1b4699605977af42e858233f6ddbcf629972e
Java
AndreiDebreceni/demoQA
/src/test/java/com/demoqa/features/ReadFromModalTest.java
UTF-8
536
1.90625
2
[]
no_license
package com.demoqa.features; import com.demoqa.steps.GenerateModalSteps; import com.demoqa.utils.BaseTest; import net.thucydides.core.annotations.Steps; import org.junit.Test; public class ReadFromModalTest extends BaseTest { @Steps private GenerateModalSteps generateModalSteps; @Test public void readTextFromModal(){ generateModalSteps.navigateToModalPage(); generateModalSteps.generateModal(); generateModalSteps.confirmModalText("This is a small modal. It has very less content"); } }
true
6a8fb8d85d85fe8da16aac5139ae0eb3df940ae2
Java
QuietClickCode/wxzj2
/wxzj2/src/com/yaltec/wxzj2/biz/system/action/SysAnnualSetAction.java
UTF-8
2,315
2.09375
2
[]
no_license
package com.yaltec.wxzj2.biz.system.action; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.yaltec.comon.log.LogUtil; import com.yaltec.comon.log.entity.Log; import com.yaltec.wxzj2.biz.system.entity.SysAnnualSet; import com.yaltec.wxzj2.biz.system.service.SysAnnualSetService; import com.yaltec.wxzj2.comon.data.DataHolder; /** * * @ClassName: SysAnnualSetAction * @Description: TODO系统年度设置实现类 * * @author jiangyong * @date 2016-8-1 下午04:40:38 */ @Controller public class SysAnnualSetAction { @Autowired private SysAnnualSetService sysAnnualSetService; /** * 查询 */ @RequestMapping("/sysannualset/index") public String list(Model model) { LogUtil.write(new Log("系统年度设置信息", "查询", "SysAnnualSetAction.list", "")); SysAnnualSet sysAnnualSet = sysAnnualSetService.find(); model.addAttribute("sysAnnualSet", sysAnnualSet); return "/system/sysannualset/index"; } /** * 保存系统年度设置 * * @param request * @return */ @RequestMapping("/sysannualset/update") public String update(SysAnnualSet sysAnnualSet, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) { LogUtil.write(new Log("系统年度设置信息", "修改", "SysAnnualSetAction.update", sysAnnualSet.toString())); Map<String, String> map = new HashMap<String, String>(); map.put("bdate", sysAnnualSet.getBegindate()); map.put("edate", sysAnnualSet.getEnddate()); map.put("cwdate", sysAnnualSet.getZwdate()); map.put("result", "-1"); // 调用service执行update方法 sysAnnualSetService.update(map); int result = Integer.valueOf(map.get("result")); if (result == 0) { DataHolder.reloadCustomerInfo(); redirectAttributes.addFlashAttribute("msg", "修改成功"); } else { redirectAttributes.addFlashAttribute("msg", "修改失败"); } return "redirect:/sysannualset/index"; } }
true
c48c162e134f2322dbafd6fe60ac80de63711746
Java
gentringer/Webservices
/Java RMI/V2/Cabinet_vet_V22/src/interfaces/CabinetVeterinaire.java
UTF-8
628
2.296875
2
[]
no_license
package interfaces; import java.rmi.Remote; import java.rmi.RemoteException; public interface CabinetVeterinaire extends Remote { String getanim(String nom) throws RemoteException; void addAnimal(String nom, String maitre, String espece, String race) throws RemoteException; void creerEspece(String nom, String duree) throws RemoteException; String getEspecee(String nom)throws RemoteException; String getDossierSuivi(String nom) throws RemoteException; void modidossier(String nom, String modification) throws RemoteException; void modifierEsepece(String nom, String modification)throws RemoteException;; }
true
7e11f39f43e5086960dda77fd39fc4403cbb0f73
Java
mSorok/COCONUT
/src/main/java/de/unijena/cheminf/npopensourcecollector/services/AtomContainerToSourceNaturalProductService.java
UTF-8
2,174
2.1875
2
[]
no_license
package de.unijena.cheminf.npopensourcecollector.services; import de.unijena.cheminf.npopensourcecollector.mongocollections.SourceNaturalProduct; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.silent.SilentChemObjectBuilder; import org.openscience.cdk.smiles.SmilesParser; import org.springframework.stereotype.Service; @Service public class AtomContainerToSourceNaturalProductService { public SourceNaturalProduct createSNPlInstance(IAtomContainer ac) { SourceNaturalProduct np = new SourceNaturalProduct(); np.setSource(ac.getProperty("SOURCE")); np.setIdInSource(ac.getID()); np.setOriginalInchi(ac.getProperty("ORIGINAL_INCHI")); np.setOriginalInchiKey(ac.getProperty("ORIGINAL_INCHIKEY")); np.setOriginalSmiles(ac.getProperty("ORIGINAL_SMILES")); np.setSimpleInchi(ac.getProperty("SIMPLE_INCHI")); np.setSimpleInchiKey(ac.getProperty("SIMPLE_INCHIKEY")); np.setSimpleSmiles(ac.getProperty("SIMPLE_SMILES")); if(ac.getProperties().containsKey("ABSOLUTE_SMILES")) { np.setAbsoluteSmiles(ac.getProperty("ABSOLUTE_SMILES")); } if(ac.getProperties().containsKey("CAS")) { np.setCas(ac.getProperty("CAS")); } np.setTotalAtomNumber(ac.getAtomCount()); int heavyAtomCount = 0; for(IAtom a : ac.atoms()){ if(!a.getSymbol().equals("H")){ heavyAtomCount=heavyAtomCount+1; } } np.setHeavyAtomNumber(heavyAtomCount); np.setAcquisition_date(ac.getProperty("ACQUISITION_DATE")); return np; } public IAtomContainer createAtomContainer(SourceNaturalProduct snp){ IAtomContainer ac = null; try { SmilesParser sp = new SmilesParser(SilentChemObjectBuilder.getInstance()); ac = sp.parseSmiles( snp.getSimpleSmiles() ); } catch (InvalidSmilesException e) { System.err.println(e.getMessage()); } return ac; } }
true
ee8ea1ab98e1f0eb9f182376920955e9a30fc0c5
Java
xiaoyu-G/xiaoyu001
/src/gitPro/A.java
UTF-8
153
1.757813
2
[]
no_license
package gitPro; public class A { public A() { } public static void main(String[] args){ System.out.println("你好,git"); } }
true
76d7964267b364cecfc5ab9fa0d48cab18376e98
Java
shpikpavlo/telephone_book1
/src/main/java/ua/com/my/telephone_book/repository/UserRepo.java
UTF-8
221
1.679688
2
[]
no_license
package ua.com.my.telephone_book.repository; import org.springframework.data.jpa.repository.JpaRepository; import ua.com.my.telephone_book.models.User; public interface UserRepo extends JpaRepository<User,Integer> { }
true
5b4c7e23d5675a6302409e7a799afaf66f7f1a2a
Java
nbodapati/C-Python-Coding-
/Java-WebApplication/Hashtable.java
UTF-8
1,814
3.46875
3
[]
no_license
public class Hashtable { private int numel; private Node[] llist; //this is executed each time a hash table is created. static { System.out.println("Hashtable is created!"); } public Hashtable() { this(10); //default numel=10 } public Hashtable(int n) { numel=n; llist= new User[numel]; } public void printContents(int idx) { //System.out.println("Printing the contents.."); Node header=llist[idx]; while(header!=null) { header.print_user(); header=header.next; } } public void insert(User l) { int k=l.id; int get_idx=k%this.numel; Node llist_= this.llist[get_idx]; if(llist_==null) { //this is the first element. this.llist[get_idx]=new User(l); } else { while(llist_.next!=null) { llist_=llist_.next; } llist_.next=new User(l); } } public void remove(User l) { int k=l.get_id(); int get_idx=k%this.numel; Node llist_= this.llist[get_idx]; Node llist2=llist_; while(llist_!=null) { if(llist_.get_id()==k) { System.out.println("Found the element"); break; } llist2=llist_; llist_=llist_.next; } if(llist_!=null) { System.out.println("Remove the element."); Node next=llist_.next; //copy the contents from next to current and delete next. llist2.next=next; } } public void lookUp(int id) { int get_idx=id%this.numel; Node llist_= this.llist[get_idx]; while(llist_!=null) { if(llist_.get_id()==id) { System.out.println("Found the element"); break; } llist_=llist_.next; } if(llist_==null) { System.out.println("Element Not Found"); } } }
true
abd7d29ba981a93a5e6a3ede14ee256e0a236604
Java
pabplanalp/pvmail
/java/source/com/vmail/edi/uspsI1IftsaiStatus1r3/AcEdiUspsI1IftsaiStatus1r3Loc.java
UTF-8
2,463
1.921875
2
[]
no_license
package com.vmail.edi.uspsI1IftsaiStatus1r3; import com.jwApps.edi.JwEdiSegment; import com.jwApps.utility.JwUtility; import com.vmail.edi.base.AcEdiSegmentFinder; import com.vmail.edi.un.D96B.AcEdiUnLoc; public class AcEdiUspsI1IftsaiStatus1r3Loc extends AcEdiUnLoc { //################################################## //# constants //##################################################// public static final String QUALIFIER_ORIGIN = "5"; public static final String QUALIFIER_DESTINATION = "8"; //################################################## //# constructor //##################################################// public AcEdiUspsI1IftsaiStatus1r3Loc(JwEdiSegment e) { super(e); } //################################################## //# accessing //##################################################// public String getQualifier() { return get010_3227(); } public String getLocation() { return get020_3225(); } public boolean hasValidLocation() { String s = getLocation(); if ( s == null ) return false; s = s.trim(); return JwUtility.isNotEmpty(s) && s.length() == 3; } public boolean hasQualifier(String s) { return JwUtility.isEqual(getQualifier(), s); } public boolean isOrigin() { return hasQualifier(QUALIFIER_ORIGIN); } public boolean isDestination() { return hasQualifier(QUALIFIER_DESTINATION); } //################################################## //# segment finder //##################################################// public static AcEdiSegmentFinder getSegmentFinder() { return createSegmentFinder( AcEdiUspsI1IftsaiStatus1r3ConstantsIF.TAG_PLACE_LOCATION_IDENTIFICATION, null, "Location"); } public static AcEdiSegmentFinder getOriginSegmentFinder() { return createSegmentFinder( AcEdiUspsI1IftsaiStatus1r3ConstantsIF.TAG_PLACE_LOCATION_IDENTIFICATION, QUALIFIER_ORIGIN, "Origin Location"); } public static AcEdiSegmentFinder getDestinationSegmentFinder() { return createSegmentFinder( AcEdiUspsI1IftsaiStatus1r3ConstantsIF.TAG_PLACE_LOCATION_IDENTIFICATION, QUALIFIER_DESTINATION, "Destination Location"); } }
true
001fae7bf6c202711ac85bba4c119ef333a5699f
Java
TeamDevintia/DevAthlon3
/src/main/java/io/github/teamdevintia/magicpotions/enums/SoundSource.java
UTF-8
1,067
3.1875
3
[ "MIT" ]
permissive
package io.github.teamdevintia.magicpotions.enums; /** * @author Shad0wCore * <p> * A collection of sound catorgories. * <p> * <b>Description from Minecraft Wiki:</b> * The category this sound event belongs to. Valid category names are * "ambient", "weather", "player", "neutral", "hostile", "block", "record", "music", "master" and "voice". * This String lets the sound system know what sound events belong to what category, so the volume can * be adjusted based on what the sound options are set to for each category. */ public enum SoundSource { MASTER("master"), MUSIC("music"), RECORD("record"), WEATHER("weather"), BLOCK("block"), HOSTILE("hostile"), NEUTRAL("neutral"), PLAYER("player"), AMBIENT("ambient"), VOICE("voice"); private String source; SoundSource(String source) { this.source = source; } /** * @return the name of this source */ public String source() { return this.source; } }
true
d4bcad5b9644bbfb149c7e6a708b872988db04af
Java
Maveriick/JavaAlgo
/MinMaxDC/src/MinMaxDC.java
UTF-8
894
3.71875
4
[]
no_license
import java.util.Arrays; /** * * @author ashutosh * Divide and Conquer Algorithm for Min/Max Finding * Reduces the number of comparisons compared to the linear algorithm */ public class MinMaxDC { public static int MinDC(int data[]){ if (data.length == 1){ return data[0]; }else if(data.length == 2){ if(data[0] < data[1]){ return data[0]; }else{ return data[1]; } }else{ int mid = (int) Math.floor((data.length) / 2); int[] dataLeft = Arrays.copyOfRange(data,0,mid); int[] dataRight = Arrays.copyOfRange(data,mid,data.length); int minLeft = MinDC(dataLeft); int minRight = MinDC(dataRight); if(minLeft < minRight){ return minLeft; }else{ return minRight; } } } public static void main(String args[]){ int data[] = {-4,-9,44,23,10,5,-99,4,5,33,58,62,39}; int min = MinDC(data); System.out.print(min); } }
true
a220dec116e0dd18ab4f6688eed41c96bec7c58f
Java
justin-cotarla/big-wiki-crew
/app/src/main/java/org/wikipedia/feed/categories/recommended/RecommendedCategoriesClient.java
UTF-8
2,143
2.109375
2
[ "Apache-2.0" ]
permissive
package org.wikipedia.feed.categories.recommended; import android.support.annotation.NonNull; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.mwapi.MwQueryPage; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.bottomcontent.MainPageReadMoreTopicTask; import java.util.Collections; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class RecommendedCategoriesClient { public interface Delegate { void run(List<MwQueryPage.Category> categories); } private static final int HISTORY_ENTRY_INDEX = 0; private static final int CATEGORY_LIMIT = 5; private CompositeDisposable disposables = new CompositeDisposable(); public void request(WikiSite wiki, Delegate callback) { disposables.add(Observable.fromCallable(new MainPageReadMoreTopicTask(HISTORY_ENTRY_INDEX)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(entry -> getCategoriesForHistoryEntry(entry, wiki, callback))); } private void getCategoriesForHistoryEntry(@NonNull final HistoryEntry entry, WikiSite wiki, final Delegate callback) { disposables.add(ServiceFactory.get(wiki).getCategoriesInPage(entry.getTitle().toString(), CATEGORY_LIMIT) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> { if (response != null && response.success() && response.query().pages() != null && !response.query().pages().isEmpty()) { return response.query().pages().get(0).categories(); } return Collections.emptyList(); }) .subscribe(results -> { callback.run((List<MwQueryPage.Category>) results); })); } }
true
abffd5395c916730bdd5829f19e371ef84364890
Java
TheAndroidMaster/APReader
/app/src/main/java/james/apreader/fragments/FeaturedFragment.java
UTF-8
1,936
2.296875
2
[ "Apache-2.0" ]
permissive
package james.apreader.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Locale; import james.apreader.R; import james.apreader.adapters.ListAdapter; import james.apreader.common.Supplier; import james.apreader.common.data.ArticleData; public class FeaturedFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { RecyclerView recycler = (RecyclerView) inflater.inflate(R.layout.fragment_recycler, container, false); recycler.setLayoutManager(new GridLayoutManager(getContext(), 1)); ArrayList<ArticleData> walls = ((Supplier) getContext().getApplicationContext()).getArticles(); Collections.sort(walls, new Comparator<ArticleData>() { @Override public int compare(ArticleData lhs, ArticleData rhs) { DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH); try { Date lhd = format.parse(lhs.date), rhd = format.parse(rhs.date); return rhd.compareTo(lhd); } catch (ParseException e) { e.printStackTrace(); return 0; } } }); ListAdapter adapter = new ListAdapter(getActivity(), walls); recycler.setAdapter(adapter); return recycler; } }
true
ab8fc0ebc36f8af4064ca2038fcd1b3a3571c1b2
Java
SolaceSamples/solace-samples-javarto
/src/main/java/com/solace/samples/javarto/features/RRDirectRequester.java
UTF-8
8,701
2.484375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2004-2021 Solace Corporation. All rights reserved. * */ package com.solace.samples.javarto.features; import java.nio.ByteBuffer; import java.util.logging.Level; import com.solacesystems.solclientj.core.SolEnum; import com.solacesystems.solclientj.core.Solclient; import com.solacesystems.solclientj.core.SolclientException; import com.solacesystems.solclientj.core.event.SessionEventCallback; import com.solacesystems.solclientj.core.handle.ContextHandle; import com.solacesystems.solclientj.core.handle.MessageHandle; import com.solacesystems.solclientj.core.handle.SessionHandle; import com.solacesystems.solclientj.core.resource.Topic; /** * RRDirectRequester.java * * This sample shows how to implement a Requester for direct Request-Reply * messaging, where * * <dl> * <dt>RRDirectRequester * <dd>A message Endpoint that sends a request message and waits to receive a * reply message as a response. * <dt>RRDirectReplier * <dd>A message Endpoint that waits to receive a request message and responses * to it by sending a reply message. * </dl> * * <pre> * |-------------------| ---RequestTopic --> |------------------| * | RRDirectRequester | | RRDirectReplier | * |-------------------| <--ReplyToTopic---- |------------------| * </pre> * * <strong>This sample illustrates the ease of use of concepts, and may not be * GC-free.<br> * See Perf* samples for GC-free examples. </strong> * */ public class RRDirectRequester extends AbstractSample { private SessionHandle sessionHandle = Solclient.Allocator .newSessionHandle(); private ContextHandle contextHandle = Solclient.Allocator .newContextHandle(); private MessageHandle txMessageHandle = Solclient.Allocator .newMessageHandle(); private MessageHandle rxMessageHandle = Solclient.Allocator .newMessageHandle(); private ByteBuffer txContent = ByteBuffer.allocateDirect(200); private ByteBuffer rxContent = ByteBuffer.allocateDirect(200); @Override protected void printUsage(boolean secureSession) { String usage = ArgumentsParser.getCommonUsage(secureSession); usage += "This sample:\n"; usage += "\t[-t topic]\t Topic, default:" + SampleUtils.SAMPLE_TOPIC + "\n"; usage += "\t[-n number]\t Number of request messages to send, default: 5\n"; System.out.println(usage); finish(1); } public void sendRequests(int maxRequestMessages, String aDestinationName) { Topic topic = Solclient.Allocator.newTopic(aDestinationName); int rc = 0; if (!txMessageHandle.isBound()) { // Allocate the message rc = Solclient.createMessageForHandle(txMessageHandle); assertReturnCode("Solclient.createMessageForHandle()", rc, SolEnum.ReturnCode.OK); } /* Set the message delivery mode. */ txMessageHandle .setMessageDeliveryMode(SolEnum.MessageDeliveryMode.DIRECT); // Set the destination/topic txMessageHandle.setDestination(topic); for (int i = 0; i < maxRequestMessages; i++) { txContent.clear(); txContent.putInt(i); txContent.flip(); /* Add some content to the message. */ txMessageHandle.setBinaryAttachment(txContent); /* Send the message. */ print("Sending Request [" + i + "] and blocking for a response"); rc = sessionHandle.sendRequest(txMessageHandle, rxMessageHandle, 5000); print("Response was "+ rc); assertReturnCode("aSessionHandle.sendRequest()", rc, SolEnum.ReturnCode.OK); // Clear the buffer and copy message content into it. rxContent.clear(); rxMessageHandle.getBinaryAttachment(rxContent); rxContent.flip(); int response = rxContent.getInt(); print("Received response [" + response + "]"); // Do some assertion for the expected response if (response != i) { throw new IllegalStateException(String.format( "[%d] was expected, got this response instead [%d]", i, response)); } if (rxMessageHandle.isBound()) { // Clean up time print("rxMessageHandle.destroy()"); rxMessageHandle.destroy(); } } // EndFor } /** * This is the main method of the sample */ @Override protected void run(String[] args, SessionConfiguration config, Level logLevel) throws SolclientException { // Determine a destinationName (topic), default to // SampleUtils.SAMPLE_TOPIC String destinationName = config.getArgBag().get("-t"); if (destinationName == null) { destinationName = SampleUtils.SAMPLE_TOPIC; } int numberOfRequestMessages = 5; String strCount = config.getArgBag().get("-n"); if (strCount != null) { try { numberOfRequestMessages = Integer.parseInt(strCount); } catch (NumberFormatException e) { printUsage(config instanceof SecureSessionConfiguration); } } // Init print(" Initializing the Java RTO Messaging API..."); int rc = Solclient.init(new String[0]); assertReturnCode("Solclient.init()", rc, SolEnum.ReturnCode.OK); // Set a log level (not necessary as there is a default) Solclient.setLogLevel(logLevel); // Context print(" Creating a context ..."); rc = Solclient.createContextForHandle(contextHandle, new String[0]); assertReturnCode("Solclient.createContext()", rc, SolEnum.ReturnCode.OK); /* Create a Session */ print(" Create a Session."); int spareRoom = 10; String[] sessionProps = getSessionProps(config, spareRoom); int sessionPropsIndex = sessionProps.length - spareRoom; /* * Note: Reapplying subscriptions allows Sessions to reconnect after * failure and have all their subscriptions automatically restored. For * Sessions with many subscriptions this can increase the amount of time * required for a successful reconnect. */ sessionProps[sessionPropsIndex++] = SessionHandle.PROPERTIES.REAPPLY_SUBSCRIPTIONS; sessionProps[sessionPropsIndex++] = SolEnum.BooleanValue.ENABLE; /* * Note: Including meta data fields such as sender timestamp, sender ID, * and sequence number will reduce the maximum attainable throughput as * significant extra encoding/decoding is required. This is true whether * the fields are autogenerated or manually added. */ sessionProps[sessionPropsIndex++] = SessionHandle.PROPERTIES.GENERATE_SEND_TIMESTAMPS; sessionProps[sessionPropsIndex++] = SolEnum.BooleanValue.ENABLE; sessionProps[sessionPropsIndex++] = SessionHandle.PROPERTIES.GENERATE_SENDER_ID; sessionProps[sessionPropsIndex++] = SolEnum.BooleanValue.ENABLE; sessionProps[sessionPropsIndex++] = SessionHandle.PROPERTIES.GENERATE_SEQUENCE_NUMBER; sessionProps[sessionPropsIndex++] = SolEnum.BooleanValue.ENABLE; /* * The certificate validation property is ignored on non-SSL sessions. * For simple demo applications, disable it on SSL sesssions (host * string begins with tcps:) so a local trusted root and certificate * store is not required. See the API users guide for documentation on * how to setup a trusted root so the servers certificate returned on * the secure connection can be verified if this is desired. */ sessionProps[sessionPropsIndex++] = SessionHandle.PROPERTIES.SSL_VALIDATE_CERTIFICATE; sessionProps[sessionPropsIndex++] = SolEnum.BooleanValue.DISABLE; SessionEventCallback sessionEventCallback = getDefaultSessionEventCallback(); MessageCallbackSample messageCallback = getMessageCallback(false); /* Create the Session. */ rc = contextHandle.createSessionForHandle(sessionHandle, sessionProps, messageCallback, sessionEventCallback); assertReturnCode("contextHandle.createSession() - session", rc, SolEnum.ReturnCode.OK); /* Connect the Session. */ print(" Connecting session ..."); rc = sessionHandle.connect(); assertReturnCode("sessionHandle.connect()", rc, SolEnum.ReturnCode.OK); /* Send the requests and wait for the responses. */ sendRequests(numberOfRequestMessages, destinationName); // ///////////////////////////////////////////// SHUTDOWN // /////////////////////////////////// print("Test Passed"); print("Run() DONE"); } /** * Invoked when the sample finishes */ @Override protected void finish(int status) { /************************************************************************* * Cleanup *************************************************************************/ finish_DestroyHandle(txMessageHandle, "messageHandle"); finish_Disconnect(sessionHandle); finish_DestroyHandle(sessionHandle, "sessionHandle"); finish_DestroyHandle(contextHandle, "contextHandle"); finish_Solclient(); } /** * Boilerplate, calls {@link #run(String[]) * @param args */ public static void main(String[] args) { RRDirectRequester sample = new RRDirectRequester(); sample.run(args); } }
true
cfec29eeeaa46f1daba5141a0a18296b4602389b
Java
El-houssine/Mini-projet-J2EE
/src/metier/LivreService.java
UTF-8
1,873
2.65625
3
[]
no_license
package metier; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import model.Livre; public class LivreService { private List<Livre>listLivre=new ArrayList<Livre>();; public void valider(Livre lvr) { try { Class.forName("com.mysql.jdbc.Driver"); Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/ecomlivre","root",""); PreparedStatement ps=connection.prepareStatement("INSERT INTO livre( titre, isbn, auteur, annee, nbPage, prix) VALUES(?,?,?,?,?,?)"); ps.setString(1,lvr.getTitre()); ps.setString(2,lvr.getIsbn()); ps.setString(3,lvr.getAuteur()); ps.setString(4,lvr.getAnneeParution()); ps.setInt(5,lvr.getNbPage()); ps.setDouble(6,lvr.getPrix()); ps.executeUpdate(); ps.close(); connection.close(); System.out.println("bien fait"); } catch (Exception e) { e.getMessage(); } } //liste Produit public List<Livre>livres() { try { Class.forName("com.mysql.jdbc.Driver"); Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/ecomlivre","root",""); PreparedStatement ps=connection.prepareStatement("SELECT * FROM livre"); ResultSet rs=ps.executeQuery(); while (rs.next()) { Livre lvr=new Livre(); lvr.setTitre(rs.getString("titre")); lvr.setIsbn(rs.getString("isbn")); lvr.setAuteur(rs.getNString("auteur")); lvr.setAnneeParution(rs.getNString("annee")); lvr.setNbPage(rs.getInt("nbPage")); lvr.setPrix(rs.getDouble("prix")); listLivre.add(lvr); System.out.println("bien "); } rs.close(); ps.close(); connection.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return listLivre; } }
true
0f623b90b918574edee93a897e20b7f7972187c1
Java
lucklyperson/CarTypeDemo
/app/src/main/java/com/example/wu/cartypedemo/MainActivity.java
UTF-8
9,591
2.078125
2
[]
no_license
package com.example.wu.cartypedemo; import android.animation.ObjectAnimator; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { @BindView(R.id.tv_tip) TextView tvTip; @BindView(R.id.recyclerView_brand) RecyclerView recyclerViewBrand; @BindView(R.id.recyclerView_type) RecyclerView recyclerViewType; @BindView(R.id.rl_type) RelativeLayout rlType; @BindView(R.id.recyclerView_color) RecyclerView recyclerViewColor; private int screenWidth; private CarColorAdapter carColorAdapter; private CarBrandAdapter carBrandAdapter; private CarTypeAdapter carTypeAdapter; private List<Car> brandList; private List<Car> typeList; private List<String> colorList; private Car carResult; //选择车型的结果 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initView(); initColorRecyclerView(); initBrandRecyclerView(); initTypeRecyclerView(); setListener(); } private void initView() { //获取屏幕的宽度,设置偏移量 screenWidth = DeviceScreen.getScreenWidth(this); rlType.setTranslationX(screenWidth); recyclerViewColor.setTranslationX(screenWidth); } private void setListener() { carBrandAdapter.setOnItemClickListener(new OnAdapterClickListener() { @Override public void onItemClick(int position) { float startX = recyclerViewColor.getTranslationX(); setAnimation(rlType, screenWidth, screenWidth / 3); setAnimation(recyclerViewColor, startX, screenWidth); String id = brandList.get(position).getId(); typeList.clear(); carTypeAdapter.notifyDataSetChanged(); getCarTypeByCarId(id); carResult = new Car(); carResult.setName(brandList.get(position).getName()); } }); carTypeAdapter.setOnItemClickListener(new OnAdapterClickListener() { @Override public void onItemClick(int position) { setAnimation(recyclerViewColor, screenWidth, screenWidth / 3 * 2); carResult.setType(typeList.get(position).getName()); } }); carColorAdapter.setOnItemClickListener(new OnAdapterClickListener() { @Override public void onItemClick(int position) { float startX1 = rlType.getTranslationX(); float startX2 = recyclerViewColor.getTranslationX(); setAnimation(rlType, startX1, screenWidth); setAnimation(recyclerViewColor, startX2, screenWidth); carResult.setColor(colorList.get(position)); StringBuffer sb = new StringBuffer(); sb.append(carResult.getName()) .append(" · " + carResult.getType()) .append(" · " + carResult.getColor()); } }); } private void initBrandRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerViewBrand.setLayoutManager(linearLayoutManager); brandList = new ArrayList<>(); carBrandAdapter = new CarBrandAdapter(brandList, this); recyclerViewBrand.setAdapter(carBrandAdapter); recyclerViewBrand.setItemAnimator(new DefaultItemAnimator()); getCarBrandData(); } private void initTypeRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerViewType.setLayoutManager(linearLayoutManager); typeList = new ArrayList<>(); carTypeAdapter = new CarTypeAdapter(typeList, this); recyclerViewType.setAdapter(carTypeAdapter); recyclerViewType.setItemAnimator(new DefaultItemAnimator()); } private void initColorRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerViewColor.setLayoutManager(linearLayoutManager); colorList = new ArrayList<>(); colorList.add("白色"); colorList.add("红色"); colorList.add("黑色"); colorList.add("银色"); colorList.add("香槟色"); colorList.add("灰色"); colorList.add("蓝色"); colorList.add("黄色"); colorList.add("绿色"); colorList.add("咖啡色"); colorList.add("橙色"); colorList.add("其他"); carColorAdapter = new CarColorAdapter(colorList, this); recyclerViewColor.setAdapter(carColorAdapter); } private void setAnimation(View view, float startOffSet, float offSet) { ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "translationX", startOffSet, offSet); objectAnimator.setDuration(500); objectAnimator.start(); } /** * 获取车商标 */ private void getCarBrandData() { RetrofitService retrofitService = RetrofitServiceUtil.getRetrofitServiceWithHeader(); retrofitService.getCarBrandList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Result<Car>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.d("MainActivity", "e = " + e.getMessage()); } @Override public void onNext(Result<Car> result) { Log.d("MainActivity", "result = " + result); if (TextUtils.equals("0", result.getStatus())) { List<Car> data = result.getResult(); brandList.clear(); dataSort(data); brandList.addAll(data); carBrandAdapter.notifyDataSetChanged(); } } }); } /** * 获取车标获取车型 */ private void getCarTypeByCarId(String carId) { RetrofitService retrofitService = RetrofitServiceUtil.getRetrofitServiceWithHeader(); retrofitService.getCarTypeById(carId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Result<Car>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Result<Car> result) { if (TextUtils.equals("0", result.getStatus())) { List<Car> data = result.getResult(); for (Car car : data) { List<Car> cars = car.getCarlist(); typeList.addAll(cars); } carTypeAdapter.notifyDataSetChanged(); } } }); } /** * 排序 * * @param data data */ private void dataSort(List<Car> data) { Comparator<? super Car> comparator = new Comparator<Car>() { @Override public int compare(Car var1, Car var2) { return var1.getInitial().toLowerCase().compareTo(var2.getInitial().toLowerCase()); } }; Collections.sort(data, comparator); } public class Result<T> implements Serializable { String status; String msg; List<T> result; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<T> getResult() { return result; } public void setResult(List<T> result) { this.result = result; } @Override public String toString() { return "Result{" + "status='" + status + '\'' + ", msg='" + msg + '\'' + ", result=" + result + '}'; } } }
true
b567cf2f0f3033050632662355be45ccaa96b9de
Java
rrabit42/Malware_Project_EWHA
/src/androidx/work/impl/background/systemalarm/CommandHandler.java
UTF-8
10,651
1.875
2
[]
no_license
package androidx.work.impl.background.systemalarm; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.support.annotation.WorkerThread; import androidx.work.Logger; import androidx.work.impl.ExecutionListener; import androidx.work.impl.WorkDatabase; import java.util.HashMap; import java.util.Map; @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) public class CommandHandler implements ExecutionListener { static final String ACTION_CONSTRAINTS_CHANGED = "ACTION_CONSTRAINTS_CHANGED"; static final String ACTION_DELAY_MET = "ACTION_DELAY_MET"; static final String ACTION_EXECUTION_COMPLETED = "ACTION_EXECUTION_COMPLETED"; static final String ACTION_RESCHEDULE = "ACTION_RESCHEDULE"; static final String ACTION_SCHEDULE_WORK = "ACTION_SCHEDULE_WORK"; static final String ACTION_STOP_WORK = "ACTION_STOP_WORK"; private static final String KEY_NEEDS_RESCHEDULE = "KEY_NEEDS_RESCHEDULE"; private static final String KEY_WORKSPEC_ID = "KEY_WORKSPEC_ID"; private static final String TAG = Logger.tagWithPrefix("CommandHandler"); static final long WORK_PROCESSING_TIME_IN_MS = 600000L; private final Context mContext; private final Object mLock; private final Map<String, ExecutionListener> mPendingDelayMet; CommandHandler(@NonNull Context paramContext) { this.mContext = paramContext; this.mPendingDelayMet = new HashMap(); this.mLock = new Object(); } static Intent createConstraintsChangedIntent(@NonNull Context paramContext) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_CONSTRAINTS_CHANGED"); return intent; } static Intent createDelayMetIntent(@NonNull Context paramContext, @NonNull String paramString) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_DELAY_MET"); intent.putExtra("KEY_WORKSPEC_ID", paramString); return intent; } static Intent createExecutionCompletedIntent(@NonNull Context paramContext, @NonNull String paramString, boolean paramBoolean) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_EXECUTION_COMPLETED"); intent.putExtra("KEY_WORKSPEC_ID", paramString); intent.putExtra("KEY_NEEDS_RESCHEDULE", paramBoolean); return intent; } static Intent createRescheduleIntent(@NonNull Context paramContext) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_RESCHEDULE"); return intent; } static Intent createScheduleWorkIntent(@NonNull Context paramContext, @NonNull String paramString) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_SCHEDULE_WORK"); intent.putExtra("KEY_WORKSPEC_ID", paramString); return intent; } static Intent createStopWorkIntent(@NonNull Context paramContext, @NonNull String paramString) { Intent intent = new Intent(paramContext, SystemAlarmService.class); intent.setAction("ACTION_STOP_WORK"); intent.putExtra("KEY_WORKSPEC_ID", paramString); return intent; } private void handleConstraintsChanged(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { Logger.get().debug(TAG, String.format("Handling constraints changed %s", new Object[] { paramIntent }), new Throwable[0]); (new ConstraintsCommandHandler(this.mContext, paramInt, paramSystemAlarmDispatcher)).handleConstraintsChanged(); } private void handleDelayMet(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { Bundle bundle = paramIntent.getExtras(); synchronized (this.mLock) { String str; Logger.get().debug(TAG, (str = bundle.getString("KEY_WORKSPEC_ID")).format("Handing delay met for %s", new Object[] { str }), new Throwable[0]); if (!this.mPendingDelayMet.containsKey(str)) { DelayMetCommandHandler delayMetCommandHandler = new DelayMetCommandHandler(this.mContext, paramInt, str, paramSystemAlarmDispatcher); this.mPendingDelayMet.put(str, delayMetCommandHandler); delayMetCommandHandler.handleProcessWork(); } else { Logger.get().debug(TAG, String.format("WorkSpec %s is already being handled for ACTION_DELAY_MET", new Object[] { str }), new Throwable[0]); } return; } } private void handleExecutionCompleted(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { Bundle bundle = paramIntent.getExtras(); String str = bundle.getString("KEY_WORKSPEC_ID"); boolean bool = bundle.getBoolean("KEY_NEEDS_RESCHEDULE"); Logger.get().debug(TAG, String.format("Handling onExecutionCompleted %s, %s", new Object[] { paramIntent, Integer.valueOf(paramInt) }), new Throwable[0]); onExecuted(str, bool); } private void handleReschedule(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { Logger.get().debug(TAG, String.format("Handling reschedule %s, %s", new Object[] { paramIntent, Integer.valueOf(paramInt) }), new Throwable[0]); paramSystemAlarmDispatcher.getWorkManager().rescheduleEligibleWork(); } private void handleScheduleWorkIntent(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { String str; Logger.get().debug(TAG, (str = paramIntent.getExtras().getString("KEY_WORKSPEC_ID")).format("Handling schedule work for %s", new Object[] { str }), new Throwable[0]); workDatabase = paramSystemAlarmDispatcher.getWorkManager().getWorkDatabase(); workDatabase.beginTransaction(); try { Logger logger; String str1 = workDatabase.workSpecDao().getWorkSpec(str); if (str1 == null) { logger = Logger.get(); str1 = TAG; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Skipping scheduling "); stringBuilder.append(str); stringBuilder.append(" because it's no longer in the DB"); logger.warning(str1, stringBuilder.toString(), new Throwable[0]); return; } if (str1.state.isFinished()) { logger = Logger.get(); str1 = TAG; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Skipping scheduling "); stringBuilder.append(str); stringBuilder.append("because it is finished."); logger.warning(str1, stringBuilder.toString(), new Throwable[0]); return; } long l = str1.calculateNextRunTime(); if (!str1.hasConstraints()) { Logger.get().debug(TAG, String.format("Setting up Alarms for %s at %s", new Object[] { str, Long.valueOf(l) }), new Throwable[0]); Alarms.setAlarm(this.mContext, logger.getWorkManager(), str, l); } else { Logger.get().debug(TAG, String.format("Opportunistically setting an alarm for %s at %s", new Object[] { str, Long.valueOf(l) }), new Throwable[0]); Alarms.setAlarm(this.mContext, logger.getWorkManager(), str, l); logger.postOnMainThread(new SystemAlarmDispatcher.AddRunnable(logger, createConstraintsChangedIntent(this.mContext), paramInt)); } workDatabase.setTransactionSuccessful(); return; } finally { workDatabase.endTransaction(); } } private void handleStopWork(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { String str; Logger.get().debug(TAG, (str = paramIntent.getExtras().getString("KEY_WORKSPEC_ID")).format("Handing stopWork work for %s", new Object[] { str }), new Throwable[0]); paramSystemAlarmDispatcher.getWorkManager().stopWork(str); Alarms.cancelAlarm(this.mContext, paramSystemAlarmDispatcher.getWorkManager(), str); paramSystemAlarmDispatcher.onExecuted(str, false); } private static boolean hasKeys(@Nullable Bundle paramBundle, @NonNull String... paramVarArgs) { if (paramBundle != null) { if (paramBundle.isEmpty()) return false; int i = paramVarArgs.length; for (byte b = 0; b < i; b++) { if (paramBundle.get(paramVarArgs[b]) == null) return false; } return true; } return false; } boolean hasPendingCommands() { synchronized (this.mLock) { if (!this.mPendingDelayMet.isEmpty()) return true; } boolean bool = false; /* monitor exit ClassFileLocalVariableReferenceExpression{type=ObjectType{java/lang/Object}, name=SYNTHETIC_LOCAL_VARIABLE_2} */ return bool; } public void onExecuted(@NonNull String paramString, boolean paramBoolean) { synchronized (this.mLock) { ExecutionListener executionListener = (ExecutionListener)this.mPendingDelayMet.remove(paramString); if (executionListener != null) executionListener.onExecuted(paramString, paramBoolean); return; } } @WorkerThread void onHandleIntent(@NonNull Intent paramIntent, int paramInt, @NonNull SystemAlarmDispatcher paramSystemAlarmDispatcher) { String str = paramIntent.getAction(); if ("ACTION_CONSTRAINTS_CHANGED".equals(str)) { handleConstraintsChanged(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } if ("ACTION_RESCHEDULE".equals(str)) { handleReschedule(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } if (!hasKeys(paramIntent.getExtras(), new String[] { "KEY_WORKSPEC_ID" })) { Logger.get().error(TAG, String.format("Invalid request for %s, requires %s.", new Object[] { str, "KEY_WORKSPEC_ID" }), new Throwable[0]); return; } if ("ACTION_SCHEDULE_WORK".equals(str)) { handleScheduleWorkIntent(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } if ("ACTION_DELAY_MET".equals(str)) { handleDelayMet(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } if ("ACTION_STOP_WORK".equals(str)) { handleStopWork(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } if ("ACTION_EXECUTION_COMPLETED".equals(str)) { handleExecutionCompleted(paramIntent, paramInt, paramSystemAlarmDispatcher); return; } Logger.get().warning(TAG, String.format("Ignoring intent %s", new Object[] { paramIntent }), new Throwable[0]); } }
true
0c1f67c25c2dd21e7fe5ce3a900f770a73c7e2f6
Java
cdahmedeh/SMLabTestingSimulation
/SMLabTestingSimulation_ABSModJ/src/org/smlabtesting/simabs/model/ModelPrinter.java
UTF-8
4,860
2.75
3
[]
no_license
package org.smlabtesting.simabs.model; import static org.smlabtesting.simabs.entity.QNewSamples.REGULAR; import static org.smlabtesting.simabs.entity.QNewSamples.RUSH; import org.smlabtesting.simabs.entity.RSampleHolder; /** * Helper methods to handle printing of the model onto the console. Printing * code would need templating to be more readable. */ public class ModelPrinter { public static void showBasicModelInfo(SMLabModel model) { System.out.println("-------- Model Information -------- \n"); System.out .print(String.format( "Clock: %f, \n" + "Q.NewSamples[REGULAR].n: %d \n" + "Q.NewSamples[RUSH].n: %d \n" + "\n" + "Station(L/U): \n" + " Q.UnloadBuffer.n: %d, Q.UnloadBuffer.nEmpty: %d, \n" + " numFailedStationEntries[0]: %d \n" + " R.LoadUnloadMachine.busy: %b \n" + " Q.RacetrackLine[UL].n: %d \n", model.getClock(), model.qNewSamples[REGULAR].n(), model.qNewSamples[RUSH].n(), model.qUnloadBuffer.n(), model.qUnloadBuffer.nEmpty, model.output.totalFailedStationEntries[0], model.rLoadUnloadMachine.busy, model.qRacetrackLine[0].n())); for (int stationId = 1; stationId < 6; stationId++) { System.out.print(String.format( "Station(%d): \n" + " Q.TestCellBuffer.n: %d, totalFailedStationEntries: %d\n" , stationId, model.qTestCellBuffer[stationId].n(), model.output.totalFailedStationEntries[stationId]) ); for (int machineId = 0; machineId < model.parameters.numCellMachines[stationId]; machineId++) { System.out.print(String.format( " RC.TestingMachine[%d][%d].status: %s \n" , stationId, machineId, model.rcTestingMachine[stationId][machineId].status) ); } System.out.println(String.format( " Q.RacetrackLine[%d].n: %d" , stationId, model.qRacetrackLine[stationId].n()) ); } } /** * Prints a visual representation of the 48 racetrack slots, for logging purposes. */ public static void printRacetrackView(SMLabModel model) { //Print the 'top' row, so belt indexes 15-36 System.out.println(" ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___"); for(int i = 15; i < 37; i++){ String sHolder = getSlotRepresentation(model, i); System.out.print("|"+sHolder); } System.out.println("|"); System.out.println("|___|Ex4|___|___|___|In4|___|___|___|Ex3|___|___|___|In3|___|___|___|Ex2|___|___|___|In2|"); //Print the left and right sides of the belt, so right belt indexes = 37, 38, and left belt indexes = 14, 13 String innerBeltSpace = " "; System.out.println("|"+getSlotRepresentation(model, 14)+"|"+innerBeltSpace+"|"+getSlotRepresentation(model, 37)+"|"); System.out.println("|___|"+innerBeltSpace+"|___|"); System.out.println("|"+getSlotRepresentation(model, 13)+"|"+innerBeltSpace+"|"+getSlotRepresentation(model, 38)+"|"); //Print the bottom side of the belt, so belt indexes 39-47 and 0-12 String bottom = ""; System.out.println("|___|___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___|___|"); for(int i = 39; i < (47 + 13 + 1); ++i){ String sHolder = getSlotRepresentation(model, i%48); bottom =sHolder +"|" + bottom; } System.out.println("|"+bottom); System.out.println("|In5|___|___|___|Ex5|___|___|___|In0|___|___|___|Ex0|___|___|___|In1|___|___|___|Ex1|___|"); System.out.println(); } /** * Determines whether a slot on the racetrack (at index slotId) has nothing (" "), an empty sample holder ("[ ]"), or a sample holder with a sample ("[x]") * @param slotId index of the slot * @return the string representing the slot content (or lack thereof) */ private static String getSlotRepresentation(SMLabModel model, int slotId){ String sHolder = " "; RSampleHolder sampleHolder = model.udp.getSampleHolder(model.rqRacetrack.slots.get(slotId)); if(sampleHolder != null && sampleHolder.sample != null){ sHolder = "[x]"; } else if(sampleHolder != null && sampleHolder.sample == null){ sHolder = "[ ]"; } return sHolder; } public static void printOutputs(SMLabModel model) { model.output.percentageLateRegularSamples(); model.output.percentageLateRushSamples(); System.out.println("Regular percentage late: "+model.output.percentageLateRegularSamples); System.out.println("Rush percentage late: "+model.output.percentageLateRushSamples); //Print failed station entries System.out.print("Total Failed Station Entries: < "); System.out.print(model.output.totalFailedStationEntries[0]); for(int i = 1; i < 6; i++){ System.out.print(", "+ model.output.totalFailedStationEntries[i]); } System.out.print(" > "); System.out.println(); } }
true
70e0c513f3d6baafad229da62782f30d5409851b
Java
talk2morris/TEST-PROJECT
/omod/src/main/java/org/openmrs/module/patientindextracing/utility/Utils.java
UTF-8
11,573
1.703125
2
[]
no_license
package org.openmrs.module.patientindextracing.utility; import javax.servlet.http.HttpServletRequest; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; import org.codehaus.jackson.map.ObjectMapper; import org.openmrs.Encounter; import org.openmrs.Obs; import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.api.context.Context; import org.openmrs.module.patientindextracing.omodmodels.DBConnection; import org.openmrs.module.patientindextracing.omodmodels.Version; import org.openmrs.util.OpenmrsUtil; public class Utils { public final static int HIV_Enrollment_Encounter_Type_Id = 14; public final static int Pharmacy_Encounter_Type_Id = 13; public final static int Laboratory_Encounter_Type_Id = 11; public final static int Care_card_Encounter_Type_Id = 12; public final static int Adult_Ped_Initial_Encounter_Type_Id = 8; public final static int Client_Tracking_And_Termination_Encounter_Type_Id = 15; public final static int Client_Intake_Form_Encounter_Type_Id = 20; public final static int Patient_PEPFAR_Id = 3; public final static int Patient_Hospital_Id = 3; public final static int Patient_RNLSerial_No = 3; public final static int Reason_For_Termination = 165470; public final static int Antenatal_Registration_Encounter_Type_Id = 10; public final static int Delivery_Encounter_Type_Id = 16; public final static int Child_Birth_Detail_Encounter_Type_Id = 9; public final static int Child_Followup_Encounter_Type_Id = 18; public final static int Partner_register_Encounter_Id = 19;//Check this data from the database when there is record public final static int Admission_Simple_Client_intake = 2; public final static int Risk_Stratification_PED_Encounter = 33; public final static int Risk_Stratification_ADULT_Encounter = 34; public static String getMacAddress() { // temp for NELSON return "ISMAILTEST"; // InetAddress ip; // try { // // ip = InetAddress.getLocalHost(); // //System.out.println("Current IP address : " + ip.getHostAddress()); // // NetworkInterface network = NetworkInterface.getByInetAddress(ip); // // byte[] mac = network.getHardwareAddress(); // // //System.out.print("Current MAC address : "); // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < mac.length; i++) { // sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); // } // // //System.out.println(sb.toString()); // return sb.toString(); // // } // catch (UnknownHostException e) { // // e.printStackTrace(); // // } // catch (SocketException e) { // // e.printStackTrace(); // // } // // return null; } public static String getLoggedInUser() { return Context.getAuthenticatedUser().toString(); } public static String getFacilityName() { return Context.getAdministrationService().getGlobalProperty("Facility_Name"); } public static String getFacilityLocalId() { return Context.getAdministrationService().getGlobalProperty("facility_local_id"); } public static String getNigeriaQualId() { return Context.getAdministrationService().getGlobalProperty("nigeria_qual_id"); } public static String getFacilityDATIMId() { return Context.getAdministrationService().getGlobalProperty("facility_datim_code"); } public static String getIPFullName() { return Context.getAdministrationService().getGlobalProperty("partner_full_name"); } public static String getIPShortName() { return Context.getAdministrationService().getGlobalProperty("partner_short_name"); } //date is always saved as yyyy-MM-dd public static Date getLastNDRDate() { String lastRunDateString = Context.getAdministrationService().getGlobalProperty("ndr_last_run_date"); if (String.valueOf(lastRunDateString).isEmpty()) { return null; } else { try { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(lastRunDateString); } catch (Exception e) { System.out.println("Last Date was not in the correct format"); return null; } } } public static String getBiometricServer() { return Context.getAdministrationService().getGlobalProperty("biometric_server"); } public static Version getVersionInfo() throws URISyntaxException, IOException { File f = new File(Utils.class.getClassLoader().getResource("version.json").getFile()); ObjectMapper mapper = new ObjectMapper(); Version versionModel = mapper.readValue(f, Version.class); return versionModel; } public static Version getNmrsVersion() { URL resource = Utils.class.getClassLoader().getResource("version.json"); try { File filePath = Paths.get(resource.toURI()).toFile(); ObjectMapper mapper = new ObjectMapper(); Version versionModel = mapper.readValue(filePath, Version.class); return versionModel; } catch (Exception e) { } return null; } public static void updateLast_NDR_Run_Date(Date date) { String dateString = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); Context.getAdministrationService().updateGlobalProperty("ndr_last_run_date", dateString); } public static String getVisitId(Patient pts, Encounter enc) { return enc.getEncounterId().toString(); //getVisit().getVisitId().toString(); /*String dateString = new SimpleDateFormat("dd-MM-yyyy").format(enc.getEncounterDatetime()); return pts.getPatientIdentifier(3).getIdentifier() + "-" + dateString;*/ } public static Obs extractObs(int conceptID, List<Obs> obsList) { if (obsList == null) { return null; } return obsList.stream().filter(ele -> ele.getConcept().getConceptId() == conceptID).findFirst().orElse(null); } public static Obs extractObsByValues(int conceptID, List<Obs> obsList) { if (obsList == null) { return null; } return obsList.stream().filter(ele -> ele.getValueCoded().getId() == conceptID).findFirst().orElse(null); } public static Encounter getLastEncounter(Patient patient) { List<Encounter> hivEnrollmentEncounter = Context.getEncounterService() .getEncountersByPatient(patient); //sort the list by date hivEnrollmentEncounter.sort(Comparator.comparing(Encounter::getEncounterDatetime)); int size = hivEnrollmentEncounter.size(); return hivEnrollmentEncounter.get(size - 1); } public static List<Obs> getCareCardObs(Patient patient, Date endDate) { List<Encounter> hivEnrollmentEncounter = Context.getEncounterService() .getEncountersByPatient(patient).stream() .filter(x -> x.getEncounterDatetime().before(endDate) && x.getEncounterType().getEncounterTypeId() == Care_card_Encounter_Type_Id) .sorted(Comparator.comparing(Encounter::getEncounterDatetime)) .collect(Collectors.toList()); if (hivEnrollmentEncounter != null && hivEnrollmentEncounter.size() > 0) { int lastIndex = hivEnrollmentEncounter.size() - 1; return new ArrayList<>(hivEnrollmentEncounter.get(lastIndex).getAllObs(false)); } else { return null; } } public static List<Obs> getHIVEnrollmentObs(Patient patient) { Optional<Encounter> hivEnrollmentEncounter = Context.getEncounterService() .getEncountersByPatient(patient).stream() .filter(x -> x.getEncounterType().getEncounterTypeId() == HIV_Enrollment_Encounter_Type_Id) .findAny(); if (hivEnrollmentEncounter != null && hivEnrollmentEncounter.isPresent()) { return new ArrayList<>(hivEnrollmentEncounter.get().getAllObs(false)); } return null; } public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException { XMLGregorianCalendar cal = null; if (date != null) { cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd").format(date)); } return cal; } public static XMLGregorianCalendar getXmlDateTime(Date date) throws DatatypeConfigurationException { XMLGregorianCalendar cal = null; if (date != null) { cal = DatatypeFactory.newInstance().newXMLGregorianCalendar( new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date)); } return cal; } public static String formatDate(Date date) { return formatDate(date, "dd/MM/yyyy"); } public static String formatDate(Date date, String format) { String dateString = ""; if (date != null) { SimpleDateFormat df = new SimpleDateFormat(format); dateString = df.format(date); } return dateString; } public static String getPatientPEPFARId(Patient patient) { PatientIdentifier patientId = patient.getPatientIdentifier(Patient_PEPFAR_Id); if (patientId != null) { return patientId.getIdentifier(); } else { return patient.getPatientIdentifier(4).getIdentifier(); } } public static String getPatientHospitalNo(Patient patient) { PatientIdentifier patientId = patient.getPatientIdentifier(ConstantsUtil.HOSPITAL_IDENTIFIER_INDEX); if (patientId != null) { return patientId.getIdentifier(); } else { return ""; } } public static String getPatientRNLSerialNo(Patient patient) { PatientIdentifier patientId = patient.getPatientIdentifier(Patient_RNLSerial_No); if (patientId != null) { return patientId.getIdentifier(); } else { return ""; } } /*public String ensureTodayDownloadFolderExist(String parentFolder, HttpServletRequest request) { //create today's folder String dateString = new SimpleDateFormat("dd-MM-yyyy").format(new Date()); String todayFolders = parentFolder + "/" + dateString; File dir = new File(todayFolders); Boolean b = dir.mkdir(); System.out.println("creating folder : " + todayFolders + "was successful : " + b); return todayFolders; }*/ public static void ShowSystemProps() { System.getProperties().list(System.out); } public static DBConnection getNmrsConnectionDetails() { DBConnection result = new DBConnection(); try { // // throw new FileNotFoundException("property file '" + appDirectory + "' not found in the classpath"); //starts here Properties props = new Properties(); props = OpenmrsUtil.getRuntimeProperties("openmrs"); if (props == null) { props = OpenmrsUtil.getRuntimeProperties("openmrs-standalone"); } result.setUsername(props.getProperty("connection.username")); result.setPassword(props.getProperty("connection.password")); result.setUrl(props.getProperty("connection.url")); } catch (Exception ex) { System.err.println(ex.getMessage()); //LoggerUtils.write(Utils.class.getName(), ex.getMessage(), LogFormat.FATAL, LogLevel.live); } return result; } public static String isSurgeSite() { String isSurge = ""; try { isSurge = Context.getAdministrationService().getGlobalProperty("surge_site"); } catch (Exception e) { isSurge = ""; } return isSurge; } }
true
191e425cddf58f3320e55cf120692a55ff0c7858
Java
JMtorii/SectionedRecyclerView
/app/src/main/java/com/juntorii/testapplication/BestRecyclerAdapter.java
UTF-8
2,691
2.53125
3
[]
no_license
package com.juntorii.testapplication; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class BestRecyclerAdapter extends SectionedRecyclerAdapter { private List<SectionDataModel> data = new ArrayList<>(); @Override protected int numberOfSections() { return data.size(); } @Override protected int numberOfRowsInSection(int section) { return data.get(section).getPersonList().size(); } @Override protected RecyclerView.ViewHolder viewHolderForHeader(ViewGroup parent) { View headerView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_header, parent, false); return new HeaderViewHolder(headerView); } @Override protected RecyclerView.ViewHolder viewHolderForItemRow(ViewGroup parent) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent, false); return new ItemRowViewHolder(itemView); } @Override protected void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, IndexPath indexPath) { HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder; headerViewHolder.textView.setText(data.get(indexPath.section).getHeaderTitle()); } @Override protected void onBindItemViewHolder(RecyclerView.ViewHolder holder, IndexPath indexPath) { ItemRowViewHolder itemRowViewHolder = (ItemRowViewHolder) holder; Person person = data.get(indexPath.section).getPersonList().get(indexPath.row); itemRowViewHolder.mainTextView.setText(person.getName()); itemRowViewHolder.subtitleTextView.setText(String.format("%s", person.getAge())); } public void bindData(List<SectionDataModel> data) { this.data = data; notifyDataSetChanged(); } public class HeaderViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.row_header_text_view) TextView textView; public HeaderViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public class ItemRowViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.row_item_main_text_view) TextView mainTextView; @BindView(R.id.row_item_subtitle_text_view) TextView subtitleTextView; public ItemRowViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
true
9d6fa86abbc7ffc058b1e8c36d0e940241f9f4e9
Java
mayhew3/Postgres-Object
/src/main/java/com/mayhew3/postgresobject/db/MySQLConnectionFactory.java
UTF-8
1,291
2.859375
3
[]
no_license
package com.mayhew3.postgresobject.db; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; @SuppressWarnings("unused") public class MySQLConnectionFactory { protected final Logger logger = Logger.getLogger(MySQLConnectionFactory.class.getName()); public SQLConnection createConnection(String dbhost, String dbuser, String dbpassword) { String[] pieces = dbhost.split("/"); String schemaName = pieces[pieces.length-1]; return new MySQLConnection(initiateDBConnect(dbhost, dbuser, dbpassword), schemaName); } private Connection initiateDBConnect(String dbhost, String dbuser, String dbpassword) { logger.log(Level.INFO, "Initializing connection."); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Cannot find MySQL drivers. Exiting."); throw new RuntimeException(e.getLocalizedMessage()); } try { return DriverManager.getConnection(dbhost, dbuser, dbpassword); } catch (SQLException e) { System.out.println("Cannot connect to database. Exiting."); throw new RuntimeException(e.getLocalizedMessage()); } } }
true
1fd527ec2778713f0e83c519d4b960de5dd134ea
Java
my0sotis/Android_Homework
/A3-Collage-BaseCode/app/src/main/java/com/mikeriv/ssui_2016/a2_collage_basecode/drawing/CircleLayout.java
UTF-8
997
2.78125
3
[]
no_license
package com.mikeriv.ssui_2016.a2_collage_basecode.drawing; import android.graphics.Canvas; public class CircleLayout extends BaseVisualElement { private float CenterX; private float CenterY; private float CenterRadius; public CircleLayout(float x,float y,float w,float h, float layoutCenterX,float layoutCenterY, float layourtRadius){ super(x,y,w,h); this.CenterX=layoutCenterX; this.CenterY=layoutCenterY; this.CenterRadius=layourtRadius; } // @Override public void doLayout(){ float sum=0f; for(int i=0;i<super.getNumChildren();i++){ super.getChildAt(i).setX((super.getX()+super.getW())/2); sum=super.getChildAt(i).getH()+sum; super.getChildAt(i).setH(sum); super.getChildAt(i).doLayout(); } } @Override public void draw(Canvas onCanvas){ doLayout(); super.draw(onCanvas); } }
true
b30b68576f4f0dc00484f954a41f7c0d2d5b0292
Java
SoftEng-HEIGVD/Teaching-HEIGVD-RES-2019-Chill
/src/test/java/ch/heigvd/res/chill/domain/CosmicElodie/DogFishTest.java
UTF-8
1,009
2.734375
3
[ "MIT" ]
permissive
package ch.heigvd.res.chill.domain.CosmicElodie; import static org.junit.jupiter.api.Assertions.*; import ch.heigvd.res.chill.domain.Bartender; import org.junit.jupiter.api.Test; import ch.heigvd.res.chill.protocol.OrderRequest; import ch.heigvd.res.chill.protocol.OrderResponse; import java.math.BigDecimal; class DogFishTest { @Test void PriceAndNameForDogFishShouldBeCorrect() { DogFish beer = new DogFish(); assertEquals(beer.getName(), DogFish.NAME); assertEquals(beer.getPrice(), DogFish.PRICE); } @Test void aBartenderShouldAcceptAnOrderForDogFish() { Bartender john = new Bartender(); String productName = "ch.heigvd.res.chill.domain.CosmicElodie.DogFish"; OrderRequest request = new OrderRequest(3, productName); OrderResponse response = john.order(request); BigDecimal expectedTotalPrice = DogFish.PRICE.multiply(new BigDecimal(3)); assertEquals(expectedTotalPrice, response.getTotalPrice()); } }
true
2f7932d89adbb185442f79dd3b6cdc852639eed3
Java
ydl1997/learn-
/src/day27/CopyDemo1.java
UTF-8
466
2.984375
3
[]
no_license
package day27; import java.io.FileInputStream; import java.io.FileOutputStream; public class CopyDemo1 { public static void main(String[] args) throws Exception { FileInputStream in =new FileInputStream("d:\\javastest\\1.bmp"); FileOutputStream out =new FileOutputStream("d:\\javastest\\2.bmp"); int read =0; while((read=in.read())!=-1){ out.write(read); } in.close(); out.close(); } }
true
9be38856f7905a1458dc344f09a44bd5a99ceca5
Java
fangrenfu/onepage
/src/main/java/com/keysoft/onepage/controller/home/Index.java
UTF-8
519
1.859375
2
[]
no_license
package com.keysoft.onepage.controller.home; import com.keysoft.onepage.common.IndexTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/home/index") public class Index extends IndexTemplate { @RequestMapping(value = {"/","index"}) public String index(){ return "this in index"; } @RequestMapping("/url") public String operation(){ return getPageURL(); } }
true
da01ff3c18c01dce965e45275387af9bb4f9ffad
Java
harshalpande/SpringJMSApacheActiveMQ
/Topic/SpringBootWithExternalJMSTopicProducer/src/main/java/org/javabrains/SpringBootWithExternalJMSTopicProducer/config/TopicProducerConfig.java
UTF-8
1,389
2.125
2
[]
no_license
package org.javabrains.SpringBootWithExternalJMSTopicProducer.config; import javax.jms.ConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.connection.CachingConnectionFactory; import org.springframework.jms.core.JmsTemplate; @Configuration public class TopicProducerConfig { @Value("${active-mq-url}") String activeMQUrl; @Bean public ActiveMQConnectionFactory getConnectionFactory() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL(activeMQUrl); connectionFactory.setUserName("admin"); connectionFactory.setPassword("admin"); return connectionFactory; } @Bean @Autowired public CachingConnectionFactory cachingConnectionFactory(ConnectionFactory connectionFactory) { return new CachingConnectionFactory(connectionFactory); } @Bean @Autowired public JmsTemplate getJMSTemplate(CachingConnectionFactory cachingConnectionFactory) { JmsTemplate jmsTemplate = new JmsTemplate(cachingConnectionFactory); jmsTemplate.setPubSubDomain(true); // for Topic, if unset Queue is used return jmsTemplate; } }
true
4487c6162dba68fff83db01a979b979bae4131d9
Java
anastayaa/Android-Safi-Geo
/app/src/main/java/com/example/simo/safigeo/TestActivity.java
UTF-8
2,352
2.21875
2
[]
no_license
package com.example.simo.safigeo; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.Marker; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.util.concurrent.CountDownLatch; public class TestActivity extends AppCompatActivity { private volatile boolean imageDownloaded = false; private volatile CountDownLatch latch = new CountDownLatch(1); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); ImageView img = findViewById(R.id.tstimage); String path = "https://firebasestorage.googleapis.com/v0/b/safigeo-6f5be.appspot.com/o/Places%2FMohamed%20Karam-captu-1556389749894.jpg?alt=media&token=84e1f0c3-682f-4e98-aec5-2beb7bafc8e6"; new Handler().post(new Runnable() { @Override public void run() { Target target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { Log.d("MyTag", "onBitmapLoaded: "); img.setImageBitmap(bitmap); latch.countDown(); } @Override public void onBitmapFailed(Drawable errorDrawable) { Log.d("MyTag", "onBitmapFailed: "); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { Log.d("MyTag", "onPrepareLoad: "); } }; Picasso.with(getApplicationContext()) .load(path) .into(target); img.setTag(target); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } Toast.makeText(this, "Image Downloaded", Toast.LENGTH_SHORT).show(); } }
true
e1493f95729a7ca65f36e2a2502ad88374150381
Java
sidgopinath/CS308-cell-society-project
/src/view/SplashScreen.java
UTF-8
9,145
2.765625
3
[ "MIT" ]
permissive
package view; import java.util.ArrayList; import java.util.HashMap; import java.util.ResourceBundle; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import controller.CellSocietyController; /** * This function will initialize the splash screen. The splash screen needs to display text that says the title * of the program, which will come from the class that returns the input stream of the property files. * @author Sunjeev * */ public class SplashScreen { private static final int SPLASH_TEXT_SIZE = 5; private static final int LOAD_BUTTON_SIZE = 1; private Group myRoot; private int myWidth; private int myHeight; private CellSocietyController myController; private ArrayList<Button> myButtons; private ArrayList<Node> myAskScreenNodes; private static ResourceBundle myProperties; public SplashScreen(CellSocietyController controller){ myController = controller; myProperties = ResourceBundle.getBundle("resources/resources"); } /** * This function will initialize the splash screen. The splash screen needs to display text that says the title * of the program, which will come from the class that returns the input stream of the property files. * * This function will also have to have add button that takes it to the FileLoaderScreen class. */ public Group getNode(int width, int height){ myRoot = new Group(); myWidth = width; myHeight = height; myButtons = new ArrayList<>(); myAskScreenNodes = new ArrayList<>(); addTitle(); addLoadButton(); addRandomButton(); addProbablityButton(); for(Button button: myButtons){ button.setPrefWidth(myWidth / 5); button.setTranslateX((myWidth - button.getPrefWidth()) / 2); } return myRoot; } /** * collects integers for probability distribution */ private void addProbablityButton() { Button probButton = new Button((String) myProperties.getObject("probability")); myButtons.add(probButton); final Scene snapScene = new Scene(probButton); snapScene.snapshot(null); formatNode(probButton,myWidth /2, myHeight * 1/2, LOAD_BUTTON_SIZE ); probButton.setOnAction(e -> displayAskInformatio(true)); } private void displayAskInformatio(boolean probability) { removeButtons(); TextField[] dimensions = addDimensionsText(); TextField simulationName = addSimulationNameText(); Button submit = new Button(myProperties.getString("submit")); myAskScreenNodes.add(submit); submit.setTranslateX(myWidth/2); submit.setTranslateY(myHeight * 5/6); myRoot.getChildren().add(submit); submit.setOnAction(e -> { if(simulationName.getText() != null && dimensions[0].getText() != null && dimensions[1].getText() != null){ int numTextFields = 0; if(simulationName.getText().equals(myProperties.getObject("fire_simulation_name"))){ numTextFields = 3; } else if(simulationName.getText().equals(myProperties.getObject("segregation_simulation_name"))){ numTextFields = 3; } else if(simulationName.getText().equals(myProperties.getObject("life_simulation_name"))){ numTextFields = 2; } else if(simulationName.getText().equals(myProperties.getObject("predator_simulation_name"))){ numTextFields = 3; } else{ System.out.println(myProperties.getString("invalid_simulation_name")); throw new IllegalArgumentException(); } if(probability){ addProbabilityText(numTextFields, dimensions, simulationName.getText()); } else{ myController.generateRandomGrid(Integer.parseInt(dimensions[0].getText()), Integer.parseInt(dimensions[1].getText()), simulationName.getText()); } } }); } private void addProbabilityText(int numTextFields, TextField[] dimensions, String simName) { removeAskScreenNodes(); VBox probabilities = new VBox(myHeight / 20); for(int i = 0; i < numTextFields; i++){ HBox cellProbability = new HBox(myWidth / 20); cellProbability.setTranslateX(myWidth / 4); cellProbability.setTranslateY(myHeight / 2); Text probabilityName = new Text(myProperties.getString("cell") + " " + i + " " + myProperties.getString("probability")); cellProbability.getChildren().add(probabilityName); TextField probabilityText = new TextField(); probabilityText.setPromptText(myProperties.getString("enter_value_of_cell")); cellProbability.getChildren().add(probabilityText); probabilities.getChildren().add(cellProbability); } myRoot.getChildren().add(probabilities); Button runSimulation = new Button(myProperties.getString("run_simulation")); runSimulation.setTranslateX(myWidth/2); runSimulation.setTranslateY(myHeight * 5/6); myRoot.getChildren().add(runSimulation); runSimulation.setOnAction(e -> { HashMap<Integer, Integer> probabilityMap = new HashMap<>(); for(int i = 0; i < numTextFields; i++){ HBox probabilityHBox = (HBox) probabilities.getChildren().get(i); TextField probability = (TextField) probabilityHBox.getChildren().get(1); try{ probabilityMap.put(i, Integer.parseInt(probability.getText())); } catch(NumberFormatException e1){ System.out.println(myProperties.getString("invalid_value")); } } myController.generateProbabilityRandomGrid(Integer.parseInt(dimensions[0].getText()), Integer.parseInt(dimensions[1].getText()), simName, probabilityMap); }); } private void removeAskScreenNodes() { for(Node node: myAskScreenNodes){ if(myRoot.getChildren().contains(node)){ myRoot.getChildren().remove(node); } } } private TextField addSimulationNameText() { HBox simulation = new HBox(myWidth/20); Text simulationName = new Text(myProperties.getString("simulation_name")); simulation.getChildren().add(simulationName); TextField simulationNameText = new TextField(); simulationNameText.setPromptText(myProperties.getString("enter_name")); simulation.getChildren().add(simulationNameText); simulation.setTranslateX(myWidth / 4); simulation.setTranslateY(myHeight/2); myRoot.getChildren().add(simulation); myAskScreenNodes.add(simulation); return simulationNameText; } private TextField[] addDimensionsText() { HBox dimensions = new HBox(myWidth / 20); Text gridHeight = new Text(myProperties.getString("grid_height")); dimensions.getChildren().add(gridHeight); TextField gridHeightText = new TextField(); gridHeightText.setPromptText(myProperties.getString("enter_height")); dimensions.getChildren().add(gridHeightText); Text gridWidth = new Text(myProperties.getString("grid_width")); dimensions.getChildren().add(gridWidth); TextField gridWidthText = new TextField(); gridWidthText.setPromptText(myProperties.getString("enter_width")); dimensions.getChildren().add(gridWidthText); dimensions.setTranslateX(myWidth / 20); dimensions.setTranslateY(myHeight * 5/8); myRoot.getChildren().add(dimensions); myAskScreenNodes.add(dimensions); TextField[] ret = new TextField[]{gridHeightText, gridWidthText}; return ret; } private void removeButtons() { for(Button button: myButtons){ if(myRoot.getChildren().contains(button)){ myRoot.getChildren().remove(button); } } } /** * remove other buttons, and have user select grid height, width, and type of simulation */ private void addRandomButton() { Button probButton = new Button(myProperties.getString("random")); myButtons.add(probButton); final Scene snapScene = new Scene(probButton); snapScene.snapshot(null); formatNode(probButton,myWidth/2, myHeight * 3/4, LOAD_BUTTON_SIZE ); probButton.setOnAction(e -> displayAskInformatio(false)); } /** * This function will add the title in. This is example code of what it might do. It will have to get the name of the * program from the .properties file which will then dictate where it goes. */ private void addTitle(){ String splashTitle = myProperties.getString("splash_title"); Text splashTitleText = new Text(splashTitle); formatNode(splashTitleText, (myWidth - splashTitleText.getLayoutBounds().getWidth())/2, myHeight / 4, SPLASH_TEXT_SIZE); } /** * This function will add the button to the scene. This includes all the formatting of the button. * It will have to get the button's position from the .properties file. */ private void addLoadButton(){ String loadButtonString = myProperties.getString("load_button_string"); Button loadButton = new Button(loadButtonString); myButtons.add(loadButton); final Scene snapScene = new Scene(loadButton); snapScene.snapshot(null); formatNode(loadButton,myWidth / 2, myHeight * 5/8, LOAD_BUTTON_SIZE ); loadButton.setOnAction(e -> myController.transitionToFileLoaderScreen()); } private void formatNode(Node node, double width, double height, int scale) { node.setTranslateX(width); node.setTranslateY(height); node.setScaleX(scale); node.setScaleY(scale); myRoot.getChildren().add(node); } }
true
d8da1da52faf2bee826ff897f4c26c6d4b56855d
Java
ahmedatefabd/Clinics
/app/src/main/java/com/example/ragab/clinics/Upload_X_Ray/Upload_X_RayFragment.java
UTF-8
14,898
1.898438
2
[]
no_license
package com.example.ragab.clinics.Upload_X_Ray; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.example.ragab.clinics.R; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import cn.pedant.SweetAlert.SweetAlertDialog; public class Upload_X_RayFragment extends Fragment implements View.OnClickListener { private Button addPicturee; private LinearLayout selectedImagess; // private ImageView xrayImg; private String filePath; private static final int REQUEST_PERMISSIONS_READ_EXTERNAL_STORAGE = 600, REQUEST_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 601; DialogInterface.OnClickListener onDialogClickWithImagee; public static ArrayList<String> bookingPhotos = new ArrayList<>(); { onDialogClickWithImagee = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: if (checkReadExternalPermission()) openImageChooser(); break; case 1: if (checkCameraPermission()) takeCameraPhoto(); break; case 2: dialog.dismiss(); break; } } }; } public Upload_X_RayFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_x__ray, container, false); Define_Strings(); Declare_controls(view); addPicturee.setOnClickListener(this); return view; } private void Define_Strings() { } private void Declare_controls(View view) { addPicturee = view.findViewById(R.id.addpicture); selectedImagess = view.findViewById(R.id.show_selected_photo); // xrayImg = view.findViewById(R.id.xrayImg); // Picasso.get() // .load(R.drawable.xray12) // .transform(new RoundedTransformation()) // .resize(500, 500) // .into(xrayImg); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_PERMISSIONS_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openImageChooser(); } else { Toast.makeText(getActivity(), "readFromGalleryPhotoPermissionRequired", Toast.LENGTH_SHORT).show(); } break; } case REQUEST_PERMISSIONS_WRITE_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { takeCameraPhoto(); } else { Toast.makeText(getActivity(), "takingCameraPhotoPermissionRequired", Toast.LENGTH_SHORT).show(); } break; } } } private boolean checkReadExternalPermission() { boolean isGranted = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; if (!isGranted) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS_READ_EXTERNAL_STORAGE); } return isGranted; } private boolean checkCameraPermission() { boolean isGranted = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED; if (!isGranted) ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS_WRITE_EXTERNAL_STORAGE); return isGranted; } private void openImageChooser() { Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, 100); } private void takeCameraPhoto() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(takePictureIntent, 200); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { try { if (resultCode == getActivity().RESULT_CANCELED) { return; } if (requestCode == 100 && resultCode == Activity.RESULT_OK && null != data) { if (data != null) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); Log.w("filepath", filePath); cursor.close(); String encodedImage = encodeImage(filePath); bookingPhotos.add(encodedImage); Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath); final ImageView imageView = new ImageView(getActivity()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(250, 270); imageView.setLayoutParams(layoutParams); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setPadding(10, 10, 10, 10); imageView.setImageBitmap(yourSelectedImage); if (selectedImagess.getVisibility() == View.GONE) selectedImagess.setVisibility(View.VISIBLE); selectedImagess.addView(imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("هل تريد مسح الصوره") .setCancelable(false) .setPositiveButton("نعم", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (bookingPhotos.size() == 1) { imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(0)); selectedImagess.setVisibility(View.GONE); } else if (bookingPhotos.size() == 2){ imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(1)); }else if (bookingPhotos.size() >= 3){ imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(2)); } } }).setNegativeButton("لا", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.setTitle("مسح"); alert.show(); } }); Log.w("path", encodedImage); } } else if (requestCode == 200 && resultCode == Activity.RESULT_OK) { Bundle extras = data.getExtras(); Bitmap captureImage = (Bitmap) extras.get("data"); String encodedImage = encodeImage(captureImage); bookingPhotos.add(encodedImage); Log.w("takePhotoFile", encodedImage); final ImageView imageView = new ImageView(getActivity()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(250, 270); imageView.setLayoutParams(layoutParams); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setPadding(10, 10, 10, 10); imageView.setImageBitmap(captureImage); if (selectedImagess.getVisibility() == View.GONE) selectedImagess.setVisibility(View.VISIBLE); selectedImagess.addView(imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("هل تريد مسح الصوره") .setCancelable(false) .setPositiveButton("نعم", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (bookingPhotos.size() == 1) { imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(0)); selectedImagess.setVisibility(View.GONE); } else if (bookingPhotos.size() == 2){ imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(1)); }else if (bookingPhotos.size() >= 3){ imageView.setVisibility(View.GONE); bookingPhotos.remove(bookingPhotos.get(2)); } } }).setNegativeButton("لا", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.setTitle("مسح"); alert.show(); } }); } } catch (Exception e) { Toast.makeText(getActivity(), "حدث خطأ", Toast.LENGTH_SHORT).show(); } } private String encodeImage(String path) { File imagefile = new File(path); FileInputStream fis = null; try { fis = new FileInputStream(imagefile); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap bm = BitmapFactory.decodeStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String encImage = Base64.encodeToString(b, Base64.DEFAULT); return encImage; } private String encodeImage(Bitmap bitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); return encoded; } private void errorMessage(String message) { new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE) .setTitleText("عفوا") .setContentText(message) .setConfirmText("العودة") .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.dismiss(); } }) .show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.addpicture: if (bookingPhotos.size() < 3) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.add_photo)); builder.setItems(new CharSequence[]{getString(R.string.choose_photo), getString(R.string.take_photo), getString(R.string.cancle_photo)}, onDialogClickWithImagee); AlertDialog alert = builder.create(); alert.show(); } else { errorMessage("لا يمكن إضافة أكثر من 3 صور"); } break; } } }
true
2822278888e9396c4781abf504d7479fdbb1d147
Java
gregmaka/java_student_codesamples
/GregMaka_Lesson_2_Project/Dollars.java
UTF-8
1,036
3.578125
4
[]
no_license
// Greg Maka CIS163AA // with modification import java.util.*; import javax.swing.*; public class Dollars { public static void main(String[] args) { double money; String input; input = JOptionPane.showInputDialog("Enter the total amount of cash you have ","ENTER MONEY"); money = Double.parseDouble(input); int noTwenty = (int) money / 20; System.out.println("You have " + noTwenty + " twenty dollar bill(s)."); double balanceAfterTwenty = money - (noTwenty * 20); int noTen = (int) balanceAfterTwenty / 10; System.out.println("You have " + noTen + " ten dollar bill(s)."); double balanceAfterTen = money - ((noTwenty * 20) + (noTen * 10)); int noFive = (int) balanceAfterTen / 5; System.out.println("You have " + noFive + " five dollar bill(s)."); double balanceAfterFive = money - ((noTwenty * 20) + (noTen * 10) + (noFive * 5)); int noOne = (int) (balanceAfterFive / 1); System.out.println("You have " + noOne + " one dollar bills."); } }
true
9af3e8f6e5907ce55184511742ce21446ba5b829
Java
zhongxingyu/Seer
/Diff-Raw-Data/1/1_5977307c513654ef8e424b32b99a0362ecdc6698/GroovyEclipseCompiler/1_5977307c513654ef8e424b32b99a0362ecdc6698_GroovyEclipseCompiler_t.java
UTF-8
15,439
1.523438
2
[]
no_license
/******************************************************************************* * Copyright (c) 2010 Codehaus.org, SpringSource, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andrew Eisenberg - Initial API and implementation * Carlos Fernandez - fix for nowarn *******************************************************************************/ package org.codehaus.groovy.eclipse.compiler; import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.codehaus.plexus.compiler.AbstractCompiler; import org.codehaus.plexus.compiler.CompilerConfiguration; import org.codehaus.plexus.compiler.CompilerError; import org.codehaus.plexus.compiler.CompilerException; import org.codehaus.plexus.compiler.CompilerOutputStyle; import org.eclipse.jdt.core.compiler.CompilationProgress; import org.eclipse.jdt.internal.compiler.batch.Main; /** * @plexus.component role="org.codehaus.plexus.compiler.Compiler" * role-hint="groovy-eclipse" * * * @author <a href="mailto:[email protected]">Andrew Eisenberg</a> * @author <a href="mailto:[email protected]">Jason van Zyl</a> */ public class GroovyEclipseCompiler extends AbstractCompiler { boolean verbose; /* Eclipse Compiler for Java(TM) 0.A58, 3.6.0 Copyright IBM Corp 2000, 2010. All rights reserved. Usage: <options> <source files | directories> If directories are specified, then their source contents are compiled. Possible options are listed below. Options enabled by default are prefixed with '+'. Classpath options: -cp -classpath <directories and ZIP archives separated by :> specify location for application classes and sources. Each directory or file can specify access rules for types between '[' and ']' (e.g. [-X] to forbid access to type X, [~X] to discourage access to type X, [+p/X:-p/*] to forbid access to all types in package p but allow access to p/X) -bootclasspath <directories and ZIP archives separated by :> specify location for system classes. Each directory or file can specify access rules for types between '[' and ']' -sourcepath <directories and ZIP archives separated by :> specify location for application sources. Each directory or file can specify access rules for types between '[' and ']'. Each directory can further specify a specific destination directory using a '-d' option between '[' and ']'; this overrides the general '-d' option. .class files created from source files contained in a jar file are put in the user.dir folder in case no general '-d' option is specified. ZIP archives cannot override the general '-d' option -extdirs <directories separated by :> specify location for extension ZIP archives -endorseddirs <directories separated by :> specify location for endorsed ZIP archives -d <dir> destination directory (if omitted, no directory is created); this option can be overridden per source directory -d none generate no .class files -encoding <enc> specify default encoding for all source files. Each file/directory can override it when suffixed with '['<enc>']' (e.g. X.java[utf8]). If multiple default encodings are specified, the last one will be used. Compliance options: -1.3 use 1.3 compliance (-source 1.3 -target 1.1) -1.4 + use 1.4 compliance (-source 1.3 -target 1.2) -1.5 -5 -5.0 use 1.5 compliance (-source 1.5 -target 1.5) -1.6 -6 -6.0 use 1.6 compliance (-source 1.6 -target 1.6) -1.7 -7 -7.0 use 1.7 compliance (-source 1.7 -target 1.7) -source <version> set source level: 1.3 to 1.7 (or 5, 5.0, etc) -target <version> set classfile target: 1.1 to 1.7 (or 5, 5.0, etc) cldc1.1 can also be used to generate the StackMap attribute Warning options: -deprecation + deprecation outside deprecated code (equivalent to -warn:+deprecation) -nowarn -warn:none disable all warnings -?:warn -help:warn display advanced warning options Error options: -err:<warnings separated by ,> convert exactly the listed warnings to be reported as errors -err:+<warnings separated by ,> enable additional warnings to be reported as errors -err:-<warnings separated by ,> disable specific warnings to be reported as errors Setting warning or error options using properties file: -properties: <file> set warnings/errors option based on the properties file contents. This option can be used with -nowarn, -err:.. or -warn:.. options, but the last one on the command line sets the options to be used. Debug options: -g[:lines,vars,source] custom debug info -g:lines,source + both lines table and source debug info -g all debug info -g:none no debug info -preserveAllLocals preserve unused local vars for debug purpose Annotation processing options: These options are meaningful only in a 1.6 environment. -Akey[=value] options that are passed to annotation processors -processorpath <directories and ZIP archives separated by :> specify locations where to find annotation processors. If this option is not used, the classpath will be searched for processors -processor <class1[,class2,...]> qualified names of the annotation processors to run. This bypasses the default annotation discovery process -proc:only run annotation processors, but do not compile -proc:none perform compilation but do not run annotation processors -s <dir> destination directory for generated source files -XprintProcessorInfo print information about which annotations and elements a processor is asked to process -XprintRounds print information about annotation processing rounds -classNames <className1[,className2,...]> qualified names of binary classes to process Advanced options: @<file> read command line arguments from file -maxProblems <n> max number of problems per compilation unit (100 by default) -log <file> log to a file. If the file extension is '.xml', then the log will be a xml file. -proceedOnError[:Fatal] do not stop at first error, dumping class files with problem methods With ":Fatal", all optional errors are treated as fatal -verbose enable verbose output -referenceInfo compute reference info -progress show progress (only in -log mode) -time display speed information -noExit do not call System.exit(n) at end of compilation (n==0 if no error) -repeat <n> repeat compilation process <n> times for perf analysis -inlineJSR inline JSR bytecode (implicit if target >= 1.5) -enableJavadoc consider references in javadoc -Xemacs used to enable emacs-style output in the console. It does not affect the xml log output -? -help print this help message -v -version print compiler version -showversion print compiler version and continue Ignored options: -J<option> pass option to virtual machine (ignored) -X<option> specify non-standard option (ignored except for listed -X options) -X print non-standard options and exit (ignored) -O optimize for execution time (ignored) */ public GroovyEclipseCompiler() { super(CompilerOutputStyle.ONE_OUTPUT_FILE_PER_INPUT_FILE, ".groovy", ".class", null); } public List compile(CompilerConfiguration config) throws CompilerException { File destinationDir = new File(config.getOutputLocation()); if (!destinationDir.exists()) { destinationDir.mkdirs(); } // force the resetting of the source files so that java files are included config.setSourceFiles(null); config.addInclude("**/*.java"); config.addInclude("**/*.groovy"); String[] sourceFiles = getSourceFiles(config); if (sourceFiles.length == 0) { getLogger().warn("No sources added to compile; skipping"); return Collections.EMPTY_LIST; } getLogger().info("Using Groovy-Eclipse compiler to compile both Java and Groovy files"); getLogger().info("Compiling " + sourceFiles.length + " " + "source file" + (sourceFiles.length == 1 ? "" : "s") + " to " + destinationDir.getAbsolutePath()); List args = new ArrayList(); String cp = super.getPathString(config.getClasspathEntries()); verbose = config.isVerbose(); if (verbose) { getLogger().info("Classpath: " + cp); } if (cp.length() > 0) { args.add("-cp"); args.add(cp); } if (config.getOutputLocation()!= null && config.getOutputLocation().length() > 0) { args.add("-d"); args.add(config.getOutputLocation()); } args.add("-g"); // change default to 1.5...why? because I say so. String source = config.getSourceVersion(); args.add("-source"); if (source != null && source.length() > 0) { args.add(source); } else { args.add("1.5"); } String target = config.getTargetVersion(); args.add("-target"); if (target != null && target.length() > 0) { args.add(target); } else { args.add("1.5"); } // trigger nowarn based on the CompilerConfiguration if (config.isShowWarnings() ) { args.add("-nowarn"); } //TODO review CompilerConfiguration - make sure all options are taken into account for (Iterator argIter = config.getCustomCompilerArguments().entrySet().iterator(); argIter.hasNext();) { Entry entry = (Entry) argIter.next(); Object key = entry.getKey(); if (doesStartWithHyphen(key)) { // don't add a "-" if the arg already has one args.add(key); } else { /* * Not sure what the possible range of usage looks like but * i don't think this should allow for null keys? * "-null" probably isn't going to play nicely with any compiler? */ args.add("-" + key); } if (null != entry.getValue()) { // don't allow a null value args.add("\"" + entry.getValue() + "\""); } } args.addAll(composeSourceFiles(sourceFiles)); if (verbose) { args.add("-verbose"); } if (verbose) { getLogger().info("All args: " + args); } Progress progress = new Progress(); Main main = new Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*systemExit*/, null/*options*/, progress); boolean result = main.compile((String[]) args.toArray(new String[args.size()])); return formatResult(main, result); } private boolean doesStartWithHyphen(Object key) { return null != key && String.class.isInstance(key) && ((String)key).startsWith("-"); } /** * @param main * @param result * @return */ private List formatResult(Main main, boolean result) { if (result) { return Collections.EMPTY_LIST; } else { String error = main.globalErrorsCount == 1 ? "error" : "errors"; String warning = main.globalWarningsCount == 1 ? "warning" : "warnings"; return Collections.singletonList(new CompilerError("Found " + main.globalErrorsCount + " " + error + " and " + main.globalWarningsCount + " " + warning + ".", true)); } } private List composeSourceFiles(String[] sourceFiles) { List sources = new ArrayList(sourceFiles.length); for (int i = 0; i < sourceFiles.length; i++) { sources.add(sourceFiles[i]); } return sources; } public String[] createCommandLine(CompilerConfiguration config) throws CompilerException { return null; } /** * Simple progress monitor to keep track of number of files compiled * * @author Andrew Eisenberg * @created Aug 13, 2010 */ private class Progress extends CompilationProgress { int numCompiled = 0; public void begin(int arg0) { } public void done() { } public boolean isCanceled() { return false; } public void setTaskName(String newTaskName) { } public void worked(int workIncrement, int remainingWork) { if (verbose) { String file = remainingWork == 1 ? "file" : "files"; getLogger().info(remainingWork + " " + file + " left."); } numCompiled++; } } }
true
ac3682cfcf0f3473e0a5e6dc90419b6a80639c33
Java
navyanswamy20/TYSS-16Sep19-NavyaHN
/thread/src/com/tyss/thread/properties/MyThread.java
UTF-8
577
3.21875
3
[]
no_license
package com.tyss.thread.properties; public class MyThread extends Thread { public static void main(String[] args) { System.out.println("main started"); //to get the name of the thread String tname = Thread.currentThread().getName(); System.out.println("current thread name is " +tname); MyThread t1 = new MyThread(); String mname = t1.getName(); System.out.println("my thread name is "+mname); //to change the name of the thread Thread.currentThread().setName("momo"); System.out.println(10 / 0); System.out.println("main ended"); } }
true
318181d1cb7dc6fccbd7f78d4c202b9fb0841591
Java
MaghiarCatalina/StockAlarmsApp
/src/main/java/com/devm8/demo/stockalarms/services/UserService.java
UTF-8
1,910
2.375
2
[]
no_license
package com.devm8.demo.stockalarms.services; import com.devm8.demo.stockalarms.dto.UserDTO; import com.devm8.demo.stockalarms.entities.User; import com.devm8.demo.stockalarms.repo.UserRepo; import lombok.RequiredArgsConstructor; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; @Service @Transactional @RequiredArgsConstructor public class UserService implements UserDetailsService { private final UserRepo userRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepo.findById(username) .map(UserService::mapUser) .orElseThrow(() -> new UsernameNotFoundException("The requested user was not found.")); } private static UserDetails mapUser(User user){ List<SimpleGrantedAuthority> list = new ArrayList<>(); list.add(new SimpleGrantedAuthority("ROLE_USER")); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list); } @Transactional public boolean registerUser(UserDTO dto){ if(userRepo.findById(dto.getUsername()).isPresent()){ return false; } else { String encodedPassword = new BCryptPasswordEncoder().encode(dto.getPassword()); dto.setPassword(encodedPassword); userRepo.save(UserDTO.toEntity(dto)); return true; } } }
true
b5ed188949f5fa3bb85d64f127cafb2eb4e1c2a2
Java
hafizjef/mvc-java
/src/com/xyz/view/RentalEntryDialog.java
UTF-8
1,495
2.609375
3
[]
no_license
package com.xyz.view; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.xyz.crms.model.Car; import com.xyz.crms.model.Customer; public class RentalEntryDialog extends AbstractEntryDialog { private static final long serialVersionUID = 1L; private JTextField dateInput = new JTextField(); private JComboBox<Car> carsInput = new JComboBox<>(); private JComboBox<Customer> customerInput = new JComboBox<>(); private JTextField durationInput = new JTextField(); private JButton searchButton = new JButton("Search"); public RentalEntryDialog(MainMenuFrame frame) { super(frame, null, 5); JPanel panel = new JPanel(); BoxLayout layout = new BoxLayout(panel, BoxLayout.LINE_AXIS); panel.setLayout(layout); panel.add(dateInput); panel.add(searchButton); center.add(new JLabel("Rental (dd/MM/yyyy HH:mm):", JLabel.RIGHT)); center.add(panel); center.add(new JLabel("Car:", JLabel.RIGHT)); center.add(carsInput); center.add(new JLabel("Customer:", JLabel.RIGHT)); center.add(customerInput); center.add(new JLabel("Duration (hours):", JLabel.RIGHT)); center.add(durationInput); resetInput(); finalizeUI(searchButton, submitButton, resetButton); } @Override protected void submitInput() { } @Override protected void resetInput() { dateInput.setText(""); durationInput.setText(""); } }
true