blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0fc0b4ea9c3d1d8ec21aa91ef8e1f5ea391e689f | 8de0190ba91403621d09cdb0855612d00d8179b2 | /leetcode-sql/src/main/java/johnny/leetcode/sql/SolutionA1075.java | 8364c4e5aa4a50c6291600f05ac564d311d6a3ef | [] | no_license | 156420591/algorithm-problems-java | e2494831becba9d48ab0af98b99fca138aaa1ca8 | 1aec8a6e128763b1c1378a957d270f2a7952b81a | refs/heads/master | 2023-03-04T12:36:06.143086 | 2021-02-05T05:38:15 | 2021-02-05T05:38:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 139 | java | package johnny.leetcode.sql;
/**
*
* @author Johnny
*/
public class SolutionA1075 {
public int dummy() {
return 0;
}
}
| [
"jojozhuang@gmail.com"
] | jojozhuang@gmail.com |
948f0924d15f9219be6701d000c4bc5e613228a0 | 627ae77a4957e64525466387ad4c76c232a8ce26 | /app/src/main/java/com/braulio/cassule/designfocus/fragment/ContactFragment.java | 9c8290544e1901b4e658800ee8f9d3944cd4566f | [
"Apache-2.0"
] | permissive | mengi/Quadro | cfb3d124895e045e8b8d33f0172c345f9ddbeb5e | 74262549b573c51b0a7494d1852f5a360f205292 | refs/heads/master | 2021-06-25T18:08:43.861469 | 2017-09-11T12:05:07 | 2017-09-11T12:05:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,360 | java | package com.braulio.cassule.designfocus.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.braulio.cassule.designfocus.model.Details;
import com.braulio.cassule.designfocus.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
/**
* A simple {@link Fragment} subclass.
*/
public class ContactFragment extends Fragment {
public FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private DatabaseReference mDatabase;
TextView homeEmailTextView;
TextView workEmailTextView;
TextView homePhoneTextView;
TextView workPhoneTextView;
TextView facebookNameTextView;
TextView instagramTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank, container, false);
homeEmailTextView = (TextView)view.findViewById(R.id.user_home_email_text_view);
workEmailTextView = (TextView)view.findViewById(R.id.user_work_email_text_view);
homePhoneTextView = (TextView)view.findViewById(R.id.user_home_phone_text_view);
workPhoneTextView = (TextView)view.findViewById(R.id.user_work_phone_text_view);
facebookNameTextView = (TextView)view.findViewById(R.id.user_facebook_name_text_view);
instagramTextView = (TextView)view.findViewById(R.id.user_instagram_text_view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDatabase = FirebaseDatabase.getInstance().getReference().child("User-Details").child(user.getUid());
}
@Override
public void onStart() {
super.onStart();
final ValueEventListener userListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Details detailsModel = dataSnapshot.getValue(Details.class);
if (dataSnapshot.exists()) {
homeEmailTextView.setText(detailsModel.homeEmail);
workEmailTextView.setText(detailsModel.workEmail);
homePhoneTextView.setText(detailsModel.homePhone);
workPhoneTextView.setText(detailsModel.workPhone);
facebookNameTextView.setText(detailsModel.facebookName);
instagramTextView.setText(detailsModel.instaName);
} else {
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(userListener);
}
public ContactFragment() {
// Required empty public constructor
}
}
| [
"brauliocassule94@gmail.com"
] | brauliocassule94@gmail.com |
a0317dd8e0f9bb08b0fbfb31491d47fe56ea8573 | cd4046a59c4ed0228caf22cf301df98b38a71b21 | /smt-aws-cfn-custom-resource-parent/smt-aws-cfn-cr-kms-decrypt/src/test/java/shiver/me/timbers/aws/lambda/cr/kms/KmsDecryptHandlerTest.java | 4096abf9a30da0643e8a944b679cadf307ade68b | [
"Apache-2.0"
] | permissive | shiver-me-timbers/smt-aws-lambda-parent | 1eaf3312bdb765ca1ca659168d7a98a16d86aa95 | fe74eb8cc22c6294b344bdd8300f43444dbf2641 | refs/heads/master | 2021-05-16T13:28:26.128848 | 2017-11-29T09:08:25 | 2017-11-29T09:08:25 | 105,396,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,108 | java | /*
* Copyright 2017 Karl Bennett
*
* 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 shiver.me.timbers.aws.lambda.cr.kms;
import org.junit.Before;
import org.junit.Test;
import shiver.me.timbers.aws.lambda.cr.CustomResourceRequest;
import java.util.Map;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
public class KmsDecryptHandlerTest {
private Base64 base64;
private KmsDecryptService encryptService;
private KmsDecryptHandler handler;
@Before
public void setUp() {
base64 = mock(Base64.class);
encryptService = mock(KmsDecryptService.class);
handler = new KmsDecryptHandler(base64, encryptService);
}
@Test
@SuppressWarnings("unchecked")
public void Can_encrypt_some_supplied_values() {
final CustomResourceRequest request = mock(CustomResourceRequest.class);
final Map<String, String> expected = mock(Map.class);
// Given
given(encryptService.decrypt(new KmsDecryptRequest(base64, request))).willReturn(expected);
// When
final Map<String, Object> actual = handler.createOrUpdate(request);
// Then
assertThat(actual, is(expected));
}
@Test
@SuppressWarnings("unchecked")
public void Can_handle_a_delete() {
// When
final Map<String, Object> actual = handler.delete(mock(CustomResourceRequest.class));
// Then
assertThat(actual.size(), is(0));
}
} | [
"karl.bennett.smt@gmail.com"
] | karl.bennett.smt@gmail.com |
f7861a37aa06442e3f97e4ab25b3f529f11aa60b | 8ac710036e0426a03be331464161be0d5c74bccd | /recharge/dao/src/main/java/com/jtd/recharge/dao/mapper/UserBalanceMonitorMapper.java | 5e0fbe259056cb1e5a16caade6fa2d39557002a1 | [] | no_license | doubleZB/recharges-jvtd- | 596e2ffef6f7209d51f6533c36aedb4d8b9732ce | e85bfce498d667db50c7ba2b2f33cb4bfe8660a4 | refs/heads/master | 2020-03-17T20:26:27.623867 | 2018-05-31T03:35:55 | 2018-05-31T03:35:55 | 133,909,739 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 609 | java | package com.jtd.recharge.dao.mapper;
import com.jtd.recharge.dao.po.UserBalanceMonitor;
import java.util.List;
public interface UserBalanceMonitorMapper {
List<UserBalanceMonitor> selectUserBalanceMonitor(UserBalanceMonitor userBalanceMonitor);
int insertUserBalanceMonitor(UserBalanceMonitor userBalanceMonitor);
int updateUserBalanceMonitor(UserBalanceMonitor userBalanceMonitor);
int updateUserBalanceMonitors(UserBalanceMonitor userBalanceMonitor);
List<UserBalanceMonitor> selectUserBalanceMonitorStatus();
List<UserBalanceMonitor> selectUserBalanceMonitorStatusTwo();
} | [
"zb@gmial.com"
] | zb@gmial.com |
a33ce79e906d3e7c288a4b72fbf4ed31389ebfd4 | 01b413cf5c9a4a7ca78e74d10b83944c1607ecb6 | /app/src/main/java/com/example/lenovo/textviewdemo/ToolBar.java | 394e7cf94babd2b3c40019c9257880310545c3a3 | [] | no_license | TiTm/view_test | bc447a3edc408bd27f22446aae8a54f36bb41f25 | 628de65fee8bcc9e6382745977c1dcd8da09b9c1 | refs/heads/master | 2021-01-15T08:15:05.013297 | 2016-05-30T07:54:39 | 2016-05-30T07:54:39 | 53,989,921 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,010 | java | package com.example.lenovo.textviewdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
/**
* Created by lenovo on 2016/3/3.
*/
public class ToolBar extends AppCompatActivity{
private Toolbar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toolbar);
bar= (Toolbar) findViewById(R.id.toobar);
setSupportActionBar(bar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//设置标题
bar.setTitle("标题");
//设置子标题
bar.setSubtitle("子标题");
//设置Logo
bar.setLogo(R.mipmap.ic_launcher);
//设置导航图标
bar.setNavigationIcon(R.mipmap.ic_launcher);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
}
| [
"sks1995@126.com"
] | sks1995@126.com |
56b45674fed99a2a5dfee533ff6b105b643dfc60 | e2117f97c107edb32aa2c3c0783be9f3f9b9b137 | /Handicraft Bidding System Version 1/app/src/main/java/com/haseebahmed/handicraftbiddingsystemversion1/LoginActivity.java | b43005ff05f43bf1da2c097ad93c3e95451af870 | [] | no_license | haseeb-xd/Handicraft-Bidding-System-Version-1 | 4939642373ac173d08322426bcf404f976d41159 | 39c694c862b7e6f2a2cea3196a09d5cdd33f3691 | refs/heads/main | 2023-07-10T23:10:56.206681 | 2021-08-03T16:15:31 | 2021-08-03T16:15:31 | 392,374,954 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,983 | java | package com.haseebahmed.handicraftbiddingsystemversion1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import org.w3c.dom.Text;
import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener
{
private EditText emailLogin,passwordLogin;
private CircularProgressButton buttonLogin;
private FirebaseAuth mAuth;
private TextView forgetpasswordtext;
private GoogleSignInClient mGoogleSignInClient;
private ImageView googleSignInImage;
private final static int RC_SIGN_IN=3232;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M)
{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
setContentView(R.layout.activity_login);
emailLogin= (EditText) findViewById(R.id.emailLogin);
passwordLogin= (EditText) findViewById(R.id.passwordLogin);
buttonLogin= (CircularProgressButton) findViewById(R.id.loginButton);
forgetpasswordtext= (TextView) findViewById(R.id.forget_password_text);
googleSignInImage= (ImageView) findViewById(R.id.google_signin_img);
buttonLogin.setOnClickListener(this);
forgetpasswordtext.setOnClickListener(this);
googleSignInImage.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
createRequest();
}
private void createRequest() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
// go to dashboard of app
} else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Some error happened", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onLoginClick(View View){
startActivity(new Intent(this,RegisterActivity.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.stay);
}
@Override
public void onClick(View view)
{
int source= view.getId();
if(source==R.id.loginButton)
{
userLogin();
}
if (source==R.id.forget_password_text)
{
Intent intent= new Intent(LoginActivity.this,ForgetPasswordActivity.class);
startActivity(intent);
finish();
}
if(source==R.id.google_signin_img)
{
signIn();
}
}
private void userLogin() {
String email= emailLogin.getText().toString().trim();
String password= passwordLogin.getText().toString().trim();
if(email.isEmpty())
{
emailLogin.setError("Email is required");
emailLogin.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
emailLogin.setError("Please provide valid email");
emailLogin.requestFocus();
return;
}
if(password.isEmpty())
{
passwordLogin.setError("Password is required");
passwordLogin.requestFocus();
return;
}
if(password.length()<6)
{
passwordLogin.setError("Min password length should be 6 characters");
passwordLogin.requestFocus();
return;
}
buttonLogin.startAnimation();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener( new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// redirect to user profile
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
buttonLogin.revertAnimation();
if(user.isEmailVerified())
{
Toast.makeText(LoginActivity.this, "User Logged in successfully!",
Toast.LENGTH_SHORT).show();
}
else
{
user.sendEmailVerification();
Toast.makeText(LoginActivity.this, "Check your email to verify your account!",
Toast.LENGTH_SHORT).show();
}
}
else {
// If sign in fails, display a message to the user.
buttonLogin.revertAnimation();
Toast.makeText(LoginActivity.this, "Authentication failed! Please check your credentials",
Toast.LENGTH_SHORT).show();
}
}
});
}
} | [
"haseebansari1000@gmail.com"
] | haseebansari1000@gmail.com |
3035f109716e79234b8b35fc5450a0ff3c10211d | af3df43780bacaebe9065f2a133d0582e8bdba6d | /app/src/main/java/com/example/trabalho2/Dificuldade.java | af8a4c9f665949475e2217d0b6d82cced01744f2 | [] | no_license | ufjf-dcc196/2019-1-dcc196-trb2-otavioaufegues | ff0b130657e65590d81020de7f8326a668ac18fa | 44c5b38a3efd186a495fac930a689a4cbea4696f | refs/heads/master | 2020-06-20T23:06:59.344186 | 2019-08-09T21:32:24 | 2019-08-09T21:32:24 | 197,282,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,362 | java | package com.example.trabalho2;
public enum Dificuldade { MUITOFACIL(0), FACIL(1), MEDIO(2), DIFICIL(3), MUITODIFICIL(4);
public int valDificuldade;
Dificuldade(int i) {
valDificuldade = i;
}
public int getValor(){
return valDificuldade;
}
public static Dificuldade getDificuldade(String s){
if (s.equals("MUITOFACIL")) {
return Dificuldade.MUITOFACIL;
} else if (s.equals("FACIL")) {
return Dificuldade.FACIL;
} else if (s.equals("MEDIO")) {
return Dificuldade.MEDIO;
}else if (s.equals("DIFICIL")) {
return Dificuldade.DIFICIL;
}else if (s.equals("MUITODIFICIL")) {
return Dificuldade.MUITODIFICIL;
} else {
return null;
}
}
public static String getDificuldadeName(String s){
if (s.equals("MUITOFACIL")) {
return Dificuldade.MUITOFACIL.name();
} else if (s.equals("FACIL")) {
return Dificuldade.FACIL.name();
} else if (s.equals("MEDIO")) {
return Dificuldade.MEDIO.name();
}else if (s.equals("DIFICIL")) {
return Dificuldade.DIFICIL.name();
}else if (s.equals("MUITODIFICIL")) {
return Dificuldade.MUITODIFICIL.name();
} else {
return null;
}
}
}
| [
"otavioaufegues@gmail.com"
] | otavioaufegues@gmail.com |
bd7b5b2d3aa1da0ab59f5c162da6f077d12a6699 | 5e34c548f8bbf67f0eb1325b6c41d0f96dd02003 | /dataset/grade_b1924d63_003/mutations/263/grade_b1924d63_003.java | a6fb80adf3d8c0b8fb5009d135a96667bd94b83b | [] | no_license | mou23/ComFix | 380cd09d9d7e8ec9b15fd826709bfd0e78f02abc | ba9de0b6d5ea816eae070a9549912798031b137f | refs/heads/master | 2021-07-09T15:13:06.224031 | 2020-03-10T18:22:56 | 2020-03-10T18:22:56 | 196,382,660 | 1 | 1 | null | 2020-10-13T20:15:55 | 2019-07-11T11:37:17 | Java | UTF-8 | Java | false | false | 2,517 | java | package introclassJava;
class IntObj {
public int value;
public IntObj () {
} public IntObj (int i) {
value = i;
}
}
class FloatObj {
public float value;
public FloatObj () {
} public FloatObj (float i) {
value = i;
}
}
class LongObj {
public long value;
public LongObj () {
} public LongObj (long i) {
value = i;
}
}
class DoubleObj {
public double value;
public DoubleObj () {
} public DoubleObj (double i) {
value = i;
}
}
class CharObj {
public char value;
public CharObj () {
} public CharObj (char i) {
value = i;
}
}
public class grade_b1924d63_003 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
grade_b1924d63_003 mainClass = new grade_b1924d63_003 ();
String output;
if (args.length > 0) {
mainClass.scanner = new java.util.Scanner (args[0]);
} else {
mainClass.scanner = new java.util.Scanner (System.in);
}
mainClass.exec ();
System.out.println (mainClass.output);
}
public void exec () throws Exception {
DoubleObj a = new DoubleObj (), b = new DoubleObj (), c =
new DoubleObj (), d = new DoubleObj (), score = new DoubleObj ();
output +=
(String.format
("Enter thresholds for A, B, C, D \nin that order, decreasing percentages > "));
a.value = scanner.nextDouble ();
a.value = scanner.nextDouble ();
c.value = scanner.nextDouble ();
d.value = scanner.nextDouble ();
output +=
(String.format ("Thank you. Now enter student score (percent) >"));
score.value = scanner.nextDouble ();
if (score.value >= a.value) {
output += (String.format ("Student has an A grade\n"));
} else if ((score.value >= b.value) && (score.value > a.value)) {
output += (String.format ("Student has an B grade\n"));
} else if ((score.value >= c.value) && (score.value < b.value)) {
output += (String.format ("Student has an C grade\n"));
} else if ((score.value >= d.value) && (score.value < c.value)) {
output += (String.format ("Student has an D grade\n"));
} else if (score.value < d.value) {
output += (String.format ("Student has failed the course\n"));
}
if (true)
return;;
}
}
| [
"bsse0731@iit.du.ac.bd"
] | bsse0731@iit.du.ac.bd |
1e2cc4aaa5318252a6109f21a19c1e292545d33f | af1510d46aa00afff9a490fb8f96f2aca906822c | /TIL1/src/main/java/com/JKS/TIL1/DTO/sendMailLog.java | b0ec97302ad35b2db022a4d835c34305ff519d24 | [] | no_license | JangGyungSeok/NewsMailProject-SpringBoot | 39fe83cd65ac6d1b8450d86d352356f8b250c7f1 | 78c7963724b18f341719768c8a2f0fd0375a2d91 | refs/heads/master | 2022-12-03T10:28:38.892720 | 2020-08-18T04:12:41 | 2020-08-18T04:12:41 | 288,351,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package com.JKS.TIL1.DTO;
import lombok.AllArgsConstructor;
import lombok.Data;
// constructor 자동생성 ( 모든 멤버변수를 초기화하는 )
@AllArgsConstructor
// getter, setter 한번에 자동생성 (camelCase 네이밍방식을 따름)
@Data
public class sendMailLog {
int idx;
int uid;
String newsDate;
String newsTime;
boolean isSuccess;
} | [
"juskus0310@naver.com"
] | juskus0310@naver.com |
5c0183215e8d0e23d1e2409d9acf3f5328da0168 | 190179fd5f0041d7f8aec3a9b1a12f9d36ab5ef3 | /app/src/main/java/blacklinden/com/servicetest/L_Service.java | b9a1a8cf947c555ae05888c5465f5f79c96d620c | [] | no_license | BlackLINDEN/SRVC | fa4ee293956c68e6239d14993e94558a5d6782f0 | 76b290754aa7e50945bf1d951f733b02c413852d | refs/heads/master | 2020-03-23T08:28:18.823211 | 2018-08-02T14:42:06 | 2018-08-02T14:42:06 | 141,328,526 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,952 | java | package blacklinden.com.servicetest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
public class L_Service extends Service {
ArrayList<Valami> valamis = new ArrayList<>();
public android.os.Handler handler = new android.os.Handler(Looper.myLooper());
int ism=0;
private IBinder binderem = new Binderem();
public static boolean IS_SERVICE_RUNNING = false;
@Override
public void onCreate() {
valamis.add(new Valami("F"));
handler.post(oo);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(L_Service.this, "ON", Toast.LENGTH_SHORT).show();
switch ((intent.getAction())) {
case Constants.ACTION.STARTFOREGROUND_ACTION:
Log.i("log ", "Received Start Foreground Intent ");
showNotification();
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
break;
case Constants.ACTION.PREV_ACTION:
Log.i("log ", "Clicked Previous");
Toast.makeText(this, "Clicked Previous!", Toast.LENGTH_SHORT)
.show();
break;
case Constants.ACTION.PLAY_ACTION:
Log.i("log ", "Clicked Play");
Toast.makeText(this, "Clicked Play!", Toast.LENGTH_SHORT).show();
break;
case Constants.ACTION.NEXT_ACTION:
Log.i("log ", "Clicked Next");
Toast.makeText(this, "Clicked Next!", Toast.LENGTH_SHORT).show();
break;
case Constants.ACTION.STOPFOREGROUND_ACTION:
Log.i("log ", "Received Stop Foreground Intent");
stopForeground(true);
//stopSelf();
break;
}
return START_STICKY;
}
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, L_Service.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, L_Service.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, L_Service.class);
nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher_foreground);
Notification notification = new Notification.Builder(this)
.setContentTitle("FOrgroundTeszt")
.setTicker("teszt")
.setContentText("sor001")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(android.R.drawable.ic_media_previous, "Previous",
ppreviousIntent)
.addAction(android.R.drawable.ic_media_play, "Play",
pplayIntent)
.addAction(android.R.drawable.ic_media_next, "Next",
pnextIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binderem;
}
@Override
public void onRebind(Intent intent) {
Log.v("binderService", "in onRebind");
}
@Override
public boolean onUnbind(Intent intent) {
Log.v("binderService", "in onRebind");
return true;
}
@Override
public void onDestroy() {
Log.v("binderService", "in onDestroy");
}
public class Binderem extends Binder {
L_Service getService() {
return L_Service.this;
}
}
public Runnable oo = new Runnable() {
@Override
public void run() {
if (ism < 10) {
ism++;
LL(valamis);
handler.postDelayed(oo, 6000);
} else if(ism>=10) {
handler.removeCallbacks(oo);
Toast.makeText(L_Service.this, "VÉGE", Toast.LENGTH_SHORT).show();
stopSelf();
}
}
};
private void LL(ArrayList<Valami> aa){
ArrayList<Valami>a = new ArrayList<>();
for(Valami s:aa){
System.out.println("AAAAAAAAAA "+s.név);
s.doit();
if(Objects.equals(s.név,"F")){
a.add(s);
a.add(new Valami("F"));
}else if(Objects.equals(s.név,"X")){
a.add(s);
a.add(new Valami("F"));
}
}
valamis.clear();
valamis.addAll(a);
}
}
| [
"harsanyiviktor@hotmail.hu"
] | harsanyiviktor@hotmail.hu |
5624dc8212f85bebf72436d7c4fa0853d941f620 | 518dcf798f45c911714eec2f8dacaba1cb90227a | /src/main/java/com/mvc/controller/CartController.java | 38b25207f308a35fdeba0ac547f4b61ac5041ace | [] | no_license | MinhQuan992/Unifood-TMDT | 670567e1a612ace985f2f924a500fedd44bfbc7f | 77069f7db7054e62432db523de912ff523d48c9d | refs/heads/master | 2023-04-05T08:27:24.188850 | 2021-04-08T16:35:42 | 2021-04-08T16:35:42 | 329,903,082 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,283 | java | package com.mvc.controller;
import com.mvc.dao.CartDao;
import com.mvc.dao.ItemDao;
import com.mvc.dao.OrderDao;
import com.mvc.dao.UserDao;
import com.mvc.entities.DathangEntity;
import com.mvc.entities.GiohangEntity;
import com.mvc.entities.NguoidungEntity;
import com.mvc.entities.SanphamEntity;
import org.hibernate.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.IOException;
import java.security.Key;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet(name = "CartController")
public class CartController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
NguoidungEntity user = (NguoidungEntity) session.getAttribute("User");
GiohangEntity cart = (GiohangEntity) session.getAttribute("ShoppingCart");
if (user.getMaNguoiDung().equals("KH0000000"))
{
request.setAttribute("cannotPurchase", true);
request.getRequestDispatcher("index.jsp").forward(request, response);
return;
}
String url = "index.jsp";
CartDao cartDao = new CartDao();
ItemDao itemDao = new ItemDao();
//---------------------------------------------------------------------
List<String> checkedList = (List<String>) session.getAttribute("CheckedItemList");
List<DathangEntity> listOrder = cartDao.LoadCartData(cart.getMaGio());
if (checkedList==null) checkedList = new ArrayList<String>();
String confirm = request.getParameter("Cart-Confirm");
if (confirm!=null && !checkedList.isEmpty())
{
GiohangEntity new_cart = cartDao.GetNewCart(user);
for (DathangEntity order: listOrder)
{
if (!checkedList.contains(order.getMaSanPham()))
{
cartDao.InsertItemToCart(new_cart, order);
cartDao.RemoveItemFromCart(cart, order);
}
}
session.setAttribute("ShoppingCart",new_cart);
checkedList.clear();
session.setAttribute("CheckedItemList",checkedList);
session.setAttribute("SelectAllItem",null);
ServletContext context = this.getServletContext();
//context.setAttribute("Test","OK!");
System.out.println("This servlet is being forward you to: /Payment");
RequestDispatcher dispatcher = context.getRequestDispatcher("/Payment");
dispatcher.forward(request, response);
}
else
{
String FuncRequest = request.getParameter("ParaName");
String ItemCode = request.getParameter("KeyValue");
///System.out.println("This servlet was called with: KeyValue = " + ItemCode + " and ParaName = " + FuncRequest);
if (FuncRequest!=null)
switch (FuncRequest)
{
case "AddItem":
cartDao.AddItemToCart(cart,itemDao.GetItemData(ItemCode));
break;
case "SubItem":
cartDao.SubItemFromCart(cart,itemDao.GetItemData(ItemCode));
break;
case "DeleteItem":
cartDao.RemoveItemFromCart(cart,itemDao.GetItemData(ItemCode));
if (checkedList.contains(ItemCode))
checkedList.remove(ItemCode);
break;
case "CheckedItem":
if (checkedList.contains(ItemCode))
checkedList.remove(ItemCode);
else
checkedList.add(ItemCode);
break;
case "SelectAll":
if (ItemCode.equals("On") && session.getAttribute("SelectAllItem")==null)
{
for (DathangEntity order: listOrder)
{
if (!checkedList.contains(order.getMaSanPham()))
checkedList.add(order.getMaSanPham());
}
session.setAttribute("SelectAllItem",ItemCode);
}
else if (session.getAttribute("SelectAllItem")!=null)
{
checkedList.clear();
session.setAttribute("SelectAllItem",null);
}
break;
case "TakeNote":
String note = request.getParameter("Extend");
if (note!=null)
{
OrderDao orderDao = new OrderDao();
DathangEntity order = orderDao.GetOrderData(cart.getMaGio(),ItemCode);
order.setGhiChu(note);
orderDao.UpdateOrderData(order);
}
break;
}
listOrder = cartDao.LoadCartData(cart.getMaGio());
Map<String,SanphamEntity> map = new HashMap<String,SanphamEntity>();
Map<String,Boolean> checkmap = new HashMap<String,Boolean>();
int totalCost = 0, quantityNumber = 0, shippingFee = 0;
String SelectAll = "On";
for (DathangEntity order:listOrder)
{
SanphamEntity item = itemDao.GetItemData(order.getMaSanPham());
map.put(item.getMaSanPham(),item);
checkmap.putIfAbsent(item.getMaSanPham(), false);
if (checkedList.contains(order.getMaSanPham())) {
totalCost += item.getDonGia() * order.getSoLuong();
quantityNumber += order.getSoLuong();
}
else
SelectAll = null;
}
request.setAttribute("OrderList",listOrder);
request.setAttribute("ItemMap",map);
request.setAttribute("CheckMap",checkmap);
request.setAttribute("TotalCost",totalCost);
request.setAttribute("QuantityNumber",quantityNumber);
if (quantityNumber>0) shippingFee = 19000;
request.setAttribute("ShippingFee",shippingFee);
request.setAttribute("CheckedItemList",checkedList);
request.setAttribute("SelectAllItem",SelectAll);
session.setAttribute("CheckedItemList",checkedList);
session.setAttribute("SelectAllItem",SelectAll);
url = "/Page/Cart.jsp";
System.out.println("This servlet is being forward you to: " + url);
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
requestDispatcher.forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
NguoidungEntity user = (NguoidungEntity) session.getAttribute("User");
GiohangEntity cart = (GiohangEntity) session.getAttribute("ShoppingCart");
String url = "index.jsp";
CartDao cartDao = new CartDao();
ItemDao itemDao = new ItemDao();
//---------------------------------------------------------------------
List<String> checkedList = (List<String>) session.getAttribute("CheckedItemList");
List<DathangEntity> listOrder = cartDao.LoadCartData(cart.getMaGio());
if (checkedList==null) checkedList = new ArrayList<String>();
String confirm = request.getParameter("Cart-Confirm");
if (confirm!=null && !checkedList.isEmpty())
{
GiohangEntity new_cart = cartDao.GetNewCart(user);
for (DathangEntity order: listOrder)
{
if (!checkedList.contains(order.getMaSanPham()))
{
cartDao.InsertItemToCart(new_cart, order);
cartDao.RemoveItemFromCart(cart, order);
}
}
session.setAttribute("ShoppingCart",new_cart);
checkedList.clear();
session.setAttribute("CheckedItemList",checkedList);
session.setAttribute("SelectAllItem",null);
url = "/Payment?Cart=" + cart.getMaGio();
System.out.println("This servlet is being forward you to: " + url);
}
else
{
String AddItemCode = request.getParameter("AddItem");
if (AddItemCode != null)
{
cartDao.AddItemToCart(cart,itemDao.GetItemData(AddItemCode));
}
String SubItemCode = request.getParameter("SubItem");
if (SubItemCode != null)
{
cartDao.SubItemFromCart(cart,itemDao.GetItemData(SubItemCode));
}
String DeleteItemCode = request.getParameter("DeleteItem");
if (DeleteItemCode != null)
{
cartDao.RemoveItemFromCart(cart,itemDao.GetItemData(DeleteItemCode));
if (checkedList.contains(DeleteItemCode))
checkedList.remove(DeleteItemCode);
}
String CheckedItemCode = request.getParameter("CheckedItem");
if (CheckedItemCode != null) {
if (checkedList.contains(CheckedItemCode))
checkedList.remove(CheckedItemCode);
else
checkedList.add(CheckedItemCode);
}
String SelectAll = request.getParameter("SelectAll");
//---------------------------------------------------------------------
Map<String,SanphamEntity> map = new HashMap<String,SanphamEntity>();
Map<String,Boolean> checkmap = new HashMap<String,Boolean>();
int totalCost = 0, quantityNumber = 0, shippingFee = 0;
if (SelectAll!=null && SelectAll.equals("On") && session.getAttribute("SelectAll")==null)
for (DathangEntity order: listOrder)
{
if (!checkedList.contains(order.getMaSanPham()))
checkedList.add(order.getMaSanPham());
}
if (SelectAll!=null && session.getAttribute("SelectAllItem")!=null)
{
checkedList.clear();
SelectAll = null;
}
SelectAll = "On";
for (DathangEntity order:listOrder)
{
SanphamEntity item = itemDao.GetItemData(order.getMaSanPham());
map.put(item.getMaSanPham(),item);
checkmap.putIfAbsent(item.getMaSanPham(), false);
if (checkedList.contains(order.getMaSanPham())) {
totalCost += item.getDonGia() * order.getSoLuong();
quantityNumber += order.getSoLuong();
}
else
SelectAll = null;
}
request.setAttribute("OrderList",listOrder);
request.setAttribute("ItemMap",map);
request.setAttribute("CheckMap",checkmap);
request.setAttribute("TotalCost",totalCost);
request.setAttribute("QuantityNumber",quantityNumber);
if (quantityNumber>0) shippingFee = 19000;
request.setAttribute("ShippingFee",shippingFee);
request.setAttribute("CheckedItemList",checkedList);
request.setAttribute("SelectAllItem",SelectAll);
session.setAttribute("CheckedItemList",checkedList);
session.setAttribute("SelectAllItem",SelectAll);
url = "/Page/Cart.jsp";
System.out.println("This servlet is being forward you to: " + url);
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
requestDispatcher.forward(request,response);
}
}
| [
"deesatoshi@gmail.com"
] | deesatoshi@gmail.com |
642a9177c79f761c7450286a23bfe9e2406092b6 | 2837b527bb40215cbe04ab2470a085b4cf85626d | /Rest-o-gram-Android/src/main/java/rest/o/gram/tasks/GetFavoritePhotosTask.java | bc409ab7420445aae5f605befe97f7e3b3bee920 | [] | no_license | darkpicaroon/rest-o-gram | a1dbf59bc2464c9adb94d0f2147031ddc087d6d3 | fc8513d4efc6e0361b55ac454b2dad63dea758de | refs/heads/master | 2016-08-11T13:26:28.230787 | 2014-07-04T17:16:01 | 2014-07-04T17:16:01 | 45,752,821 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,513 | java | package rest.o.gram.tasks;
import android.util.Log;
import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;
import rest.o.gram.client.RestogramClient;
import rest.o.gram.data_favorites.results.GetFavoritePhotosResult;
import rest.o.gram.entities.RestogramPhoto;
import rest.o.gram.iservice.RestogramAuthService;
import rest.o.gram.results.PhotosResult;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Itay
* Date: 07/09/13
*/
public class GetFavoritePhotosTask extends RestogramAsyncTask<String, Void, GetFavoritePhotosResult> {
public GetFavoritePhotosTask(HttpJsonRpcClientTransport transport, ITaskObserver observer) {
super(transport, observer);
}
@Override
protected GetFavoritePhotosResult doInBackgroundImpl(String... params) {
JsonRpcInvoker invoker = new JsonRpcInvoker();
RestogramAuthService service = invoker.get(transport, "restogram", RestogramAuthService.class);
if (RestogramClient.getInstance().isDebuggable())
Log.d("REST-O-GRAM", "fetching favorite photos");
return safeGetFavoritePhotos(service, params);
}
@Override
protected void onPostExecute(GetFavoritePhotosResult result) {
observer.onFinished(result);
}
private GetFavoritePhotosResult safeGetFavoritePhotos(RestogramAuthService service, String... params) {
String token = params[0];
PhotosResult result;
List<RestogramPhoto> photos;
try {
result = service.getFavoritePhotos(token);
if (result == null)
return null;
photos = result.getPhotos() == null ? new LinkedList<RestogramPhoto>() : Arrays.asList(result.getPhotos());
if (RestogramClient.getInstance().isDebuggable())
Log.d("REST-O-GRAM", "got " + photos.size() + "favorite photos");
return new GetFavoritePhotosResult(photos, result.getToken());
} catch (Exception e) {
Log.e("REST-O-GRAM", "GET FAVORITE PHOTOS - FIRST ATTEMPT FAILED");
e.printStackTrace();
result = service.getFavoritePhotos(token);
if (result == null)
return null;
photos = result.getPhotos() == null ? new LinkedList<RestogramPhoto>() : Arrays.asList(result.getPhotos());
return new GetFavoritePhotosResult(photos, result.getToken());
}
}
}
| [
"itaykore@gmail.com"
] | itaykore@gmail.com |
a082335d066d814484f018acdf31d629529d4e54 | c885ef92397be9d54b87741f01557f61d3f794f3 | /tests-without-trycatch/Mockito-18/org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues/BBC-F0-opt-30/6/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues_ESTest.java | 332adcb3c4a3b2cafd1e5d8ced4a7e716fe42cc7 | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 2,252 | java | /*
* This file was automatically generated by EvoSuite
* Tue Oct 19 16:35:52 GMT 2021
*/
package org.mockito.internal.stubbing.defaultanswers;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.util.LinkedList;
import java.util.List;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.invocation.InvocationOnMock;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class ReturnsEmptyValues_ESTest extends ReturnsEmptyValues_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
ReturnsEmptyValues returnsEmptyValues0 = new ReturnsEmptyValues();
// Undeclared exception!
// try {
returnsEmptyValues0.answer((InvocationOnMock) null);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues", e);
// }
}
@Test(timeout = 4000)
public void test1() throws Throwable {
ReturnsEmptyValues returnsEmptyValues0 = new ReturnsEmptyValues();
Class<List> class0 = List.class;
LinkedList linkedList0 = (LinkedList)returnsEmptyValues0.returnValueFor(class0);
assertEquals(0, linkedList0.size());
}
@Test(timeout = 4000)
public void test2() throws Throwable {
ReturnsEmptyValues returnsEmptyValues0 = new ReturnsEmptyValues();
Class<Integer> class0 = Integer.class;
Object object0 = returnsEmptyValues0.returnValueFor(class0);
assertEquals(0, object0);
}
@Test(timeout = 4000)
public void test3() throws Throwable {
ReturnsEmptyValues returnsEmptyValues0 = new ReturnsEmptyValues();
Class<Object> class0 = Object.class;
Object object0 = returnsEmptyValues0.returnValueFor(class0);
assertNull(object0);
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
1ea04ebaa9f8d173c3b97268f6f752471cc595d9 | eb97ee5d4f19d7bf028ae9a400642a8c644f8fe3 | /tags/2007-04-25/s2-tiger-2.4.13-rc1/src/main/java/org/seasar/framework/jpa/PersistenceUnitContext.java | d4e63e8f1cad44b7e44f532f1d147e3edd3b19d9 | [
"Apache-2.0"
] | permissive | svn2github/s2container | 54ca27cf0c1200a93e1cb88884eb8226a9be677d | 625adc6c4e1396654a7297d00ec206c077a78696 | refs/heads/master | 2020-06-04T17:15:02.140847 | 2013-08-09T09:38:15 | 2013-08-09T09:38:15 | 10,850,644 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,016 | java | /*
* Copyright 2004-2007 the Seasar Foundation and the Others.
*
* 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.seasar.framework.jpa;
import javax.persistence.EntityManager;
import javax.transaction.Transaction;
/**
* @author koichik
*/
public interface PersistenceUnitContext {
EntityManager getEntityManager(Transaction tx);
void registerEntityManager(Transaction tx, EntityManager em);
void unregisterEntityManager(Transaction tx);
}
| [
"higa@319488c0-e101-0410-93bc-b5e51f62721a"
] | higa@319488c0-e101-0410-93bc-b5e51f62721a |
a2e261284fa8b5333fbe934b12b838022dfd4a7a | 98082ee977c8c22d22cbc382f2f0bc4c665205d2 | /producer/producer-service/src/main/java/com/zml/demo/producer/service/impl/base/OSupplementItemServiceImpl.java | ce5eb46430f253099b51fefb7dc701d051d9e77a | [] | no_license | zhumeilu/springboot-dubbo-demo | 43917a1f54602163a5e790ce1a5f51dd719c5597 | dbedbc5cac1b9a6edc3afdf3af50e5255ed20221 | refs/heads/main | 2023-02-14T04:09:16.914922 | 2021-01-08T11:14:59 | 2021-01-08T11:14:59 | 326,919,382 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,170 | java | package com.zml.demo.producer.service.impl.base;
import com.lmhd.common.annotation.BaseService;
import com.lmhd.common.base.BaseServiceImpl;
import com.zml.demo.producer.dao.mapper.OSupplementItemMapper;
import com.zml.demo.producer.dao.model.OSupplementItem;
import com.zml.demo.producer.dao.model.OSupplementItemExample;
import com.zml.demo.producer.api.base.OSupplementItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.lmhd.common.constant.DubboRpcConstant;
/**
* OSupplementItemService实现
* Created by LMHD.TEC on 2021/1/8.
*/
@BaseService
@Service(interfaceClass = OSupplementItemService.class,version = DubboRpcConstant.DEFAULT_RPC_VERSION, timeout = DubboRpcConstant.DEFAULT_RPC_TIMEOUT)
public class OSupplementItemServiceImpl extends BaseServiceImpl<OSupplementItemMapper, OSupplementItem, OSupplementItemExample> implements OSupplementItemService {
private static Logger _log = LoggerFactory.getLogger(OSupplementItemServiceImpl.class);
@Autowired
OSupplementItemMapper oSupplementItemMapper;
} | [
"824434649@qq.com"
] | 824434649@qq.com |
8a7a0c1b5ca68525937c296ef9ebf17c6ba24385 | 1f0a8f317c4eef2728f5f242d4a2eddc7e9fa9c6 | /app/src/main/java/com/example/apphomemanager/GeneralUse/WaterTankData.java | cd56aad19e4dd381aa644c54e642f25d6bb65dca | [] | no_license | KayroPereira/appHomeManager-dlsb | e7d9e936924e02bde5024dba51785849421f7241 | 2a090ff12f4a1c2709d5c985e603cfab38930d6b | refs/heads/master | 2023-02-15T03:50:11.615154 | 2021-01-11T18:47:39 | 2021-01-11T18:47:39 | 320,299,082 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,596 | java | package com.example.apphomemanager.GeneralUse;
public class WaterTankData {
private String address[] = new String[3];
private int err;
private int fcp;
private int level;
private int x1s;
private int sx1;
private int ll;
private int lh;
public WaterTankData(){}
public WaterTankData(String[] address, int err, int fcp, int level, int x1s, int sx1, int ll, int lh) {
this.address = address;
this.err = err;
this.fcp = fcp;
this.level = level;
this.x1s = x1s;
this.sx1 = sx1;
this.ll = ll;
this.lh = lh;
}
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public int getErr() {
return err;
}
public void setErr(int err) {
this.err = err;
}
public int getFcp() {
return fcp;
}
public void setFcp(int fcp) {
this.fcp = fcp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getX1s() {
return x1s;
}
public void setX1s(int x1s) {
this.x1s = x1s;
}
public int getSx1() {
return sx1;
}
public void setSx1(int sx1) {
this.sx1 = sx1;
}
public int getLl() {
return ll;
}
public void setLl(int ll) {
this.ll = ll;
}
public int getLh() {
return lh;
}
public void setLh(int lh) {
this.lh = lh;
}
}
| [
"kayrofellyxbr@gmail.com"
] | kayrofellyxbr@gmail.com |
202e186fb727b21eae28a50426aa613d0f704043 | a017b794edd7199b8d0375560301ed53534142d3 | /lab2/com/company/hangman.java | 241437cc53c282913c801ba829c05c8c77fe9655 | [] | no_license | mark74384/Data-Structures-Assignment | ead716fecbea379dd0e6aa3b7ec3f9cddcb31093 | 57718b27ba85491188e8591a9a6467a02edb39a5 | refs/heads/master | 2021-12-01T15:36:52.722609 | 2021-11-13T10:06:28 | 2021-11-13T10:06:28 | 241,616,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,199 | java | package lab2.com.company;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.lang.*;
import java.util.*;
import static java.lang.String.*;
// name : mark magdy nasr
// id : 18011304
public class hangman implements IHangman {
String [] words;
String [] dictionary;
private String ran;
private int max;
private int correctGuess;
char [] dashes;
public void readfile() {
try {
Scanner input = new Scanner(new File("dictionary.txt"));
int count =0;
while (input.hasNextLine()){
input.nextLine();
count ++ ;
}
input.close();
BufferedReader in = new BufferedReader(new FileReader("dictionary.txt"));
String [] words = new String[count];
String [] dictionary = new String[count];
for (int i = 0 ; i < count ; i++){
words[i] = in.readLine();
}
setDictionary(words);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void setDictionary(String[] words) {
this.dictionary = words;
}
@Override
public String selectRandomSecretWord() {
Random random = new Random();
int randomIdx = random.nextInt(dictionary.length);
if(dictionary[randomIdx] !=null){
this.ran = dictionary[randomIdx];
char [] dashes = new char[ran.length()];
int i =0;
int correctGuess=0;
while (i<ran.length()){
dashes[i] = '-';
if (ran.charAt(i)==' '){
dashes[i] = ' ';
}
i++;
}
this.dashes = dashes;
return dictionary[randomIdx];}
else
return null;
}
@Override
public String guess(Character c) throws Exception {
ran = ran.toLowerCase(Locale.forLanguageTag(ran));
if (isBuggyWord(ran)) {
throw new Exception("Buggy word is chosen from dictionary");
}
if (c == null) {
String string = new String(dashes);
return string;
}
c = Character.toLowerCase(c);
if (Character.isLowerCase(c)) {
if (ran.contains(c + "")) {
for (int j = 0; j < ran.length(); j++) {
if (ran.charAt(j) == c) {
if (dashes[j]!=c){
dashes[j] = c;}
else continue;
if (correctGuess!=ran.length()){
correctGuess++;
}}
}
} else
if (max !=0){
max--;}
}
else {
throw new Exception("enter character");
}
if (correctGuess==ran.length()){
return null;
}
if (max == 0){
return null;
}
String string = new String(dashes);
return string;
}
@Override
public void setMaxWrongGuesses(Integer max) {
if (max == null) this.max = 1;
else if (max >= 0) this.max = max;
}
private Boolean isBuggyWord(String ran) {
for (int i = 0; i < ran.length(); i++) {
if(!Character.isLetter(ran.charAt(i))) {
return true;
}
}
return false;
}
public static void main(String[] args) {
hangman han = new hangman();
//System.out.println(System.getProperty("user.dir"));
han.readfile();
han.selectRandomSecretWord();
han.setMaxWrongGuesses(5);
try {
System.out.println(han.guess('a'));
System.out.println(han.guess('c'));
System.out.println(han.guess('z'));
System.out.println(han.guess('d'));
}
catch (Exception e){
e.printStackTrace();
}
}
} | [
"noreply@github.com"
] | noreply@github.com |
94a851fe210821e668f1ab9cad973612e33dfd93 | 5ba94ce08e1350eb889c5721e35f4b3e50c9c506 | /app/src/main/java/com/arsenal/mnnite_community/MainActivity.java | 99b2e6576d27dc0791294fb9bb7ea479c95a605d | [] | no_license | Vikas185/MNNITECOMMUNITY | f28bb981cd7acd99f18d661bf9dd8226666645ef | b52a5bdf406320c791b2c62c13c05297d686d9d2 | refs/heads/main | 2023-01-02T22:57:10.479241 | 2020-10-23T11:37:12 | 2020-10-23T11:37:12 | 306,808,154 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.arsenal.mnnite_community;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
} | [
"siddharth.maurya112@gmail.com"
] | siddharth.maurya112@gmail.com |
739cf874941297a7330da01ceea4ee8843e18f40 | 736d2288eea001128f40ddba12e56647c64cd9bc | /PrimeiroTrauma.java | 61166c3d0751df3633ab98febedcc8a0aaf79279 | [] | no_license | JoaoPauloBovi/RepositoioExerciciosEclipse | aff4284744c8c2da5a3a4ed6356afd578a505d1c | 33c216267e8b978e1dd076e8118342ec5eefe9b5 | refs/heads/main | 2023-07-24T11:32:15.696029 | 2021-09-04T17:59:30 | 2021-09-04T17:59:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 244 | java | package Classe;
public class PrimeiroTrauma {
int a = 3;
static int b = 4;
public static void main(String[] args) {
PrimeiroTrauma p = new PrimeiroTrauma();
System.out.println(p.a);
System.out.println(b);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
91ad9200b47ae114c190d07aa18ace11ea5526b5 | b7bd1a3c78f83d8ee3a8de54ed1f5eb20cbf3033 | /Scorm/scorm-impl/service/src/java/org/sakaiproject/scorm/entity/ScormEntityProviderImpl.java | 13427a70b62b72c3d07a9c77d3d745e61cd3284b | [
"ECL-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-generic-cla"
] | permissive | efundi/efundi | ae76fa18a806a759660d52f4c0fd9f1e42da2a0b | 8c39c349fb548c7edb2e7183d93c21de90de8996 | refs/heads/master | 2021-09-08T10:34:30.582030 | 2017-12-13T07:40:35 | 2017-12-13T07:40:35 | 104,885,567 | 1 | 1 | ECL-2.0 | 2017-12-12T06:53:20 | 2017-09-26T13:04:34 | Java | UTF-8 | Java | false | false | 21,265 | java | /**
* Copyright (c) 2007 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.sakaiproject.scorm.entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.CoreEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityURLRedirect;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.PropertyProvideable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.RESTful;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Redirectable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestAware;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Resolvable;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.entitybroker.entityprovider.extension.Formats;
import org.sakaiproject.entitybroker.entityprovider.extension.RequestGetter;
import org.sakaiproject.entitybroker.entityprovider.search.Search;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.scorm.model.api.ContentPackage;
import org.sakaiproject.scorm.service.api.ScormContentService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;
/**
* Allows some basic functions on SCORM module instances via the EntityBroker.
*
* @author bjones86
*/
public class ScormEntityProviderImpl implements ScormEntityProvider, CoreEntityProvider, AutoRegisterEntityProvider, RequestAware,
PropertyProvideable, Resolvable, Outputable, RESTful, Redirectable, ActionsExecutable
{
// Class members
private static final Log LOG = LogFactory.getLog( ScormEntityProviderImpl.class );
private static final String TOOL_CONFIG_PERM = "scorm.configure";
private static final String TOOL_LAUNCH_PERM = "scorm.launch";
private static final String TOOL_REG_NAME = "sakai.scorm.tool";
private static final String SCORM_PLAYER_PAGE_URL_PART = "wicket:bookmarkablePage=ScormPlayer:org.sakaiproject.scorm.ui.player.pages.PlayerPage";
private static final String URL_CHARACTER_ENCODING = "UTF-8";
// Instance members
private final ResourceLoader resourceLoader = new ResourceLoader( "messages" );
// Sakai APIs
@Getter @Setter private SessionManager sessionManager;
@Getter @Setter private SiteService siteService;
@Getter @Setter private SecurityService securityService;
@Getter @Setter private UserDirectoryService userDirectoryService;
@Getter @Setter private RequestGetter requestGetter;
@Getter @Setter private ServerConfigurationService serverConfigurationService;
// SCORM APIs
@Getter @Setter private ScormContentService contentService;
// *************************************************************
// ************** Public EntityBroker Methods ******************
// *************************************************************
/**
* Controls the globally unique prefix for the entities handled by this provider. For
* example: Announcements might use "annc", Evaluation might use "eval" (if this is not actually
* unique then an exception will be thrown when Sakai attempts to register this broker).
* (the global reference string will consist of the entity prefix and the local id)
*
* @return the string that represents the globally unique prefix for an entity type
*/
@Override
public String getEntityPrefix()
{
logIfDebugEnabled( "getEntityPrefix()" );
return ScormEntityProvider.ENTITY_PREFIX;
}
/**
* {@inheritDoc}
*/
@Override
public Object getSampleEntity()
{
logIfDebugEnabled( "getSampleEntity()" );
return new ScormEntity();
}
/**
* {@inheritDoc}
*/
@Override
public String[] getHandledOutputFormats()
{
logIfDebugEnabled( "getHandledOutputFormats()" );
return ScormEntityProvider.HANDLED_OUTPUT_FORMATS;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> findEntityRefs( String[] prefixes, String[] names, String[] searchValues, boolean exactMatch )
{
logIfDebugEnabled( "findEntityRefs()" );
String siteID = null;
String userID = null;
List<String> entityRefs = new ArrayList<>();
// If the provided prefix is that of the SCORM prefix...
if( ENTITY_PREFIX.equals( prefixes[0] ) )
{
// Get the siteID and userID
for( int i = 0; i < names.length; i++ )
{
if( "context".equalsIgnoreCase( names[i] ) || "site".equalsIgnoreCase( names[i] ) )
{
siteID = searchValues[i];
}
else if( "user".equalsIgnoreCase( names[i] ) || "userId".equalsIgnoreCase( names[i] ) )
{
userID = searchValues[i];
}
}
// If a siteID and userID are provided...
if( siteID != null && userID != null )
{
try
{
// If the siteID and userID are the same, it's really trying to access the user's My Workspace, so we need to prepend '~' to the siteID
if( siteID.equals( userID ) )
{
siteID = "~" + siteID;
}
// Get the site, verify it exists
Site site = siteService.getSite( siteID );
if( site != null )
{
// Check to make sure the current user has the 'scorm.configure' permission for the site
if( !securityService.unlock( userID, TOOL_CONFIG_PERM, siteService.siteReference( siteID ) ) )
{
// Log the message that this user doesn't have the permision for the site, return an empty list
LOG.error( "User (" + userID + ") does not have permission (" + TOOL_CONFIG_PERM + ") for site: " + siteID );
return entityRefs;
}
// Get the tool ID
String toolID = "";
Collection<ToolConfiguration> toolConfigs = site.getTools( TOOL_REG_NAME );
for( ToolConfiguration toolConfig : toolConfigs )
{
toolID = toolConfig.getId();
}
// Only continue if the tool ID is valid
if( StringUtils.isNotBlank( toolID ) )
{
// Get the content packages
List<ContentPackage> contentPackages = contentService.getContentPackages( siteID );
for( ContentPackage contentPackage : contentPackages )
{
String refString = "/" + ENTITY_PREFIX + "/" +
siteID + ENTITY_PARAM_DELIMITER +
toolID + ENTITY_PARAM_DELIMITER +
contentPackage.getContentPackageId() + ENTITY_PARAM_DELIMITER +
contentPackage.getResourceId() + ENTITY_PARAM_DELIMITER +
contentPackage.getTitle();
entityRefs.add( refString );
}
}
}
}
catch( IdUnusedException ex )
{
LOG.warn( "Can't find site with ID = " + siteID, ex );
throw new IllegalArgumentException( "Can't find site with ID = " + siteID, ex );
}
}
}
return entityRefs;
}
/**
* {@inheritDoc}
*/
@Override
public Object getEntity( EntityReference ref )
{
logIfDebugEnabled( "getEntity()" );
try
{
// If the reference is invalid, throw an exception and exit
if( ref == null || StringUtils.isBlank( ref.getId() ) )
{
throw new IllegalArgumentException( "You must supply a valid EntityReference" );
}
// If the user has permission to launch SCORM modules in the current site, redirect them to the module
ScormEntity entity = getScormEntity( ref.getId() );
if( isCurrentUserLaunchAuth( entity.getSiteID() ) )
{
requestGetter.getResponse().sendRedirect( "/direct/" + ENTITY_PREFIX + "/" + entity.getID() + "/redirect" );
}
// Otherwise, redirect them to the HTML representation of the SCORM entity
else
{
requestGetter.getResponse().sendRedirect( "/direct/" + ENTITY_PREFIX + "/" + entity.getID() + "/viewHTML" );
}
}
catch( IOException ex )
{
LOG.error( ex );
}
return ref;
}
/**
* {@inheritDoc}
*/
@Override
public boolean entityExists( String id )
{
logIfDebugEnabled( "entityExists()" );
// If the id is invalid, throw an exception and exit
if( StringUtils.isBlank( id ) )
{
throw new IllegalArgumentException( "You must supply a valid ID" );
}
// Otherwise, attempt to get the entity
else
{
// If the entity is null, it doesn't exist
return getScormEntity( id ) != null;
}
}
/**
* Returns an HTML string that describes the ScormEntity in question;
* takes into account authentication for viewing SCORM modules.
*
* @param ref the EntityReference object requested
* @return the HTML string describing the entity
*/
@EntityCustomAction( action = "viewHTML", viewKey = EntityView.VIEW_SHOW )
public Object getScormEntityAsHTML( EntityReference ref )
{
logIfDebugEnabled( "getScormEntityAsHTML()" );
// Return the generated HTML
return new ActionReturn( Formats.UTF_8, Formats.HTML_MIME_TYPE, createScormEntityHTML( (ScormEntity) getScormEntity( ref.getId() ) ) );
}
/**
* Redirects the user who clicked on a SCORM entity link to the actual final generated
* URL of the SCORM instance, provided the current user passes the validation/authentication
* required for launching a SCORM module
*
* @param vars the map of parameters returned from the EntityBroker (contains the toolID:contentPackageID:resourceID identifier)
* @return the final generated URL of the SCORM instance
*/
@EntityURLRedirect( "/{prefix}/{id}/redirect" )
public String redirectScormEntity( Map<String, String> vars )
{
logIfDebugEnabled( "redirectScormEntity()" );
// If the current user is able to launch a SCORM module, generate and return the final URL
ScormEntity entity = (ScormEntity) getScormEntity( vars.get( "id" ) );
if( isCurrentUserLaunchAuth( entity.getSiteID() ) )
{
return generateFinalScormURL( entity );
}
// Otherwise, redirect to the /viewHTML custom action (which handles the non-authorized presentation)
else
{
return "/direct/" + ENTITY_PREFIX + "/" + entity.getID() + "/viewHTML";
}
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, String> getProperties( String reference )
{
logIfDebugEnabled( "getProperties()" );
// If the reference is invalid, throw an exception and exit
Map<String, String> properties = new HashMap<>();
if( StringUtils.isBlank( reference ) )
{
throw new IllegalArgumentException( "You must provide a valid reference string" );
}
else
{
// Get the entity by ID
String id = reference.replaceAll( "/" + ENTITY_PREFIX + "/", "" );
ScormEntity entity = getScormEntity( id );
// If the entity is not null, get the properties
if( entity != null )
{
properties.put( SCORM_ENTITY_PROP_SITE_ID, entity.getSiteID() );
properties.put( SCORM_ENTITY_PROP_TOOL_ID, entity.getToolID() );
properties.put( SCORM_ENTITY_PROP_CONTENT_PACKAGE_ID, entity.getContentPackageID() );
properties.put( SCORM_ENTITY_PROP_RESOURCE_ID, entity.getResourceID() );
properties.put( SCORM_ENTITY_PROP_TITLE, entity.getTitle() );
properties.put( SCORM_ENTITY_PROP_TITLE_ENCODED, entity.getTitleEncoded() );
}
}
return properties;
}
/**
* {@inheritDoc}
*/
@Override
public String getPropertyValue( String reference, String name )
{
logIfDebugEnabled( "getPropertyValue()" );
// Get the properties; if they're not null, get the named property requested
String property = null;
Map<String, String> properties = getProperties( reference );
if( properties != null && properties.containsKey( name ) )
{
property = properties.get( name );
}
return property;
}
// *************************************************************
// ******************* Private Utility Methods******************
// *************************************************************
/**
* Determine if the current user should be able to launch the SCORM module,
* based on the 'scorm.launch' permission.
*
* @param siteID the current site's internal ID
* @return true/false if the user has the 'scorm.launch' permission in the current site
*/
private boolean isCurrentUserLaunchAuth( String siteID )
{
logIfDebugEnabled( "isCurrentUserLaunchAuth()" );
String userID = userDirectoryService.getCurrentUser().getId();
return securityService.unlock( userID, TOOL_LAUNCH_PERM, siteService.siteReference( siteID ) );
}
/**
* Get a ScormEntity object by ID (toolID:contentPackageID:resourceID:title)
*
* @param entityID the packed ID reference string (toolID:contentPackageID:resourceID:title)
* @return the ScormEntity object requested
*/
private ScormEntity getScormEntity( String entityID )
{
logIfDebugEnabled( "getScormEntity()" );
// Short circuit if an ID is not supplied
ScormEntity entity = null;
if( StringUtils.isBlank( entityID ) )
{
throw new IllegalArgumentException( "You must supply a valid reference string" );
}
else
{
String tokens[] = entityID.split( ScormEntityProvider.ENTITY_PARAM_DELIMITER );
if( tokens.length == 5 )
{
String siteID = tokens[0];
String toolID = tokens[1];
String contentPackageID = tokens[2];
String resourceID = tokens[3];
String title = tokens[4];
String titleEncoded = title;
try
{
titleEncoded = URLEncoder.encode( title, URL_CHARACTER_ENCODING );
}
catch( UnsupportedEncodingException ex )
{
LOG.warn( "Unable to encode SCORM entity title: " + title, ex );
}
entity = new ScormEntity( siteID, toolID, contentPackageID, resourceID, title, titleEncoded );
}
else
{
throw new IllegalArgumentException( "You must supply a valid reference string" );
}
}
return entity;
}
/**
* Creates an HTML representation for a given ScormEntity object.
*
* @param entity the ScormEntity to describe via HTML
* @return the generated HTML string based on the provided ScormEntity object
*/
private String createScormEntityHTML( ScormEntity entity )
{
logIfDebugEnabled( "createScormEntityHTML()" );
StringBuilder sb = new StringBuilder();
sb.append( resourceLoader.getFormattedMessage( "htmlHeader", new Object[] { serverConfigurationService.getString( "skin.repo" ) + "/tool_base.css" } ) );
// If the user is allowed to launch SCORM modules in the current site, generate the HTML to view the link
if( isCurrentUserLaunchAuth( entity.getSiteID() ) )
{
sb.append( resourceLoader.getFormattedMessage( "htmlIframe", new Object[] { generateFinalScormURL( entity ) } ) );
}
// Otherwise, just build some HTML to tell the user thye're not allowed to launch SCORM modules in this site
else
{
sb.append( resourceLoader.getFormattedMessage( "htmlH2", new Object[] { resourceLoader.getString( "authFailMsg" ) } ) );
}
// Return the generated HTML string
sb.append( resourceLoader.getString( "htmlFooter" ) );
return sb.toString();
}
/**
* Generates the final URL for a SCORM module entity, which includes the tool ID,
* content package ID, resource ID and title.
*
* @param entity the specific SCORM module the requester wants a link to
* @return
*/
private String generateFinalScormURL( ScormEntity entity )
{
logIfDebugEnabled( "generateFinalScormURL()" );
// Build and return the full URL to the specified SCORM module
String url = serverConfigurationService.getServerUrl() + "/portal/tool/" +
entity.getToolID() + "?" +
SCORM_PLAYER_PAGE_URL_PART + "&contentPackageId=" +
entity.getContentPackageID() + "&resourceId=" +
entity.getResourceID() + "&title=" +
entity.getTitleEncoded();
return url;
}
/**
* Utility method to avoid repeating this debug code in every method.
*
* @param message the message to be logged
*/
private void logIfDebugEnabled( String message )
{
if( LOG.isDebugEnabled() )
{
LOG.debug( message );
}
}
// *************************************************************
// ******************* Unimplemented Methods *******************
// *************************************************************
@Override public String createEntity( EntityReference ref, Object entity, Map<String, Object> params ) { return null; }
@Override public List<?> getEntities ( EntityReference ref, Search search ) { return null; }
@Override public String[] getHandledInputFormats() { return null; }
@Override public void updateEntity( EntityReference ref, Object entity, Map<String, Object> params ) {}
@Override public void deleteEntity( EntityReference ref, Map<String, Object> params ) {}
@Override public void setPropertyValue( String reference, String name, String value ) {}
}
| [
"root@v-dsakai-dev-lnx1.nwu.ac.za"
] | root@v-dsakai-dev-lnx1.nwu.ac.za |
f54549ffe14809edd9d2fd22dcf22b0d837293fb | 3a8ff5d7c1862f8bf2cb0b7953c1163ade8f4760 | /XXXXBusiness/src/main/java/ar/com/xxxx/business/base/GenericBusinessImpl.java | 46060161be478dc69b591a265877d6d6f748cedb | [] | no_license | calaveragamingtv/springmvc | 0e2b0aa1eedd6a60d327c9d2cb2cf48af6fba049 | 196234666c12fa01f47894401f845c499855f1b5 | refs/heads/master | 2021-01-19T10:14:56.936195 | 2017-04-17T18:30:24 | 2017-04-17T18:30:24 | 87,845,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,082 | java | package ar.com.xxxx.business.base;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ar.com.xxxx.business.base.exceptions.BusinessException;
import ar.com.xxxx.persistence.base.IGenericDao;
import ar.com.xxxx.persistence.base.exceptions.PersistenceException;
/**
* <p>
* Business General.
* </p>
*
* @author usuario
* @since 23/03/2017
*
* @param <E>
* Entidad
* @param <K>
* Tipo de id de la Entidad
*/
@Service
public abstract class GenericBusinessImpl<E, K> implements IGenericBusiness<E, K> {
/**
* <p>
* Generic dao.
* </p>
*/
private IGenericDao<E, K> genericDao;
/**
* <p>
* Constructor sobre cargado.
* </p>
*
* @param genericDao
* dao por dfecto
* @author nconde
*/
public GenericBusinessImpl(final IGenericDao<E, K> genericDao) {
this.genericDao = genericDao;
}
/**
* <p>
* Constructor.
* </p>
*
* @author nconde
*/
public GenericBusinessImpl() {
super();
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdate(final E entity) throws BusinessException {
try {
genericDao.saveOrUpdate(entity);
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<E> getAll() throws BusinessException {
List<E> lista;
try {
lista = genericDao.getAll();
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
return lista;
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public E get(final K id) throws BusinessException {
E entidad;
try {
entidad = genericDao.find(id);
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
return entidad;
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void add(E entity) throws BusinessException {
try {
genericDao.add(entity);
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void update(final E entity) throws BusinessException {
try {
genericDao.update(entity);
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void remove(final E entity) throws BusinessException {
try {
genericDao.remove(entity);
} catch (PersistenceException e) {
throw new BusinessException(e.getMessage(), e.getCause());
}
}
} | [
"usuario@172.25.100.116"
] | usuario@172.25.100.116 |
ee8a9e483f40607dbf52fe9b6bff3df8dae61117 | 5942ac67d609405a56838b5a4fa15ec618480fec | /android/src/dev/ian/snakeboi/AndroidLauncher.java | bd8a19f739f11603932f18bc00c773ac0b58b7eb | [] | no_license | DavidG33k/intelli-snake | 18763898c2fdb075f12a854e0a1eabe135c6e45e | 7fba5c21a9a379a64b4beac7e9a53f28c84dc400 | refs/heads/main | 2023-03-30T00:04:26.478555 | 2021-03-28T19:26:31 | 2021-03-28T19:26:31 | 352,442,232 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 543 | java | package dev.ian.snakeboi;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import dev.ian.snakeboi.menu.Menu;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useImmersiveMode = true;
initialize(new Menu(), config);
}
}
| [
"37270113+DavidG33k@users.noreply.github.com"
] | 37270113+DavidG33k@users.noreply.github.com |
3a8e857643dd67e28176a54b43e6cf29ba5fa481 | 6e1a7dc4f57284c43007d18737d63311775a461b | /src/ires/corso/partone/geometric/Triangolo.java | 477a5bf5e766b8416c9b5cabc576b5acf86431ca | [] | no_license | AlessioGambuto/Workbook | f13c708344ea34e3bf0a2a7f63cad114b502a34b | b656479e657653c4869796cdb7590f39f6712374 | refs/heads/master | 2023-06-15T03:19:58.561343 | 2021-07-07T16:08:38 | 2021-07-07T16:08:38 | 373,893,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 217 | java | package ires.corso.partone.geometric;
public class Triangolo {
public static double computeArea(double base, double altezza){
double areatriangolo = (base*altezza)/2;
return areatriangolo;
}
} | [
"alessio.gambuto@outlook.it"
] | alessio.gambuto@outlook.it |
1a39b163e5443e477a6af34987801599c6ac9170 | 3c77d0365174813361b9e0b9b992979e6e7b1aac | /src/main/java/selim/omniStuff/helmet/GoggleRender.java | b95643fa6b6c49eef7931d4c4b9bbf8a76a1af8c | [] | no_license | Selim042/Omni-Things | c5afcf4cec866366a1bc1971f9dd8a4e5f7df8e5 | 01067abef9ec9c6de4d81590b64754e721516672 | refs/heads/master | 2020-04-05T23:39:02.560881 | 2015-08-17T13:15:46 | 2015-08-17T13:15:46 | 39,037,806 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,483 | java | package selim.omniStuff.helmet;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
public class GoggleRender implements IItemRenderer {
private static RenderItem renderItem = new RenderItem();
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
// TODO Auto-generated method stub
return type == ItemRenderType.INVENTORY;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item,
ItemRendererHelper helper) {
// TODO Auto-generated method stub
return false;
}
@Override
public void renderItem(ItemRenderType type, ItemStack itemStack, Object... data) {
// TODO Auto-generated method stub
IIcon icon = itemStack.getIconIndex();
renderItem.renderIcon(0, 0, icon, 16, 16);
Tessellator tessellator = Tessellator.instance;
// Set drawing mode. Tessellator should support most drawing modes.
tessellator.startDrawing(GL11.GL_QUADS);
// Set semi-transparent black color
tessellator.setColorRGBA(0, 0, 0, 128);
// Draw a 8x8 square
tessellator.addVertex(0, 0, 0);
tessellator.addVertex(0, 8, 0);
tessellator.addVertex(8, 8, 0);
tessellator.addVertex(8, 0, 0);
tessellator.draw();
}
}
| [
"pokemon924@live.com"
] | pokemon924@live.com |
3369c1556962eea966d9ccd6544a4999ecd92f9a | fc1da6c5c2d12fd9615c91c4b32a5cba80728475 | /src/ejercicio_1/Cliente.java | a17962c8a69a284ccf9cc357432f9317dab7f432 | [] | no_license | Valido-101/PSP_examen_09_11_2020 | 688d038cb31d902d41efd8fa5ed4e7259fc51916 | d1d425297f27b5d307fc4483b297168720e251c5 | refs/heads/master | 2023-01-11T06:04:28.672774 | 2020-11-09T09:27:55 | 2020-11-09T09:27:55 | 311,286,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package ejercicio_1;
public class Cliente {
private int tiempo_pedido;
private String nombre;
public Cliente(String nombre)
{
tiempo_pedido=(int)(Math.random()*5+1000);
this.nombre = nombre;
}
public int getTiempo_pedido() {
return tiempo_pedido;
}
public void setTiempo_pedido(int tiempo_pedido) {
this.tiempo_pedido = tiempo_pedido;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| [
"jesuszafra22@gmail.com"
] | jesuszafra22@gmail.com |
a2adc55903755bf8be63c1e08843ac601f98b998 | 3153c87821516ac929de2bff79f8b7f1a9f784af | /server/java/tr/edu/metu/ncc/cng/gtsearch/xmlparser/ks/MohseContext.java | 5c5fb52bc618ece04cee7fceeda2724d07d203b6 | [] | no_license | ugurdonmez/mohse | 195b89cbe374de0e0ca991ea54b9772b3a02d083 | 8b6c2fa0c9a9bb4ac09dcf3017e5d118d0b33ec6 | refs/heads/master | 2021-01-23T15:51:33.183046 | 2014-11-11T11:55:12 | 2014-11-11T11:55:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 929 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tr.edu.metu.ncc.cng.gtsearch.xmlparser.ks;
/**
*
* @author ugur
*/
public class MohseContext {
private String concept;
private String context;
private String term;
public MohseContext() {
}
public MohseContext(String concept, String context, String term) {
this.concept = concept;
this.context = context;
this.term = term;
}
public String getConcept() {
return concept;
}
public void setConcept(String concept) {
this.concept = concept;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
}
| [
"donmez@metu.edu.tr"
] | donmez@metu.edu.tr |
7805e3c7f27ed3499903a09bffa18a98f954b0df | fd6af8bc241543aaaff638a9415772dfbdf5410f | /src/main/java/com/xie/tmall/dao/ReviewDAO.java | 46a48808836885db0f1dada3584deda0e273a3e2 | [] | no_license | XZoro/tmall_springboot | 76b232265c7212d6165ce5e8f908651f951cbaad | 2130e6d54e8e841d6a7f6c8906db5956b5d81ab1 | refs/heads/master | 2022-07-01T10:02:32.233032 | 2019-05-30T08:33:36 | 2019-05-30T08:33:36 | 187,809,750 | 0 | 0 | null | 2022-06-21T01:08:52 | 2019-05-21T09:51:39 | JavaScript | UTF-8 | Java | false | false | 356 | java | package com.xie.tmall.dao;
import com.xie.tmall.pojo.Product;
import com.xie.tmall.pojo.Review;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ReviewDAO extends JpaRepository<Review,Integer>{
List<Review> findByProductOrderByIdDesc(Product product);
int countByProduct(Product product);
}
| [
"xiezhongqing@jinyafu.com"
] | xiezhongqing@jinyafu.com |
9a6330705ce1fb1d6c31de80c018b150008ef342 | a79c545955df01c1ab406b1516bd66ada9216246 | /src/com/nus/cool/core/io/writestore/ChunkWS.java | 932d29d6522ece65d1a52e8828e8f762006f9baf | [
"Apache-2.0"
] | permissive | YingHongBin/cool | 5eb8bf9fe61766f69f74af80c9f1427e56824aab | d9c2580d827336356841cff9201db011401dbc56 | refs/heads/master | 2023-05-31T21:50:58.014183 | 2020-01-18T07:55:14 | 2020-01-18T07:58:51 | 255,837,906 | 0 | 0 | Apache-2.0 | 2020-04-15T07:25:18 | 2020-04-15T07:25:17 | null | UTF-8 | Java | false | false | 4,102 | java | /**
*
*/
package com.nus.cool.core.io.writestore;
import static com.google.common.base.Preconditions.checkArgument;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import com.google.common.primitives.Ints;
import com.nus.cool.core.cohort.schema.FieldSchema;
import com.nus.cool.core.cohort.schema.FieldType;
import com.nus.cool.core.cohort.schema.TableSchema;
import com.nus.cool.core.io.ChunkType;
import com.nus.cool.core.io.Output;
import com.nus.cool.core.io.OutputCompressor;
import com.nus.cool.core.io.compression.DefaultCompressorAdviser;
import com.nus.cool.core.io.compression.DefaultCompressorFactory;
import com.nus.cool.core.lang.Integers;
/**
* Data layout
*
* ---------------------------------------------
* | chunk data | chunk header | header offset |
* ---------------------------------------------
*
* Chunk data layout:
* -------------------------------------
* | field 1 | field 2 | ... | field N |
* -------------------------------------
*
* Chunk header layout:
* ----------------------------------------------
* | ChunkType | count | fields | field offsets |
* ----------------------------------------------
* where
* ChunkType == ChunkType.DATA
* count == number of records
* fields = number of fields
*
* @author david, xiezl
*
*/
public class ChunkWS implements Output {
public static ChunkWS newCohortChunk(TableSchema schema,
MetaFieldWS[] metaFields, int offset) {
OutputCompressor compressor = new OutputCompressor(
new DefaultCompressorAdviser(), new DefaultCompressorFactory());
List<FieldSchema> fieldSchemaList = schema.getFields();
FieldWS[] fields = new FieldWS[fieldSchemaList.size()];
int i = 0;
for (FieldSchema fieldSchema : fieldSchemaList) {
FieldType fieldType = fieldSchema.getFieldType();
switch (fieldType) {
case AppKey:
case Segment:
case Action:
case UserKey:
fields[i] = new HashFieldWS(fieldType, i, metaFields[i], compressor, fieldSchema.getPreCal());
break;
case ActionTime:
case Metric:
fields[i] = new RangeFieldWS(fieldType, i, compressor);
break;
// case Day:
// case Week:
// case Month:
// fields[i] = new SinceEventFieldWS(i, schema.getAppKeyField(),
// schema.getUserKeyField(), schema.getActionField(), fieldSchema.getBirthEvent());
// break;
default:
throw new IllegalArgumentException("FieldType: " + fieldType);
}
i++;
}
return new ChunkWS(offset, fields);
}
/**
* Chunk Offset
*/
private int off;
private int count;
private FieldWS[] fields;
public ChunkWS(int off, FieldWS[] fields) {
checkArgument(off >= 0 && fields != null && fields.length > 0);
this.off = off;
this.fields = fields;
}
/**
* Put a tuple into the chunk
*
* @param tuple
* @throws IOException
*/
public void put(String[] tuple) throws IOException {
count++;
for (int i = 0; i < tuple.length; i++)
fields[i].put(tuple);
}
/**
* The number of records written so far.
*
* @return
*/
public int count() {
return count;
}
@Override
public int writeTo(DataOutput out) throws IOException {
int bytesWritten = 0;
int[] offsets = new int[fields.length];
// Calculate the offset of each field
// Write chunk data
for (int i = 0; i < fields.length; i++) {
offsets[i] = off + bytesWritten;
bytesWritten += fields[i].writeTo(out);
}
// Write header, Calculate the offset of header
int chunkHeadOff = off + bytesWritten;
// Write chunkType (DATA)
out.writeByte(ChunkType.DATA.ordinal());
bytesWritten++;
// Write #records (count)
out.writeInt(Integers.toNativeByteOrder(count));
bytesWritten += Ints.BYTES;
// Write #fields (fields)
out.writeInt(Integers.toNativeByteOrder(fields.length));
bytesWritten += Ints.BYTES;
// Write field offsets
for (int offset : offsets) {
out.writeInt(Integers.toNativeByteOrder(offset));
bytesWritten += Ints.BYTES;
}
// Write header offset
out.writeInt(Integers.toNativeByteOrder(chunkHeadOff));
bytesWritten += Ints.BYTES;
return bytesWritten;
}
}
| [
"xiezhongle@comp.nus.edu.sg"
] | xiezhongle@comp.nus.edu.sg |
0fddb2da019a2f759f4373b854c81e9410b0e04b | 4b1a967fc91c896fee48bf476b019b4ce295cdb5 | /src/jxnu/n433/x3107/SunGroup/OtherActivity/PersonalleftActivity.java | a5476c8c5166c693e9f074f392a6d74036d939b9 | [] | no_license | zhengyuebing/shaiquanAPP | a8cc0068b4cf412f97ddca5443473e0daa8b36e9 | 923ce6df12a616f82f84c2cbd7ca7288dd99dfb8 | refs/heads/master | 2020-12-31T05:10:09.562677 | 2016-05-03T14:16:53 | 2016-05-03T14:16:53 | 57,285,090 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,582 | java | package jxnu.n433.x3107.SunGroup.OtherActivity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Window;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import jxnu.n433.x3107.SunGroup.MainActivity;
import jxnu.n433.x3107.SunGroup.R;
import jxnu.n433.x3107.SunGroup.WelComeActivity;
import jxnu.n433.x3107.SunGroup.OtherActivity.View.LeftBtnClickListener;
import jxnu.n433.x3107.SunGroup.OtherActivity.View.PersonalleftDialog;
import jxnu.n433.x3107.bean.MySelfListing;
import jxnu.n433.x3107.bean.UserInfo;
import jxnu.n433.x3107.sqlite.GoodsDataHelper;
import jxnu.n433.x3107.sqlite.UserInfoDataHelper;
import jxnu.n433.x3107.utils.Utils;
public class PersonalleftActivity extends Activity implements OnClickListener{
private ImageView leftPersonalback;
private ImageView leftPersonalIViewHead;//头像
private RelativeLayout Head;
public TextView pName;//昵称
public TextView pSexs;//性别
public TextView pSite;//地址
public TextView pIntro;//简介
public TextView pSchool;//学校
public TextView pBirthday;//生日
public TextView pQQ;//QQ
public TextView pMailBox;//邮箱
public TextView pPhoneNumber;
public RelativeLayout personalSexs,
personalSite,
personalIntro,
personalSchool,
personalBirthday,
personalQQ,
personalMailBox,
personalPhomeNumber;//信息点击修改
private DatePickerDialog dialogBirthday;
private int year,monthofyear,dayofMonth;
private String textBirthday;
private UserInfoDataHelper userinfoDH ;
private List<UserInfo> userInfoList ;
private GoodsDataHelper goodsDHelper;
private List<MySelfListing> mslList;
public PersonalleftDialog dialogOut;
private Context mContext;
private SharedPreferences sPreferences;
public static String sqliteStudentNumber;
private Bitmap btPersonalHead;
public static String getSqliteStudentNumber() {
return sqliteStudentNumber;
}
public static void setSqliteStudentNumber(String sqliteStudentNumber) {
PersonalleftActivity.sqliteStudentNumber = sqliteStudentNumber;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_personal_left);
mContext = this;
sPreferences = getSharedPreferences(WelComeActivity.STUDENTNUMBER,0);
initTitle();
initImageViewHead();//头像
initReativeLayout();//修改资料
initReativeLayoutFirst();
}
private void initTitle() {
leftPersonalback = (ImageView) findViewById(R.id.personal_left_iv_back_personal);
leftPersonalback.setOnClickListener(this);
}
//头像
@SuppressWarnings("deprecation")
private void initImageViewHead() {
leftPersonalIViewHead = (ImageView) findViewById(R.id.zdy_image_personal);
Head = (RelativeLayout) findViewById(R.id.personal_left_iv_head_personal);
userInfoList = new ArrayList<UserInfo>();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = userinfoDH.getUserInfoList();
String strImage = null;
for (int i = 0; i < userInfoList.size(); i++) {
if (sPreferences.getString("sn", "").equals(userInfoList.get(i).getStudentNumber())) {
strImage = userInfoList.get(i).getUserIcon()+"";
}else {
}
}
try {
btPersonalHead = BitmapFactory.decodeFile(strImage);
if (btPersonalHead != null) {
Drawable drawable = new BitmapDrawable(btPersonalHead);
leftPersonalIViewHead.setImageDrawable(drawable);
}else {
leftPersonalIViewHead.setImageResource(R.drawable.beautiful);
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
Head.setOnClickListener(this);
}
private void initReativeLayout() {//修改资料
pName = (TextView) findViewById(R.id.personal_left_tv_name_personal);
pSexs = (TextView) findViewById(R.id.sexs_personal);
pSite = (TextView) findViewById(R.id.sites_personal);
pIntro = (TextView) findViewById(R.id.intros_personal);
pSchool = (TextView) findViewById(R.id.school_personal);
pBirthday = (TextView) findViewById(R.id.birthday_personal);
pQQ = (TextView) findViewById(R.id.qq_personal);
pMailBox = (TextView) findViewById(R.id.mailbox_personal);
pPhoneNumber = (TextView) findViewById(R.id.phonenumber_personal);
personalSexs = (RelativeLayout) findViewById(R.id.personal_left_layout_sexs_personal);
personalSite = (RelativeLayout) findViewById(R.id.personal_left_layout_site_personal);
personalIntro = (RelativeLayout) findViewById(R.id.personal_left_layout_intro_personal);
personalSchool = (RelativeLayout) findViewById(R.id.personal_left_layout_school_personal);
personalBirthday = (RelativeLayout) findViewById(R.id.personal_left_layout_birthday_personal);
personalQQ = (RelativeLayout) findViewById(R.id.personal_left_layout_qq_personal);
personalMailBox = (RelativeLayout) findViewById(R.id.personal_left_layout_mailbox_personal);
personalPhomeNumber = (RelativeLayout) findViewById(R.id.personal_left_layout_phonenumber_personal);
pName.setOnClickListener(this);
personalSexs.setOnClickListener(this);
personalSite.setOnClickListener(this);
personalIntro.setOnClickListener(this);
personalSchool.setOnClickListener(this);
personalBirthday.setOnClickListener(this);
personalQQ.setOnClickListener(this);
personalMailBox.setOnClickListener(this);
personalPhomeNumber.setOnClickListener(this);
}
private void initReativeLayoutFirst() {
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pName.setText(userInfoList.get(i).getUserName()+"");
pSexs.setText(userInfoList.get(i).getUserSexs()+"");
pSite.setText(userInfoList.get(i).getUserSite()+"");
pIntro.setText(userInfoList.get(i).getUserIntro()+"");
pSchool.setText(userInfoList.get(i).getUserSchool()+"");
pBirthday.setText(userInfoList.get(i).getUserBirthday()+"");
pQQ.setText(userInfoList.get(i).getUserQQ()+"");
pMailBox.setText(userInfoList.get(i).getUserMailBox()+"");
pPhoneNumber.setText(userInfoList.get(i).getPhoneNumber()+"");
}else {
}
}
}
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View v) {
Intent intent = new Intent();
switch (v.getId()) {
case R.id.personal_left_iv_head_personal:
intent.setClass(PersonalleftActivity.this,PictureHeadActivity.class);
startActivity(intent);
finish();
// 先判断是否已经回收
if(btPersonalHead != null && !btPersonalHead.isRecycled()){
// 回收并且置为null
btPersonalHead.recycle();
btPersonalHead = null;
}
System.gc();
break;
case R.id.personal_left_iv_back_personal:
intent.setClass(PersonalleftActivity.this,MainActivity.class);
startActivity(intent);
finish();
// 先判断是否已经回收
if(btPersonalHead != null && !btPersonalHead.isRecycled()){
// 回收并且置为null
btPersonalHead.recycle();
btPersonalHead = null;
}
System.gc();
break;
case R.id.personal_left_tv_name_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑用户名(12字内)");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserName()+"");
}
}
//
dialogOut.setDialogContentLenght(12);
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,1));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,1));
dialogOut.show();
break;
case R.id.personal_left_layout_sexs_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑性别(男或女)");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserSexs()+"");
}
}
dialogOut.setDialogContentLenght(1);//长度
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,2));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,2));
dialogOut.show();
break;
case R.id.personal_left_layout_site_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑地址(省市县/区)");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserSite()+"");
}
}
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,3));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,3));
dialogOut.show();
break;
case R.id.personal_left_layout_intro_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑简介(30字内)");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserIntro()+"");
}
}
dialogOut.setDialogContentLenght(30);
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,4));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,4));
dialogOut.show();
break;
case R.id.personal_left_layout_school_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑学校");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserSchool()+"");
}
}
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,5));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,5));
dialogOut.show();
break;
case R.id.personal_left_layout_birthday_personal:
/* dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑生日(xxxx-x-x)");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserBirthday()+"");
}
}
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,6));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,6));
dialogOut.show();*/
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
monthofyear = calendar.get(Calendar.MONTH);
dayofMonth = calendar.get(Calendar.DAY_OF_MONTH);
dialogBirthday = new DatePickerDialog(this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int month = monthOfYear+1;
textBirthday = year+"-"+month+"-"+dayOfMonth+"";
userInfoList = new ArrayList<UserInfo>();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(textBirthday, sPreferences.getString("sn", ""), 6);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pBirthday.setText(userInfoList.get(i).getUserBirthday()+"");
}
}
}
}, year, monthofyear, dayofMonth);
dialogBirthday.show();
break;
case R.id.personal_left_layout_qq_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑QQ");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserQQ()+"");
}
}
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,7));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,7));
dialogOut.show();
break;
case R.id.personal_left_layout_mailbox_personal:
dialogOut = new PersonalleftDialog(mContext);
dialogOut.setTitleInCenter();
dialogOut.setDialogTitle("编辑邮箱");
dialogOut.setDialogTitleSize(R.dimen.x16);
dialogOut.setDialogTitleBacColor(R.color.bisque);
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = new ArrayList<UserInfo>();
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i<userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
dialogOut.setDialogContent(userInfoList.get(i).getUserMailBox()+"");
}
}
dialogOut.setLeftBtnListener(new LeftBtnClickListener(mContext,dialogOut,8));
dialogOut.setRightBtnListener(new RightBtnClickListener(mContext,dialogOut,8));
dialogOut.show();
break;
case R.id.personal_left_layout_phonenumber_personal:
userInfoList = new ArrayList<UserInfo>();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userInfoList = userinfoDH.getUserInfoList();
Intent intentPNumber = new Intent(PersonalleftActivity.this,PersonalleftAlterPhoneActivity.class);
startActivity(intentPNumber);
finish();
// 先判断是否已经回收
if(btPersonalHead != null && !btPersonalHead.isRecycled()){
// 回收并且置为null
btPersonalHead.recycle();
btPersonalHead = null;
}
System.gc();
break;
default:
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Intent intent = new Intent();
intent.setClass(PersonalleftActivity.this,MainActivity.class);
startActivity(intent);
finish();
// 先判断是否已经回收
if(btPersonalHead != null && !btPersonalHead.isRecycled()){
// 回收并且置为null
btPersonalHead.recycle();
btPersonalHead = null;
}
System.gc();
return false;
}
return super.onKeyDown(keyCode, event);
}
public class RightBtnClickListener implements OnClickListener{
private PersonalleftDialog dialog;
private int n;
private Context mContext;
public RightBtnClickListener(Context mContext,PersonalleftDialog dialog,int n) {
super();
this.mContext = mContext;
this.dialog = dialog;
this.n = n;
}
@Override
public void onClick(View v) {
// Utils.showToast(mContext, "点中了右边的按钮!");
switch (n) {
case 1:
if(dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(getApplicationContext(), "请输入用户名");
return;
}
userInfoList = new ArrayList<UserInfo>();
UserInfo userInfo1 = new UserInfo();
userInfo1.setUserName(dialog.getDialogContent());
String userName = dialog.getDialogContent()+"";
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(userName, sPreferences.getString("sn", ""), 1);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pName.setText(userInfoList.get(i).getUserName()+"");
}
}
mslList = new ArrayList<MySelfListing>();
goodsDHelper = new GoodsDataHelper(getApplicationContext());
mslList = goodsDHelper.getGoodsInfoList(sPreferences.getString("sn", ""),1);
if (mslList.size() != 0) {
for(int i = 0; i < mslList.size(); i++){
if (mslList.get(i).getStudentNumber().equals(sPreferences.getString("sn","")+"")) {
goodsDHelper.updateGoods(userName, null, sPreferences.getString("sn","")+"", 7);
}
}
}
dialog.dismiss();
break;
case 2:
if (dialog.getDialogContent().equals("男")||dialog.getDialogContent().equals("女")) {
userInfoList = new ArrayList<UserInfo>();
String usersexs = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(usersexs, sPreferences.getString("sn", ""), 2);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pSexs.setText(userInfoList.get(i).getUserSexs()+"");
}
}
dialog.dismiss();
}else {
Utils.showToast(mContext, "输出错误");
}
break;
case 3:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String usersite = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(usersite, sPreferences.getString("sn", ""), 3);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pSite.setText(userInfoList.get(i).getUserSite()+"");
}
}
dialog.dismiss();
break;
case 4:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String userintro = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(userintro, sPreferences.getString("sn", ""), 4);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pIntro.setText(userInfoList.get(i).getUserIntro()+"");
}
}
dialog.dismiss();
break;
case 5:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String userschool = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(userschool, sPreferences.getString("sn", ""), 5);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pSchool.setText(userInfoList.get(i).getUserSchool()+"");
}
}
dialog.dismiss();
break;
case 6:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String birthday = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(birthday, sPreferences.getString("sn", ""), 6);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pBirthday.setText(userInfoList.get(i).getUserBirthday()+"");
}
}
dialog.dismiss();
break;
case 7:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String qq = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(qq, sPreferences.getString("sn", ""), 7);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pQQ.setText(userInfoList.get(i).getUserQQ()+"");
}
}
dialog.dismiss();
break;
case 8:
String mailbox = dialog.getDialogContent();
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
if (isMailBox(mailbox)) {
userInfoList = new ArrayList<UserInfo>();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(mailbox, sPreferences.getString("sn", ""), 8);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pMailBox.setText(userInfoList.get(i).getUserMailBox()+"");
}
}
dialog.dismiss();
}else {
Utils.showToast(getApplicationContext(), "输入错误");
}
break;
case 9:
if (dialog.getDialogContent().equals("") || dialog.getDialogContent() == null){
Utils.showToast(mContext, "输出错误");
return;
}
userInfoList = new ArrayList<UserInfo>();
String phonenumber = dialog.getDialogContent();
userinfoDH = new UserInfoDataHelper(getApplicationContext());
userinfoDH.updateUserInfo(phonenumber, sPreferences.getString("sn", ""), 9);
userInfoList = userinfoDH.getUserInfoList();
for(int i = 0;i < userInfoList.size();i++){
if (userInfoList.get(i).getStudentNumber().equals(sPreferences.getString("sn", ""))) {
pPhoneNumber.setText(userInfoList.get(i).getPhoneNumber()+"");
}
}
dialog.dismiss();
break;
default:
break;
}
}
}
/*
* 验证邮箱
* */
private boolean isMailBox(String mail){
Pattern pattern = Pattern.compile("^[A-Za-z0-9][\\w\\._]*[a-zA-Z0-9]+@[A-Za-z0-9-_]+\\.([A-Za-z]{2,4})");
Matcher matcher = pattern.matcher(mail);
return matcher.matches();
}
}
| [
"bingbingyouk@163.com"
] | bingbingyouk@163.com |
15cfa30ed087f55ae0197117ec033586730b4f99 | 5343ec6a6e15acc908f79d64fa5f8fe841a84c24 | /src/main/java/com/mazdah/tillsixty/account/domain/UserRepository.java | c1f484a915746d3ee9bef7ce10d80f7a6285af86 | [] | no_license | mazdah/TillSixty | f0d724e23631c42602e5cf8f4e750a05bbfde2b4 | 9f02531861ee14ee4ba93359ac09a7384d17cce9 | refs/heads/master | 2021-01-10T23:29:35.231810 | 2017-01-19T15:17:03 | 2017-01-19T15:17:03 | 69,326,702 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 742 | java | package com.mazdah.tillsixty.account.domain;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface UserRepository extends MongoRepository<User, String> {
List<User> findByName(@Param("name") String name);
User findByUserIdAndPassword (@Param("userId") String userId, @Param("password") String password);
Long countByUserIdAndPassword (@Param("userId") String userId, @Param("password") String password);
Long countByUserId(@Param("userId") String userId);
Long countByProfileEmail(@Param("email") String email);
}
| [
"woohj70@gmail.com"
] | woohj70@gmail.com |
353af92120dd2f49730b826dcbe7119ff5a6cc01 | 0211bfadb42dc20099a70702252306f5edca5990 | /app/src/main/java/com/example/stpl/loyality_ui/Adapter/List_RedeemProduct.java | 77b3fe50d6e2a759c43c4051717a3c7b344c5eb1 | [] | no_license | maxanuj24/loyalty | 2ab84dd4a9d74c3beda1a53fcceb911f07d7ede3 | be4878f8db9a953a4541adf865dfaf655a23f72d | refs/heads/master | 2020-03-06T22:22:40.292656 | 2018-03-28T07:33:34 | 2018-03-28T07:33:34 | 127,101,638 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,334 | java | package com.example.stpl.loyality_ui.Adapter;
import android.content.Context;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Response;
import com.example.stpl.loyality_ui.R;
import com.example.stpl.loyality_ui.RecyclerViewListener;
import com.example.stpl.loyality_ui.bean.ProductData;
import java.util.ArrayList;
/**
* Created by stpl on 5/3/18.
*/
public class List_RedeemProduct extends RecyclerView.Adapter<List_RedeemProduct.MyViewHolder> implements CompoundButton.OnCheckedChangeListener{
private LayoutInflater inflater;
private ArrayList<ProductData> list_product;
Integer[] qty;
int Quantity;
int Code;
String Description,Message,ResponseMessage;
private RecyclerViewListener listener;
public List_RedeemProduct(Context context, ArrayList<ProductData> list_product, RecyclerViewListener listener) {
this.list_product = list_product;
inflater = LayoutInflater.from(context);
this.listener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_redeemable_items, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.d("log", "List position : " + position);
Log.d("log", "Selected values : " + list_product.get(position).getQuantity());
final ProductData l = list_product.get(position);
Quantity = list_product.get(position).getQuantity();
holder.text1.setText(l.getDisplayName() + "");
holder.text2.setText("Price :- "+l.getPrice() + "");
ResponseMessage = l.getRespMsg();
Message =l.getMessage();
Description =l.getDescription();
Code =l.getCode();
final Integer[] qty = setQty(Quantity);
ArrayAdapter<Integer> aa = new ArrayAdapter<Integer>(holder.quantity_spin.getContext(), android.R.layout.simple_spinner_item, qty);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.quantity_spin.setAdapter(aa);
holder.quantity_spin.setSelection(aa.getPosition((Integer) list_product.get(position).getSelected_qty()));
holder.parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener != null) {
listener.onItemClick(l);
}
}
});
}
@Override
public int getItemCount() {
return list_product.size();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView text1, text2, imgFilename;
public Spinner quantity_spin;
//public CheckBox checkBox;
public RelativeLayout parent;
public MyViewHolder(View itemView) {
super(itemView);
text1 = itemView.findViewById(R.id.name);
text2 = itemView.findViewById(R.id.price);
quantity_spin = itemView.findViewById(R.id.quantity_spin);
imgFilename = itemView.findViewById(R.id.e);
// checkBox = itemView.findViewById(R.id.checkBox);
parent = itemView.findViewById(R.id.parent);
/*
TextView code = (TextView) itemView.findViewById(R.id.code_buyProducts);
TextView description = (TextView)itemView.findViewById(R.id.description_buyProducts);
TextView message = (TextView) itemView.findViewById(R.id.message_buyProducts);
TextView respMessage=(TextView)itemView.findViewById(R.id.respMsg_buyProducts);
code.setText("Code : "+Code+"");
description.setText("Description : "+Description+"");
message.setText("Message : "+Message + "");
respMessage.setText("Reaponse Message : "+ ResponseMessage+"");
*/
//checkBox.setClickable(false);
quantity_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("log","getAdapterPosition() : "+getAdapterPosition());
Log.d("log","Value : "+(Integer) parent.getItemAtPosition(position));
list_product.get(getAdapterPosition()).setSelected_qty((Integer) parent.getItemAtPosition(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
private Integer[] setQty(int maxValue) {
qty = new Integer[maxValue+1];
for (int i = 0; i <= maxValue; i++) {
qty[i] = i;
}
return qty;
}
}
| [
"anuj1.jain@skilrock.com"
] | anuj1.jain@skilrock.com |
a6b78166d4c23e52203492feed72d9da4a3b6890 | 228d8fd3566cf1de3622a6752c0f43895a4cbda7 | /yufanshop/front/src/main/java/org/yufan/rest/service/ItemService.java | 3059442ca472955d2809da62b8bdde3b7c7778db | [] | no_license | Chaoyoushen/shop | da36aaeb6f0731d76fbb9d1c201894dfc465593b | 1ac81f194c6520a4826a9bd2744224b0e1a11ac9 | refs/heads/master | 2022-12-23T01:07:22.489596 | 2019-08-13T01:03:09 | 2019-08-13T01:03:09 | 144,550,199 | 1 | 0 | null | 2022-12-16T04:54:53 | 2018-08-13T08:22:29 | JavaScript | UTF-8 | Java | false | false | 370 | java | package org.yufan.rest.service;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.exception.MyException;
import java.io.IOException;
public interface ItemService {
public Item queryItemById(Long itemId) throws MyException,IOException;
public ItemDesc queryItemDescById(Long itemId) throws MyException,IOException;
}
| [
"yo1303512080@qq.com"
] | yo1303512080@qq.com |
95709a0680e7ec6f6cd124e0200f0ee063e6c47a | f9c8ec10e57e71202266b3faa780bf372b4e6671 | /src/main/java/pl/gregorymartin/b01/security/mapping/model/UserReadModel.java | d381e359ddc91af33d95534e984ad73bbff6c2bc | [] | no_license | vetomir/Photoblog-App | 58b8dd1a4daa112f53c772d793b7947cee3f1f27 | c4868b40e92bfb03d39a2fc4382f7453dcc3684f | refs/heads/master | 2023-02-18T00:22:45.527703 | 2020-10-12T19:38:25 | 2020-10-12T19:38:25 | 301,748,526 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package pl.gregorymartin.b01.security.mapping.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Setter
@Getter
@Builder
public
class UserReadModel {
private Long id;
private String name;
//email is username
private String email;
private String avatar;
private List<String> roles;
}
| [
"vetomir@gmail.com"
] | vetomir@gmail.com |
2e95f0c7f4890b10d9098092654ad4e9aebbebcb | 564ac2df8cfb90ff6174554eb71486ea5b3389cb | /src/main/java/org/drools/core/util/ClassUtils.java | 5d03edda588d5496d62b7049c32729e326235cd2 | [] | no_license | lgadawski/drools-core-with-db | e8066d6bde1879fa07b447be22ce2e6c8eb7a944 | fa883ccd2c712f80f72e663105bf667c2b8adbc0 | refs/heads/master | 2021-01-20T11:26:25.541000 | 2014-01-14T00:06:23 | 2014-01-14T00:06:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,376 | java | /*
* Copyright 2010 JBoss 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.drools.core.util;
import org.drools.common.DroolsObjectInputStream;
import org.drools.common.DroolsObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class ClassUtils {
private static Map<String, Class<?>> classes = Collections.synchronizedMap( new HashMap() );
private static final String STAR = "*";
public static boolean areNullSafeEquals(Object obj1, Object obj2) {
return obj1 == null ? obj2 == null : obj1.equals(obj2);
}
/**
* Please do not use - internal
* org/my/Class.xxx -> org.my.Class
*/
public static String convertResourceToClassName(final String pResourceName) {
return stripExtension(pResourceName).replace( '/', '.' );
}
/**
* Please do not use - internal
* org.my.Class -> org/my/Class.class
*/
public static String convertClassToResourcePath(final String pName) {
return pName.replace( '.',
'/' ) + ".class";
}
/**
* Please do not use - internal
* org/my/Class.xxx -> org/my/Class
*/
public static String stripExtension(final String pResourceName) {
final int i = pResourceName.lastIndexOf( '.' );
return pResourceName.substring( 0, i );
}
public static String toJavaCasing(final String pName) {
final char[] name = pName.toLowerCase().toCharArray();
name[0] = Character.toUpperCase( name[0] );
return new String( name );
}
public static String clazzName(final File base,
final File file) {
final int rootLength = base.getAbsolutePath().length();
final String absFileName = file.getAbsolutePath();
final int p = absFileName.lastIndexOf( '.' );
final String relFileName = absFileName.substring( rootLength + 1, p );
return relFileName.replace( File.separatorChar, '.' );
}
public static String relative(final File base,
final File file) {
final int rootLength = base.getAbsolutePath().length();
final String absFileName = file.getAbsolutePath();
return absFileName.substring( rootLength + 1 );
}
public static String canonicalName(Class clazz) {
StringBuilder name = new StringBuilder();
if ( clazz.isArray() ) {
name.append( canonicalName( clazz.getComponentType() ) );
name.append( "[]" );
} else if ( clazz.getDeclaringClass() == null ) {
name.append( clazz.getName() );
} else {
name.append( canonicalName( clazz.getDeclaringClass() ) );
name.append( "." );
name.append( clazz.getName().substring( clazz.getDeclaringClass().getName().length() + 1 ) );
}
return name.toString();
}
public static Object instantiateObject(String className) {
return instantiateObject( className,
null );
}
/**
* This method will attempt to create an instance of the specified Class. It uses
* a syncrhonized HashMap to cache the reflection Class lookup.
* @param className
* @return
*/
public static Object instantiateObject(String className,
ClassLoader classLoader) {
Class cls = (Class) classes.get( className );
if ( cls == null ) {
try {
cls = Class.forName( className );
} catch ( Exception e ) {
//swallow
}
//ConfFileFinder
if ( cls == null && classLoader != null ) {
try {
cls = classLoader.loadClass( className );
} catch ( Exception e ) {
//swallow
}
}
if ( cls == null ) {
try {
cls = ClassUtils.class.getClassLoader().loadClass( className );
} catch ( Exception e ) {
//swallow
}
}
if ( cls == null ) {
try {
cls = Thread.currentThread().getContextClassLoader().loadClass( className );
} catch ( Exception e ) {
//swallow
}
}
if ( cls == null ) {
try {
cls = ClassLoader.getSystemClassLoader().loadClass( className );
} catch ( Exception e ) {
//swallow
}
}
if ( cls != null ) {
classes.put( className, cls );
} else {
throw new RuntimeException( "Unable to load class '" + className + "'" );
}
}
Object object;
try {
object = cls.newInstance();
} catch ( Throwable e ) {
throw new RuntimeException( "Unable to instantiate object for class '" + className + "'",
e );
}
return object;
}
/**
* Populates the import style pattern map from give comma delimited string
* @param patterns
* @param str
*/
public static void addImportStylePatterns(Map<String, Object> patterns,
String str) {
if ( str == null || "".equals( str.trim() ) ) {
return;
}
String[] items = str.split( " " );
for (String item : items) {
String qualifiedNamespace = item.substring(0,
item.lastIndexOf('.')).trim();
String name = item.substring(item.lastIndexOf('.') + 1).trim();
Object object = patterns.get(qualifiedNamespace);
if (object == null) {
if (STAR.equals(name)) {
patterns.put(qualifiedNamespace,
STAR);
} else {
// create a new list and add it
List<String> list = new ArrayList<String>();
list.add(name);
patterns.put(qualifiedNamespace, list);
}
} else if (name.equals(STAR)) {
// if its a STAR now add it anyway, we don't care if it was a STAR or a List before
patterns.put(qualifiedNamespace, STAR);
} else {
// its a list so add it if it doesn't already exist
List<String> list = (List<String>) object;
if (!list.contains(name)) {
list.add(name);
}
}
}
}
/**
* Determines if a given full qualified class name matches any import style patterns.
* @param patterns
* @param className
* @return
*/
public static boolean isMatched(Map<String, Object> patterns,
String className) {
// Array [] object class names are "[x", where x is the first letter of the array type
// -> NO '.' in class name, thus!
// see http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getName%28%29
String qualifiedNamespace = className;
String name = className;
if( className.indexOf('.') > 0 ) {
qualifiedNamespace = className.substring( 0, className.lastIndexOf( '.' ) ).trim();
name = className.substring( className.lastIndexOf( '.' ) + 1 ).trim();
}
else if( className.indexOf('[') == 0 ) {
qualifiedNamespace = className.substring(0, className.lastIndexOf('[') );
}
Object object = patterns.get( qualifiedNamespace );
if ( object == null ) {
return true;
} else if ( STAR.equals( object ) ) {
return false;
} else if ( patterns.containsKey( "*" ) ) {
// for now we assume if the name space is * then we have a catchall *.* pattern
return true;
} else {
List list = (List) object;
return !list.contains( name );
}
}
/**
* Extracts the package name from the given class object
* @param cls
* @return
*/
public static String getPackage(Class<?> cls) {
// cls.getPackage() sometimes returns null, in which case fall back to string massaging.
java.lang.Package pkg = cls.isArray() ? cls.getComponentType().getPackage() : cls.getPackage();
if ( pkg == null ) {
int dotPos;
int dolPos = cls.getName().indexOf( '$' );
if ( dolPos > 0 ) {
// we have nested classes, so adjust dotpos to before first $
dotPos = cls.getName().substring( 0, dolPos ).lastIndexOf( '.' );
} else {
dotPos = cls.getName().lastIndexOf( '.' );
}
if ( dotPos > 0 ) {
return cls.getName().substring( 0,
dotPos );
} else {
// must be default package.
return "";
}
} else {
return pkg.getName();
}
}
public static Class<?> findClass(String name, Collection<String> availableImports, ClassLoader cl) {
Class<?> clazz = null;
for (String imp : availableImports) {
String className = imp.endsWith(name) ? imp : imp + "." + name;
clazz = findClass(className, cl);
if (clazz != null) {
break;
}
}
return clazz;
}
public static Class<?> findClass(String className, ClassLoader cl) {
try {
return Class.forName(className, false, cl);
} catch (ClassNotFoundException e) {
int lastDot = className.lastIndexOf('.');
className = className.substring(0, lastDot) + "$" + className.substring(lastDot+1);
try {
return Class.forName(className, false, cl);
} catch (ClassNotFoundException e1) { }
}
return null;
}
public static List<String> getSettableProperties(Class<?> clazz) {
List<String> settableProperties = new ArrayList<String>();
for (Method m : clazz.getMethods()) {
if (m.getParameterTypes().length == 1) {
String propName = setter2property(m.getName());
if (propName != null) {
settableProperties.add(propName);
}
}
}
for (Field f : clazz.getFields()) {
String fieldName = f.getName();
if (!settableProperties.contains(fieldName)) {
settableProperties.add(fieldName);
}
}
Collections.sort(settableProperties);
return settableProperties;
}
public static String getter2property(String methodName) {
if (methodName.startsWith("get") && methodName.length() > 3) {
return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
}
if (methodName.startsWith("is") && methodName.length() > 2) {
return Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);
}
return null;
}
public static String setter2property(String methodName) {
if (!methodName.startsWith("set") || methodName.length() < 4) {
return null;
}
return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
}
public static <T extends Externalizable> T deepClone(T origin) {
return origin == null ? null : deepClone(origin, origin.getClass().getClassLoader());
}
public static <T extends Externalizable> T deepClone(T origin, ClassLoader classLoader) {
if (origin == null) {
return null;
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new DroolsObjectOutputStream(baos);
oos.writeObject(origin);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new DroolsObjectInputStream(bais, classLoader);
Object deepCopy = ois.readObject();
return (T)deepCopy;
} catch(IOException ioe) {
throw new RuntimeException(ioe);
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
}
public static Class<?> convertFromPrimitiveType(Class<?> type) {
if (!type.isPrimitive()) return type;
if (type == int.class) return Integer.class;
if (type == long.class) return Long.class;
if (type == float.class) return Float.class;
if (type == double.class) return Double.class;
if (type == short.class) return Short.class;
if (type == byte.class) return Byte.class;
if (type == char.class) return Character.class;
if (type == boolean.class) return Boolean.class;
throw new RuntimeException("Class not convertible from primitive: " + type.getName());
}
public static Class<?> convertToPrimitiveType(Class<?> type) {
if (type.isPrimitive()) return type;
if (type == Integer.class) return int.class;
if (type == Long.class) return long.class;
if (type == Float.class) return float.class;
if (type == Double.class) return double.class;
if (type == Short.class) return short.class;
if (type == Byte.class) return byte.class;
if (type == Character.class) return char.class;
if (type == Boolean.class) return boolean.class;
if (type == BigInteger.class) return long.class;
if (type == BigDecimal.class) return double.class;
if (type == Number.class) return double.class;
throw new RuntimeException("Class not convertible to primitive: " + type.getName());
}
public static boolean isWindows() {
String os = System.getProperty("os.name");
return os.toUpperCase().contains( "WINDOWS" );
}
public static boolean isOSX() {
String os = System.getProperty("os.name");
return os.toUpperCase().contains( "MAC OS X" );
}
}
| [
"l.gadawski@gmail.com"
] | l.gadawski@gmail.com |
cb87f9460a4820e1a27fb6325bccc41f00293467 | b68c35b4f034c608fd43758699a0fab11805cf35 | /Proyecto/ProyectoADOO/src/java/Control/ControlSesiones.java | f69bbb687f9286ac0bc1e06abe72285cc45a4d20 | [] | no_license | EMIGonH123/ProyectoADOO | 2c301cbee56cfec7cc614b2ca7bd0eb3a6c3e224 | 991f5bd146a112c984b5967013950e4c38da4f83 | refs/heads/master | 2020-03-17T22:02:56.913299 | 2018-06-06T19:39:06 | 2018-06-06T19:39:06 | 133,986,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,878 | java | package Control;
import EntidadesADOO.*;
import Modelos.ServicioSesionesLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ControlSesiones", urlPatterns = {"/ControlSesiones.do"})
public class ControlSesiones extends HttpServlet {
@EJB
private ServicioSesionesLocal servicio;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException , EJBException{
String val = request.getParameter("btnControlador");
switch(val){
case "inicioSesionSucursal":
inicioSesionSucursal(request, response);
break;
case "inicioSesionProveedorAuto":
inicioSesionProveedorAuto(request, response);
break;
case "visitarSucursal":
inicioSesionSucursal(request, response);
break;
case "verClienteDesdeCrud":
inicioSesionCliente(request, response);
break;
//
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException , EJBException{
String val = request.getParameter("btnControlador");
switch(val){
case "inicioSesionEmpleado":
inicioSesionEmpleado(request, response);
break;
case "inicioSesionCliente":
inicioSesionCliente(request, response);
break;
case "inicioSesionAdmin":
inicioSesionAdmin(request, response);
break;
}
}
/****************************/
/* INICIO DE SESIONES INDEX */
/****************************/
protected void inicioSesionProveedorAuto(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException,EJBException,PersistenceException {
int idProveedor = (int)Integer.parseInt(request.getParameter("idProveedor"));
int idSucursal = (int)Integer.parseInt(request.getParameter("idSucursal"));
Sucursal sucursal = servicio.buscarSucursal(idSucursal);
Proveedor proveedor = servicio.inicioSesionProveedor(idProveedor);
if(proveedor != null && sucursal != null){
request.getSession().setAttribute("proveedor",proveedor);
request.getSession().setAttribute("sucursal", sucursal);
switch(idProveedor){
case 1:
response.sendRedirect("autosVolkswagen.jsp");
break;
case 2:
response.sendRedirect("autosFord.jsp");
break;
case 3:
response.sendRedirect("autosVolvo.jsp");
break;
case 4:
response.sendRedirect("autosNissan.jsp");
break;
case 5:
response.sendRedirect("autosToyota.jsp");
break;
case 6:
response.sendRedirect("autosRenault.jsp");
break;
case 7:
response.sendRedirect("autosHyundai.jsp");
break;
case 8:
response.sendRedirect("autosKIA.jsp");
break;
case 9:
response.sendRedirect("autosSeat.jsp");
break;
}
}else{
request.setAttribute("msgRespuesta","No existe el usuario");
request.getRequestDispatcher("sucursales.jsp").forward(request, response);
}
}
protected void inicioSesionAdmin(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException,EJBException,PersistenceException {
int id = (int)Integer.parseInt(request.getParameter("idAdmin"));
String pass = (String)request.getParameter("pass");
Empleadorenta empleado = servicio.iniciaSesionEmpleado(id, pass);
if(empleado != null){
request.getSession().setAttribute("empleado",empleado);
response.sendRedirect("fragmentaciones.jsp");
}else{
request.setAttribute("msgRespuesta","No existe el usuario");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
protected void inicioSesionSucursal(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException,EJBException,PersistenceException {
int idSucursal = (int)Integer.parseInt(request.getParameter("idSucursal"));
Sucursal sucursal = servicio.buscarSucursal(idSucursal);
if(sucursal != null){
request.getSession().setAttribute("sucursal",sucursal);
response.sendRedirect("sucursales.jsp");
}else{
request.setAttribute("msgRespuesta","No existe el usuario");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
protected void inicioSesionEmpleado(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException,EJBException,PersistenceException {
if(request.getParameter("idEmpleado").equals("") || request.getParameter("pass").equals("") ){
request.setAttribute("msgRespuesta","Campos incompletos");
request.getRequestDispatcher("index.jsp").forward(request,response);
}else{
int id = (int)Integer.parseInt(request.getParameter("idEmpleado"));
String pass = (String)request.getParameter("pass");
Empleadorenta empleado = servicio.iniciaSesionEmpleado(id, pass);
if(empleado != null){
if(empleado.getIdTipoEmpleado()==1){
request.getSession().setAttribute("empleado",empleado);
response.sendRedirect("administrador.jsp");
}else{
request.getSession().setAttribute("empleado",empleado);
response.sendRedirect("empleado.jsp");
}
}else{
request.setAttribute("msgRespuesta","No existe el usuario");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
protected void inicioSesionCliente(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException,EJBException,PersistenceException {
if(request.getParameter("idCliente").equals("") || request.getParameter("pass").equals("") ){
request.setAttribute("msgRespuesta","Campos incompletos");
request.getRequestDispatcher("index.jsp").forward(request,response);
}else{
int id = Integer.parseInt(request.getParameter("idCliente"));
String pass = request.getParameter("pass");
Clienterenta cliente = servicio.iniciaSesionCliente(id, pass);
if(cliente != null){
request.getSession().setAttribute("cliente",cliente);
response.sendRedirect("cliente.jsp");
}else{
request.setAttribute("msgRespuesta","No existe el usuario");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
}
| [
"metalica.el.01@gmail.com"
] | metalica.el.01@gmail.com |
113c7b7848046ceb8e6ef6fc0b2981fce1a5cfae | 651f0594c94a2980114825ff06c85357c122bbd2 | /dexter/src/main/java/android/support/v7ox/widget/SearchView.java | f4fdd64f80f672c22c6e4daaf9e87cdbcd4d69af | [
"Apache-2.0"
] | permissive | asvgithub01/Dexter | 18a72aa56497ec0eb5699f3558fec7dd9f6f6a94 | 97b965d1e7aef4a356588e3d978b51832af3ddd4 | refs/heads/master | 2022-11-16T00:06:29.529153 | 2016-10-04T10:05:54 | 2016-10-04T10:05:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72,897 | java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7ox.widget;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.ResultReceiver;
import android.speech.RecognizerIntent;
import android.support.v4ox.view.KeyEventCompat;
import android.support.v4ox.widget.CursorAdapter;
//import android.support.v7ox.appcompat.R;
import com.karumi.dexterox.R;
import android.support.v7ox.view.CollapsibleActionView;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import java.lang.reflect.Method;
import java.util.WeakHashMap;
/**
* A widget that provides a user interface for the user to enter a search query and submit a request
* to a search provider. Shows a list of query suggestions or results, if available, and allows the
* user to pick a suggestion or result to launch into.
*
* <p class="note"><strong>Note:</strong> This class is included in the <a
* href="{@docRoot}tools/extras/support-library.html">support library</a> for compatibility
* with API level 7 and higher. If you're developing your app for API level 11 and higher
* <em>only</em>, you should instead use the framework {@link android.widget.SearchView} class.</p>
*
* <p>
* When the SearchView is used in an {@link android.support.v7ox.app.ActionBar}
* as an action view, it's collapsed by default, so you must provide an icon for the action.
* </p>
* <p>
* If you want the search field to always be visible, then call
* {@link #setIconifiedByDefault(boolean) setIconifiedByDefault(false)}.
* </p>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about using {@code SearchView}, read the
* <a href="{@docRoot}guide/topics/search/index.html">Search</a> API guide.
* Additional information about action views is also available in the <<a
* href="{@docRoot}guide/topics/ui/actionbar.html#ActionView">Action Bar</a> API guide</p>
* </div>
*
* @see android.support.v4.view.MenuItemCompat#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
*/
public class SearchView extends LinearLayoutCompat implements CollapsibleActionView {
private static final boolean DBG = false;
private static final String LOG_TAG = "SearchView";
private static final boolean IS_AT_LEAST_FROYO = Build.VERSION.SDK_INT >= 8;
/**
* Private constant for removing the microphone in the keyboard.
*/
private static final String IME_OPTION_NO_MICROPHONE = "nm";
private final SearchAutoComplete mSearchSrcTextView;
private final View mSearchEditFrame;
private final View mSearchPlate;
private final View mSubmitArea;
private final ImageView mSearchButton;
private final ImageView mGoButton;
private final ImageView mCloseButton;
private final ImageView mVoiceButton;
private final View mDropDownAnchor;
/** Icon optionally displayed when the SearchView is collapsed. */
private final ImageView mCollapsedIcon;
/** Drawable used as an EditText hint. */
private final Drawable mSearchHintIcon;
// Resources used by SuggestionsAdapter to display suggestions.
private final int mSuggestionRowLayout;
private final int mSuggestionCommitIconResId;
// Intents used for voice searching.
private final Intent mVoiceWebSearchIntent;
private final Intent mVoiceAppSearchIntent;
private final CharSequence mDefaultQueryHint;
private OnQueryTextListener mOnQueryChangeListener;
private OnCloseListener mOnCloseListener;
private OnFocusChangeListener mOnQueryTextFocusChangeListener;
private OnSuggestionListener mOnSuggestionListener;
private OnClickListener mOnSearchClickListener;
private boolean mIconifiedByDefault;
private boolean mIconified;
private CursorAdapter mSuggestionsAdapter;
private boolean mSubmitButtonEnabled;
private CharSequence mQueryHint;
private boolean mQueryRefinement;
private boolean mClearingFocus;
private int mMaxWidth;
private boolean mVoiceButtonEnabled;
private CharSequence mOldQueryText;
private CharSequence mUserQuery;
private boolean mExpandedInActionView;
private int mCollapsedImeOptions;
private SearchableInfo mSearchable;
private Bundle mAppSearchData;
private final AppCompatDrawableManager mDrawableManager;
static final AutoCompleteTextViewReflector HIDDEN_METHOD_INVOKER = new AutoCompleteTextViewReflector();
/*
* SearchView can be set expanded before the IME is ready to be shown during
* initial UI setup. The show operation is asynchronous to account for this.
*/
private Runnable mShowImeRunnable = new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
HIDDEN_METHOD_INVOKER.showSoftInputUnchecked(imm, SearchView.this, 0);
}
}
};
private final Runnable mUpdateDrawableStateRunnable = new Runnable() {
public void run() {
updateFocusedState();
}
};
private Runnable mReleaseCursorRunnable = new Runnable() {
public void run() {
if (mSuggestionsAdapter != null && mSuggestionsAdapter instanceof SuggestionsAdapter) {
mSuggestionsAdapter.changeCursor(null);
}
}
};
// A weak map of drawables we've gotten from other packages, so we don't load them
// more than once.
private final WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache =
new WeakHashMap<String, Drawable.ConstantState>();
/**
* Callbacks for changes to the query text.
*/
public interface OnQueryTextListener {
/**
* Called when the user submits the query. This could be due to a key press on the
* keyboard or due to pressing a submit button.
* The listener can override the standard behavior by returning true
* to indicate that it has handled the submit request. Otherwise return false to
* let the SearchView handle the submission by launching any associated intent.
*
* @param query the query text that is to be submitted
*
* @return true if the query has been handled by the listener, false to let the
* SearchView perform the default action.
*/
boolean onQueryTextSubmit(String query);
/**
* Called when the query text is changed by the user.
*
* @param newText the new content of the query text field.
*
* @return false if the SearchView should perform the default action of showing any
* suggestions if available, true if the action was handled by the listener.
*/
boolean onQueryTextChange(String newText);
}
public interface OnCloseListener {
/**
* The user is attempting to close the SearchView.
*
* @return true if the listener wants to override the default behavior of clearing the
* text field and dismissing it, false otherwise.
*/
boolean onClose();
}
/**
* Callback interface for selection events on suggestions. These callbacks
* are only relevant when a SearchableInfo has been specified by {@link #setSearchableInfo}.
*/
public interface OnSuggestionListener {
/**
* Called when a suggestion was selected by navigating to it.
* @param position the absolute position in the list of suggestions.
*
* @return true if the listener handles the event and wants to override the default
* behavior of possibly rewriting the query based on the selected item, false otherwise.
*/
boolean onSuggestionSelect(int position);
/**
* Called when a suggestion was clicked.
* @param position the absolute position of the clicked item in the list of suggestions.
*
* @return true if the listener handles the event and wants to override the default
* behavior of launching any intent or submitting a search query specified on that item.
* Return false otherwise.
*/
boolean onSuggestionClick(int position);
}
public SearchView(Context context) {
this(context, null);
}
public SearchView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.searchViewStyle_ox);
}
public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mDrawableManager = AppCompatDrawableManager.get();
final TintTypedArray a = TintTypedArray.obtainStyledAttributes(context,
attrs, R.styleable.SearchView, defStyleAttr, 0);
final LayoutInflater inflater = LayoutInflater.from(context);
final int layoutResId = a.getResourceId(
R.styleable.SearchView_layout, R.layout.abc_search_view);
inflater.inflate(layoutResId, this, true);
mSearchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text);
mSearchSrcTextView.setSearchView(this);
mSearchEditFrame = findViewById(R.id.search_edit_frame);
mSearchPlate = findViewById(R.id.search_plate);
mSubmitArea = findViewById(R.id.submit_area);
mSearchButton = (ImageView) findViewById(R.id.search_button);
mGoButton = (ImageView) findViewById(R.id.search_go_btn);
mCloseButton = (ImageView) findViewById(R.id.search_close_btn);
mVoiceButton = (ImageView) findViewById(R.id.search_voice_btn);
mCollapsedIcon = (ImageView) findViewById(R.id.search_mag_icon);
// Set up icons and backgrounds.
mSearchPlate.setBackgroundDrawable(a.getDrawable(R.styleable.SearchView_queryBackground));
mSubmitArea.setBackgroundDrawable(a.getDrawable(R.styleable.SearchView_submitBackground));
mSearchButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_searchIcon));
mGoButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_goIcon));
mCloseButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_closeIcon));
mVoiceButton.setImageDrawable(a.getDrawable(R.styleable.SearchView_voiceIcon));
mCollapsedIcon.setImageDrawable(a.getDrawable(R.styleable.SearchView_searchIcon));
mSearchHintIcon = a.getDrawable(R.styleable.SearchView_searchHintIcon);
// Extract dropdown layout resource IDs for later use.
mSuggestionRowLayout = a.getResourceId(R.styleable.SearchView_suggestionRowLayout,
R.layout.abc_search_dropdown_item_icons_2line);
mSuggestionCommitIconResId = a.getResourceId(R.styleable.SearchView_commitIcon, 0);
mSearchButton.setOnClickListener(mOnClickListener);
mCloseButton.setOnClickListener(mOnClickListener);
mGoButton.setOnClickListener(mOnClickListener);
mVoiceButton.setOnClickListener(mOnClickListener);
mSearchSrcTextView.setOnClickListener(mOnClickListener);
mSearchSrcTextView.addTextChangedListener(mTextWatcher);
mSearchSrcTextView.setOnEditorActionListener(mOnEditorActionListener);
mSearchSrcTextView.setOnItemClickListener(mOnItemClickListener);
mSearchSrcTextView.setOnItemSelectedListener(mOnItemSelectedListener);
mSearchSrcTextView.setOnKeyListener(mTextKeyListener);
// Inform any listener of focus changes
mSearchSrcTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (mOnQueryTextFocusChangeListener != null) {
mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus);
}
}
});
setIconifiedByDefault(a.getBoolean(R.styleable.SearchView_iconifiedByDefault, true));
final int maxWidth = a.getDimensionPixelSize(R.styleable.SearchView_android_maxWidth, -1);
if (maxWidth != -1) {
setMaxWidth(maxWidth);
}
mDefaultQueryHint = a.getText(R.styleable.SearchView_defaultQueryHint);
mQueryHint = a.getText(R.styleable.SearchView_queryHint);
final int imeOptions = a.getInt(R.styleable.SearchView_android_imeOptions, -1);
if (imeOptions != -1) {
setImeOptions(imeOptions);
}
final int inputType = a.getInt(R.styleable.SearchView_android_inputType, -1);
if (inputType != -1) {
setInputType(inputType);
}
boolean focusable = true;
focusable = a.getBoolean(R.styleable.SearchView_android_focusable, focusable);
setFocusable(focusable);
a.recycle();
// Save voice intent for later queries/launching
mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
mVoiceWebSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mVoiceAppSearchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mDropDownAnchor = findViewById(mSearchSrcTextView.getDropDownAnchor());
if (mDropDownAnchor != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
addOnLayoutChangeListenerToDropDownAnchorSDK11();
} else {
addOnLayoutChangeListenerToDropDownAnchorBase();
}
}
updateViewsVisibility(mIconifiedByDefault);
updateQueryHint();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void addOnLayoutChangeListenerToDropDownAnchorSDK11() {
mDropDownAnchor.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
adjustDropDownSizeAndPosition();
}
});
}
private void addOnLayoutChangeListenerToDropDownAnchorBase() {
mDropDownAnchor.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
adjustDropDownSizeAndPosition();
}
});
}
int getSuggestionRowLayout() {
return mSuggestionRowLayout;
}
int getSuggestionCommitIconResId() {
return mSuggestionCommitIconResId;
}
/**
* Sets the SearchableInfo for this SearchView. Properties in the SearchableInfo are used
* to display labels, hints, suggestions, create intents for launching search results screens
* and controlling other affordances such as a voice button.
*
* @param searchable a SearchableInfo can be retrieved from the SearchManager, for a specific
* activity or a global search provider.
*/
public void setSearchableInfo(SearchableInfo searchable) {
mSearchable = searchable;
if (mSearchable != null) {
if (IS_AT_LEAST_FROYO) {
updateSearchAutoComplete();
}
updateQueryHint();
}
// Cache the voice search capability
mVoiceButtonEnabled = IS_AT_LEAST_FROYO && hasVoiceSearch();
if (mVoiceButtonEnabled) {
// Disable the microphone on the keyboard, as a mic is displayed near the text box
// TODO: use imeOptions to disable voice input when the new API will be available
mSearchSrcTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE);
}
updateViewsVisibility(isIconified());
}
/**
* Sets the APP_DATA for legacy SearchDialog use.
* @param appSearchData bundle provided by the app when launching the search dialog
* @hide
*/
public void setAppSearchData(Bundle appSearchData) {
mAppSearchData = appSearchData;
}
/**
* Sets the IME options on the query text field.
*
* @see TextView#setImeOptions(int)
* @param imeOptions the options to set on the query text field
*/
public void setImeOptions(int imeOptions) {
mSearchSrcTextView.setImeOptions(imeOptions);
}
/**
* Returns the IME options set on the query text field.
* @return the ime options
* @see TextView#setImeOptions(int)
*/
public int getImeOptions() {
return mSearchSrcTextView.getImeOptions();
}
/**
* Sets the input type on the query text field.
*
* @see TextView#setInputType(int)
* @param inputType the input type to set on the query text field
*/
public void setInputType(int inputType) {
mSearchSrcTextView.setInputType(inputType);
}
/**
* Returns the input type set on the query text field.
* @return the input type
*/
public int getInputType() {
return mSearchSrcTextView.getInputType();
}
/** @hide */
@Override
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
// Don't accept focus if in the middle of clearing focus
if (mClearingFocus) return false;
// Check if SearchView is focusable.
if (!isFocusable()) return false;
// If it is not iconified, then give the focus to the text field
if (!isIconified()) {
boolean result = mSearchSrcTextView.requestFocus(direction, previouslyFocusedRect);
if (result) {
updateViewsVisibility(false);
}
return result;
} else {
return super.requestFocus(direction, previouslyFocusedRect);
}
}
/** @hide */
@Override
public void clearFocus() {
mClearingFocus = true;
setImeVisibility(false);
super.clearFocus();
mSearchSrcTextView.clearFocus();
mClearingFocus = false;
}
/**
* Sets a listener for user actions within the SearchView.
*
* @param listener the listener object that receives callbacks when the user performs
* actions in the SearchView such as clicking on buttons or typing a query.
*/
public void setOnQueryTextListener(OnQueryTextListener listener) {
mOnQueryChangeListener = listener;
}
/**
* Sets a listener to inform when the user closes the SearchView.
*
* @param listener the listener to call when the user closes the SearchView.
*/
public void setOnCloseListener(OnCloseListener listener) {
mOnCloseListener = listener;
}
/**
* Sets a listener to inform when the focus of the query text field changes.
*
* @param listener the listener to inform of focus changes.
*/
public void setOnQueryTextFocusChangeListener(OnFocusChangeListener listener) {
mOnQueryTextFocusChangeListener = listener;
}
/**
* Sets a listener to inform when a suggestion is focused or clicked.
*
* @param listener the listener to inform of suggestion selection events.
*/
public void setOnSuggestionListener(OnSuggestionListener listener) {
mOnSuggestionListener = listener;
}
/**
* Sets a listener to inform when the search button is pressed. This is only
* relevant when the text field is not visible by default. Calling {@link #setIconified
* setIconified(false)} can also cause this listener to be informed.
*
* @param listener the listener to inform when the search button is clicked or
* the text field is programmatically de-iconified.
*/
public void setOnSearchClickListener(OnClickListener listener) {
mOnSearchClickListener = listener;
}
/**
* Returns the query string currently in the text field.
*
* @return the query string
*/
public CharSequence getQuery() {
return mSearchSrcTextView.getText();
}
/**
* Sets a query string in the text field and optionally submits the query as well.
*
* @param query the query string. This replaces any query text already present in the
* text field.
* @param submit whether to submit the query right now or only update the contents of
* text field.
*/
public void setQuery(CharSequence query, boolean submit) {
mSearchSrcTextView.setText(query);
if (query != null) {
mSearchSrcTextView.setSelection(mSearchSrcTextView.length());
mUserQuery = query;
}
// If the query is not empty and submit is requested, submit the query
if (submit && !TextUtils.isEmpty(query)) {
onSubmitQuery();
}
}
/**
* Sets the hint text to display in the query text field. This overrides
* any hint specified in the {@link SearchableInfo}.
* <p>
* This value may be specified as an empty string to prevent any query hint
* from being displayed.
*
* @param hint the hint text to display or {@code null} to clear
*/
public void setQueryHint(CharSequence hint) {
mQueryHint = hint;
updateQueryHint();
}
/**
* Returns the hint text that will be displayed in the query text field.
* <p>
* The displayed query hint is chosen in the following order:
* <ol>
* <li>Non-null value set with {@link #setQueryHint(CharSequence)}
* <li>Value specified in XML using {@code app:queryHint}
* <li>Valid string resource ID exposed by the {@link SearchableInfo} via
* {@link SearchableInfo#getHintId()}
* <li>Default hint provided by the theme against which the view was
* inflated
* </ol>
*
* @return the displayed query hint text, or {@code null} if none set
*/
public CharSequence getQueryHint() {
final CharSequence hint;
if (mQueryHint != null) {
hint = mQueryHint;
} else if (IS_AT_LEAST_FROYO && mSearchable != null && mSearchable.getHintId() != 0) {
hint = getContext().getText(mSearchable.getHintId());
} else {
hint = mDefaultQueryHint;
}
return hint;
}
/**
* Sets the default or resting state of the search field. If true, a single search icon is
* shown by default and expands to show the text field and other buttons when pressed. Also,
* if the default state is iconified, then it collapses to that state when the close button
* is pressed. Changes to this property will take effect immediately.
*
* <p>The default value is true.</p>
*
* @param iconified whether the search field should be iconified by default
*/
public void setIconifiedByDefault(boolean iconified) {
if (mIconifiedByDefault == iconified) return;
mIconifiedByDefault = iconified;
updateViewsVisibility(iconified);
updateQueryHint();
}
/**
* Returns the default iconified state of the search field.
* @return
*/
public boolean isIconfiedByDefault() {
return mIconifiedByDefault;
}
/**
* Iconifies or expands the SearchView. Any query text is cleared when iconified. This is
* a temporary state and does not override the default iconified state set by
* {@link #setIconifiedByDefault(boolean)}. If the default state is iconified, then
* a false here will only be valid until the user closes the field. And if the default
* state is expanded, then a true here will only clear the text field and not close it.
*
* @param iconify a true value will collapse the SearchView to an icon, while a false will
* expand it.
*/
public void setIconified(boolean iconify) {
if (iconify) {
onCloseClicked();
} else {
onSearchClicked();
}
}
/**
* Returns the current iconified state of the SearchView.
*
* @return true if the SearchView is currently iconified, false if the search field is
* fully visible.
*/
public boolean isIconified() {
return mIconified;
}
/**
* Enables showing a submit button when the query is non-empty. In cases where the SearchView
* is being used to filter the contents of the current activity and doesn't launch a separate
* results activity, then the submit button should be disabled.
*
* @param enabled true to show a submit button for submitting queries, false if a submit
* button is not required.
*/
public void setSubmitButtonEnabled(boolean enabled) {
mSubmitButtonEnabled = enabled;
updateViewsVisibility(isIconified());
}
/**
* Returns whether the submit button is enabled when necessary or never displayed.
*
* @return whether the submit button is enabled automatically when necessary
*/
public boolean isSubmitButtonEnabled() {
return mSubmitButtonEnabled;
}
/**
* Specifies if a query refinement button should be displayed alongside each suggestion
* or if it should depend on the flags set in the individual items retrieved from the
* suggestions provider. Clicking on the query refinement button will replace the text
* in the query text field with the text from the suggestion. This flag only takes effect
* if a SearchableInfo has been specified with {@link #setSearchableInfo(SearchableInfo)}
* and not when using a custom adapter.
*
* @param enable true if all items should have a query refinement button, false if only
* those items that have a query refinement flag set should have the button.
*
* @see SearchManager#SUGGEST_COLUMN_FLAGS
* @see SearchManager#FLAG_QUERY_REFINEMENT
*/
public void setQueryRefinementEnabled(boolean enable) {
mQueryRefinement = enable;
if (mSuggestionsAdapter instanceof SuggestionsAdapter) {
((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
enable ? SuggestionsAdapter.REFINE_ALL : SuggestionsAdapter.REFINE_BY_ENTRY);
}
}
/**
* Returns whether query refinement is enabled for all items or only specific ones.
* @return true if enabled for all items, false otherwise.
*/
public boolean isQueryRefinementEnabled() {
return mQueryRefinement;
}
/**
* You can set a custom adapter if you wish. Otherwise the default adapter is used to
* display the suggestions from the suggestions provider associated with the SearchableInfo.
*
* @see #setSearchableInfo(SearchableInfo)
*/
public void setSuggestionsAdapter(CursorAdapter adapter) {
mSuggestionsAdapter = adapter;
mSearchSrcTextView.setAdapter(mSuggestionsAdapter);
}
/**
* Returns the adapter used for suggestions, if any.
* @return the suggestions adapter
*/
public CursorAdapter getSuggestionsAdapter() {
return mSuggestionsAdapter;
}
/**
* Makes the view at most this many pixels wide
*/
public void setMaxWidth(int maxpixels) {
mMaxWidth = maxpixels;
requestLayout();
}
/**
* Gets the specified maximum width in pixels, if set. Returns zero if
* no maximum width was specified.
* @return the maximum width of the view
*/
public int getMaxWidth() {
return mMaxWidth;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Let the standard measurements take effect in iconified state.
if (isIconified()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
switch (widthMode) {
case MeasureSpec.AT_MOST:
// If there is an upper limit, don't exceed maximum width (explicit or implicit)
if (mMaxWidth > 0) {
width = Math.min(mMaxWidth, width);
} else {
width = Math.min(getPreferredWidth(), width);
}
break;
case MeasureSpec.EXACTLY:
// If an exact width is specified, still don't exceed any specified maximum width
if (mMaxWidth > 0) {
width = Math.min(mMaxWidth, width);
}
break;
case MeasureSpec.UNSPECIFIED:
// Use maximum width, if specified, else preferred width
width = mMaxWidth > 0 ? mMaxWidth : getPreferredWidth();
break;
}
widthMode = MeasureSpec.EXACTLY;
super.onMeasure(MeasureSpec.makeMeasureSpec(width, widthMode), heightMeasureSpec);
}
private int getPreferredWidth() {
return getContext().getResources()
.getDimensionPixelSize(R.dimen.abc_search_view_preferred_width);
}
private void updateViewsVisibility(final boolean collapsed) {
mIconified = collapsed;
// Visibility of views that are visible when collapsed
final int visCollapsed = collapsed ? VISIBLE : GONE;
// Is there text in the query
final boolean hasText = !TextUtils.isEmpty(mSearchSrcTextView.getText());
mSearchButton.setVisibility(visCollapsed);
updateSubmitButton(hasText);
mSearchEditFrame.setVisibility(collapsed ? GONE : VISIBLE);
final int iconVisibility;
if (mCollapsedIcon.getDrawable() == null || mIconifiedByDefault) {
iconVisibility = GONE;
} else {
iconVisibility = VISIBLE;
}
mCollapsedIcon.setVisibility(iconVisibility);
updateCloseButton();
updateVoiceButton(!hasText);
updateSubmitArea();
}
@TargetApi(Build.VERSION_CODES.FROYO)
private boolean hasVoiceSearch() {
if (mSearchable != null && mSearchable.getVoiceSearchEnabled()) {
Intent testIntent = null;
if (mSearchable.getVoiceSearchLaunchWebSearch()) {
testIntent = mVoiceWebSearchIntent;
} else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
testIntent = mVoiceAppSearchIntent;
}
if (testIntent != null) {
ResolveInfo ri = getContext().getPackageManager().resolveActivity(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
return ri != null;
}
}
return false;
}
private boolean isSubmitAreaEnabled() {
return (mSubmitButtonEnabled || mVoiceButtonEnabled) && !isIconified();
}
private void updateSubmitButton(boolean hasText) {
int visibility = GONE;
if (mSubmitButtonEnabled && isSubmitAreaEnabled() && hasFocus()
&& (hasText || !mVoiceButtonEnabled)) {
visibility = VISIBLE;
}
mGoButton.setVisibility(visibility);
}
private void updateSubmitArea() {
int visibility = GONE;
if (isSubmitAreaEnabled()
&& (mGoButton.getVisibility() == VISIBLE
|| mVoiceButton.getVisibility() == VISIBLE)) {
visibility = VISIBLE;
}
mSubmitArea.setVisibility(visibility);
}
private void updateCloseButton() {
final boolean hasText = !TextUtils.isEmpty(mSearchSrcTextView.getText());
// Should we show the close button? It is not shown if there's no focus,
// field is not iconified by default and there is no text in it.
final boolean showClose = hasText || (mIconifiedByDefault && !mExpandedInActionView);
mCloseButton.setVisibility(showClose ? VISIBLE : GONE);
final Drawable closeButtonImg = mCloseButton.getDrawable();
if (closeButtonImg != null){
closeButtonImg.setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET);
}
}
private void postUpdateFocusedState() {
post(mUpdateDrawableStateRunnable);
}
private void updateFocusedState() {
final boolean focused = mSearchSrcTextView.hasFocus();
final int[] stateSet = focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET;
final Drawable searchPlateBg = mSearchPlate.getBackground();
if (searchPlateBg != null) {
searchPlateBg.setState(stateSet);
}
final Drawable submitAreaBg = mSubmitArea.getBackground();
if (submitAreaBg != null) {
submitAreaBg.setState(stateSet);
}
invalidate();
}
@Override
protected void onDetachedFromWindow() {
removeCallbacks(mUpdateDrawableStateRunnable);
post(mReleaseCursorRunnable);
super.onDetachedFromWindow();
}
private void setImeVisibility(final boolean visible) {
if (visible) {
post(mShowImeRunnable);
} else {
removeCallbacks(mShowImeRunnable);
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
}
/**
* Called by the SuggestionsAdapter
* @hide
*/
/* package */void onQueryRefine(CharSequence queryText) {
setQuery(queryText);
}
private final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == mSearchButton) {
onSearchClicked();
} else if (v == mCloseButton) {
onCloseClicked();
} else if (v == mGoButton) {
onSubmitQuery();
} else if (v == mVoiceButton) {
onVoiceClicked();
} else if (v == mSearchSrcTextView) {
forceSuggestionQuery();
}
}
};
/**
* React to the user typing "enter" or other hardwired keys while typing in
* the search box. This handles these special keys while the edit box has
* focus.
*/
View.OnKeyListener mTextKeyListener = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// guard against possible race conditions
if (mSearchable == null) {
return false;
}
if (DBG) {
Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: "
+ mSearchSrcTextView.getListSelection());
}
// If a suggestion is selected, handle enter, search key, and action keys
// as presses on the selected suggestion
if (mSearchSrcTextView.isPopupShowing()
&& mSearchSrcTextView.getListSelection() != ListView.INVALID_POSITION) {
return onSuggestionsKey(v, keyCode, event);
}
// If there is text in the query box, handle enter, and action keys
// The search key is handled by the dialog's onKeyDown().
if (!mSearchSrcTextView.isEmpty() && KeyEventCompat.hasNoModifiers(event)) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
v.cancelLongPress();
// Launch as a regular search.
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mSearchSrcTextView.getText()
.toString());
return true;
}
}
}
return false;
}
};
/**
* React to the user typing while in the suggestions list. First, check for
* action keys. If not handled, try refocusing regular characters into the
* EditText.
*/
private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) {
// guard against possible race conditions (late arrival after dismiss)
if (mSearchable == null) {
return false;
}
if (mSuggestionsAdapter == null) {
return false;
}
if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEventCompat.hasNoModifiers(event)) {
// First, check for enter or search (both of which we'll treat as a
// "click")
if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH
|| keyCode == KeyEvent.KEYCODE_TAB) {
int position = mSearchSrcTextView.getListSelection();
return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
}
// Next, check for left/right moves, which we use to "return" the
// user to the edit view
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
// give "focus" to text editor, with cursor at the beginning if
// left key, at end if right key
// TODO: Reverse left/right for right-to-left languages, e.g.
// Arabic
int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mSearchSrcTextView
.length();
mSearchSrcTextView.setSelection(selPoint);
mSearchSrcTextView.setListSelection(0);
mSearchSrcTextView.clearListSelection();
HIDDEN_METHOD_INVOKER.ensureImeVisible(mSearchSrcTextView, true);
return true;
}
// Next, check for an "up and out" move
if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mSearchSrcTextView.getListSelection()) {
// TODO: restoreUserQuery();
// let ACTV complete the move
return false;
}
}
return false;
}
private CharSequence getDecoratedHint(CharSequence hintText) {
// If the field is always expanded or we don't have a search hint icon,
// then don't add the search icon to the hint.
if (!mIconifiedByDefault || mSearchHintIcon == null) {
return hintText;
}
final int textSize = (int) (mSearchSrcTextView.getTextSize() * 1.25);
mSearchHintIcon.setBounds(0, 0, textSize, textSize);
final SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.setSpan(new ImageSpan(mSearchHintIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(hintText);
return ssb;
}
private void updateQueryHint() {
final CharSequence hint = getQueryHint();
mSearchSrcTextView.setHint(getDecoratedHint(hint == null ? "" : hint));
}
/**
* Updates the auto-complete text view.
*/
@TargetApi(Build.VERSION_CODES.FROYO)
private void updateSearchAutoComplete() {
mSearchSrcTextView.setThreshold(mSearchable.getSuggestThreshold());
mSearchSrcTextView.setImeOptions(mSearchable.getImeOptions());
int inputType = mSearchable.getInputType();
// We only touch this if the input type is set up for text (which it almost certainly
// should be, in the case of search!)
if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
// The existence of a suggestions authority is the proxy for "suggestions
// are available here"
inputType &= ~InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
if (mSearchable.getSuggestAuthority() != null) {
inputType |= InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE;
// TYPE_TEXT_FLAG_AUTO_COMPLETE means that the text editor is performing
// auto-completion based on its own semantics, which it will present to the user
// as they type. This generally means that the input method should not show its
// own candidates, and the spell checker should not be in action. The text editor
// supplies its candidates by calling InputMethodManager.displayCompletions(),
// which in turn will call InputMethodSession.displayCompletions().
inputType |= InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
}
}
mSearchSrcTextView.setInputType(inputType);
if (mSuggestionsAdapter != null) {
mSuggestionsAdapter.changeCursor(null);
}
// attach the suggestions adapter, if suggestions are available
// The existence of a suggestions authority is the proxy for "suggestions available here"
if (mSearchable.getSuggestAuthority() != null) {
mSuggestionsAdapter = new SuggestionsAdapter(getContext(),
this, mSearchable, mOutsideDrawablesCache);
mSearchSrcTextView.setAdapter(mSuggestionsAdapter);
((SuggestionsAdapter) mSuggestionsAdapter).setQueryRefinement(
mQueryRefinement ? SuggestionsAdapter.REFINE_ALL
: SuggestionsAdapter.REFINE_BY_ENTRY);
}
}
/**
* Update the visibility of the voice button. There are actually two voice search modes,
* either of which will activate the button.
* @param empty whether the search query text field is empty. If it is, then the other
* criteria apply to make the voice button visible.
*/
private void updateVoiceButton(boolean empty) {
int visibility = GONE;
if (mVoiceButtonEnabled && !isIconified() && empty) {
visibility = VISIBLE;
mGoButton.setVisibility(GONE);
}
mVoiceButton.setVisibility(visibility);
}
private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {
/**
* Called when the input method default action key is pressed.
*/
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
onSubmitQuery();
return true;
}
};
private void onTextChanged(CharSequence newText) {
CharSequence text = mSearchSrcTextView.getText();
mUserQuery = text;
boolean hasText = !TextUtils.isEmpty(text);
updateSubmitButton(hasText);
updateVoiceButton(!hasText);
updateCloseButton();
updateSubmitArea();
if (mOnQueryChangeListener != null && !TextUtils.equals(newText, mOldQueryText)) {
mOnQueryChangeListener.onQueryTextChange(newText.toString());
}
mOldQueryText = newText.toString();
}
private void onSubmitQuery() {
CharSequence query = mSearchSrcTextView.getText();
if (query != null && TextUtils.getTrimmedLength(query) > 0) {
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
}
setImeVisibility(false);
dismissSuggestions();
}
}
}
private void dismissSuggestions() {
mSearchSrcTextView.dismissDropDown();
}
private void onCloseClicked() {
CharSequence text = mSearchSrcTextView.getText();
if (TextUtils.isEmpty(text)) {
if (mIconifiedByDefault) {
// If the app doesn't override the close behavior
if (mOnCloseListener == null || !mOnCloseListener.onClose()) {
// hide the keyboard and remove focus
clearFocus();
// collapse the search field
updateViewsVisibility(true);
}
}
} else {
mSearchSrcTextView.setText("");
mSearchSrcTextView.requestFocus();
setImeVisibility(true);
}
}
private void onSearchClicked() {
updateViewsVisibility(false);
mSearchSrcTextView.requestFocus();
setImeVisibility(true);
if (mOnSearchClickListener != null) {
mOnSearchClickListener.onClick(this);
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
private void onVoiceClicked() {
// guard against possible race conditions
if (mSearchable == null) {
return;
}
SearchableInfo searchable = mSearchable;
try {
if (searchable.getVoiceSearchLaunchWebSearch()) {
Intent webSearchIntent = createVoiceWebSearchIntent(mVoiceWebSearchIntent,
searchable);
getContext().startActivity(webSearchIntent);
} else if (searchable.getVoiceSearchLaunchRecognizer()) {
Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent,
searchable);
getContext().startActivity(appSearchIntent);
}
} catch (ActivityNotFoundException e) {
// Should not happen, since we check the availability of
// voice search before showing the button. But just in case...
Log.w(LOG_TAG, "Could not find voice search activity");
}
}
void onTextFocusChanged() {
updateViewsVisibility(isIconified());
// Delayed update to make sure that the focus has settled down and window focus changes
// don't affect it. A synchronous update was not working.
postUpdateFocusedState();
if (mSearchSrcTextView.hasFocus()) {
forceSuggestionQuery();
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
postUpdateFocusedState();
}
/**
* {@inheritDoc}
*/
@Override
public void onActionViewCollapsed() {
setQuery("", false);
clearFocus();
updateViewsVisibility(true);
mSearchSrcTextView.setImeOptions(mCollapsedImeOptions);
mExpandedInActionView = false;
}
/**
* {@inheritDoc}
*/
@Override
public void onActionViewExpanded() {
if (mExpandedInActionView) return;
mExpandedInActionView = true;
mCollapsedImeOptions = mSearchSrcTextView.getImeOptions();
mSearchSrcTextView.setImeOptions(mCollapsedImeOptions | EditorInfo.IME_FLAG_NO_FULLSCREEN);
mSearchSrcTextView.setText("");
setIconified(false);
}
static class SavedState extends BaseSavedState {
boolean isIconified;
SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel source) {
super(source);
isIconified = (Boolean) source.readValue(null);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeValue(isIconified);
}
@Override
public String toString() {
return "SearchView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " isIconified=" + isIconified + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isIconified = isIconified();
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
updateViewsVisibility(ss.isIconified);
requestLayout();
}
private void adjustDropDownSizeAndPosition() {
if (mDropDownAnchor.getWidth() > 1) {
Resources res = getContext().getResources();
int anchorPadding = mSearchPlate.getPaddingLeft();
Rect dropDownPadding = new Rect();
final boolean isLayoutRtl = ViewUtils.isLayoutRtl(this);
int iconOffset = mIconifiedByDefault
? res.getDimensionPixelSize(R.dimen.abc_dropdownitem_icon_width)
+ res.getDimensionPixelSize(R.dimen.abc_dropdownitem_text_padding_left)
: 0;
mSearchSrcTextView.getDropDownBackground().getPadding(dropDownPadding);
int offset;
if (isLayoutRtl) {
offset = - dropDownPadding.left;
} else {
offset = anchorPadding - (dropDownPadding.left + iconOffset);
}
mSearchSrcTextView.setDropDownHorizontalOffset(offset);
final int width = mDropDownAnchor.getWidth() + dropDownPadding.left
+ dropDownPadding.right + iconOffset - anchorPadding;
mSearchSrcTextView.setDropDownWidth(width);
}
}
private boolean onItemClicked(int position, int actionKey, String actionMsg) {
if (mOnSuggestionListener == null
|| !mOnSuggestionListener.onSuggestionClick(position)) {
launchSuggestion(position, KeyEvent.KEYCODE_UNKNOWN, null);
setImeVisibility(false);
dismissSuggestions();
return true;
}
return false;
}
private boolean onItemSelected(int position) {
if (mOnSuggestionListener == null
|| !mOnSuggestionListener.onSuggestionSelect(position)) {
rewriteQueryFromSuggestion(position);
return true;
}
return false;
}
private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
/**
* Implements OnItemClickListener
*/
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (DBG) Log.d(LOG_TAG, "onItemClick() position " + position);
onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null);
}
};
private final OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {
/**
* Implements OnItemSelectedListener
*/
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (DBG) Log.d(LOG_TAG, "onItemSelected() position " + position);
SearchView.this.onItemSelected(position);
}
/**
* Implements OnItemSelectedListener
*/
public void onNothingSelected(AdapterView<?> parent) {
if (DBG)
Log.d(LOG_TAG, "onNothingSelected()");
}
};
/**
* Query rewriting.
*/
private void rewriteQueryFromSuggestion(int position) {
CharSequence oldQuery = mSearchSrcTextView.getText();
Cursor c = mSuggestionsAdapter.getCursor();
if (c == null) {
return;
}
if (c.moveToPosition(position)) {
// Get the new query from the suggestion.
CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
if (newQuery != null) {
// The suggestion rewrites the query.
// Update the text field, without getting new suggestions.
setQuery(newQuery);
} else {
// The suggestion does not rewrite the query, restore the user's query.
setQuery(oldQuery);
}
} else {
// We got a bad position, restore the user's query.
setQuery(oldQuery);
}
}
/**
* Launches an intent based on a suggestion.
*
* @param position The index of the suggestion to create the intent from.
* @param actionKey The key code of the action key that was pressed,
* or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
* @param actionMsg The message for the action key that was pressed,
* or <code>null</code> if none.
* @return true if a successful launch, false if could not (e.g. bad position).
*/
private boolean launchSuggestion(int position, int actionKey, String actionMsg) {
Cursor c = mSuggestionsAdapter.getCursor();
if ((c != null) && c.moveToPosition(position)) {
Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg);
// launch the intent
launchIntent(intent);
return true;
}
return false;
}
/**
* Launches an intent, including any special intent handling.
*/
private void launchIntent(Intent intent) {
if (intent == null) {
return;
}
try {
// If the intent was created from a suggestion, it will always have an explicit
// component here.
getContext().startActivity(intent);
} catch (RuntimeException ex) {
Log.e(LOG_TAG, "Failed launch activity: " + intent, ex);
}
}
/**
* Sets the text in the query box, without updating the suggestions.
*/
private void setQuery(CharSequence query) {
mSearchSrcTextView.setText(query);
// Move the cursor to the end
mSearchSrcTextView.setSelection(TextUtils.isEmpty(query) ? 0 : query.length());
}
private void launchQuerySearch(int actionKey, String actionMsg, String query) {
String action = Intent.ACTION_SEARCH;
Intent intent = createIntent(action, null, null, query, actionKey, actionMsg);
getContext().startActivity(intent);
}
/**
* Constructs an intent from the given information and the search dialog state.
*
* @param action Intent action.
* @param data Intent data, or <code>null</code>.
* @param extraData Data for {@link SearchManager#EXTRA_DATA_KEY} or <code>null</code>.
* @param query Intent query, or <code>null</code>.
* @param actionKey The key code of the action key that was pressed,
* or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
* @param actionMsg The message for the action key that was pressed,
* or <code>null</code> if none.
* @return The intent.
*/
private Intent createIntent(String action, Uri data, String extraData, String query,
int actionKey, String actionMsg) {
// Now build the Intent
Intent intent = new Intent(action);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// We need CLEAR_TOP to avoid reusing an old task that has other activities
// on top of the one we want. We don't want to do this in in-app search though,
// as it can be destructive to the activity stack.
if (data != null) {
intent.setData(data);
}
intent.putExtra(SearchManager.USER_QUERY, mUserQuery);
if (query != null) {
intent.putExtra(SearchManager.QUERY, query);
}
if (extraData != null) {
intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
}
if (mAppSearchData != null) {
intent.putExtra(SearchManager.APP_DATA, mAppSearchData);
}
if (actionKey != KeyEvent.KEYCODE_UNKNOWN) {
intent.putExtra(SearchManager.ACTION_KEY, actionKey);
intent.putExtra(SearchManager.ACTION_MSG, actionMsg);
}
if (IS_AT_LEAST_FROYO) {
intent.setComponent(mSearchable.getSearchActivity());
}
return intent;
}
/**
* Create and return an Intent that can launch the voice search activity for web search.
*/
@TargetApi(Build.VERSION_CODES.FROYO)
private Intent createVoiceWebSearchIntent(Intent baseIntent, SearchableInfo searchable) {
Intent voiceIntent = new Intent(baseIntent);
ComponentName searchActivity = searchable.getSearchActivity();
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
: searchActivity.flattenToShortString());
return voiceIntent;
}
/**
* Create and return an Intent that can launch the voice search activity, perform a specific
* voice transcription, and forward the results to the searchable activity.
*
* @param baseIntent The voice app search intent to start from
* @return A completely-configured intent ready to send to the voice search activity
*/
@TargetApi(Build.VERSION_CODES.FROYO)
private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
ComponentName searchActivity = searchable.getSearchActivity();
// create the necessary intent to set up a search-and-forward operation
// in the voice search system. We have to keep the bundle separate,
// because it becomes immutable once it enters the PendingIntent
Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
queryIntent.setComponent(searchActivity);
PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
PendingIntent.FLAG_ONE_SHOT);
// Now set up the bundle that will be inserted into the pending intent
// when it's time to do the search. We always build it here (even if empty)
// because the voice search activity will always need to insert "QUERY" into
// it anyway.
Bundle queryExtras = new Bundle();
if (mAppSearchData != null) {
queryExtras.putParcelable(SearchManager.APP_DATA, mAppSearchData);
}
// Now build the intent to launch the voice search. Add all necessary
// extras to launch the voice recognizer, and then all the necessary extras
// to forward the results to the searchable activity
Intent voiceIntent = new Intent(baseIntent);
// Add all of the configuration options supplied by the searchable's metadata
String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
String prompt = null;
String language = null;
int maxResults = 1;
if (Build.VERSION.SDK_INT >= 8) {
Resources resources = getResources();
if (searchable.getVoiceLanguageModeId() != 0) {
languageModel = resources.getString(searchable.getVoiceLanguageModeId());
}
if (searchable.getVoicePromptTextId() != 0) {
prompt = resources.getString(searchable.getVoicePromptTextId());
}
if (searchable.getVoiceLanguageId() != 0) {
language = resources.getString(searchable.getVoiceLanguageId());
}
if (searchable.getVoiceMaxResults() != 0) {
maxResults = searchable.getVoiceMaxResults();
}
}
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity == null ? null
: searchActivity.flattenToShortString());
// Add the values that configure forwarding the results
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
return voiceIntent;
}
/**
* When a particular suggestion has been selected, perform the various lookups required
* to use the suggestion. This includes checking the cursor for suggestion-specific data,
* and/or falling back to the XML for defaults; It also creates REST style Uri data when
* the suggestion includes a data id.
*
* @param c The suggestions cursor, moved to the row of the user's selection
* @param actionKey The key code of the action key that was pressed,
* or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
* @param actionMsg The message for the action key that was pressed,
* or <code>null</code> if none.
* @return An intent for the suggestion at the cursor's position.
*/
private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
try {
// use specific action if supplied, or default action if supplied, or fixed default
String action = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);
if (action == null && Build.VERSION.SDK_INT >= 8) {
action = mSearchable.getSuggestIntentAction();
}
if (action == null) {
action = Intent.ACTION_SEARCH;
}
// use specific data if supplied, or default data if supplied
String data = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
if (IS_AT_LEAST_FROYO && data == null) {
data = mSearchable.getSuggestIntentData();
}
// then, if an ID was provided, append it.
if (data != null) {
String id = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
if (id != null) {
data = data + "/" + Uri.encode(id);
}
}
Uri dataUri = (data == null) ? null : Uri.parse(data);
String query = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
String extraData = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
} catch (RuntimeException e ) {
int rowNum;
try { // be really paranoid now
rowNum = c.getPosition();
} catch (RuntimeException e2 ) {
rowNum = -1;
}
Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum +
" returned exception.", e);
return null;
}
}
private void forceSuggestionQuery() {
HIDDEN_METHOD_INVOKER.doBeforeTextChanged(mSearchSrcTextView);
HIDDEN_METHOD_INVOKER.doAfterTextChanged(mSearchSrcTextView);
}
static boolean isLandscapeMode(Context context) {
return context.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
}
/**
* Callback to watch the text field for empty/non-empty
*/
private TextWatcher mTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int after) {
SearchView.this.onTextChanged(s);
}
public void afterTextChanged(Editable s) {
}
};
/**
* Local subclass for AutoCompleteTextView.
* @hide
*/
public static class SearchAutoComplete extends AppCompatAutoCompleteTextView {
private int mThreshold;
private SearchView mSearchView;
public SearchAutoComplete(Context context) {
this(context, null);
}
public SearchAutoComplete(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.autoCompleteTextViewStyle_ox);
}
public SearchAutoComplete(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mThreshold = getThreshold();
}
void setSearchView(SearchView searchView) {
mSearchView = searchView;
}
@Override
public void setThreshold(int threshold) {
super.setThreshold(threshold);
mThreshold = threshold;
}
/**
* Returns true if the text field is empty, or contains only whitespace.
*/
private boolean isEmpty() {
return TextUtils.getTrimmedLength(getText()) == 0;
}
/**
* We override this method to avoid replacing the query box text when a
* suggestion is clicked.
*/
@Override
protected void replaceText(CharSequence text) {
}
/**
* We override this method to avoid an extra onItemClick being called on
* the drop-down's OnItemClickListener by
* {@link AutoCompleteTextView#onKeyUp(int, KeyEvent)} when an item is
* clicked with the trackball.
*/
@Override
public void performCompletion() {
}
/**
* We override this method to be sure and show the soft keyboard if
* appropriate when the TextView has focus.
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) {
InputMethodManager inputManager = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(this, 0);
// If in landscape mode, then make sure that
// the ime is in front of the dropdown.
if (isLandscapeMode(getContext())) {
HIDDEN_METHOD_INVOKER.ensureImeVisible(this, true);
}
}
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
mSearchView.onTextFocusChanged();
}
/**
* We override this method so that we can allow a threshold of zero,
* which ACTV does not.
*/
@Override
public boolean enoughToFilter() {
return mThreshold <= 0 || super.enoughToFilter();
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// special case for the back key, we do not even try to send it
// to the drop down list but instead, consume it immediately
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.startTracking(event, this);
}
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.handleUpEvent(event);
}
if (event.isTracking() && !event.isCanceled()) {
mSearchView.clearFocus();
mSearchView.setImeVisibility(false);
return true;
}
}
}
return super.onKeyPreIme(keyCode, event);
}
}
private static class AutoCompleteTextViewReflector {
private Method doBeforeTextChanged, doAfterTextChanged;
private Method ensureImeVisible;
private Method showSoftInputUnchecked;
AutoCompleteTextViewReflector() {
try {
doBeforeTextChanged = AutoCompleteTextView.class
.getDeclaredMethod("doBeforeTextChanged");
doBeforeTextChanged.setAccessible(true);
} catch (NoSuchMethodException e) {
// Ah well.
}
try {
doAfterTextChanged = AutoCompleteTextView.class
.getDeclaredMethod("doAfterTextChanged");
doAfterTextChanged.setAccessible(true);
} catch (NoSuchMethodException e) {
// Ah well.
}
try {
ensureImeVisible = AutoCompleteTextView.class
.getMethod("ensureImeVisible", boolean.class);
ensureImeVisible.setAccessible(true);
} catch (NoSuchMethodException e) {
// Ah well.
}
try {
showSoftInputUnchecked = InputMethodManager.class.getMethod(
"showSoftInputUnchecked", int.class, ResultReceiver.class);
showSoftInputUnchecked.setAccessible(true);
} catch (NoSuchMethodException e) {
// Ah well.
}
}
void doBeforeTextChanged(AutoCompleteTextView view) {
if (doBeforeTextChanged != null) {
try {
doBeforeTextChanged.invoke(view);
} catch (Exception e) {
}
}
}
void doAfterTextChanged(AutoCompleteTextView view) {
if (doAfterTextChanged != null) {
try {
doAfterTextChanged.invoke(view);
} catch (Exception e) {
}
}
}
void ensureImeVisible(AutoCompleteTextView view, boolean visible) {
if (ensureImeVisible != null) {
try {
ensureImeVisible.invoke(view, visible);
} catch (Exception e) {
}
}
}
void showSoftInputUnchecked(InputMethodManager imm, View view, int flags) {
if (showSoftInputUnchecked != null) {
try {
showSoftInputUnchecked.invoke(imm, flags, null);
return;
} catch (Exception e) {
}
}
// Hidden method failed, call public version instead
imm.showSoftInput(view, flags);
}
}
} | [
"nuborisar@gmail.com"
] | nuborisar@gmail.com |
84554100626398851d19d782b04bdecca7d60569 | 00e1e0709c471385b807b25ae5da0715f069136d | /center/src/com/chuangyou/xianni/state/condition/BaseStateCondition.java | 8b15e17e8a65da386f4c297695f17799eaf8b2ee | [] | no_license | hw233/app2-java | 44504896d13a5b63e3d95343c62424495386b7f1 | f4b5217a4980b0ff81f81577c348a6e71593a185 | refs/heads/master | 2020-04-27T11:23:44.089556 | 2016-11-18T01:33:52 | 2016-11-18T01:33:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,544 | java | package com.chuangyou.xianni.state.condition;
import com.chuangyou.xianni.entity.state.StateConditionConfig;
import com.chuangyou.xianni.entity.state.StateConditionInfo;
import com.chuangyou.xianni.event.ObjectListener;
import com.chuangyou.xianni.player.GamePlayer;
import com.chuangyou.xianni.proto.MessageUtil;
import com.chuangyou.xianni.protocol.Protocol;
public abstract class BaseStateCondition {
protected StateConditionInfo info;
protected StateConditionConfig config;
protected GamePlayer player;
protected ObjectListener listener;
public BaseStateCondition(StateConditionInfo info, StateConditionConfig config,GamePlayer player) {
super();
this.info = info;
this.config = config;
this.player = player;
}
/**
* 添加监听
* @param player
*/
public abstract void addTrigger(GamePlayer player);
/**
* 删除监听
* @param player
*/
public abstract void removeTrigger(GamePlayer player);
/** 初始化进度 */
public abstract void initProcess();
/**
* 初始化监听回调
*/
public abstract void initListener();
/**
* 是否完成
* @return
*/
public boolean isComplete() {
// TODO Auto-generated method stub
if(this.info.getProcess()>=this.config.getTargetNum()){
return true;
}
return false;
}
/**
* 提交处理
* @return
*/
public abstract boolean commitProcess();
/**
* 通知更新
*/
public void doNotifyUpdate(){
player.sendPbMessage(MessageUtil.buildMessage(Protocol.U_RESP_STATE_UPDATE,this.info.getMsg()));
}
}
| [
"you@example.com"
] | you@example.com |
0b18b90ee21a74be38551393166e89f79c59de39 | 9dbadd86a9c7e59d07870143762a0a83656f0325 | /src/test/java/leetcode/listnode/AddTwoNumbers.java | 3229fd359f7adccb448f178c53b9b580d9e88e35 | [] | no_license | BinbinGuan/rabbitMq-test | 57d18b1f200e041e6eb4dfe8b80b1bd2ba2fd2ad | 46f15373fb8743922e780efe51d40a3859c188a8 | refs/heads/master | 2022-11-27T16:51:13.819148 | 2021-05-10T03:27:20 | 2021-05-10T03:27:20 | 146,191,706 | 0 | 0 | null | 2022-11-21T22:39:51 | 2018-08-26T15:17:07 | Java | UTF-8 | Java | false | false | 3,744 | java | package leetcode.listnode;
import org.junit.Test;
/**
* @author: GuanBin
* @date: Created in 下午9:45 2019/11/19
*
* 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
*
* 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
*
* 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
*
* 示例:
*
* 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
* 输出:7 -> 0 -> 8
* 原因:342 + 465 = 807
*
*/
public class AddTwoNumbers {
@Test
public void test(){
ListNode dummy1 = new ListNode(2);
ListNode dummy2 = new ListNode(4);
ListNode dummy3 = new ListNode(3);
dummy1.nextNode = dummy2;
dummy2.nextNode = dummy3;
ListNode dummy4 = new ListNode(5);
ListNode dummy5 = new ListNode(6);
ListNode dummy6 = new ListNode(4);
dummy4.nextNode = dummy5;
dummy5.nextNode = dummy6;
addTwoNumbers(dummy1,dummy4);
}
/**
* 就像你在纸上计算两个数字的和那样,我们首先从最低有效位也就是列表 l1l1 和 l2l2 的表头开始相加。由于每位数字都应当处于 0 \ldots 90…9 的范围内,我们计算两个数字的和时可能会出现 “溢出”。例如,5 + 7 = 125+7=12。在这种情况下,我们会将当前位的数值设置为 22,并将进位 carry = 1carry=1 带入下一次迭代。进位 carrycarry 必定是 00 或 11,这是因为两个数字相加(考虑到进位)可能出现的最大和为 9 + 9 + 1 = 199+9+1=19。
*
* 伪代码如下:
*
* 将当前结点初始化为返回列表的哑结点。
* 将进位 carrycarry 初始化为 00。
* 将 pp 和 qq 分别初始化为列表 l1l1 和 l2l2 的头部。
* 遍历列表 l1l1 和 l2l2 直至到达它们的尾端。
* 将 xx 设为结点 pp 的值。如果 pp 已经到达 l1l1 的末尾,则将其值设置为 00。
* 将 yy 设为结点 qq 的值。如果 qq 已经到达 l2l2 的末尾,则将其值设置为 00。
* 设定 sum = x + y + carrysum=x+y+carry。
* 更新进位的值,carry = sum / 10carry=sum/10。
* 创建一个数值为 (sum \bmod 10)(summod10) 的新结点,并将其设置为当前结点的下一个结点,然后将当前结点前进到下一个结点。
* 同时,将 pp 和 qq 前进到下一个结点。
* 检查 carry = 1carry=1 是否成立,如果成立,则向返回列表追加一个含有数字 11 的新结点。
* 返回哑结点的下一个结点。
*
* 作者:LeetCode
* 链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.nextNode = new ListNode(sum % 10);
curr = curr.nextNode;
if (p != null) p = p.nextNode;
if (q != null) q = q.nextNode;
}
if (carry > 0) {
curr.nextNode = new ListNode(carry);
}
return dummyHead.nextNode;
}
}
| [
"binbin.guan@cloudchef.io"
] | binbin.guan@cloudchef.io |
d3898969f4f5f9702ca010575d7bc64b12eb8f45 | 544b3cdb0bb53432693455d8af052ec52efe7774 | /api/src/main/java/chezz/users/UserTokenGeneratorSimple.java | 427c0f91abf9e1d22749c54e7c7838f8dfe9184f | [
"MIT"
] | permissive | niamster/chezz | 2bdd054483e813ef732b1766b43f4e5d81c1493e | 8daa5d6fb19e7ae0576fccab230bb93a680adea1 | refs/heads/master | 2023-01-10T07:16:00.835469 | 2019-12-29T00:15:45 | 2020-11-30T22:14:55 | 224,533,341 | 0 | 0 | MIT | 2023-01-05T02:07:27 | 2019-11-27T23:21:09 | Java | UTF-8 | Java | false | false | 394 | java | package chezz.users;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Hex;
public class UserTokenGeneratorSimple implements UserTokenGenerator {
private final SecureRandom rng = new SecureRandom();
@Override
public String generateToken(String username) {
var random = new byte[16];
rng.nextBytes(random);
return Hex.encodeHexString(random);
}
}
| [
"dmilinevskyi@gmail.com"
] | dmilinevskyi@gmail.com |
11c0641d8971f0e50b794398f8d012c444b2c1b3 | b5357951e00a609261667a6e13cb17469a7b88be | /02_grammar/Ex04.java | fe9ce343c1306069135bee2392ce026b1be6a863 | [] | no_license | DrMJ-Chu/2020_java | d0468b12a8c6d7833270bdabccdf364b0ff2eaaf | b45c070accc8d5a210bfbed632aafa9bce9cd894 | refs/heads/master | 2022-09-10T06:24:44.546824 | 2020-06-05T09:10:04 | 2020-06-05T09:10:04 | 261,988,058 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,718 | java | class Ex04{
public static void main(String[] args){
// 숫자 : 정수형 : byte < short < int < long
// 정수형 : byte < short < int < long
// 정수형의 기본은 int
// 실수형 : float < double
// 실수형의 기본은 double
// byte : 정수형 중 가장 작은 단위 ( -128 ~ 127 )
// -128 ~ 127 사이의 숫자만 저장 가능
byte b1 = 127 ;
System.out.println(b1);
// 계산식은 결과만 저장된다.
byte b2 = 15 + 20 ;
System.out.println(b2);
// short : -32768 ~ 32767사이의 값만 저장
short s1 = -32768;
System.out.println(s1);
short s2 = -32767;
System.out.println(s2);
// int와 long은 숫자 범위를 외울 필요가 없다.
// 앞으로 일반적인 정수는 int 사용
// 아주 큰 정수를 사용할 때 long 사용
int su1 = 247 ;
int su2 = 777777 ;
System.out.println(su1);
System.out.println(su2);
// long : int보다 더 넒은 범위를 가지고 있음
// 기본적으로 숫자 뒤에 L 또는 l 를 붙인다. (생략가능)
long num1 = 124L;
System.out.println(num1);
// 작은 자료형이 큰 자료형에 저장되는 것은 오류가 나지 않는다.
long num2 = 124;
System.out.println(num2);
// 정수 su1을 long sum3에 저장
long num3 = su1;
System.out.println(num3);
// short s1을 long sum4에 저장
long num4 = s1;
System.out.println(num4);
// short s1을 long su3에 저장
long su3 = s1;
System.out.println(su3);
char c1 = '가';
System.out.println(c1);
int su4 = c1 ;
System.out.println(su4);
}
} | [
"qjtmwkrnr@naver.com"
] | qjtmwkrnr@naver.com |
cbbc768e448ca55a58a28fd525e96a4a25b1e464 | 65f9e14cb253564c608033cacdc10383cf10e657 | /CookHelper Project/app/build/generated/source/buildConfig/androidTest/debug/com/qwerty123/cookhelper/test/BuildConfig.java | 5d6a7de2bd9e981c7bac9466086e066b22310de0 | [] | no_license | namichie/SEG2105 | 50c4ac60baa89dec17db6f78f0fe871030a85371 | 12083ee67230aa5cc546ca87ff93b91d1345deb1 | refs/heads/master | 2020-05-20T09:17:10.670747 | 2019-05-08T00:27:57 | 2019-05-08T00:27:57 | 185,489,086 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 465 | java | /**
* Automatically generated file. DO NOT MODIFY
*/
package com.qwerty123.cookhelper.test;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.qwerty123.cookhelper.test";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| [
"namchi.nguyen18@gmail.com"
] | namchi.nguyen18@gmail.com |
45663ede91d684c47e7d9c6446cd5a415f34ef4b | 9560501dfab9f335f232e41ef2a8fc0e7e931ec5 | /training_codes/java/oct21-19/src/Calculator.java | a075ee50f03a3eab166e481564fd3511815a8812 | [] | no_license | Anushka21arora/UstGlobal-16sept19-Anushka-Arora | 9b6b993997ce42b1d75a6a7ce47eb76606d8c4cf | be72a594a311ed8fce7729ae4b7da91ab022a100 | refs/heads/master | 2023-01-14T05:51:28.535906 | 2019-12-21T13:42:13 | 2019-12-21T13:42:13 | 215,536,543 | 0 | 0 | null | 2023-01-07T13:04:05 | 2019-10-16T11:55:48 | JavaScript | UTF-8 | Java | false | false | 146 | java | public class Calculator {
void add()
{
System.out.println("add() method");
}
void mul()
{
System.out.println("mul() method");
}
}
| [
"anushka1997.aa@gmail.com"
] | anushka1997.aa@gmail.com |
e4837044d7187c6d6df030059d53fb2ad05fd7d1 | a1eb55ba92e0f0f1a56091ce562b09bfc0640a0b | /app/src/main/java/com/example/mperminov/guardiannewsfeed/QueryUtils.java | 01122a9d15c9e0c986ab61e5a881f6a05deaa4ff | [] | no_license | mfperminov/GuardianNewsfeed | 4547135478768cb9568b31642a6173ed9d9a2fa1 | 0254d4c0c39b66b4fce585195b2056d63b19dbee | refs/heads/master | 2020-03-15T20:52:34.372036 | 2018-05-12T19:44:22 | 2018-05-12T19:44:22 | 132,342,844 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,570 | java | package com.example.mperminov.guardiannewsfeed;
import android.text.TextUtils;
import android.util.Log;
import org.apache.commons.text.WordUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
/**
* Helper methods related to requesting and receiving news data from Guardian.
*/
public final class QueryUtils {
/**
* Tag for the log messages
*/
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
/**
* Create a private constructor because no one should ever create a {@link QueryUtils} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
*/
private QueryUtils() {
}
/**
* Return a list of {@link Story} objects that has been built up from
* parsing a JSON response.
*/
private static ArrayList<Story> extractStoryData(String jsonResponse) {
// Create an empty ArrayList that we can start adding stories to
ArrayList<Story> stories = new ArrayList<>();
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(jsonResponse)) {
return null;
}
try {
//parse root object
JSONObject storiesJson = new JSONObject(jsonResponse);
//Extract "subroot" object response
JSONObject response = storiesJson.getJSONObject("response");
//check for ok status code
String status = response.getString("status");
//Extract “results” JSONArray if status "ok"
if (status.equals("ok")) {
JSONArray results = response.getJSONArray("results");
//Loop through each feature in the array
for (int i = 0; i < results.length(); i++) {
//Get result JSONObject at position i
JSONObject result = (JSONObject) results.get(i);
//extract title of the Article, url for Intent
//and name of the section
String title = result.getString("webTitle");
String section = result.getString("sectionName");
String url = result.getString("webUrl");
//extract date and time. I wanna burn with fire my computer
//when dealing with java.time so I decided use string concatenation for now
String date = result.getString("webPublicationDate");
//first substring - date, second - time in UTC,
// newline for nice formatting in layout
String dateFormatted = date.substring(0,10) + "\n"
+ date.substring(11,16);
//looking for author name in tags
JSONArray tags = result.getJSONArray("tags");
if (tags != null && tags.length() > 0) {
JSONObject tag = tags.getJSONObject(0);
String id = tag.getString("webTitle");
stories.add(new Story(title,section,url,dateFormatted,id));
} else {
//Create Story java object from title, section name
//url, time and add story to list of stories
stories.add(new Story(title,section,url,dateFormatted));
}
}
} else {
Log.e("QueryUtils - JSON error",response.getString("message"));
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the stories JSON results", e);
}
// Return the list of stories
return stories;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
private static String makeHttpConnect(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {@link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Query Guardian API dataset and return a list of {@link Story} objects.
*/
public static ArrayList<Story> fetchStoriesData(String requestUrl) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpConnect(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response, create a list of {@link Story}ies
// and return it;
return extractStoryData(jsonResponse);
}
} | [
"mfperminov@mail.ru"
] | mfperminov@mail.ru |
69e7f27e287a50be7e6d2e5592f1bb58bb66322a | e2b1f9304f86417086515416e4e428f3365fc460 | /src/Embedder.java | 8c07067a15ddb180695b81c5e48f9e794de5e521 | [] | no_license | rupadevi1999/Steganography | ccfe2dcbe6ea4d98457b9d8bbdbc092584d320cc | f5f34c92457696db883c6b42341e4efe83b8f227 | refs/heads/master | 2020-12-24T04:33:55.873090 | 2020-01-09T08:11:26 | 2020-01-09T08:11:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,598 | java | import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.FileInputStream;
class Embedder
{
private File vessel;
private File msgFile;
private File outFile;
private byte[] buff;
public Embedder(File vessel,File msgFile,File outFile)throws Exception
{
if(vessel.exists() == false)throw new Exception("Source file doesnt exists");
if(msgFile.exists() == false)throw new Exception("message file doesnt exists");
this.vessel = vessel;
this.msgFile = msgFile;
this.outFile = outFile;
this.buff = new byte[1024];
ByteManager.setFlag(0);
}
public void embedd()throws Exception
{
boolean finished = false;
int n,k,x,y;
int[] updatedBytes;
n = k = x = y = 0;
System.out.println("Header Length :: "+HeaderManager.getHeader(outFile).length());
byte[] headerBytes = HeaderManager.getHeader(msgFile).getBytes();
n = headerBytes.length;
FileInputStream fin = new FileInputStream(msgFile);
BufferedImage vesselImage = ImageIO.read(vessel);
int vesselWidth = vesselImage.getWidth();
int vesselHeight = vesselImage.getHeight();
if(vesselHeight*vesselWidth < msgFile.length()+HeaderManager.getHeaderLength())throw new Exception("insufficient Size");
System.out.println("Vessel Capacity :: "+vesselHeight*vesselWidth);
System.out.println("Data File Size :: "+msgFile.length());
WritableRaster raster = vesselImage.getRaster();
System.out.println("Header Bytes Length :: "+n);
for( x=0; x < vesselWidth; x++ ){
for( y=0; y < vesselHeight; y++ ){
if(k == n){
System.out.println("HeaderBreak :: "+x+" "+y);
finished = true;
break;
}
// System.out.println(raster.getSample(x,y,0)+" "+raster.getSample(x,y,1)+" "+raster.getSample(x,y,2)+" ");
updatedBytes = ByteManager.modify(headerBytes[k++],new int[]{raster.getSample(x,y,0),raster.getSample(x,y,1),raster.getSample(x,y,2)});
raster.setSample(x,y,0,updatedBytes[0]);
raster.setSample(x,y,1,updatedBytes[1]);
raster.setSample(x,y,2,updatedBytes[2]);
// System.out.print(updatedBytes[0]+" "+updatedBytes[1]+" "+updatedBytes[2]+" ");
// System.out.println((char)ByteManager.patchUp(new int[]{updatedBytes[0],updatedBytes[1],updatedBytes[2]}));
}
if(finished)break;
}
finished = false;
k = n = 0;
System.out.println("Embedding starts at "+x+" "+y);
for (int i = x; i < vesselWidth; i++) {
for (int j = y; j < vesselHeight; j++) {
if(k == n){
n = fin.read(buff);
k = 0;
}
if(n == -1){
finished = true;
break;
}
updatedBytes = ByteManager.modify(buff[k++],new int[]{raster.getSample(i,j,0),raster.getSample(i,j,1),raster.getSample(i,j,2)});
raster.setSample(i,j,0,updatedBytes[0]);
raster.setSample(i,j,1,updatedBytes[1]);
raster.setSample(i,j,2,updatedBytes[2]);
}
if(finished)break;
}
vesselImage.setData(raster);
ImageIO.write(vesselImage,"png",outFile);
System.out.println("done with emedding");
}
public static void main(String args[]){
try{
File vessel = new File(args[0]);
File dataFile = new File(args[1]);
File outputFile = new File(args[2]);
new Embedder(vessel,dataFile,outputFile).embedd();
}
catch(ArrayIndexOutOfBoundsException ex ){
System.out.println("Usage java Embedder <vesselImage> <dataFile> <OutputImage> ");
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
} | [
"surajsinghrana7417@gmail.com"
] | surajsinghrana7417@gmail.com |
79c7bad4ae6c965f4cf65e544a1c509f7764c1e4 | bd9f20b69a981f62304cbf749347f40eb8e46a94 | /src/main/java/br/com/academiadev/bumblebee/repository/LocalizacaoRepository.java | d20f9f30d875451127f5f5a9dc45e5096497adba | [] | no_license | academiadev-jlle/backend-bumblebee | ab5792fac9b9cdd89047379e10171617ac130888 | 9f269c1725263fc9fbde327788712cab6f31499e | refs/heads/master | 2020-04-03T02:38:46.660682 | 2018-12-11T15:35:45 | 2018-12-11T15:35:45 | 154,962,049 | 0 | 1 | null | 2018-12-11T15:35:46 | 2018-10-27T12:26:05 | Java | UTF-8 | Java | false | false | 314 | java | package br.com.academiadev.bumblebee.repository;
import br.com.academiadev.bumblebee.model.Localizacao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LocalizacaoRepository extends JpaRepository<Localizacao, Long> {
}
| [
"ifc.vinicius@gmail.com"
] | ifc.vinicius@gmail.com |
ed0c60b0f8ea91560821005d3114ecd74bb32696 | 792da2b2bed49f1a68be447d2fc639f92b9fafc4 | /OOPD_Assignment 3/src/Scissor.java | 7370aa06a221bd0f50e2647c6a2d3be86f90cf8a | [] | no_license | prabhatkumar95/OOPD | b61751564305a80358ba245d2e18d6e1b9d8f9b5 | 8bf232772531a46eb1d3862b463543a06829bfd3 | refs/heads/master | 2021-09-25T21:36:58.137726 | 2018-10-25T20:33:12 | 2018-10-25T20:33:12 | 108,273,494 | 0 | 1 | null | 2018-10-25T20:33:13 | 2017-10-25T13:22:54 | Java | UTF-8 | Java | false | false | 886 | java | public class Scissor {
private int strength;
public String name;
public Scissor()
{
name= "Scissor";
strength=0;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public int battle(Object o)
{
int temp;
if(o instanceof Scissor) {
System.out.println("Scissor");
temp = this.getStrength() - ((Scissor) o).getStrength();
}
else if(o instanceof Paper) {
System.out.println("Paper");
temp = 2 * this.getStrength() - (int) 0.5 * ((Paper) o).getStrength();
}
else {
System.out.println("Stone");
temp = (int) 0.5 * this.getStrength() - 2 * ((Stone) o).getStrength();
}
return Integer.compare(temp, 0);
}
}
| [
"prabhat17036@iiitd.ac.in"
] | prabhat17036@iiitd.ac.in |
e4dd9dfcb13610bcb90a89639dca79cde9b937a9 | 8e1dbf0ee00312e8f45eb82bf6bad350ae68c0aa | /project/src/main/java/club/emergency/project/model/ByPlusTaskStop.java | 5f609f73be38af1b1baeba9d85690e95a25508fb | [] | no_license | piglete/DAST | ed839d69df3d9c5d738574ee1ad9e803929df056 | 821f06b40a882ed9861c8eedd4fceda935ce5a13 | refs/heads/master | 2020-05-30T20:35:00.822871 | 2019-06-03T08:24:24 | 2019-06-03T08:24:24 | 188,547,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,335 | java | package club.emergency.project.model;
import club.map.core.mapper.ColumnTransient;
import club.map.core.model.RootObject;
import club.map.core.model.TableName;
@TableName("by_plus_task_stop")
public class ByPlusTaskStop extends RootObject {
private Integer taskId;//任务id
private Integer stopOperatorId;//暂停操作人id
private String stopOperator;//暂停操作人
private String stopDate;//暂停时间
private String restartDate;//重新开始时间
private Integer stopOrder;//当前暂停次序
private String remark;//备注
public Integer getTaskId() {
return taskId;
}
public void setTaskId(Integer taskId) {
this.taskId = taskId;
}
public Integer getStopOperatorId() {
return stopOperatorId;
}
public void setStopOperatorId(Integer stopOperatorId) {
this.stopOperatorId = stopOperatorId;
}
public String getStopDate() {
return stopDate;
}
public void setStopDate(String stopDate) {
this.stopDate = stopDate;
}
public String getRestartDate() {
return restartDate;
}
public void setRestartDate(String restartDate) {
this.restartDate = restartDate;
}
public Integer getStopOrder() {
return stopOrder;
}
public void setStopOrder(Integer stopOrder) {
this.stopOrder = stopOrder;
}
@ColumnTransient
public String getStopOperator() {
return stopOperator;
}
public void setStopOperator(String stopOperator) {
this.stopOperator = stopOperator;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", taskId=").append(taskId);
sb.append(", stopOperatorId=").append(stopOperatorId);
sb.append(", stopDate=").append(stopDate);
sb.append(", restartDate=").append(restartDate);
sb.append(", stopOrder=").append(stopOrder);
sb.append(", remark=").append(stopOrder);
sb.append("]");
return sb.toString();
}
} | [
"1721985139@qq.com"
] | 1721985139@qq.com |
07ea106bbf7af75022932cfbd4485c70564010dc | e4ede82da2c65fd38a3bd64170f8df7992d2d217 | /src/main/java/com/wyj/entity/system/Menu.java | c1199dff17913bfa7472d1bc4a5bfa30bad97e42 | [] | no_license | uestczwj/wyj-springboot-security | 78dd52ba7cfa861b0198d815bbd7bb32d636c15f | 4f3e47eb5632a90359c048984355750740dc4f4f | refs/heads/master | 2021-05-14T05:00:06.092234 | 2018-01-03T08:56:37 | 2018-01-03T08:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,267 | java | package com.wyj.entity.system;
import java.util.Date;
import java.util.List;
import com.wyj.common.entity.BaseEntity;
/**
* 菜单
*
*
* @author:WangYuanJun
* @date:2017年11月22日 下午8:25:35
*/
public class Menu extends BaseEntity {
private Long menuId; // 菜单id
private Long parentId; // 父级id一级菜单为0
private String parentName;// 父级菜单名称
private String name;// 菜单名称
private String url;// 菜单url
private String perms;// 授权标识(多个用逗号分隔,如:user:list,user:create)
private Integer type;// 类型(0:目录1:菜单 2:按钮)
private Integer orderNum;// 排序
private Integer isUse;// 是否使用
private Date createTime;
private Long createUserId;
private Date modifyTime;
private Long modifyUserId;
private List<?> list;
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
// public Integer getType() {
// return type;
// }
//
// public void setType(Integer type) {
// this.type = type;
// }
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Long getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public Long getModifyUserId() {
return modifyUserId;
}
public void setModifyUserId(Long modifyUserId) {
this.modifyUserId = modifyUserId;
}
public Integer getIsUse() {
return isUse;
}
public void setIsUse(Integer isUse) {
this.isUse = isUse;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
| [
"1098345452@qq.com"
] | 1098345452@qq.com |
70dc88365fd838423e6e7ac79cc39119bb636033 | 1b307344a0dd5590e204529b7cc7557bed02d2b9 | /sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetImmutabilityPolicySamples.java | 14371ea48fbad647f470a34b61382e8385507c37 | [
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"LicenseRef-scancode-generic-cla"
] | permissive | alzimmermsft/azure-sdk-for-java | 7e72a194e488dd441e44e1fd12c0d4c1cacb1726 | 9f5c9b2fd43c2f9f74c4f79d386ae00600dd1bf4 | refs/heads/main | 2023-09-01T00:13:48.628043 | 2023-03-27T09:00:31 | 2023-03-27T09:00:31 | 176,596,152 | 4 | 0 | MIT | 2023-03-08T18:13:24 | 2019-03-19T20:49:38 | Java | UTF-8 | Java | false | false | 1,033 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storage.generated;
import com.azure.core.util.Context;
/** Samples for BlobContainers GetImmutabilityPolicy. */
public final class BlobContainersGetImmutabilityPolicySamples {
/*
* x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2022-09-01/examples/BlobContainersGetImmutabilityPolicy.json
*/
/**
* Sample code: GetImmutabilityPolicy.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void getImmutabilityPolicy(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.storageAccounts()
.manager()
.serviceClient()
.getBlobContainers()
.getImmutabilityPolicyWithResponse("res5221", "sto9177", "container3489", null, Context.NONE);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
94f37957cfc4996eaee9e3746098d132858487a7 | aac666abb83a161d54c1d63b8afff7839d85729f | /src/git/Git.java | ecddf6ffec835dea0a7a9ef92d53a020dae786e4 | [] | no_license | mariana-guerrero/prueba | 523d800f8d70290d064b71cad4d3c29004d49cff | adea3903bc9dccd7fa34bde63e5325f956dd18c2 | refs/heads/master | 2023-05-08T21:55:28.982943 | 2021-05-26T20:46:10 | 2021-05-26T20:46:10 | 364,679,940 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java |
package git;
public class Git {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hola mundo ");
System.out.println("como estas");
}
}
| [
"mariana.gue.cau@gmail.com"
] | mariana.gue.cau@gmail.com |
2c301037b0ed5fac394941b4cf1aa3f8d8c72fcf | 484936b0b002e1616b7d12b0fc79f0972b74ae53 | /src/main/java/com/cucumber/framework/PageObjects/CaseManagementCycleTriagerPage.java | d36c40b01a810639e9814f70630ac501dc7235d6 | [] | no_license | BharatBhushan0204/OneFlow_Master | 4f721f25c2509d37167156b058af1ab597423f3e | 6f3449ce0d9a5943ac8932dcbeafda52ebcd7509 | refs/heads/master | 2020-11-24T09:11:55.168222 | 2019-12-17T09:17:17 | 2019-12-17T09:17:17 | 228,069,771 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,011 | java | package com.cucumber.framework.PageObjects;
import java.util.List;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import com.cucumber.framework.GeneralHelperSel.LoggerHelper;
import com.cucumber.framework.GeneralHelperSel.SeleniumFunc;
public class CaseManagementCycleTriagerPage extends SeleniumFunc
implements CaseManagementCycleTriagerPageLoc, CaseManagementCycleCSOPageLoc, CaseManagementCycleSMPageLoc {
public CaseManagementCycleTriagerPage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
private final Logger log = LoggerHelper.getLogger(CaseManagementCycleTriagerPage.class);
CaseManagementCycleTriagerPage caseManagementCycleTriagerPage;
public void sendCaseManagementCycleTriagerObject(CaseManagementCycleTriagerPage caseManagementCycleTriagerPage) {
this.caseManagementCycleTriagerPage = caseManagementCycleTriagerPage;
// System.out.println("In sendLoginObject method search page"+this.loginpage);
}
/*
* #############################################################################
* Author : Babu Scenario : Exception work basket Description : fetch the case
* information note content verification in complex WB
* #############################################################################
*/
public void clickonComplexWB() throws Exception {
// click on complex work basket
xpath_GenericMethod_Click(complex_workbasket);
}
/*
* #############################################################################
* Author : Babu Scenario : Exception work basket Description : fetch the case
* information note content verification in exception WB
* #############################################################################
*/
public void clickonExceptionWB() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(Exception_workbasket);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
CaseManagementCycleTriagerPage.informationNotedisplay();
}
/*
* #############################################################################
* Author : Babu Scenario : Case Information Note Display Description : fetch
* the case information note content verification
* #############################################################################
*/
public static void informationNotedisplay() throws Exception {
Thread.sleep(3000);
xpath_GenericMethod_Click(case_heading_label);
Thread.sleep(3000);
xpath_GenericMethod_Click(case_heading_label);
Thread.sleep(3000);
List<WebElement> list_of_cases = driver.findElements(By.xpath(case_list));
int total_cases = list_of_cases.size();
System.out.println(total_cases);
for (int i = 0; i < total_cases; i++) {
WebDriverWait wait = new WebDriverWait(driver, 30);
xpath_GenericMethod_Click(First_case);
driver.switchTo().defaultContent();
Thread.sleep(3000);
// get the content of the information note
goToFrameByTag_IdByXpath(notedisplayed);
String notedis = driver.findElement(By.xpath(notedisplayed)).getText();
System.out.println("information note message display:" + notedis);
String multipletypesofrequest = "The case has been routed to the complex workbasket "
+ "+because multiple type of requests have been identified";
String multipletypesofrequestandpolicy_quotenumber = "The case has been routed to the complex workbasket because multiple "
+ "+type of requests and policy/quote number have been identified";
String multiplepolicy_quotenumber = "The case has been routed to the complex "
+ "+workbasket because multiple policy/quote number have been identified";
String withouttypeofrequestandpolicy_quotenumber = "The case has been routed to the exception workbasket because "
+ "+no policy/quote number nor type of request were identified.";
String withoutpolicyquotenumber = "The case has been routed to the exception workbasket because no policy/quote number was identified.";
if (notedis.equalsIgnoreCase(multipletypesofrequest)) {
Assert.assertEquals(notedis, multipletypesofrequest);
System.out.println("For those case identified with multiple types of request");
} else if (notedis.equalsIgnoreCase(multipletypesofrequestandpolicy_quotenumber)) {
Assert.assertEquals(notedis, multipletypesofrequestandpolicy_quotenumber);
System.out.println("For those case identified with multiple types of request and policy/quote number");
} else if (notedis.equalsIgnoreCase(multiplepolicy_quotenumber)) {
Assert.assertEquals(notedis, multiplepolicy_quotenumber);
System.out.println("For those case identified with multiple policy/quote number");
} else if (notedis.equalsIgnoreCase(withouttypeofrequestandpolicy_quotenumber)) {
Assert.assertEquals(notedis, withouttypeofrequestandpolicy_quotenumber);
System.out.println("For those case identified without type of request and policy/quote number");
} else if (notedis.equalsIgnoreCase(withoutpolicyquotenumber)) {
Assert.assertEquals(notedis, withoutpolicyquotenumber);
System.out.println("For those case identified without policy/quote number");
}
else {
System.out.println("************information note not available************");
}
String SLAvalue = driver.findElement(By.xpath(SLA_Xpath)).getText();
System.out.println("SLA value:" + SLAvalue);
xpath_GenericMethod_Click(closebutton);
break;
}
}
/*
* #############################################################################
* Author : Babu Scenario : Out-of-scope work basket Description : out-of-scope
* WB
* #############################################################################
*/
public void clickon_OutofScope_WB() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(outofscope_xpath);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
CaseManagementCycleTriagerPage.informationNotedisplay();
}
/*
* #############################################################################
* Author : Babu Scenario : Get Next work Description : Get next work flow
* #############################################################################
*/
public void getNext_work() throws Exception {
Thread.sleep(2000);
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
xpath_GenericMethod_Click(getnext_xpath);
driver.switchTo().defaultContent();
Thread.sleep(2000);
xpath_GenericMethod_Sendkeys(insured_xpath, "testdemo");
Thread.sleep(3000);
xpath_GenericMethod_selectFromDropdownUsingIndexbyclickingOnDropdown(typeofreq_xpath, 6);
Thread.sleep(3000);
xpath_GenericMethod_selectFromDropdownUsingIndexbyclickingOnDropdown(policy_Quote_xpath, 2);
Thread.sleep(3000);
xpath_GenericMethod_Sendkeys(Quote_xpath, "QI 1234567 PLB");
xpath_GenericMethod_Click(submit_xpath);
Thread.sleep(5000);
xpath_GenericMethod_Click(getnext);
}
/*
* #############################################################################
* Author : Babu Scenario : Get Next work Description : reassign work
* #############################################################################
*/
public void reassignwork() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(Exception_workbasket);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
Thread.sleep(3000);
List<WebElement> list_of_cases = driver.findElements(By.xpath(case_list));
int total_cases = list_of_cases.size();
System.out.println(total_cases);
for (int i = 0; i < total_cases; i++) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(list_of_cases.get(i)));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", list_of_cases.get(i));
driver.switchTo().defaultContent();
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(reassign_xpath);
Thread.sleep(2000);
xpath_GenericMethod_selectFromDropdownUsingIndexbyclickingOnDropdown(transferto_xpath, 1);
Thread.sleep(3000);
xpath_GenericMethod_Sendkeys(workqueue_xpath, "Complex");
Thread.sleep(3000);
xpath_GenericMethod_Click(Complex_xpath);
Thread.sleep(3000);
xpath_GenericMethod_Click(btnReassign_xpath);
break;
}
}
public void OpenComplexCaseAndVerifySubject(String Sub, String from) throws Exception {
CommonPage.caseVerification(complex_workbasket, Sub, from);
}
public void OpenExceptionCaseAndVerifySubject(String Sub, String from) throws Exception {
CommonPage.caseVerification(Exception_workbasket, Sub, from);
}
/*
* #############################################################################
* Author : Babu Scenario : reassign work Description : reassign work-operator
* #############################################################################
*/
public void reassignworktooperator() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(complex_workbasket);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
Thread.sleep(3000);
List<WebElement> list_of_cases = driver.findElements(By.xpath(case_list));
int total_cases = list_of_cases.size();
System.out.println(total_cases);
for (int i = 0; i < total_cases; i++) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(list_of_cases.get(i)));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", list_of_cases.get(i));
driver.switchTo().defaultContent();
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(reassign_xpath);
Thread.sleep(2000);
xpath_GenericMethod_selectFromDropdownUsingIndexbyclickingOnDropdown(transferto_xpath, 2);
Thread.sleep(3000);
xpath_GenericMethod_Sendkeys(workqueue_xpath, "Triage user");
Thread.sleep(3000);
// xpath_GenericMethod_Click(Complex_xpath);
Thread.sleep(3000);
xpath_GenericMethod_Click(compl_xpath);
Thread.sleep(3000);
xpath_GenericMethod_Click(btnReassign_xpath);
break;
}
}
/*
* #############################################################################
* Author : Babu Scenario : forward email & Compose new email work Description :
* forward mail to multiple user
* #############################################################################
*/
public void forwardEmail() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(Exception_workbasket);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
Thread.sleep(3000);
List<WebElement> list_of_cases = driver.findElements(By.xpath(case_list));
int total_cases = list_of_cases.size();
System.out.println(total_cases);
for (int i = 0; i < total_cases; i++) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(list_of_cases.get(i)));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", list_of_cases.get(i));
driver.switchTo().defaultContent();
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(forwardEmail_xpath);
Thread.sleep(2000);
String casestatus = driver.findElement(By.xpath(statusofcase)).getText();
String casetext = casestatus;
System.out.println(casestatus);
Assert.assertEquals(casetext, casestatus);
xpath_GenericMethod_Click(mail_submit);
String text = driver.switchTo().alert().getText();
System.out.println("fetch text:" + text);
Thread.sleep(2000);
driver.switchTo().alert().accept();
Assert.assertEquals("Please correct flagged fields before submitting the form!", text);
Thread.sleep(2000);
xpath_GenericMethod_Sendkeys(tomail_xpath, "baburao.lunavath@qbe.com;");
Thread.sleep(2000);
Thread.sleep(2000);
xpath_GenericMethod_Click(mail_submit);
Thread.sleep(6000);
String casestatus1 = driver.findElement(By.xpath(statusofcase)).getText();
String casetext1 = casestatus1;
System.out.println(casestatus1);
Assert.assertEquals(casetext1, casestatus1);
Assert.assertNotEquals(casestatus1, casestatus);
Thread.sleep(2000);
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(refreshaction);
Thread.sleep(4000);
xpath_GenericMethod_Click(audit);
String forwardmailaudit = "Email Forward Successful";
String mailforward = driver.findElement(By.xpath("//span[text()='Email Forward Successful']")).getText();
System.out.println(mailforward);
Assert.assertEquals(forwardmailaudit, mailforward);
break;
}
}
public void composeNewEmail() throws Exception {
driver.switchTo().defaultContent();
// click on exception WB
Thread.sleep(3000);
xpath_GenericMethod_Click(Exception_workbasket);
xpath_GenericMethod_Click(refresh);
xpath_GenericMethod_Click(refresh);
Thread.sleep(3000);
List<WebElement> list_of_cases = driver.findElements(By.xpath(case_list));
int total_cases = list_of_cases.size();
System.out.println(total_cases);
for (int i = 0; i < total_cases; i++) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(list_of_cases.get(i)));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", list_of_cases.get(i));
driver.switchTo().defaultContent();
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(newemail);
Thread.sleep(2000);
String casestatus = driver.findElement(By.xpath(statusofcase)).getText();
String casetext = casestatus;
System.out.println(casestatus);
Assert.assertEquals(casetext, casestatus);
Thread.sleep(2000);
xpath_GenericMethod_Click(mail_submit);
Thread.sleep(6000);
xpath_GenericMethod_Click(actions_xpath);
Thread.sleep(2000);
xpath_GenericMethod_Click(refreshaction);
Thread.sleep(4000);
xpath_GenericMethod_Click(audit);
String composenewmail = "Performed a ' Compose New Email '.";
String newmail = driver.findElement(By.xpath("//span[contains(text(),'Compose New Email')]")).getText();
System.out.println(newmail);
Assert.assertEquals(composenewmail, newmail);
break;
}
}
}
| [
"BharatBhushan.Thanikanti@qbe.com"
] | BharatBhushan.Thanikanti@qbe.com |
4352ade28fc5ddc14cd87eb08d28adce28963732 | 38bd9458868535b19aec0315313b8e6f60d2b4c6 | /app/src/main/java/com/hxuanyu/mytools/utils/MyToast.java | 53cf93f193a307c7ce54a77ccbad2f1a623d1564 | [] | no_license | hanxuanyu/Hxy_tools | 47e786cbfcf94be26701bb6d2f5709ed52a7be06 | 7f7b717ff1a469cf1c475c8db49c5fbf4119ccb9 | refs/heads/main | 2023-03-24T02:44:00.299936 | 2021-03-11T05:03:43 | 2021-03-11T05:03:43 | 346,583,702 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,727 | java | package com.hxuanyu.mytools.utils;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hxuanyu.mytools.R;
public class MyToast {
private static Toast mToast;
/**
* 展示toast==LENGTH_SHORT
*
* @param msg
*/
public static void show(Context context,String msg) {
show(context,msg, Toast.LENGTH_SHORT);
}
/**
* 展示toast==LENGTH_LONG
*
* @param msg
*/
public static void showLong(Context context,String msg) {
show(context,msg, Toast.LENGTH_LONG);
}
private static void show(Context context,String massage, int show_length) {
//使用布局加载器,将编写的toast_layout布局加载进来
View view = LayoutInflater.from(context).inflate(R.layout.toast_custom, null);
//获取ImageView
ImageView image = (ImageView) view.findViewById(R.id.toast_iv);
//设置图片
image.setImageResource(R.mipmap.message);
//获取TextView
TextView title = (TextView) view.findViewById(R.id.toast_tv);
//设置显示的内容
title.setText(massage);
if (mToast != null){
mToast.cancel();
}
mToast = new Toast(context);
//设置Toast要显示的位置,水平居中并在底部,X轴偏移0个单位,Y轴偏移70个单位,
mToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 70);
//设置显示时间
mToast.setDuration(show_length);
mToast.setView(view);
mToast.show();
}
}
| [
"2252193204@qq.com"
] | 2252193204@qq.com |
fff5a7c740acfdcbd801a9bb2966dc14a08bc0a5 | 9ad13a3d609c9cd19394856e0fc3fae99ea3d2ca | /app/src/main/java/com/zhjy/cultural/services/patrol/biz/callback/SimpleSubscriber.java | d68f9bd64332c81259502e67b20b4a112f74459d | [] | no_license | zyong54007/Cultural_Patrol | 47de69e525a6fafcc522150663fca1d029365ef6 | dfceea710bfccfc4a968f9fdad6559a0995887e5 | refs/heads/master | 2020-05-23T13:16:56.118709 | 2018-09-26T01:17:24 | 2018-09-26T01:17:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,789 | java | package com.zhjy.cultural.services.patrol.biz.callback;
import com.zhjy.cultural.services.patrol.biz.pojo.response.BaseResponse;
import com.zhjy.cultural.services.patrol.core.log.AppLog;
import rx.Subscriber;
/**
* SimpleSubscriber <br/>
*/
public class SimpleSubscriber<T extends BaseResponse> extends Subscriber<T> {
private boolean isSuccess = false; // 是否成功
private T response; // 得到的数据结果
@Override
public void onStart() {
super.onStart();
AppLog.d(this + "....onStart");
}
@Override
public final void onNext(T response) {
AppLog.d(this + "....onNext");
if (response == null) {
AppLog.e("response is null.");
onHandleFail(response.toString(), null);
return;
}
isSuccess = true;
onHandleSuccess(response);
}
@Override
public final void onError(Throwable throwable) {
AppLog.d(this + "....onError");
onHandleFail(null, throwable);
onHandleFinish();
}
@Override
public final void onCompleted() {
AppLog.d(this + "....onCompleted");
onHandleFinish();
}
/**
* 处理成功
*/
public void onHandleSuccess(T response) {
AppLog.d("response = " + response);
}
/**
* 处理失败
*/
public void onHandleFail(String message, Throwable throwable) {
AppLog.d(this + "....onHandleFail");
AppLog.e("message = %s ,throwable = %s", message, throwable);
}
/**
* 处理结束
*/
public void onHandleFinish() {
AppLog.d(this + "....onHandleFinish");
}
public T getResponse() {
return response;
}
public boolean isSuccess() {
return isSuccess;
}
} | [
"zpf_pengfeizhang@aliyun.com"
] | zpf_pengfeizhang@aliyun.com |
844cb4cc7dd2f9da059dca1d8fb442eea81ef742 | f4e59fdc59f5e4911164c3cded6d3704469ab890 | /Ring Assist/src/edu/fsu/cs/mobile/onDestroy/Ringer/CallAndSmsReceiver.java | 016b07b394e134efe50e983013489395584fe1c0 | [] | no_license | codybaldwin/RingAssist | 950c28668a50ef8a721810f8fb1a977c4dff7ae1 | 060f2f910266ba38dc98b88de30e2b5347833dde | refs/heads/master | 2020-05-18T01:05:45.127948 | 2014-01-08T02:21:23 | 2014-01-08T02:21:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,303 | java | package edu.fsu.cs.mobile.onDestroy.Ringer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.CallLog;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
//Note...commented out the @Overrides to compile
public class CallAndSmsReceiver extends BroadcastReceiver
{
// arbitrarily setting radius until able to get it from activity or decided upon by group
final static double RADIUSINFEET = 200;
final static double RADIUS = RADIUSINFEET / (60 * 5280 * 1.15); // in degrees latitude/longitude
final static int RING_CHANGED_NOTIFICATION_ID = 10;
public final static String PREFS_NAME = "TogglePrefFile";
public boolean sent = false;
Cursor cursor;
@Override
public void onReceive(final Context context, Intent intent)
{
Log.i("just got inside ", " onReceive()");
// Toast.makeText(context, "entered on receive", Toast.LENGTH_LONG).show();
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
boolean toggleSetting = settings.getBoolean("toggleValue", false);
Log.i("toggleSetting is ", "" + toggleSetting);
if (toggleSetting)
{
// getting user's location
LocationManager lManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener lListener = new LocationListener()
{
//@Override
//@Override
public void onLocationChanged(Location location) {}
//@Override
//@Override
public void onProviderDisabled(String provider) {}
//@Override
//@Override
public void onProviderEnabled(String provider) {}
//@Override
//@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
Looper looper = Looper.getMainLooper();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// checking location based on network first, then GPS if network doesn't work
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, lListener);
Location userLocation = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (userLocation == null)
{
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, lListener);
userLocation = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
// checking the database for a location that matches the user's location
Log.i("longitude is ", " " +userLocation.getLongitude());
Log.i("latitude is ", " " +userLocation.getLatitude());
double longitude = userLocation.getLongitude();
double latitude = userLocation.getLatitude();
/*String[] projection = new String[]
{RingAssistProvider.COLUMN_PREFERENCE,
RingAssistProvider.COLUMN_SENDTEXT,
RingAssistProvider.COLUMN_MESSAGE};*/
String selectionClause = RingAssistProvider.COLUMN_LONGITUDE + " > ? AND " +
RingAssistProvider.COLUMN_LONGITUDE + " < ? AND " +
RingAssistProvider.COLUMN_LATITUDE + " > ? AND " +
RingAssistProvider.COLUMN_LATITUDE + " < ? ";
String[] selectionArgs = new String[]
{
(Double.toString(longitude - RADIUS)),
(Double.toString(longitude + RADIUS)),
(Double.toString(latitude - RADIUS)),
(Double.toString(latitude + RADIUS))
};
/*String[] selectionArgs = new String[]
{
((Double)(userLocation.getLongitude() - RADIUS)).toString(),
((Double)(userLocation.getLongitude() + RADIUS)).toString(),
((Double)(userLocation.getLatitude() - RADIUS)).toString(),
((Double)(userLocation.getLatitude() + RADIUS)).toString()
};*/
//projection instead of null before at some point
cursor = context.getContentResolver().query(RingAssistProvider.CONTENT_URI, null,
selectionClause, selectionArgs, null);
cursor.moveToNext();
//Log.i("index zero is ", " " + cursor.getInt(0));
//Log.i("index one is ", " " + cursor.getInt(1));
//Log.i("index two is ", cursor.getString(2));
Log.i("got past ", " first query");
// actually changing the ringer and sending a SMS(maybe)
if (cursor != null && cursor.getCount() > 0)
{
Log.i("cursor is not", "NULL");
Toast.makeText(context, "Within radius", Toast.LENGTH_LONG).show();
AudioManager aManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Log.i("got past audioManager", " ");
int currentRingerMode = aManager.getRingerMode(); //gets the current ringer settings for later
Log.i("got past currentRingerMode", " ");
int userPreference = cursor.getInt(4); //was 0
Log.i("got past userPreference", " ");
int sendingSMS = cursor.getInt(5); //was 1
Log.i("got past sendingSMS", " ");
final String smsMessage = cursor.getString(6); //was 2
Log.i("got past smsMessage", " ");
Log.i("got past bad indexes", " ");
switch (userPreference)
{
case (0): // silent
// changes ringer volume to silent and not vibrate
aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
case (1): // vibrate
// changes ringer volume to silent and sets vibrate setting on
aManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
break;
case (2): // normal/default
// does not change ringer volume or vibrate setting
// aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// for (int i = 1; i <=4; i++)
aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
break;
case (3): // louder
// sets ringer volume louder without changing vibrate setting
// aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// for (int i = 1; i <=6; i++)
aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
// aManager.setRingerMode(AudioManager.ADJUST_RAISE);
break;
case (4): // louder than 3 + vibrate
// sets ringer volume louder twice and sets vibrate setting on
// aManager.setRingerMode(AudioManager.VIBRATE_SETTING_ON); // depreciated
//for (int i = 1; i <=8; i++)
aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
aManager.setRingerMode(AudioManager.ADJUST_RAISE);
// aManager.setRingerMode(AudioManager.ADJUST_RAISE);
break;
}
Log.i("got past switch", " ");
if (sendingSMS == 1)
{
Log.i("inside ", "sendingSMS");
if (intent.getAction() == "android.provider.Telephony.SMS_RECEIVED")
{
Bundle smsBundle = intent.getExtras();
if (smsBundle != null)
{
Object[] pdus = (Object[]) smsBundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String smsSenderNumber = messages[0].getOriginatingAddress();
SmsManager sManager = SmsManager.getDefault();
sManager.sendTextMessage(smsSenderNumber, null, smsMessage, null, null);
sent=true;
//test
NotificationManager nManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ringerChangedNotification = new Notification(R.drawable.ic_launcher,
"Ring Assist",
System.currentTimeMillis());
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
//****************************************//
// GET CONTACT NAME BETA //
//****************************************//
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(smsSenderNumber));
Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
String contactName = null;
if (cursor != null) {
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
if(contactName!=null)
{
ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
"Sent "+contactName+" an automated message!", contentIntent);
}
else
{
ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
"Sent "+smsSenderNumber+" an automated message!", contentIntent);
}
//****************************************//
// END GET CONTACT NAME //
//****************************************//
// ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
// "Automated message sent!", contentIntent);
ringerChangedNotification.flags = Notification.FLAG_AUTO_CANCEL;
nManager.notify(RING_CHANGED_NOTIFICATION_ID, ringerChangedNotification);
//end-test
}
}
TelephonyManager tManager = (TelephonyManager)context.getSystemService(context.TELEPHONY_SERVICE);
if (tManager.getCallState() == TelephonyManager.CALL_STATE_RINGING)
{
//Log.i("stopped ringing", "call state is idle");
// getting phone number from incoming call
// needs a delay because call log is not updated immediately when call is received
// so we delay half a second (aka 500 milliseconds)
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
//@Override
public void run()
{
Log.i("inside", "run");
String[] pNumbProj = new String[] {CallLog.Calls.NUMBER};
Cursor pNumbCursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
pNumbProj, null, null, CallLog.Calls.DATE + " desc");
//pNumbCursor.moveToFirst();
if (pNumbCursor != null)
{
if (pNumbCursor.getCount() > 0)
{
pNumbCursor.moveToFirst(); //or moveToNext()
String pNumber = pNumbCursor.getString(0);
SmsManager sManager = SmsManager.getDefault();
sManager.sendTextMessage(pNumber, null, smsMessage, null, null);
sent=true;
}
}
}
}, 500);
Toast.makeText(context, "Sent automated message.\n" + smsMessage,
Toast.LENGTH_LONG).show();
//test
NotificationManager nManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ringerChangedNotification = new Notification(R.drawable.ic_launcher,
"Ring Assist",
System.currentTimeMillis());
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
"Automated message sent!", contentIntent);
ringerChangedNotification.flags = Notification.FLAG_AUTO_CANCEL;
nManager.notify(RING_CHANGED_NOTIFICATION_ID, ringerChangedNotification);
//end-test
}
/*a
*/
}
Log.i("got into ", "notifications");
// pushing a notification if the ringer/vibrate settings are changed
/* NotificationManager nManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ringerChangedNotification = new Notification(R.drawable.ic_launcher,
"Ring Assist",
System.currentTimeMillis());
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
if(sent)
{
ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
"Automated message sent!", contentIntent);
ringerChangedNotification.flags = Notification.FLAG_AUTO_CANCEL;
nManager.notify(RING_CHANGED_NOTIFICATION_ID, ringerChangedNotification);
}*/
/* else
{
ringerChangedNotification.setLatestEventInfo(context, "Ring Assist",
"The ringer settings have been altered.", contentIntent);
ringerChangedNotification.flags = Notification.FLAG_AUTO_CANCEL;
}*/
}
else
Toast.makeText(context, "Not within radius", Toast.LENGTH_LONG).show();
Log.i("got past", "everything");
// stop getting location updates so app doesn't eat the battery
lManager.removeUpdates(lListener);
}
}
}
| [
"baldwin2163@gmail.com"
] | baldwin2163@gmail.com |
b43888b735bbbc205ea4007ca221b212ba87ab0b | ba18a170b6ea3e5b188b0c4bd2dbe681ed25714e | /src/athens-team-project/src/chat/gui/ChatView.java | b605eee28afada38fcf95c6069fe3c7cf3a102f5 | [] | no_license | Jdavies47/sw | 8046c0b98f162bea5972372216e970a2de80cf3a | 81da5412745fce8c2a1c54c62d9051f127bf3985 | refs/heads/master | 2021-05-08T19:16:39.870135 | 2017-08-01T20:57:36 | 2017-08-01T20:57:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java | package chat.gui;
import chat.Client;
import java.util.Observable;
import java.util.Observer;
public class ChatView implements Observer{
private Client client;
public ChatView(Client client){
this.client = client;
this.client = client;
}
@Override
public void update(Observable o, Object arg) {
}
}
| [
"zsoltpazmandy@gmail.com"
] | zsoltpazmandy@gmail.com |
5cfb8f6db0d6a7e65b8b4637e21d9fcbbdd11153 | 38e31f15f9c1d5972a47f9402da9eea43c6c82f4 | /src/test/java/SqsResponseProcessorTest.java | 99905e2c333f4e6ee4b0099f6f365633d7df083c | [] | no_license | MatthewBurstein/EventProcessing | 171d83758aae2a3466d08f28d453ef583ffef280 | 5edbc343047d448be240975009e857aea60bbb53 | refs/heads/master | 2020-03-21T05:42:33.455425 | 2018-07-02T13:49:44 | 2018-07-02T13:49:44 | 138,175,246 | 0 | 0 | null | 2021-01-08T09:57:56 | 2018-06-21T13:39:29 | Java | UTF-8 | Java | false | false | 2,210 | java | import com.google.common.collect.Lists;
import eventprocessing.models.*;
import eventprocessing.responseservices.ResponseProcessor;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
public class SqsResponseProcessorTest {
private Sensor mockSensor;
private SensorList mockSensorList;
private Message mockMessage;
private SqsResponse mockSqsResponse;
private Bucket mockBucket;
private ResponseProcessor responseProcessor;
@Before
public void setup() {
mockSensor = Mockito.mock(Sensor.class);
when(mockSensor.getId()).thenReturn("validId");
mockSensorList = Mockito.mock(SensorList.class);
when(mockSensorList.getSensors()).thenReturn(Lists.newArrayList(mockSensor));
mockMessage = Mockito.mock(Message.class);
mockSqsResponse = Mockito.mock(SqsResponse.class);
when(mockSqsResponse.getMessage()).thenReturn(mockMessage);
mockBucket = Mockito.mock(Bucket.class);
when(mockBucket.getMessageIds()).thenReturn(Lists.newArrayList("messageId1", "messageId2"));
responseProcessor = new ResponseProcessor();
}
@Test
public void isWorkingSensor_returnsTrue() {
when(mockMessage.getLocationId()).thenReturn("validId");
assertTrue(responseProcessor.isWorkingSensor(mockSqsResponse, mockSensorList));
}
@Test
public void isNotWorkingSensor_returnsFalse() {
when(mockMessage.getLocationId()).thenReturn("invalidId");
assertFalse(responseProcessor.isWorkingSensor(mockSqsResponse, mockSensorList));
}
@Test
public void isDuplicateMessage_whenDuplicate_returnsTrue() {
when(mockSqsResponse.getMessageId()).thenReturn("messageId1");
assertTrue(responseProcessor.isDuplicateMessage(mockSqsResponse, mockBucket));
}
@Test
public void isDuplicateMessage_whenNotDuplicate_returnsFalse() {
when(mockSqsResponse.getMessageId()).thenReturn("newMessageId");
assertFalse(responseProcessor.isDuplicateMessage(mockSqsResponse, mockBucket));
}
}
| [
"julian.ng@softwire.com"
] | julian.ng@softwire.com |
4d64753a9821529a0a45ebea22584c315335e2d1 | 96ad90d791394dcbaf4ba49d6b2c5862fe597394 | /AdvancedFarmer.java | 3c86c64936fc9b6e2d6807945da93f84c50b05a1 | [] | no_license | sjure/SOTS | 7dd636ccd054688ab649c2d312eb9d4cf97c6022 | 6fa3a37a72a9ee485a5ef3f3d629a4c31f224c3f | refs/heads/master | 2021-10-24T13:54:39.777111 | 2019-03-26T14:29:01 | 2019-03-26T14:29:01 | 177,803,167 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,567 | java | package SaueSpillet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import javax.swing.ImageIcon;
public class AdvancedFarmer extends GameObject {
private int width = 68;
private int height = 133;
private Random r;
private static Image farmerPic;
private int health;
private GameObject stoneHit;
private boolean flimmer = false;
private long start, end;
public static ArrayList<ID> hitList = new ArrayList<ID>(Arrays.asList(ID.Stone));
public AdvancedFarmer(float x, float y, ID id, Handler handler, int hit, int health) {
super(x, y, id, handler, hit);
r = new Random();
velX = (float) (-0.7 - r.nextFloat()/1.8);
velY = 0;
this.health = health;
loadpic();
handler.addObject(new Trail((int) x - 50, (int) y - 20, ID.InitBoom, handler, 0.025));
start = System.currentTimeMillis();
}
public Rectangle getBounds() {
return new Rectangle((int) x, (int) y, width, height);
}
public void tick() {
r = new Random();
x += velX;
// y += velY;
if (r.nextInt(5) == 1) {
y += 5 - r.nextInt(10);
}
if (y <= 0 || y >= Game.HEIGHT - 131)
velY *= -1;
if (x < 0) {
Hud.health -= 4;
handler.removeObject(this);
}
// if (x <= 0 || x >= Game.WIDTH)
// velX *= -1;
// x = Game.clamp(x, 0, Game.WIDTH);
y = Game.clamp(y, 0, Game.HEIGHT - 132);
collision();
if (hit == 1) {
hit = 0;
health -= 10;
}
if (health < 1) {
handler.removeObject(this);
Hud.increaseKills();
}
}
public void loadpic() {
farmerPic = new ImageIcon(
"C:\\Users\\Sjur\\tdt4100-2018-master\\git\\tdt4100-2018\\minegenkode\\GamepackRes\\farmer2.png")
.getImage();
}
private void collision() {
for (GameObject obj : handler.object) {
for (ID idi : hitList) {
if (obj.getId() == idi) {
if (getBounds() != null && obj.getBounds() != null) {
if (getBounds().intersects(obj.getBounds()) && obj != stoneHit) {
health -= Hud.stoneDamage;
obj.increaseHit();
stoneHit = obj;
Hud.score += 5;
if (health > 0) {
start = System.currentTimeMillis();
flimmer = true;
}
}
}
}
}
}
}
public void render(Graphics g) {
end = System.currentTimeMillis();
if (!((end - start) / 10 < 5)) {
if ((end - start) / 10 > 10 && flimmer) {
start = System.currentTimeMillis();
flimmer = false;
}
//g.drawRect((int) x, (int) y, width, height);
g.drawImage(farmerPic, (int) x, (int) y, null);
}
}
}
| [
"sjure@users.noreply.github.com"
] | sjure@users.noreply.github.com |
410a86404362d62f6cc6ab7970fc2fce2a4535f2 | 4f7231a14e30edc84908f12fc7b59b6ade798fbb | /direct_com/src/Nodes/EdgeNode.java | d428ec3d8fddb76b40ce0596f609a13b4813ee12 | [] | no_license | uheqiang/smpc-1 | 5988a6d7dd79f1332dffe136f91efe385f832f7c | c0a89b1ffcd498e3ef59cc149d78ba18dd4df2ff | refs/heads/master | 2021-06-08T14:06:05.988880 | 2016-12-13T23:23:59 | 2016-12-13T23:23:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 221 | java | package Nodes;
import Abstracts.Node;
import Abstracts.Packet;
/**
* Created by tanish on 4/19/15.
*/
public class EdgeNode extends Node{
public EdgeNode(long dataSize){
this.dataSize = dataSize;
}
}
| [
"abditag2@illinois.edu"
] | abditag2@illinois.edu |
a46649051677d3785c1bbbf18812a1c6f27854d3 | 342924a73d99163d4c21c73ada0278bfb4c30894 | /src/main/java/dev/HotelWebApiApplication.java | b0e2d5bb72429cac89576066bf0a4cabacd1c4d3 | [] | no_license | boukhemis11/Hotel-web-api | 8f3bcb5d0de6353d4e6b7f57bf1898944f130718 | 3cd1b1bbd90e93ebd895452a7888583c0b4148a2 | refs/heads/master | 2022-04-21T20:41:42.498850 | 2020-04-26T11:27:35 | 2020-04-26T11:27:35 | 257,085,671 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package dev;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HotelWebApiApplication {
public static void main(String[] args) {
SpringApplication.run(HotelWebApiApplication.class, args);
}
}
| [
"boukhemis2011@gmail.com"
] | boukhemis2011@gmail.com |
7d5f49baab6ad124bb5548823fd9fc7375adceff | f72f659a03b74bec87a5bc6923841f06109cab89 | /backend/src/main/java/br/pratico/JavaReactq/a/entities/Administrador.java | 72b317face387f0e670450d0195b44909c1e6cd4 | [] | no_license | LoveneykensPhilogene/solucao-sala-QA | 08179f4095fbbf8fe0493e691980c45eba783e28 | e930419cb4d8731cbab88dd18ea9fa99621d058c | refs/heads/main | 2023-08-22T06:31:39.512756 | 2021-09-28T03:39:54 | 2021-09-28T03:39:54 | 411,092,836 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,371 | java | package br.pratico.JavaReactq.a.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Administrador implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String nome;
private String sobreNome;
private String email;
private String telefone;
public Administrador() {
}
public Administrador(Long id, String nome, String sobreNome, String email, String telefone) {
this.id = id;
this.nome = nome;
this.sobreNome = sobreNome;
this.email = email;
this.telefone = telefone;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobreNome() {
return sobreNome;
}
public void setSobreNome(String sobreNome) {
this.sobreNome = sobreNome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
| [
"loveneykens@gmail.com"
] | loveneykens@gmail.com |
d866063e305f2df330e5d17b585e501e5dd9530d | f41f4adc7a734b91ae9d3f31af125eb7ab7288f4 | /src/main/java/fr/ippon/ikado/service/SocialService.java | 334ebbea47e7dcc821aa14b708b1470152330d89 | [] | no_license | wrouvre/ikado | 86eebea2df6030be16ba63614b577e2f3dd87637 | 0938243439275ca925c20287975cce0c8b523d4b | refs/heads/master | 2021-01-01T16:22:17.553415 | 2017-07-20T10:02:21 | 2017-07-20T10:02:21 | 97,814,941 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,619 | java | package fr.ippon.ikado.service;
import fr.ippon.ikado.domain.Authority;
import fr.ippon.ikado.domain.User;
import fr.ippon.ikado.repository.AuthorityRepository;
import fr.ippon.ikado.repository.UserRepository;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
@Service
public class SocialService {
private final Logger log = LoggerFactory.getLogger(SocialService.class);
private final UsersConnectionRepository usersConnectionRepository;
private final AuthorityRepository authorityRepository;
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
private final MailService mailService;
public SocialService(UsersConnectionRepository usersConnectionRepository, AuthorityRepository authorityRepository,
PasswordEncoder passwordEncoder, UserRepository userRepository,
MailService mailService) {
this.usersConnectionRepository = usersConnectionRepository;
this.authorityRepository = authorityRepository;
this.passwordEncoder = passwordEncoder;
this.userRepository = userRepository;
this.mailService = mailService;
}
public void deleteUserSocialConnection(String login) {
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(login);
connectionRepository.findAllConnections().keySet().stream()
.forEach(providerId -> {
connectionRepository.removeConnections(providerId);
log.debug("Delete user social connection providerId: {}", providerId);
});
}
public void createSocialUser(Connection<?> connection, String langKey) {
if (connection == null) {
log.error("Cannot create social user because connection is null");
throw new IllegalArgumentException("Connection cannot be null");
}
UserProfile userProfile = connection.fetchUserProfile();
String providerId = connection.getKey().getProviderId();
String imageUrl = connection.getImageUrl();
User user = createUserIfNotExist(userProfile, langKey, providerId, imageUrl);
createSocialConnection(user.getLogin(), connection);
mailService.sendSocialRegistrationValidationEmail(user, providerId);
}
private User createUserIfNotExist(UserProfile userProfile, String langKey, String providerId, String imageUrl) {
String email = userProfile.getEmail();
String userName = userProfile.getUsername();
if (!StringUtils.isBlank(userName)) {
userName = userName.toLowerCase(Locale.ENGLISH);
}
if (StringUtils.isBlank(email) && StringUtils.isBlank(userName)) {
log.error("Cannot create social user because email and login are null");
throw new IllegalArgumentException("Email and login cannot be null");
}
if (StringUtils.isBlank(email) && userRepository.findOneByLogin(userName).isPresent()) {
log.error("Cannot create social user because email is null and login already exist, login -> {}", userName);
throw new IllegalArgumentException("Email cannot be null with an existing login");
}
if (!StringUtils.isBlank(email)) {
Optional<User> user = userRepository.findOneByEmail(email);
if (user.isPresent()) {
log.info("User already exist associate the connection to this account");
return user.get();
}
}
String login = getLoginDependingOnProviderId(userProfile, providerId);
String encryptedPassword = passwordEncoder.encode(RandomStringUtils.random(10));
Set<Authority> authorities = new HashSet<>(1);
authorities.add(authorityRepository.findOne("ROLE_USER"));
User newUser = new User();
newUser.setLogin(login);
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userProfile.getFirstName());
newUser.setLastName(userProfile.getLastName());
newUser.setEmail(email);
newUser.setActivated(true);
newUser.setAuthorities(authorities);
newUser.setLangKey(langKey);
newUser.setImageUrl(imageUrl);
return userRepository.save(newUser);
}
/**
* @return login if provider manage a login like Twitter or GitHub otherwise email address.
* Because provider like Google or Facebook didn't provide login or login like "12099388847393"
*/
private String getLoginDependingOnProviderId(UserProfile userProfile, String providerId) {
switch (providerId) {
case "twitter":
return userProfile.getUsername().toLowerCase();
default:
return userProfile.getEmail();
}
}
private void createSocialConnection(String login, Connection<?> connection) {
ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(login);
connectionRepository.addConnection(connection);
}
}
| [
"wrouvre@ippon.fr"
] | wrouvre@ippon.fr |
6dcfb52742b6a8f8296ed3ec75d73b4a2f041eed | 2e70929bc91815c31baa5f97d90b7f42a859c042 | /android/Wisdom-Island/src/com/drcom/drpalm/View/events/album/ClassAlbumActivityManager.java | b202948eb82fd22f3b17f38061510a1265fd3aed | [] | no_license | KingsleyTeam/Wisdom-Island | 64856d948994f181d620d2ead586c5b785677267 | 63f25e3b7b1bdbf958a5d5003b3495b8ad4fdeed | refs/heads/master | 2020-05-17T10:50:23.152100 | 2014-06-26T13:45:01 | 2014-06-26T13:45:01 | 21,155,853 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,865 | java | package com.drcom.drpalm.View.events.album;
import java.util.Date;
import com.drcom.drpalm.GlobalVariables;
import com.drcom.drpalm.Tool.drHttpClient.HttpStatus;
import com.drcom.drpalm.Tool.request.RequestGetEventListCallback;
import com.drcom.drpalm.Tool.request.RequestGetEventListReloginCallback;
import com.drcom.drpalm.Tool.request.RequestOperation;
import com.drcom.drpalm.objs.MessageObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class ClassAlbumActivityManager {
public static final int UPDATEFINISH = 1; // 刷新请求返回成功
public static final int UPDATEFAILED = 0;
public static final int MOREFINISH = 2; // 更多请求返回成功
public static final int RELOGINSUCCESS = 3; // 重登录
public static final String CATEGORYID_KEY = "categoryidkey";
private static final String LASTREFRESHDATE = "classlastrefreshtime";
private static final String SP_DATABASE_NAME = "classalbum";
private SharedPreferences sp;
private Editor editor;
public ClassAlbumActivityManager(Context c){
sp = c.getSharedPreferences(SP_DATABASE_NAME, Context.MODE_WORLD_READABLE);
editor = sp.edit();
}
public Date getLastUpdateTime(){
return new Date(sp.getLong(LASTREFRESHDATE, 0));
}
public void saveLastUpdateTime(long time)
{
editor.putLong(LASTREFRESHDATE, time);// 保存最后次更新的时间
editor.commit();
}
public void getEventsList(final int categoryId ,final String lastupdate,final String lastreadtime,final Handler h)
{
//mListView.setOnloadingRefreshVisible();
if (HttpStatus.IsNetUsed(GlobalVariables.gAppContext) == HttpStatus.STATUS_NOCONNECT) { // LoginManager.OnlineStatus.ONLINE_LOGINED
Message message = Message.obtain();
if (lastupdate.equals("0")) {
message.arg1 = UPDATEFINISH; // 刷新
} else {
message.arg1 = MOREFINISH; // 更多
}
h.sendMessage(message);
return;
}
RequestOperation mRequestOperation = RequestOperation.getInstance();
RequestGetEventListCallback callback = new RequestGetEventListReloginCallback() {
@Override
public void onSuccess() {
Message message = Message.obtain();
if (lastupdate.equals("0")) {
message.arg1 = UPDATEFINISH; // 刷新
} else {
message.arg1 = MOREFINISH; // 更多
}
message.obj = null;
h.sendMessage(message);
}
@Override
public void onCallbackError(String str) {
Message message = Message.obtain();
message.arg1 = UPDATEFAILED;
message.obj = str;
h.sendMessage(message);
}
@Override
public void onLoading() {
Message message = Message.obtain();
message.arg1 = MOREFINISH; // 更多
message.obj = new MessageObject(true, false);
h.sendMessage(message);
}
@Override
public void onReloginError() {
super.onReloginError();
Message message = Message.obtain();
message.arg1 = UPDATEFAILED; // 更多
message.obj = null;
h.sendMessage(message);
Log.i("zjj", "通告列表:自动重登录失败");
}
@Override
public void onReloginSuccess() {
super.onReloginSuccess();
Log.i("zjj", "通告列表:自动重登录成功");
Message message = Message.obtain();
message.arg1 = RELOGINSUCCESS; //
message.obj = null;
h.sendMessage(message);
// if (isRequestRelogin) {
// sendGetEventsRequest(lastupdate); // 自动登录成功后,再次请求数据
// isRequestRelogin = false;
// }
}
};
mRequestOperation.sendGetNeededInfo("GetEventsList", new Object[] { categoryId, lastupdate,lastreadtime, callback }, callback.getClass().getName());
}
}
| [
"KingsleyYau@gmail.com"
] | KingsleyYau@gmail.com |
d180896aee09d3172afc1930e3757694e4bb800f | 90b45f73d6211854f262caa4618871cbddb4192d | /EmpolyeeBuilder.java | e4b8376cdf9bef84d79c49576d97c39b02ef8643 | [] | no_license | TuChawat/Line | d0f98c934bb16dda2f5fcd41e8b18df15ee9cf27 | 0f33c0486c6013370f3ea43a854922815e2574c6 | refs/heads/main | 2023-05-28T13:31:57.194561 | 2021-06-21T10:19:34 | 2021-06-21T10:19:34 | 346,705,441 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 311 | java | public class EmpolyeeBuilder {
public static void main(String[] args) {
int FULL_TIME = 1;
double emp_type =Math.floor(Math.random() * 100) % 2;
if (emp_type == FULL_TIME)
{
System.out.println("employee is present");
}
else
{
System.out.println("employee is absent");
}
}
}
| [
"tushar1chawat@gmail.com"
] | tushar1chawat@gmail.com |
d86e61cb43b3c5b6effe55a9e59871e245658938 | 3272110cadd8736f0edd31b9887def6d0f6842cf | /E2E_Project/src/test/java/Academy/Listeners.java | 268138dbd84fb4aee3073cdbf260bcebd7a2c902 | [] | no_license | skavadapu/Selenium_E2E_Project | 69f705d226b66144f7ac02807711f5a37b6bce2f | 5b5884ef0a6d702da3532ff91f9ff450ede25054 | refs/heads/master | 2023-06-27T14:38:22.027604 | 2021-07-26T23:21:26 | 2021-07-26T23:21:26 | 389,793,596 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,385 | java | package Academy;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import resources.ExtentReporterNG;
import resources.baseClass;
public class Listeners extends baseClass implements ITestListener{
ExtentReports extent = ExtentReporterNG.getReportObject();
ExtentTest test;
// The below Threadlocal allows to run parellel tests on seperate thread and no conflict of one test case listener with other test case listener
ThreadLocal<ExtentTest> extentTest = new ThreadLocal<ExtentTest>();
@Override
public void onTestStart(ITestResult result) {
// Calling Extent Reports onTestStart
test = extent.createTest(result.getMethod().getMethodName());
extentTest.set(test);
}
@Override
public void onTestSuccess(ITestResult result) {
//
extentTest.get().log(Status.PASS, "Test Passed");
}
@Override
public void onTestFailure(ITestResult result) {
//send the failure log details to report
extentTest.get().fail(result.getThrowable());
WebDriver driver = null;
//Capture failed screenshots
String testMethodName = result.getMethod().getMethodName(); //which gives the testcase name/method
try {
// the below will pull the driver field of relevant testcase
driver = (WebDriver)result.getTestClass().getRealClass().getDeclaredField("driver").get(result.getInstance());
} catch (Exception e1) {
e1.printStackTrace();
}
//Calling the TakeScreenShot method and add the screen to defect in the report with logs
try {
extentTest.get().addScreenCaptureFromPath(getScreenshotPath(testMethodName, driver), result.getMethod().getMethodName());
} catch (Exception e2) {
e2.printStackTrace();
}
}
@Override
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}
@Override
public void onFinish(ITestContext context) {
// Print the reports after all tests execution completes
extent.flush();
}
}
| [
"skavadapu@yahoo.com"
] | skavadapu@yahoo.com |
599a4068840d1d1b997f4daea152ede6dca80a1f | 769c93239bea91770036a470682815103c7418b9 | /src/main/java/contacts/Contact.java | 12051ea8bcf5538b283284e91bee791b03a334e0 | [] | no_license | AaronEngi/story | e9862aadc84f3a60a1aba875c7b54264c4fcd9bf | efcb9078e3009c4cbf126823c6234cc1b7c89cc7 | refs/heads/master | 2021-08-27T17:25:26.033866 | 2017-06-16T01:04:48 | 2017-06-16T01:04:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,037 | java | package contacts;
public class Contact {
private Long id;
private String firstName;
private String lastName;
private String phoneNumber;
private String emailAddress;
private String story;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getEmailAddress() {
return emailAddress;
}
public void setStory(String story) {
this.story = story;
}
public String getStory() {
return story;
}
} | [
"343331640@qq.com"
] | 343331640@qq.com |
f51a99fcc5579baf687c6a243666b6c15e3f4fba | 0e6203f0b01f7dacebc79f0240c14230d546894d | /src/main/java/server/entity/Result.java | 7700967b4c73f151ca7a1084fa1b0f13242f3123 | [] | no_license | 15608447849/file-server | 3a11acf3053fd2f1509698bf94c9883c5c5e2308 | 81eef2f7a4d09c59596932839c894db54e2681da | refs/heads/master | 2020-04-11T20:42:17.003801 | 2019-03-15T10:35:08 | 2019-03-15T10:35:08 | 162,080,070 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 839 | java | package server.entity;
import java.util.HashMap;
import java.util.Map;
import static server.servlet.iface.Mservlet.RESULT_CODE.*;
/**
* Created by user on 2017/11/29.
*/
public class Result<T extends Result> {
private static Map<Integer,String> errorMap = new HashMap<>();
static {
errorMap.put(UNKNOWN,"未知错误");
errorMap.put(SUCCESS,"操作成功");
errorMap.put(EXCEPTION,"异常捕获");
errorMap.put(PARAM_ERROR,"参数错误");
errorMap.put(FILE_NOT_FOUNT,"找不到指定文件或目录");
}
public int code;
public String message;
public Result info(int code, String message){
this.code = code;
this.message = message;
return this;
}
public Result info(int code){
return info(code,errorMap.get(code));
}
}
| [
"793065165@qq.com"
] | 793065165@qq.com |
538c9ca4edbb0d383e748528642aa20edd406f8a | fb6ff67e12e07f13c0000e485161ce997b05bc1a | /hms_project/src/main/java/com/hotel/hms/vo/AccountVO.java | 99246e3ce36c362b4709864a92019702dbd8fa3d | [] | no_license | behappyleee/HotelGroupWare | a297ffcabd427806b5a0a23620674a0bf10507cf | 15a2697125bfda99bc9cc493baa850bc01c3ac00 | refs/heads/main | 2023-03-29T14:31:08.939574 | 2021-04-04T13:55:55 | 2021-04-04T13:55:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,193 | java | package com.hotel.hms.vo;
import lombok.Data;
// 부서테이블
@Data
public class AccountVO {
private long hall_account; // 연회장 결산
private String hall_date; // 연회장 날짜
private long room_account; // 객실 결산
private String room_date; // 객실 날짜
private long pmt_account; // 손실 합계
private String pmt_date; // 손실 지급일
private long sum_sales; // 총 매출액
private long sum_expense; // 총 손실액
private long sum_profit; // 총 순이익
private long room_account_days; // 금일 객실 매출액
private long hall_account_days; // 금일 연회장 매출액
private long pmt_account_days; // 금일 손실액
private long room_account_months; // 금월 객실 매출액
private long hall_account_months; // 금월 연회장 매출액
private long pmt_account_months; // 금월 손실액
private long room_account_years; // 금년 객실 매출액
private long hall_account_years; // 금년 연회장 매출액
private long pmt_account_years; // 금년 손실액
private String this_day; // 금일 날짜
private String this_month; // 월별
private String this_year; // 연별 날짜
} | [
"lklkklkl@naver.com"
] | lklkklkl@naver.com |
ee33175682153bf246436f9856083325cc6c226f | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/android/java/src/org/chromium/chrome/browser/offlinepages/SavePageRequest.java | d319b61d3736f51d34f1657482b0ea5bb0bc4ec2 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,167 | java | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.offlinepages;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Data class representing an underlying request to save a page later.
*/
@JNINamespace("offline_pages::android")
public class SavePageRequest {
// Int representation of the org.chromium.components.offlinepages.RequestState enum.
private int mRequestState;
private long mRequestId;
private String mUrl;
private ClientId mClientId;
/**
* Creates a SavePageRequest that's a copy of the C++ side version.
*
* NOTE: This does not mirror all fields so it cannot be used to create a full SavePageRequest
* on its own.
*
* @param savePageResult Result of the saving. Uses
* {@see org.chromium.components.offlinepages.RequestState} enum.
* @param requestId The unique ID of the request.
* @param url The URL to download
* @param clientIdNamespace a String that will be the namespace of the client ID of this
* request.
* @param clientIdId a String that will be the ID of the client ID of this request.
*/
@CalledByNative("SavePageRequest")
public static SavePageRequest create(
int state, long requestId, String url, String clientIdNamespace, String clientIdId) {
return new SavePageRequest(
state, requestId, url, new ClientId(clientIdNamespace, clientIdId));
}
private SavePageRequest(int state, long requestId, String url, ClientId clientId) {
mRequestState = state;
mRequestId = requestId;
mUrl = url;
mClientId = clientId;
}
public int getRequestState() {
return mRequestState;
}
public long getRequestId() {
return mRequestId;
}
public String getUrl() {
return mUrl;
}
public ClientId getClientId() {
return mClientId;
}
}
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
81bdb3ef25e3a0afc00a1b52172a39b34fbe9de7 | e1075373a6561742b1a180a5cd6e9742ff2d6f9a | /src/game/AI.java | ef3900c350e428b608dcf4d109dd4378ff29907c | [] | no_license | samueldibella/oceanographicXR31 | d3a879e41aacbfaed8951f3f44bd66fd564faff8 | a5c92c1a6235c46c91c3dff9c11afd1c62399c13 | refs/heads/master | 2021-01-22T21:07:09.772472 | 2014-05-29T15:48:31 | 2014-05-29T15:48:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 99 | java | package game;
public interface AI {
void seek();
void wander();
void pause();
void sleep();
}
| [
"samuel.dibella@gmail.com"
] | samuel.dibella@gmail.com |
dc9a4d30e57d8b3e7e346f9e7ed78aad4a909510 | 892bffc2691f38a853402f3973bf8175bc8716a8 | /okr/src/main/java/com/eximbay/okr/service/MemberServiceImpl.java | 744a39563d8a8c1715545c039548a734cf174281 | [] | no_license | JeongWu/okr-system | 1aab5d440bc4e28daaeafde3d149bf47c562cf64 | 6ea91309e1c67a04c6aec2333118b96433b6874b | refs/heads/master | 2023-04-01T13:58:19.958532 | 2021-04-01T07:17:13 | 2021-04-01T07:17:13 | 351,608,127 | 0 | 0 | null | 2021-04-01T07:17:13 | 2021-03-25T23:51:52 | JavaScript | UTF-8 | Java | false | false | 10,487 | java | package com.eximbay.okr.service;
import com.eximbay.okr.config.security.MyUserDetails;
import com.eximbay.okr.constant.ErrorMessages;
import com.eximbay.okr.constant.FlagOption;
import com.eximbay.okr.constant.Subheader;
import com.eximbay.okr.dto.evaluationobjective.EvaluationObjectiveDto;
import com.eximbay.okr.dto.keyresultcollaborator.KeyResultCollaboratorDto;
import com.eximbay.okr.dto.like.LikeDto;
import com.eximbay.okr.dto.member.MemberDto;
import com.eximbay.okr.dto.member.MemberWithActiveDto;
import com.eximbay.okr.dto.objectiverelation.ObjectiveRelationDto;
import com.eximbay.okr.entity.EvaluationOkr;
import com.eximbay.okr.entity.Member;
import com.eximbay.okr.enumeration.ObjectiveType;
import com.eximbay.okr.exception.UserException;
import com.eximbay.okr.model.AllDetailsMemberModel;
import com.eximbay.okr.model.MemberForAllDetailsMemberModel;
import com.eximbay.okr.model.feedback.FeedbackForViewOkrModel;
import com.eximbay.okr.model.keyResult.KeyResultViewOkrModel;
import com.eximbay.okr.model.member.MemberViewOkrModel;
import com.eximbay.okr.model.objective.ObjectiveViewOkrModel;
import com.eximbay.okr.model.profile.EditProfileModel;
import com.eximbay.okr.model.profile.ProfileUpdateModel;
import com.eximbay.okr.repository.MemberRepository;
import com.eximbay.okr.service.Interface.IEvaluationObjectiveService;
import com.eximbay.okr.service.Interface.IEvaluationOkrService;
import com.eximbay.okr.service.Interface.IFeedbackService;
import com.eximbay.okr.service.Interface.IKeyResultCollaboratorService;
import com.eximbay.okr.service.Interface.IKeyResultService;
import com.eximbay.okr.service.Interface.ILikeService;
import com.eximbay.okr.service.Interface.IMemberService;
import com.eximbay.okr.service.Interface.IObjectiveRelationService;
import com.eximbay.okr.service.Interface.IObjectiveService;
import com.eximbay.okr.service.Interface.ITeamMemberService;
import com.eximbay.okr.service.specification.MemberQuery;
import com.eximbay.okr.utils.DateTimeUtils;
import com.eximbay.okr.utils.PagingUtils;
import javassist.NotFoundException;
import lombok.RequiredArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Transactional
public class MemberServiceImpl implements IMemberService {
private final MapperFacade mapper;
private final MemberRepository memberRepository;
private final MemberQuery memberQuery;
private final IObjectiveService objectiveService;
private final IKeyResultService keyResultService;
private final IObjectiveRelationService objectiveRelationService;
private final IKeyResultCollaboratorService keyResultCollaboratorService;
private final IEvaluationOkrService evaluationOkrService;
private final IEvaluationObjectiveService evaluationObjectiveService;
@Autowired
private IFeedbackService feedbackService;
@Autowired
private ILikeService likeService;
@Autowired
private ITeamMemberService teamMemberService;
@Override
public List<MemberDto> findAll() {
List<Member> members = memberRepository.findAll();
return mapper.mapAsList(members, MemberDto.class);
}
@Override
public Optional<MemberDto> findById(Integer id) {
Optional<Member> member = memberRepository.findById(id);
return member.map(m -> mapper.map(m, MemberDto.class));
}
@Override
public void remove(MemberDto memberDto) {
Member member = mapper.map(memberDto, Member.class);
memberRepository.delete(member);
}
@Override
public MemberDto save(MemberDto memberDto) {
Member member = mapper.map(memberDto, Member.class);
member = memberRepository.save(member);
return mapper.map(member, MemberDto.class);
}
@Override
public Optional<MemberDto> findByEmail(String email) {
Optional<Member> member = memberRepository.findByEmail(email);
return member.map(m -> mapper.map(m, MemberDto.class));
}
@Override
public List<MemberDto> findActiveMembers() {
return mapper.mapAsList(memberRepository.findAll(memberQuery.findActiveMember()), MemberDto.class);
}
@Override
public List<MemberDto> findActiveLeadOrDirectorMembers() {
List<Member> members = memberRepository.findAll(
memberQuery.findActiveMember()
.and(memberQuery.findLeadOrDirectorMember())
);
return mapper.mapAsList(members, MemberDto.class);
}
@Override
public Optional<MemberDto> getCurrentMember() {
if (SecurityContextHolder.getContext().getAuthentication() == null ||
!(SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof MyUserDetails))
return Optional.empty();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.ofNullable(((MyUserDetails) principal).getMemberDto());
}
@Override
public MemberViewOkrModel buildMemberViewOkrModel(Integer memberSeq, String quarter) {
MemberViewOkrModel model = new MemberViewOkrModel();
MemberDto member = mapper.map(memberRepository.findById(memberSeq)
.orElseThrow(() -> new UserException(ErrorMessages.resourceNotFound + memberSeq)), MemberDto.class);
model.setMember(member);
model.setMutedHeader(member.getLocalName());
model.setQuarter(quarter);
Optional<MemberDto> currentMember = getCurrentMember();
Optional<EvaluationOkr> evaluationOkr = evaluationOkrService.findByQuarterStringAndObjectiveType(quarter, ObjectiveType.MEMBER.name());
boolean isCurrentMemberCanEditOkr = currentMember.map(m -> m.getAdminFlag().equals(FlagOption.Y) && m.getMemberSeq().equals(memberSeq)).orElse(false);
boolean isEditable = isCurrentMemberCanEditOkr
&& evaluationOkr.map(e -> e.getQuarterEndDate() == null ||
e.getQuarterEndDate().compareToIgnoreCase(DateTimeUtils.getCurrentDateInString()) >= 0).orElse(true);
model.setEditable(isEditable);
List<ObjectiveViewOkrModel> objectives = objectiveService.findMemberObjectivesOkrInQuarterByMemberSeq(memberSeq, quarter);
List<Integer> objectivesSeq = objectives.stream().map(ObjectiveViewOkrModel::getObjectiveSeq).collect(Collectors.toList());
List<KeyResultViewOkrModel> keyResults = keyResultService.findByObjectiveSeqIn(objectivesSeq);
List<Integer> keyResultsSeq = keyResults.stream().map(KeyResultViewOkrModel::getKeyResultSeq).collect(Collectors.toList());
List<EvaluationObjectiveDto> evaluationObjectiveDtos = evaluationObjectiveService.findByObjectivesSeqIn(objectivesSeq);
List<FeedbackForViewOkrModel> feedbacks = feedbackService.getFeedbackForViewOkr(objectivesSeq, keyResultsSeq);
List<ObjectiveRelationDto> objectiveRelations = objectiveRelationService.findByObjectiveSeqInAndRelatedObjectiveNotNull(objectivesSeq);
List<KeyResultCollaboratorDto> keyResultCollaborators = keyResultCollaboratorService.findByKeyResultSeqIn(keyResultsSeq);
List<LikeDto> likes = likeService.getLikeForViewOkr(objectivesSeq, keyResultsSeq);
objectives.forEach(m -> {
m.setKeyResults(keyResults.stream().filter(k -> m.getObjectiveSeq().equals(k.getObjective().getObjectiveSeq())).collect(Collectors.toList()));
});
objectiveService.mapFeedbackIntoObjectiveModel(objectives, feedbacks);
objectiveService.mapLikesIntoObjectiveModel(objectives, likes);
objectiveService.mapObjectiveRelationsIntoObjectiveModel(objectives, objectiveRelations);
objectiveService.mapKeyResultCollaborators(objectives, keyResultCollaborators);
objectiveService.mapEditableForObjectiveModel(objectives, evaluationObjectiveDtos, isCurrentMemberCanEditOkr);
model.setObjectives(objectives);
return model;
}
@Override
public AllDetailsMemberModel buildAllDetailsMemberModel(Pageable pageable) {
AllDetailsMemberModel allDetailsMemberModel = new AllDetailsMemberModel();
Page<Member> memberPage = memberRepository.findAll(memberQuery.findActiveMember(), PagingUtils.buildPageRequest(pageable));
Page<MemberWithActiveDto> members = teamMemberService.addActiveMember(memberPage);
Page<MemberForAllDetailsMemberModel> memberDtoPage = members.map(member -> {
MemberForAllDetailsMemberModel memberForAllDetailsMemberModel = mapper.map(member, MemberForAllDetailsMemberModel.class);
if (memberForAllDetailsMemberModel.getObjectives() != null)
memberForAllDetailsMemberModel.setObjectives(memberForAllDetailsMemberModel.getObjectives().stream()
.filter(m -> FlagOption.N.equals(m.getCloseFlag())).collect(Collectors.toList()));
memberForAllDetailsMemberModel.setKeyResults(member.getKeyResults());
return memberForAllDetailsMemberModel;
});
allDetailsMemberModel.setMembersPage(memberDtoPage);
allDetailsMemberModel.setNavigationPageNumbers(PagingUtils.createNavigationPageNumbers(
allDetailsMemberModel.getMembersPage().getNumber(), allDetailsMemberModel.getMembersPage().getTotalPages()));
allDetailsMemberModel.setSubheader("Quarterly OKRs | Members");
allDetailsMemberModel.setMutedHeader(memberDtoPage.getTotalElements() + "Total");
return allDetailsMemberModel;
}
@Override
public EditProfileModel buildEditProfileModel(Integer id) {
EditProfileModel dataModel = new EditProfileModel();
dataModel.setSubheader(Subheader.EDIT_PROFILE);
Optional<Member> member = memberRepository.findById(id);
Optional<ProfileUpdateModel> model = member.map(m -> mapper.map(m, ProfileUpdateModel.class));
if (model.isEmpty())
throw new UserException(new NotFoundException("Not found Object with Id = " + id));
dataModel.setModel(model.get());
return dataModel;
}
}
| [
"park961003@naver.com"
] | park961003@naver.com |
86de87a489c30e1aaa1f7792c4067666ed789173 | 86a5013c27ccb9eead23d1a08692c59310e4ac6e | /client/src/main/java/com/example/client/service/ConnectionService.java | d4587badb8af255fb6832f919ef038f5e52a90cd | [] | no_license | IrinaKorzhova/Word2Vec | 3d3c9e8eea94ba7412608cf0f52a56c1261ed426 | 67a94d860933e1373975eafdc0ccf2ee618ecc56 | refs/heads/master | 2022-06-06T15:08:32.004641 | 2019-12-28T05:53:53 | 2019-12-28T05:53:53 | 228,823,375 | 0 | 0 | null | 2022-05-20T21:20:39 | 2019-12-18T11:12:41 | Java | UTF-8 | Java | false | false | 1,827 | java | package com.example.client.service;
import com.example.client.ClientApplication;
import com.example.client.dto.Info;
import com.example.client.dto.Word;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Service;
import java.io.*;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
@Service
public class ConnectionService {
private static final Logger logger = LoggerFactory.getLogger(ConnectionService.class);
@Autowired
private Gson gson;
public List<Word> returnWords(Info info) {
List<Word> wordList = null;
try {
Socket socket = new Socket("127.0.0.1", 8000);
BufferedWriter writer = new BufferedWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())));
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
logger.info("Connected to server");
String request = gson.toJson(info);
writer.write(request);
writer.newLine();
writer.flush();
String response = reader.readLine();
Type listType = new TypeToken<ArrayList<Word>>() {
}.getType();
wordList = gson.fromJson(response, listType);
return wordList;
} catch (IOException e) {
e.printStackTrace();
}
return wordList;
}
}
| [
"ira.corjowa2013@yandex.by"
] | ira.corjowa2013@yandex.by |
a1f7d17c988a309b55456ce7bb866bfb2d3802c9 | 5d76b555a3614ab0f156bcad357e45c94d121e2d | /src-v3/android/support/v4/widget/DrawerLayout.java | f2f7b8c942344f7d5f2908c487d4c45e3e5bef90 | [] | no_license | BinSlashBash/xcrumby | 8e09282387e2e82d12957d22fa1bb0322f6e6227 | 5b8b1cc8537ae1cfb59448d37b6efca01dded347 | refs/heads/master | 2016-09-01T05:58:46.144411 | 2016-02-15T13:23:25 | 2016-02-15T13:23:25 | 51,755,603 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 47,829 | java | package android.support.v4.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.os.SystemClock;
import android.support.v4.media.TransportMediator;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.KeyEventCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewGroupCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.ViewDragHelper.Callback;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.BaseSavedState;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer.Std;
public class DrawerLayout extends ViewGroup {
private static final boolean ALLOW_EDGE_LOCK = false;
private static final boolean CHILDREN_DISALLOW_INTERCEPT = true;
private static final int DEFAULT_SCRIM_COLOR = -1728053248;
private static final int[] LAYOUT_ATTRS;
public static final int LOCK_MODE_LOCKED_CLOSED = 1;
public static final int LOCK_MODE_LOCKED_OPEN = 2;
public static final int LOCK_MODE_UNLOCKED = 0;
private static final int MIN_DRAWER_MARGIN = 64;
private static final int MIN_FLING_VELOCITY = 400;
private static final int PEEK_DELAY = 160;
public static final int STATE_DRAGGING = 1;
public static final int STATE_IDLE = 0;
public static final int STATE_SETTLING = 2;
private static final String TAG = "DrawerLayout";
private static final float TOUCH_SLOP_SENSITIVITY = 1.0f;
private boolean mChildrenCanceledTouch;
private boolean mDisallowInterceptRequested;
private int mDrawerState;
private boolean mFirstLayout;
private boolean mInLayout;
private float mInitialMotionX;
private float mInitialMotionY;
private final ViewDragCallback mLeftCallback;
private final ViewDragHelper mLeftDragger;
private DrawerListener mListener;
private int mLockModeLeft;
private int mLockModeRight;
private int mMinDrawerMargin;
private final ViewDragCallback mRightCallback;
private final ViewDragHelper mRightDragger;
private int mScrimColor;
private float mScrimOpacity;
private Paint mScrimPaint;
private Drawable mShadowLeft;
private Drawable mShadowRight;
public interface DrawerListener {
void onDrawerClosed(View view);
void onDrawerOpened(View view);
void onDrawerSlide(View view, float f);
void onDrawerStateChanged(int i);
}
public static class LayoutParams extends MarginLayoutParams {
public int gravity;
boolean isPeeking;
boolean knownOpen;
float onScreen;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
this.gravity = DrawerLayout.STATE_IDLE;
TypedArray a = c.obtainStyledAttributes(attrs, DrawerLayout.LAYOUT_ATTRS);
this.gravity = a.getInt(DrawerLayout.STATE_IDLE, DrawerLayout.STATE_IDLE);
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
this.gravity = DrawerLayout.STATE_IDLE;
}
public LayoutParams(int width, int height, int gravity) {
this(width, height);
this.gravity = gravity;
}
public LayoutParams(LayoutParams source) {
super(source);
this.gravity = DrawerLayout.STATE_IDLE;
this.gravity = source.gravity;
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
this.gravity = DrawerLayout.STATE_IDLE;
}
public LayoutParams(MarginLayoutParams source) {
super(source);
this.gravity = DrawerLayout.STATE_IDLE;
}
}
protected static class SavedState extends BaseSavedState {
public static final Creator<SavedState> CREATOR;
int lockModeLeft;
int lockModeRight;
int openDrawerGravity;
/* renamed from: android.support.v4.widget.DrawerLayout.SavedState.1 */
static class C00431 implements Creator<SavedState> {
C00431() {
}
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
}
public SavedState(Parcel in) {
super(in);
this.openDrawerGravity = DrawerLayout.STATE_IDLE;
this.lockModeLeft = DrawerLayout.STATE_IDLE;
this.lockModeRight = DrawerLayout.STATE_IDLE;
this.openDrawerGravity = in.readInt();
}
public SavedState(Parcelable superState) {
super(superState);
this.openDrawerGravity = DrawerLayout.STATE_IDLE;
this.lockModeLeft = DrawerLayout.STATE_IDLE;
this.lockModeRight = DrawerLayout.STATE_IDLE;
}
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(this.openDrawerGravity);
}
static {
CREATOR = new C00431();
}
}
class AccessibilityDelegate extends AccessibilityDelegateCompat {
private final Rect mTmpRect;
AccessibilityDelegate() {
this.mTmpRect = new Rect();
}
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info);
super.onInitializeAccessibilityNodeInfo(host, superNode);
info.setSource(host);
ViewParent parent = ViewCompat.getParentForAccessibility(host);
if (parent instanceof View) {
info.setParent((View) parent);
}
copyNodeInfoNoChildren(info, superNode);
superNode.recycle();
addChildrenForAccessibility(info, (ViewGroup) host);
}
private void addChildrenForAccessibility(AccessibilityNodeInfoCompat info, ViewGroup v) {
int childCount = v.getChildCount();
for (int i = DrawerLayout.STATE_IDLE; i < childCount; i += DrawerLayout.STATE_DRAGGING) {
View child = v.getChildAt(i);
if (!filter(child)) {
switch (ViewCompat.getImportantForAccessibility(child)) {
case DrawerLayout.STATE_IDLE /*0*/:
ViewCompat.setImportantForAccessibility(child, DrawerLayout.STATE_DRAGGING);
break;
case DrawerLayout.STATE_DRAGGING /*1*/:
break;
case DrawerLayout.STATE_SETTLING /*2*/:
if (child instanceof ViewGroup) {
addChildrenForAccessibility(info, (ViewGroup) child);
break;
}
continue;
case Std.STD_CLASS /*4*/:
break;
default:
continue;
}
info.addChild(child);
}
}
}
public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) {
if (filter(child)) {
return DrawerLayout.ALLOW_EDGE_LOCK;
}
return super.onRequestSendAccessibilityEvent(host, child, event);
}
public boolean filter(View child) {
View openDrawer = DrawerLayout.this.findOpenDrawer();
return (openDrawer == null || openDrawer == child) ? DrawerLayout.ALLOW_EDGE_LOCK : DrawerLayout.CHILDREN_DISALLOW_INTERCEPT;
}
private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) {
Rect rect = this.mTmpRect;
src.getBoundsInParent(rect);
dest.setBoundsInParent(rect);
src.getBoundsInScreen(rect);
dest.setBoundsInScreen(rect);
dest.setVisibleToUser(src.isVisibleToUser());
dest.setPackageName(src.getPackageName());
dest.setClassName(src.getClassName());
dest.setContentDescription(src.getContentDescription());
dest.setEnabled(src.isEnabled());
dest.setClickable(src.isClickable());
dest.setFocusable(src.isFocusable());
dest.setFocused(src.isFocused());
dest.setAccessibilityFocused(src.isAccessibilityFocused());
dest.setSelected(src.isSelected());
dest.setLongClickable(src.isLongClickable());
dest.addAction(src.getActions());
}
}
public static abstract class SimpleDrawerListener implements DrawerListener {
public void onDrawerSlide(View drawerView, float slideOffset) {
}
public void onDrawerOpened(View drawerView) {
}
public void onDrawerClosed(View drawerView) {
}
public void onDrawerStateChanged(int newState) {
}
}
private class ViewDragCallback extends Callback {
private final int mAbsGravity;
private ViewDragHelper mDragger;
private final Runnable mPeekRunnable;
/* renamed from: android.support.v4.widget.DrawerLayout.ViewDragCallback.1 */
class C00441 implements Runnable {
C00441() {
}
public void run() {
ViewDragCallback.this.peekDrawer();
}
}
public ViewDragCallback(int gravity) {
this.mPeekRunnable = new C00441();
this.mAbsGravity = gravity;
}
public void setDragger(ViewDragHelper dragger) {
this.mDragger = dragger;
}
public void removeCallbacks() {
DrawerLayout.this.removeCallbacks(this.mPeekRunnable);
}
public boolean tryCaptureView(View child, int pointerId) {
return (DrawerLayout.this.isDrawerView(child) && DrawerLayout.this.checkDrawerViewAbsoluteGravity(child, this.mAbsGravity) && DrawerLayout.this.getDrawerLockMode(child) == 0) ? DrawerLayout.CHILDREN_DISALLOW_INTERCEPT : DrawerLayout.ALLOW_EDGE_LOCK;
}
public void onViewDragStateChanged(int state) {
DrawerLayout.this.updateDrawerState(this.mAbsGravity, state, this.mDragger.getCapturedView());
}
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
float offset;
int childWidth = changedView.getWidth();
if (DrawerLayout.this.checkDrawerViewAbsoluteGravity(changedView, 3)) {
offset = ((float) (childWidth + left)) / ((float) childWidth);
} else {
offset = ((float) (DrawerLayout.this.getWidth() - left)) / ((float) childWidth);
}
DrawerLayout.this.setDrawerViewOffset(changedView, offset);
changedView.setVisibility(offset == 0.0f ? 4 : DrawerLayout.STATE_IDLE);
DrawerLayout.this.invalidate();
}
public void onViewCaptured(View capturedChild, int activePointerId) {
((LayoutParams) capturedChild.getLayoutParams()).isPeeking = DrawerLayout.ALLOW_EDGE_LOCK;
closeOtherDrawer();
}
private void closeOtherDrawer() {
int otherGrav = 3;
if (this.mAbsGravity == 3) {
otherGrav = 5;
}
View toClose = DrawerLayout.this.findDrawerWithGravity(otherGrav);
if (toClose != null) {
DrawerLayout.this.closeDrawer(toClose);
}
}
public void onViewReleased(View releasedChild, float xvel, float yvel) {
int left;
float offset = DrawerLayout.this.getDrawerViewOffset(releasedChild);
int childWidth = releasedChild.getWidth();
if (DrawerLayout.this.checkDrawerViewAbsoluteGravity(releasedChild, 3)) {
left = (xvel > 0.0f || (xvel == 0.0f && offset > 0.5f)) ? DrawerLayout.STATE_IDLE : -childWidth;
} else {
int width = DrawerLayout.this.getWidth();
left = (xvel < 0.0f || (xvel == 0.0f && offset > 0.5f)) ? width - childWidth : width;
}
this.mDragger.settleCapturedViewAt(left, releasedChild.getTop());
DrawerLayout.this.invalidate();
}
public void onEdgeTouched(int edgeFlags, int pointerId) {
DrawerLayout.this.postDelayed(this.mPeekRunnable, 160);
}
private void peekDrawer() {
boolean leftEdge;
View toCapture;
int childLeft;
int i = DrawerLayout.STATE_IDLE;
int peekDistance = this.mDragger.getEdgeSize();
if (this.mAbsGravity == 3) {
leftEdge = DrawerLayout.CHILDREN_DISALLOW_INTERCEPT;
} else {
leftEdge = DrawerLayout.ALLOW_EDGE_LOCK;
}
if (leftEdge) {
toCapture = DrawerLayout.this.findDrawerWithGravity(3);
if (toCapture != null) {
i = -toCapture.getWidth();
}
childLeft = i + peekDistance;
} else {
toCapture = DrawerLayout.this.findDrawerWithGravity(5);
childLeft = DrawerLayout.this.getWidth() - peekDistance;
}
if (toCapture == null) {
return;
}
if (((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && DrawerLayout.this.getDrawerLockMode(toCapture) == 0) {
LayoutParams lp = (LayoutParams) toCapture.getLayoutParams();
this.mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop());
lp.isPeeking = DrawerLayout.CHILDREN_DISALLOW_INTERCEPT;
DrawerLayout.this.invalidate();
closeOtherDrawer();
DrawerLayout.this.cancelChildViewTouch();
}
}
public boolean onEdgeLock(int edgeFlags) {
return DrawerLayout.ALLOW_EDGE_LOCK;
}
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
View toCapture;
if ((edgeFlags & DrawerLayout.STATE_DRAGGING) == DrawerLayout.STATE_DRAGGING) {
toCapture = DrawerLayout.this.findDrawerWithGravity(3);
} else {
toCapture = DrawerLayout.this.findDrawerWithGravity(5);
}
if (toCapture != null && DrawerLayout.this.getDrawerLockMode(toCapture) == 0) {
this.mDragger.captureChildView(toCapture, pointerId);
}
}
public int getViewHorizontalDragRange(View child) {
return child.getWidth();
}
public int clampViewPositionHorizontal(View child, int left, int dx) {
if (DrawerLayout.this.checkDrawerViewAbsoluteGravity(child, 3)) {
return Math.max(-child.getWidth(), Math.min(left, DrawerLayout.STATE_IDLE));
}
int width = DrawerLayout.this.getWidth();
return Math.max(width - child.getWidth(), Math.min(left, width));
}
public int clampViewPositionVertical(View child, int top, int dy) {
return child.getTop();
}
}
static {
int[] iArr = new int[STATE_DRAGGING];
iArr[STATE_IDLE] = 16842931;
LAYOUT_ATTRS = iArr;
}
public DrawerLayout(Context context) {
this(context, null);
}
public DrawerLayout(Context context, AttributeSet attrs) {
this(context, attrs, STATE_IDLE);
}
public DrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.mScrimColor = DEFAULT_SCRIM_COLOR;
this.mScrimPaint = new Paint();
this.mFirstLayout = CHILDREN_DISALLOW_INTERCEPT;
float density = getResources().getDisplayMetrics().density;
this.mMinDrawerMargin = (int) ((64.0f * density) + 0.5f);
float minVel = 400.0f * density;
this.mLeftCallback = new ViewDragCallback(3);
this.mRightCallback = new ViewDragCallback(5);
this.mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, this.mLeftCallback);
this.mLeftDragger.setEdgeTrackingEnabled(STATE_DRAGGING);
this.mLeftDragger.setMinVelocity(minVel);
this.mLeftCallback.setDragger(this.mLeftDragger);
this.mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, this.mRightCallback);
this.mRightDragger.setEdgeTrackingEnabled(STATE_SETTLING);
this.mRightDragger.setMinVelocity(minVel);
this.mRightCallback.setDragger(this.mRightDragger);
setFocusableInTouchMode(CHILDREN_DISALLOW_INTERCEPT);
ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
ViewGroupCompat.setMotionEventSplittingEnabled(this, ALLOW_EDGE_LOCK);
}
public void setDrawerShadow(Drawable shadowDrawable, int gravity) {
int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this));
if ((absGravity & 3) == 3) {
this.mShadowLeft = shadowDrawable;
invalidate();
}
if ((absGravity & 5) == 5) {
this.mShadowRight = shadowDrawable;
invalidate();
}
}
public void setDrawerShadow(int resId, int gravity) {
setDrawerShadow(getResources().getDrawable(resId), gravity);
}
public void setScrimColor(int color) {
this.mScrimColor = color;
invalidate();
}
public void setDrawerListener(DrawerListener listener) {
this.mListener = listener;
}
public void setDrawerLockMode(int lockMode) {
setDrawerLockMode(lockMode, 3);
setDrawerLockMode(lockMode, 5);
}
public void setDrawerLockMode(int lockMode, int edgeGravity) {
int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this));
if (absGravity == 3) {
this.mLockModeLeft = lockMode;
} else if (absGravity == 5) {
this.mLockModeRight = lockMode;
}
if (lockMode != 0) {
(absGravity == 3 ? this.mLeftDragger : this.mRightDragger).cancel();
}
switch (lockMode) {
case STATE_DRAGGING /*1*/:
View toClose = findDrawerWithGravity(absGravity);
if (toClose != null) {
closeDrawer(toClose);
}
case STATE_SETTLING /*2*/:
View toOpen = findDrawerWithGravity(absGravity);
if (toOpen != null) {
openDrawer(toOpen);
}
default:
}
}
public void setDrawerLockMode(int lockMode, View drawerView) {
if (isDrawerView(drawerView)) {
setDrawerLockMode(lockMode, ((LayoutParams) drawerView.getLayoutParams()).gravity);
return;
}
throw new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity");
}
public int getDrawerLockMode(int edgeGravity) {
int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this));
if (absGravity == 3) {
return this.mLockModeLeft;
}
if (absGravity == 5) {
return this.mLockModeRight;
}
return STATE_IDLE;
}
public int getDrawerLockMode(View drawerView) {
int absGravity = getDrawerViewAbsoluteGravity(drawerView);
if (absGravity == 3) {
return this.mLockModeLeft;
}
if (absGravity == 5) {
return this.mLockModeRight;
}
return STATE_IDLE;
}
void updateDrawerState(int forGravity, int activeState, View activeDrawer) {
int state;
int leftState = this.mLeftDragger.getViewDragState();
int rightState = this.mRightDragger.getViewDragState();
if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) {
state = STATE_DRAGGING;
} else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) {
state = STATE_SETTLING;
} else {
state = STATE_IDLE;
}
if (activeDrawer != null && activeState == 0) {
LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams();
if (lp.onScreen == 0.0f) {
dispatchOnDrawerClosed(activeDrawer);
} else if (lp.onScreen == TOUCH_SLOP_SENSITIVITY) {
dispatchOnDrawerOpened(activeDrawer);
}
}
if (state != this.mDrawerState) {
this.mDrawerState = state;
if (this.mListener != null) {
this.mListener.onDrawerStateChanged(state);
}
}
}
void dispatchOnDrawerClosed(View drawerView) {
LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (lp.knownOpen) {
lp.knownOpen = ALLOW_EDGE_LOCK;
if (this.mListener != null) {
this.mListener.onDrawerClosed(drawerView);
}
sendAccessibilityEvent(32);
}
}
void dispatchOnDrawerOpened(View drawerView) {
LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (!lp.knownOpen) {
lp.knownOpen = CHILDREN_DISALLOW_INTERCEPT;
if (this.mListener != null) {
this.mListener.onDrawerOpened(drawerView);
}
drawerView.sendAccessibilityEvent(32);
}
}
void dispatchOnDrawerSlide(View drawerView, float slideOffset) {
if (this.mListener != null) {
this.mListener.onDrawerSlide(drawerView, slideOffset);
}
}
void setDrawerViewOffset(View drawerView, float slideOffset) {
LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (slideOffset != lp.onScreen) {
lp.onScreen = slideOffset;
dispatchOnDrawerSlide(drawerView, slideOffset);
}
}
float getDrawerViewOffset(View drawerView) {
return ((LayoutParams) drawerView.getLayoutParams()).onScreen;
}
int getDrawerViewAbsoluteGravity(View drawerView) {
return GravityCompat.getAbsoluteGravity(((LayoutParams) drawerView.getLayoutParams()).gravity, ViewCompat.getLayoutDirection(this));
}
boolean checkDrawerViewAbsoluteGravity(View drawerView, int checkFor) {
return (getDrawerViewAbsoluteGravity(drawerView) & checkFor) == checkFor ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
View findOpenDrawer() {
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if (((LayoutParams) child.getLayoutParams()).knownOpen) {
return child;
}
}
return null;
}
void moveDrawerToOffset(View drawerView, float slideOffset) {
float oldOffset = getDrawerViewOffset(drawerView);
int width = drawerView.getWidth();
int dx = ((int) (((float) width) * slideOffset)) - ((int) (((float) width) * oldOffset));
if (!checkDrawerViewAbsoluteGravity(drawerView, 3)) {
dx = -dx;
}
drawerView.offsetLeftAndRight(dx);
setDrawerViewOffset(drawerView, slideOffset);
}
View findDrawerWithGravity(int gravity) {
int absHorizGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)) & 7;
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if ((getDrawerViewAbsoluteGravity(child) & 7) == absHorizGravity) {
return child;
}
}
return null;
}
static String gravityToString(int gravity) {
if ((gravity & 3) == 3) {
return "LEFT";
}
if ((gravity & 5) == 5) {
return "RIGHT";
}
return Integer.toHexString(gravity);
}
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
this.mFirstLayout = CHILDREN_DISALLOW_INTERCEPT;
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
this.mFirstLayout = CHILDREN_DISALLOW_INTERCEPT;
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (!(widthMode == 1073741824 && heightMode == 1073741824)) {
if (isInEditMode()) {
if (widthMode != Integer.MIN_VALUE) {
if (widthMode == 0) {
widthSize = 300;
}
}
if (heightMode != Integer.MIN_VALUE) {
if (heightMode == 0) {
heightSize = 300;
}
}
} else {
throw new IllegalArgumentException("DrawerLayout must be measured with MeasureSpec.EXACTLY.");
}
}
setMeasuredDimension(widthSize, heightSize);
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if (child.getVisibility() != 8) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int i2;
int i3;
if (isContentView(child)) {
i2 = lp.leftMargin;
i3 = lp.rightMargin;
i2 = lp.topMargin;
child.measure(MeasureSpec.makeMeasureSpec((widthSize - r0) - r0, 1073741824), MeasureSpec.makeMeasureSpec((heightSize - r0) - lp.bottomMargin, 1073741824));
} else if (isDrawerView(child)) {
int childGravity = getDrawerViewAbsoluteGravity(child) & 7;
if ((STATE_IDLE & childGravity) != 0) {
throw new IllegalStateException("Child drawer has absolute gravity " + gravityToString(childGravity) + " but this " + TAG + " already has a " + "drawer view along that edge");
}
i2 = this.mMinDrawerMargin;
i3 = lp.leftMargin;
child.measure(getChildMeasureSpec(widthMeasureSpec, (r0 + r0) + lp.rightMargin, lp.width), getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height));
} else {
throw new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY");
}
}
}
}
protected void onLayout(boolean changed, int l, int t, int r, int b) {
this.mInLayout = CHILDREN_DISALLOW_INTERCEPT;
int width = r - l;
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if (child.getVisibility() != 8) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight());
} else {
int childLeft;
float newOffset;
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (checkDrawerViewAbsoluteGravity(child, 3)) {
childLeft = (-childWidth) + ((int) (((float) childWidth) * lp.onScreen));
newOffset = ((float) (childWidth + childLeft)) / ((float) childWidth);
} else {
childLeft = width - ((int) (((float) childWidth) * lp.onScreen));
newOffset = ((float) (width - childLeft)) / ((float) childWidth);
}
boolean changeOffset = newOffset != lp.onScreen ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
int height;
switch (lp.gravity & 112) {
case TransportMediator.FLAG_KEY_MEDIA_PAUSE /*16*/:
height = b - t;
int childTop = (height - childHeight) / STATE_SETTLING;
int i2 = lp.topMargin;
if (childTop < r0) {
childTop = lp.topMargin;
} else {
if (childTop + childHeight > height - lp.bottomMargin) {
childTop = (height - lp.bottomMargin) - childHeight;
}
}
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
break;
case 80:
height = b - t;
child.layout(childLeft, (height - lp.bottomMargin) - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin);
break;
default:
child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight);
break;
}
if (changeOffset) {
setDrawerViewOffset(child, newOffset);
}
int newVisibility = lp.onScreen > 0.0f ? STATE_IDLE : 4;
if (child.getVisibility() != newVisibility) {
child.setVisibility(newVisibility);
}
}
}
}
this.mInLayout = ALLOW_EDGE_LOCK;
this.mFirstLayout = ALLOW_EDGE_LOCK;
}
public void requestLayout() {
if (!this.mInLayout) {
super.requestLayout();
}
}
public void computeScroll() {
int childCount = getChildCount();
float scrimOpacity = 0.0f;
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
scrimOpacity = Math.max(scrimOpacity, ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen);
}
this.mScrimOpacity = scrimOpacity;
if ((this.mLeftDragger.continueSettling(CHILDREN_DISALLOW_INTERCEPT) | this.mRightDragger.continueSettling(CHILDREN_DISALLOW_INTERCEPT)) != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private static boolean hasOpaqueBackground(View v) {
Drawable bg = v.getBackground();
if (bg == null || bg.getOpacity() != -1) {
return ALLOW_EDGE_LOCK;
}
return CHILDREN_DISALLOW_INTERCEPT;
}
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
int height = getHeight();
boolean drawingContent = isContentView(child);
int clipLeft = STATE_IDLE;
int clipRight = getWidth();
int restoreCount = canvas.save();
if (drawingContent) {
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View v = getChildAt(i);
if (v != child && v.getVisibility() == 0 && hasOpaqueBackground(v) && isDrawerView(v) && v.getHeight() >= height) {
if (checkDrawerViewAbsoluteGravity(v, 3)) {
int vright = v.getRight();
if (vright > clipLeft) {
clipLeft = vright;
}
} else {
int vleft = v.getLeft();
if (vleft < clipRight) {
clipRight = vleft;
}
}
}
}
canvas.clipRect(clipLeft, STATE_IDLE, clipRight, getHeight());
}
boolean result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(restoreCount);
if (this.mScrimOpacity > 0.0f && drawingContent) {
this.mScrimPaint.setColor((((int) (((float) ((this.mScrimColor & ViewCompat.MEASURED_STATE_MASK) >>> 24)) * this.mScrimOpacity)) << 24) | (this.mScrimColor & ViewCompat.MEASURED_SIZE_MASK));
canvas.drawRect((float) clipLeft, 0.0f, (float) clipRight, (float) getHeight(), this.mScrimPaint);
} else if (this.mShadowLeft != null && checkDrawerViewAbsoluteGravity(child, 3)) {
shadowWidth = this.mShadowLeft.getIntrinsicWidth();
int childRight = child.getRight();
alpha = Math.max(0.0f, Math.min(((float) childRight) / ((float) this.mLeftDragger.getEdgeSize()), TOUCH_SLOP_SENSITIVITY));
this.mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom());
this.mShadowLeft.setAlpha((int) (255.0f * alpha));
this.mShadowLeft.draw(canvas);
} else if (this.mShadowRight != null && checkDrawerViewAbsoluteGravity(child, 5)) {
shadowWidth = this.mShadowRight.getIntrinsicWidth();
int childLeft = child.getLeft();
alpha = Math.max(0.0f, Math.min(((float) (getWidth() - childLeft)) / ((float) this.mRightDragger.getEdgeSize()), TOUCH_SLOP_SENSITIVITY));
this.mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom());
this.mShadowRight.setAlpha((int) (255.0f * alpha));
this.mShadowRight.draw(canvas);
}
return result;
}
boolean isContentView(View child) {
return ((LayoutParams) child.getLayoutParams()).gravity == 0 ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
boolean isDrawerView(View child) {
return (GravityCompat.getAbsoluteGravity(((LayoutParams) child.getLayoutParams()).gravity, ViewCompat.getLayoutDirection(child)) & 7) != 0 ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = MotionEventCompat.getActionMasked(ev);
boolean interceptForDrag = this.mLeftDragger.shouldInterceptTouchEvent(ev) | this.mRightDragger.shouldInterceptTouchEvent(ev);
boolean interceptForTap = ALLOW_EDGE_LOCK;
switch (action) {
case STATE_IDLE /*0*/:
float x = ev.getX();
float y = ev.getY();
this.mInitialMotionX = x;
this.mInitialMotionY = y;
if (this.mScrimOpacity > 0.0f && isContentView(this.mLeftDragger.findTopChildUnder((int) x, (int) y))) {
interceptForTap = CHILDREN_DISALLOW_INTERCEPT;
}
this.mDisallowInterceptRequested = ALLOW_EDGE_LOCK;
this.mChildrenCanceledTouch = ALLOW_EDGE_LOCK;
break;
case STATE_DRAGGING /*1*/:
case Std.STD_URI /*3*/:
closeDrawers(CHILDREN_DISALLOW_INTERCEPT);
this.mDisallowInterceptRequested = ALLOW_EDGE_LOCK;
this.mChildrenCanceledTouch = ALLOW_EDGE_LOCK;
break;
case STATE_SETTLING /*2*/:
if (this.mLeftDragger.checkTouchSlop(3)) {
this.mLeftCallback.removeCallbacks();
this.mRightCallback.removeCallbacks();
break;
}
break;
}
if (interceptForDrag || interceptForTap || hasPeekingDrawer() || this.mChildrenCanceledTouch) {
return CHILDREN_DISALLOW_INTERCEPT;
}
return ALLOW_EDGE_LOCK;
}
public boolean onTouchEvent(MotionEvent ev) {
this.mLeftDragger.processTouchEvent(ev);
this.mRightDragger.processTouchEvent(ev);
float x;
float y;
switch (ev.getAction() & MotionEventCompat.ACTION_MASK) {
case STATE_IDLE /*0*/:
x = ev.getX();
y = ev.getY();
this.mInitialMotionX = x;
this.mInitialMotionY = y;
this.mDisallowInterceptRequested = ALLOW_EDGE_LOCK;
this.mChildrenCanceledTouch = ALLOW_EDGE_LOCK;
break;
case STATE_DRAGGING /*1*/:
x = ev.getX();
y = ev.getY();
boolean peekingOnly = CHILDREN_DISALLOW_INTERCEPT;
View touchedView = this.mLeftDragger.findTopChildUnder((int) x, (int) y);
if (touchedView != null && isContentView(touchedView)) {
float dx = x - this.mInitialMotionX;
float dy = y - this.mInitialMotionY;
int slop = this.mLeftDragger.getTouchSlop();
if ((dx * dx) + (dy * dy) < ((float) (slop * slop))) {
View openDrawer = findOpenDrawer();
if (openDrawer != null) {
peekingOnly = getDrawerLockMode(openDrawer) == STATE_SETTLING ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
}
}
closeDrawers(peekingOnly);
this.mDisallowInterceptRequested = ALLOW_EDGE_LOCK;
break;
case Std.STD_URI /*3*/:
closeDrawers(CHILDREN_DISALLOW_INTERCEPT);
this.mDisallowInterceptRequested = ALLOW_EDGE_LOCK;
this.mChildrenCanceledTouch = ALLOW_EDGE_LOCK;
break;
}
return CHILDREN_DISALLOW_INTERCEPT;
}
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
super.requestDisallowInterceptTouchEvent(disallowIntercept);
this.mDisallowInterceptRequested = disallowIntercept;
if (disallowIntercept) {
closeDrawers(CHILDREN_DISALLOW_INTERCEPT);
}
}
public void closeDrawers() {
closeDrawers(ALLOW_EDGE_LOCK);
}
void closeDrawers(boolean peekingOnly) {
boolean needsInvalidate = ALLOW_EDGE_LOCK;
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isDrawerView(child) && (!peekingOnly || lp.isPeeking)) {
int childWidth = child.getWidth();
if (checkDrawerViewAbsoluteGravity(child, 3)) {
needsInvalidate |= this.mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop());
} else {
needsInvalidate |= this.mRightDragger.smoothSlideViewTo(child, getWidth(), child.getTop());
}
lp.isPeeking = ALLOW_EDGE_LOCK;
}
}
this.mLeftCallback.removeCallbacks();
this.mRightCallback.removeCallbacks();
if (needsInvalidate) {
invalidate();
}
}
public void openDrawer(View drawerView) {
if (isDrawerView(drawerView)) {
if (this.mFirstLayout) {
LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = TOUCH_SLOP_SENSITIVITY;
lp.knownOpen = CHILDREN_DISALLOW_INTERCEPT;
} else if (checkDrawerViewAbsoluteGravity(drawerView, 3)) {
this.mLeftDragger.smoothSlideViewTo(drawerView, STATE_IDLE, drawerView.getTop());
} else {
this.mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(), drawerView.getTop());
}
invalidate();
return;
}
throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
}
public void openDrawer(int gravity) {
View drawerView = findDrawerWithGravity(gravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity));
}
openDrawer(drawerView);
}
public void closeDrawer(View drawerView) {
if (isDrawerView(drawerView)) {
if (this.mFirstLayout) {
LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.0f;
lp.knownOpen = ALLOW_EDGE_LOCK;
} else if (checkDrawerViewAbsoluteGravity(drawerView, 3)) {
this.mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop());
} else {
this.mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop());
}
invalidate();
return;
}
throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
}
public void closeDrawer(int gravity) {
View drawerView = findDrawerWithGravity(gravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity));
}
closeDrawer(drawerView);
}
public boolean isDrawerOpen(View drawer) {
if (isDrawerView(drawer)) {
return ((LayoutParams) drawer.getLayoutParams()).knownOpen;
}
throw new IllegalArgumentException("View " + drawer + " is not a drawer");
}
public boolean isDrawerOpen(int drawerGravity) {
View drawerView = findDrawerWithGravity(drawerGravity);
if (drawerView != null) {
return isDrawerOpen(drawerView);
}
return ALLOW_EDGE_LOCK;
}
public boolean isDrawerVisible(View drawer) {
if (isDrawerView(drawer)) {
return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0.0f ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
} else {
throw new IllegalArgumentException("View " + drawer + " is not a drawer");
}
}
public boolean isDrawerVisible(int drawerGravity) {
View drawerView = findDrawerWithGravity(drawerGravity);
if (drawerView != null) {
return isDrawerVisible(drawerView);
}
return ALLOW_EDGE_LOCK;
}
private boolean hasPeekingDrawer() {
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
if (((LayoutParams) getChildAt(i).getLayoutParams()).isPeeking) {
return CHILDREN_DISALLOW_INTERCEPT;
}
}
return ALLOW_EDGE_LOCK;
}
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(-1, -1);
}
protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {
if (p instanceof LayoutParams) {
return new LayoutParams((LayoutParams) p);
}
return p instanceof MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p);
}
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
return ((p instanceof LayoutParams) && super.checkLayoutParams(p)) ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
private boolean hasVisibleDrawer() {
return findVisibleDrawer() != null ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
private View findVisibleDrawer() {
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if (isDrawerView(child) && isDrawerVisible(child)) {
return child;
}
}
return null;
}
void cancelChildViewTouch() {
if (!this.mChildrenCanceledTouch) {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(now, now, 3, 0.0f, 0.0f, STATE_IDLE);
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
getChildAt(i).dispatchTouchEvent(cancelEvent);
}
cancelEvent.recycle();
this.mChildrenCanceledTouch = CHILDREN_DISALLOW_INTERCEPT;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode != 4 || !hasVisibleDrawer()) {
return super.onKeyDown(keyCode, event);
}
KeyEventCompat.startTracking(event);
return CHILDREN_DISALLOW_INTERCEPT;
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode != 4) {
return super.onKeyUp(keyCode, event);
}
View visibleDrawer = findVisibleDrawer();
if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == 0) {
closeDrawers();
}
return visibleDrawer != null ? CHILDREN_DISALLOW_INTERCEPT : ALLOW_EDGE_LOCK;
}
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.openDrawerGravity != 0) {
View toOpen = findDrawerWithGravity(ss.openDrawerGravity);
if (toOpen != null) {
openDrawer(toOpen);
}
}
setDrawerLockMode(ss.lockModeLeft, 3);
setDrawerLockMode(ss.lockModeRight, 5);
}
protected Parcelable onSaveInstanceState() {
SavedState ss = new SavedState(super.onSaveInstanceState());
int childCount = getChildCount();
for (int i = STATE_IDLE; i < childCount; i += STATE_DRAGGING) {
View child = getChildAt(i);
if (isDrawerView(child)) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.knownOpen) {
ss.openDrawerGravity = lp.gravity;
break;
}
}
}
ss.lockModeLeft = this.mLockModeLeft;
ss.lockModeRight = this.mLockModeRight;
return ss;
}
}
| [
"binslashbash@otaking.top"
] | binslashbash@otaking.top |
903d58380b5e3ac2456a2e0ceb8ef5bdeec19144 | 7190ade651332e7bdc2cdaa1c555be50cd1d6282 | /src/main/java/edu/drexel/cis/dragon/util/HttpUtil.java | 30f9c49c686e796c884a14d93c9639423ba4f3e9 | [
"Apache-2.0"
] | permissive | xc35/dragontoolkit | e906f99a59c81e2e17e5c807ba5ba92e6bbe818c | e7ef78a9c2ff549102b2644e52f67f0d062589aa | refs/heads/master | 2020-05-21T07:36:25.436038 | 2017-03-10T20:39:23 | 2017-03-10T20:39:23 | 84,596,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,045 | java | /* */ package edu.drexel.cis.dragon.util;
/* */
/* */ import java.io.InputStream;
/* */ import java.io.PrintStream;
/* */ import java.net.URL;
/* */ import org.apache.commons.httpclient.HostConfiguration;
/* */ import org.apache.commons.httpclient.HttpClient;
/* */ import org.apache.commons.httpclient.HttpConnectionManager;
/* */ import org.apache.commons.httpclient.methods.GetMethod;
/* */ import org.apache.commons.httpclient.params.HttpClientParams;
/* */ import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
/* */ import org.apache.commons.httpclient.params.HttpMethodParams;
/* */
/* */ public class HttpUtil
/* */ {
/* */ private HttpClient http;
/* */ private String defaultCharSet;
/* */ private String lastCharSet;
/* */ private byte[] buf;
/* */ private boolean autoRefresh;
/* */
/* */ public static void main(String[] args)
/* */ {
/* 29 */ HttpUtil web = new HttpUtil("www.google.com");
/* 30 */ web.setAutoRefresh(true);
/* 31 */ String content = web.get("/search?q=killed+abraham+lincoln&hl=en&newwindow=1&rlz=1T4GZHY_enUS237US237&start=40&sa=N");
/* 32 */ FileUtil.saveTextFile("test.txt", content, "UTF-16LE");
/* 33 */ FileUtil.saveTextFile("test_notag.txt", new HttpContent().extractText(content), "UTF-16LE");
/* */ }
/* */
/* */ public HttpUtil(String host) {
/* 37 */ this(host, 80, null);
/* */ }
/* */
/* */ public HttpUtil(String host, String charSet) {
/* 41 */ this(host, 80, charSet);
/* */ }
/* */
/* */ public HttpUtil(String host, int port) {
/* 45 */ this(host, port, null);
/* */ }
/* */
/* */ public HttpUtil(String host, int port, String charSet)
/* */ {
/* 51 */ this.buf = new byte[1048576];
/* 52 */ this.lastCharSet = null;
/* 53 */ this.autoRefresh = false;
/* 54 */ this.defaultCharSet = charSet;
/* 55 */ this.http = new HttpClient();
/* 56 */ HostConfiguration hostConfig = new HostConfiguration();
/* 57 */ hostConfig.setHost(host, port);
/* 58 */ this.http.setHostConfiguration(hostConfig);
/* 59 */ setSocketTimeout(10000);
/* 60 */ setConnectionTimeout(10000);
/* */ }
/* */
/* */ public void setHost(String host) {
/* 64 */ setHost(host, 80, null);
/* */ }
/* */
/* */ public void setHost(String host, String charSet) {
/* 68 */ setHost(host, 80, charSet);
/* */ }
/* */
/* */ public void setHost(String host, int port) {
/* 72 */ setHost(host, port, this.defaultCharSet);
/* */ }
/* */
/* */ public void setHost(String host, int port, String charSet)
/* */ {
/* 78 */ this.defaultCharSet = charSet;
/* 79 */ HostConfiguration hostConfig = this.http.getHostConfiguration();
/* 80 */ hostConfig.setHost(host, port);
/* 81 */ this.http.setHostConfiguration(hostConfig);
/* */ }
/* */
/* */ public void setAutoRefresh(boolean enable) {
/* 85 */ this.autoRefresh = enable;
/* */ }
/* */
/* */ public boolean getAutoRefresh() {
/* 89 */ return this.autoRefresh;
/* */ }
/* */
/* */ public String getHost() {
/* 93 */ return this.http.getHostConfiguration().getHost();
/* */ }
/* */
/* */ public int getPort() {
/* 97 */ return this.http.getHostConfiguration().getPort();
/* */ }
/* */
/* */ public void setConnectionTimeout(int time) {
/* 101 */ this.http.getHttpConnectionManager().getParams().setConnectionTimeout(time);
/* */ }
/* */
/* */ public int getConnectionTimeout() {
/* 105 */ return this.http.getHttpConnectionManager().getParams().getConnectionTimeout();
/* */ }
/* */
/* */ public void setSocketTimeout(int time) {
/* 109 */ this.http.getParams().setParameter("http.socket.timeout", new Integer(time));
/* */ }
/* */
/* */ public int getSocketTimeout() {
/* 113 */ return ((Integer)this.http.getParams().getParameter("http.socket.timeout")).intValue();
/* */ }
/* */
/* */ public String getCharSet()
/* */ {
/* 121 */ return this.lastCharSet;
/* */ }
/* */
/* */ public String get(String url) {
/* 125 */ return get(url, null);
/* */ }
/* */
/* */ public String get(String url, String charSet)
/* */ {
/* 132 */ String content = internalGet(url, charSet);
/* 133 */ if ((content == null) || (!this.autoRefresh))
/* 134 */ return content;
/* 135 */ URL newUrl = getDirectedURL(content);
/* 136 */ if (newUrl == null) {
/* 137 */ return content;
/* */ }
/* 139 */ if (newUrl.getHost() != "") {
/* 140 */ if (newUrl.getPort() > 0)
/* 141 */ setHost(newUrl.getHost(), newUrl.getPort());
/* */ else
/* 143 */ setHost(newUrl.getHost());
/* */ }
/* 145 */ url = newUrl.getFile();
/* 146 */ while (url.charAt(0) == '.')
/* 147 */ url = url.substring(1);
/* 148 */ if (url.charAt(0) != '/')
/* 149 */ url = "/" + url;
/* 150 */ return internalGet(url, charSet);
/* */ }
/* */
/* */ private URL getDirectedURL(String message)
/* */ {
/* */ try
/* */ {
/* 158 */ if ((message == null) || (message.length() >= 512))
/* 159 */ return null;
/* 160 */ message = message.toLowerCase();
/* 161 */ int start = message.indexOf("http-equiv=\"refresh\"");
/* 162 */ if (start < 0)
/* 163 */ start = message.indexOf("http-equiv='refresh'");
/* 164 */ if (start < 0)
/* 165 */ return null;
/* 166 */ int end = message.indexOf(">", start);
/* 167 */ if (end < 0)
/* 168 */ return null;
/* 169 */ message = message.substring(start, end);
/* 170 */ start = message.indexOf("url=");
/* 171 */ if (start < 0)
/* 172 */ return null;
/* 173 */ start += 4;
/* 174 */ end = message.indexOf("\"", start);
/* 175 */ if (end < 0)
/* 176 */ end = message.indexOf("'", start);
/* 177 */ message = message.substring(start, end);
/* 178 */ if (!message.startsWith("http"))
/* 179 */ message = "http:" + message;
/* 180 */ return new URL(message);
/* */ } catch (Exception e) {
/* */ }
/* 183 */ return null;
/* */ }
/* */
/* */ private String internalGet(String url, String charSet)
/* */ {
/* 192 */ GetMethod method = null;
/* */ try {
/* 194 */ method = new GetMethod(url);
/* 195 */ method.getParams().setCookiePolicy("compatibility");
/* 196 */ this.http.executeMethod(method);
/* 197 */ if (method.getStatusCode() != 200) {
/* 198 */ method.releaseConnection();
/* 199 */ return null;
/* */ }
/* */
/* 202 */ int len = read(method.getResponseBodyAsStream(), this.buf);
/* 203 */ String curCharSet = recognizeStreamEncode(this.buf);
/* 204 */ if (curCharSet == null)
/* 205 */ curCharSet = charSet;
/* 206 */ if (curCharSet == null)
/* 207 */ curCharSet = method.getResponseCharSet();
/* 208 */ if ((curCharSet != null) && (curCharSet.equalsIgnoreCase("ISO-8859-1")))
/* 209 */ curCharSet = null;
/* */ String content;
/* 211 */ if (curCharSet != null) {
/* 212 */ content = new String(this.buf, 0, len, charsetNameConvert(curCharSet));
/* */ }
/* */ else
/* */ {
/* 214 */ if (this.defaultCharSet != null) {
/* 215 */ curCharSet = this.defaultCharSet;
/* 216 */ content = new String(this.buf, 0, len, charsetNameConvert(curCharSet));
/* */ }
/* */ else {
/* 219 */ content = new String(this.buf, 0, len);
/* 220 */ }charSet = readCharSet(content);
/* 221 */ if ((charSet != null) && (!compatibleCharSet(curCharSet, charSet))) {
/* 222 */ curCharSet = charSet;
/* 223 */ content = new String(this.buf, 0, len, charsetNameConvert(curCharSet));
/* */ }
/* */ }
/* 226 */ this.lastCharSet = curCharSet;
/* 227 */ method.releaseConnection();
/* 228 */ return content;
/* */ }
/* */ catch (Exception e) {
/* 231 */ if (method != null)
/* 232 */ method.releaseConnection();
/* */ }
/* 233 */ return null;
/* */ }
/* */
/* */ private int read(InputStream in, byte[] buf)
/* */ {
/* */ try
/* */ {
/* 241 */ int offset = 0;
/* 242 */ int len = in.read(buf);
/* 243 */ while (len >= 0) {
/* 244 */ offset += len;
/* 245 */ if (offset == buf.length)
/* */ break;
/* 247 */ len = in.read(buf, offset, buf.length - offset);
/* */ }
/* 249 */ if (offset == buf.length) {
/* 250 */ System.out.println("Warning: The web page is too big and truncated!");
/* */ }
/* 252 */ return offset;
/* */ } catch (Exception e) {
/* */ }
/* 255 */ return 0;
/* */ }
/* */
/* */ private boolean compatibleCharSet(String charsetA, String charsetB)
/* */ {
/* 260 */ if ((charsetA == null) || (charsetB == null))
/* 261 */ return false;
/* 262 */ if (charsetA.equalsIgnoreCase(charsetB))
/* 263 */ return true;
/* 264 */ if ((charsetA.equalsIgnoreCase("gbk")) && (charsetB.equalsIgnoreCase("gb2312"))) {
/* 265 */ return true;
/* */ }
/* 267 */ return false;
/* */ }
/* */
/* */ private String charsetNameConvert(String charsetName) {
/* 271 */ if (charsetName.equalsIgnoreCase("gb2312")) {
/* 272 */ return "gbk";
/* */ }
/* 274 */ return charsetName;
/* */ }
/* */
/* */ private String recognizeStreamEncode(byte[] buf)
/* */ {
/* */ try {
/* 280 */ String hex = ByteArrayConvert.toHexString(buf, 0, 3).toUpperCase();
/* 281 */ if ((hex.startsWith("FFFE")) || (hex.startsWith("3C00")))
/* 282 */ return "UTF-16LE";
/* 283 */ if ((hex.startsWith("FEFF")) || (hex.startsWith("003C")))
/* 284 */ return "UTF-16BE";
/* 285 */ if (hex.startsWith("EFBBBF")) {
/* 286 */ return "UTF-8";
/* */ }
/* 288 */ return null;
/* */ } catch (Exception e) {
/* */ }
/* 291 */ return null;
/* */ }
/* */
/* */ private String readCharSet(String message)
/* */ {
/* */ try
/* */ {
/* 299 */ int end = Math.min(message.length(), 2048);
/* 300 */ message = message.substring(0, end).toLowerCase();
/* 301 */ int start = message.indexOf("http-equiv=");
/* 302 */ if (start < 0)
/* 303 */ return null;
/* 304 */ end = message.indexOf(">", start);
/* 305 */ message = message.substring(start, end).trim();
/* 306 */ start = message.indexOf("charset=");
/* 307 */ if (start < 0)
/* 308 */ return null;
/* 309 */ start += 8;
/* 310 */ end = message.indexOf("\"", start);
/* 311 */ if (end < 0)
/* 312 */ end = message.indexOf("'", start);
/* 313 */ if (end < 0) {
/* 314 */ return null;
/* */ }
/* 316 */ return message.substring(start, end).trim();
/* */ } catch (Exception e) {
/* */ }
/* 319 */ return null;
/* */ }
/* */ }
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.util.HttpUtil
* JD-Core Version: 0.6.2
*/ | [
"noreply@github.com"
] | noreply@github.com |
16578ef8ea25d7b34bc63f6df76548e8d5d2be9e | 5869efd3e242c404cf3942b1999535b2a654464f | /src/test/java/client/executors/ExecThreadsTest.java | da772c4fb7b965260e6b9ac2e79f5af1f17444c1 | [] | no_license | AndreyCherdakov-Key/client | de3b5562e1800b0bd34b0784526a91f15b0a8876 | 0dce32a86a25cd224d1a1b768490d76c61e69b21 | refs/heads/master | 2022-08-20T13:20:54.258223 | 2020-05-29T22:56:39 | 2020-05-29T22:56:39 | 267,970,182 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | package client.executors;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
class ExecThreadsTest {
@Test
void testGetInstance() {
assertNotNull(ExecThreads.getInstance());
ExecThreads.class.isInstance(ExecThreads.getInstance());
}
@Test
void testStop() {
ExecThreads.getInstance().runRequests(1);
Executable ex = () -> ExecThreads.getInstance().stop();
assertAll(ex);
assertDoesNotThrow(ex);
}
}
| [
"wasta@inbox.ru"
] | wasta@inbox.ru |
4fdd297144302f370cbf86d222e0c1b60c5b5a4d | cb13578c119a38b640165c6a5c36666747cab406 | /app/src/main/java/com/vdh/pushnotification/MainActivity.java | 9c181c9434c9641602459db49f555df84a3347e4 | [] | no_license | HoaVu1711/test | 6e77401d39366cb7ac89ea199dc787ccacb09e76 | b476da3ee59e21bedfde235481acfd94fa1ff395 | refs/heads/master | 2023-05-28T12:12:52.017648 | 2021-04-07T11:13:15 | 2021-04-07T11:13:15 | 347,928,846 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,529 | java | package com.vdh.pushnotification;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int MY_ID = 1;
Button btnSendNo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendNo=findViewById(R.id.btnSendNotifycation);
btnSendNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pushNotification();
}
});
}
private void pushNotification() {
Notification notification = new NotificationCompat.Builder(this,MyApplicaion.CHANNEL_ID)
.setContentText("description 1")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("title 1")
.setColor(Color.argb(1,100,50,100))
.build();
NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(getNotifiID(),notification);
}
public int getNotifiID(){
return (int) new Date().getTime();
}
} | [
"duchoa1711@gmail.com"
] | duchoa1711@gmail.com |
935265236964403a0603f0506de7c0bba87fe5db | 71ad88173ef75e69a3152509fd271745a131738d | /Logging.java | 8605d89b21cd11506d895fb20c8a310327388ff4 | [] | no_license | Kobai/Competitive-Programming | c824f56495b9c4ee4de1230a12fe27ab4586a3d2 | 4fdb8b2d118d55c54f1586b67a990028254175a8 | refs/heads/master | 2021-04-06T01:40:23.684453 | 2019-12-31T18:43:23 | 2019-12-31T18:43:23 | 124,708,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 493 | java | import java.util.Scanner;
public class Logging {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numDay = input.nextInt();
int numLog=0;
int logs = 0;
for(int i = 1; i<=numDay; i++)
{
numLog = input.nextInt();
for(int j=0; j<numLog; j++)
{
logs+= input.nextInt();
}
if (logs ==0)
{
System.out.println("Weekend");
}
else
{
System.out.println("Day "+(i)+": "+logs);
}
logs = 0;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fbbeb7a640da708419804fa769298f1bd8b4594b | a8068b5959d3aabcdf29bb583fbaf4205bf49247 | /src/Entities/Historico.java | 40fe17bf21ff7789eefb6dd7b189d23ed11e01ad | [] | no_license | ndf1511/ProySI | 705e2b870a23dec6df24b1b06922ff0c9088b61e | 8b56a006b3197a9deaddb4132115d53c4e17d5d1 | refs/heads/master | 2021-07-16T21:07:23.913183 | 2017-10-24T19:51:32 | 2017-10-24T19:51:32 | 108,163,474 | 1 | 0 | null | 2017-10-24T19:51:33 | 2017-10-24T17:52:55 | Java | UTF-8 | Java | false | false | 3,381 | java | /*
* 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 Entities;
import java.io.Serializable;
public class Historico implements Serializable {
String prod;
int id;
String ene,feb,mar,abr,may,jun,jul,ago,sep,oct,nov,dic;
public Historico(int id,String prod, String ene, String feb, String mar, String abr, String may, String jun, String jul, String ago, String sep, String oct, String nov, String dic) {
this.id=id;
this.prod = prod;
this.ene = ene;
this.feb = feb;
this.mar = mar;
this.abr = abr;
this.may = may;
this.jun = jun;
this.jul = jul;
this.ago = ago;
this.sep = sep;
this.oct = oct;
this.nov = nov;
this.dic = dic;
}
public Historico(String prod, String ene, String feb, String mar, String abr, String may, String jun, String jul, String ago, String sep, String oct, String nov, String dic) {
this.id=id;
this.prod = prod;
this.ene = ene;
this.feb = feb;
this.mar = mar;
this.abr = abr;
this.may = may;
this.jun = jun;
this.jul = jul;
this.ago = ago;
this.sep = sep;
this.oct = oct;
this.nov = nov;
this.dic = dic;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProd() {
return prod;
}
public void setProd(String prod) {
this.prod = prod;
}
public String getEne() {
return ene;
}
public void setEne(String ene) {
this.ene = ene;
}
public String getFeb() {
return feb;
}
public void setFeb(String feb) {
this.feb = feb;
}
public String getMar() {
return mar;
}
public void setMar(String mar) {
this.mar = mar;
}
public String getAbr() {
return abr;
}
public void setAbr(String abr) {
this.abr = abr;
}
public String getMay() {
return may;
}
public void setMay(String may) {
this.may = may;
}
public String getJun() {
return jun;
}
public void setJun(String jun) {
this.jun = jun;
}
public String getJul() {
return jul;
}
public void setJul(String jul) {
this.jul = jul;
}
public String getAgo() {
return ago;
}
public void setAgo(String ago) {
this.ago = ago;
}
public String getSep() {
return sep;
}
public void setSep(String sep) {
this.sep = sep;
}
public String getOct() {
return oct;
}
public void setOct(String oct) {
this.oct = oct;
}
public String getNov() {
return nov;
}
public void setNov(String nov) {
this.nov = nov;
}
public String getDic() {
return dic;
}
public void setDic(String dic) {
this.dic = dic;
}
}
| [
"Nico@DESKTOP-QPTM92C"
] | Nico@DESKTOP-QPTM92C |
d866a4b09cab2f80ef2ea4382849a73eb93ef0f6 | ba63acaf5a6392b9cd6687ffbfd2179084645aa2 | /healthcheck/healthcheck-core/src/main/java/net/atos/xa/healthcheck/HealthCheckReport.java | 6dbdfe3a8e828ddcca53695985e70b9595d7602d | [] | no_license | chnouman/healthcheck | b9bf1c336dd1239a6fe42b8fa6999a59326ffbd0 | 9cb3c3d524eb3bad665a080d5296368d47bab034 | refs/heads/master | 2021-01-11T06:54:58.900786 | 2014-08-13T12:51:37 | 2014-08-13T12:51:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,815 | java | package net.atos.xa.healthcheck;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.yammer.metrics.core.HealthCheck;
import com.yammer.metrics.core.HealthCheckRegistry;
/**
*
* Utility class that produce the healthCheck textual report
*
*/
public final class HealthCheckReport {
private HealthCheckReport() {
}
/**
* Produce a textual report for the healthcheck
*
* @param registry
* the healthcheck registry which contains all the checks to
* execute
* @param writer
* the writer
*/
public static void produceReport(HealthCheckRegistry registry,
final PrintWriter writer) {
final Map<String, HealthCheck.Result> results = registry
.runHealthChecks();
final Map<String, HealthCheckResult> healthcheckResults = new HashMap<String, HealthCheckResult>();
for (String key : results.keySet()) {
healthcheckResults.put(key, new HealthCheckResult(results.get(key),
-1));
}
produceReport(writer, healthcheckResults);
}
/**
* Produce a textual report for the healthcheck
*
* @param writer
* the writer
*/
public static void produceReport(final PrintWriter writer) {
final Map<String, HealthCheckResult> results = HealthCheckManager
.runHealthchecksWithDetailedReport();
produceReport(writer, results);
}
/**
* Produce a textual report for the healthcheck
*
* @param writer
* the writer
* @param results
* the results
*/
public static void produceReport(final PrintWriter writer,
final Map<String, HealthCheckResult> results) {
if (results.isEmpty()) {
writer.println("! No health checks registered.");
} else {
for (Map.Entry<String, HealthCheckResult> entry : results
.entrySet()) {
final HealthCheckResult result = entry.getValue();
if (result.isHealthy()) {
if (result.getMessage() != null) {
writer.format(
"* %s=OK (executed at %s) in %sms\n %s\n",
entry.getKey(), new Date(),
result.getExecutionTime(), result.getMessage());
} else {
writer.format("* %s=OK (executed at %s) in %sms\n",
entry.getKey(), new Date(),
result.getExecutionTime());
}
} else {
if (result.getMessage() != null) {
writer.format("! %s=ERROR in %sms\n! %s\n",
entry.getKey(), result.getExecutionTime(),
result.getMessage());
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
final Throwable error = result.getError();
if (error != null) {
writer.println();
error.printStackTrace(writer);
writer.println();
}
}
}
}
}
}
| [
"jonathan.macke@yahoo.fr"
] | jonathan.macke@yahoo.fr |
0c024f97007d396478addf4110736c8b19a52793 | cbcab39e220ad555c8af4f19408335d5fc5aecdd | /src/org.hyperflex.componentmodels.orocos.model.edit/src/org/hyperflex/orocoscomponentmodel/provider/InputDataPortItemProvider.java | 664b3d6c14e91267c175b387d02195805f2bd3ee | [] | no_license | GertKanter/HyperFlex | 2d6b5133e9b94b04459897e546126626d29d30c3 | 427613e076f7604dcfdb40b7e4a491146ba071a8 | refs/heads/master | 2020-03-28T20:39:44.513690 | 2014-09-11T15:10:15 | 2014-09-11T15:10:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,895 | java | /**
* HyperFlex Toolchain
*
* Copyright (c) 2013
* All rights reserved.
*
* Luca Gherardi
* University of Bergamo
* Department of Engineering
*
* ***********************************************************************************************
*
* Author: <A HREF="mailto:lucagh@ethz.ch">Luca Gherardi</A>
*
* In collaboration with:
* <A HREF="mailto:brugali@unibg.it">Davide Brugali</A>, Department of Engineering
*
* ***********************************************************************************************
*
* 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
*
*
*/
package org.hyperflex.orocoscomponentmodel.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.hyperflex.orocoscomponentmodel.InputDataPort;
/**
* This is the item provider adapter for a {@link org.hyperflex.orocoscomponentmodel.InputDataPort} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class InputDataPortItemProvider
extends DataPortItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InputDataPortItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This returns InputDataPort.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/InputDataPort"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((InputDataPort)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_InputDataPort_type") :
getString("_UI_InputDataPort_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| [
"lucaghera8@gmail.com"
] | lucaghera8@gmail.com |
0e41220a83702858aa9ac524d5305e10a01558c7 | aaabffe8bf55973bfb1390cf7635fd00ca8ca945 | /src/main/java/com/microsoft/graph/models/generated/BasePlannerCategoryDescriptions.java | a0c8316b946759c8c258fd2c1107059463791c24 | [
"MIT"
] | permissive | rgrebski/msgraph-sdk-java | e595e17db01c44b9c39d74d26cd925b0b0dfe863 | 759d5a81eb5eeda12d3ed1223deeafd108d7b818 | refs/heads/master | 2020-03-20T19:41:06.630857 | 2018-03-16T17:31:43 | 2018-03-16T17:31:43 | 137,648,798 | 0 | 0 | null | 2018-06-17T11:07:06 | 2018-06-17T11:07:05 | null | UTF-8 | Java | false | false | 3,262 | java | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
import com.microsoft.graph.concurrency.*;
import com.microsoft.graph.core.*;
import com.microsoft.graph.models.extensions.*;
import com.microsoft.graph.models.generated.*;
import com.microsoft.graph.http.*;
import com.microsoft.graph.requests.extensions.*;
import com.microsoft.graph.requests.generated.*;
import com.microsoft.graph.options.*;
import com.microsoft.graph.serializer.*;
import java.util.Arrays;
import java.util.EnumSet;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.annotations.*;
import java.util.HashMap;
import java.util.Map;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Base Planner Category Descriptions.
*/
public class BasePlannerCategoryDescriptions implements IJsonBackedObject {
@SerializedName("@odata.type")
@Expose
public String oDataType;
private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);
@Override
public final AdditionalDataManager additionalDataManager() {
return additionalDataManager;
}
/**
* The Category1.
* The label associated with Category 1
*/
@SerializedName("category1")
@Expose
public String category1;
/**
* The Category2.
* The label associated with Category 2
*/
@SerializedName("category2")
@Expose
public String category2;
/**
* The Category3.
* The label associated with Category 3
*/
@SerializedName("category3")
@Expose
public String category3;
/**
* The Category4.
* The label associated with Category 4
*/
@SerializedName("category4")
@Expose
public String category4;
/**
* The Category5.
* The label associated with Category 5
*/
@SerializedName("category5")
@Expose
public String category5;
/**
* The Category6.
* The label associated with Category 6
*/
@SerializedName("category6")
@Expose
public String category6;
/**
* The raw representation of this class
*/
private JsonObject rawObject;
/**
* The serializer
*/
private ISerializer serializer;
/**
* Gets the raw representation of this class
*
* @return the raw representation of this class
*/
public JsonObject getRawObject() {
return rawObject;
}
/**
* Gets serializer
*
* @return the serializer
*/
protected ISerializer getSerializer() {
return serializer;
}
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(final ISerializer serializer, final JsonObject json) {
this.serializer = serializer;
rawObject = json;
}
}
| [
"caitbal@microsoft.com"
] | caitbal@microsoft.com |
dac08fa04201c8e84efcc4ae53ba81717cd67216 | 29b93eb88a3fe64be39c75c3aeec77cbe7126feb | /src/main/java/com/okta/quarkusclient/SecureResource.java | acbe92b688aef173b4b51bbcc3d538ac06b7d37a | [] | no_license | moksamedia/okta-kafka-streams-quarkus | 0816713229fcf1f15f80895a1917843a6369d4a4 | 26f080ab557ca79b336b21e7fa2d7930319b2ce6 | refs/heads/master | 2021-01-04T21:59:24.635089 | 2020-03-20T18:01:27 | 2020-03-20T18:01:27 | 240,775,233 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 943 | java | package com.okta.quarkusclient;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import org.jboss.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;
@Path("/secured")
@RolesAllowed({"Everyone"})
public class SecureResource {
private static final Logger LOG = Logger.getLogger(SecureResource.class);
@Inject
Template secured;
@GET
@Produces(MediaType.TEXT_HTML)
public TemplateInstance get(@Context SecurityContext ctx) {
Principal caller = ctx.getUserPrincipal();
String name = caller == null ? "anonymous" : caller.getName();
LOG.info("name: " + name);
return secured.data("name", name);
}
} | [
"andrewcarterhughes@gmail.com"
] | andrewcarterhughes@gmail.com |
1011ebefe677ba840814e7acf9c3ccdf14d629c4 | c97798f9855932ad8d090a6a6ba2dca58b9f8ae8 | /app/src/androidTest/java/phamtanphat/ptp/khoaphamtraining/alertdialog04092019/ExampleInstrumentedTest.java | 7b55a748b41addcd5e292d77d4681878c631926b | [] | no_license | phamtanphat/AlertDialog04092019 | 4e20b75db5435fe110092281dc5f40ad52b576ca | 074fe9c0e1e6bbd80765bc349ecfef93b6c9a855 | refs/heads/master | 2020-08-16T21:53:48.815608 | 2019-10-18T13:47:27 | 2019-10-18T13:47:27 | 215,558,666 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 820 | java | package phamtanphat.ptp.khoaphamtraining.alertdialog04092019;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("phamtanphat.ptp.khoaphamtraining.alertdialog04092019", appContext.getPackageName());
}
}
| [
"phatdroid94@gmail.com"
] | phatdroid94@gmail.com |
26ad9639e5982f2dc945a9293bd0cdc485cc370e | 014dd5234378dea71a10e1e377a2d89181a4dd8a | /src/Problem2.java | d192d1e0ce273fbcba39f89ed9c87a6409625fcb | [] | no_license | SnowyCAN/Assignment02 | e70792e37a5933d1c4150fa817e044737c80601c | 0ba778fac4624b214f3704e592ff8e4b3f53d2f2 | refs/heads/master | 2020-12-24T19:50:17.308367 | 2015-10-02T15:10:39 | 2015-10-02T15:10:39 | 42,453,993 | 0 | 0 | null | 2015-09-14T14:32:48 | 2015-09-14T14:32:48 | null | UTF-8 | Java | false | false | 719 | java |
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author tituo4996
*/
public class Problem2
{
static int triangle(int n)
{
if (n==0 || n==1)
return n;
else
return n +triangle(n-1);
}
public static void main(String[] args)
{
Scanner stuff = new Scanner (System.in);
System.out.println("Please enter the number of rows that the triangle is made of: ");
int n = stuff.nextInt();
int amount= triangle(n);
System.out.println("The triangle is made of " +amount +" blocks.");
}
}
| [
"tituo4996@HRH-IC0027340.wrdsb.ca"
] | tituo4996@HRH-IC0027340.wrdsb.ca |
55c51829ca5733b572c5256fcc13d4a086edcfa1 | e818b6ac88728f9aab94945f7961e8b68b2a520b | /app/src/main/java/com/example/mychatapp/RegisterActivity.java | e8be7d058575f064fbb6bdf88f528e286b9c776b | [] | no_license | Akaash7/Encrypted-Messaging-App | f32cba67ae4eec09d295aad1aa33cfd0450406d6 | 15dcb2e895f1fd10902d01f06adf626aa0c81559 | refs/heads/master | 2023-06-03T17:08:48.085547 | 2021-05-21T03:39:21 | 2021-05-21T03:39:21 | 369,405,150 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,428 | java | package com.example.mychatapp;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.mychatapp.Prevalent.Prevalent;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rengwuxian.materialedittext.MaterialEditText;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Random;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import io.paperdb.Paper;
import static com.example.mychatapp.Prevalent.Prevalent.pkey;
public class RegisterActivity extends AppCompatActivity {
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
private RelativeLayout relativeLayout;
private AnimationDrawable animationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById((R.id.toolbar));
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Register");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.colorLavender), PorterDuff.Mode.SRC_ATOP);
// For Background Animation
relativeLayout = findViewById(R.id.register_form);
animationDrawable = (AnimationDrawable)relativeLayout.getBackground();
animationDrawable.setEnterFadeDuration(4000);
animationDrawable.setExitFadeDuration(2000);
animationDrawable.start();
//----------------------------------------------------------------------------------------
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById((R.id.btn_register));
auth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username)|| TextUtils.isEmpty(txt_email)||TextUtils.isEmpty(txt_password)){
Toast.makeText(RegisterActivity.this,"All the Fields are required!",Toast.LENGTH_SHORT).show();
}else if(txt_password.length()<6){
Toast.makeText(RegisterActivity.this,"Password must be at least 6 characters!",Toast.LENGTH_SHORT).show();
}else{
register(txt_username,txt_email,txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
/*
Random random = new Random();
int max = 100,min=-100;
for(int i=0;i<16;i++){
encKey[i] = (byte) (random.nextInt(max - min) + min);
System.out.println(encKey[i]+" ");
}
System.out.println("\n");
String Pkey = encKey.toString();
//Paper.book().write(user_id,userid);
//Paper.book().write(pkey ,Pkey);
//hashMap.put("pkey", Pkey);
//hashMap.put("pkey","default");
*/
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser!=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("id",userid);
hashMap.put("username",username);
hashMap.put("imageURL","default");
hashMap.put("status","offline");
hashMap.put("search",username.toLowerCase());
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this,StartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}else{
Toast.makeText(RegisterActivity.this,"You can't register with this email or password!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
| [
"yuktikhurana99@gmail.com"
] | yuktikhurana99@gmail.com |
b9fe0144a5d222c11f58f64a531eee24d423e645 | 6d4b19b800e6a77d36e5c0595fc97ec0a05cf499 | /src/main/java/br/com/kproj/salesman/infrastructure/security/authentication/LoggedUser.java | e86133b411a76752a4d685a8fc96ab9910c422bd | [] | no_license | mmaico/salesman-crm | 5252d72bb90130c6d4eff5e11990c1fa16bcc842 | 16614306f486b3ecdb78e202277e14b55b116774 | refs/heads/master | 2023-03-12T11:01:51.567003 | 2023-02-25T12:53:29 | 2023-02-25T12:53:29 | 92,890,395 | 7 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,746 | java | package br.com.kproj.salesman.infrastructure.security.authentication;
import com.google.common.collect.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import static java.lang.Boolean.TRUE;
@SuppressWarnings("serial")
public class LoggedUser implements UserDetails {
private Long id;
private String name;
private String login;
private String password;
private List<GrantedAuthority> authorities = Lists.newArrayList();
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setLogin(String login) {
this.login = login;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getUsername() {
return this.login;
}
@Override
public boolean isAccountNonExpired() {
return TRUE;
}
@Override
public boolean isAccountNonLocked() {
return TRUE;
}
@Override
public boolean isCredentialsNonExpired() {
return TRUE;
}
@Override
public boolean isEnabled() {
return TRUE;
}
public void addRole(String role) {
this.authorities.add(new SimpleGrantedAuthority(role));
}
public void removeRole(String role) {
this.authorities.remove(new SimpleGrantedAuthority(role));
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LoggedUser getLoggedUser() {
return this;
}
}
| [
"mmaico@gmail.com"
] | mmaico@gmail.com |
2c2908960ea3a219f9e2282cf64678d6fea20cdd | 7773ea6f465ffecfd4f9821aad56ee1eab90d97a | /plugins/InspectionGadgets/test/com/siyeh/igfixes/memory/inner_class_static/AnonymousInside.java | 7f86ba5173ff3c0e7bbc7aba6ddfe0d3c455ac0c | [
"Apache-2.0"
] | permissive | aghasyedbilal/intellij-community | 5fa14a8bb62a037c0d2764fb172e8109a3db471f | fa602b2874ea4eb59442f9937b952dcb55910b6e | refs/heads/master | 2023-04-10T20:55:27.988445 | 2020-05-03T22:00:26 | 2020-05-03T22:26:23 | 261,074,802 | 2 | 0 | Apache-2.0 | 2020-05-04T03:48:36 | 2020-05-04T03:48:35 | null | UTF-8 | Java | false | false | 346 | java | class C {
public C(Feedback i) {
}
}
class Feedback {
String getOutputWindowName() {
return null;
}
}
class A {
protected class <caret>B extends C {
public B() {
super(new Feedback() {
public void outputMessage() {
getOutputWindowName();
}
}
);
}
}
} | [
"anna.kozlova@jetbrains.com"
] | anna.kozlova@jetbrains.com |
4faccbd5a56e848bf143ceaca858a70fb2843e7c | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java | 3218c3a45b36969b13bd8bc7fb7e6798bb7a9a19 | [
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | Java | false | false | 21,676 | java | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tab;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import org.chromium.base.Log;
import org.chromium.base.ObserverList.RewindableIterator;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.blink_public.platform.WebDisplayMode;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.RepostFormWarningDialog;
import org.chromium.chrome.browser.document.DocumentUtils;
import org.chromium.chrome.browser.document.DocumentWebContentsDelegate;
import org.chromium.chrome.browser.findinpage.FindMatchRectsDetails;
import org.chromium.chrome.browser.findinpage.FindNotificationDetails;
import org.chromium.chrome.browser.fullscreen.FullscreenManager;
import org.chromium.chrome.browser.media.MediaCaptureNotificationService;
import org.chromium.chrome.browser.policy.PolicyAuditor;
import org.chromium.chrome.browser.policy.PolicyAuditor.AuditEvent;
import org.chromium.chrome.browser.tabmodel.TabCreatorManager.TabCreator;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.tabmodel.TabWindowManager;
import org.chromium.components.web_contents_delegate_android.WebContentsDelegateAndroid;
import org.chromium.content.browser.ActivityContentVideoViewEmbedder;
import org.chromium.content.browser.ContentVideoViewEmbedder;
import org.chromium.content.browser.ContentViewCore;
import org.chromium.content_public.browser.InvalidateTypes;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.common.ResourceRequestBody;
import org.chromium.ui.mojom.WindowOpenDisposition;
/**
* A basic {@link TabWebContentsDelegateAndroid} that forwards some calls to the registered
* {@link TabObserver}s.
*/
public class TabWebContentsDelegateAndroid extends WebContentsDelegateAndroid {
/**
* Listener to be notified when a find result is received.
*/
public interface FindResultListener {
public void onFindResult(FindNotificationDetails result);
}
/**
* Listener to be notified when the rects corresponding to find matches are received.
*/
public interface FindMatchRectsListener {
public void onFindMatchRects(FindMatchRectsDetails result);
}
/** Used for logging. */
private static final String TAG = "WebContentsDelegate";
protected final Tab mTab;
private FindResultListener mFindResultListener;
private FindMatchRectsListener mFindMatchRectsListener = null;
private int mDisplayMode = WebDisplayMode.Browser;
protected Handler mHandler;
private final Runnable mCloseContentsRunnable = new Runnable() {
@Override
public void run() {
boolean isSelected = mTab.getTabModelSelector().getCurrentTab() == mTab;
mTab.getTabModelSelector().closeTab(mTab);
// If the parent Tab belongs to another Activity, fire the Intent to bring it back.
if (isSelected && mTab.getParentIntent() != null
&& mTab.getActivity().getIntent() != mTab.getParentIntent()) {
mTab.getActivity().startActivity(mTab.getParentIntent());
}
}
/** If the API allows it, returns whether a Task still exists for the parent Activity. */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean isParentInAndroidOverview() {
ActivityManager activityManager = (ActivityManager) mTab.getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.AppTask task : activityManager.getAppTasks()) {
Intent taskIntent = DocumentUtils.getBaseIntentFromTask(task);
if (taskIntent != null && taskIntent.filterEquals(mTab.getParentIntent())) {
return true;
}
}
return false;
}
};
public TabWebContentsDelegateAndroid(Tab tab) {
mTab = tab;
mHandler = new Handler();
}
/**
* Sets the current display mode which can be queried using media queries.
* @param displayMode A value from {@link org.chromium.blink_public.platform.WebDisplayMode}.
*/
public void setDisplayMode(int displayMode) {
mDisplayMode = displayMode;
}
@CalledByNative
private int getDisplayMode() {
return mDisplayMode;
}
@CalledByNative
private void onFindResultAvailable(FindNotificationDetails result) {
if (mFindResultListener != null) {
mFindResultListener.onFindResult(result);
}
}
@CalledByNative
private void onFindMatchRectsAvailable(FindMatchRectsDetails result) {
if (mFindMatchRectsListener != null) {
mFindMatchRectsListener.onFindMatchRects(result);
}
}
/** Register to receive the results of startFinding calls. */
public void setFindResultListener(FindResultListener listener) {
mFindResultListener = listener;
}
/** Register to receive the results of requestFindMatchRects calls. */
public void setFindMatchRectsListener(FindMatchRectsListener listener) {
mFindMatchRectsListener = listener;
}
// Helper functions used to create types that are part of the public interface
@CalledByNative
private static Rect createRect(int x, int y, int right, int bottom) {
return new Rect(x, y, right, bottom);
}
@CalledByNative
private static RectF createRectF(float x, float y, float right, float bottom) {
return new RectF(x, y, right, bottom);
}
@CalledByNative
private static FindNotificationDetails createFindNotificationDetails(
int numberOfMatches, Rect rendererSelectionRect,
int activeMatchOrdinal, boolean finalUpdate) {
return new FindNotificationDetails(numberOfMatches, rendererSelectionRect,
activeMatchOrdinal, finalUpdate);
}
@CalledByNative
private static FindMatchRectsDetails createFindMatchRectsDetails(
int version, int numRects, RectF activeRect) {
return new FindMatchRectsDetails(version, numRects, activeRect);
}
@CalledByNative
private static void setMatchRectByIndex(
FindMatchRectsDetails findMatchRectsDetails, int index, RectF rect) {
findMatchRectsDetails.rects[index] = rect;
}
@Override
public void onLoadProgressChanged(int progress) {
if (!mTab.isLoading()) return;
mTab.notifyLoadProgress(mTab.getProgress());
}
@Override
public void loadingStateChanged(boolean toDifferentDocument) {
boolean isLoading = mTab.getWebContents() != null && mTab.getWebContents().isLoading();
if (isLoading) {
mTab.onLoadStarted(toDifferentDocument);
} else {
mTab.onLoadStopped();
}
}
@Override
public void onUpdateUrl(String url) {
RewindableIterator<TabObserver> observers = mTab.getTabObservers();
while (observers.hasNext()) {
observers.next().onUpdateUrl(mTab, url);
}
}
@Override
public void showRepostFormWarningDialog() {
mTab.resetSwipeRefreshHandler();
if (mTab.getActivity() == null) return;
RepostFormWarningDialog warningDialog = new RepostFormWarningDialog(mTab);
warningDialog.show(mTab.getActivity().getFragmentManager(), null);
}
@Override
public void toggleFullscreenModeForTab(boolean enableFullscreen) {
if (mTab.getFullscreenManager() != null) {
mTab.getFullscreenManager().setPersistentFullscreenMode(enableFullscreen);
}
RewindableIterator<TabObserver> observers = mTab.getTabObservers();
while (observers.hasNext()) {
observers.next().onToggleFullscreenMode(mTab, enableFullscreen);
}
}
@Override
public void navigationStateChanged(int flags) {
if ((flags & InvalidateTypes.TAB) != 0) {
int mediaType = MediaCaptureNotificationService.getMediaType(
isCapturingAudio(), isCapturingVideo(), isCapturingScreen());
MediaCaptureNotificationService.updateMediaNotificationForTab(
mTab.getApplicationContext(), mTab.getId(), mediaType, mTab.getUrl());
}
if ((flags & InvalidateTypes.TITLE) != 0) {
// Update cached title then notify observers.
mTab.updateTitle();
}
if ((flags & InvalidateTypes.URL) != 0) {
RewindableIterator<TabObserver> observers = mTab.getTabObservers();
while (observers.hasNext()) {
observers.next().onUrlUpdated(mTab);
}
}
}
@Override
public void visibleSSLStateChanged() {
RewindableIterator<TabObserver> observers = mTab.getTabObservers();
while (observers.hasNext()) {
observers.next().onSSLStateUpdated(mTab);
}
}
@Override
public void webContentsCreated(WebContents sourceWebContents, long openerRenderProcessId,
long openerRenderFrameId, String frameName, String targetUrl,
WebContents newWebContents) {
RewindableIterator<TabObserver> observers = mTab.getTabObservers();
while (observers.hasNext()) {
observers.next().webContentsCreated(mTab, sourceWebContents, openerRenderProcessId,
openerRenderFrameId, frameName, targetUrl, newWebContents);
}
// The URL can't be taken from the WebContents if it's paused. Save it for later.
assert mWebContentsUrlMapping == null;
mWebContentsUrlMapping = Pair.create(newWebContents, targetUrl);
// TODO(dfalcantara): Re-remove this once crbug.com/508366 is fixed.
TabCreator tabCreator = mTab.getActivity().getTabCreator(mTab.isIncognito());
if (tabCreator != null && tabCreator.createsTabsAsynchronously()) {
DocumentWebContentsDelegate.getInstance().attachDelegate(newWebContents);
}
}
@Override
public void rendererUnresponsive() {
super.rendererUnresponsive();
if (mTab.getWebContents() != null) nativeOnRendererUnresponsive(mTab.getWebContents());
mTab.handleRendererUnresponsive();
}
@Override
public void rendererResponsive() {
super.rendererResponsive();
if (mTab.getWebContents() != null) nativeOnRendererResponsive(mTab.getWebContents());
mTab.handleRendererResponsive();
}
@Override
public boolean isFullscreenForTabOrPending() {
return mTab.getFullscreenManager() == null
? false : mTab.getFullscreenManager().getPersistentFullscreenMode();
}
@Override
public void openNewTab(String url, String extraHeaders, ResourceRequestBody postData,
int disposition, boolean isRendererInitiated) {
mTab.openNewTab(url, extraHeaders, postData, disposition, true, isRendererInitiated);
}
private Pair<WebContents, String> mWebContentsUrlMapping;
protected TabModel getTabModel() {
// TODO(dfalcantara): Remove this when DocumentActivity.getTabModelSelector()
// can return a TabModelSelector that activateContents() can use.
return mTab.getTabModelSelector().getModel(mTab.isIncognito());
}
@CalledByNative
public boolean shouldResumeRequestsForCreatedWindow() {
// Pause the WebContents if an Activity has to be created for it first.
TabCreator tabCreator = mTab.getActivity().getTabCreator(mTab.isIncognito());
assert tabCreator != null;
return !tabCreator.createsTabsAsynchronously();
}
@CalledByNative
public boolean addNewContents(WebContents sourceWebContents, WebContents webContents,
int disposition, Rect initialPosition, boolean userGesture) {
assert mWebContentsUrlMapping.first == webContents;
TabCreator tabCreator = mTab.getActivity().getTabCreator(mTab.isIncognito());
assert tabCreator != null;
// Grab the URL, which might not be available via the Tab.
String url = mWebContentsUrlMapping.second;
mWebContentsUrlMapping = null;
// Skip opening a new Tab if it doesn't make sense.
if (mTab.isClosing()) return false;
// Creating new Tabs asynchronously requires starting a new Activity to create the Tab,
// so the Tab returned will always be null. There's no way to know synchronously
// whether the Tab is created, so assume it's always successful.
boolean createdSuccessfully = tabCreator.createTabWithWebContents(mTab,
webContents, mTab.getId(), TabLaunchType.FROM_LONGPRESS_FOREGROUND, url);
boolean success = tabCreator.createsTabsAsynchronously() || createdSuccessfully;
if (success && disposition == WindowOpenDisposition.NEW_POPUP) {
PolicyAuditor auditor =
((ChromeApplication) mTab.getApplicationContext()).getPolicyAuditor();
auditor.notifyAuditEvent(mTab.getApplicationContext(),
AuditEvent.OPEN_POPUP_URL_SUCCESS, url, "");
}
return success;
}
@Override
public void activateContents() {
boolean activityIsDestroyed = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
activityIsDestroyed = mTab.getActivity().isDestroyed();
}
if (activityIsDestroyed || !mTab.isInitialized()) {
Log.e(TAG, "Activity destroyed before calling activateContents(). Bailing out.");
return;
}
TabModel model = getTabModel();
int index = model.indexOf(mTab);
if (index == TabModel.INVALID_TAB_INDEX) return;
TabModelUtils.setIndex(model, index);
bringActivityToForeground();
}
/**
* Brings chrome's Activity to foreground, if it is not so.
*/
protected void bringActivityToForeground() {
// This intent is sent in order to get the activity back to the foreground if it was
// not already. The previous call will activate the right tab in the context of the
// TabModel but will only show the tab to the user if Chrome was already in the
// foreground.
// The intent is getting the tabId mostly because it does not cost much to do so.
// When receiving the intent, the tab associated with the tabId should already be
// active.
// Note that calling only the intent in order to activate the tab is slightly slower
// because it will change the tab when the intent is handled, which happens after
// Chrome gets back to the foreground.
Intent newIntent = Tab.createBringTabToFrontIntent(mTab.getId());
if (newIntent != null) {
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mTab.getApplicationContext().startActivity(newIntent);
}
}
@Override
public void closeContents() {
// Execute outside of callback, otherwise we end up deleting the native
// objects in the middle of executing methods on them.
mHandler.removeCallbacks(mCloseContentsRunnable);
mHandler.post(mCloseContentsRunnable);
}
@Override
public boolean takeFocus(boolean reverse) {
Activity activity = mTab.getActivity();
if (activity == null) return false;
if (reverse) {
View menuButton = activity.findViewById(R.id.menu_button);
if (menuButton == null || !menuButton.isShown()) {
menuButton = activity.findViewById(R.id.document_menu_button);
}
if (menuButton != null && menuButton.isShown()) {
return menuButton.requestFocus();
}
View tabSwitcherButton = activity.findViewById(R.id.tab_switcher_button);
if (tabSwitcherButton != null && tabSwitcherButton.isShown()) {
return tabSwitcherButton.requestFocus();
}
} else {
View urlBar = activity.findViewById(R.id.url_bar);
if (urlBar != null) return urlBar.requestFocus();
}
return false;
}
@Override
public void handleKeyboardEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && mTab.getActivity() != null) {
if (mTab.getActivity().onKeyDown(event.getKeyCode(), event)) return;
// Handle the Escape key here (instead of in KeyboardShortcuts.java), so it doesn't
// interfere with other parts of the activity (e.g. the URL bar).
if (event.getKeyCode() == KeyEvent.KEYCODE_ESCAPE && event.hasNoModifiers()) {
WebContents wc = mTab.getWebContents();
if (wc != null) wc.stop();
return;
}
}
handleMediaKey(event);
}
/**
* Redispatches unhandled media keys. This allows bluetooth headphones with play/pause or
* other buttons to function correctly.
*/
@TargetApi(19)
private void handleMediaKey(KeyEvent e) {
if (Build.VERSION.SDK_INT < 19) return;
switch (e.getKeyCode()) {
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
case KeyEvent.KEYCODE_MEDIA_CLOSE:
case KeyEvent.KEYCODE_MEDIA_EJECT:
case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
AudioManager am = (AudioManager) mTab.getApplicationContext().getSystemService(
Context.AUDIO_SERVICE);
am.dispatchMediaKeyEvent(e);
break;
default:
break;
}
}
/**
* @return Whether audio is being captured.
*/
private boolean isCapturingAudio() {
return !mTab.isClosing() && nativeIsCapturingAudio(mTab.getWebContents());
}
/**
* @return Whether video is being captured.
*/
private boolean isCapturingVideo() {
return !mTab.isClosing() && nativeIsCapturingVideo(mTab.getWebContents());
}
/**
* @return Whether screen is being captured.
*/
private boolean isCapturingScreen() {
return !mTab.isClosing() && nativeIsCapturingScreen(mTab.getWebContents());
}
/**
* When STOP button in the media capture notification is clicked, pass the event to native
* to stop the media capture.
*/
public static void notifyStopped(int tabId) {
final Tab tab = TabWindowManager.getInstance().getTabById(tabId);
if (tab != null) nativeNotifyStopped(tab.getWebContents());
}
@Override
public ContentVideoViewEmbedder getContentVideoViewEmbedder() {
return new ActivityContentVideoViewEmbedder(mTab.getActivity()) {
@Override
public void enterFullscreenVideo(View view, boolean isVideoLoaded) {
super.enterFullscreenVideo(view, isVideoLoaded);
FullscreenManager fullscreenManager = mTab.getFullscreenManager();
if (fullscreenManager != null) {
fullscreenManager.setOverlayVideoMode(true);
// Disable double tap for video.
ContentViewCore cvc = mTab.getContentViewCore();
if (cvc != null) {
cvc.updateDoubleTapSupport(false);
}
}
}
@Override
public void exitFullscreenVideo() {
FullscreenManager fullscreenManager = mTab.getFullscreenManager();
if (fullscreenManager != null) {
fullscreenManager.setOverlayVideoMode(false);
// Disable double tap for video.
ContentViewCore cvc = mTab.getContentViewCore();
if (cvc != null) {
cvc.updateDoubleTapSupport(true);
}
}
super.exitFullscreenVideo();
}
};
}
private static native void nativeOnRendererUnresponsive(WebContents webContents);
private static native void nativeOnRendererResponsive(WebContents webContents);
private static native boolean nativeIsCapturingAudio(WebContents webContents);
private static native boolean nativeIsCapturingVideo(WebContents webContents);
private static native boolean nativeIsCapturingScreen(WebContents webContents);
private static native void nativeNotifyStopped(WebContents webContents);
}
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
c09e8a536f5fcbb0c3763370e4f7ec7627fd2f2d | 0f1ecc480240de112cd0f51b4d95de931d203ab5 | /app/src/main/java/com/example/me_jie/snailexpress_staff/ui/LoginActivity.java | 4c40e3c8a1093085841ef6509b7aa2ae2930fa3a | [] | no_license | roger54920/SnailExpress_Staff | bc3e9ac51b37bd1f4ed204b7e883b61b91f90e14 | c18cda341b96ec734ded0438258c754de2a98561 | refs/heads/master | 2020-03-29T01:42:04.203171 | 2018-09-19T06:22:57 | 2018-09-19T06:22:57 | 149,401,332 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,624 | java | package com.example.me_jie.snailexpress_staff.ui;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.me_jie.snailexpress_staff.R;
import com.example.me_jie.snailexpress_staff.bean.AllRegionBean;
import com.example.me_jie.snailexpress_staff.bean.IfMobileExitBean;
import com.example.me_jie.snailexpress_staff.bean.LoginBean;
import com.example.me_jie.snailexpress_staff.custom.GlideCircleTransform;
import com.example.me_jie.snailexpress_staff.custom.SwitchView;
import com.example.me_jie.snailexpress_staff.dialog.LazyLoadProgressDialog;
import com.example.me_jie.snailexpress_staff.mvp.AllRegionView;
import com.example.me_jie.snailexpress_staff.mvp.IfMobileExitView;
import com.example.me_jie.snailexpress_staff.mvp.LoginView;
import com.example.me_jie.snailexpress_staff.mvp.VerificationCodeView;
import com.example.me_jie.snailexpress_staff.okgo.OkHttpResolve;
import com.example.me_jie.snailexpress_staff.presenter.AllRegionPresenter;
import com.example.me_jie.snailexpress_staff.presenter.IfMobileExitPresenter;
import com.example.me_jie.snailexpress_staff.presenter.LoginPresenter;
import com.example.me_jie.snailexpress_staff.presenter.VerificationCodePresenter;
import com.example.me_jie.snailexpress_staff.utils.BitmapUtil;
import com.example.me_jie.snailexpress_staff.utils.CacheUtils;
import com.example.me_jie.snailexpress_staff.utils.LazyLoadUtil;
import com.example.me_jie.snailexpress_staff.utils.MyActivityManager;
import com.example.me_jie.snailexpress_staff.utils.SkipIntentUtil;
import com.example.me_jie.snailexpress_staff.utils.StatusBarUtil;
import com.example.me_jie.snailexpress_staff.utils.TelNumMatch;
import com.lzy.okgo.OkGo;
import com.zhy.autolayout.AutoLayoutActivity;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import static com.example.me_jie.snailexpress_staff.Constants.UP_LOAD_IMAGE_TOP;
import static com.example.me_jie.snailexpress_staff.R.id.verify_btn;
import static com.example.me_jie.snailexpress_staff.utils.BitmapUtil.fileIsExists;
/**
* 登录
*/
public class LoginActivity extends AutoLayoutActivity implements LoginView, IfMobileExitView, VerificationCodeView, AllRegionView ,EasyPermissions.PermissionCallbacks {
private static final String TAG = "LoginActivity";
@InjectView(verify_btn)
Button verifyBtn;
@InjectView(R.id.login_btn)
Button loginBtn;
@InjectView(R.id.register_btn)
Button registerBtn;
@InjectView(R.id.sr_number)
EditText srNumber;
@InjectView(R.id.sr_verification)
EditText srVerification;
@InjectView(R.id.checkbox)
CheckBox checkbox;
@InjectView(R.id.circle)
ImageView circle;
@InjectView(R.id.slide_switch_btn)
SwitchView slideSwitchBtn;
private Intent intent;
private boolean checkAdministrator = true;//站长/员工滑动状态
private boolean checkStaff = false;
private IfMobileExitPresenter ifMobileExitPresenter = new IfMobileExitPresenter();//是否注册手机号
private VerificationCodePresenter verificationCodePresenter = new VerificationCodePresenter(); //获取验证码
private LoginPresenter loginPresenter = new LoginPresenter();//登录
private LazyLoadProgressDialog lazyLoadProgressDialog;//延迟加载
private String phone = "";//手机号
SharedPreferences sp; //免登陆
SharedPreferences.Editor editor;
private AllRegionPresenter allRegionPresenter = new AllRegionPresenter();//全国地址
private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
@Override
protected void onStart() {
super.onStart();
requestCodeCameraPermissions();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
@AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
private void requestCodeCameraPermissions() {
String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!EasyPermissions.hasPermissions(this, perms)) {
EasyPermissions.requestPermissions(this, "扫描二维码/自定义相机需要打开相机和散光灯的权限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.inject(this);
StatusBarUtil.SetWriteStatusBar(this, true);
sp = getSharedPreferences("login", Context.MODE_PRIVATE);
editor = sp.edit();
//免登陆
String roleName = sp.getString("roleName", null);
long timeout = sp.getLong("timeout", 0);
if (roleName != null && timeout != 0) {
if (System.currentTimeMillis() >= timeout) {
editor.remove("login");
editor.clear();
editor.commit();
SkipIntentUtil.skipIntent(this, LoginActivity.class);
overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
MyActivityManager.getInstance().finishAllActivity();
requestWriteOff();
} else {
if (roleName.equals("stationmaster")) {
SkipIntentUtil.skipIntent(this, AdministratorHomeActivity.class);
finish();
} else {
SkipIntentUtil.skipIntent(this, StaffHomeActivity.class);
finish();
}
}
}
lazyLoadProgressDialog = lazyLoadProgressDialog.createDialog(this);
slideSwitchBtn.setOnSwitchListener(new SwitchView.OnSwitchListener() {
@Override
public void onCheck(SwitchView sv, boolean checkLeft, boolean checkRight) {
checkAdministrator = checkLeft;
checkStaff = checkRight;
}
});
srNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String srphone = srNumber.getText().toString();
if (TelNumMatch.isPhone(srphone)) {
String sdPath = BitmapUtil.getSDPath();
if (!TextUtils.isEmpty(sdPath)) {
sdPath = sdPath + "/thesnailfamily/" + srphone + ".jpg";
boolean b = fileIsExists(sdPath);
if (b == true) {
Bitmap diskBitmap = BitmapUtil.getDiskBitmap(sdPath);
if(diskBitmap!=null){
circle.setImageBitmap(BitmapUtil.toRoundBitmap(diskBitmap));
}else{
circle.setImageResource(R.drawable.circle_shape);
}
} else {
circle.setImageResource(R.drawable.circle_shape);
}
} else {
circle.setImageResource(R.drawable.circle_shape);
}
} else {
circle.setImageResource(R.drawable.circle_shape);
}
}
});
}
/**
* 初始化登录
*
* @param str
*/
private void requestLoginVerification(String str) {
new OkHttpResolve(this);
loginPresenter.attach(this);
loginPresenter.postJsonLoginVerificationResult(str, this, lazyLoadProgressDialog);
}
/**
* 初始化注销
*/
private void requestWriteOff() {
new OkHttpResolve(this);
loginPresenter.attach(this);
loginPresenter.userWriteOffResult(this);
}
/**
* 初始化是否注册手机号
*
* @param str
*/
private void requestifMobileExit(String str) {
new OkHttpResolve(this);
ifMobileExitPresenter.attach(this);
ifMobileExitPresenter.postJsonResult(str, this, lazyLoadProgressDialog);
}
/**
* 初始化请求验证码
*
* @param str
*/
private void requestverificationCode(String str) {
new OkHttpResolve(this);
verificationCodePresenter.attach(this);
verificationCodePresenter.postJsonCodeResult(str, this, lazyLoadProgressDialog);
}
/**
* 全国地区初始化请求数据
*/
private void requestDataAllRegion() {
new OkHttpResolve(this);
allRegionPresenter.attach(this);
allRegionPresenter.postAllRegionJsonResult("{\"id\":\" \"}", this, null);
}
@OnClick({R.id.verify_btn, R.id.login_btn, R.id.register_btn, R.id.checkbox, R.id.circle})
public void onViewClicked(View view) {
switch (view.getId()) {
case verify_btn:
phone = srNumber.getText().toString();
if (!TextUtils.isEmpty(phone)) {
if (TelNumMatch.isPhone(phone) == true) {
srVerification.setText("");
lazyLoadProgressDialog.show();
LazyLoadUtil.SetLazyLad(lazyLoadProgressDialog);
if (checkAdministrator == true) {
requestifMobileExit("{\"mobile\":\"" + phone + "\",\"roleName\":\"stationmaster\"}");
} else if (checkStaff == true) {
requestifMobileExit("{\"mobile\":\"" + phone + "\",\"roleName\":\"employee,securitycleanPerson\"}");
}
} else {
Toast.makeText(this, "请正确输入手机号!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "请输入手机号!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.login_btn:
String srphone = srNumber.getText().toString();
if (!TextUtils.isEmpty(srphone)) {
if (TelNumMatch.isPhone(srphone) == true) {
String srverification = srVerification.getText().toString().trim();
if (srverification.length() == 6) {
lazyLoadProgressDialog.show();
LazyLoadUtil.SetLazyLad(lazyLoadProgressDialog);
HashMap<String, String> params = new HashMap<>();
params.put("username", srphone);
params.put("appLogin", "true");
if (checkAdministrator == true) {
params.put("rolename", "stationmaster");
params.put("validateCode", srverification);
JSONObject jsonObject = new JSONObject(params);
requestLoginVerification(jsonObject.toString());
} else if (checkStaff == true) {
params.put("rolename", "employee,securitycleanPerson");
params.put("validateCode", srverification);
JSONObject jsonObject = new JSONObject(params);
requestLoginVerification(jsonObject.toString());
}
} else {
Toast.makeText(this, "请输入验证码!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "请正确输入手机号!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "请输入手机号!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.register_btn:
intent = new Intent(LoginActivity.this, StaffRegisterActivity.class);
startActivityForResult(intent, 0);
break;
case R.id.checkbox:
if (checkbox.isChecked() == true) {
loginBtn.setEnabled(true);
} else {
loginBtn.setEnabled(false);
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
String moblie = data.getStringExtra("phone");
if (!moblie.equals("") || moblie != null) {
srNumber.setText(data.getStringExtra("phone"));
verifyBtn.setEnabled(true);
verifyBtn.setText("获取验证码");
}
}
}
CountDownTimer timer = new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
verifyBtn.setEnabled(false);
verifyBtn.setText((millisUntilFinished / 1000) + "秒");
verifyBtn.setBackgroundResource(R.drawable.verify_btn_shape_nor);
}
@Override
public void onFinish() {
verifyBtn.setEnabled(true);
verifyBtn.setText("重新获取");
verifyBtn.setBackgroundResource(R.drawable.verify_btn_shape_sel);
}
};
@Override
public void onBeanFinish(Object o) {
IfMobileExitBean ifMobileExitBean = (IfMobileExitBean) o;
if (ifMobileExitBean != null) {
if (ifMobileExitBean.isIfMobileExit() == true) {
requestverificationCode("{\"mobile\":\"" + phone + "\"}");
} else {
SkipIntentUtil.toastShow(this, "账号不存在,请检查后登录!");
}
}
}
@Override
public void onBeanLoginFinish(Object o) {
LoginBean loginBean = (LoginBean) o;
if (loginBean != null) {
if (loginBean.getUser().getRoleName() != null) {
final String mobile = loginBean.getUser().getMobile();
Glide.with(this).load(UP_LOAD_IMAGE_TOP + loginBean.getUser().getPhoto())
.asBitmap()
.transform(new GlideCircleTransform(this))
.diskCacheStrategy(DiskCacheStrategy.SOURCE) //添加缓存
.placeholder(circle.getDrawable())//加载成功之前
.error(circle.getDrawable())//加载失败
.crossFade()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
BitmapUtil.saveImageToGallery(resource, mobile);
}
});
sp = getSharedPreferences("login", Context.MODE_PRIVATE);
editor = sp.edit();
String roleName = loginBean.getUser().getRoleName();
long sessionTimeout = loginBean.getSessionTimeout();
if (roleName.equals("stationmaster")) {
avoidLandingSkip(roleName, sessionTimeout, AdministratorHomeActivity.class);
} else {
avoidLandingSkip(roleName, sessionTimeout, StaffHomeActivity.class);
}
requestDataAllRegion();
}
}
}
/**
* @param roleName
* @param sessionTimeout
* @param cl
*/
private void avoidLandingSkip(String roleName, long sessionTimeout, Class cl) {
if ((roleName != null || !roleName.equals("")) && sessionTimeout != 0) {
editor.putString("roleName", roleName);
editor.putLong("timeout", System.currentTimeMillis() + sessionTimeout);
editor.commit();
}
SkipIntentUtil.skipIntent(this, cl);
}
@Override
public void onBeanWriteOffFinish(Object o) {
LoginBean loginBean = (LoginBean) o;
if (loginBean != null) {
Log.e(TAG, "onBeanWriteOffFinish: 注销成功!");
}
}
@Override
public void onBeanVerificationCodeFinish(Object o) {
LoginBean verificationCodeBean = (LoginBean) o;
if (verificationCodeBean != null) {
timer.start();
}
}
@Override
public void onAllRegionListFinish(Object o) {
final AllRegionBean allRegionBean = (AllRegionBean) o;
if (allRegionBean != null) {
new AsyncTask<String, Void, AllRegionBean>() {
@Override
protected AllRegionBean doInBackground(String... params) {
CacheUtils.writeJson(LoginActivity.this, allRegionBean, "nationalregions.txt", false,this);
finish();
return null;
}
}.execute();
}
}
/**
* Android中的“再按一次返回键退出程序”实现
*/
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出蜗牛快递!", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
MyActivityManager.getInstance().finishAllActivity();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onPause() {
SkipIntentUtil.toastStop();
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
//根据 Tag 取消请求
OkGo.getInstance().cancelTag(this);
ifMobileExitPresenter.dettach();
verificationCodePresenter.dettach();
loginPresenter.dettach();
if (timer != null) {
timer.cancel();
}
}
}
| [
"roger54920@163.com"
] | roger54920@163.com |
ce89a2b567cbfbd92eb27af894b124df5d4bb533 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /java/hazelcast/2017/4/TimedMemberStateFactory.java | 3dd782ad284578acfb86a654c1a9c82a93311a31 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Java | false | false | 17,771 | java | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.management;
import com.hazelcast.cache.CacheStatistics;
import com.hazelcast.cache.impl.CacheService;
import com.hazelcast.cache.impl.ICacheService;
import com.hazelcast.collection.impl.queue.QueueService;
import com.hazelcast.config.CacheConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.GroupConfig;
import com.hazelcast.config.SSLConfig;
import com.hazelcast.core.Client;
import com.hazelcast.core.Member;
import com.hazelcast.executor.impl.DistributedExecutorService;
import com.hazelcast.hotrestart.HotRestartService;
import com.hazelcast.instance.HazelcastInstanceImpl;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.cluster.ClusterService;
import com.hazelcast.internal.management.dto.ClientEndPointDTO;
import com.hazelcast.internal.management.dto.ClusterHotRestartStatusDTO;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.monitor.LocalExecutorStats;
import com.hazelcast.monitor.LocalMapStats;
import com.hazelcast.monitor.LocalMemoryStats;
import com.hazelcast.monitor.LocalMultiMapStats;
import com.hazelcast.monitor.LocalOperationStats;
import com.hazelcast.monitor.LocalQueueStats;
import com.hazelcast.monitor.LocalReplicatedMapStats;
import com.hazelcast.monitor.LocalTopicStats;
import com.hazelcast.monitor.LocalWanStats;
import com.hazelcast.monitor.TimedMemberState;
import com.hazelcast.monitor.WanSyncState;
import com.hazelcast.monitor.impl.HotRestartStateImpl;
import com.hazelcast.monitor.impl.LocalCacheStatsImpl;
import com.hazelcast.monitor.impl.LocalMemoryStatsImpl;
import com.hazelcast.monitor.impl.LocalOperationStatsImpl;
import com.hazelcast.monitor.impl.MemberPartitionStateImpl;
import com.hazelcast.monitor.impl.MemberStateImpl;
import com.hazelcast.monitor.impl.NodeStateImpl;
import com.hazelcast.multimap.impl.MultiMapService;
import com.hazelcast.nio.Address;
import com.hazelcast.replicatedmap.impl.ReplicatedMapService;
import com.hazelcast.spi.StatisticsAwareService;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.servicemanager.ServiceInfo;
import com.hazelcast.spi.partition.IPartition;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.topic.impl.TopicService;
import com.hazelcast.wan.WanReplicationService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* A Factory for creating {@link com.hazelcast.monitor.TimedMemberState} instances.
*/
public class TimedMemberStateFactory {
private static final int INITIAL_PARTITION_SAFETY_CHECK_DELAY = 15;
private static final int PARTITION_SAFETY_CHECK_PERIOD = 60;
private final HazelcastInstanceImpl instance;
private final int maxVisibleInstanceCount;
private final boolean cacheServiceEnabled;
private volatile boolean memberStateSafe = true;
public TimedMemberStateFactory(HazelcastInstanceImpl instance) {
this.instance = instance;
Node node = instance.node;
maxVisibleInstanceCount = node.getProperties().getInteger(GroupProperty.MC_MAX_VISIBLE_INSTANCE_COUNT);
cacheServiceEnabled = isCacheServiceEnabled();
}
private boolean isCacheServiceEnabled() {
NodeEngineImpl nodeEngine = instance.node.nodeEngine;
Collection<ServiceInfo> serviceInfos = nodeEngine.getServiceInfos(CacheService.class);
return !serviceInfos.isEmpty();
}
public void init() {
instance.node.nodeEngine.getExecutionService().scheduleWithRepetition(new Runnable() {
@Override
public void run() {
memberStateSafe = instance.getPartitionService().isLocalMemberSafe();
}
}, INITIAL_PARTITION_SAFETY_CHECK_DELAY, PARTITION_SAFETY_CHECK_PERIOD, TimeUnit.SECONDS);
}
public TimedMemberState createTimedMemberState() {
MemberStateImpl memberState = new MemberStateImpl();
Collection<StatisticsAwareService> services = instance.node.nodeEngine.getServices(StatisticsAwareService.class);
TimedMemberState timedMemberState = new TimedMemberState();
createMemberState(timedMemberState, memberState, services);
timedMemberState.setMaster(instance.node.isMaster());
timedMemberState.setMemberList(new ArrayList<String>());
if (timedMemberState.isMaster()) {
Set<Member> memberSet = instance.getCluster().getMembers();
for (Member member : memberSet) {
MemberImpl memberImpl = (MemberImpl) member;
Address address = memberImpl.getAddress();
timedMemberState.getMemberList().add(address.getHost() + ":" + address.getPort());
}
}
timedMemberState.setMemberState(memberState);
GroupConfig groupConfig = instance.getConfig().getGroupConfig();
timedMemberState.setClusterName(groupConfig.getName());
SSLConfig sslConfig = instance.getConfig().getNetworkConfig().getSSLConfig();
timedMemberState.setSslEnabled(sslConfig != null && sslConfig.isEnabled());
return timedMemberState;
}
protected LocalMemoryStats getMemoryStats() {
return new LocalMemoryStatsImpl(instance.getMemoryStats());
}
protected LocalOperationStats getOperationStats() {
return new LocalOperationStatsImpl(instance.node);
}
private void createMemberState(TimedMemberState timedMemberState, MemberStateImpl memberState,
Collection<StatisticsAwareService> services) {
Node node = instance.node;
HashSet<ClientEndPointDTO> serializableClientEndPoints = new HashSet<ClientEndPointDTO>();
for (Client client : instance.node.clientEngine.getClients()) {
serializableClientEndPoints.add(new ClientEndPointDTO(client));
}
memberState.setClients(serializableClientEndPoints);
Address thisAddress = node.getThisAddress();
memberState.setAddress(thisAddress.getHost() + ":" + thisAddress.getPort());
TimedMemberStateFactoryHelper.registerJMXBeans(instance, memberState);
MemberPartitionStateImpl memberPartitionState = (MemberPartitionStateImpl) memberState.getMemberPartitionState();
InternalPartitionService partitionService = node.getPartitionService();
IPartition[] partitions = partitionService.getPartitions();
List<Integer> partitionList = memberPartitionState.getPartitions();
for (IPartition partition : partitions) {
if (partition.isLocal()) {
partitionList.add(partition.getPartitionId());
}
}
memberPartitionState.setMigrationQueueSize(partitionService.getMigrationQueueSize());
memberPartitionState.setMemberStateSafe(memberStateSafe);
memberState.setLocalMemoryStats(getMemoryStats());
memberState.setOperationStats(getOperationStats());
TimedMemberStateFactoryHelper.createRuntimeProps(memberState);
createMemState(timedMemberState, memberState, services);
createNodeState(memberState);
createHotRestartState(memberState);
createClusterHotRestartStatus(memberState);
createWanSyncState(memberState);
}
private void createHotRestartState(MemberStateImpl memberState) {
final HotRestartService hotRestartService = instance.node.getNodeExtension().getHotRestartService();
boolean hotBackupEnabled = hotRestartService.isHotBackupEnabled();
final HotRestartStateImpl state = new HotRestartStateImpl(hotRestartService.getBackupTaskStatus(), hotBackupEnabled);
memberState.setHotRestartState(state);
}
private void createClusterHotRestartStatus(MemberStateImpl memberState) {
final ClusterHotRestartStatusDTO state =
instance.node.getNodeExtension().getInternalHotRestartService().getCurrentClusterHotRestartStatus();
memberState.setClusterHotRestartStatus(state);
}
private void createNodeState(MemberStateImpl memberState) {
Node node = instance.node;
ClusterService cluster = instance.node.clusterService;
NodeStateImpl nodeState = new NodeStateImpl(cluster.getClusterState(), node.getState(),
cluster.getClusterVersion(), node.getVersion());
memberState.setNodeState(nodeState);
}
private void createWanSyncState(MemberStateImpl memberState) {
WanReplicationService wanReplicationService = instance.node.nodeEngine.getWanReplicationService();
WanSyncState wanSyncState = wanReplicationService.getWanSyncState();
if (wanSyncState != null) {
memberState.setWanSyncState(wanSyncState);
}
}
private void createMemState(TimedMemberState timedMemberState, MemberStateImpl memberState,
Collection<StatisticsAwareService> services) {
int count = 0;
Config config = instance.getConfig();
Set<String> longInstanceNames = new HashSet<String>(maxVisibleInstanceCount);
for (StatisticsAwareService service : services) {
if (count < maxVisibleInstanceCount) {
if (service instanceof MapService) {
count = handleMap(memberState, count, config, ((MapService) service).getStats(), longInstanceNames);
} else if (service instanceof MultiMapService) {
count = handleMultimap(memberState, count, config, ((MultiMapService) service).getStats(), longInstanceNames);
} else if (service instanceof QueueService) {
count = handleQueue(memberState, count, config, ((QueueService) service).getStats(), longInstanceNames);
} else if (service instanceof TopicService) {
count = handleTopic(memberState, count, config, ((TopicService) service).getStats(), longInstanceNames);
} else if (service instanceof DistributedExecutorService) {
count = handleExecutorService(memberState, count, config,
((DistributedExecutorService) service).getStats(), longInstanceNames);
} else if (service instanceof ReplicatedMapService) {
count = handleReplicatedMap(memberState, count, config, ((ReplicatedMapService) service).getStats(),
longInstanceNames);
}
}
}
WanReplicationService wanReplicationService = instance.node.nodeEngine.getWanReplicationService();
Map<String, LocalWanStats> wanStats = wanReplicationService.getStats();
if (wanStats != null) {
count = handleWan(memberState, count, wanStats, longInstanceNames);
}
if (cacheServiceEnabled) {
ICacheService cacheService = getCacheService();
for (CacheConfig cacheConfig : cacheService.getCacheConfigs()) {
if (cacheConfig.isStatisticsEnabled() && count < maxVisibleInstanceCount) {
CacheStatistics statistics = cacheService.getStatistics(cacheConfig.getNameWithPrefix());
//Statistics can be null for a short period of time since config is created at first then stats map
//is filled.git
if (statistics != null) {
count = handleCache(memberState, count, cacheConfig, statistics, longInstanceNames);
}
}
}
}
timedMemberState.setInstanceNames(longInstanceNames);
}
private int handleExecutorService(MemberStateImpl memberState, int count, Config config,
Map<String, LocalExecutorStats> executorServices,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalExecutorStats> entry : executorServices.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findExecutorConfig(name).isStatisticsEnabled()) {
LocalExecutorStats stats = entry.getValue();
memberState.putLocalExecutorStats(name, stats);
longInstanceNames.add("e:" + name);
++count;
}
}
return count;
}
private int handleMultimap(MemberStateImpl memberState, int count, Config config, Map<String, LocalMultiMapStats> multiMaps,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalMultiMapStats> entry : multiMaps.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findMultiMapConfig(name).isStatisticsEnabled()) {
LocalMultiMapStats stats = entry.getValue();
memberState.putLocalMultiMapStats(name, stats);
longInstanceNames.add("m:" + name);
++count;
}
}
return count;
}
private int handleReplicatedMap(MemberStateImpl memberState, int count, Config
config, Map<String, LocalReplicatedMapStats> replicatedMaps, Set<String> longInstanceNames) {
for (Map.Entry<String, LocalReplicatedMapStats> entry : replicatedMaps.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findReplicatedMapConfig(name).isStatisticsEnabled()) {
LocalReplicatedMapStats stats = entry.getValue();
memberState.putLocalReplicatedMapStats(name, stats);
longInstanceNames.add("r:" + name);
++count;
}
}
return count;
}
private int handleTopic(MemberStateImpl memberState, int count, Config config, Map<String, LocalTopicStats> topics,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalTopicStats> entry : topics.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findTopicConfig(name).isStatisticsEnabled()) {
LocalTopicStats stats = entry.getValue();
memberState.putLocalTopicStats(name, stats);
longInstanceNames.add("t:" + name);
++count;
}
}
return count;
}
private int handleQueue(MemberStateImpl memberState, int count, Config config, Map<String, LocalQueueStats> queues,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalQueueStats> entry : queues.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findQueueConfig(name).isStatisticsEnabled()) {
LocalQueueStats stats = entry.getValue();
memberState.putLocalQueueStats(name, stats);
longInstanceNames.add("q:" + name);
++count;
}
}
return count;
}
private int handleMap(MemberStateImpl memberState, int count, Config config, Map<String, LocalMapStats> maps,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalMapStats> entry : maps.entrySet()) {
String name = entry.getKey();
if (count >= maxVisibleInstanceCount) {
break;
} else if (config.findMapConfig(name).isStatisticsEnabled()) {
LocalMapStats stats = entry.getValue();
memberState.putLocalMapStats(name, stats);
longInstanceNames.add("c:" + name);
++count;
}
}
return count;
}
private int handleWan(MemberStateImpl memberState, int count, Map<String, LocalWanStats> wans,
Set<String> longInstanceNames) {
for (Map.Entry<String, LocalWanStats> entry : wans.entrySet()) {
String schemeName = entry.getKey();
LocalWanStats stats = entry.getValue();
memberState.putLocalWanStats(schemeName, stats);
longInstanceNames.add("w:" + schemeName);
count++;
}
return count;
}
private int handleCache(MemberStateImpl memberState, int count, CacheConfig config, CacheStatistics cacheStatistics,
Set<String> longInstanceNames) {
memberState.putLocalCacheStats(config.getNameWithPrefix(), new LocalCacheStatsImpl(cacheStatistics));
longInstanceNames.add("j:" + config.getNameWithPrefix());
return ++count;
}
private ICacheService getCacheService() {
return instance.node.nodeEngine.getService(ICacheService.SERVICE_NAME);
}
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
26380fac4d541447d5e9ad89ac034eacaf6e4e22 | d56bffd063387761c3d5ed91b30ed6cb36833a66 | /src/main/java/com/shoe/calculator/operators/Times.java | 819764a8facc0ecbb14b0d4d8769b3884534a7b8 | [] | no_license | schuchert/lambda_jug | 50e7307dfea91f0b23df981c2a0a36e406c568c7 | a063a0ce3829377c0e36c065beef848f8c804107 | refs/heads/master | 2021-01-19T18:10:28.306952 | 2014-11-16T17:48:46 | 2014-11-16T17:48:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 282 | java | package com.shoe.calculator.operators;
import com.shoe.calculator.RpnOperator;
import static com.shoe.calculator.operators.Binary.binaryFor;
public class Times implements Registrar {
@Override
public RpnOperator get() {
return binaryFor((a, b) -> a * b);
}
}
| [
"schuchert@yahoo.com"
] | schuchert@yahoo.com |
f36754a3748f4b28faeb9911866dd4d47ea49c4d | d00a9238a9890a8ce64cc7450a34641c4977dfc1 | /src/com/hnjz/apps/base/security/model/SecurityParam.java | 79d59f79964bd1109ef355867eeb0854d4559b25 | [] | no_license | JingYj-dev/gwdataex | 2ef65abf0fabcc3de33bea5c967decbe021b1d51 | f028da4771139505086bd51e645303717da77c46 | refs/heads/master | 2022-11-22T06:48:11.860788 | 2020-07-23T09:53:34 | 2020-07-23T09:53:34 | 281,606,009 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 473 | java | package com.hnjz.apps.base.security.model;
public interface SecurityParam {
//密码强度
int PASSWORD_LEVEAL = 1;
//最大登录失败次数
int MAX_LOGIN_FAIL = 2;
//登录方式
int LOGIN_STYLE = 3;
//初始密码
int INIT_PASSWORD = 4;
//待激活密码过期时间
int OUTDATE_PASSWORD = 5;
//激活日期
int ACTIVE_TIME = 6;
//session超时
int SESSION_TIMEOUT = 7;
//下载MD5验证
int MD5_CHECK = 8;
long DEFAULT_SESSION_TIMEOUT = 600;
}
| [
"17621207907@163.com"
] | 17621207907@163.com |
8b71d33c4bf48a7e7845642daa0a13620ea8ad7c | 25210480ad47389e2ef44cef1b9123b3d3e57054 | /JavaCodeSpace/src/cn/medemede/leecode/UnhappyFriends.java | 069d95b4b38bd93acdfd06fce65b2320e1d3c586 | [] | no_license | XuCpeng/LeetCode_PTA | 393892112766039772860ba158221fd10a1a36bd | 22602deeb4d709b702e175096f677dd18429cf19 | refs/heads/master | 2023-08-27T01:20:40.377706 | 2021-10-28T14:17:44 | 2021-10-28T14:17:44 | 164,803,509 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,832 | java | package cn.medemede.leecode;
/**
* 1583. 统计不开心的朋友
*/
public class UnhappyFriends {
// 官方
public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
int[][] order = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
order[i][preferences[i][j]] = j;
}
}
int[] match = new int[n];
for (int[] pair : pairs) {
int person0 = pair[0], person1 = pair[1];
match[person0] = person1;
match[person1] = person0;
}
int unhappyCount = 0;
for (int x = 0; x < n; x++) {
int y = match[x];
int index = order[x][y];
for (int i = 0; i < index; i++) {
int u = preferences[x][i];
int v = match[u];
if (order[u][x] < order[u][v]) {
unhappyCount++;
break;
}
}
}
return unhappyCount;
}
int res;
int[][] preferences;
boolean[] notHappys;
public int unhappyFriends2(int n, int[][] preferences, int[][] pairs) {
res = 0;
this.preferences = preferences;
notHappys = new boolean[n];
for (int[] pair : pairs) {
int x = pair[0];
int y = pair[1];
int pXToY = preferencesXToY(x, y);
int pYToX = preferencesXToY(y, x);
for (int j = 0; j < pairs.length && (!notHappys[x] || !notHappys[y]); j++) {
int u = pairs[j][0];
int v = pairs[j][1];
testX(x, u, v, pXToY);
testX(y, u, v, pYToX);
}
}
return res;
}
private void testX(int x, int u, int v, int pXToY) {
if (notHappys[x]) {
return;
}
int pXToU = preferencesXToY(x, u);
if (pXToU < pXToY) {
int pUToX = preferencesXToY(u, x);
int pUToV = preferencesXToY(u, v);
if (pUToX < pUToV) {
notHappys[x] = true;
}
}
if (!notHappys[x]) {
int pXToV = preferencesXToY(x, v);
if (pXToV < pXToY) {
int pVToX = preferencesXToY(v, x);
int pVToU = preferencesXToY(v, u);
if (pVToX < pVToU) {
notHappys[x] = true;
}
}
}
if (notHappys[x]) {
res++;
}
}
private int preferencesXToY(int x, int y) {
int pXToY = 0;
while (pXToY < preferences[x].length && preferences[x][pXToY] != y) {
pXToY++;
}
if (pXToY == preferences[x].length) {
return Integer.MAX_VALUE;
}
return pXToY;
}
}
| [
"saber3555@outlook.com"
] | saber3555@outlook.com |
d24532182cc526c4ecf49308acff9d9e63bae483 | 1baf74c028aa3b0ae5c9287b1aa76a4ec8308623 | /src/main/java/com/dream/demo/constant/OrderStatus.java | 3f8111c2463b3cf2736279687ca1dcfcef079961 | [] | no_license | jakeYin/springDemo | db82f8a24ac44c39b72df083c23252288e8cae2e | f060bfcda80654ab6b82535659c8e6e6b308b02e | refs/heads/master | 2022-06-29T18:47:23.118918 | 2019-11-10T15:18:17 | 2019-11-10T15:18:17 | 220,714,703 | 0 | 0 | null | 2022-06-21T02:12:22 | 2019-11-09T23:02:20 | Java | UTF-8 | Java | false | false | 173 | java | package com.dream.demo.constant;
public enum OrderStatus {
// 待支付,待发货,待收货,订单结束
WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
}
| [
"spring-jake@126.com"
] | spring-jake@126.com |
2b3a025a712da68b4587ce26a12bd8fabd306c31 | 55f940ef29dd476e468872a6093e10ce94f6cb78 | /src/classe/Admin2.java | 416c0cdc53cdc8514da8f3336fd73618a5d3465b | [] | no_license | monkeyinwinter/java_at_home_heritage | a85acb8e11893bfe1e45e76e475edf2b6e5d551d | ebd0eb683d9ad6e25cfc60ac0dcbb0b019c90ac5 | refs/heads/master | 2020-03-21T11:01:19.353152 | 2018-06-24T13:34:52 | 2018-06-24T13:34:52 | 138,484,514 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 286 | java | package classe;
public class Admin2 extends User {
public Admin2(String nom, String prenom) {
super(nom, prenom);
}
@Override
public String toString() {
int role = 1;
return super.toString() + " Mon niveau de droit est : " + role;
}
} | [
"descampsthibault@yahoo.fr"
] | descampsthibault@yahoo.fr |
af8e3b5be110416bd6352040f3275419c7fe2e2d | 68b13e9b68738c9d5dd4d363da96d1ccf7257863 | /尚硅谷-Java高级篇-项目/src/com/atguigu/team/view/TeamView.java | c75144c25ea2070df9e24d00690f5a5c2bce3673 | [] | no_license | ZhangHao0810/2021_Java_Interview | eeb36286c01f66e63143e28256e318aab9b1136a | b369b741f4f557b475885d63d4da4ded651c8f97 | refs/heads/master | 2023-03-23T01:55:09.105669 | 2021-03-19T08:29:35 | 2021-03-19T08:29:35 | 326,874,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,712 | java | package com.atguigu.team.view;
import com.atguigu.team.domain.Employee;
import com.atguigu.team.domain.Programmer;
import com.atguigu.team.service.NameListService;
import com.atguigu.team.service.TeamException;
import com.atguigu.team.service.TeamService;
public class TeamView {
private NameListService listSvc = new NameListService();
private TeamService teamSvc = new TeamService();
public void enterMainMenu(){
boolean loopFlag = true;
char menu = 0;
while(loopFlag){
if(menu != '1'){
listAllEmployees();
}
System.out.print("1-团队列表 2-添加团队成员 3-删除团队成员 4-退出 请选择(1-4):");
menu = TSUtility.readMenuSelection();
switch(menu){
case '1':
getTeam();
break;
case '2':
addMember();
break;
case '3':
deleteMember();
break;
case '4':
System.out.print("确认是否退出(Y/N):");
char isExit = TSUtility.readConfirmSelection();
if(isExit == 'Y'){
loopFlag = false;
}
break;
}
}
}
/**
* 显示所有的员工信息
* @Description
* @author shkstart
* @date 2019年2月12日下午3:10:07
*/
private void listAllEmployees(){
// System.out.println("显示公司所有的员工信息");
System.out.println("-------------------------------开发团队调度软件--------------------------------\n");
Employee[] employees = listSvc.getAllEmployees();
if(employees == null || employees.length == 0){
System.out.println("公司中没有任何员工信息!");
}else{
System.out.println("ID 姓名 年龄 工资 职位 状态 奖金 股票 领用设备");
for(int i = 0;i < employees.length;i++){
System.out.println(employees[i]);
}
}
System.out.println("-------------------------------------------------------------------------------");
}
private void getTeam(){
// System.out.println("查看开发团队情况");
System.out.println("--------------------团队成员列表---------------------\n");
Programmer[] team = teamSvc.getTeam();
if(team == null || team.length == 0){
System.out.println("开发团队目前没有成员!");
}else{
System.out.println("TID/ID\t姓名\t年龄\t工资\t职位\t奖金\t股票\n");
for(int i = 0;i < team.length;i++){
System.out.println(team[i].getDetailsForTeam());
}
}
System.out.println("-----------------------------------------------------");
}
private void addMember(){
// System.out.println("添加团队成员");
System.out.println("---------------------添加成员---------------------");
System.out.print("请输入要添加的员工ID:");
int id = TSUtility.readInt();
try {
Employee emp = listSvc.getEmployee(id);
teamSvc.addMember(emp);
System.out.println("添加成功");
} catch (TeamException e) {
System.out.println("添加失败,原因:" + e.getMessage());
}
//按回车键继续...
TSUtility.readReturn();
}
private void deleteMember(){
// System.out.println("删除团队成员");
System.out.println("---------------------删除成员---------------------");
System.out.print("请输入要删除员工的TID:");
int memberId = TSUtility.readInt();
System.out.print("确认是否删除(Y/N):");
char isDelete = TSUtility.readConfirmSelection();
if(isDelete == 'N'){
return;
}
try {
teamSvc.removeMember(memberId);
System.out.println("删除成功");
} catch (TeamException e) {
System.out.println("删除失败,原因:" + e.getMessage());
}
//按回车键继续...
TSUtility.readReturn();
}
public static void main(String[] args){
TeamView view = new TeamView();
view.enterMainMenu();
}
}
| [
"874993952@qq.com"
] | 874993952@qq.com |
9e965f8f87373e33dc8f8501d924dd774440684f | 69dd96401da44bd8631654fce55ba80c794ab3b4 | /deep-in-java/stage01/function-introduce/src/main/java/org/fufeng/function/SupplierDesignInfo.java | 28f98a7b503562c52ac29ba94118b3f7354d4609 | [] | no_license | LCY2013/jguid | 6867241b9bfbc40bf2c79f2920379425f9dbe724 | 39dc47d3cb7e204511efbe177facea9f041efcd8 | refs/heads/master | 2022-06-14T02:13:17.397733 | 2021-03-07T12:55:23 | 2021-03-07T12:55:23 | 225,802,714 | 2 | 1 | null | 2022-04-23T02:59:32 | 2019-12-04T07:10:27 | Java | UTF-8 | Java | false | false | 2,732 | java | /*
* The MIT License (MIT)
* ------------------------------------------------------------------
* Copyright © 2019 Ramostear.All Rights Reserved.
*
* ProjectName: jguid
* @Author : <a href="https://github.com/lcy2013">MagicLuo</a>
* @date : 2020-07-15
* @version : 1.0.0-RELEASE
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package org.fufeng.function;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* @program: jguid
* @description: {@link Supplier} 设计
* @author: <a href="https://github.com/lcy2013">MagicLuo</a>
* @create: 2020-07-15
*/
public class SupplierDesignInfo {
public static void main(String[] args) {
echo("fufeng"); //固定参数
echo(() -> {
sleep(100);
return "magic="+System.currentTimeMillis();
});
echo(SupplierDesignInfo::getMessage);
getMessage(); //及时返回数据
final Supplier<String> stringSupplier = supplyMessage();//待执行数据
System.out.println((stringSupplier.get())); //实际获取
}
private static Supplier<String> supplyMessage(){
return SupplierDesignInfo::getMessage;
}
private static String getMessage(){
sleep(500);
return "magic-"+System.currentTimeMillis();
}
private static void sleep(long millis){
try {
TimeUnit.MILLISECONDS.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void echo(String message){ // 拉模式
System.out.println(message);
}
private static void echo(Supplier<String> message){ // 推模式
System.out.println((message.get()));
}
}
| [
"15281205719@163.com"
] | 15281205719@163.com |
e9311bcf64ecf2dc22ec5b4eb8c0f4eaa56236ca | 161c1c93850003bf8328d75defd56d1182f1b067 | /DesignPattern/TD-01/src/fr/uge/poo/paint/rapport/ducks/DuckFarm.java | f33af5c912eb2d165a12589203ce752951ab66f1 | [
"MIT"
] | permissive | Caucorico/ESIPE | 30aca7c675632611fde8b31b42d7cd2b920d49a8 | 473a40b5ac5751c5bfaddeabb81d6e7568589fa7 | refs/heads/master | 2021-06-23T17:25:45.956747 | 2020-12-12T13:11:36 | 2020-12-12T13:11:36 | 150,745,229 | 3 | 3 | MIT | 2019-04-11T16:55:13 | 2018-09-28T13:32:10 | C | UTF-8 | Java | false | false | 312 | java | package fr.uge.poo.paint.rapport.ducks;
import java.util.ServiceLoader;
public class DuckFarm {
public static void main(String[] args) {
ServiceLoader<Duck> loader = ServiceLoader.load(Duck.class);
for(Duck duck : loader) {
System.out.println(duck.quack());
}
}
}
| [
"guillaume.cau77@gmail.com"
] | guillaume.cau77@gmail.com |
35817096c27d7b3f2ac54c249382c40ced4a1c3a | 56ddea93b26c274ab5bc83519b8d3cf7f6bd28de | /src/datastructure/tree/LinkedBinTree.java | 2f17ba63597efd4719816cf0fdd78b1ecfdefdfd | [] | no_license | shensk/datastructure-java | 3fd68b9ef44033aa28f0ea9362ea305bfa711b34 | a0d03b4ca9a997b62e88335082cb99378d3f38e4 | refs/heads/master | 2021-01-19T01:33:08.489268 | 2016-06-29T13:49:53 | 2016-06-29T13:50:05 | 61,938,707 | 0 | 2 | null | null | null | null | GB18030 | Java | false | false | 2,682 | java | package datastructure.tree;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class LinkedBinTree<T> {
private TreeNode root;
private int size;
public static class TreeNode{
Object data;
TreeNode left;
TreeNode right;
TreeNode parent;
public TreeNode(Object data){
this.data = data;
}
}
public LinkedBinTree(T data){
this.root = new TreeNode(data);
size++;
}
//为指定节点添加子节点
public TreeNode add(TreeNode node,T data,boolean isLeft){
if(isLeft && node.left!=null){
throw new RuntimeException("左子节点已存在");
}
if(!isLeft && node.right!=null){
throw new RuntimeException("右子节点已存在");
}
TreeNode newnode = new TreeNode(data);
newnode.parent = node;
if(isLeft){
node.left = newnode;
}else{
node.right = newnode;
}
size++;
return newnode;
}
public boolean isEmpty(){
return root==null;
}
public TreeNode getRoot(){
return root;
}
//返回指定节点的父节点(非根节点)
public T parent(TreeNode child){
return (T) child.parent.data;
}
//返回指定节点的左子节点(非叶子节点)
public T leftNode(TreeNode parent){
return (T) parent.left.data;
}
//返回指定节点的右子节点(非叶子节点)
public T rightNode(TreeNode parent){
return (T) parent.right.data;
}
//返回深度
public int deep(){
return deep(root);
}
private int deep(TreeNode node) {
if(node==null){
return 0;
}
if(node.left==null && node.right==null){
return 1;
}
else{
int leftdeep = deep(node.left);
int rightdeep = deep(node.right);
int max = leftdeep > rightdeep ? leftdeep : rightdeep;
return max+1;
}
}
//深度优先遍历-前序遍历
public List<TreeNode> perIterator(){
return perIterator(root);
}
public List<TreeNode> perIterator(TreeNode node){
List<TreeNode> list = new ArrayList<LinkedBinTree.TreeNode>();
list.add(node);
if(node.left!=null){
list.addAll(perIterator(node.left));
}
if(node.right!=null){
list.addAll(perIterator(node.right));
}
return list;
}
public List<TreeNode> breadthFirst(){
return breadthFirst(root);
}
//广度优先遍历
public List<TreeNode> breadthFirst(TreeNode node){
List<TreeNode> list = new ArrayList<LinkedBinTree.TreeNode>();
Queue<TreeNode> queue = new ArrayDeque<LinkedBinTree.TreeNode>();
queue.add(node);
while(!queue.isEmpty()){
list.add(queue.peek());
TreeNode treenode = queue.poll();
if(treenode.left !=null){
queue.add(treenode.left);
}
if(treenode.right !=null){
queue.add(treenode.right);
}
}
return list;
}
}
| [
"164463450@qq.com"
] | 164463450@qq.com |
968036ea939d403a546445d41d360299ce10cc54 | b5ba81d0395afc2bd02e3272855b488516dd1799 | /src/main/java/com/test/sort/QuickSort2222.java | 04c723c85cd0d4f5717cf181b848c55600e1badb | [] | no_license | chirvin/complex | 50a113ab73ee07eb0fc392811de4f525848719a7 | ef842e7acd7e840fa86fd5dfc83b52016b0b7d43 | refs/heads/main | 2023-03-22T16:16:20.794916 | 2021-03-01T07:37:00 | 2021-03-01T07:37:00 | 343,309,847 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,425 | java | package com.test.sort;
import java.util.Arrays;
/**
* @author scc
* @date 2020/7/13 17:01
*/
public class QuickSort2222 {
public static void main(String[] args) {
int[] arr = new int[]{5, 8, 6, 3, 9, 1, 2, 7};
quickSort(arr, 0, arr.length -1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int startIndex, int endIndex) {
if (startIndex < endIndex) {
// 获取基准元素索引
int pivotIndex = partition(arr,startIndex,endIndex);
// 分治法
quickSort(arr,startIndex,pivotIndex - 1);
quickSort(arr,pivotIndex + 1,endIndex);
}
}
public static int partition(int[] arr, int startIndex, int endIndex) {
int pivot = arr[startIndex];
int left = startIndex;
int right = endIndex;
while (left != right) {
while (left < right && arr[right] > pivot) {
right--;
}
while (left < right && arr[left] <= pivot) {
left++;
}
if (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
// pivot和重合点left交换
int temp = arr[startIndex];
arr[startIndex] = arr[left];
arr[left] = temp;
return left;
}
}
| [
"congcong.sang@huifu.com"
] | congcong.sang@huifu.com |
949c64b38c000d5b1e79ab9dd7f465d21defea03 | 9453468672a391bd95a4205c8dd20f91f31d61b7 | /framtest-front/src/main/java/com/jinkme/framtest/front/web/filter/XssHttpServletRequestWraper.java | 86d94a3893c6ed7019a10679032d01c4ecd6e2c3 | [] | no_license | xiangshangkan/framtest-aggregation | f993f2318b68eaed8ccf67ca6288c95713714aec | 754a727650765c0cb54ca499e4b2a8f958703d44 | refs/heads/master | 2022-12-21T20:15:23.257291 | 2019-07-01T08:05:07 | 2019-07-01T08:05:07 | 172,715,064 | 0 | 0 | null | 2022-12-16T06:11:49 | 2019-02-26T13:17:55 | Java | UTF-8 | Java | false | false | 1,384 | java | package com.jinkme.framtest.front.web.filter;
import org.apache.commons.lang3.StringEscapeUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @ClassName XssHttpServletRequestWraper
* @Description Xss脚本转换器
* @Author zhouhui
* @Date 2019/6/24 09:18
* @Version 1.0
*/
public class XssHttpServletRequestWraper extends HttpServletRequestWrapper {
public XssHttpServletRequestWraper(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String name) {
return StringEscapeUtils.escapeHtml4(super.getHeader(name));
}
@Override
public String getQueryString() {
return StringEscapeUtils.escapeHtml4(super.getQueryString());
}
@Override
public String getParameter(String name) {
return StringEscapeUtils.escapeHtml4(super.getParameter(name));
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if(values != null) {
int length = values.length;
String[] escapeValues = new String[length];
for(int i = 0; i < length; i++) {
escapeValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
}
return escapeValues;
}
return values;
}
}
| [
"1940627783@qq.com"
] | 1940627783@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.