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
7a8b4824d409006e419b6375fdf2c9f2c0378652
Java
apache/ignite
/modules/core/src/test/java/org/apache/ignite/spi/loadbalancing/roundrobin/GridRoundRobinTestUtils.java
UTF-8
3,858
2.203125
2
[ "Apache-2.0", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0", "BSD-3-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.loadbalancing.roundrobin; import java.util.List; import java.util.UUID; import org.apache.ignite.GridTestJob; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.compute.ComputeTaskSession; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Helper class for balancer tests. */ class GridRoundRobinTestUtils { /** * Performs two full cycles by round robin routine for check correct order. * * @param spi Load balancing SPI. * @param allNodes Topology nodes. * @param orderedNodes Balancing nodes. * @param ses Task session. */ static void checkCyclicBalancing(RoundRobinLoadBalancingSpi spi, List<ClusterNode> allNodes, List<UUID> orderedNodes, ComputeTaskSession ses) { ClusterNode firstNode = spi.getBalancedNode(ses, allNodes, new GridTestJob()); int startIdx = firstBalancedNodeIndex(firstNode, orderedNodes); // Two full cycles by round robin routine. for (int i = 0; i < allNodes.size() * 2; i++) { int actualIdx = (startIdx + i + 1) % allNodes.size(); ClusterNode nextNode = spi.getBalancedNode(ses, allNodes, new GridTestJob()); assertEquals("Balancer returns node out of order", nextNode.id(), orderedNodes.get(actualIdx)); } } /** * Performs two full cycles by round robin routine for check correct order. * Switches between two task sessions by turns. * * @param spi Load balancing SPI. * @param allNodes Topology nodes. * @param orderedNodes Balancing nodes. * @param ses1 First task session. * @param ses2 Second task session. */ static void checkCyclicBalancing(RoundRobinLoadBalancingSpi spi, List<ClusterNode> allNodes, List<UUID> orderedNodes, ComputeTaskSession ses1, ComputeTaskSession ses2) { ClusterNode firstNode = spi.getBalancedNode(ses1, allNodes, new GridTestJob()); int startIdx = firstBalancedNodeIndex(firstNode, orderedNodes); // Two full cycles by round robin routine. for (int i = 0; i < allNodes.size() * 2; i++) { int actualIdx = (startIdx + i + 1) % allNodes.size(); ClusterNode nextNode = spi.getBalancedNode(i % 2 == 0 ? ses1 : ses2, allNodes, new GridTestJob()); assertEquals("Balancer returns node out of order", nextNode.id(), orderedNodes.get(actualIdx)); } } /** * @param firstNode First node which was return by balancer. * @param orderedNodes Balancing nodes. * @return Index of first node which was return by balancer. */ static int firstBalancedNodeIndex(ClusterNode firstNode, List<UUID> orderedNodes) { int startIdx = -1; for (int i = 0; i < orderedNodes.size(); i++) { if (firstNode.id() == orderedNodes.get(i)) startIdx = i; } assertTrue("Can't find position of first balanced node", startIdx >= 0); return startIdx; } }
true
4bb9de7f377a1adbd79b09ea89905d47581fab12
Java
v13nr/suara
/app/src/main/java/com/nanangrustianto/suara2019/daftar.java
UTF-8
8,536
1.992188
2
[]
no_license
package com.nanangrustianto.suara2019; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import com.nanangrustianto.suara2019.AppConfig; import com.nanangrustianto.suara2019.app.AppController2; import com.nanangrustianto.suara2019.R; /** * Created by Nanang R on 20/10/2017. */ public class daftar extends Activity { private static final String TAG = LoginActivity.class.getSimpleName(); private Button btnLogin; private TextView btnLinkToRegister,skip,reset; private EditText inputEmail; private EditText inputPassword; private EditText inputNama; private ProgressDialog pDialog; private SharedPreferences pref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_daftar); TextView tv = (TextView)findViewById(R.id.link_login); pref = getSharedPreferences("data", MODE_PRIVATE); inputEmail = (EditText) findViewById(R.id.input_email); inputPassword = (EditText) findViewById(R.id.input_password); inputNama = (EditText) findViewById(R.id.nama_lengkap); btnLogin = (Button) findViewById(R.id.btn_login); //btnLinkToRegister = (TextView) findViewById(R.id.btnLinkToRegisterScreen); // Progress dialog pDialog = new ProgressDialog(this); pDialog.setCancelable(false); // ngecek apakah user udah login atau belum pref = getSharedPreferences("data", Context.MODE_PRIVATE); final int login = pref.getInt("login", 0); if (login == 1) { // kalau user ternyata udah login langsung di lempar ke main activity tanpa harus login terlebih dahulu Intent intent = new Intent(daftar.this, MainActivity.class); startActivity(intent); finish(); } // ketika login button di klik btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String email = inputEmail.getText().toString().trim(); String password = inputPassword.getText().toString().trim(); String nama = inputNama.getText().toString().trim(); // ngecek apakah inputannya kosong atau tidak if (!email.isEmpty() && !password.isEmpty() && !nama.isEmpty()) { // login user checkLogin(email, password, nama); } else { // jika inputan kosong tampilkan pesan Toast.makeText(getApplicationContext(), "Jangan kosongkan nama, email dan password!", Toast.LENGTH_LONG) .show(); } } }); // Link ke register activity /* btnLinkToRegister.setOnClickListener(new View.OnClickListener() { *//* public void onClick(View view) { Intent i = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(i); finish(); }*//* });*/ tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Silahkan Login..!", Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent); } }); } private void checkLogin(final String email, final String password, final String nama) { // Tag biasanya digunakan ketika ingin membatalkan request volley String tag_string_req = "req_login"; pDialog.setMessage("Registering in ..."); showDialog(); StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_DAFTAR, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Login Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); // ngecek node error dari api if (!error) { // user berhasil login String uid = jObj.getString("username"); String nama = jObj.getString("email"); String email = jObj.getString("email"); String alamat = jObj.getString("email"); AppConfig.emailAktif = jObj.getString("username"); // buat session user yang sudah login yang menyimpan nama,apikey,alamat dan email SharedPreferences.Editor editor = pref.edit(); editor.putString("apikey", uid); editor.putString("nama",nama); editor.putString("email",email); editor.putString("alamat", alamat); editor.putInt("login", 1); editor.commit(); //jika sudah masuk ke mainactivity Intent intent = new Intent(daftar.this, MainActivity.class); startActivity(intent); finish(); } else { // terjadi error dan tampilkan pesan error dari API String errorMsg = jObj.getString("message"); Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { // JSON error e.printStackTrace(); Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Login Error: " + error.getMessage()); //cek error timeout, noconnection dan network error if ( error instanceof TimeoutError || error instanceof NoConnectionError ||error instanceof NetworkError) { Toast.makeText(getApplicationContext(), "Please Check Your Connection", Toast.LENGTH_SHORT).show();} hideDialog(); } }) { @Override protected Map<String, String> getParams() { // kirim parameter ke server Map<String, String> params = new HashMap<String, String>(); params.put("username", email); params.put("password", password); params.put("nama", nama); return params; } }; // menggunakan fungsi volley adrequest yang kita taro di appcontroller AppController2.getInstance().addToRequestQueue(strReq, tag_string_req); } //untuk menampilkan loading dialog private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
true
4af487a9cecbc31d2da011dd044c40663cd23b76
Java
WonSik36/baekjoon
/1624/Main.java
UTF-8
3,310
3.3125
3
[]
no_license
/* baekjoon online judge problem number 1624 https://www.acmicpc.net/problem/1624 https://handongproblemsolvers.github.io/2019/11/17/Week_12_Contest_Problem_Solving/#%EB%8D%B0%ED%81%AC-%EC%86%8C%ED%8A%B8 deep reference level dynamic programming and greedy algorithm if input is 1 3 5 7 9 2 4 6 8 than there can be deque 1 2 3 / 4 5 6 7 / 8 9 it need to find out 1~3 is possible in given array */ // import java.io.FileReader; // import java.io.FileWriter; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.StringTokenizer; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.Collections; import java.util.Arrays; public class Main{ static final int MAX_INF = 10000; static final int MIN_INF = -10000; public static void main(String[] args)throws IOException{ // BufferedReader br = new BufferedReader(new FileReader("./1.in")); // BufferedWriter bw = new BufferedWriter(new FileWriter("./1.out")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int N = Integer.parseInt(br.readLine()); int[] arr = new int[N]; Set<Integer> set = new HashSet<Integer>(); for(int i=0;i<N;i++){ arr[i] = Integer.parseInt(br.readLine()); set.add(arr[i]); } // list of number ordered by ascending order and not duplicated List<Integer> list = new ArrayList<Integer>(set); Collections.sort(list); int[] dp = new int[N]; Arrays.fill(dp, MAX_INF); for(int i=0;i<list.size();i++){ // if value from 0 to i in list can afford to one deque if(check(0,i,arr,list)){ dp[i] = 1; continue; } for(int j=i;j>0;j--){ // if value from j to i in list can't afford to one deque if(!check(j,i,arr,list)) break; // if value j~i in list can afford to one deque dp[i] = Min(dp[i], dp[j-1]+1); } } bw.write(Integer.toString(dp[list.size()-1])+"\n"); bw.flush(); bw.close(); br.close(); } // check i~j can afford one deque public static boolean check(int i, int j, int[] arr, List<Integer> list){ if(j-i<2) return true; int a = list.get(i); int b = list.get(j); int head = MAX_INF; int tail = MIN_INF; for(int k=0;k<arr.length;k++){ // number is not in a~b if(a>arr[k] || b<arr[k]) continue; // number is in head~tail which is in deque if(head<arr[k] && tail>arr[k]) return false; head = Min(head, arr[k]); tail = Max(tail, arr[k]); } return true; } public static int Min(int a, int b){ return a<b?a:b; } public static int Max(int a, int b){ return a>b?a:b; } }
true
b5385d2a886dd0e8dd9b140b5aaa7c1cdf8d1ca2
Java
aetheriac/RuneWarsCombatSimulator
/Daqan/java/rwcsim/factions/daqan/upgrades/unique/SweepingStrikes.java
UTF-8
471
2.046875
2
[]
no_license
package rwcsim.factions.daqan.upgrades.unique; import rwcsim.basicutils.stages.OnMeleeAttack; import rwcsim.basicutils.concepts.Cost; import rwcsim.basicutils.upgrades.HeroSpecific; import rwcsim.basicutils.upgrades.Unique; import rwcsim.factions.daqan.LordHawthorne; import rwcsim.factions.daqan.upgrades.Daqan; public class SweepingStrikes implements Cost, Daqan, HeroSpecific<LordHawthorne>, Unique { @Override public int price() { return 5; } }
true
9dc0b2cf97cfb85a2e680ce9212512cc722858e8
Java
andrew-mcgrath/unit-testing-course
/src/main/java/com/drewmcgrath/datemagic/notification/PushMatchNotifier.java
UTF-8
1,287
2.46875
2
[]
no_license
/** * Copyright Andrew McGrath 2013 * */ package com.drewmcgrath.datemagic.notification; import com.drewmcgrath.datemagic.domain.Profile; import com.drewmcgrath.mobile.push.PushService; import java.util.Collection; /** * * @author amcgrath */ public class PushMatchNotifier implements MatchNotifier { private PushService pushService; private PushNotificationBuilder pushNotificationBuilder; public PushMatchNotifier() { } @Override public void notify(Profile profileToNotify, Collection<Profile> matches) { for (Profile match : matches) { notify(profileToNotify, match); } } protected void notify(Profile profileToNotify, Profile matchedProfile) { pushService.send(profileToNotify.getMobilePhone(), pushNotificationBuilder.build(matchedProfile)); } public PushService getPushService() { return pushService; } public void setPushService(PushService pushService) { this.pushService = pushService; } public PushNotificationBuilder getPushNotificationBuilder() { return pushNotificationBuilder; } public void setPushNotificationBuilder(PushNotificationBuilder pushNotificationBuilder) { this.pushNotificationBuilder = pushNotificationBuilder; } }
true
6093f7e406b322d765c74511258b0fed816aabd9
Java
motiour/CUE_Retailer
/com.cue/src/test/java/com/cucumber/com/cue/CUESignUpTestFromCUE.java
UTF-8
5,142
1.804688
2
[]
no_license
package com.cucumber.com.cue; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.interactions.HasInputDevices; import org.openqa.selenium.interactions.Mouse; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.support.ui.Select; public class CUESignUpTestFromCUE { public WebDriver driver = null; @Before public void beforeTest() { /* System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.at60inches.com/romy-owens/i-have-a-scheme-for-stopping-war-its-this-no-nation-is-allowed-to-enter-a-war-until-they-have-paid-for-the-last-one-2"); */ FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("browser.cache.disk.enable", "false"); driver = new FirefoxDriver(profile); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("http://www.at60inches.com/romy-owens/i-have-a-scheme-for-stopping-war-its-this-no-nation-is-allowed-to-enter-a-war-until-they-have-paid-for-the-last-one-2"); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } public void mouseClick(WebElement element) { String code = "var fireOnThis = arguments[0];" + "var evObj = document.createEvent('MouseEvents');" + "evObj.initEvent( 'click',true,false );" + "fireOnThis.dispatchEvent(evObj);"; ((JavascriptExecutor) driver).executeScript(code, element); } public void hoverItem(WebElement element) { Actions actions = new Actions(driver); actions.moveToElement(element); actions.perform(); } public void hoverItem(By by) { WebElement element = driver.findElement(by); hoverItem(element); } public void hoverItemEx(WebElement element) { Locatable hoverItem = (Locatable) element; Mouse mouse = ((HasInputDevices) driver).getMouse(); mouse.mouseMove(hoverItem.getCoordinates()); } public void hoverItemEx(By by) { WebElement element = driver.findElement(by); hoverItemEx(element); } public void delayFor(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } @After public void afterTest() { driver.close(); } @Test public void shareByTumblr() { WebElement CUElInk = driver.findElement(By.xpath("//*[@id='nav-user']/ul/li[3]/a")); delayFor(2000); mouseClick(CUElInk); delayFor(5000); driver.switchTo().defaultContent(); driver.switchTo().frame(driver.findElement(By.id("streamIFrame"))); WebElement menu = driver.findElement(By.xpath("//*[@id='signup']")); // the triger event element Actions build = new Actions(driver); // heare you state ActionBuider build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden WebElement m2m= driver.findElement(By.xpath("//*[@id='signup']"));//the previous non visible element m2m.click(); WebElement EmailsignUpButton = driver.findElement(By.xpath("//*[@id='signupModal']/div[2]/div[3]")); delayFor(2000); EmailsignUpButton.click(); WebElement NameTextBox = driver.findElement(By.xpath("//*[@id='signup-name']")); delayFor(2000); NameTextBox.sendKeys("MOhammad Rahman"); WebElement emailTextBox = driver.findElement(By.xpath("//*[@id='signup-email']")); delayFor(2000); emailTextBox.sendKeys("QA@yahoo.com"); WebElement passWordBox = driver.findElement(By.xpath("//*[@id='signup-password']")); delayFor(2000); passWordBox.sendKeys("123456"); Select month = new Select(driver.findElement(By.xpath("//*[@id='signup-birthdate-month']"))); month.selectByVisibleText("October"); Select day = new Select(driver.findElement(By.xpath("//*[@id='signup-birthdate-day']"))); day.selectByVisibleText("12"); Select year = new Select(driver.findElement(By.xpath("//*[@id='signup-birthdate-year']"))); year.selectByVisibleText("1984"); WebElement EmailsignUpsubmitButton = driver.findElement(By.xpath("//*[@id='signup-submit']")); delayFor(2000); EmailsignUpsubmitButton.click(); driver.close(); } }
true
0582ce10453403aa85a27ebb0e8ab07d5423b030
Java
kimyh5910/java
/chap07/src/chap07/ControllerTest.java
UTF-8
240
2.234375
2
[]
no_license
package chap07; public class ControllerTest { public static void main(String[] args) { // TODO Auto-generated method stub Controller[] c = { new TV5(false), new Radio5(true) }; for (Controller con : c) { con.show(); } } }
true
035951db5c8e3de9dd46b3f4ef5fc7119113a1ae
Java
arydz/advanced-jpa-demo
/src/main/java/com/arydz/jpa/hibernate/demo/entity/Course.java
UTF-8
3,125
2.640625
3
[]
no_license
package com.arydz.jpa.hibernate.demo.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.UpdateTimestamp; import org.hibernate.annotations.Where; import javax.persistence.Cacheable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Getter @Entity @ToString(of = "name") @NamedQueries(value = { @NamedQuery(name = "get_all_courses", query = "select c from Course c"), @NamedQuery(name = "get_all_courses_with_join_fetch", query = "select c from Course c JOIN FETCH c.studentList s"), @NamedQuery(name = "get_100_steps_courses", query = "select c from Course c where name like '%100 steps'") }) @Cacheable // Those annotations are for Soft Delete - it's mean that row isn't removed from table, but appropriate column (in our example 'is_deleted') stores // information, if row was deleted. Below we write appropriate query to do this. // Column get updated in the database, however the entity in the cache does not get updated because hibernate doesn't now know at all about what // happening in this query. For that we need to create PreRemove hook, which will update entity isDelete attribute to true. @SQLDelete(sql = "update course set is_deleted=true where id=?") // With annotation @Where we specify that only rows with false value in 'is_delete' column should be return. We want only active rows (not deleted). // This clause is added to hibernate query @Where(clause = "is_deleted = false") // Native queries doesn't support it public class Course { @Id @GeneratedValue private Long id; @Setter private String name; // Default fetch type is LAZY @OneToMany(mappedBy = "course") //, fetch = FetchType.EAGER) private List<Review> reviewList = new ArrayList<>(); // In many to many relationships, owning side of relation is not important. // Course is not owning side! @ManyToMany(mappedBy = "courseList") @JsonIgnore private List<Student> studentList = new ArrayList<>(); @CreationTimestamp private LocalDateTime createdDate; @UpdateTimestamp private LocalDateTime lastUpdatedDate; private boolean isDeleted; // Without it Course entity would stays outdated comparing to database @PreRemove private void preRemove() { this.isDeleted = true; } public void addReview(Review review) { this.reviewList.add(review); } public void removeReview(Review review) { this.reviewList.remove(review); } public void addStudent(Student student) { this.studentList.add(student); } public void removeReview(Student student) { this.studentList.remove(student); } protected Course() { } public Course(String name) { this.name = name; } }
true
bb5abd6f20a6e4a90226ee21500925febea260f8
Java
nablarch/nablarch-messaging-simulator
/src/main/java/please/change/me/simulator/incoming/http/launcher/HttpIncomingSimulatorLauncher.java
UTF-8
1,616
2.703125
3
[ "Apache-2.0" ]
permissive
package please.change.me.simulator.incoming.http.launcher; import nablarch.core.repository.SystemRepository; import nablarch.core.repository.di.DiContainer; import nablarch.core.repository.di.config.xml.XmlComponentDefinitionLoader; import nablarch.fw.web.HttpServer; /** * HTTPメッセージ受信シミュレータを起動するクラス。 * <p/> * 下記の処理を行う。 * 1. リポジトリ設定の読み込みとハンドラー構成の初期化 * 2. NTF内蔵サーバ({@link HttpServer})の起動 * <p/> * クラスパス上の {@code incoming-http-simulator-component-configuration.xml} をコンポーネント定義ファイルとして読み込んで、リポジトリを初期化する。 * NTF内蔵サーバは、リポジトリから {@code server} というコンポーネント名で取得する。 * * @author Ryo TANAKA * @since 1.4.2 */ public final class HttpIncomingSimulatorLauncher { /** プライベートコンストラクタ。 */ private HttpIncomingSimulatorLauncher() { } /** * エントリポイント。 * @param args 実行時引数 */ public static void main(String... args) { initializeRepository(); HttpServer server = SystemRepository.get("server"); server.start(); } /** リポジトリの初期化を行う。*/ public static void initializeRepository() { // リポジトリ初期化 DiContainer container = new DiContainer(new XmlComponentDefinitionLoader("incoming-http-simulator-component-configuration.xml")); SystemRepository.load(container); } }
true
e10d3bae230f310601b45dd5d17907d9fd77c049
Java
TalgatAkhm/EasyRealTalk
/src/main/java/ru/mtl/VoidVoice/model/MainVector.java
UTF-8
8,775
2.859375
3
[ "MIT" ]
permissive
package ru.mtl.VoidVoice.model; import java.util.ArrayList; import java.util.List; public class MainVector { private List<Double> vectorNd; private MainVectorType mainVectorType; private List<Finger> leftFingerList; private List<Finger> rightFingerList; private Hand leftHand; private Hand rightHand; private List<Double> leftHandVecor; private List<Double> rightHandVecor; private List<Double> leftFingersListVector; private List<Double> rightFingersListVector; private List<Double> touchListVector; private List<List<Double>> touchList; public MainVector(MotionVector motionVector) throws IllegalArgumentException { if ((motionVector.getLeftFingersList() == null && motionVector.getRightFingersList() == null)) { throw new IllegalArgumentException("Both finger lists are empty"); } else if (motionVector.getRightFingersList() != null && motionVector.getLeftFingersList() == null) { mainVectorType = MainVectorType.OnlyRightHand; rightHandVecor = new ArrayList<>(); rightHandVecor.addAll(motionVector.getRightHand().getPalmNormalVector().getCoordinatesList()); rightHandVecor.addAll(motionVector.getRightHand().getPalmDirectionVector().getCoordinatesList()); rightHandVecor.addAll(motionVector.getRightHand().getPalmVelocity().getCoordinatesList()); rightFingersListVector = new ArrayList<>(); for (Finger finger : motionVector.getRightFingersList()) { rightFingersListVector.addAll(finger.getFingerDirectionVector().getCoordinatesList()); } // получится вектор длины 10. touchListVector = new ArrayList<>(); for (int i = 0; motionVector.getTouchList() != null && i < motionVector.getTouchList().size(); i++) { for (int j = 0; j < motionVector.getTouchList().get(i).size() - 1; j++) { touchListVector.add(motionVector.getTouchList().get(i).get(j)); } } leftHandVecor = null; leftFingersListVector = null; vectorNd = new ArrayList<>(); vectorNd.addAll(rightHandVecor); vectorNd.addAll(rightFingersListVector); vectorNd.addAll(touchListVector); this.rightHand = motionVector.getRightHand(); this.rightFingerList = motionVector.getRightFingersList(); this.touchList = motionVector.getTouchList(); } else if (motionVector.getLeftFingersList() != null && motionVector.getRightFingersList() == null) { mainVectorType = MainVectorType.OnlyLeftHand; leftHandVecor = new ArrayList<>(); leftHandVecor.addAll(motionVector.getLeftHand().getPalmNormalVector().getCoordinatesList()); leftHandVecor.addAll(motionVector.getLeftHand().getPalmDirectionVector().getCoordinatesList()); leftHandVecor.addAll(motionVector.getLeftHand().getPalmVelocity().getCoordinatesList()); leftFingersListVector = new ArrayList<>(); for (Finger finger : motionVector.getLeftFingersList()) { leftFingersListVector.addAll(finger.getFingerDirectionVector().getCoordinatesList()); } // получится вектор длины 10. touchListVector = new ArrayList<>(); for (int i = 0; motionVector.getTouchList() != null && i < motionVector.getTouchList().size(); i++) { for (int j = 0; j < motionVector.getTouchList().get(i).size() - 1; j++) { touchListVector.add(motionVector.getTouchList().get(i).get(j)); } } rightHandVecor = null; rightFingersListVector = null; vectorNd = new ArrayList<>(); vectorNd.addAll(leftHandVecor); vectorNd.addAll(leftFingersListVector); vectorNd.addAll(touchListVector); this.leftHand = motionVector.getLeftHand(); this.leftFingerList = motionVector.getLeftFingersList(); this.touchList = motionVector.getTouchList(); } else { mainVectorType = MainVectorType.BothHands; leftHandVecor = new ArrayList<>(); leftHandVecor.addAll(motionVector.getLeftHand().getPalmNormalVector().getCoordinatesList()); leftHandVecor.addAll(motionVector.getLeftHand().getPalmDirectionVector().getCoordinatesList()); leftHandVecor.addAll(motionVector.getLeftHand().getPalmVelocity().getCoordinatesList()); rightHandVecor = new ArrayList<>(); rightHandVecor.addAll(motionVector.getRightHand().getPalmNormalVector().getCoordinatesList()); rightHandVecor.addAll(motionVector.getRightHand().getPalmDirectionVector().getCoordinatesList()); rightHandVecor.addAll(motionVector.getRightHand().getPalmVelocity().getCoordinatesList()); leftFingersListVector = new ArrayList<>(); for (Finger finger : motionVector.getLeftFingersList()) { leftFingersListVector.addAll(finger.getFingerDirectionVector().getCoordinatesList()); } rightFingersListVector = new ArrayList<>(); for (Finger finger : motionVector.getRightFingersList()) { rightFingersListVector.addAll(finger.getFingerDirectionVector().getCoordinatesList()); } //получится вектор длины 50. touchListVector = new ArrayList<>(); for (List<Double> layer : motionVector.getTouchList()) { touchListVector.addAll(layer); } vectorNd = new ArrayList<>(); vectorNd.addAll(leftHandVecor); vectorNd.addAll(rightHandVecor); vectorNd.addAll(leftFingersListVector); vectorNd.addAll(rightFingersListVector); vectorNd.addAll(touchListVector); this.rightHand = motionVector.getRightHand(); this.rightFingerList = motionVector.getRightFingersList(); this.leftHand = motionVector.getLeftHand(); this.leftFingerList = motionVector.getLeftFingersList(); this.touchList = motionVector.getTouchList(); } for (int i = 0; i < touchListVector.size(); i++) { touchListVector.set(i, 0d); } } // если нужно получить значение соприкосновения любых двух пальцев // нумерация: левый мезинец 0; левый большой 4; правый мезинец 5; правый большой 9. Double getTouchOfIandJfingers(int i, int j) { if (this.mainVectorType.equals(MainVectorType.OnlyLeftHand) || this.mainVectorType.equals(MainVectorType.OnlyRightHand)) { if (i == j) { return -1.d; } else if (i > j) { return this.touchList.get(i).get(j); } else { return this.touchList.get(j).get(i); } } else { if (i == j) { return -1.d; } else if (i > j) { if (j <= 4) { return this.touchList.get(j).get(i); } else { return this.touchList.get(9 - j).get(i - j - 1); } } else { if (i <= 4) { return this.touchList.get(i).get(j); } else { return this.touchList.get(9 - i).get(j - i - 1); } } } } public List<Double> getVectorNd() { return vectorNd; } public MainVectorType getType() { return mainVectorType; } public List<Double> getTouchListVector() { return touchListVector; } public MainVectorType getMainVectorType() { return mainVectorType; } public List<Double> getLeftHandVecor() { return leftHandVecor; } public List<Double> getRightHandVecor() { return rightHandVecor; } public List<Double> getLeftFingersListVector() { return leftFingersListVector; } public List<Double> getRightFingersListVector() { return rightFingersListVector; } public List<Finger> getLeftFingerList() { return leftFingerList; } public List<Finger> getRightFingerList() { return rightFingerList; } public Hand getLeftHand() { return leftHand; } public Hand getRightHand() { return rightHand; } }
true
4aa56310d4c34c813b5a0754b4e1e7e337219848
Java
Kinjaljain047/ibm-fsd-000ggc
/eclipse-workspace/spring-rest-10thsept/src/main/java/comm/spring/CustomerService.java
UTF-8
172
1.851563
2
[]
no_license
package comm.spring; import java.util.List; public interface CustomerService { public List<Customer> getAllCustomers(); public void saveCustomer(Customer theCustomer); }
true
0074e30abf5db2f5bf408c0f65b4301f766d4f3a
Java
r3ndogg/mergeRepo
/COATapp-Merged/app/src/main/java/au/edu/federation/myapplication/Global.java
UTF-8
1,767
2.84375
3
[]
no_license
package au.edu.federation.myapplication; import android.content.Context; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import au.edu.federation.myapplication.DietaryLogPackage.DietaryLogItem; /** * Modified by Nick to remove activity references, and implement a singleton pattern * * If you want to access things stored in this, make a local Global variable, and instantiate * it with getInstance */ public class Global { private static Global instance; //Temporary storage of dietary log, Needs to sync with on phone Database asap. public List<DietaryLogItem> dietaryLogList = new ArrayList<DietaryLogItem>(); //To store what treasure have been collected. Needs to be refreshed each day. public ArrayList<String> treasureList = new ArrayList<String>(); //Tracks the balance across the application public int balance = 0 ; public Context appContext = null ; //Specify the constructor to do nothing, to stop people making more than one of these private Global(){} //gets the instance if it exists, creates it if doesn't public static synchronized Global getInstance(){ if (instance == null){ instance = new Global(); } return instance; } //Create timer to automatically upload data at set intervals of time public void createTimer() { Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { Control.uploadData(); } }, 1000, 15*60*1000);//minutes*seconds*milliseconds, 2*60*1000 = 15 minutes //Wait 1 second before executing, execute every 2 minutes after } }
true
dbd8c80af90d6b4cd6ea1c4c0e7360937517cf4d
Java
misonamoo03/SenderRoader
/Sender/src/main/java/com/misonamoo/smileway/domain/UserVO.java
UTF-8
2,065
2.03125
2
[]
no_license
package com.misonamoo.smileway.domain; public class UserVO { private String SUSER_ID; private String SUSER_PW; private String SUSER_EMAIL; private String SPHONE; private String SUSER_NAME; private String SUSER_ADDRESS; private String SUSER_POSTCODE; private String SUSER_AGRE_ESSEN; private String SUSER_AGRE_OPTION; public String getSUSER_ID() { return SUSER_ID; } public void setSUSER_ID(String SUSER_ID) { this.SUSER_ID = SUSER_ID; } public String getSUSER_PW() { return SUSER_PW; } public void setSUSER_PW(String SUSER_PW) { this.SUSER_PW = SUSER_PW; } public String getSUSER_EMAIL() { return SUSER_EMAIL; } public void setSUSER_EMAIL(String SUSER_EMAIL) { this.SUSER_EMAIL = SUSER_EMAIL; } public String getSPHONE() { return SPHONE; } public void setSPHONE(String SPHONE) { this.SPHONE = SPHONE; } public String getSUSER_NAME() { return SUSER_NAME; } public void setSUSER_NAME(String SUSER_NAME) { this.SUSER_NAME = SUSER_NAME; } public String getSUSER_ADDRESS() { return SUSER_ADDRESS; } public void setSUSER_ADDRESS(String SUSER_ADDRESS) { this.SUSER_ADDRESS = SUSER_ADDRESS; } public String getSUSER_POSTCODE() { return SUSER_POSTCODE; } public void setSUSER_POSTCODE(String SUSER_POSTCODE) { this.SUSER_POSTCODE = SUSER_POSTCODE; } public String getSUSER_AGRE_ESSEN() { return SUSER_AGRE_ESSEN; } public void setSUSER_AGRE_ESSEN(String SUSER_AGRE_ESSEN) { this.SUSER_AGRE_ESSEN = SUSER_AGRE_ESSEN; } public String getSUSER_AGRE_OPTION() { return SUSER_AGRE_OPTION; } public void setSUSER_AGRE_OPTION(String SUSER_AGRE_OPTION) { this.SUSER_AGRE_OPTION = SUSER_AGRE_OPTION; } @Override public String toString() { return "UserVO [SUSER_ID=" + SUSER_ID + ", SUSER_PW=" + SUSER_PW + ", SUSER_EMAIL=" + SUSER_EMAIL + ", SPHONE=" + SPHONE + ", SUSER_NAME=" + SUSER_NAME + ", SUSER_ADDRESS=" + SUSER_ADDRESS + ", SUSER_POSTCODE=" + SUSER_POSTCODE + ", SUSER_AGRE_ESSEN=" + SUSER_AGRE_ESSEN + ", SUSER_AGRE_OPTION=" + SUSER_AGRE_OPTION + "]"; } }
true
1da921045283f31487c1e8ce00df3cd064040b4a
Java
mrlanu/warmsnow
/schedule-service/src/main/java/io/lanu/warmsnow/scheduleservice/services/ScheduleServiceImpl.java
UTF-8
3,804
2.4375
2
[]
no_license
package io.lanu.warmsnow.scheduleservice.services; import io.lanu.warmsnow.scheduleservice.models.TaskViewModel; import io.lanu.warmsnow.common_models.requests.FieldUpgradeRequest; import io.lanu.warmsnow.scheduleservice.clients.VillagesServiceClient; import io.lanu.warmsnow.scheduleservice.entities.TaskEntity; import io.lanu.warmsnow.scheduleservice.repositories.ScheduleRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Service @Slf4j public class ScheduleServiceImpl implements ScheduleService { private ScheduleRepository scheduleRepository; private ThreadPoolTaskScheduler threadPoolTaskScheduler; private VillagesServiceClient villagesServiceClient; private static final Map<String, ScheduledFuture> SCHEDULED_FUTURE_MAP = new ConcurrentHashMap<>(); public ScheduleServiceImpl(ScheduleRepository scheduleRepository, ThreadPoolTaskScheduler threadPoolTaskScheduler, VillagesServiceClient villagesServiceClient) { this.scheduleRepository = scheduleRepository; this.threadPoolTaskScheduler = threadPoolTaskScheduler; this.villagesServiceClient = villagesServiceClient; } @Override public String scheduleTask(FieldUpgradeRequest request) { final String taskId = UUID.randomUUID().toString(); // count duration for the task long scheduledQueueDuration = getDurationsAllTasksFromQueue(request.getVillageId()); long finalDuration = request.getField().getTimeToNextLevel() * 1000 + scheduledQueueDuration; //schedule the task ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule( () -> { //completed task removing from map & DB log.info("Task complete."); deleteByTaskId(taskId); SCHEDULED_FUTURE_MAP.remove(taskId); villagesServiceClient.upgradeField(request); }, new Date(System.currentTimeMillis() + finalDuration)); log.info("Task has been scheduled. Duration - " + finalDuration); //creating new Task end persist it to map & DB TaskEntity newTask = new TaskEntity(taskId, request.getVillageId(), request.getField().getPosition(), request.getField().getLevel(), finalDuration); scheduleRepository.save(newTask); SCHEDULED_FUTURE_MAP.put(taskId, scheduledFuture); return taskId; } private Long getDurationsAllTasksFromQueue(String villageId){ return scheduleRepository.findAllByVillageId(villageId) .stream() .mapToLong(t -> SCHEDULED_FUTURE_MAP.get(t.getTaskId()).getDelay(TimeUnit.MILLISECONDS)) .sum(); } @Override public List<TaskViewModel> findAllTasksByVillageId(String villageId) { List<TaskEntity> taskEntities = scheduleRepository.findAllByVillageId(villageId); return taskEntities.stream() .map(t -> { long timeLeft = SCHEDULED_FUTURE_MAP.get(t.getTaskId()).getDelay(TimeUnit.MILLISECONDS) / 1000; return new TaskViewModel(t.getTaskId(), t.getPosition(), t.getLevel(), timeLeft); }) .collect(Collectors.toList()); } private void deleteByTaskId(String taskId) { scheduleRepository.deleteByTaskId(taskId); } }
true
7198e2ba3a113a5b64b78b2d5f8a29c1a69bb13f
Java
subhashjha35/cloudbreak
/core/src/main/java/com/sequenceiq/cloudbreak/service/recipe/GeneratedRecipeService.java
UTF-8
542
1.773438
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0" ]
permissive
package com.sequenceiq.cloudbreak.service.recipe; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.domain.stack.cluster.host.GeneratedRecipe; import com.sequenceiq.cloudbreak.repository.GeneratedRecipeRepository; @Service public class GeneratedRecipeService { @Inject private GeneratedRecipeRepository generatedRecipeRepository; public GeneratedRecipe save(GeneratedRecipe generatedRecipe) { return generatedRecipeRepository.save(generatedRecipe); } }
true
21024512b79347f2155de4caee620d835bd5763e
Java
kristinclemens/ratpack
/ratpack-pac4j/src/main/java/ratpack/pac4j/RatpackPac4j.java
UTF-8
24,178
1.664063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ratpack.pac4j; import com.google.common.collect.ImmutableList; import org.pac4j.core.authorization.Authorizer; import org.pac4j.core.client.Client; import org.pac4j.core.client.Clients; import org.pac4j.core.client.DirectClient; import org.pac4j.core.context.WebContext; import org.pac4j.core.credentials.Credentials; import org.pac4j.core.exception.RequiresHttpAction; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.profile.UserProfile; import ratpack.exec.Blocking; import ratpack.exec.Downstream; import ratpack.exec.Operation; import ratpack.exec.Promise; import ratpack.func.Block; import ratpack.handling.Chain; import ratpack.handling.Context; import ratpack.handling.Handler; import ratpack.handling.UserId; import ratpack.http.Request; import ratpack.pac4j.internal.Pac4jAuthenticator; import ratpack.pac4j.internal.Pac4jSessionKeys; import ratpack.pac4j.internal.RatpackWebContext; import ratpack.path.PathBinding; import ratpack.registry.Registry; import ratpack.session.Session; import ratpack.util.Types; import java.util.List; import java.util.Optional; import static com.google.common.collect.Iterables.all; import static java.util.Arrays.asList; /** * Provides integration with the <a href="http://www.pac4j.org">Pac4j library</a> for authentication and authorization. * <p> * Pac4j support many different authentication providers, such as external sources like GitHub, Twitter, Facebook etc., as well * as proprietary local authentication sources. * <p> * The {@link #authenticator(Client[])} method provides a handler that implements the authentication process, * and is required in all apps wanting to use authentication. * <p> * The {@link #requireAuth(Class, Authorizer...)} method provides a handler that acts like a filter, ensuring that the user is authenticated for all requests. * This can be used for requiring authentication for all requests starting with a particular request path for example. * <p> * The {@link #userProfile(Context)}, {@link #login(Context, Class)} and {@link #logout(Context)} methods provide programmatic authentication mechanisms. */ public class RatpackPac4j { /** * The default path to the authenticator, {@value}, used by {@link #authenticator(Client[])}. */ public static final String DEFAULT_AUTHENTICATOR_PATH = "authenticator"; private RatpackPac4j() { } /** * Calls {@link #authenticator(String, Client[])} with {@link #DEFAULT_AUTHENTICATOR_PATH}. * * @param clients the supported auth clients * @return a handler */ public static Handler authenticator(Client<?, ?>... clients) { return authenticator(DEFAULT_AUTHENTICATOR_PATH, clients); } /** * Creates a handler that implements authentication when the request path matches, and makes a Pac4j {@link Clients} available to downstream handlers otherwise. * <p> * This methods performs the same function as {@link #authenticator(String, ClientsProvider)}, * but is more convenient to use when the {@link Client} instances do not depend on the request environment. * * @param path the path to bind the authenticator to (relative to the current request path binding) * @param clients the supported authentication clients * @return a handler */ public static Handler authenticator(String path, Client<?, ?>... clients) { ImmutableList<Client<?, ?>> clientList = ImmutableList.copyOf(clients); return authenticator(path, ctx -> clientList); } /** * Provides the set of Pac4j {@link Client clients}. * * @see #authenticator(String, ClientsProvider) * @since 1.1 */ public interface ClientsProvider { Iterable<? extends Client<?, ?>> get(Context ctx); } /** * Creates a handler that implements authentication when the request path matches, and makes a Pac4j {@link Clients} available to downstream handlers otherwise. * <p> * This handler <b>MUST</b> be <b>BEFORE</b> any code in the handler pipeline that tries to identify the user, such as a {@link #requireAuth} handler in the pipeline. * It should be added to the handler chain via the {@link Chain#all(Handler)}. * That is, it should not be added with {@link Chain#get(Handler)} or any method that filters based on request method. * It is common for this handler to be one of the first handlers in the pipeline. * <p> * This handler performs two different functions, based on whether the given path matches the {@link PathBinding#getPastBinding()} component of the current path binding. * If the path matches, the handler will attempt authentication, which may involve redirecting to an external auth provider, which may then redirect back to this handler. * If authentication is successful, the {@link UserProfile} of the authenticated user will be placed into the session. * The user will then be redirected back to the URL that initiated the authentication. * <p> * If the path does not match, the handler will push an instance of {@link Clients} into the context registry and pass control downstream. * The {@link Clients} instance will be retrieved downstream by any {@link #requireAuth(Class, Authorizer...)} handler (or use of {@link #login(Context, Class)}. * * @param path the path to bind the authenticator to (relative to the current request path binding) * @param clientsProvider the provider of authentication clients * @return a handler */ public static Handler authenticator(String path, ClientsProvider clientsProvider) { return new Pac4jAuthenticator(path, clientsProvider); } /** * An authentication and authorization “filter”. * <p> * This handler can be used to ensure that a user profile is available for all downstream handlers. * If there is no user profile present in the session (i.e. user not logged in), authentication will be initiated based on the given client type (i.e. redirect to the {@link #authenticator(Client[])} handler). * If there is a {@link UserProfile} present in the session, this handler will push the user profile into the context registry before delegating downstream. * If there is a {@link UserProfile} present in the context registry, this handler will simply delegate downstream. * <p> * If there is a {@link UserProfile}, <b>each</b> of the given authorizers will be tested in turn and all must return true. * If so, control will flow to the next handler. * Otherwise, a {@code 403} {@link Context#clientError(int) client error} will be issued. * <p> * This handler requires a {@link Clients} instance available in the context registry. * As such, this handler should be downstream of the {@link #authenticator(Client[])} handler. * * <pre class="java">{@code * import org.pac4j.core.profile.UserProfile; * import org.pac4j.http.client.indirect.IndirectBasicAuthClient; * import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; * import ratpack.guice.Guice; * import ratpack.pac4j.RatpackPac4j; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import static org.junit.Assert.assertEquals; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(s -> s * .registry(Guice.registry(b -> b.module(SessionModule.class))) * .handlers(c -> c * .all(RatpackPac4j.authenticator(new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()))) * .get("logout", ctx -> RatpackPac4j.logout(ctx).then(() -> ctx.render("logged out"))) * .prefix("require-authn", a -> a * .all(RatpackPac4j.requireAuth(IndirectBasicAuthClient.class)) * .get(ctx -> ctx.render("Hello " + ctx.get(UserProfile.class).getId())) * ) * .prefix("require-authz", a -> a * .all(RatpackPac4j.requireAuth(IndirectBasicAuthClient.class, (ctx, profile) -> { return "special-user".equals(profile.getId()); })) * .get(ctx -> ctx.render("Hello " + ctx.get(UserProfile.class).getId())) * ) * .get(ctx -> ctx.render("no auth required")) * ) * ).test(httpClient -> { * httpClient.requestSpec(r -> r.redirects(1)); * assertEquals("no auth required", httpClient.getText()); * * assertEquals(401, httpClient.get("require-authn").getStatusCode()); * assertEquals("Hello user", httpClient.requestSpec(r -> r.basicAuth("user", "user")).getText("require-authn")); * * assertEquals(403, httpClient.get("require-authz").getStatusCode()); * * assertEquals("logged out", httpClient.getText("logout")); * httpClient.resetRequest(); * * assertEquals(401, httpClient.get("require-authz").getStatusCode()); * assertEquals("Hello special-user", httpClient.requestSpec(r -> r.basicAuth("special-user", "special-user")).getText("require-authz")); * }); * } * } * }</pre> * * @param clientType the client type to use to authenticate with if required * @param authorizers the authorizers to check authorizations * @return a handler */ @SafeVarargs @SuppressWarnings("varargs") public static <C extends Credentials, U extends UserProfile> Handler requireAuth(Class<? extends Client<C, U>> clientType, Authorizer<? super U>... authorizers) { List<Authorizer<? super U>> authorizerList = asList(authorizers); return ctx -> RatpackPac4j.login(ctx, clientType).then(userProfile -> { if (authorizerList.isEmpty()) { ctx.next(Registry.single(userProfile)); } else { RatpackWebContext.from(ctx, false).then(webContext -> { if (all(authorizerList, a -> a == null || a.isAuthorized(webContext, userProfile))) { ctx.next(Registry.single(userProfile)); } else { ctx.clientError(403); } }); } }); } /** * Logs the user in by redirecting to the authenticator, or provides the user profile if already logged in. * <p> * This method can be used to programmatically initiate a log in, if required. * If the user is already logged in, the user profile will be provided via the returned promise. * If the user is not already logged in, the promise will not be fulfilled and the user will be redirected to the authenticator. * As such, like {@link #requireAuth(Class, Authorizer...)}, this can only be used downstream of the {@link #authenticator(Client[])} handler. * * <pre class="java">{@code * import org.pac4j.http.client.indirect.IndirectBasicAuthClient; * import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; * import ratpack.guice.Guice; * import ratpack.http.client.ReceivedResponse; * import ratpack.pac4j.RatpackPac4j; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import java.util.Optional; * * import static org.junit.Assert.assertEquals; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(s -> s * .registry(Guice.registry(b -> b.module(SessionModule.class))) * .handlers(c -> c * .all(RatpackPac4j.authenticator(new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()))) * .get("auth", ctx -> RatpackPac4j.login(ctx, IndirectBasicAuthClient.class).then(p -> ctx.redirect("/"))) * .get(ctx -> * RatpackPac4j.userProfile(ctx) * .route(Optional::isPresent, p -> ctx.render("Hello " + p.get().getId())) * .then(p -> ctx.render("not authenticated")) * ) * ) * ).test(httpClient -> { * // user is not authenticated * assertEquals("not authenticated", httpClient.getText()); * * // authenticate… * ReceivedResponse response = httpClient.requestSpec(r -> r.basicAuth("user", "user")).get("auth"); * * // authenticated (redirected to /) * assertEquals("Hello user", response.getBody().getText()); * }); * } * } * }</pre> * * @param ctx the handling context * @param clientType the client type to authenticate with * @return a promise for the user profile, fulfilled if logged in */ public static <C extends Credentials, U extends UserProfile> Promise<U> login(Context ctx, Class<? extends Client<C, U>> clientType) { if (isDirect(clientType)) { return userProfile(ctx) .flatMap(p -> { if (p.isPresent()) { Optional<U> cast = Types.cast(p); return Promise.value(cast); } else { return performDirectAuthentication(ctx, clientType); } }) .route(p -> !p.isPresent(), p -> ctx.clientError(401)) .map(Optional::get); } else { return userProfile(ctx) .route(p -> !p.isPresent(), p -> initiateAuthentication(ctx, clientType)) .map(Optional::get) .map(Types::<U>cast); } } /** * Obtains the logged in user's profile, if the user is logged in. * <p> * The promised optional will be empty if the user is not authenticated. * <p> * This method should be used if the user <i>may</i> have been authenticated. * That is, when the the need for the profile is not downstream of an {@link #requireAuth(Class, Authorizer...)} handler, * as the auth handler puts the profile into the context registry for easy retrieval. * <p> * This method returns a promise as it will attempt to load the profile from the session if it * isn't already in the context registry. * * <pre class="java">{@code * import io.netty.handler.codec.http.HttpHeaderNames; * import org.pac4j.core.profile.UserProfile; * import org.pac4j.http.client.indirect.IndirectBasicAuthClient; * import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; * import ratpack.guice.Guice; * import ratpack.http.client.ReceivedResponse; * import ratpack.pac4j.RatpackPac4j; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import java.util.Optional; * * import static org.junit.Assert.assertEquals; * import static org.junit.Assert.assertTrue; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(s -> s * .registry(Guice.registry(b -> b.module(SessionModule.class))) * .handlers(c -> c * .all(RatpackPac4j.authenticator(new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()))) * .prefix("auth", a -> a * .all(RatpackPac4j.requireAuth(IndirectBasicAuthClient.class)) * .get(ctx -> { * ctx.render("Hello " + ctx.get(UserProfile.class).getId()); * }) * ) * .get("no-auth", ctx -> { * RatpackPac4j.userProfile(ctx) * .route(Optional::isPresent, p -> ctx.render("Hello " + p.get().getId())) * .then(p -> ctx.render("not authenticated")); * }) * ) * ).test(httpClient -> { * // User is not authenticated * assertEquals("not authenticated", httpClient.getText("no-auth")); * * // Authenticate… * ReceivedResponse response = httpClient.requestSpec(r -> r.redirects(0)).get("auth"); * assertEquals(302, response.getStatusCode()); * String redirectTo = response.getHeaders().get(HttpHeaderNames.LOCATION); * assertEquals(401, httpClient.get(redirectTo).getStatusCode()); * response = httpClient.requestSpec(r -> r * .basicAuth("user", "user") * .redirects(0) * ).post(redirectTo); * assertEquals(302, response.getStatusCode()); * redirectTo = response.getHeaders().get(HttpHeaderNames.LOCATION); * assertTrue(redirectTo.endsWith("/auth")); * assertEquals("Hello user", httpClient.getText(redirectTo)); * * // User is now authenticated * assertEquals("Hello user", httpClient.getText("no-auth")); * }); * } * } * }</pre> * * @param ctx the handling context * @return a promise for the user profile * @see #userProfile(Context, Class) */ public static Promise<Optional<UserProfile>> userProfile(Context ctx) { return userProfile(ctx, UserProfile.class); } /** * Obtains the logged in user's profile, of the given type, if the user is logged in. * <p> * The promised optional will be empty if the user is not authenticated. * If there exists a {@link UserProfile} for the current user but it is not compatible with the requested type, * the returned promise will be a failure with a {@link ClassCastException}. * <p> * This method should be used if the user <i>may</i> have been authenticated. * That is, when the the need for the profile is not downstream of an {@link #requireAuth(Class, Authorizer...)} handler, * as the auth handler puts the profile into the context registry for easy retrieval. * <p> * This method returns a promise as it will attempt to load the profile from the session if it * isn't already in the context registry. * * @param ctx the handling context * @param type the type of the user profile * @param <T> the type of the user profile * @return a promise for the user profile * @see #userProfile(Context) */ public static <T extends UserProfile> Promise<Optional<T>> userProfile(Context ctx, Class<T> type) { return Promise.async(f -> toProfile(type, f, ctx.maybeGet(UserProfile.class), () -> ctx.get(Session.class) .get(Pac4jSessionKeys.USER_PROFILE) .then(p -> { if (p.isPresent()) { ctx.getRequest().add(UserId.class, UserId.of(p.get().getId())); } toProfile(type, f, p, () -> f.success(Optional.<T>empty())); }) ) ); } /** * Logs out the current user, removing their profile from the session. * <p> * The returned operation simply removes the profile from the session, regardless of whether it's actually there or not. * * <pre class="java">{@code * import org.pac4j.http.client.indirect.IndirectBasicAuthClient; * import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator; * import ratpack.guice.Guice; * import ratpack.http.client.ReceivedResponse; * import ratpack.pac4j.RatpackPac4j; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import java.util.Optional; * * import static org.junit.Assert.assertEquals; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(s -> s * .registry(Guice.registry(b -> b.module(SessionModule.class))) * .handlers(c -> c * .all(RatpackPac4j.authenticator(new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator()))) * .get("auth", ctx -> RatpackPac4j.login(ctx, IndirectBasicAuthClient.class).then(p -> ctx.redirect("/"))) * .get(ctx -> * RatpackPac4j.userProfile(ctx) * .route(Optional::isPresent, p -> ctx.render("Hello " + p.get().getId())) * .then(p -> ctx.render("not authenticated")) * ) * .get("logout", ctx -> * RatpackPac4j.logout(ctx).then(() -> ctx.redirect("/")) * ) * ) * ).test(httpClient -> { * // user is not authenticated * assertEquals("not authenticated", httpClient.getText()); * * // authenticate… * ReceivedResponse response = httpClient.requestSpec(r -> r.basicAuth("user", "user")).get("auth"); * * // authenticated (redirected to /) * assertEquals("Hello user", response.getBody().getText()); * * // logout (redirected to /) * assertEquals("not authenticated", httpClient.getText("logout")); * }); * } * } * }</pre> * * @param ctx the handling context * @return the logout operation */ public static Operation logout(Context ctx) { return ctx.get(Session.class) .remove(Pac4jSessionKeys.USER_PROFILE); } /** * Adapts a Ratpack {@link Context} to a Pac4j {@link WebContext}. * <p> * The returned WebContext does not have access to the request body. * {@link WebContext#getRequestParameters()} and associated methods will not include any * form parameters if the request was a form. * * @param ctx a Ratpack context * @return a Pac4j web context * @since 1.4 */ public static Promise<WebContext> webContext(Context ctx) { return Types.cast(RatpackWebContext.from(ctx, false)); } private static <T extends UserProfile> void toProfile(Class<T> type, Downstream<? super Optional<T>> downstream, Optional<UserProfile> userProfileOptional, Block onEmpty) throws Exception { if (userProfileOptional.isPresent()) { final UserProfile userProfile = userProfileOptional.get(); if (type.isInstance(userProfile)) { downstream.success(Optional.of(type.cast(userProfile))); } else { downstream.error(new ClassCastException("UserProfile is of type " + userProfile.getClass() + ", and is not compatible with " + type)); } } else { onEmpty.execute(); } } private static void initiateAuthentication(Context ctx, Class<? extends Client<?, ?>> clientType) { Request request = ctx.getRequest(); Clients clients = ctx.get(Clients.class); Client<?, ?> client = clients.findClient(clientType); RatpackWebContext.from(ctx, false).then(webContext -> { webContext.getSession().set(Pac4jSessionKeys.REQUESTED_URL, request.getUri()); try { client.redirect(webContext, true); } catch (Exception e) { if (e instanceof RequiresHttpAction) { webContext.sendResponse((RequiresHttpAction) e); return; } else { ctx.error(new TechnicalException("Failed to redirect", e)); } } webContext.sendResponse(); }); } private static <C extends Credentials, U extends UserProfile> Promise<Optional<U>> performDirectAuthentication(Context ctx, Class<? extends Client<C, U>> clientType) { return RatpackWebContext.from(ctx, false).flatMap(webContext -> Blocking.get(() -> { Clients clients = ctx.get(Clients.class); Client<C, U> client = clients.findClient(clientType); return userProfileFromCredentials(client, webContext); }) ); } private static <C extends Credentials, U extends UserProfile> Optional<U> userProfileFromCredentials(Client<C, U> client, RatpackWebContext webContext) throws RequiresHttpAction { C credentials = client.getCredentials(webContext); U userProfile = client.getUserProfile(credentials, webContext); return Optional.ofNullable(userProfile); } private static boolean isDirect(Class<? extends Client<?, ?>> clientType) { return DirectClient.class.isAssignableFrom(clientType); } }
true
e6546734ec2a5e2c21b8a11a3ecbf2e78aead72f
Java
mswiczar/AdmobHutmadsAdaptorAndroid
/com/huntmads/admobadaptor/InternalBrowser.java
UTF-8
7,147
2.140625
2
[]
no_license
package com.huntmads.admobadaptor; import java.io.IOException; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.net.Uri; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.LinearLayout; public class InternalBrowser extends Dialog { int ID_MAIN = 1; int ID_WEB = 2; int ID_BOTTOM = 3; Context _context; Button buttonBack; Button buttonForward; Button buttonRefresh; Button buttonStopRefresh; Button buttonOpen; WebView webView; Dialog thisDialog; public InternalBrowser(Context context, String url) { super(context); thisDialog = this; this._context = context; requestWindowFeature(Window.FEATURE_NO_TITLE); LinearLayout mailLayout = new LinearLayout(context); mailLayout.setId(ID_MAIN); mailLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); mailLayout.setOrientation(LinearLayout.VERTICAL); webView = new WebView(context); webView.setId(ID_WEB); webView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1f)); webView.loadUrl(url); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setBuiltInZoomControls(true); LinearLayout bottomLayout = new LinearLayout(context); mailLayout.setOrientation(LinearLayout.VERTICAL); bottomLayout.setId(ID_BOTTOM); bottomLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0f)); bottomLayout.setOrientation(LinearLayout.HORIZONTAL); bottomLayout.setBackgroundDrawable(GetDrawable(_context,"ib_bg_down.png")); buttonBack = AddButton(bottomLayout,"ib_arrow_left_regular.png","ib_arrow_left_press.png","ib_arrow_left_disabled.png"); buttonForward = AddButton(bottomLayout,"ib_arrow_right_regular.png","ib_arrow_right_press.png","ib_arrow_right_disabled.png"); buttonRefresh = AddButton(bottomLayout,"ib_apdate_regular.png","ib_apdate_press.png",null,true); buttonOpen = AddButton(bottomLayout,"ib_window_regular.png","ib_window_press.png",null); mailLayout.addView(webView); mailLayout.addView(bottomLayout); setContentView(mailLayout); getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); getWindow().setBackgroundDrawable(null); buttonBack.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { webView.goBack(); UpdateButtons(); } }); buttonForward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { webView.goForward(); UpdateButtons(); } }); buttonRefresh.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { webView.reload(); } }); buttonOpen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webView.getUrl())); _context.startActivity(intent); } catch (Exception e) { } thisDialog.dismiss(); } }); buttonStopRefresh.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { webView.stopLoading(); } }); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); buttonRefresh.setVisibility(buttonRefresh.VISIBLE); buttonStopRefresh.setVisibility(buttonRefresh.GONE); UpdateButtons(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); buttonRefresh.setVisibility(buttonRefresh.GONE); buttonStopRefresh.setVisibility(buttonRefresh.VISIBLE); } }); UpdateButtons(); } void UpdateButtons() { buttonBack.setEnabled(webView.canGoBack()); buttonForward.setEnabled(webView.canGoForward()); } Button AddButton(LinearLayout bottomLayout,String normal,String pressed, String disable) { return AddButton(bottomLayout, normal, pressed, disable,false); } Button AddButton(LinearLayout bottomLayout,String normal,String pressed, String disable,boolean isStop) { Button button = new Button(_context); button.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); button.setBackgroundDrawable(GetSelector(_context,normal, pressed, disable)); LinearLayout ll = new LinearLayout(_context); ll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1f)); ll.setGravity(Gravity.CENTER); ll.addView(button); if(isStop) { buttonStopRefresh = new Button(_context); buttonStopRefresh.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); buttonStopRefresh.setBackgroundDrawable(GetSelector(_context,"ib_close_regular.png", "ib_close_press.png", null)); ll.addView(buttonStopRefresh); buttonStopRefresh.setVisibility(buttonRefresh.GONE); } bottomLayout.addView(ll); return button; } public static StateListDrawable GetSelector(Context context, String normal,String pressed, String disable) { StateListDrawable result = new StateListDrawable(); result.addState((new int[] {-android.R.attr.state_pressed, android.R.attr.state_enabled}),GetDrawable(context,normal)); if(pressed!=null) result.addState((new int[] {android.R.attr.state_pressed, android.R.attr.state_enabled}),GetDrawable(context,pressed)); if(disable!=null) result.addState((new int[] {-android.R.attr.state_enabled}),GetDrawable(context,disable)); else result.addState((new int[] {-android.R.attr.state_enabled}),GetDrawable(context,normal)); return result; } public static Drawable GetDrawable(Context context, String fileName) { try { return Drawable.createFromStream(context.getAssets().open(fileName), null); } catch (IOException e) { return null; } } /* private Bitmap getBitmapFromAsset(String strName) throws IOException { AssetManager assetManager = context.getAssets(); InputStream istr = assetManager.open(strName); Bitmap bitmap = BitmapFactory.decodeStream(istr); return bitmap; } Drawable GetImage(String imageName) { try { Bitmap bitmap = getBitmapFromAsset(imageName); } catch (IOException e) { return null; } return null; }*/ }
true
886b0e8c63573c06ab309869fa34a1d53e792e59
Java
s-labus/java-functions
/HeronsFormula.java
UTF-8
789
3.296875
3
[]
no_license
// Straxinja Labus on 05/2020 public class HeronsFormula { public static double triangleArea(int a, int b, int c){ double s; double A; s = (a+b+c)/2.0; A = Math.sqrt(s*(s-a)*(s-b)*(s-c)); return A; } public static void main(String[] args){ double a; a = triangleArea(3, 3, 3); System.out.println("A triangle with sides 3, 3, 3 has an area of " + a + "."); a = triangleArea(3, 4, 5); System.out.println("A triangle with sides 3, 4, 5 has an area of " + a + "."); a = triangleArea(7, 8, 9); System.out.println("A triangle with sides 7, 8, 9 has an area of " + a + "."); System.out.println("A triangle with sides 4, 6, 9 has an area of " + triangleArea(4,6,9) + "."); System.out.println("A triangle with sides 9, 9, 9 has an area of " + triangleArea(9,9,9) + "."); } }
true
abc29d06cb6eba5a70ca9442bdbb45f162c7e3b2
Java
Yjiarui/Practise
/Square.java
UTF-8
1,004
3.625
4
[]
no_license
package homework; import java.util.Scanner; public class Square { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String a = scan.nextLine(); System.out.println(painting(n,a)); } private static String painting(int n, String a) { int y = n/2 ; for (int i = 0;i < n;i++){ if(i == 0 ){ for (int k = 0;k < n;k++){ System.out.print(a); } System.out.println( ); }else if (i == y-1){ for (int k = 0;k < n-1;k++){ System.out.print(a); } break; } else if(i != 0 && i != y -1){ System.out.print(a); for (int k = 0;k < n-2;k++){ System.out.print(" "); } System.out.println(a); } } return a; } }
true
66a48e930a0fe17a7aaec14248c6ec90d8ab70b2
Java
sereske/WireCalc
/src/ru/sereske/util/KLUtil.java
UTF-8
1,475
3.234375
3
[]
no_license
package ru.sereske.util; import java.util.*; /** * Created by Sergey on 07.05.2017. */ public class KLUtil { private static Map<Double, Double> values = new HashMap<>(); private static void init() { values.put(50.0, 1.2); values.put(100.0, 1.1); values.put(150.0, 1.05); values.put(250.0, 1.0); } public static double getKL(double diffX) { init(); List<Double> sortedList = new ArrayList(values.keySet()); Collections.sort(sortedList); double kl = 0.0; double l1 = 0.0; double l2 = 0.0; double k1 = 0.0; double k2 = 0.0; for (int i = 0; i < sortedList.size() - 1; i++) { if (sortedList.get(0) >= diffX) { kl = values.get(sortedList.get(0)); break; } if (sortedList.get(sortedList.size() - 1) <= diffX) { kl = values.get(sortedList.get(sortedList.size() - 1)); break; } if (sortedList.get(i) <= diffX && sortedList.get(i + 1) >= diffX) { l1 = sortedList.get(i); l2 = sortedList.get(i + 1); k1 = values.get(l1); k2 = values.get(l2); kl = k1 + (k2 - k1) * (diffX - l1) / (l2 - l1); break; } } return kl; } public static void main(String[] args) { System.out.println(getKL(250)); } }
true
1a970950916226d530a6720333ff70316952f0e7
Java
lizuohuan/daoyuan-admin
/src/main/java/com/magic/daoyuan/controller/SupplierAccountToBeCreditedController.java
UTF-8
6,123
2.203125
2
[]
no_license
package com.magic.daoyuan.controller; import com.magic.daoyuan.business.entity.PageArgs; import com.magic.daoyuan.business.entity.PageList; import com.magic.daoyuan.business.entity.SupplierAccountToBeCredited; import com.magic.daoyuan.business.exception.InterfaceCommonException; import com.magic.daoyuan.business.service.SupplierAccountToBeCreditedService; import com.magic.daoyuan.business.util.StatusConstant; import com.magic.daoyuan.util.ViewData; import com.magic.daoyuan.util.ViewDataPage; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * 供应商收款账户控制器 * @author lzh * @create 2017/9/26 16:21 */ @RestController @RequestMapping("/supplierAccountToBeCredited") public class SupplierAccountToBeCreditedController extends BaseController { @Resource private SupplierAccountToBeCreditedService supplierAccountToBeCreditedService; /** * 查询供应商收款账户的基础信息 * @return */ @RequestMapping("/info") public ViewData info(Integer id){ try { if (null == id){ return buildFailureJson(StatusConstant.FIELD_NOT_NULL,"字段不能为空"); } SupplierAccountToBeCredited supplierAccountToBeCredited = supplierAccountToBeCreditedService.info(id); return buildSuccessViewData(StatusConstant.SUCCESS_CODE,"获取成功 ",supplierAccountToBeCredited); } catch (Exception e) { logger.error("服务器超时,获取失败",e); return buildFailureJson(StatusConstant.Fail_CODE,"服务器超时,获取失败"); } } /** * 更新供应商收款账户 不为空的字段 通过ID * @param SupplierAccountToBeCredited */ @RequestMapping("/update") public ViewData update(SupplierAccountToBeCredited SupplierAccountToBeCredited){ try { if (null == SupplierAccountToBeCredited.getId()) { return buildFailureJson(StatusConstant.FIELD_NOT_NULL,"字段不能为空"); } supplierAccountToBeCreditedService.update(SupplierAccountToBeCredited); return buildSuccessCodeJson(StatusConstant.SUCCESS_CODE,"更新成功"); } catch (InterfaceCommonException e) { logger.info(e.getMessage(),e.getErrorCode()); return buildFailureJson(e.getErrorCode(),e.getMessage()); } catch (Exception e) { logger.error("服务器超时,更新失败",e); return buildFailureJson(StatusConstant.Fail_CODE,"服务器超时,更新失败"); } } /** * 更新供应商收款账户 所有的字段 通过ID * @param SupplierAccountToBeCredited */ @RequestMapping("/updateAll") public ViewData updateAll(SupplierAccountToBeCredited SupplierAccountToBeCredited){ try { if (null == SupplierAccountToBeCredited.getId()) { return buildFailureJson(StatusConstant.FIELD_NOT_NULL,"字段不能为空"); } supplierAccountToBeCreditedService.updateAll(SupplierAccountToBeCredited); return buildSuccessCodeJson(StatusConstant.SUCCESS_CODE,"更新成功"); } catch (InterfaceCommonException e) { logger.info(e.getMessage(),e.getErrorCode()); return buildFailureJson(e.getErrorCode(),e.getMessage()); } catch (Exception e) { logger.error("服务器超时,更新失败",e); return buildFailureJson(StatusConstant.Fail_CODE,"服务器超时,更新失败"); } } /** * 新增供应商收款账户 * @param SupplierAccountToBeCredited */ @RequestMapping("/save") public ViewData save(SupplierAccountToBeCredited SupplierAccountToBeCredited){ try { supplierAccountToBeCreditedService.save(SupplierAccountToBeCredited); return buildSuccessCodeJson(StatusConstant.SUCCESS_CODE,"新增成功"); } catch (InterfaceCommonException e) { return buildFailureJson(e.getErrorCode(),e.getMessage()); } catch (Exception e) { logger.error("服务器超时,新增失败",e); return buildFailureJson(StatusConstant.Fail_CODE,"服务器超时,新增失败"); } } /** * 后台页面 分页获取供应商联系人 * * @param pageArgs 分页属性 * @param accountName 账户名 * @param account 账号 * @param bankName 开户行 type=0时不能为空 * @param type 账号类型 0:银行卡 1:支付宝 * @param supplierId 供应商ID * @return */ @RequestMapping("/list") public ViewDataPage list(PageArgs pageArgs , String accountName , String account , String bankName , Integer type , Integer supplierId) { try { PageList pageList = supplierAccountToBeCreditedService.list(pageArgs, accountName, account, bankName, type, supplierId); return buildSuccessViewDataPage(StatusConstant.SUCCESS_CODE,"获取成功",pageList.getTotalSize(),pageList.getList()); } catch (Exception e) { logger.error("服务器超时,获取失败",e); return buildFailureJsonPage(StatusConstant.Fail_CODE,"服务器超时,获取失败"); } } /** * 根据供应商ID查询 -- 下拉使用 */ @RequestMapping("/getBySupplierId") public ViewData getBySupplierId(Integer supplierId){ try { return buildSuccessViewData(StatusConstant.SUCCESS_CODE,"获取成功 ",supplierAccountToBeCreditedService.getBySupplierId(supplierId)); } catch (InterfaceCommonException e) { logger.info(e.getMessage(),e.getErrorCode()); return buildFailureJson(e.getErrorCode(),e.getMessage()); } catch (Exception e) { logger.error("服务器超时,新增失败",e); return buildFailureJson(StatusConstant.Fail_CODE,"服务器超时,新增失败"); } } }
true
d0ba9664a5373bd0add71945080102f84a5f5ae2
Java
Byte2coder/boss
/bos_management/bos_management_web/src/test/java/com/itheima/bos/dao/test/StandardRepositoryTest.java
UTF-8
3,752
2.40625
2
[]
no_license
package com.itheima.bos.dao.test; import static org.junit.Assert.*; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.itheima.bos.dao.base.StandardRepository; import com.itheima.bos.domain.base.Standard; /** * ClassName:StandardRepositoryTest <br/> * Function: <br/> * Date: 2018年3月12日 下午8:59:29 <br/> */ //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration("classpath:applicationContext.xml") public class StandardRepositoryTest { @Autowired private StandardRepository standardRepository; //@Test public void test() { List<Standard> list = standardRepository.findAll(); for (Standard standard : list) { System.out.println(standard); } } //保存 //@Test public void test02() { Standard standard=new Standard(); standard.setName("和平平"); standard.setMaxWeight(250); standardRepository.save(standard); } //更新-save //@Test public void test03() { Standard standard=new Standard(); standard.setId(2L); standard.setMaxWeight(250); standardRepository.save(standard); } //查询--id //@Test public void test04() { Standard standard = standardRepository.findOne(2L); System.out.println(standard); } //删除 //@Test public void test05() { standardRepository.delete(2L); } //自定义查找name //@Test public void test06() { List<Standard> list = standardRepository.findByName("和平"); System.out.println(list.get(0)); } //模糊查询 //@Test public void test07() { List<Standard> list = standardRepository.findByNameLike("%和%"); for (Standard standard : list) { System.out.println(standard); } } //@Test public void test08() { List<Standard> list = standardRepository.findByNameAndMaxWeight("和平", 1000); for (Standard standard : list) { System.out.println(standard); } } //@Test public void test09() { List<Standard> list = standardRepository.findByNameAndMaxWeight469979("和平", 1000); for (Standard standard : list) { System.out.println(standard); } } // @Test public void test10() { List<Standard> list = standardRepository.findByNameAndMaxWeight469979( 1000,"和平"); for (Standard standard : list) { System.out.println(standard); } } //原生SQL // @Test public void test11() { List<Standard> list = standardRepository.findByNameAndMaxWeight469979ppp( "和平",1000); for (Standard standard : list) { System.out.println(standard); } } //更改类的操作 //修改update //@Transactional //在测试用例中使用事务,修改方法会执行,但是又回滚了, //最终不会修改数据,需要将@Transactional加到定义方法的地方 // @Test public void test12() { standardRepository.updateWeightByName(999, "和平"); } //删除操作 //@Test public void test13() { standardRepository.deleteByName("和平"); } }
true
6c81ee6a2d47d8fb6bbb522f2e9ec2488db9fca0
Java
mengwang0211/auth-center
/auth-spring-boot-starter/src/main/java/com/zijinph/base/auth/sql/SqlAppender.java
UTF-8
3,822
2.703125
3
[]
no_license
package com.zijinph.base.auth.sql; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SqlAppender { private static final String SQL_WHERE = "WHERE"; private static final String SQL_LEFT_JOIN = "LEFT JOIN "; /** * 将数据权限的sql拼进原sql中 * * @param originSql 原sql * @param privilegeSql 数据权限sql * @return String */ public static String handlerSql(String originSql, String privilegeSql) { if (originSql.endsWith(";")) { originSql = originSql.substring(0, originSql.lastIndexOf(";")); } originSql = originSql.replace("\t", " ").replace("\n", " "); originSql = originSql.replaceAll(" {2,}", " "); originSql = originSql.replaceAll(" where ", " " + SQL_WHERE + " "); originSql = addWhere(originSql); originSql = originSql.replace("left", "LEFT"); originSql = originSql.replace("join", "JOIN"); originSql = originSql.replaceAll("LEFT[ ]+JOIN[ ]+", SQL_LEFT_JOIN); // List<String> matcherList = matcherTableSql(originSql); // for (String matcherSql : matcherList) { // if (originSql.contains(SQL_LEFT_JOIN + matcherSql)) { // continue; // } // String newMatcherSql = mergeSql(matcherSql, privilegeSql); // originSql = originSql.replace(matcherSql, newMatcherSql); // } return originSql.replace(SQL_WHERE, SQL_WHERE + " " + privilegeSql); } /** * 添加where关键字 * * @param originSql 原始sql * @return String */ private static String addWhere(String originSql) { if (originSql.contains("WHERE")) { return originSql; } String[] split = originSql.split(" "); for (int i = 0; i < split.length; i++) { if (split[i].equalsIgnoreCase("GROUP") && (i + 1) < split.length && split[i + 1].equalsIgnoreCase("BY")) { return originSql.replaceAll(split[i], "WHERE 1=1 GROUP"); } if (split[i].equalsIgnoreCase("ORDER") && (i + 1) < split.length && split[i + 1].equalsIgnoreCase("BY")) { return originSql.replaceAll(split[i], "WHERE 1=1 ORDER"); } if (split[i].equalsIgnoreCase("LIMIT")) { return originSql.replaceAll(split[i], "WHERE 1=1 LIMIT"); } } return originSql + " WHERE 1=1"; } /** * 合并sql * * @param originSql 原sql * @param privilegeSql 数据权限sql * @return String */ private static String mergeSql(String originSql, String privilegeSql) { return originSql.replace(SQL_WHERE, SQL_WHERE + " " + privilegeSql); } /** * 配置符合 * * @param originSql 原sql * @return List<String> */ private static List<String> matcherTableSql(String originSql) { List<String> matcharList = new ArrayList<>(); String regex = "\\w[ ,](.*?)WHERE"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(originSql); while (matcher.find()) { matcharList.add(matcher.group()); } return matcharList; } public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { String sql = "select * from t_bill t where t.user_id = ? and t.staff_id = ? order by t.create_time desc"; String privilegeSql = " (orgi_id like '0102%' or orig_id like '0202%') and "; SqlAppender.handlerSql(sql, privilegeSql); } long end = System.currentTimeMillis(); System.out.println(end -start); } }
true
2f6dc7ecd0b18317803e82ee161097de49711515
Java
sunwenyang799/ssm2018
/spring_ioc/src/main/java/com/spring/service/IAccountService.java
UTF-8
188
1.632813
2
[]
no_license
package com.spring.service; /** * @author lenovo * @description: 模拟数据库操作account * @date 2020/8/20 15:11 */ public interface IAccountService { void saveAccount(); }
true
8a478396cd7823349c37aba4735f6321a2dcd8bd
Java
yaoh4/sm_em_audit
/src/gov/nih/nci/cbiit/scimgmt/entmaint/hibernate/EmAuditsVw.java
UTF-8
7,799
2.015625
2
[]
no_license
package gov.nih.nci.cbiit.scimgmt.entmaint.hibernate; // Generated Feb 26, 2015 9:50:07 AM by Hibernate Tools 3.4.0.CR1 import java.util.Date; import java.util.List; /** * EmAuditsVw generated by hbm2java */ public class EmAuditsVw implements java.io.Serializable { private Long id; private Date impaciiFromDate; private Date impaciiToDate = new Date(); private Date startDate; private Date endDate; private String createUserFullName; private Date createDate; private Date i2eFromDate; private Date i2eToDate; private String activeCategoryEnabledFlag = "Y"; private String newCategoryEnabledFlag = "Y"; private String deletedCategoryEnabledFlag = "Y"; private String inactiveCategoryEnabledFlag = "Y"; List<EmAuditHistoryVw> statusHistories; public EmAuditsVw() { } public EmAuditsVw(Long id, Date impaciiFromDate, Date impaciiToDate, Date startDate, Date endDate, String createUserFullName, Date createDate, Date i2eFromDate, Date i2eToDate, List<EmAuditHistoryVw> statusHistories) { this.id = id; this.impaciiFromDate = impaciiFromDate; this.impaciiToDate = impaciiToDate; this.startDate = startDate; this.endDate = endDate; this.createUserFullName = createUserFullName; this.createDate = createDate; this.i2eFromDate = i2eFromDate; this.i2eToDate = i2eToDate; this.statusHistories = statusHistories; } public EmAuditsVw(Long id, Date impaciiFromDate, Date impaciiToDate, Date startDate, String createUserFullName, Date i2eFromDate, Date i2eToDate) { this.id = id; this.impaciiFromDate = impaciiFromDate; this.impaciiToDate = impaciiToDate; this.startDate = startDate; this.createUserFullName = createUserFullName; this.i2eFromDate = i2eFromDate; this.i2eToDate = i2eToDate; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof EmAuditsVw)) { return false; } EmAuditsVw castOther = (EmAuditsVw) other; return (getId() == castOther.getId() || getId() != null && castOther.getId() != null && getId().equals(castOther.getId())) && (getImpaciiFromDate() == castOther.getImpaciiFromDate() || getImpaciiFromDate() != null && castOther.getImpaciiFromDate() != null && getImpaciiFromDate().equals(castOther.getImpaciiFromDate())) && (getImpaciiToDate() == castOther.getImpaciiToDate() || getImpaciiToDate() != null && castOther.getImpaciiToDate() != null && getImpaciiToDate().equals(castOther.getImpaciiToDate())) && (getStartDate() == castOther.getStartDate() || getStartDate() != null && castOther.getStartDate() != null && getStartDate().equals(castOther.getStartDate())) && (getEndDate() == castOther.getEndDate() || getEndDate() != null && castOther.getEndDate() != null && getEndDate().equals(castOther.getEndDate())) && (getCreateUserFullName() == castOther.getCreateUserFullName() || getCreateUserFullName() != null && castOther.getCreateUserFullName() != null && getCreateUserFullName().equals(castOther.getCreateUserFullName())) && (getCreateDate() == castOther.getCreateDate() || getCreateDate() != null && castOther.getCreateDate() != null && getCreateDate().equals(castOther.getCreateDate())) && (getI2eFromDate() == castOther.getI2eFromDate() || getI2eFromDate() != null && castOther.getI2eFromDate() != null && getI2eFromDate().equals(castOther.getI2eFromDate())) && (getI2eToDate() == castOther.getI2eToDate() || getI2eToDate() != null && castOther.getI2eToDate() != null && getI2eToDate().equals(castOther.getI2eToDate())); } public Date getCreateDate() { return createDate; } public String getCreateUserFullName() { return createUserFullName; } public Date getEndDate() { return endDate; } public Date getI2eFromDate() { return i2eFromDate; } public Date getI2eToDate() { return i2eToDate; } public Long getId() { return id; } public Date getImpaciiFromDate() { return impaciiFromDate; } public Date getImpaciiToDate() { return impaciiToDate; } public Date getStartDate() { return startDate; } @Override public int hashCode() { int result = 17; result = 37 * result + (getId() == null ? 0 : getId().hashCode()); result = 37 * result + (getImpaciiFromDate() == null ? 0 : getImpaciiFromDate().hashCode()); result = 37 * result + (getImpaciiToDate() == null ? 0 : getImpaciiToDate().hashCode()); result = 37 * result + (getStartDate() == null ? 0 : getStartDate().hashCode()); result = 37 * result + (getEndDate() == null ? 0 : getEndDate().hashCode()); result = 37 * result + (getCreateUserFullName() == null ? 0 : getCreateUserFullName().hashCode()); result = 37 * result + (getCreateDate() == null ? 0 : getCreateDate().hashCode()); result = 37 * result + (getI2eFromDate() == null ? 0 : getI2eFromDate().hashCode()); result = 37 * result + (getI2eToDate() == null ? 0 : getI2eToDate().hashCode()); return result; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public void setCreateUserFullName(String createUserFullName) { this.createUserFullName = createUserFullName; } public void setEndDate(Date endDate) { this.endDate = endDate; } public void setI2eFromDate(Date i2eFromDate) { this.i2eFromDate = i2eFromDate; } public void setI2eToDate(Date i2eToDate) { this.i2eToDate = i2eToDate; } public void setId(Long id) { this.id = id; } public void setImpaciiFromDate(Date impaciiFromDate) { this.impaciiFromDate = impaciiFromDate; } public void setImpaciiToDate(Date impaciiToDate) { this.impaciiToDate = impaciiToDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } /** * @return the activeCategoryEnabledFlag */ public String getActiveCategoryEnabledFlag() { return activeCategoryEnabledFlag; } /** * @param activeCategoryEnabledFlag the activeCategoryEnabledFlag to set */ public void setActiveCategoryEnabledFlag(String activeCategoryEnabledFlag) { this.activeCategoryEnabledFlag = activeCategoryEnabledFlag; } /** * @return the newCategoryEnabledFlag */ public String getNewCategoryEnabledFlag() { return newCategoryEnabledFlag; } /** * @param newCategoryEnabledFlag the newCategoryEnabledFlag to set */ public void setNewCategoryEnabledFlag(String newCategoryEnabledFlag) { this.newCategoryEnabledFlag = newCategoryEnabledFlag; } /** * @return the deletedCategoryEnabledFlag */ public String getDeletedCategoryEnabledFlag() { return deletedCategoryEnabledFlag; } /** * @param deletedCategoryEnabledFlag the deletedCategoryEnabledFlag to set */ public void setDeletedCategoryEnabledFlag(String deletedCategoryEnabledFlag) { this.deletedCategoryEnabledFlag = deletedCategoryEnabledFlag; } /** * @return the inactiveCategoryDeletedFlag */ public String getInactiveCategoryEnabledFlag() { return inactiveCategoryEnabledFlag; } /** * @param inactiveCategoryDeletedFlag the inactiveCategoryDeletedFlag to set */ public void setInactiveCategoryEnabledFlag(String inactiveCategoryEnabledFlag) { this.inactiveCategoryEnabledFlag = inactiveCategoryEnabledFlag; } /** * @return the statusHistories */ public List<EmAuditHistoryVw> getStatusHistories() { return statusHistories; } /** * @param statusHistories the statusHistories to set */ public void setStatusHistories(List<EmAuditHistoryVw> statusHistories) { this.statusHistories = statusHistories; } }
true
814af23373af4f892f467af2d457330cbbfc5e39
Java
agangwar/Algorithms
/src/main/java/Stack/StackUtils.java
UTF-8
397
3.140625
3
[]
no_license
package Stack; import java.util.Stack; import Tree.TreeNode; public class StackUtils { public static String printTreeNode(Stack<TreeNode> st){ String output = ""; if(st.isEmpty()==true) return output; while(!st.isEmpty()){ TreeNode temp = st.pop(); //System.out.print(temp.getData()+"->"); output = output + temp.getData()+"->"; } return output; } }
true
637d8aba446a606c3a97e977e3de3d4f5e5bb544
Java
NiordOrg/niord-dk
/niord-dk-aton-import/src/main/java/org/niord/importer/aton/batch/BatchDkLightImportProcessor.java
UTF-8
6,062
1.953125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Danish Maritime Authority. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.niord.importer.aton.batch; import org.apache.commons.lang.StringUtils; import org.niord.core.aton.AtonNode; import org.niord.core.aton.AtonTag; import org.niord.core.user.User; import org.slf4j.Logger; import javax.inject.Inject; import javax.inject.Named; /** * AtoN batch processor used for converting the legacy "AFM" Light Excel row into OSM seamark format. * Before running this batch job, run the dk-aton-import job. * * The AtoN model adheres to the OSM seamark specification, please refer to: * http://wiki.openstreetmap.org/wiki/Key:seamark * and sub-pages. */ @Named public class BatchDkLightImportProcessor extends AbstractDkAtonImportProcessor { @Inject Logger log; /** {@inheritDoc} **/ @Override protected AtonNode parseAtonExcelRow() throws Exception { // Only process active lights if (!"DRIFT".equalsIgnoreCase(stringValue("STATUS"))) { getLog().info("Skipping inactive light/fog-signal " + stringValue("NR_DK")); return null; } User user = job.getUser(); AtonNode aton = new AtonNode(); aton.setVisible(true); aton.setLat(numericValue("LATITUDE")); aton.setLon(numericValue("LONGITUDE")); aton.setTimestamp(dateValue("Ajourfoert_dato")); aton.setUser(user != null ? user.getUsername() : ""); aton.setUid(user != null ? user.getId() : -1); aton.setChangeset(getChangeSet()); aton.setVersion(1); // Unknown version // If no AtoN UID exists, construct it String atonUid = stringValue("AFM_NR"); if (StringUtils.isBlank(atonUid)) { atonUid = "light-" + stringValue("NR_DK"); } aton.updateTag(AtonTag.TAG_ATON_UID, atonUid); aton.updateTag(AtonTag.TAG_LIGHT_NUMBER, stringValue("NR_DK")); aton.updateTag(AtonTag.TAG_INT_LIGHT_NUMBER, stringValue("NR_INT")); aton.updateTag(AtonTag.TAG_LOCALITY, stringValue("Lokalitet")); aton.updateTag("seamark:name", stringValue("AFM_navn")); aton.updateTag("seamark:light:information", stringValue("Fyrudseende")); aton.updateTag("seamark:light:elevation", parseElevation()); /********* Light Character Parsing *******/ String lightChar = stringValue("Fyrkarakter"); LightSeamark light = DkLightParser.newInstance(); // Parse the light character, e.g. "Iso.WRG.2s" DkLightParser.parseLightCharacteristics(light, lightChar); // Parse the light elevations DkLightParser.parseHeight(light, numericValueOrNull("Fyrbygnings_hoejde")); // Parse the light sector angles, e.g. "G114,52°-116,52° W116,52°-117,52° R117,52°-119,52°." DkLightParser.parseLightSectorAngles(light, stringValue("Lysvinkler")); // Parse the light ranges DkLightParser.parseRange(light, stringValue("Lysstyrke_1"), stringValue("Lysstyrke_2"), stringValue("Lysstyrke_3")); // Parse the exhibition DkLightParser.parseExhibition(light, stringValue("Braendetid")); /********* Fog Signal Parsing *******/ String fogSignalSpec = stringValue("Taagesignal"); FogSignalSeamark fogSignal = DkFogSignalParser.newInstance(); // Parse the fog signal, e.g. "HORN(3)30s (2+2+2+2+2+20)" DkFogSignalParser.parseFogSignal(fogSignal, fogSignalSpec); // Either the light or the fog signal (or both) must be valid if (!light.isValid() && !fogSignal.isValid()) { getLog().info("Skipping invalid light/fog-signal " + stringValue("NR_DK") + ": light=" + lightChar + ", fog-signal=" + fogSignalSpec); return null; } // Copy the fog signal OSM tags to the AtoN. if (fogSignal.isValid()) { fogSignal.toOsm().forEach(t -> aton.updateTag(t.getK(), t.getV())); } // Copy the light OSM tags to the AtoN. // NB: Any "seamark:type" will override a fog-signal type. Lights should take precedence. if (light.isValid()) { light.toOsm().forEach(t -> aton.updateTag(t.getK(), t.getV())); } return aton; } /** {@inheritDoc} */ @Override protected void mergeAtonNodes(AtonNode original, AtonNode aton) { // Do not override the original AtoN type String origType = original.getTagValue("seamark:type"); if (origType != null) { aton.removeTags("seamark:type"); } // If the new AtoN contains light information, remove any light information from the original if (aton.matchingTags("seamark:\\w*light\\.*").size() > 0) { original.removeTags("seamark:\\w*light\\.*"); } // If the new AtoN contains fog signal information, remove any fog signal information from the original if (aton.matchingTags("seamark:fog_signal\\.*").size() > 0) { original.removeTags("seamark:fog_signal\\.*"); } // Override any remaining tags in the original original.updateNode(aton); } /** Parses the elevation fields */ private String parseElevation() { String elevation = null; for (int x = 1; x <= 4; x++) { elevation = appendValue(elevation, numericValueOrNull("Flammehoejde_" + x)); } return elevation; } }
true
98e8131220d0c0ab934771dafd1684d4be09ab6d
Java
rogercaballero36/repo3
/Proynuevo3/src/pages1/HomePage1.java
UTF-8
248
2.265625
2
[]
no_license
package pages1; import org.openqa.selenium.WebDriver; public class HomePage1 { WebDriver driver; public HomePage1(WebDriver driver) { this.driver=driver; } public String GetTitle() { return driver.getTitle(); } }
true
c1bfa567c43886cdc8f19c23f005c36fb3a6563c
Java
nayan5565/Quiz-Game
/app/src/main/java/com/techienerd/quizgame/activity/CategoryActivity.java
UTF-8
10,298
2.265625
2
[]
no_license
package com.techienerd.quizgame.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.TextView; import com.techienerd.quizgame.R; import com.techienerd.quizgame.adapter.CategoryAdapter; import com.techienerd.quizgame.model.MCategory; import com.techienerd.quizgame.model.MOption; import com.techienerd.quizgame.model.MQuestion; import com.techienerd.quizgame.tools.DatabaseHelper; import java.util.ArrayList; /** * Created by Nayan on 7/18/2017. */ public class CategoryActivity extends AppCompatActivity{ RecyclerView recyclerView; ArrayList<MOption> optionArrayList; ArrayList<MQuestion> questionArrayList; ArrayList<MCategory> categoryArrayList; MCategory mCategory; MQuestion mQuestion; MOption mOption; private TextView txtCount; private int pos; private TextView txtQues; CategoryAdapter adapter; DatabaseHelper db; private static CategoryActivity instance; public static CategoryActivity getInstance() { return instance; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lay_category); instance = this; init(); generateToMulti(); prepareView(); } private void init() { txtCount = (TextView) findViewById(R.id.txtCount); txtQues = (TextView) findViewById(R.id.tct); recyclerView = (RecyclerView) findViewById(R.id.rec); adapter = new CategoryAdapter(this); db=new DatabaseHelper(this); } public void prepareView() { Log.e("list"," size "+categoryArrayList.size()); adapter.setData(categoryArrayList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); } public void destroy(){ finish(); } private void generateToMulti() { questionArrayList = new ArrayList<>(); optionArrayList = new ArrayList<>(); categoryArrayList = new ArrayList<>(); mCategory = new MCategory(); mCategory.setType("English"); mCategory.setId(1); mQuestion = new MQuestion(); mQuestion.setQues("2+2=?"); mOption = new MOption(); mOption.setOption("2"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("7"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("8"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("4"); mOption.setTag(1); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); // 2 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("5+5=?"); mOption = new MOption(); mOption.setOption("10"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("9"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("5"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("11"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //3 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("2+5=?"); mOption = new MOption(); mOption.setOption("9"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("7"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("5"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("12"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //4 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("7+2=?"); mOption = new MOption(); mOption.setOption("5"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("6"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("9"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("10"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //5 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("8+2=?"); mOption = new MOption(); mOption.setOption("16"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("12"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("11"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("10"); mOption.setTag(1); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); mCategory.setQuestionArrayList(questionArrayList); categoryArrayList.add(mCategory); //Math question questionArrayList = new ArrayList<>(); optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mCategory = new MCategory(); mCategory.setType("Math"); mCategory.setId(2); mQuestion.setQues("২+২ =?"); mOption = new MOption(); mOption.setOption("২"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৭"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৮"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৪"); mOption.setTag(1); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); // 2 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("৫+৫=?"); mOption = new MOption(); mOption.setOption("১০"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৯"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৫"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১১"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //3 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("২+৫=?"); mOption = new MOption(); mOption.setOption("৯"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৭"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৫"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১২"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //4 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("৭+২=?"); mOption = new MOption(); mOption.setOption("৫"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৬"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("৯"); mOption.setTag(1); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১০"); mOption.setTag(0); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); //5 optionArrayList = new ArrayList<>(); mQuestion = new MQuestion(); mQuestion.setQues("৮+২=?"); mOption = new MOption(); mOption.setOption("১৬"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১২"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১১"); mOption.setTag(0); optionArrayList.add(mOption); mOption = new MOption(); mOption.setOption("১০"); mOption.setTag(1); optionArrayList.add(mOption); mQuestion.setOptionArrayList(optionArrayList); questionArrayList.add(mQuestion); mCategory.setQuestionArrayList(questionArrayList); categoryArrayList.add(mCategory); } }
true
24b5476de7b3f1ae2d7bcbe5184fa6bc91b56ac8
Java
IgorChupryna/bank
/src/main/java/ua/chup/account/NotSearchTypeCurrencyException.java
UTF-8
378
2.3125
2
[]
no_license
package ua.chup.account; public class NotSearchTypeCurrencyException extends RuntimeException { @Override public String getMessage() { return "This type of currency not exists "+super.getMessage(); } @Override public void printStackTrace() { System.out.println("This type of currency not exists "); super.printStackTrace(); } }
true
fc736bc49aa374feaaaae395af2e50aa11334033
Java
Guaniuzzt/Algorithms-Interview
/LaiCode Algorithm Class/BinaryTreeAndBinarySearchTree/GetKeysInBinarySearchTreeInGivenRange.java
UTF-8
551
2.734375
3
[]
no_license
import utils.TreeNode; import java.util.ArrayList; import java.util.List; public class GetKeysInBinarySearchTreeInGivenRange { List<Integer> list = new ArrayList<>(); public void method(TreeNode root, int min, int max){ if(root == null) return ; if(root.key > min){ method(root.left, min, max); } if(root.key >= min && root.key <= max){ this.list.add(root.key); } if(root.key > max){ method(root.right, min, max); } } }
true
b0add68ee2309097c8646c57dc41795b6e10676f
Java
jeremy6019/spring
/springmember/src/main/java/daum/jeremy6019/domain/Member.java
UTF-8
534
2.578125
3
[]
no_license
package daum.jeremy6019.domain; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //getter&setter, toString 이 생성됩니다. @Data //매개변수가 없는 생성자 @NoArgsConstructor //모든 프로퍼티를 매개변수로 받는 생성자 생성 @AllArgsConstructor public class Member { private String email; private String password; private String name; private String nickname; private String image; private Date birthday; private String phone; }
true
65985893fda400bd547162d5f01e528310cb2568
Java
liangzhengyu123/xiangmu
/frame/src/main/java/com/example/frame/base/BaseNetFragment.java
UTF-8
1,546
2.09375
2
[]
no_license
package com.example.frame.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.frame.interfaces.ICommonModule; import com.example.frame.interfaces.ICommonView; import butterknife.ButterKnife; import butterknife.Unbinder; public abstract class BaseNetFragment<P extends BasePresenter,M> extends BaseFrament implements ICommonView { public P mPresenter; public M mModule; public View view; private Unbinder mBind; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(getLayoutId(), container, false); mBind = ButterKnife.bind(this,view); initView(); mPresenter = getPresenter(); mModule = getModule(); if (mPresenter != null ){ mPresenter.attach(this, (ICommonModule) mModule); } initData(); return view; } @Override public void onDestroyView() { super.onDestroyView(); mBind.unbind(); } public abstract int getLayoutId(); public abstract void initView(); public abstract void initData(); public abstract P getPresenter(); public abstract M getModule(); @Override public void onDestroy() { super.onDestroy(); if (mPresenter != null && mModule != null){ mPresenter.deattch(); } } }
true
0ea1aabb4fb80c205ba513a1ffec3e8cf2a8f852
Java
DermoHiggs/SW_Dev_Spring2021
/src/sw_dev/interfaces/practical1/part7/StudentTester.java
UTF-8
376
3.171875
3
[]
no_license
package sw_dev.interfaces.practical1.part7; public class StudentTester { public static void main(String[] args) { Student s1 = new Student("blah blah", 20, "Computing", 0); s1.doJob(new Job("Clean House", 4.0, 3.0)); int packets = s1.howManyNoodles(2.50); System.out.println("Student can buy " + packets + "packets of noodles"); } }
true
9e67cc06b5d66ee66ca57f5778f826a2e7203941
Java
CorinaMP/java-training
/_3_design_patterns/src/main/java/code/_4_student_effort/Command/ISolicitareAnaliza.java
UTF-8
144
1.664063
2
[]
no_license
package code._4_student_effort.Command; public interface ISolicitareAnaliza { public void analizaProba(TipAnaliza tip, String pacient); }
true
65902555650131e1050372fc8b5cc306a08ed4be
Java
hiennvth1907052/AssignmentIASF
/src/main/java/com/example/assignmentiasf/util/StatusToStringUtil.java
UTF-8
244
2.265625
2
[]
no_license
package com.example.assignmentiasf.util; public class StatusToStringUtil { public static String getStatusString (int status){ return status == 1 ? "Đang sử dụng" : (status == 0 ? "Đang thi công" : "Đang tu sửa"); } }
true
3fa3e4765e05ab43936b68f861d009116c1d2004
Java
adamvan341/Lesson9
/Employee Manager/src/employee/Employee.java
UTF-8
2,087
3.359375
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 employee; /** * * @author adam */ public abstract class Employee { // Instance Variables protected int hours; protected double rate; protected String name; // Class Constants static double MIN_RATE = 6.75; static double MAX_RATE = 30.50; static int MIN_HOURS = 1; static int MAX_HOURS = 60; // Classwide Variables static double totalPay = 0; public boolean setName(String name) { if (name.charAt(0) == '0' || name.charAt(0) == '1' || name.charAt(0) == '2' || name.charAt(0) == '3' || name.charAt(0) == '4' || name.charAt(0) == '5' || name.charAt(0) == '6' || name.charAt(0) == '7' || name.charAt(0) == '8' || name.charAt(0) == '9') { return false; } this.name = name; return true; } public boolean setRate(double rate) { if (rate > MAX_RATE || rate < MIN_RATE) { return false; } else { this.rate = rate; return true; } } public boolean setHours(int hours) { if (hours > MAX_HOURS || hours < MIN_HOURS) { return false; } else { this.hours = hours; return true; } } public String getName() { return name; } public abstract double getPay(); public static String getNameRules() { return "Name must not start with a number (0-9)"; } public static String getRateRules() { return "Rate must not be lower than " + MIN_RATE + " or higher than " + MAX_RATE; } public static String getHoursRules() { return "Hours must not be less than " + MIN_HOURS + " or higher than " + MAX_HOURS; } public static double getTotalPay() { return totalPay; } }
true
c854dc1b8c437f74e9a3b1671e6109658393aba1
Java
jxxiaoxi/ME_DEMO
/Settings/src/com/mediatek/settings/deviceinfo/RadioButtonPreference.java
UTF-8
3,695
2.59375
3
[ "Apache-2.0" ]
permissive
package com.mediatek.settings.deviceinfo; import android.content.Context; import android.preference.Preference; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.TextView; import com.android.settings.R; import com.mediatek.xlog.Xlog; public class RadioButtonPreference extends Preference implements View.OnClickListener { private static final int TITLE_ID = R.id.preference_title; private static final int BUTTON_ID = R.id.preference_radiobutton; private TextView mPreferenceTitle = null; private RadioButton mPreferenceButton = null; private CharSequence mTitleValue = ""; private boolean mChecked = false; private String mMountPath; private static final String TAG = "RadioButtonPreference"; /** * RadioButtonPreference construct * * @param context * the preference associated with */ public RadioButtonPreference(Context context) { super(context); setLayoutResource(R.layout.preference_radiobutton); } @Override public View getView(View convertView, ViewGroup parent) { View view = super.getView(convertView, parent); Xlog.d(TAG, "getview"); mPreferenceTitle = (TextView) view.findViewById(TITLE_ID); mPreferenceTitle.setText(mTitleValue); mPreferenceButton = (RadioButton) view.findViewById(BUTTON_ID); mPreferenceButton.setOnClickListener(this); mPreferenceButton.setChecked(mChecked); return view; } @Override public void setTitle(CharSequence title) { if (null == mPreferenceTitle) { mTitleValue = title; } if (!title.equals(mTitleValue)) { mTitleValue = title; mPreferenceTitle.setText(mTitleValue); } } @Override public CharSequence getTitle() { return mTitleValue; } /** * get the preference checked status * * @return the checked status */ public boolean isChecked() { return mChecked; } @Override public void onClick(View v) { boolean newValue = !isChecked(); if (!newValue) { Xlog.d(TAG, "button.onClick return"); return; } if (setChecked(newValue)) { callChangeListener(newValue); Xlog.d(TAG, "button.onClick"); } } @Override protected void onClick() { super.onClick(); boolean newValue = !isChecked(); if (!newValue) { Xlog.d(TAG, "preference.onClick return"); return; } if (setChecked(newValue)) { callChangeListener(newValue); Xlog.d(TAG, "preference.onClick"); } } /** * set the preferce checked or unchecked * * @param checked * the checked status * @return set success or fail */ public boolean setChecked(boolean checked) { if (null == mPreferenceButton) { Xlog.d(TAG, "setChecked return"); mChecked = checked; return false; } if (mChecked != checked) { mPreferenceButton.setChecked(checked); mChecked = checked; return true; } return false; } /** * Set the storage preference path * * @param path * the storage path */ public void setPath(String path) { mMountPath = path; } /** * get the storage preference path * * @return the storage path */ public String getPath() { return mMountPath; } }
true
3cf543f1150073d743ddd48296589a35cc35e971
Java
yuh666/leetcode
/kgeyizufanzhuanlianbiao_25/Solution.java
UTF-8
2,431
3.84375
4
[]
no_license
package kgeyizufanzhuanlianbiao_25; /** * 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 * <p> * k 是一个正整数,它的值小于或等于链表的长度。 * <p> * 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 * <p> * 示例 : * <p> * 给定这个链表:1->2->3->4->5 * <p> * 当 k = 2 时,应当返回: 2->1->4->3->5 * <p> * 当 k = 3 时,应当返回: 3->2->1->4->5 * <p> * 说明 : * <p> * 你的算法只能使用常数的额外空间。 * 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 * <p> * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ // Definition for singly-linked list. class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode curr = dummy; ListNode pre = curr; while (true) { for (int i = 0; i < k && curr != null; i++) { curr = curr.next; } if (curr == null) { break; } ListNode start = pre.next; ListNode next = curr.next; curr.next = null; pre.next = reverseList(start); start.next = next; pre = start; curr = pre; } return dummy.next; } public ListNode reverseList(ListNode head) { ListNode newHead = null; while (head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; new Solution().reverseKGroup(node1,2); } }
true
1a3a7f46d95b9599755878b2af306a83cd4770b9
Java
Lranger321/Project-manager
/src/main/java/com/simbirsoft/projectManager/utils/mapper/UserMapper.java
UTF-8
857
2.09375
2
[]
no_license
package com.simbirsoft.projectManager.utils.mapper; import com.simbirsoft.projectManager.rest.dto.request.UserRegisterRequest; import com.simbirsoft.projectManager.rest.dto.response.UserResponse; import com.simbirsoft.projectManager.entity.User; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface UserMapper { @Mapping(source = "fullName", target = "fullName") @Mapping(source = "email", target = "email") @Mapping(source = "password", target = "password") User toUserEntity(UserRegisterRequest request); @Mapping(source = "id", target = "id") @Mapping(source = "fullName", target = "name") @Mapping(source = "email", target = "login") @Mapping(source = "dateRegister", target = "date", dateFormat = "yyyy-MM-dd HH:mm:ss") UserResponse toDto(User user); }
true
9b53b966f0ea0e711e9bae51bc94ac29a6648bb6
Java
murielK/udacity-bakingapp
/app/src/main/java/hr/murielkamgang/mf/components/Recipe/RecipeFragment.java
UTF-8
1,904
2.0625
2
[]
no_license
package hr.murielkamgang.mf.components.Recipe; import android.support.v7.widget.GridLayoutManager; import android.view.View; import javax.inject.Inject; import hr.murielkamgang.mf.R; import hr.murielkamgang.mf.components.base.BaseContentFragment; import hr.murielkamgang.mf.components.base.GridSpacingItemDecoration; import hr.murielkamgang.mf.components.detail.RecipeDetailActivity; import hr.murielkamgang.mf.data.model.receipe.Recipe; public class RecipeFragment extends BaseContentFragment<Recipe, RecipeContract.View, RecipeContract.Presenter> implements RecipeContract.View { @Inject RecipeContract.Presenter presenter; @Inject RecipeAdapter recipeAdapter; @Inject public RecipeFragment() { } @Override protected void onItemClicked(Recipe recipe) { if (presenter != null) { presenter.delegateItemClicked(recipe); } } @Override protected void onViewClicked(View view, Recipe recipe) { if (presenter != null) { presenter.delegateToggleFavorite(recipe); } } @Override protected void initRecyclerView() { swipeRefreshLayout.setEnabled(false); final int spanCount = getResources().getInteger(R.integer.span_count); recyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount)); recyclerView.setAdapter(recipeAdapter); recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, getResources().getDimensionPixelSize(R.dimen.recycler_view_spacing), true)); } @Override protected RecipeContract.Presenter providePresenter() { return presenter; } @Override protected int getResourceView() { return R.layout.default_recycler_view_fragment; } @Override public void openDetailFor(Recipe recipe) { RecipeDetailActivity.view(getContext(), recipe); } }
true
6e25fc1b97e49204f5d92d091bc61484025bbe6d
Java
tshirotatadashi/LPIII-WebTest
/src/java/services/CategoriaService.java
UTF-8
258
1.828125
2
[]
no_license
package services; import entities.Categoria; import javax.ejb.Stateless; /** * * @author Thiago */ @Stateless public class CategoriaService extends EntityService<Categoria> { public CategoriaService() { super(Categoria.class); } }
true
30b5ad0a816b691fddf535f8ca4ab7afc8961676
Java
kristi1995/SDA
/zadanie11_6.java
UTF-8
600
3.09375
3
[]
no_license
package Zadania_ksiazka; import java.util.Scanner; public class zadanie11_6 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Podaj imię nazwisko pracownika oraz ilość przepracowanych godzini i stawkę godzinową "); String a = scanner.nextLine(); Scanner input = new Scanner(a); String a1 = input.next(); String a2 = input.next(); int a3 = input.nextInt(); double a4 = input.nextDouble(); System.out.println("Pracownik "+a1 +" " +a2+" zarabia "+ a3*a4); } }
true
a6a67dd88971b99834ad887b0b305c6be0e5f19e
Java
LowTension/Social-Reader
/app/src/main/java/com/destiner/social_reader/model/structs/source/QuerySource.java
UTF-8
497
2.46875
2
[]
no_license
package com.destiner.social_reader.model.structs.source; /** * Structure describes source that is a search query. Requests for this source will be formed as * a search from all posts in VK that contain query keyword. */ public class QuerySource extends Source { String query; public QuerySource(String query) { this.query = query; } public String getQuery() { return query; } @Override public String getStringId() { return query; } }
true
7b55473df4b5ee747361e71a0dedd17f59403708
Java
SANDAG/ABM
/src/main/java/org/sandag/abm/airport/AirportDmuFactory.java
UTF-8
1,135
1.648438
2
[]
no_license
/* * Copyright 2005 PB Consult Inc. Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.sandag.abm.airport; import java.io.Serializable; /** * ArcCtrampDmuFactory is a class that creates Airport Model DMU objects * * @author Joel Freedman */ public class AirportDmuFactory implements AirportDmuFactoryIf, Serializable { //private AirportModelStructure airportModelStructure; public AirportDmuFactory()//AirportModelStructure modelStructure) { //this.airportModelStructure = modelStructure; } public AirportModelDMU getAirportModelDMU() { return new AirportModelDMU(null); } }
true
678dd3e91c9695b7d00e09ad386de040eb39745a
Java
jechante/jhipsterSampleMysql
/src/main/java/io/github/jhipster/application/domain/Layer.java
UTF-8
6,881
2
2
[]
no_license
package io.github.jhipster.application.domain; import com.fasterxml.jackson.annotation.*; import io.swagger.annotations.ApiModelProperty; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; import io.github.jhipster.application.domain.enumeration.ServerType; import io.github.jhipster.application.domain.enumeration.PointQueryType; import io.github.jhipster.application.domain.enumeration.PoiType; /** * A Layer. */ @Entity @Table(name = "layer") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) //@JsonIdentityInfo( // generator = ObjectIdGenerators.PropertyGenerator.class, // property = "id") public class Layer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "layer_name") private String layerName; /** * GIS服务器中该图层标识代码 */ @ApiModelProperty(value = "GIS服务器中该图层标识代码") @Column(name = "identifier") private String identifier; @Enumerated(EnumType.STRING) @Column(name = "source") private ServerType source; /** * 地图点击查询 */ @ApiModelProperty(value = "地图点击查询") @Enumerated(EnumType.STRING) @Column(name = "point_query_type") private PointQueryType pointQueryType; /** * 当ServerType为服务器端渲染且除了默认样式还有其他样式时,需要设置显示样式 */ @ApiModelProperty(value = "当ServerType为服务器端渲染且除了默认样式还有其他样式时,需要设置显示样式") @Column(name = "style") private String style; /** * POI相关 */ @ApiModelProperty(value = "POI相关") @Enumerated(EnumType.STRING) @Column(name = "poi_type") private PoiType poiType; @Column(name = "poi_url") private String poiURL; @OneToMany(mappedBy = "layer",fetch = FetchType.EAGER) // @JsonManagedReference @JsonIgnoreProperties("layer") // @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Legend> legends = new HashSet<>(); @ManyToOne private GisServer gisServer; @ManyToOne @JsonIgnoreProperties({"layers", "subGroups", "parentGroup"}) // 出于业务考虑,其实可以忽略掉,但出于前端CRUD维护关系需要保留id和name private LayerGroup layerGroup; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLayerName() { return layerName; } public Layer layerName(String layerName) { this.layerName = layerName; return this; } public void setLayerName(String layerName) { this.layerName = layerName; } public String getIdentifier() { return identifier; } public Layer identifier(String identifier) { this.identifier = identifier; return this; } public void setIdentifier(String identifier) { this.identifier = identifier; } public ServerType getSource() { return source; } public Layer source(ServerType source) { this.source = source; return this; } public void setSource(ServerType source) { this.source = source; } public PointQueryType getPointQueryType() { return pointQueryType; } public Layer pointQueryType(PointQueryType pointQueryType) { this.pointQueryType = pointQueryType; return this; } public void setPointQueryType(PointQueryType pointQueryType) { this.pointQueryType = pointQueryType; } public String getStyle() { return style; } public Layer style(String style) { this.style = style; return this; } public void setStyle(String style) { this.style = style; } public PoiType getPoiType() { return poiType; } public Layer poiType(PoiType poiType) { this.poiType = poiType; return this; } public void setPoiType(PoiType poiType) { this.poiType = poiType; } public String getPoiURL() { return poiURL; } public Layer poiURL(String poiURL) { this.poiURL = poiURL; return this; } public void setPoiURL(String poiURL) { this.poiURL = poiURL; } public Set<Legend> getLegends() { return legends; } public Layer legends(Set<Legend> legends) { this.legends = legends; return this; } public Layer addLegends(Legend legend) { this.legends.add(legend); legend.setLayer(this); return this; } public Layer removeLegends(Legend legend) { this.legends.remove(legend); legend.setLayer(null); return this; } public void setLegends(Set<Legend> legends) { this.legends = legends; } public GisServer getGisServer() { return gisServer; } public Layer gisServer(GisServer gisServer) { this.gisServer = gisServer; return this; } public void setGisServer(GisServer gisServer) { this.gisServer = gisServer; } public LayerGroup getLayerGroup() { return layerGroup; } public Layer layerGroup(LayerGroup layerGroup) { this.layerGroup = layerGroup; return this; } public void setLayerGroup(LayerGroup layerGroup) { this.layerGroup = layerGroup; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Layer layer = (Layer) o; if (layer.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), layer.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Layer{" + "id=" + getId() + ", layerName='" + getLayerName() + "'" + ", identifier='" + getIdentifier() + "'" + ", source='" + getSource() + "'" + ", pointQueryType='" + getPointQueryType() + "'" + ", style='" + getStyle() + "'" + ", poiType='" + getPoiType() + "'" + ", poiURL='" + getPoiURL() + "'" + "}"; } }
true
a7058b9ba888f1e128f527de81a978dac9e115c1
Java
LynxDevelopment/SDMCore
/SDMCore/src/com/lynxspa/coac/loadauxtables/customers/nodes/LoadCustomers.java
UTF-8
7,985
1.8125
2
[]
no_license
package com.lynxspa.coac.loadauxtables.customers.nodes; import java.util.List; import java.util.Locale; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.StatelessSession; import com.lynxit.fpm.admin.config.NodeBeautifier; import com.lynxit.fpm.admin.config.annotations.ConfigParam; import com.lynxit.fpm.events.scheduler.ScheduledEvent; import com.lynxit.fpm.nodes.support.InternalNodeSupport; import com.lynxit.fpm.resources.Resource; import com.lynxspa.sdm.dictionaries.logs.LogErrorDict; import com.lynxspa.sdm.dictionaries.logs.LogInfoDict; import com.lynxspa.sdm.managers.SDMConfigManager; import com.lynxspa.entities.application.logs.utils.LogUtils; import com.lynxspa.entities.securities.customers.SPCustomer; import com.lynxspa.entities.securities.customers.auxs.SPCustomerAux; import com.lynxspa.entities.securities.managers.SPManager; import com.lynxspa.exception.FPMException; import com.lynxspa.exception.dict.BasicErrorDict; import com.lynxspa.hbt.utils.HibernateUtils; /** * * @author joseluis.llorente * * @param <T> */ @NodeBeautifier(description="Load Customers", category="CorporateActionsCore", largeIcon="../../../../lynxit/fpm/nodes/icons/db_input_32.gif", smallIcon="../../../../lynxit/fpm/nodes/icons/db_input_16.gif") public class LoadCustomers<T extends ScheduledEvent> extends InternalNodeSupport <T>{ private static final Logger logger = Logger.getLogger(LoadCustomers.class); private Resource<Session> resource; private Resource<StatelessSession> resourceStateless; private String user; private String locale=null; private int pageSize = 100; @Override @SuppressWarnings("unchecked") protected void processMessage(T _message) throws FPMException { SDMConfigManager manager=null; StatelessSession statelessSession=null; Query loadCustomersQuery = null; int rowsMarkedForLoad=0, errors=0; int rowsDeleted=0; List<SPCustomerAux> auxCustomerList = null; SPCustomer customer = null; SPManager custManager = null; long totalRows = 0l; long totalPages = 0l; try { manager=SDMConfigManager.getInstance(); statelessSession=this.resourceStateless.getNewInstance(); loadCustomersQuery = statelessSession.createQuery("update SPCustomerAux auxCustomer set auxCustomer.deleted=:deleted where auxCustomer.deleted=:deletedFalse"); loadCustomersQuery.setParameter("deleted", true); loadCustomersQuery.setParameter("deletedFalse", false); rowsMarkedForLoad=loadCustomersQuery.executeUpdate(); HibernateUtils.commitTransaction(statelessSession); if (rowsMarkedForLoad>0){ LogUtils.createLog(statelessSession, this.user, manager.getBundleName(), new Locale(this.locale), manager.getApplication(statelessSession), LogInfoDict.AUX_TABLE_LOAD_BEGIN, new Object[]{"SPCustomerAux",rowsMarkedForLoad},null); //Paged query loadCustomersQuery=statelessSession.createQuery("select count(*) from SPCustomerAux auxCustomers where auxCustomers.deleted=:deleted"); loadCustomersQuery.setParameter("deleted",true); totalRows = (Long)loadCustomersQuery.uniqueResult(); totalPages = calculateTotalPages(totalRows); for (int pageNumber=0;pageNumber<totalPages;pageNumber++){ HibernateUtils.beguinTransaction(statelessSession); loadCustomersQuery=statelessSession.createQuery("select auxCustomers from SPCustomerAux auxCustomers where auxCustomers.deleted=:deleted order by auxCustomers.id asc"); loadCustomersQuery.setParameter("deleted",true); loadCustomersQuery.setMaxResults(pageSize); auxCustomerList = loadCustomersQuery.list(); for (SPCustomerAux auxCustomers:auxCustomerList){ try{ loadCustomersQuery=statelessSession.createQuery("select customer from SPCustomer customer where customer.customerId=:customerId"); loadCustomersQuery.setParameter("customerId",auxCustomers.getCustomerId()); loadCustomersQuery.setMaxResults(1); customer = (SPCustomer)loadCustomersQuery.uniqueResult(); loadCustomersQuery=statelessSession.createQuery("select manager from SPManager manager where manager.customerId=:managerId"); loadCustomersQuery.setParameter("managerId",auxCustomers.getManagerId().trim()); loadCustomersQuery.setMaxResults(1); custManager = (SPManager)loadCustomersQuery.uniqueResult(); if (customer==null){ customer = new SPCustomer(auxCustomers.getAuditorId(),auxCustomers.getName(),auxCustomers.getCustomerId()); customer.getAuditor().setDeleted(auxCustomers.getState()!=null && auxCustomers.getState().equals("A")); customer.setManager(custManager); HibernateUtils.customSave(statelessSession, customer, auxCustomers.getAuditorId()); }else{ customer.setManager(custManager); customer.setName(auxCustomers.getName()); customer.getAuditor().setDeleted(auxCustomers.getState()!=null && auxCustomers.getState().equals("A")); HibernateUtils.customUpdate(statelessSession, customer, auxCustomers.getAuditorId()); } loadCustomersQuery=statelessSession.createQuery("delete SPCustomerAux as auxCustomers where auxCustomers.deleted=:deleted and auxCustomers.id=:auxCustomerId"); loadCustomersQuery.setParameter("deleted", true); loadCustomersQuery.setLong("auxCustomerId", auxCustomers.getId()); rowsDeleted+=loadCustomersQuery.executeUpdate(); }catch(Exception e){ LogUtils.createLog(statelessSession, this.user, manager.getBundleName(), new Locale(this.locale), manager.getApplication(statelessSession), LogErrorDict.AUX_TABLE_LOAD_ERROR, new Object[]{"AUX_TB_SP_CUSTOMER",auxCustomers.getId()}, e); auxCustomers.setDeleted(false); HibernateUtils.customUpdate(statelessSession, auxCustomers, auxCustomers.getAuditorId()); } } HibernateUtils.commitTransaction(statelessSession); } loadCustomersQuery = statelessSession.createQuery("update SPCustomerAux auxCustomer set auxCustomer.deleted=:deleted where auxCustomer.deleted=:deletedFalse"); loadCustomersQuery.setParameter("deleted", true); loadCustomersQuery.setParameter("deletedFalse", false); errors=loadCustomersQuery.executeUpdate(); HibernateUtils.commitTransaction(statelessSession); LogUtils.createLog(statelessSession, this.user, manager.getBundleName(), new Locale(this.locale), manager.getApplication(statelessSession), LogInfoDict.AUX_TABLE_LOAD_END, new Object[]{"AUX_TB_SP_CUSTOMER",rowsDeleted,errors},null); } } catch (FPMException e) { logger.error("FPMException: "+e); throw e; } catch (Exception e) { logger.error("Exception stablishing events to be deleted: "+e); throw new FPMException(BasicErrorDict.UNEXPECTED_ERROR,e); }finally{ if(statelessSession!=null) statelessSession.close(); } } @ConfigParam(required=true) public Resource<Session> getResource() { return resource; } public void setResource(Resource<Session> resource) { this.resource = resource; } @ConfigParam(required=true) public Resource<StatelessSession> getResourceStateless() { return resourceStateless; } public void setResourceStateless(Resource<StatelessSession> resourceStateless) { this.resourceStateless = resourceStateless; } @ConfigParam(required=true) public String getUser() { return user; } public void setUser(String user) { this.user = user; } @ConfigParam(required=true) public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } @ConfigParam(required=false) public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize > 0) this.pageSize = pageSize; } private long calculateTotalPages(long totalElements){ long pages = 0l; pages = (totalElements/pageSize); if(totalElements % pageSize != 0){ pages++; } return pages; } }
true
f23e577c4bca52d4a4ee2e12365dae430c0187d5
Java
blckxsepia/bmeProject
/core/src/com/bmeproject/game/bmeProject/screens/battleScreen/battleController/battlefield/compass/ZoneViewer.java
UTF-8
3,093
2.515625
3
[]
no_license
package com.bmeproject.game.bmeProject.screens.battleScreen.battleController.battlefield.compass; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.AlphaAction; import com.badlogic.gdx.scenes.scene2d.actions.RotateToAction; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.bmeproject.game.bmeProject.screens.battleScreen.battleController.battlefield.Compass; public class ZoneViewer extends Image { // =================================== // ATTRIBUTES // =================================== private final Compass COMPASS; private final Sprite VIEWER; private final Texture KOMPASS_TEXTURE; // =================================== // CONSTRUCTORS // =================================== public ZoneViewer(Compass compass) { super(new Texture("core/assets/visuals/compass/zone_viewer_lights.png")); COMPASS = compass; KOMPASS_TEXTURE = new Texture("core/assets/visuals/compass/zone_view.png"); KOMPASS_TEXTURE.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); VIEWER = new Sprite(KOMPASS_TEXTURE); final Stage STAGE = COMPASS.BATTLEFIELD.BATTLE_CONTROLLER.giveStage(); final float CENTER_X = 1920 / 2f; final float CENTER_Y = 1080 / 2f; setPosition(CENTER_X - getWidth() / 2f, CENTER_Y - getHeight() / 2f); setOrigin(getWidth() / 2f, getHeight() / 2f); setColor(1f, 1f, 1f, 0f); STAGE.addActor(this); setZIndex(1); VIEWER.setPosition(CENTER_X - VIEWER.getWidth() / 2f, CENTER_Y - VIEWER.getHeight() / 2f); VIEWER.setOrigin(VIEWER.getWidth() / 2f, VIEWER.getHeight() / 2f); } // =================================== // METHODS // =================================== @Override protected void rotationChanged() { super.rotationChanged(); VIEWER.setRotation(getRotation()); } @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); VIEWER.draw(batch); } private float giveZoneViewerRotation() { return COMPASS.BATTLEFIELD.giveIndexOfSector(COMPASS.giveStartSector()) * 60f; } public void updateRotation() { setRotation(giveZoneViewerRotation()); } public void update() { SequenceAction sequenceAction = new SequenceAction(); AlphaAction alphaAction = new AlphaAction(); alphaAction.setAlpha(1f); alphaAction.setDuration(0.5f); sequenceAction.addAction(alphaAction); RotateToAction rotateToAction = new RotateToAction(); rotateToAction.setDuration(0.5f); rotateToAction.setRotation(giveZoneViewerRotation()); rotateToAction.setUseShortestDirection(true); rotateToAction.setInterpolation(Interpolation.pow3); sequenceAction.addAction(rotateToAction); AlphaAction alphaAction2 = new AlphaAction(); alphaAction2.setAlpha(0f); alphaAction2.setDuration(0.5f); sequenceAction.addAction(alphaAction2); addAction(sequenceAction); } }
true
04af46534647ecc44cea30c81bef9e2bc3180215
Java
JuanDiego1918/contaniif
/app/src/main/java/com/example/juandiego/contaniif/videos/CategoriasVideosFragment.java
UTF-8
7,269
1.9375
2
[]
no_license
package com.example.juandiego.contaniif.videos; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; 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 com.example.juandiego.contaniif.R; import com.example.juandiego.contaniif.adapter.CategoriasAdapter; import com.example.juandiego.contaniif.entidades.CategoriasVo; import com.example.juandiego.contaniif.interfaces.Puente; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link CategoriasVideosFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link CategoriasVideosFragment#newInstance} factory method to * create an instance of this fragment. */ public class CategoriasVideosFragment extends Fragment implements Response.Listener<JSONObject>,Response.ErrorListener{ // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public CategoriasVideosFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CategoriasVideosFragment. */ // TODO: Rename and change types and number of parameters public static CategoriasVideosFragment newInstance(String param1, String param2) { CategoriasVideosFragment fragment = new CategoriasVideosFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } RecyclerView recyclerView; ArrayList<CategoriasVo> listasCategorias; JsonObjectRequest jsonObjectRequest; RequestQueue request; Puente puente; Activity activity; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view=inflater.inflate(R.layout.fragment_categorias_videos, container, false); recyclerView=view.findViewById(R.id.recycler_categoria); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); request = Volley.newRequestQueue(getContext()); cargarWebservices(); return view; } private void cargarWebservices() { String url = "http://"+getContext().getString(R.string.ip)+"VideosCategorias.php"; jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, this, this); request.add(jsonObjectRequest); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if(context instanceof Activity){ this.activity= (Activity) context; puente=(Puente) this.activity; } if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getContext(),"NO se pudo Consultar:"+error.toString(), Toast.LENGTH_LONG).show(); Log.i("Error",error.toString()); } @Override public void onResponse(JSONObject response) { listasCategorias=new ArrayList<>(); JSONArray json=response.optJSONArray("categorias"); try { JSONObject jsonObject=null; for (int i=0;i<json.length();i++){ CategoriasVo categoriasVo=new CategoriasVo(); jsonObject=json.getJSONObject(i); categoriasVo.setId(jsonObject.optString("id")); String nombre,mayuscula; nombre=jsonObject.optString("nombre"); mayuscula=jsonObject.optString("nombre"); categoriasVo.setLetraMa(mayuscula.substring(0,1)); categoriasVo.setNombre(nombre.substring(1,nombre.length())); listasCategorias.add(categoriasVo); //Toast.makeText(getApplicationContext(),"Desc "+jsonObject.optString("id"),Toast.LENGTH_SHORT).show(); } CategoriasAdapter miCategoriasAdapter=new CategoriasAdapter(listasCategorias); recyclerView.setAdapter(miCategoriasAdapter); miCategoriasAdapter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { puente.numero(listasCategorias.get(recyclerView.getChildAdapterPosition(v)).getId()); } }); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(), "No se ha podido establecer conexión con el servidor" + " "+response, Toast.LENGTH_LONG).show(); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
true
54f54f2b344a775fdb43fc607580da099a8b1ca7
Java
Pvg08/binnTrdbot
/src/main/java/com/evgcompany/binntrdbot/coinrating/CoinRatingPairLogItem.java
UTF-8
2,848
2.03125
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.evgcompany.binntrdbot.coinrating; import com.evgcompany.binntrdbot.AbstractTradePairProcess; /** * * @author EVG_adm_T */ public class CoinRatingPairLogItem implements java.io.Serializable { public String symbol; public String symbolQuote; public String symbolBase; public AbstractTradePairProcess pair = null; public CoinRatingLogItem base_rating = new CoinRatingLogItem(); public Float percent_hour = 0f; public Float percent_day = 0f; public Float percent_from_begin = 0f; public Float start_price = 0f; public Float hour_ago_price = 0f; public Float day_ago_price = 0f; public Float current_price = 0f; public Float hour_volume = 0f; public Float hour_volume_base = 0f; public Float day_volume = 0f; public Float day_volume_base = 0f; public Float volatility = 0f; public Float signal_rating = 0f; public boolean do_remove_flag = false; public boolean fastbuy_skip = false; public Float sort = 0f; public int update_counter = 0; public boolean is_new_pair = false; public long last_rating_update_millis = 0; public double strategies_shouldenter_rate = 0; public double strategies_shouldexit_rate = 0; public float rating = 0; public float rating_inc = 0; public void calculateRating() { rating = 0; rating += base_rating.events_count / 20; rating += volatility * 150; if (base_rating.last_event_anno_millis < 1*60*60*1000) { rating++; } if (base_rating.last_event_anno_millis < 24*60*60*1000) { rating++; } if (base_rating.market_cap > 20000000) { rating += 0.2 * Math.pow(base_rating.market_cap / 20000000, 0.333); } if (hour_ago_price > 0 && hour_ago_price < current_price) { rating += current_price / hour_ago_price; } if (day_ago_price > 0 && day_ago_price < current_price) { rating += current_price / day_ago_price; } if (strategies_shouldenter_rate > strategies_shouldexit_rate) { rating+=2; } if (strategies_shouldenter_rate > strategies_shouldexit_rate + 4) { rating++; } if (strategies_shouldenter_rate > strategies_shouldexit_rate + 10) { rating++; } if (hour_volume > 0.1 * day_volume) { rating++; } if (hour_volume > 0.25 * day_volume) { rating++; } rating += signal_rating * 1.25; rating += rating_inc; if (is_new_pair) { rating *= 0.05; } } }
true
7b2901f3ed8446e956279d20ba9a3d6446a006bd
Java
RashmikaLasan/API_Automation_V2
/src/test/java/steps/HotelCalendar/HotelCalendarAssertionSteps.java
UTF-8
551
2.234375
2
[]
no_license
package steps.HotelCalendar; import actions.HotelCalendar.HotelCalendarAssertionAction; import cucumber.api.java.en.*; public class HotelCalendarAssertionSteps { HotelCalendarAssertionAction HotelCalendarAssertionAction = new HotelCalendarAssertionAction(); @Then("^I should get a successful response with status code (\\d+) for HTL Calendar Response$") public void iShouldGetASuccessfulResponseWithStatusCodeForHTLCalendarResponse(int statusCode){ HotelCalendarAssertionAction.HotelCalendarStatusCode(statusCode); } }
true
c0e1ecde2a01fbeb0888d091ce7ccee18438ef72
Java
w20090905/nebula
/nebula-engine/src/test/java/nebula/data/db/LegacyDbMasterDataExecutorTest.java
UTF-8
4,171
1.90625
2
[]
no_license
package nebula.data.db; import java.io.File; import java.net.URL; import junit.framework.TestCase; import nebula.data.DataRepos; import nebula.data.DataStore; import nebula.data.Entity; import nebula.lang.Type; import nebula.lang.TypeLoaderForTest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class LegacyDbMasterDataExecutorTest extends TestCase { TypeLoaderForTest loader; Type type; DbPersister<Entity> dbExec; DbConfiguration config; DataRepos p; DataStore<Entity> store; Log log = LogFactory.getLog(this.getClass()); static final String PATH_OF_ROOT = "htdocs2"; static final String APP_DEFINE_PATH = "app_define_path"; static final String DB_DRIVERCLASS = "db_driverclass"; static final String DB_URL = "db_url"; static final String DB_USERNAME = "db_username"; static final String DB_PASSWORD = "db_password"; protected void setUp() throws Exception { // ROOT Folder File root = null; URL url = this.getClass().getResource("/" + PATH_OF_ROOT + "/WEB-INF/web.xml"); if (url != null) { root = new File(url.getPath()).getParentFile().getParentFile(); } if (root == null) { root = new File(PATH_OF_ROOT); } if (!root.exists()) { throw new RuntimeException("cannot find " + PATH_OF_ROOT); } // // // Type Define locator // EditableTypeLoader editableLoader = new EditableTypeLoader(new SystemTypeLoader(), new File("apps/system")); // editableLoader.registerPath(new File("apps/adempiere")); // editableLoader.loadAllImmediately(); // this.loader = editableLoader; // // String driverClass = "org.postgresql.Driver"; // String dburl = "jdbc:postgresql://127.0.0.1/adempiere"; // String userName = "adempiere"; // String userPassword = "adempiere"; // // config = DbConfiguration.getEngine(driverClass, dburl, userName, userPassword); } protected void tearDown() throws Exception { // try { // config.shutdown(); // } catch (Exception e) { // throw new RuntimeException(e); // } } public final void testInlineType() throws Exception { // Statement statement; // ResultSet rs; // ResultSetMetaData metaData; // int i = 0; // // /*********************************************************/ // /***** test init *****/ // /*********************************************************/ // // EditableEntity data; // t = loader.findType("AdClient"); // dbExec = (DbMasterDataExecutor) (DbMasterDataExecutor) config.getPersister(t); // // // ************ Check Database table Layout *************/ // statement = config.conn.createStatement(); // rs = statement.executeQuery(dbExec.builder.builderGetMeta()); // metaData = rs.getMetaData(); // // assertEquals(36, metaData.getColumnCount()); // // i = 1; // assertEquals("AD_CLIENT_ID".toUpperCase(), metaData.getColumnName(i).toUpperCase()); // // assertEquals("Varchar".toUpperCase(), metaData.getColumnTypeName(i)); // // assertEquals(60, metaData.getColumnDisplaySize(i)); // // i++; // // assertEquals("Age".toUpperCase(), metaData.getColumnName(i)); // // assertEquals("BigInt".toUpperCase(), metaData.getColumnTypeName(i)); // // i++; // // assertEquals("Timestamp_".toUpperCase(), metaData.getColumnName(i)); // // assertEquals("Timestamp".toUpperCase(), // // metaData.getColumnTypeName(i)); // // rs.close(); // // ************ Check Database table Layout *************/ // // // // try { // // data = dbExec.get("wangshilian"); // // fail("should error"); // // } catch (RuntimeException e) { // // } // // // // data = new EditableEntity(); // // data.put("PersonName", "wangshilian"); // // data.put("Age", 10L); // // // // dbExec.insert(data); // // // // data = dbExec.get("wangshilian"); // // // // assertNotNull(data); // // // // dbExec.close(); // // dbExec = null; // // // // // ************ Check Database table Layout *************/ // // // // List<EditableEntity> dataList= dbExec.getAll(); // // assertEquals(3,dataList.size()); // // // // dbExec.close(); // // dbExec = null; } }
true
e2ca85de2addac801c1a454de2bc72718fd66dc7
Java
youngran90/KokoFarm_Project
/KokoFarm_project/src/kokofarm/register/model/RegDto.java
UTF-8
2,692
2.140625
2
[]
no_license
package kokofarm.register.model; import java.io.Serializable; public class RegDto implements Serializable{ private String auction_no; private String auction_name; private String seller_no; private String start_date; private String end_date; private int auction_up; private int auction_down; private String auction_content; private String auction_file; private String auction_detailImg; private String auction_detailImg2; public String getAuction_file() { return auction_file; } public void setAuction_file(String auction_file) { this.auction_file = auction_file; } public String getAuction_no() { return auction_no; } public void setAuction_no(String auction_no) { this.auction_no = auction_no; } public String getAuction_name() { return auction_name; } public void setAuction_name(String auction_name) { this.auction_name = auction_name; } public String getSeller_no() { return seller_no; } public void setSeller_no(String seller_no) { this.seller_no = seller_no; } public String getStart_date() { return start_date; } public void setStart_date(String start_date) { this.start_date = start_date; } public String getEnd_date() { return end_date; } public void setEnd_date(String end_date) { this.end_date = end_date; } public int getAuction_up() { return auction_up; } public void setAuction_up(int auction_up) { this.auction_up = auction_up; } public int getAuction_down() { return auction_down; } public void setAuction_down(int auction_down) { this.auction_down = auction_down; } public String getAuction_content() { return auction_content; } public void setAuction_content(String auction_content) { this.auction_content = auction_content; } public String getAuction_detailImg() { return auction_detailImg; } public void setAuction_detailImg(String auction_detailImg) { this.auction_detailImg = auction_detailImg; } public String getAuction_detailImg2() { return auction_detailImg2; } public void setAuction_detailImg2(String auction_detailImg2) { this.auction_detailImg2 = auction_detailImg2; } @Override public String toString() { return "RegDto [auction_no=" + auction_no + ", auction_name=" + auction_name + ", seller_no=" + seller_no + ", start_date=" + start_date + ", end_date=" + end_date + ", auction_up=" + auction_up + ", auction_down=" + auction_down + ", auction_content=" + auction_content + ", auction_file=" + auction_file + ", auction_detailImg=" + auction_detailImg + ", auction_detailImg2=" + auction_detailImg2 + "]"; } }
true
328fe2bf6400056d414063b2350050cb6ccd9ad4
Java
tatiana-bautista/pruebaCeibaFJT
/services-api/services-api-service/src/main/java/com/ceiba/services/api/service/common/dto/LibroDto.java
UTF-8
361
1.5625
2
[]
no_license
package com.ceiba.services.api.service.common.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class LibroDto { private String id; private String isbn; private String nombre; private String estado; private String ejemplar; }
true
d6e0feeebdefca94124131e8a7756fb9a127bd2a
Java
vjetteam/vjet
/extmod/org.ebayopensource.vjet.extmod.jsdt/src/org/eclipse/mod/wst/jsdt/internal/compiler/ast/QualifiedAllocationExpression.java
UTF-8
13,030
1.671875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.mod.wst.jsdt.internal.compiler.ast; import org.eclipse.mod.wst.jsdt.core.ast.IASTNode; import org.eclipse.mod.wst.jsdt.core.ast.IQualifiedAllocationExpression; import org.eclipse.mod.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.mod.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.mod.wst.jsdt.internal.compiler.flow.FlowInfo; //import org.eclipse.mod.wst.jsdt.internal.compiler.impl.Constant; //import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.BlockScope; //import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.LocalTypeBinding; //import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.MethodBinding; //import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.ProblemMethodBinding; import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.TypeBinding; //import org.eclipse.mod.wst.jsdt.internal.compiler.lookup.TypeConstants; /** * Variation on allocation, where can optionally be specified any of: * - leading enclosing instance * - trailing anonymous type * - generic type arguments for generic constructor invocation */ public class QualifiedAllocationExpression extends AllocationExpression implements IQualifiedAllocationExpression { //qualification may be on both side public Expression enclosingInstance; public TypeDeclaration anonymousType; public ReferenceBinding superTypeBinding; public QualifiedAllocationExpression() { // for subtypes } public QualifiedAllocationExpression(TypeDeclaration anonymousType) { this.anonymousType = anonymousType; anonymousType.allocation = this; } public FlowInfo analyseCode( BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { // analyse the enclosing instance if (this.enclosingInstance != null) { flowInfo = this.enclosingInstance.analyseCode(currentScope, flowContext, flowInfo); } // process arguments if (this.arguments != null) { for (int i = 0, count = this.arguments.length; i < count; i++) { flowInfo = this.arguments[i].analyseCode(currentScope, flowContext, flowInfo); } } // analyse the anonymous nested type if (this.anonymousType != null) { flowInfo = this.anonymousType.analyseCode(currentScope, flowContext, flowInfo); } manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo); return flowInfo; } public Expression enclosingInstance() { return this.enclosingInstance; } public boolean isSuperAccess() { // necessary to lookup super constructor of anonymous type return this.anonymousType != null; } /* Inner emulation consists in either recording a dependency * link only, or performing one level of propagation. * * Dependency mechanism is used whenever dealing with source target * types, since by the time we reach them, we might not yet know their * exact need. */ public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) { if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { ReferenceBinding allocatedTypeErasure = this.binding.declaringClass; // perform some extra emulation work in case there is some and we are inside a local type only if (allocatedTypeErasure.isNestedType() && currentScope.enclosingSourceType().isLocalType()) { if (allocatedTypeErasure.isLocalType()) { ((LocalTypeBinding) allocatedTypeErasure).addInnerEmulationDependent(currentScope, this.enclosingInstance != null); } } } } public StringBuffer printExpression(int indent, StringBuffer output) { if (this.enclosingInstance != null) this.enclosingInstance.printExpression(0, output).append('.'); super.printExpression(0, output); if (this.anonymousType != null) { this.anonymousType.print(indent, output); } return output; } public TypeBinding resolveType(BlockScope scope) { return null; // // added for code assist...cannot occur with 'normal' code // if (this.anonymousType == null && this.enclosingInstance == null) { // return super.resolveType(scope); // } // // // Propagate the type checking to the arguments, and checks if the constructor is defined. // // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt // // ClassInstanceCreationExpression ::= Name '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt // // this.constant = Constant.NotAConstant; // TypeBinding enclosingInstanceType = null; // TypeBinding receiverType = null; // boolean hasError = false; // boolean argsContainCast = false; // // if (this.enclosingInstance != null) { // if ((enclosingInstanceType = this.enclosingInstance.resolveType(scope)) == null){ // hasError = true; // } else if (enclosingInstanceType.isBaseType() || enclosingInstanceType.isArrayType()) { // scope.problemReporter().illegalPrimitiveOrArrayTypeForEnclosingInstance( // enclosingInstanceType, // this.enclosingInstance); // hasError = true; // } else if (this.type instanceof QualifiedTypeReference) { // scope.problemReporter().illegalUsageOfQualifiedTypeReference((QualifiedTypeReference)this.type); // hasError = true; // } else { // receiverType = ((SingleTypeReference) this.type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingInstanceType); // } // } else { // if (this.type == null) { // // initialization of an enum constant // receiverType = scope.enclosingSourceType(); // } else { // receiverType = this.type.resolveType(scope, true /* check bounds*/); // checkParameterizedAllocation: { // if (receiverType == null) break checkParameterizedAllocation; // } // } // } // if (receiverType == null) { // hasError = true; // } // // // will check for null after args are resolved // TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; // if (this.arguments != null) { // int length = this.arguments.length; // argumentTypes = new TypeBinding[length]; // for (int i = 0; i < length; i++) { // Expression argument = this.arguments[i]; // if ((argumentTypes[i] = argument.resolveType(scope)) == null){ // hasError = true; // } // } // } // // limit of fault-tolerance // if (hasError) { // if (receiverType instanceof ReferenceBinding) { // // record a best guess, for clients who need hint about possible contructor match // int length = this.arguments == null ? 0 : this.arguments.length; // TypeBinding[] pseudoArgs = new TypeBinding[length]; // for (int i = length; --i >= 0;) { // pseudoArgs[i] = argumentTypes[i] == null ? TypeBinding.NULL : argumentTypes[i]; // replace args with errors with null type // } // this.binding = scope.findMethod((ReferenceBinding) receiverType, TypeConstants.INIT, pseudoArgs, this); // if (this.binding != null && !this.binding.isValidBinding()) { // MethodBinding closestMatch = ((ProblemMethodBinding)this.binding).closestMatch; // // record the closest match, for clients who may still need hint about possible method match // if (closestMatch != null) { // this.binding = closestMatch; // MethodBinding closestMatchOriginal = closestMatch.original(); // if ((closestMatchOriginal.isPrivate() || closestMatchOriginal.declaringClass.isLocalType()) && !scope.isDefinedInMethod(closestMatchOriginal)) { // // ignore cases where method is used from within inside itself (e.g. direct recursions) // closestMatchOriginal.modifiers |= ExtraCompilerModifiers.AccLocallyUsed; // } // } // } // // } // return this.resolvedType = receiverType; // } // if (this.anonymousType == null) { // // qualified allocation with no anonymous type // if (!receiverType.canBeInstantiated()) { // scope.problemReporter().cannotInstantiate(this.type, receiverType); // return this.resolvedType = receiverType; // } // ReferenceBinding allocationType = (ReferenceBinding) receiverType; // if ((this.binding = scope.getConstructor(allocationType, argumentTypes, this)).isValidBinding()) { // if (isMethodUseDeprecated(this.binding, scope, true)) { // scope.problemReporter().deprecatedMethod(this.binding, this); // } // checkInvocationArguments(scope, null, allocationType, this.binding, this.arguments, argumentTypes, argsContainCast, this); // } else { // if (this.binding.declaringClass == null) { // this.binding.declaringClass = allocationType; // } // scope.problemReporter().invalidConstructor(this, this.binding); // return this.resolvedType = receiverType; // } // // // The enclosing instance must be compatible with the innermost enclosing type // ReferenceBinding expectedType = this.binding.declaringClass.enclosingType(); // if (expectedType != enclosingInstanceType) // must call before computeConversion() and typeMismatchError() // scope.compilationUnitScope().recordTypeConversion(expectedType, enclosingInstanceType); // if (enclosingInstanceType.isCompatibleWith(expectedType) || scope.isBoxingCompatibleWith(enclosingInstanceType, expectedType)) { // this.enclosingInstance.computeConversion(scope, expectedType, enclosingInstanceType); // return this.resolvedType = receiverType; // } // scope.problemReporter().typeMismatchError(enclosingInstanceType, expectedType, this.enclosingInstance); // return this.resolvedType = receiverType; // } // // // anonymous type scenario // // an anonymous class inherits from java.lang.Object when declared "after" an interface // this.superTypeBinding = (ReferenceBinding) receiverType; // // insert anonymous type in scope // scope.addAnonymousType(this.anonymousType, (ReferenceBinding) receiverType); // this.anonymousType.resolve(scope); // // // find anonymous super constructor // MethodBinding inheritedBinding = scope.getConstructor(this.superTypeBinding, argumentTypes, this); // if (!inheritedBinding.isValidBinding()) { // if (inheritedBinding.declaringClass == null) { // inheritedBinding.declaringClass = this.superTypeBinding; // } // scope.problemReporter().invalidConstructor(this, inheritedBinding); // return this.resolvedType = this.anonymousType.binding; // } // if (this.enclosingInstance != null) { // ReferenceBinding targetEnclosing = inheritedBinding.declaringClass.enclosingType(); // if (targetEnclosing == null) { // scope.problemReporter().unnecessaryEnclosingInstanceSpecification(this.enclosingInstance, (ReferenceBinding)receiverType); // return this.resolvedType = this.anonymousType.binding; // } else if (!enclosingInstanceType.isCompatibleWith(targetEnclosing) && !scope.isBoxingCompatibleWith(enclosingInstanceType, targetEnclosing)) { // scope.problemReporter().typeMismatchError(enclosingInstanceType, targetEnclosing, this.enclosingInstance); // return this.resolvedType = this.anonymousType.binding; // } // this.enclosingInstance.computeConversion(scope, targetEnclosing, enclosingInstanceType); // } // if (this.arguments != null) // checkInvocationArguments(scope, null, this.superTypeBinding, inheritedBinding, this.arguments, argumentTypes, argsContainCast, this); // // // Update the anonymous inner class : superclass, interface // this.binding = this.anonymousType.createDefaultConstructorWithBinding(inheritedBinding); // return this.resolvedType = this.anonymousType.binding; // 1.2 change } public void traverse(ASTVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { if (this.enclosingInstance != null) this.enclosingInstance.traverse(visitor, scope); if (this.type != null) // case of enum constant this.type.traverse(visitor, scope); if (this.arguments != null) { int argumentsLength = this.arguments.length; for (int i = 0; i < argumentsLength; i++) this.arguments[i].traverse(visitor, scope); } if (this.anonymousType != null) this.anonymousType.traverse(visitor, scope); } visitor.endVisit(this, scope); } public int getASTType() { return IASTNode.QUALIFIED_ALLOCATION_EXPRESSION; } }
true
4b5539572a5c109dcfe19c25040bf7992ac24ae6
Java
sonygrq2014/peacock
/basic/src/main/java/com/hframework/peacock/system/service/interfaces/IDictionarySV.java
UTF-8
2,503
2.125
2
[]
no_license
package com.hframework.peacock.system.service.interfaces; import java.util.*; import com.hframework.peacock.system.domain.model.Dictionary; import com.hframework.peacock.system.domain.model.Dictionary_Example; public interface IDictionarySV { /** * 创建瀛楀吀 * @param dictionary * @return * @throws Exception */ public int create(Dictionary dictionary) throws Exception; /** * 批量维护瀛楀吀 * @param dictionarys * @return * @throws Exception */ public int batchOperate(Dictionary[] dictionarys) throws Exception; /** * 更新瀛楀吀 * @param dictionary * @return * @throws Exception */ public int update(Dictionary dictionary) throws Exception; /** * 通过查询对象更新瀛楀吀 * @param dictionary * @param example * @return * @throws Exception */ public int updateByExample(Dictionary dictionary, Dictionary_Example example) throws Exception; /** * 删除瀛楀吀 * @param dictionary * @return * @throws Exception */ public int delete(Dictionary dictionary) throws Exception; /** * 删除瀛楀吀 * @param dictionaryId * @return * @throws Exception */ public int delete(long dictionaryId) throws Exception; /** * 查找所有瀛楀吀 * @return */ public List<Dictionary> getDictionaryAll() throws Exception; /** * 通过瀛楀吀ID查询瀛楀吀 * @param dictionaryId * @return * @throws Exception */ public Dictionary getDictionaryByPK(long dictionaryId) throws Exception; /** * 通过MAP参数查询瀛楀吀 * @param params * @return * @throws Exception */ public List<Dictionary> getDictionaryListByParam(Map<String, Object> params) throws Exception; /** * 通过查询对象查询瀛楀吀 * @param example * @return * @throws Exception */ public List<Dictionary> getDictionaryListByExample(Dictionary_Example example) throws Exception; /** * 通过MAP参数查询瀛楀吀数量 * @param params * @return * @throws Exception */ public int getDictionaryCountByParam(Map<String, Object> params) throws Exception; /** * 通过查询对象查询瀛楀吀数量 * @param example * @return * @throws Exception */ public int getDictionaryCountByExample(Dictionary_Example example) throws Exception; }
true
18e109c6e43577367865157c4a519377662adb9c
Java
dangth/VietNamABC
/src/com/example/vietnamabc/View/DrawView.java
UTF-8
2,334
2.640625
3
[]
no_license
package com.example.vietnamabc.View; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawView extends View { private static final float TOUCH_TOLERANCE = 1.0F; private Paint mPaint; private Path mPath; private float mX; private float mY; public DrawView(Context paramContext) { super(paramContext); initialze(); } public DrawView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); initialze(); } private void initialze() { this.mPaint = new Paint(); this.mPaint.setAntiAlias(true); this.mPaint.setDither(true); this.mPaint.setColor(Color.RED); this.mPaint.setStyle(Paint.Style.STROKE); this.mPaint.setStrokeJoin(Paint.Join.ROUND); this.mPaint.setStrokeCap(Paint.Cap.ROUND); this.mPaint.setStrokeWidth(12.0F); this.mPath = new Path(); } private void touch_move(float paramFloat1, float paramFloat2) { float f2 = Math.abs(paramFloat1 - this.mX); float f1 = Math.abs(paramFloat2 - this.mY); if ((f2 >= 1.0F) || (f1 >= 1.0F)) { this.mPath.quadTo(this.mX, this.mY, (paramFloat1 + this.mX) / 2.0F, (paramFloat2 + this.mY) / 2.0F); this.mX = paramFloat1; this.mY = paramFloat2; } } private void touch_start(float paramFloat1, float paramFloat2) { this.mPath.moveTo(paramFloat1, paramFloat2); this.mX = paramFloat1; this.mY = paramFloat2; } private void touch_up() { this.mPath.lineTo(this.mX, this.mY); } public void clear() { this.mPath.reset(); invalidate(); } protected void onDraw(Canvas paramCanvas) { paramCanvas.drawPath(this.mPath, this.mPaint); } protected void onSizeChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onSizeChanged(paramInt1, paramInt2, paramInt3, paramInt4); } public boolean onTouchEvent(MotionEvent paramMotionEvent) { float f1 = paramMotionEvent.getX(); float f2 = paramMotionEvent.getY(); switch (paramMotionEvent.getAction()) { case 0: touch_start(f1, f2); invalidate(); break; case 1: touch_up(); invalidate(); break; case 2: touch_move(f1, f2); invalidate(); } return true; } }
true
66c96a16d45c27f73bcff1e8311b407ff3f109f3
Java
stefanoscolapasta/OOP-lab04
/src/it/unibo/oop/lab04/robot/composable/ComponentBorderNavigator.java
UTF-8
533
2.890625
3
[]
no_license
package it.unibo.oop.lab04.robot.composable; public class ComponentBorderNavigator extends Component { private static double BORDER_NAVIGATOR_CONSUME = 1.2; public ComponentBorderNavigator() { super(); } public double getConsumePerAction() { return ComponentBorderNavigator.BORDER_NAVIGATOR_CONSUME; } public void use() { if(isItOn() && this.isItConnected()) { this.moveTowardsXBoundaryThenYBoundary(); } } private void moveTowardsXBoundaryThenYBoundary() { while(this.getRobot().moveUp()); } }
true
034f6b8ee200f4e9332ffc1f0c7e8a1a466f2b33
Java
hansaray/Prof.Rate-Android
/app/src/main/java/com/simpla/turnedTables/Objects/UserObject.java
UTF-8
2,316
2.453125
2
[]
no_license
package com.simpla.turnedTables.Objects; import java.io.Serializable; public class UserObject implements Serializable { private String username; private String uniName; private String fieldName; private String photoName; private long totalRatings; private long totalLikes; private long totalDislikes; private long totalLiked; private long totalDisliked; private String email; public UserObject(String username, String uniName, String fieldName, String photoName, String email) { this.username = username; this.uniName = uniName; this.fieldName = fieldName; this.photoName = photoName; this.email = email; } public long getTotalDislikes() { return totalDislikes; } public void setTotalDislikes(long totalDislikes) { this.totalDislikes = totalDislikes; } public long getTotalLiked() { return totalLiked; } public void setTotalLiked(long totalLiked) { this.totalLiked = totalLiked; } public long getTotalDisliked() { return totalDisliked; } public void setTotalDisliked(long totalDisliked) { this.totalDisliked = totalDisliked; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUniName() { return uniName; } public void setUniName(String uniName) { this.uniName = uniName; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getPhotoName() { return photoName; } public void setPhotoName(String photoName) { this.photoName = photoName; } public long getTotalRatings() { return totalRatings; } public void setTotalRatings(long totalRatings) { this.totalRatings = totalRatings; } public long getTotalLikes() { return totalLikes; } public void setTotalLikes(long totalLikes) { this.totalLikes = totalLikes; } }
true
efb15a5b09cda343d49cf85e65fc2e521e201c77
Java
zhouyudonghit/MyPractisePro
/RetrofitTest/app/src/main/java/com/example/localuser/retrofittest/ListViewTest/recyclelistview/MyRecycleViewHolder.java
UTF-8
528
2.015625
2
[]
no_license
package com.example.localuser.retrofittest.ListViewTest.recyclelistview; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.example.localuser.retrofittest.R; public class MyRecycleViewHolder extends RecyclerView.ViewHolder { public TextView textView; public MyRecycleViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.data_tv); } }
true
81a6109c1145124b4f2116bc0bbceb952e3d5e30
Java
Passion-Logan/SpringBootDemo
/Java_8/src/demoT/MaximumTest.java
UTF-8
2,153
4.125
4
[]
no_license
package demoT; /** * @File Name: demoT * @Author: WQL //作者及 * @Date: 2019/7/3 11:06//完成日期 * @Description: // 有界类型参数 * @Version: v0.0.1 // 版本信息 * @Function List: // 主要函数及其功能 * @Others: // 其它内容的说明 * @History: // 历史修改记录 */ public class MaximumTest { public static void main( String args[] ) { System.out.printf( "%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "%s, %s 和 %s 中最大的数为 %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); } /** * 有界的类型参数: * *可能有时候,你会想限制那些被允许传递到一个类型参数的类型种类范围。例如, *一个操作数字的方法可能只希望接受Number或者Number子类的实例。这就是有界类型参数的目的。 * *要声明一个有界的类型参数,首先列出类型参数的名称,后跟extends关键字,最后紧跟它的上界。 * *实例 *下面的例子演示了"extends"如何使用在一般意义上的意思"extends"(类)或者"implements"(接口)。 * 该例子中的泛型方法返回三个可比较对象的最大值。 * * <? extends T>:是指 “上界通配符(Upper Bounds Wildcards)” * <? super T>:是指 “下界通配符(Lower Bounds Wildcards)” * * 频繁往外读取内容的,适合用上界Extends。 * 经常往里插入的,适合用下界Super。 * * @param x * @param y * @param z * @param <T> * @return */ public static <T extends Comparable<T>> T maximum(T x, T y, T z) { // 假设x是初始最大值 T max = x; if (y.compareTo(max) > 0) { max = y; } if (z.compareTo(max) > 0) { max = z; } return max; } }
true
a6161f24b25913efdc843c3c7be66ae7e3cd063e
Java
zhuxinquan/JAVA
/Ex3_8/src/Ex3_8.java
UTF-8
714
3.4375
3
[]
no_license
import java.awt.*; import java.util.*; /** * Created by zhuxinquan on 15-11-17. */ public class Ex3_8 { public static void main(String[] args){ int a, b, c; Scanner reader = new Scanner(System.in); System.out.print("请输入两个整数:"); a = reader.nextInt(); b = reader.nextInt(); GcdLcm o = new GcdLcm(); c = o.getGcd(a, b); System.out.println("gcd("+a+","+b+")="+c); System.out.println("lcm("+a+","+b+")="+(a * b)/c); } } class GcdLcm{ public int getGcd(int m, int n){ int r; r = m%n; while(r != 0){ m = n; n = r; r = m%n; } return n; } }
true
1714abc43da1aa1974a6d4efbbff0a143fb41352
Java
nallamalli476/springBootDLQ
/src/main/java/com/aws/dla/attributes/CustomeDLQAttributes.java
UTF-8
3,761
2.3125
2
[]
no_license
package com.aws.dla.attributes; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder; import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import com.amazonaws.services.sqs.model.QueueAttributeName; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; public class CustomeDLQAttributes { public static void main(String[] args) { final String sourceQueueName ="mq-dsqs"; final String deadLetterQueueName = "mq-dsqs"; final String visibility_timeout="1"; final String delay_seconds="0"; final String receivemsgtimeout_seconds="3"; final String maxreceive_count="100"; String awsAccessKey="XXXXXXXXXXXXXXXXXXX"; String awsSecretKey="XXXXXXXXXXXXXXXXXXXXX"; final AmazonSQS sqs = AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.US_EAST_2) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey))) .build(); try { // Get the dead-letter queue ARN. final String deadLetterQueueUrl = sqs.getQueueUrl(deadLetterQueueName).getQueueUrl(); final GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn")); final String deadLetterQueueArn = deadLetterQueueAttributes.getAttributes().get("QueueArn"); final String sourceQueueUrl = sqs.getQueueUrl(sourceQueueName) .getQueueUrl(); final SetQueueAttributesRequest request = new SetQueueAttributesRequest() .withQueueUrl(sourceQueueUrl) . addAttributesEntry(QueueAttributeName.VisibilityTimeout.toString(), visibility_timeout) .addAttributesEntry(QueueAttributeName.DelaySeconds.toString(), delay_seconds) .addAttributesEntry(QueueAttributeName.ReceiveMessageWaitTimeSeconds.toString (), receivemsgtimeout_seconds); //.addAttributesEntry(QueueAttributeName.RedrivePolicy.toString(), "{\"maxReceiveCount\":\"" + maxreceive_count + "\", \"deadLetterTargetArn\":\"" + deadLetterQueueArn + "\"}"); sqs.setQueueAttributes(request); System.out.println("Set queue " + sourceQueueName + " as source queue " +"for dead-letter queue " + deadLetterQueueName + "."); } catch (final AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means " + "your request made it to Amazon SQS, but was " + "rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (final AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means " + "the client encountered a serious internal problem while " + "trying to communicate with Amazon SQS, such as not " + "being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }
true
df43e7396d5c7906428c028470b4f1641beaabe2
Java
SoundharyaBalu/code-stacks
/str_occur.java
UTF-8
535
3.25
3
[]
no_license
import java.util.*; class str_occur { public static void main(String args[]) { Scanner sc=new Scanner(System.in); String s1=args[0]; String sub=args[1]; int count=0,ind; for(int i=0; i+sub.length()<=s1.length(); i++) //i+sub.length() is used to reduce comparisions { ind=s1.indexOf(sub,i); if(ind>=0) { count++; i=ind; ind=-1; } } System.out.print(count); } }
true
334eeb732614266fc935ac1ffac886336e42054b
Java
abbisQQ/ZICK-ZACK
/AndroidStudioProjects/FreeFall/app/src/main/java/com/abbisqq/freefall/MainActivity.java
UTF-8
2,025
2.09375
2
[]
no_license
package com.abbisqq.freefall; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.net.Uri; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import layout.GameFragment; import layout.StartingFragment; public class MainActivity extends AppCompatActivity implements StartingFragment.OnStartingFragmentInteractionListener, GameFragment.OnGameFragmentInteractionListener { GameFragment gf = new GameFragment(); StartingFragment sf = new StartingFragment(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager manager = getSupportFragmentManager(); Fragment fragment = manager.findFragmentById(R.id.fragmentContainer); if (fragment == null) { fragment = new StartingFragment(); manager.beginTransaction().add(R.id.fragmentContainer, fragment).commit(); } } public void loadGameFragment() { getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, gf).addToBackStack(null).commit(); } public void loadStartingFragment() { getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, sf).commit(); } @Override public void OnStartingFragmentInteraction(Uri uri) { } @Override public void OnGameFragmentInteraction(Uri uri) { } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { super.onBackPressed(); try { gf.onPause(); loadStartingFragment(); }catch (Exception e){ } } }
true
246a2eacc2ad69878772659818dbd80293b6784d
Java
zjfking222/hyms
/src/main/java/com/hy/controller/qzgz/OpinionController.java
UTF-8
1,629
2.046875
2
[]
no_license
package com.hy.controller.qzgz; import com.hy.common.ResultObj; import com.hy.dto.OpinionDto; import com.hy.dto.OpinionForAdminWithPageDto; import com.hy.enums.ResultCode; import com.hy.service.qzgz.OpinionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/qzgz") public class OpinionController { @Autowired private OpinionService opinionService; @PostMapping("/web/handInOpinion") public ResultObj handInOpinion(OpinionDto opinionDto) { return opinionService.addOpinion(opinionDto) ? ResultObj.success(): ResultObj.error(ResultCode.ERROR_INVALID_PARAMETER); } @PostMapping("/admin/getOpinion") public ResultObj getOpinion(int page, int number, @RequestParam(required = false) String state) { OpinionForAdminWithPageDto opinion = opinionService.getOpinion(page,number,state); return opinion != null ? ResultObj.success(opinion): ResultObj.error(ResultCode.ERROR_NO_RESOURCE); } @PostMapping("/admin/setStateOfOpinion") public ResultObj setStateOfOpinion(int id, String state) { return opinionService.setStateOfOpinion(id,state)? ResultObj.success(): ResultObj.error(ResultCode.ERROR_INVALID_PARAMETER); } }
true
530a9ca8f48735821d9a8abd59bbaac27d541939
Java
anaadintechlabs/urbanstylepro
/Backend/common/src/main/java/com/anaadihsoft/common/master/PaymentDetails.java
UTF-8
2,099
1.820313
2
[]
no_license
package com.anaadihsoft.common.master; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class PaymentDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ManyToOne @JoinColumn(name="userId", nullable=false,updatable=false) private User user; @ManyToOne @JoinColumn(name="vendorId", nullable=false,updatable=false) private User userVendor; @ManyToOne @JoinColumn(name="varId", nullable=false,updatable=false) private ProductVariant prodVar; @ManyToOne @JoinColumn(name="payId", nullable=false,updatable=false) private PaymentTransaction pt; public UserOrder getOrder() { return order; } public void setOrder(UserOrder order) { this.order = order; } @ManyToOne @JoinColumn(name="order_id", nullable=false,updatable=false) private UserOrder order; private double amount; private Date createdDate; private String createdBy; public long getId() { return id; } public void setId(long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public User getUserVendor() { return userVendor; } public void setUserVendor(User userVendor) { this.userVendor = userVendor; } public ProductVariant getProdVar() { return prodVar; } public void setProdVar(ProductVariant prodVar) { this.prodVar = prodVar; } public PaymentTransaction getPt() { return pt; } public void setPt(PaymentTransaction pt) { this.pt = pt; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } }
true
22a800eb24ab32f50af5f7dd232cc47d90d03249
Java
Active-mcc/configx
/configx-web/src/main/java/com/configx/web/model/Webhook.java
UTF-8
5,569
2.234375
2
[ "Apache-2.0" ]
permissive
package com.configx.web.model; public class Webhook { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.id * * @mbggenerated */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.app_id * * @mbggenerated */ private Integer appId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.name * * @mbggenerated */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.url * * @mbggenerated */ private String url; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.content_type * * @mbggenerated */ private String contentType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.secret * * @mbggenerated */ private String secret; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column webhook.event_type * * @mbggenerated */ private Integer eventType; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.id * * @return the value of webhook.id * * @mbggenerated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.id * * @param id the value for webhook.id * * @mbggenerated */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.app_id * * @return the value of webhook.app_id * * @mbggenerated */ public Integer getAppId() { return appId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.app_id * * @param appId the value for webhook.app_id * * @mbggenerated */ public void setAppId(Integer appId) { this.appId = appId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.name * * @return the value of webhook.name * * @mbggenerated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.name * * @param name the value for webhook.name * * @mbggenerated */ public void setName(String name) { this.name = name; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.url * * @return the value of webhook.url * * @mbggenerated */ public String getUrl() { return url; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.url * * @param url the value for webhook.url * * @mbggenerated */ public void setUrl(String url) { this.url = url; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.content_type * * @return the value of webhook.content_type * * @mbggenerated */ public String getContentType() { return contentType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.content_type * * @param contentType the value for webhook.content_type * * @mbggenerated */ public void setContentType(String contentType) { this.contentType = contentType; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.secret * * @return the value of webhook.secret * * @mbggenerated */ public String getSecret() { return secret; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.secret * * @param secret the value for webhook.secret * * @mbggenerated */ public void setSecret(String secret) { this.secret = secret; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column webhook.event_type * * @return the value of webhook.event_type * * @mbggenerated */ public Integer getEventType() { return eventType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column webhook.event_type * * @param eventType the value for webhook.event_type * * @mbggenerated */ public void setEventType(Integer eventType) { this.eventType = eventType; } }
true
0485d8715b7840906662ab649946c562779c67ae
Java
Jesusjm2010/JavaProjectsBatch9
/src/com/class04/Task1.java
UTF-8
435
2.96875
3
[]
no_license
package com.class04; public class Task1 { public static void main(String[] args) { boolean diploma=true; double gpa=3.7; if (diploma) { System.out.println("Congratulations"); if (gpa<=3.5) { System.out.println("You are eligible for a scholarship"); }else { System.out.println("You should have studied harder"); } }else { System.out.println("You will need to get a degree"); } } }
true
8fb95bc2880e11cce848d4b2644f31a821a9ee52
Java
sblancogalante/geomessanger
/GeoMessanger/src/uy/edu/um/laboratoriotic/exceptions/employee/WrongLogin.java
UTF-8
457
2.140625
2
[]
no_license
package uy.edu.um.laboratoriotic.exceptions.employee; import java.io.Serializable; /** * This exception represents the case of a combination of user name and password * that does not exist on the database * * @author sblanco1 * */ public class WrongLogin extends Exception implements Serializable { /* * Constructor */ public WrongLogin(String msg) { super(msg); } public WrongLogin() { // TODO Auto-generated constructor stub } }
true
a41931765379271c6996de12495684ed774eea12
Java
Kostas-Papakostas/MinusXL_SoftwareEngineering
/ProjectMinusXL/src/Tests/AddSpreadsheetTest.java
UTF-8
584
2.34375
2
[]
no_license
package Tests; import static org.junit.Assert.*; import org.junit.Test; import minusxldatamanagment.*; public class AddSpreadsheetTest { Workbook workbook = Workbook.getInstance(); @Test public void test() { workbook.updateSpreadsheetList(); workbook.addSpreadsheet(new Spreadsheet(10 ,10 ,"Test")); String names = workbook.getRequestedSpreadsheet(0).getName(); for(int i=1;i<workbook.getNumberOfSpreadsheets();i++){ names += " " + workbook.getRequestedSpreadsheet(i).getName(); } assertEquals("Spreadsheet Test",names); //Spreadsheet einai h default } }
true
11098371c93520aefff3f75e272176a55142a28c
Java
Folf94/skillbox
/08_ExceptionsDebuggingAndTesting/SPBMetro/src/main/test/java/RouteCalculatorTest.java
UTF-8
3,108
2.671875
3
[]
no_license
import core.Line; import core.Station; import junit.framework.TestCase; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RouteCalculatorTest extends TestCase { StationIndex stationIndexTest = new StationIndex(); RouteCalculator calculator = new RouteCalculator(stationIndexTest); List<Station> noTransfer; List<Station> oneTransfer; List<Station> twoTransfer; Station oneOne; Station oneThree; Station twoOne; Station threeOne; @Override protected void setUp() throws Exception { Line line1 = new Line(1, "Первая"); Line line2 = new Line(2, "Вторая"); Line line3 = new Line(3, "Третья"); oneOne = new Station("Выхино", line1); Station oneTwo = new Station("Жулебино", line1); oneThree = new Station("Полежаевская", line1); twoOne = new Station("Косино", line2); Station twoTwo = new Station("Котельники", line2); Station twoThree = new Station("Ухтомская", line2); threeOne = new Station("Кузьминки", line3); Station threeTwo = new Station("Рязанский проспект", line3); Station threeThree = new Station("Текстильщики", line3); Stream.of(line1, line2, line3).forEach(stationIndexTest::addLine); Stream.of(oneOne, oneTwo, oneThree, twoOne, twoTwo, twoThree, threeOne, threeTwo, threeThree) .peek(s -> s.getLine().addStation(s)).forEach(stationIndexTest::addStation); stationIndexTest.addConnection(Stream.of(oneTwo, twoTwo).collect(Collectors.toList())); stationIndexTest.addConnection(Stream.of(twoThree, threeThree).collect(Collectors.toList())); stationIndexTest.getConnectedStations(oneTwo); stationIndexTest.getConnectedStations(twoThree); noTransfer = Stream.of(oneOne, oneTwo, oneThree).collect(Collectors.toList()); oneTransfer = Stream.of(oneOne, oneTwo, twoTwo, twoOne).collect(Collectors.toList()); twoTransfer = Stream.of(oneOne, oneTwo, twoTwo, twoThree, threeThree, threeTwo, threeOne).collect(Collectors.toList()); } public void testGetShortestRoute() { List<Station> expectedNoTransfer = noTransfer; List<Station> expectedOneTransfer = oneTransfer; List<Station> expectedTwoTransfer = twoTransfer; List<Station> actualNoTransfer = calculator.getShortestRoute(oneOne, oneThree); List<Station> actualOneTransfer = calculator.getShortestRoute(oneOne, twoOne); List<Station> actualTwoTransfer = calculator.getShortestRoute(oneOne, threeOne); assertEquals(actualNoTransfer, expectedNoTransfer); assertEquals(actualOneTransfer, expectedOneTransfer); assertEquals(actualTwoTransfer, expectedTwoTransfer); } public void testCalculateDuration() { double actual = RouteCalculator.calculateDuration(twoTransfer); double expected = 17; assertEquals(expected, actual); } }
true
3fdc6568f3bc981d182536413c5439e6bd5055ce
Java
Nurs77/untitled3
/src/day11/StringEquality.java
UTF-8
904
3.859375
4
[]
no_license
package day11; public class StringEquality { public static void main(String[] args) { /*char c1='b'; char c2='B'; char c3='b'; System.out.println("is c1 eaual to c2?"); System.out.println(c1==c2); System.out.println("is c1 equal to c2?"); System.out.println(c1==c3); int num1 = 10; int num2 = 10; System.out.println("is num1 equal to num2?"); System.out.println(num1==num2); */ String name = "Rabia"; String name2 = new String("Rabia"); String name3= "Rabia"; System.out.println(name); System.out.println(name2); System.out.println(name==name2); System.out.println(name==name3); System.out.println("USing different method"); System.out.println(name.equals(name2)); System.out.println(name.equals(name3)); } }
true
671fc990ea676ea82f258294d4da8918fde427fb
Java
wslsl0318/PotentialCommunity
/src/com/comparision/is/IsAlgorithmTWD.java
GB18030
15,550
2.265625
2
[]
no_license
package com.comparision.is; import java.util.*; /****** 20190614 Nodes Connectivity ******/ public class IsAlgorithmTWD { public int node_size; public int link_size; public int numberOfCommunities; public ArrayList<ArrayList<Integer>> adjacencyTable; public NodeInfluence ni = new NodeInfluence(); public TreeSet<NodeInfluence> node_influences; public Queue<Integer> c_must_queue; public String potential_community; public String core_nodes; public IsAlgorithmTWD(int n, int m, ArrayList<ArrayList<Integer>> adjacencyTable, String potential_community, String core_nodes) { this.node_size = n; this.link_size = m; this.numberOfCommunities = 0; this.adjacencyTable = adjacencyTable; this.c_must_queue = new LinkedList<>(); this.potential_community = potential_community; this.core_nodes = core_nodes; } public void initial(String type) { this.node_influences = ni.getNodeInfluence(type, adjacencyTable); } public ArrayList<ArrayList<Integer>> run_is(int seed_id) { ArrayList<ArrayList<Integer>> partitionF = new ArrayList<>(); TreeSet<Integer> detected_community = new TreeSet<>(); TreeSet<Integer> rest_nodes = new TreeSet<>(); TreeSet<Integer> community_neighbors = new TreeSet<>(); TreeSet<Integer> temp_detected_community = new TreeSet<Integer>(); ArrayList<NodeInfluence> node_influences_id = new ArrayList<>(); node_influences_id.addAll(node_influences); Collections.sort(node_influences_id, new Comparator<NodeInfluence>() { public int compare(NodeInfluence o1, NodeInfluence o2) { return o1.id - o2.id; } }); //20200124 add candidate seed node algorithm 20200624 change basic method to potential community ClusterCore cCore = new ClusterCore(); if("yes".equals(core_nodes)) { cCore = find_replacement_seed_node_for_initial_seed_node(seed_id, node_influences_id); detected_community = cCore.getList(); } else { detected_community.addAll(adjacencyTable.get(seed_id)); detected_community = initial_community(seed_id, detected_community, temp_detected_community, node_influences_id); } community_neighbors = get_community_neighbors(detected_community); Queue<Integer> suspicious_nodes = new LinkedList<>(); suspicious_nodes.addAll(community_neighbors); TreeSet<Integer> temp_suspicious = new TreeSet<>(); detected_community = extend_community(detected_community, suspicious_nodes, temp_suspicious, node_influences_id); for (int i = 0; i < node_size; i++) { if (!detected_community.contains(i)) { rest_nodes.add(i); } } ArrayList<Integer> temp_community = new ArrayList<>(); ArrayList<Integer> temp_rest_nodes = new ArrayList<>(); temp_community.addAll(detected_community); temp_rest_nodes.addAll(rest_nodes); partitionF.add(temp_community); partitionF.add(temp_rest_nodes); return partitionF; } public TreeSet<Integer> extend_community(TreeSet<Integer> detected_community, Queue<Integer> suspicious_nodes, TreeSet<Integer> temp_suspicious, ArrayList<NodeInfluence> node_influences_id) { Queue<Integer> new_suspicious_nodes = new LinkedList<>(); while(!suspicious_nodes.isEmpty()) { int node_id = suspicious_nodes.poll(); boolean contain = isContained(node_id, detected_community, node_influences_id); if (contain) { detected_community.add(node_id); TreeSet<Integer> neighbor_suspicious_nodes = new TreeSet<>(); neighbor_suspicious_nodes = getSuspiciousNodes(node_id, detected_community, suspicious_nodes, new_suspicious_nodes); new_suspicious_nodes.addAll(neighbor_suspicious_nodes); } else { new_suspicious_nodes.add(node_id); } } TreeSet<Integer> temp = new TreeSet<>(); temp.addAll(new_suspicious_nodes); if(!isSame(temp_suspicious,temp)) { temp_suspicious.clear(); temp_suspicious.addAll(new_suspicious_nodes); detected_community = extend_community(detected_community, new_suspicious_nodes, temp_suspicious, node_influences_id); } return detected_community; } public TreeSet<Integer> getSuspiciousNodes(int node_id, TreeSet<Integer> detected_community, Queue<Integer> suspicious_ndoes, Queue<Integer> new_suspicious_nodes) { TreeSet<Integer> neighbor_suspicious_nodes = new TreeSet<>(); TreeSet<Integer> neighbors = getNeighbors(node_id, adjacencyTable); for(int neighbor_id : neighbors) { if(!detected_community.contains(neighbor_id) && !suspicious_ndoes.contains(neighbor_id) && !new_suspicious_nodes.contains(neighbor_id)) { neighbor_suspicious_nodes.add(neighbor_id); } } return neighbor_suspicious_nodes; } public TreeSet<Integer> getNeighbors(int id, ArrayList<ArrayList<Integer>> adjacencyTables) { TreeSet<Integer> neighbours = new TreeSet<>(); neighbours.addAll(adjacencyTables.get(id)); neighbours.remove((Integer)id); return neighbours; } public TreeSet<Integer> initial_community(int seed_id, TreeSet<Integer> detected_community, TreeSet<Integer> temp_detected_community, ArrayList<NodeInfluence> node_influences_id) { Queue<Integer> detected_community_queue = new LinkedList<>(); detected_community_queue.addAll(detected_community); detected_community_queue.remove((Integer)seed_id); while(!detected_community_queue.isEmpty()) { int node_id = detected_community_queue.poll(); detected_community.remove((Integer)node_id); boolean contain = isContained(node_id, detected_community, node_influences_id); if (contain) { detected_community.add(node_id); } } if(!isSame(temp_detected_community,detected_community)) { temp_detected_community.clear(); temp_detected_community.addAll(detected_community); detected_community = initial_community(seed_id, detected_community, temp_detected_community, node_influences_id); } return detected_community; } public boolean isSame(TreeSet<Integer> tree1, TreeSet<Integer> tree2) { boolean isSame = true; if(tree1.size() != tree2.size()) { return isSame = false; } for(int node : tree1) { if(!tree2.contains(node)) { isSame = false; break; } } return isSame; } public boolean isContained(int node_id, TreeSet<Integer> detected_community, ArrayList<NodeInfluence> node_influences_id) { boolean isContained = true; TreeSet<Integer> neighbors = getNeighbors(node_id, adjacencyTable); TreeSet<Integer> neighbors_in = new TreeSet<>(); TreeSet<Integer> neighbors_out = new TreeSet<>(); int neighbors_conectivity_in = 0; int neighbors_conectivity_out = 0; TreeSet<Integer> connectivity_out = new TreeSet(); for(int neighbor : neighbors) { if(detected_community.contains(neighbor)) { neighbors_in.add(neighbor); } else { neighbors_out.add(neighbor); } } /****** based on node influence ******/ // neighbors_conectivity_in = neighbors_in.size(); for(int node_in : neighbors_in) { neighbors_conectivity_in += node_influences_id.get(node_in).influence; } if("yes".equals(this.potential_community)) { /****** 20200110 modify ******/ ArrayList<TreeSet<Integer>> connected_components = new ArrayList<>(); connected_components = getConnectedComponents(neighbors_out); for(TreeSet<Integer> tempList : connected_components) { int temp_out_influences = 0; for(int node_out : tempList) { temp_out_influences += node_influences_id.get(node_out).influence; } if(temp_out_influences > neighbors_conectivity_out) { neighbors_conectivity_out = temp_out_influences; } } } else { for(int node_out : neighbors_out) { neighbors_conectivity_out += node_influences_id.get(node_out).influence; } } if(neighbors_conectivity_in < neighbors_conectivity_out) { isContained = false; } return isContained; } ArrayList<TreeSet<Integer>> getConnectedComponents(TreeSet<Integer> nodes) { ArrayList<TreeSet<Integer>> connected_components = new ArrayList<>(); TreeSet<Integer> nodes_list = new TreeSet<>(); nodes_list.addAll(nodes); while(!nodes_list.isEmpty()) { TreeSet<Integer> component = new TreeSet<>(); TreeSet<Integer> queue = new TreeSet<Integer>(); queue.add(nodes_list.pollFirst()); while (!queue.isEmpty()) { int node_neighbor_id = queue.pollFirst(); component.add(node_neighbor_id); TreeSet<Integer> node_neighbor_neighbors = new TreeSet<>(); node_neighbor_neighbors.addAll(getNeighbors(node_neighbor_id, adjacencyTable)); TreeSet<Integer> insection = get_insection(node_neighbor_neighbors, nodes_list); queue.addAll(insection); nodes_list.removeAll(insection); } connected_components.add(component); } return connected_components; } public TreeSet<Integer> get_insection(TreeSet<Integer> setA, TreeSet<Integer> setB) { TreeSet<Integer> insection = new TreeSet<>(); for (int node : setA) { if (setB.contains(node)) insection.add(node); } return insection; } public TreeSet<Integer> get_community_neighbors(TreeSet<Integer> detected_community) { TreeSet<Integer> community_neighbors = new TreeSet<>(); for(int node : detected_community) { TreeSet<Integer> neighbors = getNeighbors(node, adjacencyTable); for(int neighbor : neighbors) { if(!detected_community.contains(neighbor)) { community_neighbors.add(neighbor); } } } return community_neighbors; } //20200124 add candidate seed node algorithm 20200624 change basic method to potential community /* (Tested) Find replacement node of the seed node */ public ClusterCore find_replacement_seed_node_for_initial_seed_node(int seed_id, ArrayList<NodeInfluence> node_influences_id) { int seed_id_new = seed_id; ClusterCore candidateCore = new ClusterCore(); do { candidateCore = find_replacement_seed_node_for_initial_seed_node_from_neighbors(seed_id_new, node_influences_id); int candidate_seed = candidateCore.getNode(); if (candidate_seed == -1) { break; } else { seed_id_new = candidate_seed; candidateCore.setNode(seed_id_new); } } while (true); return candidateCore; } //20200624 change the basic method to potential community /* (Tested) find the replacement seed node forthe initial_seed_node */ public ClusterCore find_replacement_seed_node_for_initial_seed_node_from_neighbors( int node_id, ArrayList<NodeInfluence> node_influences_id) { int seed_influence = node_influences_id.get(node_id).influence; ClusterCore seedCore = new ClusterCore(); seedCore = getClusterCore(node_id, node_influences_id); seedCore.setNode(-1); TreeSet<Integer> neighbors_of_seed = getNeighbors(node_id, adjacencyTable); for (Iterator<Integer> iter = neighbors_of_seed.iterator(); iter .hasNext();) { Integer neighbor = iter.next(); int neighbor_influence = node_influences_id.get(neighbor).influence; if(neighbor_influence > seed_influence) { TreeSet<Integer> neighborCoreComponent = new TreeSet<>(); int neighborCoreInfluence = 0; ClusterCore neighborCore = new ClusterCore(); neighborCore = getClusterCore(neighbor, node_influences_id); neighborCoreInfluence = neighborCore.getInfluences(); neighborCoreComponent = neighborCore.getList(); if (neighborCoreInfluence > seedCore.getInfluences()) { seedCore.setNode(neighbor); seedCore.setInfluences(neighborCoreInfluence); seedCore.setList(neighborCoreComponent); } } } return seedCore; } public ClusterCore getClusterCore(int node, ArrayList<NodeInfluence> node_influences_id) { ArrayList<TreeSet<Integer>> clusterCore = new ArrayList<>(); ClusterCore cCore = new ClusterCore(); TreeSet<Integer> nodes_list = new TreeSet<>(); TreeSet<Integer> medianList = new TreeSet<>(); nodes_list.addAll(getNeighbors(node,adjacencyTable)); int seed_influence = node_influences_id.get(node).influence; for(int neighbor : nodes_list) { int neighbor_influence = node_influences_id.get(neighbor).influence; if(seed_influence > neighbor_influence) { medianList.add(neighbor); } } clusterCore = getConnectedComponents(medianList); cCore = getClusterCoreInfluence(node, clusterCore, node_influences_id); cCore.setNode(node); cCore.setInfluences(cCore.getInfluences() + node_influences_id.get(node).influence); return cCore; } public ClusterCore getClusterCoreInfluence(int node_id, ArrayList<TreeSet<Integer>> clusterCore, ArrayList<NodeInfluence> node_influences_id) { int influences = 0; TreeSet<Integer> coreList = new TreeSet<>(); ClusterCore cCore = new ClusterCore(); for(TreeSet<Integer> tempClusterCore : clusterCore) { int temp_influences = 0; //ĶΪӰ // temp_influences = calculateClusterCoreInfluence(tempClusterCore, node_influences_id); for(int node : tempClusterCore) { temp_influences += node_influences_id.get(node).influence; } if(temp_influences > influences) { influences = temp_influences; coreList.clear(); coreList.addAll(tempClusterCore); } } influences += node_influences_id.get(node_id).influence; coreList.add(node_id); cCore.setInfluences(influences); cCore.setList(coreList); return cCore; } }
true
5118d06d938b6463abff451766cd040799db3493
Java
zyvpeople/ValueConsumerDeterminer
/valueConsumerDeterminerPagerAdapter/src/main/java/com/develop/zuzik/valueconsumerdeterminer/pageradapter/PagerAdapterValueConsumerDeterminer.java
UTF-8
1,409
2.546875
3
[]
no_license
package com.develop.zuzik.valueconsumerdeterminer.pageradapter; import android.support.v4.app.Fragment; import com.develop.zuzik.valueconsumerdeterminer.core.exception.GetValueConsumerException; import com.develop.zuzik.valueconsumerdeterminer.core.exception.GetValueConsumerTypeException; import com.develop.zuzik.valueconsumerdeterminer.core.interfaces.ValueConsumer; import com.develop.zuzik.valueconsumerdeterminer.core.interfaces.ValueConsumerDeterminer; import java.util.List; /** * Created by yaroslavzozulia on 9/23/17. */ public class PagerAdapterValueConsumerDeterminer<Value> { private final ValueConsumerDeterminer<Value, ValueFragmentFactory> determiner; public PagerAdapterValueConsumerDeterminer(ValueConsumerDeterminer<Value, ValueFragmentFactory> determiner) { this.determiner = determiner; } public Fragment getItem(int position, List<Value> values) { try { Value value = values.get(position); int type = determiner.getValueConsumerType(value); ValueConsumer<Value> consumer = determiner.getValueConsumer(type); ValueFragmentFactory<Value> factory = (ValueFragmentFactory<Value>) consumer; return factory.create(value); } catch (GetValueConsumerTypeException | GetValueConsumerException e) { throw new RuntimeException(e); } } }
true
b906cdeea6eab823bf1a31c2442871c9bf127174
Java
rLadia-demo/AttacknidPatch
/decompiled_src/JDGui/org/anddev/andengine/input/touch/controller/BaseTouchController.java
UTF-8
3,242
2.171875
2
[ "Apache-2.0" ]
permissive
package org.anddev.andengine.input.touch.controller; import android.view.MotionEvent; import org.anddev.andengine.engine.options.TouchOptions; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.pool.RunnablePoolItem; import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler; public abstract class BaseTouchController implements ITouchController { private boolean mRunOnUpdateThread; private ITouchController.ITouchEventCallback mTouchEventCallback; private final RunnablePoolUpdateHandler<TouchEventRunnablePoolItem> mTouchEventRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler() { protected BaseTouchController.TouchEventRunnablePoolItem onAllocatePoolItem() { return new BaseTouchController.TouchEventRunnablePoolItem(BaseTouchController.this); } }; public void applyTouchOptions(TouchOptions paramTouchOptions) { this.mRunOnUpdateThread = paramTouchOptions.isRunOnUpdateThread(); } protected boolean fireTouchEvent(float paramFloat1, float paramFloat2, int paramInt1, int paramInt2, MotionEvent paramMotionEvent) { if (this.mRunOnUpdateThread) { TouchEvent localTouchEvent2 = TouchEvent.obtain(paramFloat1, paramFloat2, paramInt1, paramInt2, MotionEvent.obtain(paramMotionEvent)); TouchEventRunnablePoolItem localTouchEventRunnablePoolItem = (TouchEventRunnablePoolItem)this.mTouchEventRunnablePoolUpdateHandler.obtainPoolItem(); localTouchEventRunnablePoolItem.set(localTouchEvent2); this.mTouchEventRunnablePoolUpdateHandler.postPoolItem(localTouchEventRunnablePoolItem); return true; } TouchEvent localTouchEvent1 = TouchEvent.obtain(paramFloat1, paramFloat2, paramInt1, paramInt2, paramMotionEvent); boolean bool = this.mTouchEventCallback.onTouchEvent(localTouchEvent1); localTouchEvent1.recycle(); return bool; } public void onUpdate(float paramFloat) { if (this.mRunOnUpdateThread) { this.mTouchEventRunnablePoolUpdateHandler.onUpdate(paramFloat); } } public void reset() { if (this.mRunOnUpdateThread) { this.mTouchEventRunnablePoolUpdateHandler.reset(); } } public void setTouchEventCallback(ITouchController.ITouchEventCallback paramITouchEventCallback) { this.mTouchEventCallback = paramITouchEventCallback; } class TouchEventRunnablePoolItem extends RunnablePoolItem { private TouchEvent mTouchEvent; TouchEventRunnablePoolItem() {} protected void onRecycle() { super.onRecycle(); TouchEvent localTouchEvent = this.mTouchEvent; localTouchEvent.getMotionEvent().recycle(); localTouchEvent.recycle(); } public void run() { BaseTouchController.this.mTouchEventCallback.onTouchEvent(this.mTouchEvent); } public void set(TouchEvent paramTouchEvent) { this.mTouchEvent = paramTouchEvent; } } } /* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar * Qualified Name: org.anddev.andengine.input.touch.controller.BaseTouchController * JD-Core Version: 0.7.0.1 */
true
15f4193ccee538badb002776f68a242ca349916a
Java
a-ader/zmei-intellij-plugin
/src/main/java/ee/negative/zmei/lang/intellij/structure/ZmeiLangRootPresentation.java
UTF-8
803
2.078125
2
[ "MIT" ]
permissive
package ee.negative.zmei.lang.intellij.structure; import com.intellij.navigation.ItemPresentation; import com.intellij.psi.PsiFile; import ee.negative.zmei.lang.intellij.Icons; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class ZmeiLangRootPresentation implements ItemPresentation { protected final PsiFile element; protected ZmeiLangRootPresentation(PsiFile element) { this.element = element; } @Nullable @Override public Icon getIcon(boolean unused) { return Icons.ZMEI_LANG_ICON; } @Nullable @Override public String getPresentableText() { return element.getVirtualFile().getNameWithoutExtension(); } @Nullable @Override public String getLocationString() { return null; } }
true
b6f6a9926c6e4b3dbf8ef0e08b48c2fa18a5aaec
Java
mathiasplans/minijira
/core/src/main/java/server/SessionContainer.java
UTF-8
1,298
2.609375
3
[]
no_license
package server; import auth.SecurityHelper; import common.UserContainer; import data.RawLogin; import messages.Session; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Class for containing the sessions * // TODO: In the third etapp */ public class SessionContainer { private final List<Session> sessions; private int idCounter = 0; private final UserContainer users; public SessionContainer(UserContainer container){ sessions = new ArrayList<>(); users = container; } public Session getSession(byte[] key){ for(Session session: sessions){ if(Arrays.equals(session.getSessionKey(), key)) return session; } return null; } public Session createSession(RawLogin login, Socket connection){ Session out = new Session( SecurityHelper.generateSessionKey(), idCounter++, users.getUser(login.username).getId(), connection.getInetAddress().getHostAddress(), connection.getPort(), connection.getLocalAddress().getHostAddress(), connection.getLocalPort() ); sessions.add(out); return out; } }
true
a2df369910b9776bfc8f0b6b4b242a11dec92ff4
Java
ZhongMing-Wu/practice
/leetcode/1754(字符串的处理)/1754.java
UTF-8
494
3.234375
3
[]
no_license
class Solution { public String largestMerge(String word1, String word2) { int len1 = word1.length(), len2 = word2.length(); int i = 0, j = 0; StringBuilder sb = new StringBuilder(); while(i < len1 || j < len2) { if(word1.substring(i).compareTo(word2.substring(j)) > 0) { sb.append(word1.charAt(i++)); continue; } sb.append(word2.charAt(j++)); } return sb.toString(); } }
true
cf64a986c1e2039dc0ad20895ed263001820f37b
Java
mindnervestech/maven
/app/models/SiteContent.java
UTF-8
1,610
2.1875
2
[]
no_license
package models; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import play.db.ebean.Model; import play.db.ebean.Model.Finder; @Entity public class SiteContent extends Model { @Id public Long id; public String heading; public String descHeading; public String description; @ManyToOne public AuthUser user; @ManyToOne public Location locations; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getHeading() { return heading; } public void setHeading(String heading) { this.heading = heading; } public String getDescHeading() { return descHeading; } public void setDescHeading(String descHeading) { this.descHeading = descHeading; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public AuthUser getUser() { return user; } public void setUser(AuthUser user) { this.user = user; } public Location getLocations() { return locations; } public void setLocations(Location locations) { this.locations = locations; } public static Finder<Long,SiteContent> find = new Finder<>(Long.class,SiteContent.class); public static SiteContent findById(Long id) { return find.byId(id); } public static SiteContent findByUser(AuthUser user) { return find.where().eq("user", user).findUnique(); } public static SiteContent findByLocation(Long location) { return find.where().eq("locations.id", location).findUnique(); } }
true
0e405505d95e2a3001c0af10100c1975024d3b66
Java
BackupTheBerlios/dms-svn
/development/jdmsystem/src/de/asaal/jdmsystem/core/iface/IJDMSystem.java
UTF-8
5,352
2.125
2
[]
no_license
package de.asaal.jdmsystem.core.iface; import java.sql.SQLException; import java.util.List; import de.asaal.jdmsystem.core.dto.DatabaseDTO; import de.asaal.jdmsystem.core.dto.DocumentDTO; import de.asaal.jdmsystem.core.dto.ExceptionStackDTO; import de.asaal.jdmsystem.core.dto.GroupDTO; import de.asaal.jdmsystem.core.dto.UserDTO; import de.asaal.jdmsystem.core.dto.UserDataDTO; /** * Copyright (C) 2009 Alexander Saal<br> * alex.saal@gmx.de<br> * <br> * <b>File:</b> IJDMSystem.java<br> * <b>Desc:</b> This class represent all global <strong>interface</strong> * function to interact with database.<br> * <br> * This file is part of DMS - Document Management System<br> * <br> * This program is free software; you can redistribute it and/or modify<br> * it under the terms of the GNU General Public License as published by<br> * the Free Software Foundation; either version 2 of the License, or<br> * (at your option) any later version.<br> * <br> * This program is distributed in the hope that it will be useful,<br> * but WITHOUT ANY WARRANTY; without even the implied warranty of<br> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br> * GNU General Public License for more details.<br> * <br> * You should have received a copy of the GNU General Public License<br> * along with this program; if not, write to the<br> * Free Software Foundation, Inc.,<br> * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.<br> */ public interface IJDMSystem { // TODO: Users // ############################################################################ /** * Create new user and return the user id * * @param userDTO * The {@link UserDTO} with all data */ public String createUser( UserDTO userDTO ); /** * Create new user specified data and return the user data id * * @param userDataDTO * The {@link UserDataDTO} */ public String createUserData( UserDataDTO userDataDTO ); /** * Returns the user id * * @param userDTO * The {@link UserDTO} */ public String getUserId( UserDTO userDTO ); /** * Returns all user from DMS database */ public List< UserDTO > getUsers(); /** * Update user and return true was user successfully updated * * @param userDTO * The {@link UserDTO} * @param userDataDTO * The {@link UserDataDTO} */ public boolean updateUser( UserDTO userDTO, UserDataDTO userDataDTO ); /** * Delete user from DMS database and return true was user deleted * * @param userDTO * The {@link UserDTO} */ public boolean deleteUser( UserDTO userDTO ); // TODO: Documents // ########################################################################### /** * @param documentDTO * @return */ public String createDocument( DocumentDTO documentDTO ); /** * @param userId * @param docName * @return */ public String getDocId( String userId, String docName ); /** * @return */ public List< DocumentDTO > getDocuments(); /** * @param userId * @return */ public List< DocumentDTO > geDocuments( String userId ); /** * @param documentDTO * @return */ public boolean updateDocument( DocumentDTO documentDTO ); /** * @param documentDTO * @return */ public boolean deleteDocument( DocumentDTO documentDTO ); // TODO: Groups // ############################################################################### /** * @param groupDTO * @return */ public String createGroup( GroupDTO groupDTO ); /** * @param groupName * @return */ public String getGroupId( String groupName ); /** * @return */ public List< GroupDTO > getGroups(); /** * @param groupDTO * @return */ public boolean updateGroup( GroupDTO groupDTO ); /** * @param groupDTO * @return */ public boolean deleteGroup( GroupDTO groupDTO ); // TODO: Miscellaneous // ######################################################################## /** * Returns the databases on MySQL Server */ public List< DatabaseDTO > getDatabases(); /** * @param userDTO * @return */ public boolean login( UserDTO userDTO ); /** * @param userDTO * @return */ public boolean logout( UserDTO userDTO ); /** * @param userDTO * @return */ public boolean isConnectionAvailabel( UserDTO userDTO ); /** * Returns a message if connection available * * @param dbUser * The database user (default is "root") * @param dbUserPwd * The database user password * @param host * The database host * @param port * The database port * @param database * The database name (default is "mysql") */ public String isConnectionAvailabel( String dbUser, String dbUserPwd, String host, String port, String database ); /** * @param exception * @param sqlException */ public void createExceptions( Exception exception, SQLException sqlException ); /** * @return */ public List< ExceptionStackDTO > getExceptions(); }
true
71f66041f917daa46f611fb265b848de4ee2f807
Java
NichWayoe/hulsp
/large-scale-programming/src/org/howard/edu/lsp/assignment7/tollboot/TollBooth.java
UTF-8
860
2.703125
3
[]
no_license
package org.howard.edu.lsp.assignment7.tollboot; public interface TollBooth { /** * displays the current state of the toll boot.- number of trucks and total receipts * @return */ String displayData(); /** * resets the number of trucks and receipts * prints the total number of trucks and receipts before reset */ void reset(); /** * calculates the toll due for a particular track * @param truck * @return toll due */ double calculateToll(Truck truck); /** * pays the amount for a toll * @param amount */ void payToll(double amount) ; /** * method to get the number of trucks since the last collection by supervisor * @return */ int getTotalNUmberOfTrucks(); /** * gets the total receipts recorded since the last collection by supervisor * @return */ public double getTotalReceipts(); }
true
b2a25f8a115516eb17682951f3f47aec8bc59410
Java
fengsri/note
/app/src/main/java/com/example/note/ActivityNoteWrite.java
UTF-8
2,812
1.960938
2
[]
no_license
package com.example.note; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.content.FileProvider; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.baidu.location.BDAbstractLocationListener; import com.baidu.location.BDLocation; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.bumptech.glide.Glide; import com.example.note.dao.DiaryDao; import com.example.note.dao.NoteDao; import com.example.note.util.DateUtil; import com.example.note.util.ImageUtil; import com.example.note.util.UserUtil; import java.io.File; import java.io.IOException; public class ActivityNoteWrite extends AppCompatActivity implements View.OnClickListener { private TextView noteTitle; private TextView noteText; private TextView noteDate; private TextView save; private String date; private String title; private String text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_write_note); ActionBar supportActionBar = getSupportActionBar(); this.setTitle("编辑便签"); supportActionBar.setHomeButtonEnabled(true);//主键按钮能否可点击 supportActionBar.setDisplayHomeAsUpEnabled(true);//显示返回图标 noteTitle = findViewById(R.id.note_title); noteText = findViewById(R.id.note_text); noteDate = findViewById(R.id.note_write_date); noteDate.setText(DateUtil.today()); save = findViewById(R.id.note_write_save); save.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.note_write_save:{ save(); finish(); break; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case android.R.id.home:////主键id 必须这样写 finish(); break; } return super.onOptionsItemSelected(item); } private void save(){ date = noteDate.getText().toString(); title = noteTitle.getText().toString(); text = noteText.getText().toString(); NoteDao.saveBeanNoteToYun(UserUtil.user.getObjectId(),date,title,text,null,null,null,null,ActivityNoteWrite.this); } }
true
2b0d9fee6c9788b9b44b08d0cdf468f99173321a
Java
SRH-SDP-2018-Oct/sdpoctober2018-projects-group1-food-service-application
/Old/Final Merging Process 80%/FsaDayPage.java
UTF-8
1,298
2.671875
3
[]
no_license
package com.srh_heidelberg.mealsanddeals; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class FsaDayPage { private static FSA loggedInfsa = new FSA(); public static void BacktoDay(Date date) throws ParseException, NoSuchAlgorithmException, SQLException { ShowDay(date,loggedInfsa); } public static void BacktoChooseDate() throws ParseException, NoSuchAlgorithmException, SQLException { FsaHomepage.manageFoodlist(); } public static void ShowDay(Date date,FSA loggedInFsa) throws ParseException, NoSuchAlgorithmException, SQLException { loggedInfsa = loggedInFsa; System.out.print("\033[H\033[2J"); System.out.println("DAY PAGE"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("The date you selected is "+ dateFormat.format(date)); System.out.print("1: food option\n2: offer option\n3: back to Home Page\n>>"); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); switch(n) { case 1: FoodOption.ShowFoodOption(date,loggedInfsa); case 2: OfferOption.ShowOfferOption(date,loggedInfsa); case 3: FsaHomepage.main(loggedInfsa); } } }
true
76f8609d7a2d88507c700fd52110ee5d1f9277f4
Java
robert-solomon12/Multi-Threaded-Client-Server-U.A.
/src/controller/Database.java
UTF-8
885
2.875
3
[ "MIT" ]
permissive
package controller; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class Database { /* * Connection method call to execute connection to my WAMP Server Database */ public static Connection getConnection() throws SQLException { Connection conn; /* * Connection String containing 3 parameters to establish connectivity to my Database WAMP SERVER (URL, USERNAME, PASSWORD) */ conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/assign2?serverTimezone=UTC","root","admin"); //Printing a successful connection message if a successful connection has been established. System.out.println("Connection to Database has been successfully established!"); return conn; } }
true
97b6ec44c7e5c86f0b24b82e0c81ee538c988833
Java
18237196980/wechat-server
/src/main/java/com/netty/wechatserver/model/ChatMsg.java
UTF-8
816
1.890625
2
[]
no_license
package com.netty.wechatserver.model; import com.baomidou.mybatisplus.annotation.TableName; import java.time.LocalDateTime; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author * @since 2021-04-22 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("chat_msg") public class ChatMsg implements Serializable { private static final long serialVersionUID = 1L; private String id; private String send_user_id; private String accept_user_id; private String msg; /** * 消息是否签收状态 1:签收 0:未签收 */ private Integer sign_flag; /** * 发送请求的事件 */ private LocalDateTime create_time; }
true
f4901cb0eb22e98955458442d37547c486b208c8
Java
masadkhawaja/digicart
/app/src/main/java/com/example/shiva/loginsignup/DashboardActivity.java
UTF-8
11,694
1.875
2
[ "Apache-2.0" ]
permissive
package com.example.shiva.loginsignup; import android.Manifest; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v4.app.ActivityCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class DashboardActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 1; private static final int MY_PERMISSIONS_REQUEST_RECEIVE_SMS = 2; private static final int MY_PERMISSIONS_REQUEST_READ_SMS = 3; private MySmsReceiver mySmsReceiver; public String NameHolder,EmailHolder,PasswordHolder; TextView Name; Button LogOUT,update ; EditText editText; ComponentName component; String id,gsmnumber; SQLiteDatabase sqLiteDatabaseObj; SQLiteHelper sqLiteHelper; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); checkForSmsPermission(); mySmsReceiver = new MySmsReceiver(); sqLiteHelper = new SQLiteHelper(this); checkBroadCastRec(); editText = (EditText) findViewById(R.id.editText_main); Name = (TextView)findViewById(R.id.textView1); LogOUT = (Button)findViewById(R.id.button1); update = (Button) findViewById(R.id.update); Intent intent = getIntent(); // Receiving User Email Send By MainActivity. NameHolder = intent.getStringExtra("name"); PasswordHolder = intent.getStringExtra("pass"); EmailHolder = intent.getStringExtra("email"); id = intent.getStringExtra("id"); // Setting up received email to TextView. Name.setText(Name.getText().toString()+ NameHolder); Name.setVisibility(View.GONE); editText.setText(Name.getText().toString()); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean isUpdate= sqLiteHelper.update(EmailHolder,editText.getText().toString()); if (isUpdate == true) Toast.makeText(DashboardActivity.this, "Data Update", Toast.LENGTH_SHORT).show(); else Toast.makeText(DashboardActivity.this, "Not Update", Toast.LENGTH_SHORT).show(); } }); // Adding click listener to Log Out button. LogOUT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Finishing current DashBoard activity on button click. finish(); Toast.makeText(DashboardActivity.this,"Log Out Successfull", Toast.LENGTH_LONG).show(); } }); } /** * Checks whether the app has SMS permission. */ private void checkForSmsPermission() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, getString(R.string.permission_not_granted)); // Permission not yet granted. Use requestPermissions(). // MY_PERMISSIONS_REQUEST_SEND_SMS is an // app-defined int constant. The callback method gets the // result of the request. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSIONS_REQUEST_RECEIVE_SMS); } if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, MY_PERMISSIONS_REQUEST_READ_SMS); } else { // Permission already granted. Enable the SMS button. enableSmsButton(); } } /** * Processes permission request codes. * * @param requestCode The request code passed in requestPermissions() * @param permissions The requested permissions. Never null. * @param grantResults The grant results for the corresponding permissions * which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null. */ @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { // For the requestCode, check if permission was granted or not. switch (requestCode) { case MY_PERMISSIONS_REQUEST_SEND_SMS: { if (permissions[0].equalsIgnoreCase(Manifest.permission.SEND_SMS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Enable sms button. enableSmsButton(); } else { // Permission denied. Log.d(TAG, getString(R.string.failure_permission)); Toast.makeText(this, getString(R.string.failure_permission), Toast.LENGTH_LONG).show(); // Disable the sms button. disableSmsButton(); } }break; case MY_PERMISSIONS_REQUEST_RECEIVE_SMS:{ if (permissions[0].equalsIgnoreCase(Manifest.permission.RECEIVE_SMS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Enable sms button. enableSmsButton(); } else { // Permission denied. Log.d(TAG, getString(R.string.failure_permission)); Toast.makeText(this, getString(R.string.failure_permission), Toast.LENGTH_LONG).show(); // Disable the sms button. disableSmsButton(); } }break; case MY_PERMISSIONS_REQUEST_READ_SMS:{ if (permissions[0].equalsIgnoreCase(Manifest.permission.READ_SMS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Enable sms button. enableSmsButton(); } else { // Permission denied. Log.d(TAG, getString(R.string.failure_permission)); Toast.makeText(this, getString(R.string.failure_permission), Toast.LENGTH_LONG).show(); // Disable the sms button. disableSmsButton(); } } } } /** * Defines a string (destinationAddress) for the phone number * and gets the input text for the SMS message. * Uses SmsManager.sendTextMessage to send the message. * Before sending, checks to see if permission is granted. * * @param view View (message_icon) that was clicked. */ public String number ; public String destinationAddress; public void smsSendMessage(View view) { // Set the destination phone number to the string in editText. destinationAddress = editText.getText().toString(); // Find the sms_message view. EditText smsEditText = (EditText) findViewById(R.id.sms_message); smsEditText.setVisibility(View.GONE); // Get the text of the sms message. // String smsMessage = smsEditText.getText().toString(); String smsMessage = "Bill"; // Set the service center address if needed, otherwise null. String scAddress = null; // Set pending intents to broadcast // when message sent and when delivered, or set to null. PendingIntent sentIntent = null, deliveryIntent = null; // Check for permission first. checkForSmsPermission(); // Use SmsManager. SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(destinationAddress, scAddress, smsMessage, sentIntent, deliveryIntent); } /** * Makes the sms button (message icon) invisible so that it can't be used, * and makes the Retry button visible. */ private void disableSmsButton() { Toast.makeText(this, R.string.sms_disabled, Toast.LENGTH_LONG).show(); Button smsButton = (Button) findViewById(R.id.message_icon); smsButton.setVisibility(View.INVISIBLE); Button retryButton = (Button) findViewById(R.id.button_retry); retryButton.setVisibility(View.VISIBLE); } /** * Makes the sms button (message icon) visible so that it can be used. */ private void enableSmsButton() { Button smsButton = (Button) findViewById(R.id.message_icon); smsButton.setVisibility(View.VISIBLE); } /** * Sends an intent to start the activity. * * @param view View (Retry button) that was clicked. */ public void retryApp(View view) { Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(intent); } @Override protected void onResume() { registerReceiver(mySmsReceiver, new IntentFilter( "android.provider.Telephony.SMS_RECEIVED")); super.onResume(); // getApplicationContext().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP); } @Override protected void onDestroy() { // unregisterReceiver(mySmsReceiver); super.onDestroy(); // getApplicationContext().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP); } @Override protected void onPause() { unregisterReceiver(mySmsReceiver); super.onPause(); // getApplicationContext().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP); } private void checkBroadCastRec() { component = new ComponentName(getApplicationContext(), MySmsReceiver.class); int status = getApplicationContext().getPackageManager().getComponentEnabledSetting(component); if(status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { Log.d("Check stat","receiver is enabled"); } else if(status == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) { Log.d("Check stat","receiver is disabled"); } } }
true
0e9d40c4391e3f49809a352324127e92ddb82dba
Java
kotiknorm/WhereIsMyCurrency
/app/src/main/java/apps/makarov/com/whereismycurrency/repository/ttl/NotNullCachingStrategy.java
UTF-8
209
2.21875
2
[]
no_license
package apps.makarov.com.whereismycurrency.repository.ttl; public class NotNullCachingStrategy<T> implements CachingStrategy<T> { @Override public boolean isValid(T data) { return data != null; } }
true
9560af8d88e4b640fc13d2b48fbe1a78cf5240e0
Java
icai/shushimall
/mall/mall-common/src/main/java/com/camelot/fastdfs/PicReqInterceptor.java
UTF-8
5,220
2.328125
2
[]
no_license
package com.camelot.fastdfs; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class PicReqInterceptor { //private FileManager fileManager; //http://192.168.1.186:8000/group2/M00/00/00/wKgBvFcGi3CATUkwAErASNF-ON0066.JPG!80x80 public static String handlePicReq(String reqFileUrlString){ String[] cutReqFileUrlString = cutReqFileUrlString(reqFileUrlString); if(cutReqFileUrlString != null){ if(cutReqFileUrlString.length > 2){ return reqFileUrlString; } if(isPicReq(cutReqFileUrlString[0])){ try { URL reqFileUrl = new URL(reqFileUrlString); String[] reqFilePath = cutReqFileUrl(reqFileUrl); if(reqFilePath != null){ if(reqFilePath.length < 2){ return reqFileUrlString; } String subFileName = getSubFileName(reqFilePath); // 判断缩略图是否存在 存在 直接返回 if(FileManager.fileIsExist(subFileName.substring(1))){ return FileManager.PROTOCOL+reqFileUrl.getHost()+FileManager.PORT_SEPARATOR+reqFileUrl.getPort()+ subFileName; }else { //准备尺寸 后缀 reqFilePath[0] 扩展名 ( PictureUtils.getExtensionName(cutReqFileUrlString[0]) ) return FileManager.generateThumbnail(reqFilePath[0].substring(1), reqFilePath[1], PictureUtils.getExtensionName(cutReqFileUrlString[0])); } } } catch (Exception e) { // TODO: handle exception } } } /*if(isPicReq(reqFileUrlString)){ try { URL reqFileUrl = new URL(reqFileUrlString); String[] reqFilePath = cutReqFileUrl(reqFileUrl); if(reqFilePath != null){ if(reqFilePath.length < 2){ return reqFileUrlString; } String subFileName = getSubFileName(reqFilePath); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ return reqFileUrlString; } //http://192.168.1.186:8000/group2/M00/00/00/wKgBvFcGi3CATUkwAErASNF-ON0066_80x80.JPG public static String handlePicReq2(String reqFileUrlString){ if(PictureUtils.isPicType(reqFileUrlString)){ try { URL reqFileUrl = new URL(reqFileUrlString); List<String> reqFilePath = cutReqFileUrl2(reqFileUrl); if(reqFilePath != null){ if(reqFilePath.size() < 3){ return reqFileUrlString; } //String subFileName = getSubFileName(reqFilePath); // 判断缩略图是否存在 存在 直接返回 if(FileManager.fileIsExist(reqFilePath.get(0).substring(1) + Constant.SUB_FILE_NAME_EXTEND + reqFilePath.get(2) + Constant.FILE_SUFFIX_NAME+reqFilePath.get(1))){ return reqFileUrlString; }else { //准备尺寸 后缀 reqFilePath[0] 扩展名 ( PictureUtils.getExtensionName(cutReqFileUrlString[0]) ) return FileManager.generateThumbnail(reqFilePath.get(0).substring(1)+Constant.FILE_SUFFIX_NAME+reqFilePath.get(1), reqFilePath.get(2), reqFilePath.get(1)); } } } catch (MalformedURLException e) { e.printStackTrace(); } }else { return reqFileUrlString; } return reqFileUrlString; } private static String[] cutReqFileUrlString(String reqFileUrlString) { String[] urlAndArgs = reqFileUrlString.split(Constant.URL_ARGS_DELIMITER); return urlAndArgs; } private static String getSubFileName(String[] reqFilePath) { String[] split = reqFilePath[0].split(Constant.FILE_SUFFIX_DELIMITER); //String size = reqFilePath[1].replace(Constant.PIC_HEIGHT_WIDTH_DELIMITER, Constant.SUB_FILE_NAME_EXTEND); String subFileName = split[0]+ Constant.SUB_FILE_NAME_EXTEND + reqFilePath[1] + Constant.FILE_SUFFIX_NAME +split[1]; return subFileName; } private static boolean isPicReq(String reqFileUrlString) { String extensionName = PictureUtils.getExtensionName(reqFileUrlString); return PictureUtils.isPicType(extensionName); } public static String[] cutReqFileUrl(URL reqFileUrl){ try { String path = reqFileUrl.getPath(); String[] urlAndArgs = path.split(Constant.URL_ARGS_DELIMITER); return urlAndArgs; } catch (Exception e) { e.printStackTrace(); } return null; } //http://192.168.1.186:8000/group2/M00/00/00/wKgBvFcGi3CATUkwAErASNF-ON0066_80x80.JPG public static List<String> cutReqFileUrl2(URL reqFileUrl){ try { String path = reqFileUrl.getPath(); String fileNameNoEx = PictureUtils.getFileNameNoEx(path); //获取扩展名 String extensionName = PictureUtils.getExtensionName(path); //获取尺寸参数 String sizeArgs = PictureUtils.getSizeArgs(fileNameNoEx); //获取文件名 String fileNameNoArgs = PictureUtils.getFileNameNoArgs(fileNameNoEx); ArrayList<String> pathConstructionList = new ArrayList<String>(); pathConstructionList.add(fileNameNoArgs); pathConstructionList.add(extensionName); if(sizeArgs != null){ pathConstructionList.add(sizeArgs); } return pathConstructionList; } catch (Exception e) { e.printStackTrace(); } return null; } /*public static void main(String[] args) { System.out.println(new PicReqInterceptor().handlePicReq("http://192.168.1.186:8000/group1/M00/00/00/wKgBu1cGhGaANk-3AErASNF-ON0487.jpg!100x100")); }*/ }
true
1dd12abe8be76a54255c98ea04c9e819233b2f86
Java
lese1000/lot-api
/src/main/java/com/example/demo/dao/PlayerDaoMapper.java
UTF-8
272
1.976563
2
[]
no_license
package com.example.demo.dao; import org.apache.ibatis.annotations.Param; import com.example.demo.model.entity.Player; public interface PlayerDaoMapper { Player findByNameAndPassowrd(Player player); Player findByPlayerName(@Param("playerName") String playerName); }
true
26e2a4c35de4a48d24a9778f85bc7455e7a349f5
Java
srivera/AppRiesgo
/app/src/main/java/activities/riesgo/yacare/com/ec/appriesgo/asynctask/ObtenerOficiosAsyncTask.java
UTF-8
5,125
2.0625
2
[]
no_license
package activities.riesgo.yacare.com.ec.appriesgo.asynctask; import android.content.Context; import android.os.AsyncTask; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import activities.riesgo.yacare.com.ec.appriesgo.app.DatosAplicacion; import activities.riesgo.yacare.com.ec.appriesgo.boletin.BoletinFragment; import activities.riesgo.yacare.com.ec.appriesgo.datasource.local.BoletinDataSource; import activities.riesgo.yacare.com.ec.appriesgo.dto.Boletin; import activities.riesgo.yacare.com.ec.appriesgo.util.Constantes; import activities.riesgo.yacare.com.ec.appriesgo.util.VariablesUtil; public class ObtenerOficiosAsyncTask extends AsyncTask<String, Float, String> { private BoletinFragment boletinFragment; private Context context; public ObtenerOficiosAsyncTask(Context context, BoletinFragment boletinFragment) { super(); this.boletinFragment = boletinFragment; this.context = context; } @Override protected String doInBackground(String... arg0) { final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 10000); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httppost = new HttpPost(Constantes.URL_OBTENER_OFICIOS); httppost.setHeader("content-type", "application/x-www-form-urlencoded;charset=UTF-8"); DatosAplicacion datosAplicacion = (DatosAplicacion) boletinFragment.getActivity().getApplicationContext(); BoletinDataSource boletinDataSource = new BoletinDataSource(context); boletinDataSource.open(); Integer maximo = boletinDataSource.getMaxBoletinByRiesgo(datosAplicacion.getRiesgoActual().getId()); if(maximo - 10 < 0){ maximo = 0; } boletinDataSource.close(); String respStr = ""; try { String certificadoSeguridad = VariablesUtil.generarMD5(maximo + datosAplicacion.getRiesgoActual().getId() + Constantes.CERTIFICADO_SEGURIDAD); String json = "{\"obtenerOficios\":{\"idUltimo\":\""+ maximo + "\",\"idRiesgo\":\""+ datosAplicacion.getRiesgoActual().getId() + "\",\"certificadoseguridad\":\""+ certificadoSeguridad + "\"}}"; StringEntity se = new StringEntity(json); httppost.setEntity(se); HttpResponse resp = httpclient.execute(httppost); respStr = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8); } catch (ClientProtocolException e) { e.printStackTrace(); return "ERR"; } catch (IOException e) { e.printStackTrace(); return "ERR"; } return respStr; } protected void onPostExecute(String respuesta) { if(!respuesta.equals("ERR")){ Boolean statusFlag = null; JSONObject respuestaJSON = null; try { respuestaJSON = new JSONObject(respuesta); statusFlag = respuestaJSON.getBoolean("statusFlag"); } catch (JSONException e) { e.printStackTrace(); } if(statusFlag != null && statusFlag){ String idCuenta = null; JSONObject cuentaJSON = null; try { cuentaJSON = new JSONObject( respuestaJSON.getString("resultado")); JSONArray boletines = new JSONArray(cuentaJSON.getString("boletines")); if(boletines.length() > 0) { BoletinDataSource boletinDataSource = new BoletinDataSource(context); boletinDataSource.open(); for (int i = 0, size = boletines.length(); i < size; i++) { JSONObject equipoInArray = boletines.getJSONObject(i); Boletin boletinBusqueda = boletinDataSource.getBoletinByRiesgoId(equipoInArray.getString("idriesgo"),equipoInArray.getString("id") ); if(boletinBusqueda != null){ boletinDataSource.deleteBoletin(equipoInArray.getString("idriesgo"),equipoInArray.getString("id") ); } Boletin boletin = new Boletin(); boletin.setId(equipoInArray.getString("id")); boletin.setLeyenda(equipoInArray.getString("leyenda")); boletin.setIdRiesgo(equipoInArray.getString("idriesgo")); boletin.setUrl(equipoInArray.getString("url")); boletin.setTitulo(equipoInArray.getString("titulo")); boletin.setFecha(equipoInArray.getString("fechaformateada")); boletinDataSource.createBoletin(boletin); } boletinDataSource.close(); if(boletines.length() > 0 && boletinFragment!= null) { boletinFragment.verificarBoletines(true); } } } catch (JSONException e) { e.printStackTrace(); } } } } }
true
495c4e1ae496dbf5b6c622f2d0133355732a456c
Java
helen520/catering
/src/main/java/helen/catering/model/entities/MemberPolicy.java
UTF-8
2,216
2.296875
2
[]
no_license
package helen.catering.model.entities; import helen.catering.Utils; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "MemberPolicy") public class MemberPolicy { @Id private long id; @Column private long storeId; @Column private long startDate; @Column private long endDate; @Column private String title; @Column private String subTitle; @Column private String text; @Column private String url; @Column private boolean displayOnBottom; @Transient private String startDateStr; @Transient private String validDate; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getStoreId() { return storeId; } public void setStoreId(long storeId) { this.storeId = storeId; } public long getStartDate() { return startDate; } public void setStartDate(long startDate) { this.startDate = startDate; } public long getEndDate() { return endDate; } public void setEndDate(long endDate) { this.endDate = endDate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public boolean getDisplayOnBottom() { return displayOnBottom; } public void setDisplayOnBottom(boolean displayOnBottom) { this.displayOnBottom = displayOnBottom; } public String getStartDateStr() { return Utils.formatShortDateTimeYMD(startDate); } public String getValidDate() { return Utils.formatShortDateTimeYMD(endDate); } @Transient public static MemberPolicy create() { MemberPolicy memberPolicy = new MemberPolicy(); long id = UUID.randomUUID().getLeastSignificantBits(); id = id / 0x1000; id = Long.signum(id) * id; memberPolicy.setId(id); return memberPolicy; } }
true
a82429d01f0d16af7b46a47197bbfa5311a85fc3
Java
javachandu/coreAlgorithms
/src/com/chandu/core/StringOccurences.java
UTF-8
667
3.40625
3
[]
no_license
package com.chandu.core; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class StringOccurences { static List list = new ArrayList(); public static void main(String args[]) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); input = input.replaceAll("\\s", ""); char[] arr = input.toCharArray(); for (char ch : arr) { if (!list.contains(ch)) { System.out.println(ch + "=" + countnum(input, ch)); list.add(ch); } } } public static int countnum(String st, char ch) { list.add(ch); return st.length() == 0 ? 0 : (st.charAt(0) == ch ? 1 : 0) + countnum(st.substring(1), ch); } }
true
79387961a0a6c60d07cca4f3065ae6583b598156
Java
nseidm1/DigiID
/app/src/main/java/com/noahseidman/digiid/utils/QRUtils.java
UTF-8
4,557
2.109375
2
[]
no_license
package com.noahseidman.digiid.utils; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.view.Display; import android.view.WindowManager; import android.widget.ImageView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.android.CaptureActivity; import com.google.zxing.common.BitMatrix; import java.util.EnumMap; import java.util.Map; import static android.graphics.Color.BLACK; import static android.graphics.Color.WHITE; public class QRUtils { public static final int SCANNER_REQUEST = 201; public static final int SCANNER_RESTORE = 233; private static Bitmap encodeAsBitmap(String content, int dimension) { if (content == null) { return null; } Map<EncodeHintType, Object> hints = null; String encoding = guessAppropriateEncoding(content); hints = new EnumMap<>(EncodeHintType.class); if (encoding != null) { hints.put(EncodeHintType.CHARACTER_SET, encoding); } hints.put(EncodeHintType.MARGIN, 1); BitMatrix result = null; try { result = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, dimension, dimension, hints); } catch (IllegalArgumentException iae) { // Unsupported format return null; } catch (WriterException e) { e.printStackTrace(); } if (result == null) return null; int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } public static void generateQR(Context ctx, String bitcoinURL, ImageView qrcode) { WindowManager manager = (WindowManager) ctx.getSystemService(Activity.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y; int smallerDimension = width < height ? width : height; smallerDimension = (int) (smallerDimension * 0.45f); Bitmap bitmap = QRUtils.encodeAsBitmap(bitcoinURL, smallerDimension); qrcode.setImageBitmap(bitmap); qrcode.animate().alpha(1f).setDuration(500).start(); } public static Bitmap getQRImage(Context ctx, String bitcoinURL) { WindowManager manager = (WindowManager) ctx.getSystemService(Activity.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y; int smallerDimension = width < height ? width : height; smallerDimension = (int) (smallerDimension * 0.45f); return QRUtils.encodeAsBitmap(bitcoinURL, smallerDimension); } private static String guessAppropriateEncoding(CharSequence contents) { // Very crude at the moment for (int i = 0; i < contents.length(); i++) { if (contents.charAt(i) > 0xFF) { return "UTF-8"; } } return null; } public static void openScanner(Activity app, int code) { try { if (ContextCompat.checkSelfPermission(app, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(app, new String[]{Manifest.permission.CAMERA}, code); } else { Intent intent = new Intent(app, CaptureActivity.class); intent.setAction("com.google.zxing.client.android.SCAN"); intent.putExtra("SAVE_HISTORY", false); app.startActivityForResult(intent, code); } } catch (Exception e) { e.printStackTrace(); } } }
true
ab4f6ff9b55761fbc8a3fd510829d107cb3222c0
Java
sveri/historify-spring-backend
/src/main/java/de/sveri/historify/controller/rest/Login.java
UTF-8
1,978
2.203125
2
[]
no_license
package de.sveri.historify.controller.rest; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import de.sveri.historify.controller.exception.InvalidLoginException; import de.sveri.historify.entity.User; import de.sveri.historify.entity.UserRepository; import de.sveri.historify.helper.JwtHelper; import de.sveri.historify.service.UserService; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.Getter; @RestController public class Login { public static final String INVALID_LOGIN_ID = "1000"; @Autowired @Getter private JwtHelper jwtHelper; @Autowired private UserRepository userRep; @RequestMapping(value = "/apilogin", method = RequestMethod.POST) public LoginResponse login(@RequestBody final UserLogin login, HttpServletResponse response) throws ServletException, InvalidLoginException { User user = userRep.findOneByUserNameOrEmail(login.getName(), login.getName()); if (user == null || !UserService.matchesPassword(login.getPassword(), user.getPassword())) { throw new InvalidLoginException(); } Date date = new Date(); long t = date.getTime(); Date expirationTime = new Date(t + 32960000000l); String token = Jwts.builder().setSubject(login.getName()).setExpiration(expirationTime) .claim("roles", user.getRole()).setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, jwtHelper.getSecretKey()).compact(); return new LoginResponse(token); } @SuppressWarnings("unused") private static class LoginResponse { public String token; public LoginResponse(final String token) { this.token = token; } } }
true
004eff12b1d8bb79824a07d75039305648eba823
Java
Rahul090898/.myrepository
/Task2.java
UTF-8
244
3.046875
3
[]
no_license
class Task2 { void MethodMultiply(){ int i,Num=17; for(i=1;i<=10;i++){ System.out.println(Num*i+"\n"); } } public static void main(String[] args) { Task2 s = new Task2(); s.MethodMultiply(); } }
true
fef308564b02d9ba4952cfa666e3072d6f71643c
Java
naruto2015/love_family
/WeiTuPrivate/src/main/java/com/jiedu/project/lovefamily/fragment/HomeFragment.java
UTF-8
12,205
1.679688
2
[]
no_license
package com.jiedu.project.lovefamily.fragment; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.baidu.mapapi.model.LatLng; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshGridView; import com.jiedu.project.lovefamily.R; import com.jiedu.project.lovefamily.activity.AddActivity; import com.jiedu.project.lovefamily.activity.LocationActivity; import com.jiedu.project.lovefamily.activity.MonitorRequestDialog; import com.jiedu.project.lovefamily.adapter.HomeGridViewAdapter; import com.jiedu.project.lovefamily.json.JsonHelp; import com.jiedu.project.lovefamily.message.MessageInfoUtil; import com.jiedu.project.lovefamily.mode.User; import com.jiedu.project.lovefamily.net.RequestHelp; import com.jiedu.project.lovefamily.popupwindow.HomePopupwindowUtil; import com.jiedu.project.lovefamily.sharedPreferences.SharedPreferencesUtil; import com.jiedu.project.lovefamily.stringutil.IntentString; import com.jiedu.project.lovefamily.utils.ShareUmengDialog; import com.umeng.socialize.ShareAction; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.media.UMImage; import java.util.ArrayList; import java.util.HashMap; /** * Created by Administrator on 2016/3/17. */ public class HomeFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener { View view; private PullToRefreshGridView gridView; private HomeGridViewAdapter adapter; private ArrayList<User> list = new ArrayList<User>(); public HomePopupwindowUtil util; private ImageView share; RequestHelp requestHelp; JsonHelp jsonHelp; int index; User user; private TextView del,bianji,safeEdit,myLocation; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_home, null); init(); return view; } private void init() { startGetMemberListThread(); gridView = (PullToRefreshGridView) view.findViewById(R.id.home_grid); share = (ImageView) view.findViewById(R.id.share); requestHelp = new RequestHelp(); jsonHelp = new JsonHelp(); util = new HomePopupwindowUtil(); adapter = new HomeGridViewAdapter(this.getActivity(), list); gridView.setAdapter(adapter); gridView.setOnItemClickListener(this); share.setOnClickListener(this); gridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) { startGetMemberListThread(); } @Override public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) { } }); myView=LayoutInflater.from(getActivity()).inflate(R.layout.personalpop_item,null); del= (TextView) myView.findViewById(R.id.tv_del); safeEdit= (TextView) myView.findViewById(R.id.tv_safe); myLocation= (TextView) myView.findViewById(R.id.tv_dingwei); bianji= (TextView) myView.findViewById(R.id.tv_bianji); del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); safeEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); myLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); bianji.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position < list.size() - 1) { util.showPopupwindow(gridView, this.getActivity(), handler, position, list.get(position)); //myPopwindow(); } else { startActivityForResult(new Intent(this.getActivity(), AddActivity.class), 2); } } private PopupWindow popupWindow; private View myView; private void myPopwindow(){ popupWindow=new PopupWindow(myView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true); popupWindow.setOutsideTouchable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.showAtLocation(view, Gravity.BOTTOM,0,0); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.arg1) { case MessageInfoUtil.DELETE: index=msg.arg2; new Thread(new Runnable() { @Override public void run() { String result= requestHelp.deleteMonitor(SharedPreferencesUtil.getInfo(getActivity(),"customerId"),list.get(index).getMonitoredId()); jsonHelp.dealDeleteMonitor(result,handler); } }).start(); break; case MessageInfoUtil.MEMBER: // Log.e("0011","查询数据得到结果刷新adapter"); gridView.onRefreshComplete(); initData(); adapter.notifyDataSetChanged(); break; case MessageInfoUtil.GET_LOCATION: // Log.e("0011","获取位置信息"); LatLng latLng = (LatLng) msg.obj; Intent intent = new Intent(getActivity(), LocationActivity.class); intent.putExtra("lat", latLng.latitude); intent.putExtra("lon", latLng.longitude); intent.putExtra(IntentString.NICK_NAME,list.get(msg.arg2).getUserName()); intent.putExtra(IntentString.PHONO_URL,list.get(msg.arg2).getPhotoUrl()); intent.putExtra("uploadTime",list.get(msg.arg2).uploadTime); getActivity().startActivity(intent); break; } switch (msg.what){ case MessageInfoUtil.DELETE_MONITOR: //刷新列表 startGetMemberListThread(); break; case MessageInfoUtil.DELETE_MONITOR_FAIL: Toast.makeText(getActivity(), msg.obj.toString(), Toast.LENGTH_SHORT).show(); break; case MessageInfoUtil.SHOW_TOAST: Toast.makeText(getActivity(),"该用户没有位置信息",Toast.LENGTH_SHORT).show(); break; case MessageInfoUtil.SHOW_DIAAOLG: Intent intent=new Intent(getActivity(), MonitorRequestDialog.class); intent.putExtra(IntentString.JSON,msg.obj.toString()); startActivity(intent); break; } } }; void initData() { // Log.e("0011","添加按钮"); user = new User(); user.setPhotoUrl("drawable://" + R.drawable.add); user.setUserName("添加成员"); user.setUserStatue(""); if(list.indexOf(user)<00){ list.add(user); } } private ShareUmengDialog shareUmengDialog; //为弹出窗口实现监听类 private View.OnClickListener itemsOnClick = new View.OnClickListener(){ public void onClick(View v) { shareUmengDialog.dismiss(); UMImage umImage=new UMImage(getActivity(), R.drawable.logo); switch (v.getId()) { case R.id.weixin: new ShareAction(getActivity()) .setPlatform(SHARE_MEDIA.WEIXIN) /*.setCallback(umShareListener)*/ .withText("您的家人邀请您安装爱家在线,快来看看吧") .withTitle("爱家在线") .withTargetUrl(RequestHelp.HTTP_HEAD + RequestHelp.HTTP_ACTION + "/wttp/toIntroduce.do") .withMedia(umImage) .share(); break; case R.id.weixinZong: new ShareAction(getActivity()) .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE) /*.setCallback(umShareListener)*/ .withText("您的家人邀请您安装爱家在线,快来看看吧") .withTitle("爱家在线") .withTargetUrl(RequestHelp.HTTP_HEAD + RequestHelp.HTTP_ACTION + "/wttp/toIntroduce.do") .withMedia(umImage) .share(); break; case R.id.qq: new ShareAction(getActivity()) .setPlatform(SHARE_MEDIA.QQ) /*.setCallback(umShareListener)*/ .withText("您的家人邀请您安装爱家在线,快来看看吧") .withTitle("爱家在线") .withTargetUrl(RequestHelp.HTTP_HEAD + RequestHelp.HTTP_ACTION + "/wttp/toIntroduce.do") .withMedia(umImage) .share(); break; case R.id.qqZong: new ShareAction(getActivity()) .setPlatform(SHARE_MEDIA.QZONE) /*.setCallback(umShareListener)*/ .withText("您的家人邀请您安装爱家在线,快来看看吧") .withTitle("爱家在线") .withTargetUrl(RequestHelp.HTTP_HEAD + RequestHelp.HTTP_ACTION + "/wttp/toIntroduce.do") .withMedia(umImage) .share(); break; } } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.share: //ShareUtil.share(getActivity()); shareUmengDialog=new ShareUmengDialog(getActivity(),itemsOnClick); //显示窗口 shareUmengDialog.showAtLocation(getActivity().findViewById(R.id.share), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置 break; } } public void startGetMemberListThread(){ new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); String result = requestHelp.getMember(SharedPreferencesUtil.getInfo(getActivity(), "customerId")); //Log.e("0011","查询成员"+result); jsonHelp.dealMemberList(result, getActivity(), handler, list); String resultMontior= requestHelp.requestPost(RequestHelp.GET_MONITOR_REQUEST+SharedPreferencesUtil.getInfo(getActivity(),"customerId"),new HashMap<String, Object>()); jsonHelp.dealGetMonitorRequestList(resultMontior, handler); Log.e("0011", "请求结果监控请求" + resultMontior); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
true
0ef05cd602d8db4bb5d527b0d121f72cd465f5f1
Java
SuperStarGamesNetwork/IronManMod
/forge/mcp/temp/src/minecraft/net/minecraft/entity/monster/EntityMob.java
UTF-8
4,857
1.796875
2
[ "BSD-3-Clause" ]
permissive
package net.minecraft.entity.monster; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentThorns; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; public abstract class EntityMob extends EntityCreature implements IMob { public EntityMob(World p_i1738_1_) { super(p_i1738_1_); this.field_70728_aV = 5; } public void func_70636_d() { this.func_82168_bl(); float var1 = this.func_70013_c(1.0F); if(var1 > 0.5F) { this.field_70708_bq += 2; } super.func_70636_d(); } public void func_70071_h_() { super.func_70071_h_(); if(!this.field_70170_p.field_72995_K && this.field_70170_p.field_73013_u == 0) { this.func_70106_y(); } } protected Entity func_70782_k() { EntityPlayer var1 = this.field_70170_p.func_72856_b(this, 16.0D); return var1 != null && this.func_70685_l(var1)?var1:null; } public boolean func_70097_a(DamageSource p_70097_1_, float p_70097_2_) { if(this.func_85032_ar()) { return false; } else if(super.func_70097_a(p_70097_1_, p_70097_2_)) { Entity var3 = p_70097_1_.func_76346_g(); if(this.field_70153_n != var3 && this.field_70154_o != var3) { if(var3 != this) { this.field_70789_a = var3; } return true; } else { return true; } } else { return false; } } public boolean func_70652_k(Entity p_70652_1_) { float var2 = (float)this.func_110148_a(SharedMonsterAttributes.field_111264_e).func_111126_e(); int var3 = 0; if(p_70652_1_ instanceof EntityLivingBase) { var2 += EnchantmentHelper.func_77512_a(this, (EntityLivingBase)p_70652_1_); var3 += EnchantmentHelper.func_77507_b(this, (EntityLivingBase)p_70652_1_); } boolean var4 = p_70652_1_.func_70097_a(DamageSource.func_76358_a(this), var2); if(var4) { if(var3 > 0) { p_70652_1_.func_70024_g((double)(-MathHelper.func_76126_a(this.field_70177_z * 3.1415927F / 180.0F) * (float)var3 * 0.5F), 0.1D, (double)(MathHelper.func_76134_b(this.field_70177_z * 3.1415927F / 180.0F) * (float)var3 * 0.5F)); this.field_70159_w *= 0.6D; this.field_70179_y *= 0.6D; } int var5 = EnchantmentHelper.func_90036_a(this); if(var5 > 0) { p_70652_1_.func_70015_d(var5 * 4); } if(p_70652_1_ instanceof EntityLivingBase) { EnchantmentThorns.func_92096_a(this, (EntityLivingBase)p_70652_1_, this.field_70146_Z); } } return var4; } protected void func_70785_a(Entity p_70785_1_, float p_70785_2_) { if(this.field_70724_aR <= 0 && p_70785_2_ < 2.0F && p_70785_1_.field_70121_D.field_72337_e > this.field_70121_D.field_72338_b && p_70785_1_.field_70121_D.field_72338_b < this.field_70121_D.field_72337_e) { this.field_70724_aR = 20; this.func_70652_k(p_70785_1_); } } public float func_70783_a(int p_70783_1_, int p_70783_2_, int p_70783_3_) { return 0.5F - this.field_70170_p.func_72801_o(p_70783_1_, p_70783_2_, p_70783_3_); } protected boolean func_70814_o() { int var1 = MathHelper.func_76128_c(this.field_70165_t); int var2 = MathHelper.func_76128_c(this.field_70121_D.field_72338_b); int var3 = MathHelper.func_76128_c(this.field_70161_v); if(this.field_70170_p.func_72972_b(EnumSkyBlock.Sky, var1, var2, var3) > this.field_70146_Z.nextInt(32)) { return false; } else { int var4 = this.field_70170_p.func_72957_l(var1, var2, var3); if(this.field_70170_p.func_72911_I()) { int var5 = this.field_70170_p.field_73008_k; this.field_70170_p.field_73008_k = 10; var4 = this.field_70170_p.func_72957_l(var1, var2, var3); this.field_70170_p.field_73008_k = var5; } return var4 <= this.field_70146_Z.nextInt(8); } } public boolean func_70601_bi() { return this.field_70170_p.field_73013_u > 0 && this.func_70814_o() && super.func_70601_bi(); } protected void func_110147_ax() { super.func_110147_ax(); this.func_110140_aT().func_111150_b(SharedMonsterAttributes.field_111264_e); } }
true
cdc50bb5f6c618ad7f6b3d7e08758264ab86f2ec
Java
lso0250/YMRB
/ymrb/src/main/java/com/yedam/ymrb/web/webControll.java
UTF-8
288
1.53125
2
[]
no_license
package com.yedam.ymrb.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class webControll { @RequestMapping("/reader/") public String reader(){ return "/popup/reader/index3"; } }
true
f3b5dd7e918eb95d884130b60b510dc9fe2e0786
Java
MartaMatysek/ChessStatisticsAndProfilesSPRING
/src/main/java/com/capgemini/chess/dataaccess/entities/MatchEntity.java
UTF-8
851
2.484375
2
[]
no_license
package com.capgemini.chess.dataaccess.entities; import com.capgemini.chess.dataaccess.enums.MatchResult; public class MatchEntity { private Long matchId; private Long firstPlayerId; private Long secondPlayerId; private MatchResult matchResult; public Long getMatchId() { return matchId; } public void setMatchId(Long matchId) { this.matchId = matchId; } public Long getFirstPlayerId() { return firstPlayerId; } public void setFirstPlayerId(Long firstPlayerId) { this.firstPlayerId = firstPlayerId; } public Long getSecondPlayerId() { return secondPlayerId; } public void setSecondPlayerId(Long secondPlayerId) { this.secondPlayerId = secondPlayerId; } public MatchResult getMatchResult() { return matchResult; } public void setMatchResult(MatchResult matchResult) { this.matchResult = matchResult; } }
true