blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
93fae375f2ad41b96b7ff6d54426acd3da3f9ce3 | Java | therealsanchit/Rutgers-Software-Methodology | /Photo Album Android App/app/src/main/java/com/example/sanchitsharma/photoalbum/DisplayActivity.java | UTF-8 | 9,730 | 2.171875 | 2 | [] | no_license | package com.example.sanchitsharma.photoalbum;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import io.DataIO;
import photo.Album;
import photo.Photo;
import photo.Tag;
import usr.User;
public class DisplayActivity extends AppCompatActivity {
User u;
int albumIndex;
int photoIndex;
Album currentAlbum;
Photo currentPhoto;
final Context context = this;
ListView tag_list_view;
Display_Adapter display_adapter;
ArrayList<Tag> currentTags;
private Button addtagButton;
private Button removetagButton;
private Button leftButton;
private Button rightButton;
private Button closeButton;
ImageView image_display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
addtagButton = (Button) findViewById(R.id.addTag);
removetagButton = (Button) findViewById(R.id.removeTag);
leftButton = (Button) findViewById(R.id.leftPhoto);
rightButton = (Button) findViewById(R.id.rightPhoto);
closeButton = (Button) findViewById(R.id.close);
u = (User)getIntent().getSerializableExtra(this.getString(R.string.User_Info));
albumIndex = getIntent().getIntExtra(this.getString(R.string.Album_Index), 0);
photoIndex = getIntent().getIntExtra(this.getString(R.string.Photo_Index), 0);
if(albumIndex >= 0)
currentAlbum = u.getAlbum(albumIndex);
else
currentAlbum = (Album)getIntent().getSerializableExtra(this.getString(R.string.Album_Info));
currentPhoto = currentAlbum.getPhoto(photoIndex);
Toast.makeText(DisplayActivity.this, currentPhoto.name, Toast.LENGTH_SHORT).show();
currentTags = new ArrayList<Tag>();
currentTags.addAll(currentPhoto.tags);
display_adapter = new Display_Adapter(this, currentTags);
tag_list_view = (ListView) findViewById(R.id.tagView);
tag_list_view.setAdapter(display_adapter);
image_display = (ImageView)findViewById(R.id.image_display);
int draw = context.getResources().getIdentifier(currentPhoto.path, "drawable", context.getPackageName());
image_display.setImageResource(draw);
addtagButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
final Spinner tag_type = new Spinner(context);
tag_type.setAdapter(new ArrayAdapter<Tag.Type>(context, android.R.layout.simple_spinner_item, Tag.Type.values()));
final EditText tag_value = new EditText(context);
tag_value.setHint("Tag Value");
layout.addView(tag_type);
layout.addView(tag_value);
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Details")
.setMessage("Enter Tag Information")
.setView(layout)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Tag.Type result_type = (Tag.Type)tag_type.getSelectedItem();
String result_value = tag_value.getText().toString();
if (result_value.isEmpty() || result_type == null)
return;
Tag t = new Tag(result_type, result_value);
currentPhoto.addToTags(t);
Toast.makeText(DisplayActivity.this, "Added Tag", Toast.LENGTH_SHORT).show();
saveData();
refreshList();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(DisplayActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
removetagButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
final Spinner tag_type = new Spinner(context);
tag_type.setAdapter(new ArrayAdapter<Tag.Type>(context, android.R.layout.simple_spinner_item, Tag.Type.values()));
final EditText tag_value = new EditText(context);
tag_value.setHint("Tag Value");
layout.addView(tag_type);
layout.addView(tag_value);
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Details")
.setMessage("Delete Tag")
.setView(layout)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Tag.Type result_type = (Tag.Type)tag_type.getSelectedItem();
String result_value = tag_value.getText().toString();
if (result_value.isEmpty() || result_type == null)
return;
if(!currentPhoto.deleteFromTags(result_type, result_value)){
Toast.makeText(DisplayActivity.this, "Tag not found", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(DisplayActivity.this, "Deleted Tag", Toast.LENGTH_SHORT).show();
saveData();
refreshList();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(DisplayActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
leftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
photoIndex = --photoIndex<0? currentAlbum.photos.size()-1:photoIndex;
refreshPhoto(photoIndex);
}
});
rightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
photoIndex = ++photoIndex>=currentAlbum.photos.size()? 0:photoIndex;
refreshPhoto(photoIndex);
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
try{
Intent intent = new Intent(getApplicationContext(), GalleryActivity.class);
intent.putExtra(context.getString(R.string.User_Info), u);
intent.putExtra(context.getString(R.string.Album_Index), albumIndex);
intent.putExtra(context.getString(R.string.Album_Info), currentAlbum);
startActivity(intent);
} catch (Exception e) { Toast.makeText(DisplayActivity.this, "Cannot Open", Toast.LENGTH_SHORT).show();}
}
});
}
public void saveData(){
if(DataIO.save(context, u))
Toast.makeText(DisplayActivity.this, "Saved", Toast.LENGTH_SHORT).show();
else
Toast.makeText(DisplayActivity.this, "FAILED TO SAVE", Toast.LENGTH_LONG).show();
}
public void refreshList(){
currentTags.clear();
currentTags.addAll(currentPhoto.tags);
display_adapter.notifyDataSetChanged();
tag_list_view.setAdapter(display_adapter);
}
public void refreshPhoto(int position){
currentPhoto = currentAlbum.getPhoto(position);
image_display = (ImageView)findViewById(R.id.image_display);
int draw = context.getResources().getIdentifier(currentPhoto.path, "drawable", context.getPackageName());
image_display.setImageResource(draw);
currentTags.clear();
currentTags.addAll(currentPhoto.tags);
display_adapter.notifyDataSetChanged();
}
}
| true |
aeff00d333704b25809e6705634cfffc6dc63046 | Java | DarkEyeDragon/Hangar | /src/main/java/io/papermc/hangar/service/internal/uploads/ImageService.java | UTF-8 | 2,217 | 2.109375 | 2 | [
"MIT"
] | permissive | package io.papermc.hangar.service.internal.uploads;
import io.papermc.hangar.HangarComponent;
import io.papermc.hangar.exceptions.HangarApiException;
import io.papermc.hangar.exceptions.InternalHangarException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
@Service
public class ImageService extends HangarComponent {
private final ProjectFiles projectFiles;
@Autowired
public ImageService(ProjectFiles projectFiles) {
this.projectFiles = projectFiles;
}
public ResponseEntity<byte[]> getProjectIcon(String author, String slug) {
Path iconPath = projectFiles.getIconPath(author, slug);
if (iconPath == null) {
throw new InternalHangarException("Default to avatar url");
}
try {
byte[] lastModified = Files.getLastModifiedTime(iconPath).toString().getBytes(StandardCharsets.UTF_8);
byte[] lastModifiedHash = MessageDigest.getInstance("MD5").digest(lastModified);
String hashString = Base64.getEncoder().encodeToString(lastModifiedHash);
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS).getHeaderValue());
headers.setETag("\"" + hashString + "\"");
return ResponseEntity.ok().headers(headers).body(Files.readAllBytes(iconPath));
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new HangarApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Unable to fetch project icon");
}
}
public String getUserIcon(String author) {
return String.format(config.security.api.getAvatarUrl(), author);
}
}
| true |
bbeeec8b70c2a895d2397aaa315756ef1019fe99 | Java | Leonardomav/POO-projecto | /Funcionario.java | UTF-8 | 1,150 | 2.578125 | 3 | [] | no_license |
package projeto;
import java.io.Serializable;
import java.util.ArrayList;
public abstract class Funcionario extends Pessoa implements Serializable{
private int numeroMec;
private String categoria;
private Boolean tipo;
private ArrayList<Exame> vigilancias = new ArrayList<Exame>();
public Funcionario(int numeroMec, String categoria, String nome, String email, Boolean tipo) {
super(nome, email);
this.numeroMec = numeroMec;
this.categoria = categoria;
this.tipo = tipo;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public void imprimeExames(ArrayList<Curso> listaCursos){
}
public int getNumeroMec() {
return numeroMec;
}
public Boolean getTipo() {
return tipo;
}
public ArrayList<Exame> getVigilancias() {
return vigilancias;
}
public void addVigilancias(Exame novoExame) {
vigilancias.add(novoExame);
}
}
| true |
2f588065c97b3c43b4255cc97c6b714500f8697d | Java | stickermaker20/FlashPlayerWithAdmob | /app/src/main/java/com/prog2app/mp4videoplayer/AudioVideoListAdapter.java | UTF-8 | 17,081 | 1.773438 | 2 | [] | no_license | package com.prog2app.mp4videoplayer;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.ads.nativetemplates.NativeTemplateStyle;
import com.google.android.ads.nativetemplates.TemplateView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import androidx.annotation.NonNull;
import androidx.core.app.ShareCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class AudioVideoListAdapter extends RecyclerView.Adapter<AudioVideoListAdapter.ViewHolder> {
ArrayList<String> videosUri;
ArrayList<String> videosTitle;
ArrayList<String> videosDuration;
boolean linearLayout;
String folderName;
Activity activity;
String listType;
NativeTemplateStyle styles;
UnifiedNativeAd unifiedNativeAd;
public void setValues(ArrayList<String> videosUri, ArrayList<String> videosTitle, ArrayList<String> videosDuration, Activity activity) {
this.videosUri = videosUri;
this.videosTitle = videosTitle;
this.videosDuration = videosDuration;
this.activity = activity;
}
public void setValues(ArrayList<String> videosUri, ArrayList<String> videosTitle, ArrayList<String> videosDuration, Activity activity, NativeTemplateStyle styles, UnifiedNativeAd unifiedNativeAd) {
this.videosUri = videosUri;
this.videosTitle = videosTitle;
this.videosDuration = videosDuration;
this.activity = activity;
this.styles = styles;
this.unifiedNativeAd = unifiedNativeAd;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = null;
if (viewType == 1) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.native_ad_layout, parent, false);
return new NativeAdViewHolder(view);
} else if (viewType == 2) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.banner_ad_layout, parent, false);
return new BannerAdViewHolder(view);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(linearLayout ? R.layout.audio_video_list_item : R.layout.grid_audio_video_list_items, parent, false);
return new ViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
if (getItemViewType(position) == 1) {
NativeAdViewHolder new_holder = (NativeAdViewHolder) holder;
new_holder.template.setStyles(styles);
new_holder.template.setNativeAd(unifiedNativeAd);
} else if (getItemViewType(position) == 2) {
BannerAdViewHolder banner_new_holder = (BannerAdViewHolder) holder;
banner_new_holder.mAdView.loadAd(new AdRequest.Builder().build());
} else {
try {
holder.videoName.setText(videosTitle.get(position));
holder.videoDescription.setText(getTimeString(Integer.parseInt(videosDuration.get(position))));
if (listType.equals("video")) {
Glide.with(activity).asBitmap().load(new File(videosUri.get(position)))
.centerCrop().into(holder.imageView);
} else {
Uri imgUri = getAudioAlbumImageContentUri(activity, videosUri.get(position));
if (imgUri.toString().length()<2) {
Glide.with(activity).load(activity.getResources().getIdentifier("logo", "drawable", activity.getPackageName()))
.centerInside().into(holder.imageView);
} else {
Glide.with(activity).asBitmap().load(imgUri)
.centerCrop().into(holder.imageView);
}
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity, ViewVideo.class);
intent.putStringArrayListExtra("VideoUri", videosUri);
intent.putStringArrayListExtra("VideoTitle", videosTitle);
intent.putExtra("VideoPosition", position);
if (listType.equals("audio")) {
intent.putExtra("ListType", listType);
} else {
intent.putExtra("ListType", listType);
}
if (styles != null) {
intent.putExtra("AdsLoaded", "Yes");
} else {
intent.putExtra("AdsLoaded", "No");
}
activity.startActivity(intent);
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveWhatsAppVideo(videosTitle.get(position),videosUri.get(position));
}
});
holder.moreOptions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(activity, holder.moreOptions);
//inflating menu from xml resource
popup.inflate(R.menu.video_list_item_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.delete: {
try {
deleteVideo(videosUri.get(position));
recreateActivity();
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case R.id.share: {
File videoFile = new File(videosUri.get(position));
Uri videoURI = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
? FileProvider.getUriForFile(activity, activity.getPackageName(), videoFile)
: Uri.fromFile(videoFile);
ShareCompat.IntentBuilder.from(activity)
.setStream(videoURI)
.setType("video/mp4")
.setChooserTitle("Share video...")
.startChooser();
break;
}
default: {
Log.e("default", "its default ..");
}
}
return true;
}
});
//displaying the popup
popup.show();
}
});
} catch (Exception e) {
// Toast.makeText(activity,""+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
@Override
public int getItemCount() {
return videosTitle.size();
}
@Override
public int getItemViewType(int position) {
if (styles != null) {
if (videosTitle.size() <= 5) {
if (position == videosTitle.size() - 1) {
return 1;
} else {
return 0;
}
} else {
if (position == 4) {
return 1;
} else if (position == 13 || position == 22 || position == 31 || position == 40 || position == 49) {
return 2;
} else {
return 0;
}
}
} else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView, moreOptions;
Button save;
RelativeLayout relativeLayout;
TextView videoName, videoDescription;
public ViewHolder(@NonNull View itemView) {
super(itemView);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.relativeLayout);
imageView = (ImageView) itemView.findViewById(R.id.videoThumbnail);
save = (Button) itemView.findViewById(R.id.save);
videoName = (TextView) itemView.findViewById(R.id.videoName);
moreOptions = (ImageView) itemView.findViewById(R.id.moreOptions);
if (folderName.contains("Status of WhatsApp Play Folder") && moreOptions != null) {
moreOptions.setVisibility(View.GONE);
videoName.setVisibility(View.GONE);
if(folderName.equals("Seen Status of WhatsApp Play Folder")) {
save.setVisibility(View.VISIBLE);
}else{
moreOptions.setVisibility(View.VISIBLE);
videoName.setVisibility(View.VISIBLE);
}
}
videoDescription = (TextView) itemView.findViewById(R.id.videoDescription);
}
}
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = (int) (millis / (1000 * 60 * 60));
int minutes = (int) ((millis % (1000 * 60 * 60)) / (1000 * 60));
int seconds = (int) (((millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000);
if (hours != 0) {
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
} else {
buf
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
}
return buf.toString();
}
public class NativeAdViewHolder extends ViewHolder {
TemplateView template;
public NativeAdViewHolder(@NonNull View itemView) {
super(itemView);
template = itemView.findViewById(R.id.my_template);
}
}
public class BannerAdViewHolder extends ViewHolder {
AdView mAdView;
public BannerAdViewHolder(@NonNull View itemView) {
super(itemView);
mAdView = itemView.findViewById(R.id.adView);
}
}
public void setLayout(boolean newValue) {
linearLayout = newValue;
}
public void deleteVideo(String mFilePath) {
File file = new File(mFilePath);
if (file.exists()) {
if (file.delete()) {
Log.e("-->", "file Deleted :" + mFilePath);
callBroadCast();
} else {
Log.e("-->", "file not Deleted :" + mFilePath);
}
}
//callBroadCast();
callScanItent(activity, mFilePath);
}
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
Log.e("-->", " >= 14");
MediaScannerConnection.scanFile(activity, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
}
}
public void callScanItent(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[]{path}, null, null);
}
public void recreateActivity() {
if(!folderName.contains("Status of WhatsApp Play Folder")) {
activity.finish();
Intent intent = new Intent(activity, AudioVideoList.class);
intent.putExtra("FolderName", folderName);
intent.putExtra("ListType", listType);
Toast.makeText(activity, "Video Deleted Successfully", Toast.LENGTH_LONG).show();
activity.startActivity(intent);
}else{
activity.finish();
activity.startActivity(new Intent(activity,WhatsappVideoList.class));
Toast.makeText(activity, "Video Deleted Successfully", Toast.LENGTH_LONG).show();
}
}
public void setFolderName(String name) {
folderName = name;
}
public void setListType(String listType) {
this.listType = listType;
}
public Uri getAudioAlbumImageContentUri(Context context, String filePath) {
final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String[] cursor_cols = { MediaStore.Audio.Media.ALBUM_ID };
final String where = MediaStore.Audio.Media.IS_MUSIC + "=1 AND " + MediaStore.Audio.Media.DATA + " = '"
+ filePath + "'";
final Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, cursor_cols, where, null, null);
/*
* If the cusor count is greater than 0 then parse the data and get the art id.
*/
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
Long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
cursor.close();
return albumArtUri;
}
return Uri.EMPTY;
}
public void saveWhatsAppVideo(String videoName,String videoPath) {
File myDirectory = new File(Environment.getExternalStorageDirectory(), "Play/WhatsApp Status Download");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
File sourceLocation = new File(videoPath);
File targetLocation = new File(Environment.getExternalStorageDirectory().toString() + "/Play/WhatsApp Status Download/"+videoName);
if (sourceLocation.exists()) {
try {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Toast.makeText(activity, "Status Saved Successfully, Swipe Left and Refresh List", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(activity, ""+e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(activity, "Failed to save, please try again", Toast.LENGTH_LONG).show();
}
}
}
| true |
56a78efa98d50087a61d2344ca3e8f64b31414f3 | Java | jangrott/algs | /src/main/java/pl/jangrot/algs/DeleteAtHead.java | UTF-8 | 426 | 3 | 3 | [] | no_license | package pl.jangrot.algs;
public class DeleteAtHead {
/*
Given a singly-linked list, write a method to delete the first node of the list and return the new head.
*/
public static ListNode deleteAtHead(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode t = head.next;
head.next = null;
head = t;
return head;
}
}
| true |
57f3fc2422c2e247c890a2bc8c2122b3ba46e53d | Java | swaroop-reddy/SpringBootRestAPI | /src/main/java/com/swaroop/SpringBootRestAPI/controller/ViewController.java | UTF-8 | 379 | 1.859375 | 2 | [] | no_license | package com.swaroop.SpringBootRestAPI.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class ViewController {
@RequestMapping("/home")
public ModelAndView home() {
return new ModelAndView("index");
}
}
| true |
691a975390fd1583641d8f014dcbe861e5a6ad1f | Java | Amoghmule/RailEnquiryApp | /src/main/java/com/rail/repository/RouteRepository.java | UTF-8 | 739 | 2.03125 | 2 | [] | no_license | package com.rail.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import com.rail.entity.RouteEntity;
public interface RouteRepository extends JpaRepository<RouteEntity, Integer>{
List<RouteEntity> findBySourceAndDestination(String source,String destination);
@Transactional(readOnly = false)
@Modifying(clearAutomatically = true)
@Query("update RouteEntity r SET source=?1 ,destination=?2 WHERE r.routeId=?3")
void updateSourceAndDestination(String source,String destination,Integer routeId );
}
| true |
45e9b0b1476db5df810bcad0b48b2dc4e75edc12 | Java | susom/biocatalyst | /src/proxy/src/main/java/edu/stanford/biosearch/data/elasticsearch/Util.java | UTF-8 | 9,365 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package edu.stanford.biosearch.data.elasticsearch;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class Util {
private static final String RANGE = "range";
private static final String MATCH = "match";
private static final String NOT_MATCH = "must_not";
private static final String PREFIX = "prefix";
private static final String WILDCARD = "wildcard";
private static final String REGEXP = "regexp";
private static final String EXISTS = "exists";
public JSONArray elasticFilter = new JSONArray();
public JSONArray elasticMustNot = new JSONArray();
public JSONArray elasticFilterDis_Max = new JSONArray();
public JSONArray elasticMustNotDis_Max = new JSONArray();
public Util() {
}
public JSONArray ElasticFilter() {
if (elasticFilterDis_Max.length() > 0) {
elasticFilter.put(new JSONObject().put("dis_max", new JSONObject().put("queries", elasticFilterDis_Max)));
}
return elasticFilter;
}
public JSONArray ElasticMustNot() {
if (elasticMustNotDis_Max.length() > 0) {
elasticMustNot.put(new JSONObject().put("dis_max", new JSONObject().put("queries", elasticMustNotDis_Max)));
}
return elasticMustNot;
}
public void ProcessFilters(List<Object> filters) {
if (filters == null) {
return;
}
if (filters.size() <= 0) {
return;
}
for (Object obj : filters) {
ProcessFilter((Map<String, Object>) obj);
}
}
public void ProcessFilter(Map<String, Object> filter) {
// FilterValues are the top one
// FilterValue are the entries in the search bar
String field = (String) filter.get("dataField");
String dataType = (String) filter.get("dataType");
Object filterValues = filter.get("filterValues");
Object filterValue = filter.get("filterValue");
String selectedFilterOperation = (String) filter.get("selectedFilterOperation");
Object sortOrder = filter.get("sortOrder");
Object sortIndex = filter.get("sortIndex");
// Sanity Check
// In this case don't create a filter
if (filterValue == null && filterValues == null) {
return;
}
//
String queryType = this.QueryType(selectedFilterOperation);
// Process FilterValue
if (filterValue != null) {
if (filterValue instanceof ArrayList) {
// If it's a Match
if (queryType == Util.MATCH) {
((ArrayList<Object>) filterValue).forEach(value -> {
this.ConvertDevExtremeFiltersToElasticFiltersHelper(field, dataType, queryType,
String.valueOf(value), selectedFilterOperation);
});
}
if (queryType == Util.RANGE) {
this.ConvertDevExtremeFiltersToElasticFiltersHelper(field, dataType, queryType,
String.valueOf(((ArrayList) filterValue).get(0)),
String.valueOf(((ArrayList) filterValue).get(1)), selectedFilterOperation, false);
}
} else {
this.ConvertDevExtremeFiltersToElasticFiltersHelper(field, dataType, queryType,
String.valueOf(filterValue), selectedFilterOperation);
}
}
// Process filterValues
if (filterValues != null) {
if (filterValues instanceof ArrayList) {
((ArrayList<Object>) filterValues).forEach(value -> {
String curatedValue = (value == null) ? null : String.valueOf(value);
this.ConvertDevExtremeFiltersToElasticFiltersHelper(field, dataType, Util.MATCH, curatedValue,
"=", true);
});
}
}
}
private void ConvertDevExtremeFiltersToElasticFiltersHelper(String Field, String DataType, String QueryType,
String Value, String Operator) {
this.ConvertDevExtremeFiltersToElasticFiltersHelper(Field, DataType, QueryType, Value, null, Operator, false);
}
private void ConvertDevExtremeFiltersToElasticFiltersHelper(String Field, String DataType, String QueryType,
String Value, String Operator, boolean Dis_Max) {
this.ConvertDevExtremeFiltersToElasticFiltersHelper(Field, DataType, QueryType, Value, null, Operator, Dis_Max);
}
private void ConvertDevExtremeFiltersToElasticFiltersHelper(String Field, String DataType, String QueryType,
String Value, String Value2, String Operator, boolean Dis_Max) {
JSONObject conversion = new JSONObject();
// Check if we are search for a match null value. If so we need a special case
// for this.
if (QueryType == Util.MATCH && Value == null) {
conversion = this.CreateExistQuery(Field);
if (Dis_Max) {
JSONObject booleanContext = new JSONObject().put("bool",
new JSONObject().put("must_not", new JSONArray().put(conversion)));
this.elasticFilterDis_Max.put(booleanContext);
} else {
this.elasticMustNot.put(conversion);
}
return;
}
// Create Json
switch (QueryType) {
case Util.MATCH:
conversion = this.CreateMatchQuery(Field, Value, DataType, Operator);
if (Dis_Max) {
this.elasticFilterDis_Max.put(conversion);
} else {
this.elasticFilter.put(conversion);
}
break;
case Util.NOT_MATCH:
conversion = this.CreateMatchQuery(Field, Value, DataType, Operator);
if (Dis_Max) {
this.elasticMustNotDis_Max.put(conversion);
} else {
this.elasticMustNot.put(conversion);
}
break;
case Util.RANGE:
conversion = this.CreateRangeQuery(Field, Operator, Value, Value2);
if (Dis_Max) {
this.elasticFilterDis_Max.put(conversion);
} else {
this.elasticFilter.put(conversion);
}
break;
default:
break;
}
}
private JSONObject CreateRangeQuery(String Field, String Operator, String Value, String Value2) {
JSONObject rangeQuery = new JSONObject();
if (Operator.equals("between")) {
rangeQuery.put(Util.RANGE,
new JSONObject().put(Field, new JSONObject().put("gte", Value).put("lt", Value2)));
return rangeQuery;
}
// Determine Elastic Operator
String elasticOperator = Util.ConvertRangeOperatorToElasticOperator(Operator);
rangeQuery.put(Util.RANGE, new JSONObject().put(Field, new JSONObject().put(elasticOperator, Value)));
return rangeQuery;
}
private JSONObject CreateMatchQuery(String Field, String Value, String DataType, String Operator) {
JSONObject matchQuery = new JSONObject();
// Behave Slightlty Differently based on Data Type.
if (DataType != null) {
if (DataType.equals("string")) {
if (Operator != null) {
switch (Operator) {
case "contains":
matchQuery.put(Util.MATCH, new JSONObject().put(Field, ".*" + Value + ".*"));
break;
case "notcontains":
matchQuery.put(Util.REGEXP,
new JSONObject().put(Field.concat(".raw"), ".*" + Value + ".*"));
break;
case "startswith":
matchQuery.put(Util.PREFIX, new JSONObject().put(Field.concat(".raw"), Value));
break;
case "endswith":
matchQuery.put(Util.REGEXP, new JSONObject().put(Field.concat(".raw"), ".*" + Value));
break;
case "=":
matchQuery.put(Util.MATCH, new JSONObject().put(Field.concat(".raw"), Value));
break;
case "<>":
matchQuery.put(Util.MATCH, new JSONObject().put(Field.concat(".raw"), Value));
break;
default:
matchQuery.put(Util.MATCH, new JSONObject().put(Field, Value)); // Default Value
break;
}
return matchQuery;
}
}
}
matchQuery.put(Util.MATCH, new JSONObject().put(Field, Value)); // Default Value
return matchQuery;
}
private JSONObject CreateExistQuery(String Field) {
return new JSONObject().put(Util.EXISTS, new JSONObject().put("field", Field));
}
private String QueryType(String operator) {
String result = Util.MATCH;
if (operator == null) {
return result;
}
switch (operator) {
case "contains":
case "startswith":
case "endswith":
case "=":
result = Util.MATCH;
break;
case "notcontains":
case "<>":// => This is "Not Equal"
result = Util.NOT_MATCH;
break;
case "<":
case ">":
case "<=":
case ">=":
case "between":
result = Util.RANGE;
break; // => not sure about this
default:
result = Util.MATCH;
break;
}
return result;
}
private static String ConvertRangeOperatorToElasticOperator(String operator) {
String result = null;
switch (operator) {
case "<":
result = "lt";
break;
case ">":
result = "gt";
break;
case "<=":
result = "lte";
break;
case ">=":
result = "gte";
break;
default:
break;
}
return result;
}
}
| true |
80f2e03e2af0d20e7168c325ef580a6f1e31850e | Java | toeich/datahub | /de.jworks.datahub.client/src/de/jworks/datahub/transform/editors/transformation/editparts/TransformEditPartFactory.java | UTF-8 | 2,068 | 2.046875 | 2 | [] | no_license | package de.jworks.datahub.transform.editors.transformation.editparts;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import de.jworks.datahub.business.transform.entity.Constant;
import de.jworks.datahub.business.transform.entity.Datasink;
import de.jworks.datahub.business.transform.entity.Datasource;
import de.jworks.datahub.business.transform.entity.Filter;
import de.jworks.datahub.business.transform.entity.Function;
import de.jworks.datahub.business.transform.entity.Link;
import de.jworks.datahub.business.transform.entity.Lookup;
import de.jworks.datahub.business.transform.entity.Operation;
import de.jworks.datahub.business.transform.entity.Transformation;
import de.jworks.datahub.business.transform.entity.TransformationDefinition;
public class TransformEditPartFactory implements EditPartFactory {
private Transformation transformation;
public TransformEditPartFactory(Transformation transformation) {
this.transformation = transformation;
}
@Override
public EditPart createEditPart(EditPart context, Object model) {
if (model instanceof TransformationDefinition) {
return new TransformationDefinitionEditPart((TransformationDefinition) model, transformation);
}
if (model instanceof Datasource) {
return new DatasourceEditPart((Datasource) model, transformation);
}
if (model instanceof Datasink) {
return new DatasinkEditPart((Datasink) model, transformation);
}
if (model instanceof Constant) {
return new ConstantEditPart((Constant) model, transformation);
}
if (model instanceof Function) {
return new FunctionEditPart((Function) model, transformation);
}
if (model instanceof Operation) {
return new OperationEditPart((Operation) model, transformation);
}
if (model instanceof Filter) {
return new FilterEditPart((Filter) model, transformation);
}
if (model instanceof Lookup) {
return new LookupEditPart((Lookup) model, transformation);
}
if (model instanceof Link) {
return new LinkEditPart((Link) model, transformation);
}
return null;
}
} | true |
696fb33f0779a95e765d48e9cec9e2154873a6eb | Java | chaeni96/Study_7 | /src/com/iu/c1/string/StringMain3.java | UTF-8 | 549 | 3.359375 | 3 | [] | no_license | package com.iu.c1.string;
public class StringMain3 {
public static void main(String[] args) {
String name = "Hello World";
char ch = 'o';
//'o' 문자가 몇개 있습니까?
boolean check = true;
int num = 0;
int count = 0;
while(check) {
num = name.indexOf(ch, num);
if(num>0) {
num = num+1;
count = count+1;
}else {
System.out.println("검색이 종료됩니다");
break;
}
}
System.out.println(ch+"는 총"+count + "개 있습니다");
name = "";
name = new String();
}
}
| true |
2049985249d93efefa864a4fd48aebe4e6846980 | Java | abhi9885/ZuoraAdapter | /ZuoraAdapter/src/com/cognizant/ipm/adapter/runtime/parser/OperationResponse.java | UTF-8 | 260 | 1.507813 | 2 | [] | no_license | package com.cognizant.ipm.adapter.runtime.parser;
import java.util.List;
public abstract interface OperationResponse
extends MetadataNode
{
public abstract DataObjectNode getResponseObject();
public abstract List<CloudHeader> getResponseHeaders();
} | true |
61b7a76b644422e10e4c77d2654f89b6686b4c97 | Java | stivenson/programas-java | /Programas-java-por-consola/Programas-Segundo-semestre/Recorrido_Matriz_En_Verticales_2.java | UTF-8 | 945 | 3.0625 | 3 | [] | no_license |
public class Recorrido_Matriz_En_Verticales_2 {
public static void main(String[] args) {
int M[][]=new int[4][4];
llenarMatriz(M);
ImprimirMatriz(M);
System.out.print("Recorrido: ");
for(int a=3;a>-1;a--)
{
if(!(a%2==0))
for(int e=3;e>-1;e--)
System.out.print(M[e][a]+"\t");
else
for(int e=0;e<4;e++)
System.out.print(M[e][a]+"\t");
}
}
////metodos////
private static void llenarMatriz(int M[][]){
for(int b=0;b<M.length;b++)
for(int c=0;c<M[0].length;c++)
{
System.out.print("valor Matriz [ "+b+" ][ "+c+" ] = ");
M[b][c]=Leer.leerint();
}
}
private static void ImprimirMatriz(int M[][]){
for(int b=0;b<M.length;b++){
for(int c=0;c<M[0].length;c++)
System.out.print(M[b][c]+"\t");
System.out.print("\n");
}
}
}
| true |
3355865d6b791e09439b5ae2243d57673a530297 | Java | clairejaja/project-euler | /src/main/java/problem12/HighlyDivisibleTriangularNumber.java | UTF-8 | 2,085 | 4.25 | 4 | [
"MIT"
] | permissive | import java.util.*; // for ArrayList
/**
* @author Claire Jaja
* @version 9/16/14
*
* Project Euler Problem 12
* The sequence of triangle numbers is generated by adding the natural numbers.
* So the 7th triangle number would be 1+2+3+4+5+6+7 = 28.
* The first ten terms would be: 1,3,6,10,15,21,28,36,45,55, ...
* Let us list the factors of the first seven triangle numbers:
* 1: 1
* 3: 1,3
* 6: 1,2,3,6
* 10: 1,2,5,10
* 15: 1,3,5,15
* 21: 1,3,7,21
* 28: 1,2,4,7,14,28
* We can see that 28 is the first triangle number to have over five divisors.
* What is the value of the first triangle number to have over 500 divisors?
*/
public class HighlyDivisibleTriangularNumber
{
public static void main(String[] args) {
// argument is the number of divisors we're looking for
int divisors = 5; // if no arguments, use 5
if (args.length > 0) {
try {
divisors = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
}
boolean numberFound = false;
int n = 1;
while (!numberFound) {
n += 1;
// the number of divisors for the nth triangle number
// is equal to # of divisors of n * # of divisors of (n+1)/2
int numberDivisors = countDivisors(n);
if (n % 2 == 0) {
numberDivisors *= 1;
} else {
numberDivisors *= countDivisors((n+1)/2);
}
if (numberDivisors >= divisors) {
numberFound = true;
}
}
int triangleNumber = 0;
for (int i = 1; i <= n; i++) {
triangleNumber += i;
}
System.out.println(triangleNumber);
}
public static int countDivisors(int num) {
int numberDivisors = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
numberDivisors++;
}
}
return numberDivisors;
}
}
| true |
9f79fb1a6faba26e15a0344fbd9dc4fd38ab3ec6 | Java | HideoKojimaGod/TestBackend | /src/test/java/api/mal/services/DatasetsService.java | UTF-8 | 1,137 | 2.265625 | 2 | [] | no_license | package api.mal.services;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import api.mal.builders.DatasetRequestBuilder;
import api.mal.models.*;
import java.util.Properties;
public class DatasetsService extends BaseService{
public DatasetsService(Properties properties) {
super(properties);
}
public DatasetRequestBuilder request() {
return new DatasetRequestBuilder(baseRequest());
}
public DatasetLocationModel[] executeForLocation(RequestSpecification requestSpecification, String path) {
return requestSpecification.post(path).then()
.extract()
.body().as(DatasetLocationModel[].class);
}
public DatasetDescriptionModel executeForDescription(RequestSpecification requestSpecification, String path) {
return requestSpecification.post(path).then()
.extract()
.body().as(DatasetDescriptionModel.class);
}
public Response executeRow(RequestSpecification requestSpecification, String path) {
return requestSpecification.post(path);
}
}
| true |
31c4969ffd1036dc3bf0c1db162eca47ccce623e | Java | whjz/WHJZ | /app/src/main/java/com/example/jh/buildings/Activity/Associated_people.java | UTF-8 | 5,778 | 1.953125 | 2 | [] | no_license | package com.example.jh.buildings.Activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.jh.buildings.Activity.MainActivity;
import com.example.jh.buildings.R;
public class Associated_people extends Activity{
private View imgBack;
//获取从MainActivity传入的数据,并为此界面的组件绑定数据
private Handler handler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
if (msg.what == 1){
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");
TextView tx_name = (TextView)findViewById(R.id.associated_name);
if (name.equals("null")){name = "";}
else {tx_name.setText(name);}
ImageView img_picture = (ImageView)findViewById(R.id.associatedperson_picture);
String picture = bundle.getString("picture");
if (picture.equals("http://202.114.41.165:8080null")){img_picture.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.nopicture));}
else {
Glide.with(getApplicationContext()).load(picture).into(img_picture);
}
//引入Glide来实现网络图片的加载
String birthday = bundle.getString("birthday");
TextView tx_birthday = (TextView)findViewById(R.id.associatedperson_birthday);
if (birthday.equals("null")){tx_birthday.setText("");}
else {tx_birthday.setText(birthday);}
String sex = bundle.getString("sex");
TextView tx_sex = (TextView)findViewById(R.id.associatedperson_sex);
if (sex.equals("null")){tx_sex.setText("");}
else {tx_sex.setText(sex);}
String nativeplace = bundle.getString("nativeplace");
TextView tx_nativeplace = (TextView)findViewById(R.id.associatedperson_nativeplace);
if (nativeplace.equals("null")){tx_nativeplace.setText("");}
else {tx_nativeplace.setText(nativeplace);}
String personalprofile = bundle.getString("personalprofile");
TextView tx_personalprofile = (TextView)findViewById(R.id.associatedperson_personalprofile);
LinearLayout intro0 = (LinearLayout)findViewById(R.id.intro0);
LinearLayout intro1 = (LinearLayout)findViewById(R.id.intro1);
LinearLayout intro2 = (LinearLayout)findViewById(R.id.intro2);
if (personalprofile.equals("null")){
intro0.setVisibility(View.GONE);
intro1.setVisibility(View.GONE);
intro2.setVisibility(View.GONE);
}
else {
tx_personalprofile.setMovementMethod(LinkMovementMethod.getInstance());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
tx_personalprofile.setText(Html.fromHtml(personalprofile,Html.FROM_HTML_MODE_COMPACT));
}
else{
tx_personalprofile.setText(Html.fromHtml(personalprofile));
}
}
String relatedevents = bundle.getString("relatedevents");
TextView tx_relatedevents = (TextView)findViewById(R.id.associatedperson_relatedevents);
LinearLayout Associated_event0 = (LinearLayout)findViewById(R.id.Associated_event0);
LinearLayout Associated_event1 = (LinearLayout)findViewById(R.id.Associated_event1);
LinearLayout Associated_event2 = (LinearLayout)findViewById(R.id.Associated_event2);
if (relatedevents.equals("null")){
Associated_event0.setVisibility(View.GONE);
Associated_event1.setVisibility(View.GONE);
Associated_event2.setVisibility(View.GONE);
}
else {
tx_relatedevents.setMovementMethod(LinkMovementMethod.getInstance());
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
tx_relatedevents.setText(Html.fromHtml(relatedevents,Html.FROM_HTML_MODE_COMPACT));
}
else{
tx_relatedevents.setText(Html.fromHtml(relatedevents));
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.associated_people);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
imgBack = (LinearLayout)findViewById(R.id.people_back);
imgBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*Intent i = new Intent(Associated_people.this,MainActivity.class);
startActivity(i);*/
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
}
| true |
540ccd0eee3bea4edff70d3ab33a2f3c4d164f2e | Java | NationalSecurityAgency/datawave-spring-boot-starter | /src/main/java/datawave/microservice/http/converter/protostuff/ProtostuffHttpMessageConverter.java | UTF-8 | 3,716 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package datawave.microservice.http.converter.protostuff;
import io.protostuff.LinkedBuffer;
import io.protostuff.Message;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.NonNull;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import static org.springframework.util.Assert.state;
/**
* An {@link org.springframework.http.converter.HttpMessageConverter} that reads/writes messages that implement the Protostuff {@link Message} interface.
*/
public class ProtostuffHttpMessageConverter extends AbstractHttpMessageConverter<Message<?>> {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
public static final MediaType PROTOSTUFF = new MediaType("application", "x-protostuff", DEFAULT_CHARSET);
public static final String PROTOSTUFF_VALUE = "application/x-protostuff";
private ThreadLocal<LinkedBuffer> buffer = ThreadLocal.withInitial(() -> LinkedBuffer.allocate(4096));
public ProtostuffHttpMessageConverter() {
setSupportedMediaTypes(Collections.singletonList(PROTOSTUFF));
}
@Override
protected boolean supports(@NonNull Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
@Override
protected MediaType getDefaultContentType(Message<?> message) {
return PROTOSTUFF;
}
@Override
protected @NonNull Message<?> readInternal(@NonNull Class<? extends Message<?>> clazz, @NonNull HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
MediaType contentType = inputMessage.getHeaders().getContentType();
if (contentType == null) {
contentType = PROTOSTUFF;
}
if (PROTOSTUFF.isCompatibleWith(contentType)) {
try {
// noinspection unchecked
Message<Object> msg = (Message<Object>) clazz.newInstance();
ProtostuffIOUtil.mergeFrom(inputMessage.getBody(), msg, msg.cachedSchema(), buffer.get());
return msg;
} catch (InstantiationException | IllegalAccessException e) {
throw new HttpMessageNotReadableException("Unable to read protostuff message: " + e.getMessage(), e, inputMessage);
}
}
throw new UnsupportedOperationException("Reading protostuff messages from media types other than " + PROTOSTUFF + " is not supported.");
}
@Override
protected void writeInternal(@NonNull Message<?> message, @NonNull HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
MediaType contentType = outputMessage.getHeaders().getContentType();
if (contentType == null) {
contentType = getDefaultContentType(message);
state(contentType != null, "No content type");
}
try {
@SuppressWarnings("unchecked")
Schema<Object> schema = (Schema<Object>) message.cachedSchema();
if (PROTOSTUFF.isCompatibleWith(contentType)) {
ProtostuffIOUtil.writeTo(outputMessage.getBody(), message, schema, buffer.get());
}
} finally {
buffer.get().clear();
}
}
}
| true |
6eaa4017a464e541fde5a1f1707e274dcc21a4b9 | Java | cat20546/jsp | /src/main/java/kr/or/ddit/servlet/timesTables.java | UTF-8 | 1,523 | 2.515625 | 3 | [] | no_license | package kr.or.ddit.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class timesTables extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw = resp.getWriter();
pw.println("<!DOCTYPE html> ");
pw.println("<html> ");
pw.println("<head> ");
pw.println("<meta charset=\"UTF-8\"> ");
pw.println("<title>Insert title here</title> ");
pw.println("</head> ");
pw.println("<body> ");
pw.println("<table border=\"1\"> ");
pw.println(" <table border=\"1\" border-collapse: collapse>");
for (int i = 2; i <= 9; i++) {
pw.println("<tr>");
for (int j = 1; j <= 9; j++) {
pw.println("<td>" + i + " * " + j + " = " + i * j + "</td>");
}
pw.println("</tr>");
}
pw.println("</body> ");
pw.println("</html> ");
pw.flush();
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
| true |
9c1a0291c86a3b9392201c225abaad6a7c8eb3f3 | Java | hkris710/Java-Examples | /com/hariinc/problems/ProcessNodes.java | UTF-8 | 1,515 | 3.5625 | 4 | [] | no_license | package com.hariinc.problems;
public class ProcessNodes {
static class ProcessNode{
String task;
String name;
ProcessNode next;
ProcessNode(String task, String name){
this.task = task;
this.name = name;
}
public ProcessNode getNext() {
return next;
}
public void setNext(String task, String name) {
this.next = new ProcessNode(task, name);
}
public void printTasks() {
if (next != null) {
System.out.print(task+"->");
next.printTasks();
} else
System.out.print(task);
}
public void printNames() {
if (next != null) {
System.out.print(name+"->");
next.printNames();
} else
System.out.print(name);
}
public void printBoth() {
if (next != null) {
System.out.print(name+","+task+"->");
next.printBoth();
} else
System.out.print(name+","+task);
}
}
public static void main(String[] args) {
String[] splitList = args[0].split(";");
ProcessNode head = null;
ProcessNode next = null;
for (int i = 0; i < splitList.length; i++) {
String[] splitPair = splitList[i].split(",");
if (i == 0) {
head = new ProcessNode(splitPair[0], splitPair[1]);
}
else if (i == 1) {
head.setNext(splitPair[0], splitPair[1]);
next = head.getNext();
}
else {
next.setNext(splitPair[0], splitPair[1]);
next = next.getNext();
}
}
System.out.println("");
head.printTasks();
System.out.println("");
head.printNames();
System.out.println("");
head.printBoth();
}
}
| true |
2e1bb65711f41197f890e8c66fe9d2392aabaa1b | Java | aBreaking/master-foundation | /ads/src/main/java/com/abreaking/master/ads/leetcode/VolumeOfHistogramLcci.java | UTF-8 | 1,630 | 3.71875 | 4 | [] | no_license | package com.abreaking.master.ads.leetcode;
/**
* 面试题 17.21. 直方图的水量
* 给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。
*
*
*
* 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的直方图,在这种情况下,可以接 6 个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。
*
* 示例:
*
* 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出: 6
*
* from : https://leetcode-cn.com/problems/volume-of-histogram-lcci/
* @author liwei
* @date 2021/4/2
*/
public class VolumeOfHistogramLcci {
public static void main(String[] args) {
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
System.out.println(new Solution().trap(height));
}
static class Solution {
public int trap(int[] height) {
if (height.length<=1){
return 0;
}
int[] leftMax = new int[height.length];
int[] rightMax = new int[height.length];
leftMax[0] = height[0];
rightMax[height.length-1] = height[height.length-1];
for (int i = 1; i < height.length; i++) {
leftMax[i] = Math.max(leftMax[i-1],height[i]);
}
for (int i = height.length-2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i+1],height[i]);
}
int result = 0;
for (int i = 0; i < height.length; i++) {
result += Math.min(leftMax[i],rightMax[i])-height[i];
}
return result;
}
}
}
| true |
d8ae97dff51417ed9bd1898e882d5e590324a602 | Java | song121382/aizuji | /microservice-loverent-liquidation-common-v1/src/main/java/org/gz/liquidation/common/dto/TransactionRecordQueryReq.java | UTF-8 | 2,490 | 1.898438 | 2 | [] | no_license | package org.gz.liquidation.common.dto;
import java.util.Date;
import java.util.List;
import org.gz.common.entity.QueryPager;
import lombok.Getter;
import lombok.Setter;
/**
*
* @Description:TODO 交易流水请求参数
* Author Version Date Changes
* liaoqingji 1.0 2017年12月23日 Created
*/
public class TransactionRecordQueryReq extends QueryPager {
/**
*
*/
private static final long serialVersionUID = -4748900359307688026L;
/**
* 交易流水号
*/
private String transactionSN;
/**
* 订单号
*/
private String orderSN;
/**
* 来源类别
*/
private String sourceType;
/**
* 交易方式
*/
private String transactionWay;
/**
* 交易类型
*/
@Setter @Getter
private String transactionType;
/**
* 交易来源账户
*/
private String fromAccount;
/**
* 交易状态
*/
private String state;
/**
* 姓名
*/
private String realName;
/**
* 手机号
*/
private String phone;
/**
* 交易时间
*/
@Setter @Getter
private Date startDate;
@Setter @Getter
private Date endDate;
private List<String> orderSnList;
public String getTransactionSN() {
return transactionSN;
}
public void setTransactionSN(String transactionSN) {
this.transactionSN = transactionSN;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getTransactionWay() {
return transactionWay;
}
public void setTransactionWay(String transactionWay) {
this.transactionWay = transactionWay;
}
public String getFromAccount() {
return fromAccount;
}
public void setFromAccount(String fromAccount) {
this.fromAccount = fromAccount;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getOrderSN() {
return orderSN;
}
public void setOrderSN(String orderSN) {
this.orderSN = orderSN;
}
public List<String> getOrderSnList() {
return orderSnList;
}
public void setOrderSnList(List<String> orderSnList) {
this.orderSnList = orderSnList;
}
}
| true |
476ade6fd150a3d063374d39091673140b91d39e | Java | IFuHeng/RouterTest | /src/com/changhong/telnettool/MainMenu.java | UTF-8 | 6,235 | 2.34375 | 2 | [] | no_license | package com.changhong.telnettool;
import com.changhong.telnettool.event.MyWindowAdapter;
import com.changhong.telnettool.function.cpu.CpuToolMain;
import com.changhong.telnettool.function.other.ResetExam;
import com.changhong.telnettool.function.sta.StaListMain2;
import com.changhong.telnettool.function.test_exam.Test2p2p8;
import com.changhong.telnettool.function.test_exam.Test2p2p9;
import com.changhong.telnettool.function.test_exam.TestWan;
import com.changhong.telnettool.tool.DataManager;
import com.changhong.telnettool.tool.Tool;
import javafx.util.Pair;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.HashMap;
public class MainMenu extends Frame implements ActionListener {
private static final String ACTION_WLAN = "Wlan监视器";
private static final String ACTION_CPU_MEM = "资源监视器";
private static final String ACTION_TEST_2_2_2 = "2.2.2~2.2.4. wan口测试";
private static final String ACTION_TEST_2_2_8 = "2.2.8.连接设备已连接功能测试";
private static final String ACTION_TEST_2_2_9 = "2.2.9.路由器信息正确性测试";
private static final String ACTION_FLASH_RESET = "测试flash reset";
private static final Font FONT_DEFAULT = new Font(Font.SANS_SERIF, Font.BOLD, 35);
private static final String[] ITEMS_FUNCTION = {ACTION_WLAN, ACTION_CPU_MEM, ACTION_FLASH_RESET, ACTION_TEST_2_2_2, ACTION_TEST_2_2_8, ACTION_TEST_2_2_9,};
private HashMap<Class<? extends Frame>, Frame> mMapFrame = new HashMap();
public MainMenu() {
super("WIFI自动化工具");
MyWindowAdapter.openedWindow++;
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (GraphicsDevice g : gs) {
System.out.println(g.getDisplayMode().getWidth() + " / " + g.getDisplayMode().getHeight());
}
Pair<String, Integer> version = DataManager.getVersionInfo();
if (version != null)
setTitle("WIFI自动化工具 v" + version.getKey());
GridLayout layout = new GridLayout(ITEMS_FUNCTION.length, 1);
// GridBagLayout layout = new GridBagLayout();
// GridBagConstraints gbc = new GridBagConstraints();
setLayout(layout);
// setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// gbc.fill = GridBagConstraints.HORIZONTAL;
for (int i = 0; i < ITEMS_FUNCTION.length; i++) {
// gbc.gridy = i;
JButton button = new JButton(ITEMS_FUNCTION[i]);
button.setActionCommand(ITEMS_FUNCTION[i]);
button.setFont(FONT_DEFAULT);
button.addActionListener(this);
// layout.setConstraints(button, gbc);
add(button);
}
addWindowListener(new MyWindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
setResizable(false);
// setSize(300,160);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == ACTION_CPU_MEM) {
setFrameLocation(getFrame(CpuToolMain.class));
} else if (e.getActionCommand() == ACTION_WLAN) {
setFrameLocation(getFrame(StaListMain2.class));
} else if (e.getActionCommand() == ACTION_TEST_2_2_2) {
setFrameLocation(getFrame(TestWan.class));
} else if (e.getActionCommand() == ACTION_TEST_2_2_8) {
setFrameLocation(getFrame(Test2p2p8.class));
} else if (e.getActionCommand() == ACTION_TEST_2_2_9) {
setFrameLocation(getFrame(Test2p2p9.class));
} else if (e.getActionCommand() == ACTION_FLASH_RESET) {
setFrameLocation(getFrame(ResetExam.class));
}
}
private Frame getFrame(Class<? extends Frame> frameCls) {
MyWindowAdapter.openedWindow++;
if (mMapFrame.containsKey(frameCls)) {
return mMapFrame.get(frameCls);
} else {
try {
Frame frame = frameCls.newInstance();
mMapFrame.put(frameCls, frame);
return frame;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
private void setFrameLocation(Frame frame) {
if (!frame.isVisible())
frame.setVisible(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = 0, y = 0;
switch (MyWindowAdapter.openedWindow % 4) {
case 2:
x = screenSize.width - frame.getWidth();
break;
case 3:
x = screenSize.width - frame.getWidth();
y = screenSize.height - frame.getHeight();
break;
case 0:
y = screenSize.height - frame.getHeight();
break;
}
frame.setLocation(x, y);
// frame.setLocation(this.getLocation().x + this.getSize().width, Math.max(screenSize.height - frame.getSize().height >> 1, 0));
// frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
Tool.setGlobalFontRelative(Tool.getScreenSizeLevel());
new MainMenu();
// String string = DosCmdHelper.readDosRuntime("netsh interface ip set address name=\"以太网\" source=static addr=192.168.10.88 mask=255.255.255.0 gateway=192.168.88.1 1");
// System.out.println(string);
// string = DosCmdHelper.readDosRuntime("netsh interface ip set address name=\"以太网\" source=dhcp");
// System.out.println(string);
// while (true) {
// try {
// String deviceType = BWR510LocalConnectionHelper.getInstance().getBase_DeviceType(Tool.getGuessGateway());
// System.out.println(deviceType);
//
// Thread.sleep(2000);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
}
| true |
849360b3876ac84a2254d38691f1bb403fcfcb3d | Java | pabloherrea/Polimorfismo | /Polimorfismo/src/polimorfismo/Gato.java | UTF-8 | 604 | 2.96875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package polimorfismo;
/**
*
* @author Usuario
*/
public class Gato extends Animal{
public Gato(String nombre, String tipo_alimentación, int edad) {
super(nombre, tipo_alimentación, edad);
}
@Override
public void alimentarse() {
System.out.println("soy carnivoro");
}
@Override
public void corer() {
System.out.println("corro con cuatro patas");
}
}
| true |
f607551cc31cfe525dbdd9e6b11744e0e7cc6b63 | Java | mrprez/gencross-web | /src/main/java/com/mrprez/gencross/web/action/interceptor/VersionNumberInterceptor.java | UTF-8 | 1,443 | 2.125 | 2 | [] | no_license | package com.mrprez.gencross.web.action.interceptor;
import java.io.IOException;
import java.util.Properties;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class VersionNumberInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
private String gencrossWebVersion;
private String gencrossVersion;
@Override
public void destroy() {
;
}
@Override
public void init() {
Properties properties = new Properties();
try {
properties.load(getClass().getResourceAsStream("versions.properties"));
} catch (IOException ioe) {
throw new RuntimeException("Cannot load versions.properties file", ioe);
}
gencrossWebVersion = properties.getProperty("com.mrprez.gencross.gencross-web.version");
gencrossVersion = properties.getProperty("com.mrprez.gencross.gencross.version");
}
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
if( ! ActionContext.getContext().getApplication().containsKey("gencrossWebVersion") ){
ActionContext.getContext().getApplication().put("gencrossWebVersion", gencrossWebVersion);
}
if( ! ActionContext.getContext().getApplication().containsKey("gencrossVersion") ){
ActionContext.getContext().getApplication().put("gencrossVersion", gencrossVersion);
}
return actionInvocation.invoke();
}
}
| true |
3c1cea39dcd70f2ea21f00d694a994d1299b4a7b | Java | barchetta/helidon | /examples/microprofile/hello-world-implicit/src/test/java/io/helidon/microprofile/example/helloworld/implicit/ImplicitHelloWorldTest.java | UTF-8 | 2,185 | 1.890625 | 2 | [
"Apache-2.0",
"APSL-1.0",
"LicenseRef-scancode-protobuf",
"GPL-1.0-or-later",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"CC-PDDC",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-unicode",
"EPL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL... | permissive | /*
* Copyright (c) 2018, 2023 Oracle and/or its affiliates.
*
* 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 io.helidon.microprofile.example.helloworld.implicit;
import io.helidon.microprofile.tests.junit5.HelidonTest;
import jakarta.inject.Inject;
import jakarta.json.JsonObject;
import jakarta.ws.rs.client.WebTarget;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertAll;
/**
* Unit test for {@link HelloWorldResource}.
*/
@HelidonTest
@Disabled("3.0.0-JAKARTA") // OpenAPI: Caused by: java.lang.NoSuchMethodError:
// 'java.util.List io.smallrye.jandex.ClassInfo.unsortedFields()'
class ImplicitHelloWorldTest {
private final WebTarget target;
@Inject
ImplicitHelloWorldTest(WebTarget target) {
this.target = target;
}
@Test
void testJsonResource() {
JsonObject jsonObject = target
.path("/helloworld/unit")
.request()
.get(JsonObject.class);
assertAll("JSON fields must match expected injection values",
() -> assertThat("Name from request", jsonObject.getString("name"), is("unit")),
() -> assertThat("Request id from CDI provider", jsonObject.getInt("requestId"), is(1)),
() -> assertThat("App name from config", jsonObject.getString("appName"), is("Hello World Application")),
() -> assertThat("Logger name", jsonObject.getString("logger"), is(HelloWorldResource.class.getName()))
);
}
}
| true |
cad1b40508a124144acb8496cce5fc8921abfc67 | Java | morgworth/spring-assignment | /SpringAssignment/src/main/java/com/assignment/controller/BasicController.java | UTF-8 | 290 | 2.015625 | 2 | [] | no_license | package com.assignment.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BasicController {
@GetMapping("/something")
public String something() {
return "something";
}
}
| true |
49bf815fb1191eb5c18e6f30c4f0f71edd59ec06 | Java | eMainTec-DREAM/DREAM | /JavaSource/intf/dream/bee/finder/calibration/service/spring/BeeFinderCalibrationListServiceImpl.java | UTF-8 | 1,172 | 1.890625 | 2 | [] | no_license | package intf.dream.bee.finder.calibration.service.spring;
import java.util.List;
import java.util.Map;
import intf.dream.bee.finder.calibration.dao.BeeFinderCalibrationListDAO;
import intf.dream.bee.finder.calibration.service.BeeFinderCalibrationListService;
/**
* serviceimpl
* @author kim21017
* @version $Id: $
* @since 1.0
*
* @spring.bean id="beeFinderCalibrationListServiceTarget"
* @spring.txbn id="beeFinderCalibrationListService"
* @spring.property name="beeFinderCalibrationListDAO" ref="beeFinderCalibrationListDAO"
*/
public class BeeFinderCalibrationListServiceImpl implements BeeFinderCalibrationListService
{
private BeeFinderCalibrationListDAO beeFinderCalibrationListDAO = null;
public BeeFinderCalibrationListDAO getBeeFinderCalibrationListDAO() {
return beeFinderCalibrationListDAO;
}
public void setBeeFinderCalibrationListDAO(BeeFinderCalibrationListDAO beeFinderCalibrationListDAO) {
this.beeFinderCalibrationListDAO = beeFinderCalibrationListDAO;
}
public List findCalibrationList(Map map) throws Exception
{
return beeFinderCalibrationListDAO.findCalibrationList(map);
}
}
| true |
48c1e00e4c160149cf942a93a1df0bb7ae3aeda3 | Java | FirePower-Git/ColtExpress | /src/entities/collectible/Gem.java | UTF-8 | 678 | 3.21875 | 3 | [] | no_license | package entities.collectible;
public class Gem extends Collectible {
/**
* The constructor of the Gem object
*/
public Gem() {
super();
this.value = 500;
}
/**
* The constructor of the Gem object
* @param value the value of the collectible
*/
public Gem(int value) {
super(value);
}
/**
* function getType return the type of the item (money bag or gem)
* @return CollectibleType
*/
@Override
public Collectible.CollectibleType getType() {
return Collectible.CollectibleType.GEM;
}
/**
* Get String of the object
* @return String
*/
@Override
public String toString() {
return "Gem{" +
"value=" + this.value +
'}';
}
}
| true |
6991f1088e3ec01c7ae0c95ecd1cde898ed19078 | Java | logogin/CoursesWorks | /CompNetworks/convention/SRC-JAVA/forumreply.java | UTF-8 | 6,014 | 2.5625 | 3 | [] | no_license | import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;//for sql servers...
public class forumreply extends HttpServlet{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException{
HttpSession session = req.getSession(true);
String str=(String)session.getValue("login");
if(str!=null && str.equals("true"))
{
try {
Statement stmt,stmt_tmp;//used for database access
ResultSet resultSet,resultset_tmp;//used for database access
//Set the content type of the data to be sent back
// to the client.
res.setContentType("text/html");
//Get an output writer object to send data back to
// the client.
PrintWriter out = res.getWriter();
//Begin constructing the HTML page to send back to
// the client.
out.println("<HTML>");
out.println("<HEAD><TITLE=THE FORUM</TITLE></HEAD>");
out.println("<BODY BGCOLOR=lightskyblue>");
//Register the JDBC driver
Class.forName("org.gjt.mm.mysql.Driver");
//Construct URL for database on localhost
String url = "jdbc:mysql://localhost:3306/forum";
//Get a connection to the database: port/name of db...
Connection con = DriverManager.getConnection(url,
"", "");
//Get the incoming data parameters from the client
String name = req.getParameter("name");
String id = req.getParameter("id");
String headline = req.getParameter("headline");
String message = req.getParameter("message");
if(name!=null && headline !=null && message!=null)
if (!(name.equals("")||headline.equals("")||message.equals("")||id.equals("")))
{
//Use the statement object to execute a query on the
// database.
//Get a Statement object no user no psswd
stmt = con.createStatement();
resultSet = stmt.executeQuery(
"SELECT count(DISTINCT pid) FROM forum_msg WHERE pid='"+id+"'");
resultSet.next();
Object obj1 = resultSet.getObject(1);
int newid=Integer.parseInt(obj1.toString())+1;
stmt = con.createStatement();
//Put the data into the database table. Don't forget
// to enclose the string data in single quotes to
// satisfy the SQL syntax requirement.
stmt.executeUpdate("INSERT INTO forum_msg "
+ " VALUES('"+id+"','"//new headline= new pid...
+ newid + "','"
+ name + "','"
+ headline + "','"
+ message + "'"
+ ")");
}
//start printing the database into the html forum
//Create a statement object linked to the database
// connection.
stmt = con.createStatement();
//Use the statement object to execute a query on the
// database.
resultSet = stmt.executeQuery(
"SELECT * from forum_msg WHERE PID='0'");
out.println("<h1 ALIGN=\"CENTER\">THE FORUM</H1><BR><BR>");
//Get info about the ResultSet
ResultSetMetaData resultSetMetaData =
resultSet.getMetaData();
int numColumns = resultSetMetaData.getColumnCount();
//Start an output string that is an HTML table
StringBuffer strBuf = new StringBuffer();
//begin HTML table
strBuf.append("<hr><br>");
while(resultSet.next()) {
strBuf.append("<hr><br>");
for(int i = 1; i <= numColumns; i++){
strBuf.append("<b>");
Object obj = resultSet.getObject(i);
strBuf.append(resultSetMetaData.getColumnLabel(i)
+"--></b>"+obj.toString()+"<br>");
}//end for loop
Object obj_tmp,obj = resultSet.getObject(2);
stmt_tmp=con.createStatement();
resultset_tmp=stmt_tmp.executeQuery(
"SELECT * from forum_msg WHERE pid='"
+obj.toString()+"'");
strBuf.append("<BR><b>Replies</b>.................................................");
while(resultset_tmp.next()) {
for(int i = 1; i <= numColumns; i++){
obj_tmp=resultset_tmp.getObject(i);
strBuf.append("<br>");
strBuf.append(resultSetMetaData.getColumnLabel(i)
+"-->"+obj_tmp.toString());
}//end for loop
}//end inner while
}//end outer while
strBuf.append("<br><center><form action=/convention/servlet/forumreply method=\"post\">") ;
strBuf.append("<br><a href=/convention/forum.html><b>go to home page<b><a>");
strBuf.append("<br><b>Reply to a main message</b>");
strBuf.append("<table>"+
"<tr>" +
"<td>name</td>"+
"<td><INPUT TYPE=\"TEXT\" NAME=\"name\"><BR></td>"+
"</tr>"+
"<tr>" +
"<td>id</td>"+
"<td><INPUT TYPE=\"TEXT\" NAME=\"id\"><BR></td>"+
"</tr>"+
"<tr>"+
"<td>headline</td>"+
"<td><INPUT TYPE=\"TEXT\" NAME=\"headline\"><BR></td>"+
"</tr>"+
"<tr>"+
"<td>message</td>"+
"<td><TEXTAREA NAME=\"message\" ROWS=3 COLS=40> </TEXTAREA><BR></td>"+
"</tr>"+
"</table>"+
"<br> <INPUT TYPE=\"SUBMIT\" VALUE=\"Show Forum\">"+
"</FORM><center>");
out.println(strBuf);//send table to client
//Finish the construction of the html page
out.println("</BODY></HTML>");
con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}
else res.sendRedirect("/convention/intro.html");
}//end doGet()
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}//end class reply
| true |
edd96e7c9e03f4c620efe95936e06b7ce6760e3d | Java | FairyTale-JT/-Anti-theft-lock | /JgPushTest/app/src/main/java/com/example/hjl/jgpushtest/util/Base64Utils.java | UTF-8 | 1,232 | 2.640625 | 3 | [] | no_license | package com.example.hjl.jgpushtest.util;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
/**
* Base64加密解密
*/
public class Base64Utils {
/**
* BASE64 加密
*
* @param str
* @return
*/
public static String encryptBASE64(String str) {
if (str == null || str.length() == 0) {
return null;
}
try {
byte[] encode = str.getBytes("UTF-8");
// base64 加密
return new String(Base64.encode(encode, 0, encode.length, Base64.DEFAULT), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* BASE64 解密
*
* @param str
* @return
*/
public static String decryptBASE64(String str) {
if (str == null || str.length() == 0) {
return null;
}
try {
byte[] encode = str.getBytes("UTF-8");
// base64 解密
return new String(Base64.decode(encode, 0, encode.length, Base64.DEFAULT), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
| true |
62059c51826870bb281281bdb4baa13d850f9c64 | Java | pgujva/New_java_lesson | /sandbox/src/main/java/Zerg.java | UTF-8 | 141 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | public class Zerg {
private int age = 5;
public int getAge() {
return age;
}
public int setAge(int a) {
return age;
}
}
| true |
cfe0a21bbfddddfcc3b7f757f6db9b21eaa1f863 | Java | Unitsua/java-patterns | /factory_method_pattern/src/test/java/uiTest/App.java | UTF-8 | 1,420 | 3.015625 | 3 | [] | no_license | package uiTest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class App extends JFrame {
private JComboBox<String> cbxColors;
private JTextField txtName;
private Map<String, Color> colorMap;
public App() {
this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
colorMap = new HashMap<>();
colorMap.put("红", Color.RED);
colorMap.put("绿", Color.GREEN);
colorMap.put("蓝", Color.BLUE);
colorMap.put("黄", Color.YELLOW);
cbxColors = new JComboBox(colorMap.keySet().toArray());
cbxColors.setPreferredSize(new Dimension(50, 23));
cbxColors.addItemListener(e -> {
Color color = colorMap.get(e.getItem());
txtName.setBackground(color);
});
this.add(cbxColors);
txtName = new JTextField();
txtName.setBorder ( BorderFactory.createLineBorder ( Color.GREEN,5 ) );
txtName.setPreferredSize(new Dimension(100, 23));
txtName.setBackground(Color.RED);
this.add(txtName);
}
public static void main(String[] args) {
new App().setVisible(true);
}
} | true |
1957819b9e5433b535c3f4e22742c274c5e99cd4 | Java | antoniogarmendia/EMF-Splitter | /org.miso.wizard.instantiate.modular.pattern/src/org/miso/wizard/instantiate/modular/pattern/pages/PageSelectPackagesUnits.java | UTF-8 | 20,157 | 1.78125 | 2 | [] | no_license | package org.miso.wizard.instantiate.modular.pattern.pages;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.miso.wizard.instantiate.modular.pattern.content.provider.GraphContentProvider;
import org.miso.wizard.instantiate.modular.pattern.editing.support.ESColumnExtension;
import org.miso.wizard.instantiate.modular.pattern.editing.support.ESColumnIcon;
import org.miso.wizard.instantiate.modular.pattern.editing.support.ESColumnName;
import org.miso.wizard.instantiate.modular.pattern.editing.support.ESPackageUnit;
import org.miso.wizard.instantiate.modular.pattern.label.provider.LabelProviderEClassName;
import org.miso.wizard.instantiate.modular.pattern.label.provider.LabelProviderExtension;
import org.miso.wizard.instantiate.modular.pattern.label.provider.LabelProviderIcon;
import org.miso.wizard.instantiate.modular.pattern.label.provider.LabelProviderName;
import org.miso.wizard.instantiate.modular.pattern.label.provider.LabelProviderPackageUnit;
import MetaModelGraph.Composition;
import MetaModelGraph.EnumModular;
import MetaModelGraph.Node;
import MetaModelGraph.Reference;
import MetaModelGraph.Relation;
import MetaModelGraph.SubClass;
import MetaModelGraph.SubGraph;
import MetaModelGraph.impl.MetaModelGraphFactoryImpl;
public class PageSelectPackagesUnits extends WizardPage{
private Tree eTree;
private TreeViewer eTreeViewer;
private ScrolledComposite sc;
private int clientWidth;
private SubGraph subGraph;
private EList<EClass> eListEClass;
public PageSelectPackagesUnits(String pageName, EList<EClass> eListEClass, SubGraph subGraph) {
super(pageName);
setTitle("Select the Packages and Units");
setDescription("Select the appropriate class for packages and units");
this.subGraph = subGraph;
this.eListEClass = eListEClass;
clientWidth = 770;
}
@Override
public void createControl(Composite parent) {
//Define container
final Composite container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
container.setLayout(layout);
container.setLayoutData(new GridData(GridData.FILL_BOTH));
sc = new ScrolledComposite(container, SWT.H_SCROLL | SWT.V_SCROLL );
sc.setLayout(new GridLayout());
sc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
this.eTree = new Tree (this.sc, SWT.VIRTUAL | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_SCROLL);
this.eTree.setHeaderVisible(true);
this.eTree.setLinesVisible(true);
//initialize tree viewer
this.eTreeViewer = new TreeViewer(this.eTree);
this.eTreeViewer.setUseHashlookup(true);
/*
* The following listener ensures that the Tree is always large
* enough to not need to show its own vertical scrollbar.
*/
this.eTree.addTreeListener (new TreeListener () {
@Override
public void treeExpanded (TreeEvent e) {
eTree.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
int prefHeight = eTree.computeSize (SWT.DEFAULT, SWT.DEFAULT).y;
eTree.setSize (clientWidth, prefHeight);
sc.setMinSize(eTree.computeSize(clientWidth,prefHeight));
}
});
}
@Override
public void treeCollapsed (TreeEvent e) {
eTree.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
int prefHeight = eTree.computeSize (SWT.DEFAULT, SWT.DEFAULT).y;
eTree.setSize (clientWidth, prefHeight);
sc.setMinSize(eTree.computeSize(clientWidth,prefHeight));
}
});
}
});
/*
* The following listener ensures that a newly-selected item
* in the Tree is always visible.
*/
this.eTree.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TreeItem [] selectedItems = eTree.getSelection();
if (selectedItems.length > 0) {
Rectangle itemRect = selectedItems[0].getBounds();
Rectangle area = sc.getClientArea();
Point origin = sc.getOrigin();
if (itemRect.x < origin.x || itemRect.y < origin.y
|| itemRect.x + itemRect.width > origin.x + area.width
|| itemRect.y + itemRect.height > origin.y + area.height) {
sc.setOrigin(itemRect.x, itemRect.y);
}
}
};
});
/*
* The following listener scrolls the Tree one item at a time
* in response to MouseWheel events.
*/
this.eTree.addListener(SWT.MouseWheel, event -> {
Point origin = sc.getOrigin();
if (event.count < 0) {
origin.y = Math.min(origin.y + eTree.getItemHeight(), eTree.getSize().y);
} else {
origin.y = Math.max(origin.y - eTree.getItemHeight(), 0);
}
sc.setOrigin(origin);
});
TreeViewerColumn eColumnEClass = new TreeViewerColumn(eTreeViewer, SWT.LEFT);
eColumnEClass.getColumn().setText("Containment Reference/Class Name");
eColumnEClass.getColumn().setWidth(300);
eColumnEClass.setLabelProvider(new LabelProviderEClassName());
TreeViewerColumn eColumnPackageUnit = new TreeViewerColumn(eTreeViewer, SWT.LEFT);
eColumnPackageUnit.getColumn().setText("Package or Unit");
eColumnPackageUnit.getColumn().setWidth(150);
eColumnPackageUnit.setLabelProvider(new LabelProviderPackageUnit());
eColumnPackageUnit.setEditingSupport(new ESPackageUnit(this.eTreeViewer));
TreeViewerColumn eColumName = new TreeViewerColumn(eTreeViewer, SWT.LEFT);
eColumName.getColumn().setText("Name");
eColumName.getColumn().setWidth(150);
eColumName.setLabelProvider(new LabelProviderName());
eColumName.setEditingSupport(new ESColumnName(eTreeViewer));
TreeViewerColumn eColumIcon = new TreeViewerColumn(eTreeViewer, SWT.LEFT);
eColumIcon.getColumn().setText("Icon");
eColumIcon.getColumn().setWidth(150);
eColumIcon.setLabelProvider(new LabelProviderIcon());
eColumIcon.setEditingSupport(new ESColumnIcon(eTreeViewer));
TreeViewerColumn eColumnExtension = new TreeViewerColumn(eTreeViewer, SWT.LEFT);
eColumnExtension.getColumn().setText("Extension");
eColumnExtension.getColumn().setWidth(150);
eColumnExtension.setLabelProvider(new LabelProviderExtension());
eColumnExtension.setEditingSupport(new ESColumnExtension(eTreeViewer));
Composite containerButtons = new Composite(container, SWT.NONE);
containerButtons.setLayoutData(new GridData(GridData.BEGINNING));
containerButtons.setLayout(new GridLayout(2, false));
Button btnHeuristic = new Button(containerButtons, SWT.PUSH);
btnHeuristic.setText("Execute Heuristic");
btnHeuristic.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
annotateProjectPackageAndUnits();
eTreeViewer.refresh();
}
});
Button btnClear = new Button(containerButtons, SWT.PUSH);
btnClear.setText("Clear Heuristic");
btnClear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clearHeuristics();
eTreeViewer.refresh();
}
});
container.pack();
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
sc.setAlwaysShowScrollBars(true);
sc.setContent(this.eTree);
setControl(container);
}
protected void clearHeuristics() {
Iterator<Node> itNodes = subGraph.getNodes().iterator();
while (itNodes.hasNext()) {
Node node = (Node) itNodes.next();
node.getEnumModularNotation().clear();
}
annotateProject();
}
@Override
public boolean canFlipToNextPage() {
if(this.subGraph.getNodes().size()==1)
fillTreeOfContainments();
fillWidgetTree();
return super.canFlipToNextPage();
}
private void fillTreeOfContainments() {
if(this.subGraph.getRoot()!=null)
{
Map<EClass, Node> mapElements = new ConcurrentHashMap<EClass, Node>();
mapElements.put(this.subGraph.getRoot().getEClass(), subGraph.getRoot());
ArrayList<EClass> arrayEAllClasses = new ArrayList<EClass>(Arrays.asList(this.subGraph.getRoot().getEClass()));
for (int i = 0; i < arrayEAllClasses.size(); i++) {
EClass eClass = arrayEAllClasses.get(i);
Iterator<EReference> itEAllReferences = eClass.getEAllContainments().iterator();
Node sourceNode = mapElements.get(eClass);
//Take into account the SubClasses of the Node
SubClasses(sourceNode,subGraph,arrayEAllClasses,mapElements,this.eListEClass);
while (itEAllReferences.hasNext()) {
EReference eReference = (EReference) itEAllReferences.next();
EClassifier eClassifier = eReference.getEType();
if(eClassifier instanceof EClass){
EClass eClassType = (EClass) eClassifier;
//Search in the Map of Elements
Node node = mapElements.get(eClassType);
if(node == null){
node = MetaModelGraphFactoryImpl.eINSTANCE.createNode();
node.setEClass(eClassType);
subGraph.getNodes().add(node);
mapElements.put(eClassType, node);
arrayEAllClasses.add(eClassType);
//SubClasses
//SubClasses(node,subGraph,arrayEAllClasses,mapElements,this.eListEClass);
}
Relation eRelation = null;
if(eReference.isContainment()){
eRelation = MetaModelGraphFactoryImpl.eINSTANCE.createComposition();
((Composition)eRelation).setEReference(eReference);
eRelation.setTarget(node);
sourceNode.getCompositions().add((Composition) eRelation);
}else{
eRelation = MetaModelGraphFactoryImpl.eINSTANCE.createReference();
((Reference)eRelation).setEReference(eReference);
eRelation.setTarget(node);
sourceNode.getReferences().add((Reference) eRelation);
}
subGraph.getRelations().add(eRelation);
}
}
}
annotateProject();
fillWidgetTree();
}
}
private void SubClasses(Node node, SubGraph subGraph, ArrayList<EClass> arrayEAllClasses,
Map<EClass, Node> mapElements, EList<EClass> eClassesList) {
Iterator<EClass> itListClasses = eClassesList.iterator();
EClass eClassP = node.getEClass();
while (itListClasses.hasNext()) {
EClass eClass = (EClass) itListClasses.next();
EList<EClass> listSuper = eClass.getEAllSuperTypes();
EList<EClass> listDirectSuperClass = eClass.getESuperTypes();
int index = listSuper.indexOf(eClassP);
if(index != -1){
Node subClassNode = mapElements.get(eClass);
if(subClassNode == null){
subClassNode = MetaModelGraphFactoryImpl.eINSTANCE.createNode();
subClassNode.setEClass(eClass);
subGraph.getNodes().add(subClassNode);
mapElements.put(eClass, subClassNode);
arrayEAllClasses.add(eClass);
}
SubClass sub = MetaModelGraphFactoryImpl.eINSTANCE.createSubClass();
sub.setTarget(subClassNode);
subGraph.getRelations().add(sub);
node.getSubClasses().add(sub);
if(listDirectSuperClass.indexOf(eClassP)!=-1)
node.getDirectSubclasses().add(sub);
}
}
}
private void annotateProject(){
//Project
this.subGraph.getRoot().getEnumModularNotation().add(EnumModular.PROJECT);
boolean existRecursion = detectRecursion(subGraph.getRoot());
if(existRecursion == true)
this.subGraph.getRoot().getEnumModularNotation().add(EnumModular.PACKAGE);
}
private void annotateProjectPackageAndUnits() {
boolean existRecursion = false;
EList<Node> eListAllNodes = new BasicEList<Node>();
eListAllNodes.add(subGraph.getRoot());
for (int i = 0; i < eListAllNodes.size(); i++){
Node sourceNode = eListAllNodes.get(i);
if(sourceNode.equals(subGraph.getRoot())){
//Analyze Compositions
Iterator<Composition> itCompositions = sourceNode.getCompositions().iterator();
while (itCompositions.hasNext()) {
Composition composition = (Composition) itCompositions.next();
Node currentNode = composition.getTarget();
existRecursion = detectRecursion(currentNode);
if(existRecursion==true){
currentNode.getEnumModularNotation().add(EnumModular.PACKAGE);//RECURSION_PACKAGE
if(eListAllNodes.indexOf(currentNode)==-1)
eListAllNodes.add(currentNode);
}
else
{
boolean hasComp = hasCompositionLevel(currentNode,0);
if(hasComp==true){
currentNode.getEnumModularNotation().add(EnumModular.PACKAGE);
if(eListAllNodes.indexOf(currentNode)==-1)
eListAllNodes.add(currentNode);
}
else
AnnotateUnit(currentNode);
}
}
}else{
boolean hasCompo = hasCompositionLevel(sourceNode, 0);
if(hasCompo == true){
//Analyze Compositions
Iterator<Composition> itCompositions = getAllCompositions(sourceNode).iterator();
while (itCompositions.hasNext()) {
Composition composition = (Composition) itCompositions.next();
Node currentNode = composition.getTarget();
if(sourceNode.getEnumModularNotation().indexOf(EnumModular.PACKAGE)!=-1){//RECURSION_PACKAGE
if(currentNode.getEClass().isAbstract() == false){
currentNode.getEnumModularNotation().add(EnumModular.UNIT);
}
else
AnnotateUnit(currentNode);
}
else{
existRecursion = detectRecursion(currentNode);
if (existRecursion==true) {
currentNode.getEnumModularNotation().add(EnumModular.PACKAGE);//RECURSION_PACKAGE
}
else{
boolean hasComp = hasCompositionLevel(currentNode,1);
if(hasComp==true){
currentNode.getEnumModularNotation().add(EnumModular.PACKAGE);
}
else{
currentNode.getEnumModularNotation().add(EnumModular.UNIT);
}
}
if(eListAllNodes.indexOf(currentNode)==-1)
eListAllNodes.add(currentNode);
}
}
Iterator<SubClass> itAllSubClasses = sourceNode.getSubClasses().iterator();
while (itAllSubClasses.hasNext()) {
SubClass subClass = (SubClass) itAllSubClasses.next();
if(eListAllNodes.indexOf(subClass.getTarget())==-1)
eListAllNodes.add(subClass.getTarget());
}
existRecursion = detectRecursion(sourceNode);
if(existRecursion == true){
sourceNode.getEnumModularNotation().add(EnumModular.PACKAGE);//RECURSION_PACKAGE
}
else{
sourceNode.getEnumModularNotation().add(EnumModular.PACKAGE);
}
}
else{
AnnotateUnit(sourceNode);
}
}
}
}
private void AnnotateUnit(Node node){
boolean existRecursion = detectRecursion(node);
if(existRecursion == false)
node.getEnumModularNotation().add(EnumModular.UNIT);
else{
node.getEnumModularNotation().add(EnumModular.UNIT);//RECURSION_UNIT
}
Iterator<SubClass> itAllSubClasses = node.getSubClasses().iterator();
while (itAllSubClasses.hasNext()) {
SubClass subClass = (SubClass) itAllSubClasses.next();
existRecursion = detectRecursion(subClass.getTarget());
if(existRecursion==false)
{
subClass.getTarget().getEnumModularNotation().add(EnumModular.UNIT);
}
else{
subClass.getTarget().getEnumModularNotation().add(EnumModular.UNIT);//RECURSION_UNIT
}
}
}
private boolean detectRecursion(Node node) {
EList<Node> listOfNodes = new BasicEList<Node>();
listOfNodes.add(node);
for (int i = 0; i < listOfNodes.size(); i++) {
Node currentNode = listOfNodes.get(i);
Iterator<Composition> itCompositions = getAllCompositions(currentNode).iterator();
while (itCompositions.hasNext()) {
Composition composition = (Composition) itCompositions.next();
Node target = composition.getTarget();
if(target.equals(node) ^ isSubEClass(target, node)==true)
return true;
else{
if(listOfNodes.indexOf(target)==-1)
listOfNodes.add(target);
}
}
}
return false;
}
private boolean isSubEClass(Node parent,Node children){
Iterator<SubClass> itSubClasses = parent.getSubClasses().iterator();
while (itSubClasses.hasNext()) {
SubClass subClass = (SubClass) itSubClasses.next();
if(subClass.getTarget().equals(children))
return true;
}
return false;
}
private EList<Composition> getDirectAllCompositions(Node node){
EList<Composition> eListCompositions = new BasicEList<Composition>();
eListCompositions.addAll(node.getCompositions());
return eListCompositions;
}
private EList<Composition> getAllCompositionSubClass(Node node){
EList<Composition> eListCompositions = new BasicEList<Composition>();
Iterator<SubClass> itAllSubClasses = node.getSubClasses().iterator();
while (itAllSubClasses.hasNext()) {
SubClass subClass = (SubClass) itAllSubClasses.next();
eListCompositions.addAll(subClass.getTarget().getCompositions());
}
return eListCompositions;
}
private EList<Composition> getAllCompositions(Node node){
EList<Composition> eListCompositions = new BasicEList<Composition>();
eListCompositions.addAll(getDirectAllCompositions(node));
eListCompositions.addAll(getAllCompositionSubClass(node));
return eListCompositions;
}
/*
* True has composition to unvisited node
* False has no composition
* */
private boolean hasCompositionLevel(Node node,int level){
Iterator<Composition> itCompositions = getAllCompositions(node).iterator();
if(itCompositions.hasNext() == false)
return false;
while (itCompositions.hasNext()) {
Composition composition = (Composition) itCompositions.next();
Node currentNode = composition.getTarget();
if(currentNode.equals(node) == false){
if(currentNode.getEnumModularNotation().equals(EnumModular.DEFAULT) || level==1)
return true;
else
return hasCompositionLevel(currentNode, 1);
}
}
return false;
}
private void fillWidgetTree() {
deleteWidgetTree();
this.eTreeViewer.setContentProvider(new GraphContentProvider(this.eTreeViewer));
ArrayList<Object> arrayObjects = new ArrayList<Object>();
arrayObjects.add(this.subGraph.getRoot());
arrayObjects.addAll(this.subGraph.getRoot().getCompositions());
this.eTreeViewer.setInput(arrayObjects.toArray());
this.eTreeViewer.expandToLevel(2);
int prefHeight = eTree.computeSize (SWT.DEFAULT, SWT.DEFAULT).y;
this.eTree.setSize (this.clientWidth, prefHeight);
this.sc.setMinSize(this.eTree.computeSize(this.clientWidth,prefHeight));
}
private void deleteWidgetTree() {
this.eTree.setRedraw(false);
this.eTree.removeAll();
this.eTree.setRedraw(true);
}
public SubGraph getSubGraph() {
return subGraph;
}
}
| true |
b4a6fd8ea0d005c478e4c38628509da101f02a98 | Java | peter-otten/Spotitube | /src/main/java/services/rest/PlaylistRestService.java | UTF-8 | 901 | 2.234375 | 2 | [] | no_license | package services.rest;
import com.google.inject.Inject;
import datasource.IPlaylistDao;
import datasource.ITrackDao;
import domain.Playlist;
import domain.Track;
import services.IPlaylistService;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/playlists")
@Singleton
public class PlaylistRestService implements IPlaylistService{
IPlaylistDao playlistDao;
@Inject
public void setService(IPlaylistDao playlistDao)
{
this.playlistDao = playlistDao;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Playlist> findAll(String owner) {
return playlistDao.findAll(owner);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public void addPlaylist(String name) {
playlistDao.addPlaylist(name);
}
}
| true |
81b309535f4841bff01f50ac13edab6a0f2663f5 | Java | Auch-Auch/avito_source | /sources/com/avito/android/short_term_rent/di/module/StrConfirmBookingBlueprintsModule_ProvideItemBinderFactory.java | UTF-8 | 2,843 | 1.867188 | 2 | [] | no_license | package com.avito.android.short_term_rent.di.module;
import com.avito.android.blueprints.ButtonItemBlueprint;
import com.avito.android.blueprints.InputItemBlueprint;
import com.avito.android.conveyor_shared_item.notification.NotificationItemBlueprint;
import com.avito.android.short_term_rent.confirm_booking.items.link.LinkItemBlueprint;
import com.avito.android.short_term_rent.start_booking.items.disclaimer.DisclaimerItemBlueprint;
import com.avito.android.short_term_rent.start_booking.items.summary.SummaryItemBlueprint;
import com.avito.konveyor.ItemBinder;
import dagger.internal.Factory;
import dagger.internal.Preconditions;
import javax.inject.Provider;
public final class StrConfirmBookingBlueprintsModule_ProvideItemBinderFactory implements Factory<ItemBinder> {
public final Provider<InputItemBlueprint> a;
public final Provider<NotificationItemBlueprint> b;
public final Provider<ButtonItemBlueprint> c;
public final Provider<SummaryItemBlueprint> d;
public final Provider<LinkItemBlueprint> e;
public final Provider<DisclaimerItemBlueprint> f;
public StrConfirmBookingBlueprintsModule_ProvideItemBinderFactory(Provider<InputItemBlueprint> provider, Provider<NotificationItemBlueprint> provider2, Provider<ButtonItemBlueprint> provider3, Provider<SummaryItemBlueprint> provider4, Provider<LinkItemBlueprint> provider5, Provider<DisclaimerItemBlueprint> provider6) {
this.a = provider;
this.b = provider2;
this.c = provider3;
this.d = provider4;
this.e = provider5;
this.f = provider6;
}
public static StrConfirmBookingBlueprintsModule_ProvideItemBinderFactory create(Provider<InputItemBlueprint> provider, Provider<NotificationItemBlueprint> provider2, Provider<ButtonItemBlueprint> provider3, Provider<SummaryItemBlueprint> provider4, Provider<LinkItemBlueprint> provider5, Provider<DisclaimerItemBlueprint> provider6) {
return new StrConfirmBookingBlueprintsModule_ProvideItemBinderFactory(provider, provider2, provider3, provider4, provider5, provider6);
}
public static ItemBinder provideItemBinder(InputItemBlueprint inputItemBlueprint, NotificationItemBlueprint notificationItemBlueprint, ButtonItemBlueprint buttonItemBlueprint, SummaryItemBlueprint summaryItemBlueprint, LinkItemBlueprint linkItemBlueprint, DisclaimerItemBlueprint disclaimerItemBlueprint) {
return (ItemBinder) Preconditions.checkNotNullFromProvides(StrConfirmBookingBlueprintsModule.provideItemBinder(inputItemBlueprint, notificationItemBlueprint, buttonItemBlueprint, summaryItemBlueprint, linkItemBlueprint, disclaimerItemBlueprint));
}
@Override // javax.inject.Provider
public ItemBinder get() {
return provideItemBinder(this.a.get(), this.b.get(), this.c.get(), this.d.get(), this.e.get(), this.f.get());
}
}
| true |
7b058db02913c3505ae53d1d44376ff1355735cb | Java | mikerussellnz/javacodedom | /src/test/java/com/mikerussell/javacodedom/elements/InterfaceDeclarationTest.java | UTF-8 | 2,643 | 2.578125 | 3 | [] | no_license | package com.mikerussell.javacodedom.elements;
import com.mikerussell.javacodedom.BaseTest;
import com.mikerussell.javacodedom.core.AccessModifier;
import org.junit.Test;
public class InterfaceDeclarationTest extends BaseTest {
@Test
public void testInterfaceDeclarationFields() {
InterfaceDeclaration classDeclaration = new InterfaceDeclaration("TestInterface");
classDeclaration.addField(new FieldDeclaration(AccessModifier.PRIVATE, TypeReference.get(int.class), "field1"));
classDeclaration.addField(new FieldDeclaration(AccessModifier.PRIVATE, TypeReference.get(String.class), "field2")
.initializeWith(new Primitive("Hello")));
generateAndCompare("TestInterfaceDeclarationFields", classDeclaration);
}
@Test
public void testInterfaceGenericParameters() {
InterfaceDeclaration classDeclaration = new InterfaceDeclaration("TestInterface");
classDeclaration.addGenericParameter(new GenericParameter("T")
.addBound(TypeReference.get(Integer.class))
.addBound(TypeReference.get(String.class)));
classDeclaration.addGenericParameter(new GenericParameter("V"));
generateAndCompare("TestInterfaceGenericParameters", classDeclaration);
}
@Test
public void testInterfaceDeclarationMethods() {
InterfaceDeclaration classDeclaration = new InterfaceDeclaration("TestInterface")
.addMethod(new MethodDeclaration(AccessModifier.PUBLIC, "methodOne"))
.addMethod(new MethodDeclaration(AccessModifier.PUBLIC, "methodTwo"));
generateAndCompare("TestInterfaceDeclarationMethods", classDeclaration);
}
@Test
public void testInterfaceDeclarationFieldsAndMethods() {
InterfaceDeclaration classDeclaration = new InterfaceDeclaration("TestInterface")
.addField(new FieldDeclaration(AccessModifier.PRIVATE, TypeReference.get(int.class), "field1"))
.addField(new FieldDeclaration(AccessModifier.PRIVATE, TypeReference.get(String.class), "field2")
.initializeWith(new Primitive("Hello")))
.addMethod(new MethodDeclaration(AccessModifier.PUBLIC, "methodOne"))
.addMethod(new MethodDeclaration(AccessModifier.PUBLIC, "methodTwo"));
generateAndCompare("TestInterfaceDeclarationFieldsAndMethods", classDeclaration);
}
@Test
public void testInterfaceDeclarationExtendsAndImplements() {
InterfaceDeclaration classDeclaration = new InterfaceDeclaration("TestInterface")
.addExtends(TypeReference.get("Interface1"))
.addExtends(TypeReference.get("Interface2"))
.addExtends(TypeReference.get("Interface3"));
generateAndCompare("TestInterfaceDeclarationExtendsAndImplements", classDeclaration);
}
}
| true |
2660e5f4143eb9a7530b79075384cb79a4d9e02f | Java | BAT6188/mt36k_android_4.0.4 | /ics-4.x/frameworks/base/application_platform/MediaFile/src/com/tcl/mediafile/MediaFile.java | UTF-8 | 7,756 | 2.75 | 3 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | package com.tcl.mediafile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Comparator;
import java.util.List;
import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
/**
* MediaFile为虚基类。提够类似File的接口,并增加了诸如getMimeType()等结构,方便操作。
* 一般情况下,可以通过Device的getRootFile()方法来获取一个MediaFile。
* */
public abstract class MediaFile {
private MediaFile mParent;
private String mName;
private String mPath;
private Device mDevice = null;
/**
* 根据MediaFile的path来构建MediaFile。
* */
public MediaFile(String path) {
mPath = path;
}
/**
* 构造一个MediaFile
* */
public MediaFile(){}
/**
* 设置该MediaFile的父结点。
*
* @param p 负结点,当没有父结点时,p设置为Null
* */
public void setParent(MediaFile p) {
mParent = p;
if (p != null) {
mDevice = p.getDevice();
}
}
/**
* 获取父对象
*
* @return 父对象,或null;
* */
public MediaFile getParent() {
return mParent;
}
/**
* 设置改MediaFile归属的设备。同时也可以通过{@link #getDevice() getDevice()}方法来获得一个设备对象。
*
* @param device 所归属的设备。
* */
public void setDevice(Device device) {
mDevice = device;
}
/**
* 获得设备
*
* @return 所属的设备。
* */
public Device getDevice() {
return mDevice;
}
/**
* 创建一个新的MediaFile。
*
* @return 创建文件是否成功。
* @throws IOException
* */
public boolean createMediaFile() throws IOException{
return false;
}
/**
* 获取MediaFile名
*
* @return MediaFile名
* */
public String getName() {
return mName;
}
/**
* 设置MediaFile名
*
* @param MediaFile名
* */
public void setName(String name) {
mName = name;
}
/**
* 获取文件路径
*
* @return 文件路径
* */
public String getPath(){
return mPath;
}
//如果是本地文件,则uri为:file:///xxx
public Uri uri() {
return Uri.parse("file://" + getPath());
}
/**
* 获取文件长度
*
* @return 返回文件长度
* */
abstract public long length();
// /**
// * 获取文件图标
// *
// * @return 返回文件图标
// * */
// public Bitmap getFileIcon(Context ctx) {
// if (isDirectory())
// return IconCreator.createFolderIcon(ctx);
// else
// return IconCreator.createIconWithMime(ctx, mimeType());
// }
/**
* 设置文件图标
*
* @param bm 文件图标的Bitmap
* @see #getFileIcon(Context)
* */
public void setFileIcon(Bitmap bm) {
//mThumbBitmap = bm;
}
/**
* 返回MediaFile的MimeType。
* @return MimeType,形如“video/mp4”
* */
public String mimeType() {
String ext = MimeType.getFileExtensionFromUrl(getName());
String mimeType = MimeType.getSingleton().getMimeTypeFromExtension(ext);
return mimeType;
}
/**
* MediaFile比较器,由字母序来确定文件的排序先后。当进行MediaFile列表排序时,将会使用该方法。
* */
public static class MediaFileNameComparator implements Comparator<MediaFile> {
/**
* 按字母序比较object1和object2的大小,比较的依据是文件名
* @return
* 如果返回负值,则表示这个实例小于另一个;如果返回为正值,表示大于另一个;如果为0,则两个相等。
* @throws NullPointerException 如果MediaFile为null,则抛出异常
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(MediaFile file1, MediaFile file2) {
if (file1 == null || file2 == null) {
throw new NullPointerException();
}
if (file1.isDirectory() && !file2.isDirectory())
return -1;
else if (!file1.isDirectory() && file2.isDirectory()) {
return 1;
}
if (file1.getName() == null || file2.getName() == null)
return 0;
return compareName(file1.getName(),file2.getName());//file1.getName().compareTo(file2.getName());
//compareName(file1.getName(),file2.getName());
}
//按字母和数字混个排序
private int compareName(String str1,String str2){
int flag = 0;
String digitStr1 ="";
String digitStr2 ="";
int len = str1.length()<str2.length()?str1.length():str2.length();
for(int i=0;i<len;i++){
if(digitStr1.length()>5){
if(digitStr1.compareTo(digitStr2)!=0){
return digitStr1.compareTo(digitStr2);
}
digitStr1 = "";
digitStr2 = "";
}
if(Character.isDigit(str1.charAt(i)) && Character.isDigit(str2.charAt(i))){
digitStr1+=str1.charAt(i);
digitStr2+=str2.charAt(i);
} else {
if(digitStr1.trim().length()>0){
if(Character.isDigit(str1.charAt(i))){
int j = i;
while(j<str1.length() && Character.isDigit(str1.charAt(j))){
digitStr1 += str1.charAt(j);
j++;
}
} else if(Character.isDigit(str2.charAt(i))){
int j = i;
while(j<str2.length() && Character.isDigit(str2.charAt(j))){
digitStr2 += str2.charAt(j);
j++;
}
}
if(digitStr1.length()>5 || digitStr2.length()>5){
if(str1.charAt(i)>str2.charAt(i)){
flag = 1;
break;
}else if(str1.charAt(i)<str2.charAt(i)){
flag = -1;
break;
}
}else{
if(Integer.parseInt(digitStr1)>Integer.parseInt(digitStr2)){
flag = 1;
break;
} else if(Integer.parseInt(digitStr1)<Integer.parseInt(digitStr2)){
flag = -1;
break;
}
}
digitStr1 = "";
digitStr2 = "";
} else if(str1.charAt(i)>str2.charAt(i)){
flag = 1;
break;
} else if(str1.charAt(i)<str2.charAt(i)){
flag = -1;
break;
}
}
}
return flag;
}
}
/**
* 当两个MediaFile的路径相同时,我们就认为这两个MediaFile是相同的。
* @see java.lang.Object#equals(java.lang.Object)
* @return true表示相同,反之,不相同
*/
@Override
public boolean equals(Object o) {
if ((o == null) || !(o.getClass().equals(getClass())))
return false;
return getPath().equals(((MediaFile)o).getPath());
}
/**
* 返回MediaFile的hashCode,我们利用了文件路径String的hashCode作为替代
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return getPath().hashCode();
}
/**
* 获取MediaFile的InputStream,可以用来读取文件。
* @return InputStream
* */
public InputStream getInputStream() {
return null;
}
/**
* 获取MediaFile的OutputStream,可以用来写文件。
* @return OutputStream
* */
public OutputStream getOutputStream() {
return null;
}
/**
* 删除文件
* @return 删除操作是否成功
* */
abstract public boolean delete();
abstract public boolean exist();
/**
* 创建文件夹
* @return 创建是否成功
* */
abstract public boolean mkdir();
/**
* 返回该MediaFile是否可写
* @return 是否可写
* */
abstract public boolean canWrite();
/**
* 获取改文件夹的文件列表,如果改文件不是文件夹,则返回null
* @return 文件列表或null
* */
public List<MediaFile> listMediaFiles() {
return listMediaFiles(null);
}
/**
* @param 过滤器
* @return 文件列表或null
* @see MediaFileFilter
*/
public abstract List<MediaFile> listMediaFiles(MediaFileFilter filter);
/**
* 指示是否为文件夹
* @return true是文件夹,否则不是
* */
public abstract boolean isDirectory();
@Override
public String toString() {
return getPath();
}
}
| true |
96ef9267c5bc1f79d64741c8dc03f499c7a1a903 | Java | League-Level1-Student/level1-module3-teashopp | /src/_01_intro_to_static/Athlete.java | UTF-8 | 1,006 | 3.71875 | 4 | [] | no_license | package _01_intro_to_static;
import java.util.Random;
public class Athlete {
//static Random rn = new Random();
//int answer = rn.nextInt(10) + 1;
static Random nextBibNumber0 = new Random();
int nextBibNumber = nextBibNumber0.nextInt(500) + 1;
static String raceLocation = "New York";
static String raceStartTime = "9.00am";
String name;
int speed;
int bibNumber;
Athlete(String name, int speed) {
this.name = name;
this.speed = speed;
}
public static void main(String[] args) {
// create two athletes
// print their names, bibNumbers, and the location of their race.
Athlete John = new Athlete("John", 10);
Athlete Ray = new Athlete("Ray", 10);
System.out.println(John.name);
System.out.println(John.nextBibNumber);
System.out.println(John.raceLocation);
System.out.println("");
System.out.println(Ray.name);
System.out.println(Ray.nextBibNumber);
System.out.println(Ray.raceLocation);
}
}
| true |
119865ead7cef3a3e15c66a70a29312362019f56 | Java | guozhuoyuan/Exchangis | /modules/executor/engine/datax/datax-hdfsreader/src/main/java/com/alibaba/datax/plugin/reader/hdfsreader/HdfsReader.java | UTF-8 | 21,661 | 1.695313 | 2 | [
"Apache-2.0"
] | permissive | package com.alibaba.datax.plugin.reader.hdfsreader;
import com.webank.wedatasphere.exchangis.datax.common.constant.TransportType;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.datax.common.spi.Reader;
import com.alibaba.datax.common.util.Configuration;
import com.webank.wedatasphere.exchangis.datax.core.job.meta.MetaSchema;
import com.webank.wedatasphere.exchangis.datax.core.transport.stream.ChannelOutput;
import com.webank.wedatasphere.exchangis.datax.core.transport.stream.StreamMeta;
import com.alibaba.datax.core.util.FrameworkErrorCode;
import com.alibaba.datax.plugin.unstructuredstorage.PathMeta;
import com.alibaba.datax.plugin.unstructuredstorage.reader.UnstructuredStorageReaderUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.UnsupportedCharsetException;
import java.security.PrivilegedAction;
import java.util.*;
import static com.alibaba.datax.plugin.unstructuredstorage.reader.Key.INCR_BEGIN_TIME;
import static com.alibaba.datax.plugin.unstructuredstorage.reader.Key.INCR_END_TIME;
public class HdfsReader extends Reader {
/**
* Job 中的方法仅执行一次,task 中方法会由框架启动多个 task 线程并行执行。
* <p/>
* 整个 Reader 执行流程是:
* <pre>
* Job类init-->prepare-->split
*
* Task类init-->prepare-->startRead-->post-->destroy
* Task类init-->prepare-->startRead-->post-->destroy
*
* Job类post-->destroy
* </pre>
*/
public static class Job extends Reader.Job {
private static final Logger LOG = LoggerFactory
.getLogger(Job.class);
private Configuration readerOriginConfig = null;
private String encoding = null;
private HashSet<PathMeta> sourceFiles = new HashSet<>();
private String specifiedFileType = null;
private HdfsReaderUtil hdfsReaderUtil = null;
private List<String> path = null;
private long incrBeginTime = 0;
private long incrEndTime = 0;
private String defaultFS;
org.apache.hadoop.conf.Configuration hadoopConf = null;
private UserGroupInformation ugi = null;
@Override
public boolean isSupportStream(){
return true;
}
@Override
public void init() {
LOG.info("init() begin...");
this.readerOriginConfig = super.getPluginJobConf();
this.validate();
hdfsReaderUtil = new HdfsReaderUtil(this.readerOriginConfig);
LOG.info("init() ok and end...");
for(String eachPath : path) {
if (!hdfsReaderUtil.exists(eachPath)) {
String message = String.format("cannot find the path: [%s], please check your configuration", eachPath);
LOG.error(message);
throw DataXException.asDataXException(HdfsReaderErrorCode.PATH_NOT_FOUND, message);
}
}
}
@Override
public MetaSchema syncMetaData() {
if(StringUtils.isNotBlank(readerOriginConfig.getString(Key.HIVE_METASTORE_URIS, ""))){
return hdfsReaderUtil.getHiveMetadata(
readerOriginConfig.getString(Key.HIVE_DATABASE),
readerOriginConfig.getString(Key.HIVE_TABLE),
readerOriginConfig.getString(Key.HIVE_METASTORE_URIS)
);
}
return null;
}
private void validate() {
this.defaultFS = this.readerOriginConfig.getNecessaryValue(Key.DEFAULT_FS,
HdfsReaderErrorCode.DEFAULT_FS_NOT_FIND_ERROR);
// path check
String pathInString = this.readerOriginConfig.getNecessaryValue(Key.PATH, HdfsReaderErrorCode.REQUIRED_VALUE);
if (!pathInString.startsWith("[") && !pathInString.endsWith("]")) {
path = new ArrayList<String>();
path.add(pathInString);
} else {
path = this.readerOriginConfig.getList(Key.PATH, String.class);
if (null == path || path.size() == 0) {
throw DataXException.asDataXException(HdfsReaderErrorCode.REQUIRED_VALUE, "您需要指定待读取的源目录或文件");
}
for (String eachPath : path) {
if (!eachPath.startsWith("/")) {
String message = String.format("请检查参数path:[%s],需要配置为绝对路径", eachPath);
LOG.error(message);
throw DataXException.asDataXException(HdfsReaderErrorCode.ILLEGAL_VALUE, message);
}
}
}
if(getTransportType() == TransportType.RECORD) {
specifiedFileType = this.readerOriginConfig.getNecessaryValue(Key.FILETYPE, HdfsReaderErrorCode.REQUIRED_VALUE);
if (!specifiedFileType.equalsIgnoreCase(Constant.ORC) &&
!specifiedFileType.equalsIgnoreCase(Constant.TEXT) &&
!specifiedFileType.equalsIgnoreCase(Constant.CSV) &&
!specifiedFileType.equalsIgnoreCase(Constant.SEQ) &&
!specifiedFileType.equalsIgnoreCase(Constant.RC) &&
!specifiedFileType.equalsIgnoreCase(Constant.HFILE)) {
String message = "HdfsReader插件目前支持ORC, TEXT, CSV, SEQUENCE, RC, HFile 格式的文件," +
"请将fileType选项的值配置为ORC, TEXT, CSV, SEQUENCE, HFile 或者 RC";
throw DataXException.asDataXException(HdfsReaderErrorCode.FILE_TYPE_ERROR, message);
}
if (this.specifiedFileType.equalsIgnoreCase(Constant.CSV)) {
//compress校验
UnstructuredStorageReaderUtil.validateCompress(this.readerOriginConfig);
UnstructuredStorageReaderUtil.validateCsvReaderConfig(this.readerOriginConfig);
}
}
encoding = this.readerOriginConfig.getString(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.ENCODING, "UTF-8");
try {
Charsets.toCharset(encoding);
} catch (UnsupportedCharsetException uce) {
throw DataXException.asDataXException(
HdfsReaderErrorCode.ILLEGAL_VALUE,
String.format("不支持的编码格式 : [%s]", encoding), uce);
} catch (Exception e) {
throw DataXException.asDataXException(
HdfsReaderErrorCode.ILLEGAL_VALUE,
String.format("运行配置异常 : %s", e.getMessage()), e);
}
//check Kerberos
Boolean haveKerberos = this.readerOriginConfig.getBool(Key.HAVE_KERBEROS, false);
if (haveKerberos) {
this.readerOriginConfig.getNecessaryValue(Key.KERBEROS_KEYTAB_FILE_PATH, HdfsReaderErrorCode.REQUIRED_VALUE);
this.readerOriginConfig.getNecessaryValue(Key.KERBEROS_PRINCIPAL, HdfsReaderErrorCode.REQUIRED_VALUE);
}
this.incrBeginTime = this.readerOriginConfig.getLong(INCR_BEGIN_TIME, 0);
this.incrEndTime = this.readerOriginConfig.getLong(INCR_END_TIME, DateTime.now().getMillis());
// validate the Columns
validateColumns();
}
private void validateColumns() {
List<Configuration> column = this.readerOriginConfig
.getListConfiguration(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.COLUMN);
if(null == column){
column = new ArrayList<>();
}
boolean emptyColumn = column.isEmpty() || (1 == column.size() && ("\"*\"".equals(column.get(0).toString()) || "'*'"
.equals(column.get(0).toString())));
if (emptyColumn) {
this.readerOriginConfig
.set(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.COLUMN, new ArrayList<String>());
} else {
// column: 1. index type 2.value type 3.when type is Data, may have format
List<Configuration> columns = this.readerOriginConfig
.getListConfiguration(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.COLUMN);
if (null != columns && columns.size() != 0) {
for (Configuration eachColumnConf : columns) {
eachColumnConf.getNecessaryValue(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.TYPE, HdfsReaderErrorCode.REQUIRED_VALUE);
Integer columnIndex = eachColumnConf.getInt(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.INDEX);
String columnValue = eachColumnConf.getString(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.VALUE);
if (null == columnIndex && null == columnValue) {
throw DataXException.asDataXException(
HdfsReaderErrorCode.NO_INDEX_VALUE,
"由于您配置了type, 则至少需要配置 index 或 value");
}
if (null != columnIndex && null != columnValue) {
throw DataXException.asDataXException(
HdfsReaderErrorCode.MIXED_INDEX_VALUE,
"您混合配置了index, value, 每一列同时仅能选择其中一种");
}
}
}
}
}
@Override
public void prepare() {
if(StringUtils.isNotBlank(readerOriginConfig.getString(Key.HIVE_METASTORE_URIS, ""))) {
LOG.info("update the configuration dynamically by hive meta...");
boolean affected = hdfsReaderUtil.updateConfigByHiveMeta( readerOriginConfig.getString(Key.HIVE_DATABASE),
readerOriginConfig.getString(Key.HIVE_TABLE),
readerOriginConfig.getString(Key.HIVE_METASTORE_URIS), this.readerOriginConfig);
if(affected){
//validate the configuration again
this.validate();
}
}
LOG.info("start to getAllFiles...");
HashSet<String> sourceFiles0 = hdfsReaderUtil.getAllFiles(path, specifiedFileType);
//to find the parent directory of path
Set<String> parents = new HashSet<>();
for(String path0 : path){
boolean find = false;
for(int i = 0; i < path0.length(); i++){
if('*' == path0.charAt(i) || '?' == path0.charAt(i)){
int lastDirSeparator = path0.substring(0, i)
.lastIndexOf(IOUtils.DIR_SEPARATOR);
parents.add(path0.
substring(0, lastDirSeparator + 1));
find = true;
break;
}
}
if(!find){
parents.add(path0);
}
}
for(String sourceFile : sourceFiles0){
if(getTransportType() == TransportType.STREAM ){
FileStatus status = hdfsReaderUtil.getFileStatus(sourceFile);
if(status.getModificationTime() <= incrBeginTime
|| status.getModificationTime() > incrEndTime){
continue;
}
}
boolean find = false;
for(String parent : parents){
//0: absolute path, 1: relative path
if(sourceFile.indexOf(parent) > 0){
String relativePath = sourceFile.substring(sourceFile.indexOf(parent) + parent.length());
if(StringUtils.isNotBlank(relativePath)){
this.sourceFiles.add(new PathMeta(sourceFile,
relativePath));
}else{
this.sourceFiles.add(new PathMeta(sourceFile,
parent.substring(parent.lastIndexOf(IOUtils.DIR_SEPARATOR))));
}
find = true;
}
if(find){
break;
}
}
if(!find){
throw new DataXException(FrameworkErrorCode.ARGUMENT_ERROR, "路径参数配置错误");
}
}
String fileSeq = StringUtils.join(sourceFiles0, ",");
if(fileSeq.length() > 30){
fileSeq = fileSeq.substring(0, 30);
}
LOG.info(String.format("您即将读取的文件数为: [%s], 列表为: [%s]",
sourceFiles0.size(), fileSeq));
}
@Override
public List<Configuration> split(int adviceNumber) {
LOG.info("split() begin...");
List<Configuration> readerSplitConfigs = new ArrayList<Configuration>();
// warn:每个slice拖且仅拖一个文件,
// int splitNumber = adviceNumber;
int splitNumber = this.sourceFiles.size();
if (0 == splitNumber) {
return new ArrayList<>();
}
List<List<PathMeta>> splitedSourceFiles = this.splitSourceFiles(new ArrayList<>(this.sourceFiles), splitNumber);
for (List<PathMeta> files : splitedSourceFiles) {
Configuration splitedConfig = this.readerOriginConfig.clone();
splitedConfig.set(Constant.SOURCE_FILES, files);
readerSplitConfigs.add(splitedConfig);
}
return readerSplitConfigs;
}
private <T> List<List<T>> splitSourceFiles(final List<T> sourceList, int adviceNumber) {
List<List<T>> splitedList = new ArrayList<List<T>>();
int averageLength = sourceList.size() / adviceNumber;
averageLength = averageLength == 0 ? 1 : averageLength;
for (int begin = 0, end = 0; begin < sourceList.size(); begin = end) {
end = begin + averageLength;
if (end > sourceList.size()) {
end = sourceList.size();
}
splitedList.add(sourceList.subList(begin, end));
}
return splitedList;
}
@Override
public void post() {
}
@Override
public void destroy() {
hdfsReaderUtil.closeFileSystem();
}
}
public static class Task extends Reader.Task {
private static Logger LOG = LoggerFactory.getLogger(Reader.Task.class);
private Configuration taskConfig;
private List<Object> sourceFiles;
private String specifiedFileType;
private String encoding;
private HdfsReaderUtil hdfsReaderUtil = null;
private int bufferSize;
@Override
public void init() {
this.taskConfig = super.getPluginJobConf();
this.sourceFiles = this.taskConfig.getList(Constant.SOURCE_FILES, Object.class);
this.specifiedFileType = this.taskConfig.getString(Key.FILETYPE, "");
this.encoding = this.taskConfig.getString(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.ENCODING, "UTF-8");
this.hdfsReaderUtil = new HdfsReaderUtil(this.taskConfig);
this.bufferSize = this.taskConfig.getInt(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.BUFFER_SIZE,
com.alibaba.datax.plugin.unstructuredstorage.reader.Constant.DEFAULT_BUFFER_SIZE);
}
@Override
public void prepare() {
}
@Override
public void startRead(RecordSender recordSender) {
LOG.info("Read start");
hdfsReaderUtil.getUgi().doAs((PrivilegedAction<Object>) () -> {
for (Object sourceFile : sourceFiles) {
PathMeta pathMeta = JSONObject.parseObject(JSON.toJSONString(sourceFile), PathMeta.class);
String fileName = pathMeta.getAbsolute();
LOG.info(String.format("Reading file : [%s]", fileName));
if (specifiedFileType.equalsIgnoreCase(Constant.TEXT)
|| specifiedFileType.equalsIgnoreCase(Constant.CSV)) {
InputStream inputStream = hdfsReaderUtil.getInputStream(fileName);
if(null == taskConfig.getString(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.COMPRESS, null)){
CompressionCodecFactory factory = new CompressionCodecFactory(hdfsReaderUtil.getConf());
try {
CompressionCodec codec = factory.getCodec(new Path(fileName));
if(null != codec){
inputStream = codec.createInputStream(inputStream);
}
} catch (IOException e) {
throw DataXException.asDataXException(HdfsReaderErrorCode.READ_FILE_ERROR, "Hdfs使用压缩工厂类CodecFactory生成文件流失败,message:"
+ e.getMessage());
}
}
UnstructuredStorageReaderUtil.readFromStream(inputStream, fileName, taskConfig,
recordSender, getTaskPluginCollector());
} else if (specifiedFileType.equalsIgnoreCase(Constant.ORC)) {
hdfsReaderUtil.orcFileStartRead(fileName, taskConfig, recordSender, getTaskPluginCollector());
} else if (specifiedFileType.equalsIgnoreCase(Constant.SEQ)) {
hdfsReaderUtil.sequenceFileStartRead(fileName, taskConfig, recordSender, getTaskPluginCollector());
} else if (specifiedFileType.equalsIgnoreCase(Constant.RC)) {
hdfsReaderUtil.rcFileStartRead(fileName, taskConfig, recordSender, getTaskPluginCollector());
} else if (specifiedFileType.equalsIgnoreCase(Constant.HFILE)) {
hdfsReaderUtil.hFileStartRead(fileName, taskConfig, recordSender, getTaskPluginCollector());
}else{
String message = "HdfsReader插件目前支持ORC, TEXT, CSV, SEQUENCE, HFile, RC格式的文件," +
"请将fileType选项的值配置为ORC, TEXT, CSV, SEQUENCE, HFile或者 RC";
throw DataXException.asDataXException(HdfsReaderErrorCode.FILE_TYPE_UNSUPPORT, message);
}
if (recordSender != null) {
recordSender.flush();
}
}
return null;
});
LOG.info("end read source files...");
}
@Override
public void post() {
}
@Override
public void destroy() {
}
@Override
public void startRead(ChannelOutput channelOutput) {
LOG.info("start read source HDFS files to stream channel...");
hdfsReaderUtil.getUgi().doAs((PrivilegedAction<Object>) () ->{
for(Object sourceFile : sourceFiles){
PathMeta pathMeta = JSONObject.parseObject(JSON.toJSONString(sourceFile), PathMeta.class);
String absolutePath = pathMeta.getAbsolute();
String relativePath = pathMeta.getRelative();
LOG.info(String.format("reading file : [%s]", absolutePath));
InputStream inputStream;
try{
Path path = new Path(absolutePath);
StreamMeta streamMeta = new StreamMeta();
streamMeta.setName(path.getName());
streamMeta.setAbsolutePath(absolutePath);
streamMeta.setRelativePath(relativePath);
OutputStream outputStream = channelOutput.createStream(streamMeta, encoding);
inputStream = hdfsReaderUtil.getInputStream(absolutePath);
UnstructuredStorageReaderUtil.readFromStream(inputStream, outputStream,
this.taskConfig);
}catch(IOException e){
throw DataXException.asDataXException(FrameworkErrorCode.CHANNEL_STREAM_ERROR, e);
}
}
return null;
});
}
}
} | true |
d3a025cf2abfec0e5f930647e4173ad02004f1db | Java | maksym-pasichnyk/Server-1.16.3-Remapped | /net/minecraft/world/level/block/grower/AbstractMegaTreeGrower.java | UTF-8 | 3,801 | 1.914063 | 2 | [] | no_license | /* */ package net.minecraft.world.level.block.grower;
/* */
/* */ import java.util.Random;
/* */ import javax.annotation.Nullable;
/* */ import net.minecraft.core.BlockPos;
/* */ import net.minecraft.server.level.ServerLevel;
/* */ import net.minecraft.world.level.BlockGetter;
/* */ import net.minecraft.world.level.WorldGenLevel;
/* */ import net.minecraft.world.level.block.Block;
/* */ import net.minecraft.world.level.block.Blocks;
/* */ import net.minecraft.world.level.block.state.BlockState;
/* */ import net.minecraft.world.level.chunk.ChunkGenerator;
/* */ import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
/* */ import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
/* */
/* */ public abstract class AbstractMegaTreeGrower
/* */ extends AbstractTreeGrower {
/* */ public boolean growTree(ServerLevel debug1, ChunkGenerator debug2, BlockPos debug3, BlockState debug4, Random debug5) {
/* 19 */ for (int debug6 = 0; debug6 >= -1; debug6--) {
/* 20 */ for (int debug7 = 0; debug7 >= -1; debug7--) {
/* 21 */ if (isTwoByTwoSapling(debug4, (BlockGetter)debug1, debug3, debug6, debug7)) {
/* 22 */ return placeMega(debug1, debug2, debug3, debug4, debug5, debug6, debug7);
/* */ }
/* */ }
/* */ }
/* */
/* 27 */ return super.growTree(debug1, debug2, debug3, debug4, debug5);
/* */ }
/* */
/* */ @Nullable
/* */ protected abstract ConfiguredFeature<TreeConfiguration, ?> getConfiguredMegaFeature(Random paramRandom);
/* */
/* */ public boolean placeMega(ServerLevel debug1, ChunkGenerator debug2, BlockPos debug3, BlockState debug4, Random debug5, int debug6, int debug7) {
/* 34 */ ConfiguredFeature<TreeConfiguration, ?> debug8 = getConfiguredMegaFeature(debug5);
/* */
/* 36 */ if (debug8 == null) {
/* 37 */ return false;
/* */ }
/* */
/* 40 */ ((TreeConfiguration)debug8.config).setFromSapling();
/* 41 */ BlockState debug9 = Blocks.AIR.defaultBlockState();
/* 42 */ debug1.setBlock(debug3.offset(debug6, 0, debug7), debug9, 4);
/* 43 */ debug1.setBlock(debug3.offset(debug6 + 1, 0, debug7), debug9, 4);
/* 44 */ debug1.setBlock(debug3.offset(debug6, 0, debug7 + 1), debug9, 4);
/* 45 */ debug1.setBlock(debug3.offset(debug6 + 1, 0, debug7 + 1), debug9, 4);
/* */
/* 47 */ if (debug8.place((WorldGenLevel)debug1, debug2, debug5, debug3.offset(debug6, 0, debug7))) {
/* 48 */ return true;
/* */ }
/* 50 */ debug1.setBlock(debug3.offset(debug6, 0, debug7), debug4, 4);
/* 51 */ debug1.setBlock(debug3.offset(debug6 + 1, 0, debug7), debug4, 4);
/* 52 */ debug1.setBlock(debug3.offset(debug6, 0, debug7 + 1), debug4, 4);
/* 53 */ debug1.setBlock(debug3.offset(debug6 + 1, 0, debug7 + 1), debug4, 4);
/* 54 */ return false;
/* */ }
/* */
/* */ public static boolean isTwoByTwoSapling(BlockState debug0, BlockGetter debug1, BlockPos debug2, int debug3, int debug4) {
/* 58 */ Block debug5 = debug0.getBlock();
/* 59 */ return (debug5 == debug1.getBlockState(debug2.offset(debug3, 0, debug4)).getBlock() && debug5 == debug1
/* 60 */ .getBlockState(debug2.offset(debug3 + 1, 0, debug4)).getBlock() && debug5 == debug1
/* 61 */ .getBlockState(debug2.offset(debug3, 0, debug4 + 1)).getBlock() && debug5 == debug1
/* 62 */ .getBlockState(debug2.offset(debug3 + 1, 0, debug4 + 1)).getBlock());
/* */ }
/* */ }
/* Location: C:\Users\Josep\Downloads\Decompile Minecraft\deobfuscated.jar!\net\minecraft\world\level\block\grower\AbstractMegaTreeGrower.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | true |
4df5880a56c57a1895ac76e1134a9735f77d1f86 | Java | aftabhabib/PlayMax.TV | /app/src/main/java/hkapps/playmxtv/Services/Requester.java | UTF-8 | 3,782 | 2.34375 | 2 | [] | no_license | package hkapps.playmxtv.Services;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by hkfuertes on 25/04/2017.
*/
public class Requester {
public static void request(Context context, Requestable requestable, Response.Listener<String> listener){
if (listener == null) {
listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// nothing to be done
}
};
}
switch (requestable.getMethod()){
case Request.Method.GET:
GET_request(context,requestable,listener);
break;
case Request.Method.POST:
POST_request(context,requestable,listener);
break;
}
}
public static void request(Context context, Requestable requestable){
Response.Listener<String> listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// nothing to be done
}
};
switch (requestable.getMethod()){
case Request.Method.GET:
GET_request(context,requestable,listener);
break;
case Request.Method.POST:
POST_request(context,requestable,listener);
break;
}
}
private static void GET_request(Context context, Requestable requestable, Response.Listener<String> listener){
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(requestable.getMethod(), requestable.getUrl(), listener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Requester",error.getLocalizedMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private static void POST_request(Context context, final Requestable requestable, Response.Listener<String> listener){
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(requestable.getMethod(), requestable.getUrl(), listener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Requester",error.getLocalizedMessage());
}
}){
@Override
protected Map<String,String> getParams(){
return requestable.getBody();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public interface Requestable{
String getUrl();
int getMethod();
Map<String, String> getBody();
}
}
| true |
be5c4e58082c372360c68b2205a3263166e2e7ae | Java | libaolucky/SSmKuangjia01 | /test/spring13zhujieDi/AdminServiceImpl.java | UTF-8 | 580 | 2.234375 | 2 | [] | no_license | package spring13zhujieDi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("adminService")
public class AdminServiceImpl implements AdminService{
//@Resource //相当于我们 xml中的注入 注解1: 这个注解是 tomcat提供的 byName
@Autowired //注解2: 是spring提供的,多用这个, byType
private AdminDAO adminDAO;
@Override
public void selectAll() {
//service层 调用了 dao层---> 即:service 依赖了 dao层
adminDAO.selectAll();
}
}
| true |
bbbbd04f444707f1a7a71a18090a43dbafb99b91 | Java | phamdinhhai0810/suristoreshop | /src/main/java/com/suristore/shop/repo/ProductRepository.java | UTF-8 | 219 | 1.632813 | 2 | [] | no_license | package com.suristore.shop.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.suristore.shop.domain.Product;
public interface ProductRepository extends JpaRepository<Product, Integer> {
} | true |
a1273917e2e4208475554c7c72a2eebc26f82252 | Java | S180231891/java_data_structure_Test | /src/LeetCode/zbg_027.java | UTF-8 | 938 | 3.796875 | 4 | [] | no_license | package LeetCode;
//从数组中删除指定的数
public class zbg_027 {
public static void main(String[] args) {
int[] nums = {1,1,1,2,3,4,4,5,7};
int val=4;
zbg_27 text = new zbg_27();
int res = text.removeElement(nums,val);
System.out.println(res);
}
}
class zbg_27 {
public int removeElement(int[] nums, int val) {
int temp = 0;
for (int i=0;i<nums.length;i++){
if (nums[i]!=val){
nums[temp++] = nums[i];
}
}
return temp;
}
//倒着删除,无序排列
public int Remove(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
} | true |
34abab552f68194cd7a3e2b89f09ea341494593f | Java | HOEINNKIM/Self_Study | /Do_it_Algorithm_of_Java/src/chap02/_005_CardConv.java | UTF-8 | 2,543 | 3.8125 | 4 | [] | no_license | package chap02;
import java.util.Scanner;
public class _005_CardConv {
public static int cardConvR(int x, int r, char[] d) {
int digits = 0; //변환 후의 자릿수
String dchar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
do {
d[digits++] = dchar.charAt(x%r); //r로 나눈 나머지 값을 dchar에서 뽑아 저장.
x /= r; //x를 r로 나눈 몫으로 변경
} while(x != 0);
return digits;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int no; //변환하려는 정수
int cd; //기수
int dno; //변환 후의 자릿수
int retry; //한번 더?
char[] cno = new char[32];
System.out.println("10진수를 기수 변환합니다.");
do {
do {
System.out.print("변환하는 음이 아닌 정수 : ");
no = stdIn.nextInt();
}while(no<0);
do {
System.out.print("어떤 진수로 변환할까요? (2~36) : ");
cd = stdIn.nextInt();
} while(cd<2||cd>36);
dno = cardConvR(no, cd, cno);
System.out.print(cd + "진수로는 ");
for(int i = dno - 1; i>=0; i--) {
System.out.print(cno[i]);
}
System.out.println("입니다.");
System.out.print("한번 더 할까요? (1.예 / 2. 아니요) : ");
retry = stdIn.nextInt();
} while(retry == 1);
System.out.println("10진수를 기수 변환하여 윗자리부터 나타냅니다.");
do {
do {
System.out.print("변환하는 음이 아닌 정수 : ");
no = stdIn.nextInt();
}while(no<0);
do {
System.out.print("어떤 진수로 변환할까요? (2~36) : ");
cd = stdIn.nextInt();
} while(cd<2||cd>36);
dno = cardConvR(no, cd, cno);
System.out.print(cd + "진수로는 ");
for(int i = 0; i<=dno-1; i++) {
System.out.print(cno[i]);
}
System.out.println("입니다.");
System.out.print("한번 더 할까요? (1.예 / 2. 아니요) : ");
retry = stdIn.nextInt();
} while(retry == 1);
}
//윗자리를 앞에 넣어두는 메서드 만들어보기
//x : 바꾸려는 정수, r : 기수, d : 위치를 윗자리부터 차곡차곡 쌓는 배열
public static int cardConv(int x, int r, char[] d) {
int digits = 0; //변환 후의 자릿수
String dchar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
do {
d[digits++] = dchar.charAt(x%r);
x /= r;
}while(x!=0);
//배열의 순서를 바꾸는 방법을 사용
for(int i= 0; i < digits / 2; i++) {
char temp = d[i];
d[i] = d[digits-i-1];
d[digits-i-1] = temp;
}
return digits;
}
} | true |
1c54fae70edda6d0e4d74dbb7cef4b37f343faad | Java | SebasGA19/Prueba | /doublelinkedlist/DoubleLinkedList.java | UTF-8 | 11,027 | 3.421875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package doublelinkedlist;
import java.util.Iterator;
/**
*
* @author Repre
*/
public class DoubleLinkedList implements ListInterface, Iterable<ListNode>{
public ListNode Start;
public ListNode End;
public int size;
private ListNode inode;
public DoubleLinkedList() {
this.Start = null;
this.End = null;
this.size = 0;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return Start == null;
}
@Override
public void clear() {
Start = null;
End = null;
size = 0;
}
@Override
public Object getHead() {
return Start;
}
@Override
public Object getTail() {
return End;
}
public int GetIndex(Object object){
for(int i=0;i<this.size;i++){
if(object==this.Get(i)){
return i;
}
}
throw new IndexOutOfBoundsException("Object not in list");
}
public Object Get(int index) {
if (isEmpty() == true) {
throw new IndexOutOfBoundsException("List is empty");
}
if (index >= this.size) {
throw new IndexOutOfBoundsException("Index out of range");
}
ListNode current = this.Start;
for (int list_index = 0; list_index < this.size; list_index++) {
if (list_index == index) {
return current.Value;
}
current = current.Next;
}
// It will never execute this
return null;
}
public ListNode GetNode(int index) {
if (isEmpty() == true) {
throw new IndexOutOfBoundsException("List is empty");
}
if (index >= this.size) {
throw new IndexOutOfBoundsException("Index out of range");
}
ListNode current = this.Start;
for (int list_index = 0; list_index < this.size; list_index++) {
if (list_index == index) {
return current;
}
current = current.Next;
}
// It will never execute this
return null;
}
@Override
public ListNode search(Object object) {
Iterator<ListNode> i = this.iterator();
ListNode inode;
while ((inode = i.next()) != null) {
if (inode.getObject().toString().equals(object.toString())) {
return inode;
}
}
i = this.RevIterator();
while ((inode = i.next()) != null) {
if (inode.getObject().toString().equals(object.toString())) {
return inode;
}
}
return null;
}
@Override
public boolean add(Object value) {
try {
this.insertTail(value);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean insert(ListNode node, Object object) {
try {
if (node.Next == null) {
add(object);
} else {
ListNode newNode = new ListNode(object);
newNode.Next = node.Next;
node.Next = newNode;
}
size++;
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean insert(Object ob, Object object) {
try {
if (ob != null) {
ListNode node = this.search(ob);
if (node != null) {
return insert(node, object);
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public boolean insertTail(Object value){
try{
if (isEmpty() == true) {
this.Start = new ListNode(value);
this.End = this.Start;
this.Start.Before=null;
} else {
ListNode old_end_node = this.End;
this.End = new ListNode(value);
this.End.Before = old_end_node;
old_end_node.Next = this.End;
}
this.size++;
return true;
}
catch (Exception e) {
return false;
}
}
@Override
public boolean insertHead(Object value){
try{
if (isEmpty() == true) {
this.Start = new ListNode(value);
this.End = this.Start;
this.Start.Before=null;
} else {
Start = new ListNode(value, Start);
Start.Before=null;
}
this.size++;
return true;
}
catch (Exception e) {
return false;
}
}
public void Remove(int index) {
if (isEmpty() == true) {
throw new IndexOutOfBoundsException("List is empty");
}
if (index >= this.size) {
throw new IndexOutOfBoundsException("Index out of range");
}
if (this.size == 1) {
// The list has only one Node
this.Start = null;
this.End = null;
} else if (index == 0) {
// First Node
this.Start = this.Start.Next;
this.Start.Before = null;
} else if (index == this.size - 1) {
// Last Node
this.End = this.End.Before;
this.End.Next = null;
} else {
// Any middle node
ListNode current = this.Start;
for (int list_index = 0; list_index < this.size; list_index++) {
if (list_index == index) {
// Node1 -> Node2 -> Node3
// Node1 -> Node3
current.Before.Next = current.Next;
current.Next.Before = current.Before;
break;
}
current = current.Next;
}
}
this.size--;
}
/*
Provisional method, not final version
*/
@Override
public boolean remove(ListNode node) {
try {
int index = this.GetIndex(node.getObject());
this.Remove(index);
return true;
} catch (Exception e) {
return false;
}
}
/*
Provissional method, not final version
*/
@Override
public boolean remove(Object object) {
try {
int index = this.GetIndex(object);
this.Remove(index);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean contains(Object object) {
if(this.search(object)==null){
return false;
}
else{
return true;
}
}
@Override
public Object[] toArray(){
Object[] arrayOfObjects = new Object[this.size];
for(int i=0;i<this.size;i++){
arrayOfObjects[i]=this.Get(i);
}
return arrayOfObjects;
}
@Override
public Object[] toArray(Object[] arrayOfObjects){
for(int i=0;i<this.size;i++){
arrayOfObjects[i]=this.Get(i);
}
return arrayOfObjects;
}
@Override
public ListNode getBeforeTo(ListNode node){
ListNode current= this.search(node.getObject());
current= current.Before;
return current;
}
@Override
public Object getNextTo(ListNode node){
ListNode current= this.search(node.getObject());
current= current.Next;
return current;
}
@Override
public DoubleLinkedList subList(ListNode from, ListNode to) {
if (this.contains(from.getObject()) == true && this.contains(to.getObject()) == true) {
int indexFrom = this.GetIndex(from.getObject());
int indexTo = this.GetIndex(to.getObject());
DoubleLinkedList subList = new DoubleLinkedList();
for (int i = 0; i < this.size; i++) {
if (i >= indexFrom && i <= indexTo) {
subList.add(this.Get(i));
}
}
return subList;
}
else{
throw new IndexOutOfBoundsException("At least one of the two nodes are not in list");
}
}
@Override
public Iterator<ListNode> iterator() {
inode = Start;
return new Iterator<ListNode>() {
@Override
public boolean hasNext() {
return inode != null;
}
@Override
public ListNode next() {
if (inode != null) {
ListNode tmp = inode;
inode = inode.Next;
return tmp;
} else {
return null;
}
}
};
}
public Iterator<ListNode> RevIterator() {
inode = End;
return new Iterator<ListNode>(){
@Override
public ListNode next() {
if (inode != null) {
ListNode tmp = inode;
inode = inode.Before;
return tmp;
} else {
return null;
}
}
@Override
public boolean hasNext() {
return inode.Before != null;
}
};
}
@Override
public Object getBeforeTo() {
return null;
}
@Override
public Object getNextTo() {
return null;
}
@Override
public DoubleLinkedList sortList()
{
DoubleLinkedList sortedList= new DoubleLinkedList();
// Node current will point to head
ListNode current = this.Start, index = null;
int temp;
if (this.Start == null) {
return null;
}
else {
while (current != null) {
index = current.Next;
while (index != null) {
if ((int)current.Value > (int)index.Value) {
temp = (int)current.Value;
current.Value = index.Value;
index.Value = temp;
}
index = index.Next;
}
sortedList.add(current.Value);
current = current.Next;
}
}
return sortedList;
}
}
| true |
14ee4fc5fe1ca65e83169664cc2cd867b8dd9697 | Java | apollo78124/Selenium-WebCrawler-Project | /src/VideoToMp3.java | UTF-8 | 1,510 | 2.609375 | 3 | [] | no_license | import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class VideoToMp3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int songNumber;
String[] links;
Scanner scn = new Scanner(System.in);
boolean pageTurn = false;
System.out.println("How many songs?");
songNumber = scn.nextInt();
links = new String[songNumber];
for (int i = 0; i < songNumber; i++) {
System.out.println("Paste the link");
links[i] = scn.next();
}
for (int i = 0; i < links.length; i++) {
try {
System.setProperty("webdriver.chrome.driver",
"chromedriver.exe");
WebDriver driver = new ChromeDriver();;
try {
driver.get("https://ytmp3.cc/");
WebElement url = driver.findElement(By.id("input"));
url.click();
url.sendKeys(links[i]);
WebElement convertForm = driver.findElement(By.id("submit"));
convertForm.submit();
Thread.sleep(1500);
//WebElement download = driver.findElement(By.id("download"));
//download.click();
} catch (Exception e) {
System.out.println("Thread " + links[i] + " interrupted.");
}
} catch (Exception e) {
System.out.println("Thread " + links[i] + " interrupted.");
}
System.out.println("Thread " + links[i] + " exiting.");
}
}
}
| true |
ed8127c6160ad7dc629e8276aca8dbe0e1a81be2 | Java | sdmms1/DB_Project | /src/main/java/train/model/User.java | UTF-8 | 721 | 2.5625 | 3 | [] | no_license | package train.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
@Getter
@Setter
@Builder
public class User {
private String username;
private String id; // Identity card
private String phone;
private String password;
// TODO: Add order list
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
// Shouldn't generate users with same id or phone
return id.equals(user.id) || phone.equals(user.phone);
}
@Override
public int hashCode() {
return Objects.hash(id, phone);
}
}
| true |
9bec9e5aa4bd7570b7d7e4c2bf7b833a1ac22588 | Java | hsf301/StemCellsManager | /app/src/main/java/com/huashengfu/StemCellsManager/fragment/interaction/DynamicCommentFragment.java | UTF-8 | 7,041 | 1.851563 | 2 | [] | no_license | package com.huashengfu.StemCellsManager.fragment.interaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huashengfu.StemCellsManager.Constants;
import com.huashengfu.StemCellsManager.R;
import com.huashengfu.StemCellsManager.activity.interaction.DynamicCommentActivity;
import com.huashengfu.StemCellsManager.adapter.BaseAdapter;
import com.huashengfu.StemCellsManager.adapter.interaction.DynamicCommentAdapter;
import com.huashengfu.StemCellsManager.entity.interaction.DynamicComment;
import com.huashengfu.StemCellsManager.entity.response.PageResponse;
import com.huashengfu.StemCellsManager.fragment.BaseFragment;
import com.huashengfu.StemCellsManager.http.HttpHelper;
import com.huashengfu.StemCellsManager.http.callback.JsonCallback;
import com.huashengfu.StemCellsManager.http.utils.ResponseUtils;
import com.huashengfu.StemCellsManager.loadmore.EndlessRecyclerOnScrollListener;
import com.huashengfu.StemCellsManager.loadmore.LoadMoreWrapper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
//动态评论
public class DynamicCommentFragment extends BaseFragment {
private Unbinder unbinder;
@BindView(R.id.rv_list)
RecyclerView rvList;
@BindView(R.id.swiperefresh)
SwipeRefreshLayout mySwipeRefreshLayout;
@BindView(R.id.empty)
View emptyPage;
private int pageNum = 1;
private int pageSize = 10;
private int pageCount = 1;
private DynamicCommentAdapter adapter;
private LoadMoreWrapper loadMoreWrapper;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_interaction_dynamic_comment, null);
unbinder = ButterKnife.bind(this, view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvList.setLayoutManager(layoutManager);
adapter = new DynamicCommentAdapter();
adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<DynamicComment>() {
@Override
public void onItemClick(View view, DynamicComment dynamicComment) {
Intent intent = new Intent(getContext(), DynamicCommentActivity.class);
intent.putExtra(Constants.Tag.data, dynamicComment);
startActivity(intent);
}
});
loadMoreWrapper = new LoadMoreWrapper(adapter);
rvList.setAdapter(loadMoreWrapper);
rvList.setLayoutManager(layoutManager);
rvList.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
@Override
public void onLoadMore() {
if(pageNum <= pageCount){
loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
mySwipeRefreshLayout.postDelayed(()->{
doQuery();
}, 1000);
}else{
loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
}
}
});
mySwipeRefreshLayout.setColorSchemeColors(
getResources().getColor(R.color.colorSwipeRefreshLayout1),
getResources().getColor(R.color.colorSwipeRefreshLayout2),
getResources().getColor(R.color.colorSwipeRefreshLayout3)
);
mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pageNum = 1;
doQuery();
}
});
mySwipeRefreshLayout.post(()->{
mySwipeRefreshLayout.setRefreshing(true);
doQuery();
});
return view;
}
private void doQuery(){
OkGo.<JSONObject>get(HttpHelper.Url.Service.Comment.list)
.headers(HttpHelper.Params.Authorization, SPUtils.getInstance().getString(Constants.Tag.token))
.params(HttpHelper.Params.pageSize, pageSize)
.params(HttpHelper.Params.pageNum, pageNum)
.params(HttpHelper.Params.category, Constants.Type.Comment.DynamicComment)
.execute(new JsonCallback<JSONObject>() {
@Override
public void onSuccess(Response<JSONObject> response) {
super.onSuccess(response);
try {
if(ResponseUtils.ok(response.body())){
JSONObject data = ResponseUtils.getData(response.body());
if(data.has(Constants.Tag.comment)){
JSONObject consult = data.getJSONObject(Constants.Tag.comment);
PageResponse<DynamicComment> pageResponse = new Gson().fromJson(
consult.toString(),
new TypeToken<PageResponse<DynamicComment>>(){}.getType());
if(pageNum == 1)
adapter.clear();
adapter.addAll(pageResponse.getList());
adapter.notifyDataSetChanged();
pageCount = pageResponse.getTotalPage();
pageNum++;
}
}else{
showMessage(ResponseUtils.getMsg(response.body()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
super.onFinish();
mySwipeRefreshLayout.setRefreshing(false);
loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
if(adapter.getItemCount() == 0){
showEmpty(emptyPage, R.string.text_empty_dynamic_comment, true);
}else{
showEmpty(emptyPage, false);
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
}
| true |
736e3de53095e984aca5ed8e7286057444d7c9d0 | Java | wmjxq/untitled | /src/RJDZ/ER1.java | UTF-8 | 3,931 | 3.234375 | 3 | [] | no_license | package RJDZ;
import java.util.Scanner;
/***
* @date 2021-04-14 12:59
* @aythor weimengjie
*/
public class ER1 {
boolean flag = true;
String name; //用户的名字
String sj; //电脑出的quan
String number; // 你出的quan
int random = 1 + (int) (Math.random() * 3); //创建一个随机数 (0-9)
Scanner scanner = new Scanner(System.in);
int namefs;
int dnfs;
int dn; //电脑的角色
String Myname;// 你的名字
public void sayhello() {
System.out.println("*********************************");
System.out.println("**猜拳,开始**");
System.out.println("*********************************");
System.out.println("出拳规则:1.剪刀 2.石头 3.布");
System.out.println("请选择对方角色(1:刘备2:孙权3:曹操");
int dn = scanner.nextInt(); //电脑的角色
switch (dn) {
case 1:
name = "刘备";
break;
case 2:
name = "孙权";
break;
case 3:
name = "曹操";
break;
}
System.out.println("请输入你的姓名");
String Myname = scanner.next();
System.out.println(Myname + "VS" + name);
}
// 对决类
public void duijue() {
do {
System.out.println("要开始吗?");
String ks = scanner.next();
flag = true;
if (ks.equals("y")) {
System.out.println("请出拳:1.剪刀 2.石头 3.步(输入对应数字):");
int cq = scanner.nextInt();
switch (cq) {
case 1:
number = "剪刀";
System.out.println("你出" + number);
break;
case 2:
number = "石头";
System.out.println("你出" + number);
break;
case 3:
number = "布";
System.out.println("你出" + number);
}
if (random == 1) {
sj = "剪刀";
} else if (random == 2) {
sj = "石头";
} else if (random == 3) {
sj = "布";
} else {
System.out.println("随机错误");
}
System.out.println(name + "出" + sj);
flag = true;
if (cq == random && (number.equals(sj))) {
System.out.println("平局");
} else if (cq > random && random + 1 == cq || cq + 2 == random) {
System.out.println("你赢");
namefs++;
System.out.println( "你的分数"+namefs);
} else if ((random > cq) && (cq + 1 == random) || random + 2 == cq) {//
System.out.println(name + "赢");
dnfs++;
System.out.println( name+"分数"+dnfs);
}
jxm();
flag = false;
System.out.println("您已推出");
}
}while(flag);
}
public void jxm() {
System.out.println("还要继续吗?");
String a = scanner.next();
if (a.equals("y")) {
duijue();
}if(a.equals("n")){
flag = false;
}
}
}
| true |
5c2b49435df92c53ad66dcee9cf6de1c33055158 | Java | thomasreardon/HelloServlet | /HelloServlets/src/main/java/enums/Delegate.java | UTF-8 | 1,303 | 2.484375 | 2 | [] | no_license | package enums;
import controllers.AcceptedReimbursements;
import controllers.AddReimbursement;
import controllers.Controller;
import controllers.DeniedReimbursements;
import controllers.LoginController;
import controllers.ViewReimbursements;
import controllers.UpdateReimbursement;
import controllers.PendingReimbursements;
import controllers.AllReimbursements;
public enum Delegate {
LOGIN(new LoginController()),
ADDREIMBURSEMENT(new AddReimbursement()),
VIEWREIMBURSEMENT(new ViewReimbursements()),
UPDATEREIMBURSEMENT(new UpdateReimbursement()),
ACCEPTEDREIMBURSEMENT(new AcceptedReimbursements()),
DENIEDREIMBURSEMENT(new DeniedReimbursements()),
PENDINGREIMBURSEMENT(new PendingReimbursements()),
ALLREIMBURSEMENT(new AllReimbursements()),
NOT_FOUND(null);
public Controller controller;
private Delegate(Controller controller) {
this.controller = controller;
}
public static Delegate getDelegate(String str) {
if (str == null) return NOT_FOUND;
// compare str to each delegate
// return that delegate if the string
// matches
//String upper = str.toUpperCase();
for(Delegate delegate : Delegate.values()) {
if(str.toUpperCase().equals(delegate.name())) {
return delegate;
}
}
return NOT_FOUND;
}
}
| true |
ffa082917339f0033a5e5c3855f47a0370026c3f | Java | javaschoolrzn4/test2 | /test2code/src/test2/q05/TestImports2.java | UTF-8 | 877 | 2.84375 | 3 | [] | no_license | package test2.q05;
import test2.q05.MyClass;
public class TestImports2 {
public static void main(String[] args) {
MyClass.howdy(); // line 14
System.out.print(MyClass.myConstant + " "); // line 15
// System.out.print(myConstant + " "); // line 16
// howdy(); // line 17
// System.out.print(mc.instVar + " "); // line 18
// System.out.print(instVar + " "); // line 19
}
}
// What is the result?
// Choose all that apply:
// A. howdy 343 343 howdy 42 42
// B. Compilation fails due to an error on line 14.
// C. Compilation fails due to an error on line 15.
// !D. Compilation fails due to an error on line 16.
// !E. Compilation fails due to an error on line 17.
// !F. Compilation fails due to an error on line 18.
// !G. Compilation fails due to an error on line 19.
| true |
6630354295bc0eb3cc317c1c46bb3e6e00b01750 | Java | liuhaipen9/my_springcloud | /stream_hello/src/main/java/com/cn/stream_hello/util/Sink.java | UTF-8 | 342 | 1.820313 | 2 | [] | no_license | package com.cn.stream_hello.util;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
/**
* @author 刘海鹏
* @iphone 13714872954
* @date 2019/5/3上午10:20
*/
public interface Sink {
String INPUT="input";
@Input(Sink.INPUT)
SubscribableChannel input();
}
| true |
f936202261d0294a6a8fe9e12692e621c6d09005 | Java | OlegSedov/ConditionerHomework | /src/test/java/ru/netology/domain/ConditionerTest.java | UTF-8 | 2,308 | 2.796875 | 3 | [] | no_license | package ru.netology.domain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ConditionerTest {
@Test
public void shouldIncreaseCurrentTemperature() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(25);
conditioner.increaseCurrentTemperature();
assertEquals(26, conditioner.getCurrentTemperature());
}
@Test
public void shouldDecreaseCurrentTemperature() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(25);
conditioner.decreaseCurrentTemperature();
assertEquals(24, conditioner.getCurrentTemperature());
}
@Test
public void shouldIncreaseToMax() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(36);
conditioner.increaseCurrentTemperature();
assertEquals(36, conditioner.getCurrentTemperature());
}
@Test
public void shouldDecreaseToMin() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(15);
conditioner.decreaseCurrentTemperature();
assertEquals(15, conditioner.getCurrentTemperature());
}
@Test
public void shouldCurrentUnderMin() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(14);
conditioner.decreaseCurrentTemperature();
assertEquals(15, conditioner.getCurrentTemperature());
}
@Test
public void shouldCurrentOverMax() {
Conditioner conditioner = new Conditioner();
conditioner.setMaxTemperature(36);
conditioner.setMinTemperature(15);
conditioner.setCurrentTemperature(37);
conditioner.increaseCurrentTemperature();
assertEquals(36, conditioner.getCurrentTemperature());
}
} | true |
0a78790b928bdd28143635fcc583529e01b1475e | Java | dengjiaping/babywatch | /src/com/mobao/watch/adapter/SOSphoneAdapter.java | UTF-8 | 2,365 | 1.914063 | 2 | [] | no_license | package com.mobao.watch.adapter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mb.zjwb1.R;
import com.mobao.watch.activity.LoginActivity;
import com.mobao.watch.activity.MbApplication;
import com.mobao.watch.activity.PhoneNumberManagerActivity;
import com.mobao.watch.activity.WhiteohoneActivity;
import com.mobao.watch.util.AddWhitephoneDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SOSphoneAdapter extends BaseAdapter {
private String[] jsonarray;
private Context context;
public SOSphoneAdapter(Context context, String[] jsonarray) {
this.jsonarray = jsonarray;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
if (jsonarray != null) {
return jsonarray.length;
}
return 0;
}
@Override
public Object getItem(int index) {
// TODO Auto-generated method stub
if (jsonarray != null && index < jsonarray.length) {
return jsonarray[index];
}
return null;
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(int index, View contextview, ViewGroup parent) {
// TODO Auto-generated method stub
if (contextview == null) {
contextview = LayoutInflater.from(context).inflate(
R.layout.phone_number_listview_item, parent, false);
}
TextView phone = (TextView) contextview.findViewById(R.id.tv_number_item_number);
phone.setText(jsonarray[index]);
final int i=index;
ImageView iv_number_item_delete=(ImageView) contextview.findViewById(R.id.iv_number_item_delete);
iv_number_item_delete.setVisibility(View.GONE);
return contextview;
}
}
| true |
f27af819a36ca07d055e7051c7f78311e097682f | Java | ragilgm/bootcampG2academi | /day14/LoginRegex/App.java | UTF-8 | 2,287 | 3.078125 | 3 | [] | no_license | import java.io.IOException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws IOException {
LoginRegex login = new LoginRegex();
boolean checkRegex = false;
Scanner input = new Scanner(System.in);
String argument;
try {
argument = args[0];
} catch (Exception e) {
argument = "";
}
if (argument.equals("")) {
System.out.println("Silahkan masukan argument untuk Membuat File config untuk login");
System.out.println("Contoh : java App 'config'");
} else {
argument = args[0];
while (!checkRegex) {
String username;
String password = null;
System.out.println("Masukan Username : ");
username = input.nextLine();
if (!login.checkValidUsername(username)) {
checkRegex = false;
} else {
System.out.println("Masukan Password : ");
password = input.nextLine();
if (!login.checkValidPassword(password)) {
checkRegex = false;
} else {
login.createConfigProperties(argument, username, password);
System.out.println("file berhasil di buat\n");
checkRegex = true;
}
}
}
System.out.println("test login");
System.out.println("LOGIN REGEX....");
String konfirmasi = "";
while (!konfirmasi.equals("n")) {
System.out.println("Login test.. \n");
System.out.println("Masukan Username : ");
String username = input.nextLine();
if (!login.checkValidUsername(username)) {
System.out.println(
"\nApakah anda akan mencoba lagi ? tekan <enter> juka ya dan tekan (n) jika tidak");
konfirmasi = input.nextLine();
} else {
System.out.println("Masukan Password : ");
String password = input.nextLine();
if (!login.checkValidPassword(password)) {
System.out.println(
"\nApakah anda akan mencoba lagi ? tekan <enter> juka ya dan tekan (n) jika tidak");
konfirmasi = input.nextLine();
} else {
boolean LoginValidation = login.LoginValidation(username, password);
if (!LoginValidation) {
System.out.println(
"\nApakah anda akan mencoba lagi ? tekan <enter> juka ya dan tekan (n) jika tidak");
konfirmasi = input.nextLine();
} else {
break;
}
}
}
}
}
input.close();
}
}
| true |
a620ac28060dabd1fe37846bad093b3402b89725 | Java | StonePanda/javaeetraining | /src/main/java/com/hos/one/dao/CityhotelMapper.java | UTF-8 | 492 | 1.835938 | 2 | [] | no_license | package com.hos.one.dao;
import com.hos.one.entity.Cityhotel;
import java.util.List;
public interface CityhotelMapper {
int deleteByPrimaryKey(Integer hotelid);
int insert(Cityhotel record);
int insertSelective(Cityhotel record);
Cityhotel selectByPrimaryKey(Integer hotelid);
//根据城市名查找hotelid
List<Integer> selectByCityName(String cityname);
int updateByPrimaryKeySelective(Cityhotel record);
int updateByPrimaryKey(Cityhotel record);
} | true |
cd745d98247816bd1ad3a48f53c544c0b1e93c4e | Java | a12791602/lotto-cms-core-wl | /src/main/java/com/hhly/cmscore/cms/remote/service/status/operate/OperationOrderEnum.java | UTF-8 | 877 | 2.1875 | 2 | [] | no_license | package com.hhly.cmscore.cms.remote.service.status.operate;
import com.hhly.cmscore.cms.remote.service.status.entity.UpdateStatusBO;
/**
* @desc 订单执行操作
* @author jiangwei
* @date 2017年3月15日
* @company 益彩网络科技公司
* @version 1.0
*/
public enum OperationOrderEnum {
/**
* 检查方案
*/
CHECK {
public boolean execute(UpdateStatusBO po, IOrderOperation operation) {
operation.ckeckOrder(po);
return true;
}
},
/**
* 禁止检查方案
*/
FORBID {
public boolean execute(UpdateStatusBO po, IOrderOperation operation) {
operation.forbidCkeckOrder(po);
return true;
}
},
/**
* 撤单
*/
REVOKE {
public boolean execute(UpdateStatusBO po, IOrderOperation operation) {
operation.revoke(po);
return true;
}
};
public abstract boolean execute(UpdateStatusBO po, IOrderOperation operation);
}
| true |
997acb29a1e65f214b3a9a4d3492836c152eab14 | Java | wangle2/skt | /dataproviderex/src/main/java/net/meyki/data/client/response/GetAmountResponse.java | UTF-8 | 696 | 1.757813 | 2 | [] | no_license | package net.meyki.data.client.response;
import net.meyki.data.client.domain.AmountBean;
import net.meyki.data.client.domain.ImageItem;
import net.meyki.data.json.JavaCommonResponse;
import java.util.ArrayList;
import java.util.List;
public class GetAmountResponse extends JavaCommonResponse {
/**
*
*/
private static final long serialVersionUID = 2561290964247180613L;
public List<AmountBean> list = new ArrayList<>() ; // JSONArray
public String amountTotal ; // out String YES 消费券总金额
public String getAmountTotal; // out String YES 消费券领取总金额
public String amountUse ; //out String YES 消费券消费总金额
}
| true |
efcf8cef4d43cf57aa8985f6ff1930ab7e741b25 | Java | cristoferJaimez/Mouth-System | /src/java/Modelos/AgendaDAO.java | UTF-8 | 1,200 | 2.4375 | 2 | [] | no_license | package Modelos;
import Config.Conexion;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Cristo
*/
public class AgendaDAO {
Connection con;
PreparedStatement ps;
ResultSet rs;
Conexion cn = new Conexion();
/*para registar*/
int res;
// listar citas
public List ListarCitas() {
String ConsultaSQL = "SELECT * FROM cita ";
/*lista de citas*/
List<Agenda_cita> citas = new ArrayList();
try {
con = cn.Conexion();
ps = con.prepareStatement(ConsultaSQL);
rs = ps.executeQuery();
while (rs.next()) {
Agenda_cita agn_cit = new Agenda_cita();
agn_cit.setFecha_hora(rs.getDate("fecha_hora"));
agn_cit.setId_paciente(rs.getInt("id_paciente"));
citas.add(agn_cit);
}
} catch (SQLException e) {
System.out.println("Error: "+ e);
}
return citas;
}
}
| true |
12475967ed2849c3fb7037728c35a9d43f27af60 | Java | wq960824/test | /src/paixu/Charu.java | GB18030 | 1,157 | 2.9375 | 3 | [] | no_license | package paixu;
import com.alibaba.fastjson.JSON;
public class Charu {
public static void main(String args[]){
int arr[]={1,4,5,32,2,53,13,4,98};
Charu charu=new Charu();
int brr[]=charu.chaRu(arr);
System.out.println(JSON.toJSONString(brr));
String crr[]={"","ѧ","","Ӣ","ѧ"};
String drr[]= charu.HashString(crr);
System.out.println(JSON.toJSONString(drr));
}
public int [] chaRu(int arr[]){
int temp;
for (int i=1;i<arr.length;i++){
for (int j=0;j<i;j++){
if (arr[j]<arr[i]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return arr;
}
public String [] HashString(String arr[]){
String temp;
for (int i=1;i<arr.length;i++){
for (int j=0;j<i;j++){
if (arr[j].hashCode()<arr[i].hashCode()){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return arr;
}
}
| true |
5313601a3e1c23198862321ea7823bf24b65e6c0 | Java | dordsor21/MissionGameAware | /src/main/java/me/dordsor21/MissionGameAware/challenges/Survival/impl/Burn.java | UTF-8 | 2,350 | 2.625 | 3 | [] | no_license | package me.dordsor21.MissionGameAware.challenges.Survival.impl;
import me.dordsor21.MissionGameAware.MissionGameAware;
import me.dordsor21.MissionGameAware.challenges.Survival.TimedChallenge;
import me.dordsor21.MissionGameAware.challenges.impl.SurvivalChallenge;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Burn extends TimedChallenge {
private static final String[] messages = new String[] {"&cBurn&f. You have 2 minutes to earn double points.",
"You have 2 minutes to &cBurn&f. This is worth double points.", "&cBurn&f in the next 2 minutes for double points."};
private final GrowTreeListener listener;
public Burn() {
Bukkit.getScheduler().runTask(MissionGameAware.plugin, () -> Bukkit.broadcastMessage(
ChatColor.translateAlternateColorCodes('&', SurvivalChallenge.cPr + messages[new Random().nextInt(3)])));
Bukkit.getScheduler().runTaskLater(MissionGameAware.plugin, this::finish, 2400L);
Bukkit.getPluginManager().registerEvents((listener = new GrowTreeListener()), MissionGameAware.plugin);
}
@Override
public void finish() {
HandlerList.unregisterAll(listener);
SurvivalChallenge.running.remove(this);
}
private static final class GrowTreeListener implements Listener {
private final Set<Player> completed = new HashSet<>();
@EventHandler
public void onDeath(EntityDamageEvent e) {
if (e.getEntityType() != EntityType.PLAYER) {
return;
}
Player p = (Player) e.getEntity();
if (completed.contains(p)) {
return;
}
switch (e.getCause()) {
case FIRE:
case FIRE_TICK:
case LAVA:
completed.add(p);
SurvivalChallenge.playerScores.merge(p, 2, Integer::sum);
p.sendTitle("", ChatColor.translateAlternateColorCodes('&', "2 points obtained!"), 0, 70, 20);
}
}
}
}
| true |
434754c967341616f5d0fca693385226bfb47c95 | Java | RyanTech/android-21 | /car_android/Car_washing/src/main/java/com/kplus/car/carwash/module/OrderStatus.java | UTF-8 | 3,256 | 2.671875 | 3 | [] | no_license | package com.kplus.car.carwash.module;
/**
* Description:订单状态
* <br/><br/>Created by Fu on 2015/5/19.
* <br/><br/>
*/
public enum OrderStatus {
PAYING(21), // 本地新加的,支付中,服务端好像没此状态
BOOKED(0), // 初始值,未下单
UNABLE_PAY(1), // 无法支付
PAY_PENDING(2), // 待支付
PAID(3), // 已支付
AUDIT_PENDING(5), // 待审核
AUDIT_FAILED(6), // 审核失败
ASSIGNED(7), // 已指派(审核通过)
HANDLING(10), // 服务中(处理中)
HANDLE_FAILED(11), // 处理失败
HANDLED(12), // 已完成(处理成功)
REFUND_PENDING(13), // 待退款
REFUNDED(14), // 已退款
REVIEWED(16), // 已评价
CLOSED(20), // 已关闭
DELETED(-1), // 已删除
UNKOWN(-2); // 未知
private final int value;
OrderStatus(int v) {
value = v;
}
public int value() {
return value;
}
public static OrderStatus valueOf(int v) {
switch (v) {
case 21:
return PAYING;
case 0:
return BOOKED;
case 1:
return UNABLE_PAY;
case 2:
return PAY_PENDING;
case 3:
return PAID;
case 5:
return AUDIT_PENDING;
case 6:
return AUDIT_FAILED;
case 7:
return ASSIGNED;
case 10:
return HANDLING;
case 11:
return HANDLE_FAILED;
case 12:
return HANDLED;
case 13:
return REFUND_PENDING;
case 14:
return REFUNDED;
case 16:
return REVIEWED;
case 20:
return CLOSED;
case -1:
return DELETED;
}
return UNKOWN;
}
public String readableName() {
switch (value) {
case 21:
return "支付中";
case 0:
return "已预定";
case 1:
return "无法支付";
case 2:
return "待支付";
case 3:
return "已支付";
case 5:
return "待审核";
case 6:
return "审核失败";
case 7:
return "已指派";
case 10:
return "服务中";
case 11:
return "处理失败";
case 12:
return "已完成";
case 13:
return "待退款";
case 14:
return "已退款";
case 16:
return "已评价";
case 20:
return "已关闭";
case -1:
return "已删除";
}
return "未知";
}
}
| true |
6c9bcbc53d5ebb3bc792320fcf682158c40bde4d | Java | sujanay/E-Commerce-Website | /Online-Shoes/src/java/Entities/ShoesValidation.java | UTF-8 | 6,275 | 3.03125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entities;
/**
*
* @author sujan
*/
public class ShoesValidation {
// check to see if the user has selecte the gender
// from the drop-down list
public static boolean validateGender(String gender, ShoesErrorList errors)
{
if(gender == null)
{
errors.setGenderMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered the brand?
public static boolean validateBrand(String brand, ShoesErrorList errors)
{
if(brand == null || brand.equals("select brand"))
{
errors.setBrandMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered the Model?
// We compare the trimmed value with the empty string.
public static boolean validateModel(String model, ShoesErrorList errors)
{
if("".equals(model.trim()))
{
errors.setModelMissing(true);
return false;
}
// we compare the string to a regular expression which specifies the value
// must only contain digits and letters.
String modRegEx = "(\\w+\\s*)+";
model = model.trim();
if(!model.matches(modRegEx))
{
errors.setModelIllegal(true);
return false;
}
else{
return true;
}
}
// Has the user entered the color?
// We compare the trimmed value with the empty string
public static boolean validateColor(String color, ShoesErrorList errors)
{
if("".equals(color.trim()))
{
errors.setColorMissing(true);
return false;
}
// we compare the string to a regular expression which specifies
// the value must only contain letters.
String colRegEx = "([a-zA-Z]\\s*)+";
color = color.trim();
if(!color.matches(colRegEx))
{
errors.setColorIllegal(true);
return false;
}
else{
return true;
}
}
// Has the user entered the size?
public static boolean validateSize(String size, ShoesErrorList errors)
{
if(size == null || size.equals("select size"))
{
errors.setSizeMissing(true);
return false;
}
else{
return true;
}
}
// Validate whether the user has entered style or not
public static boolean validateStyle(String style, ShoesErrorList errors)
{
if(style == null || style.equals("select style"))
{
errors.setStyleMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered NON-EMPTY, NUMERIC price?
public static boolean validatePrice(String price, ShoesErrorList errors)
{
if("".equals(price.trim()))
{
errors.setPriceMissing(true);
return false;
}
// check to ensure numeric input is entered by the user
else{
// we attempt to parse the price to double
try{
double numPrice = Double.parseDouble(price);
// If the price is numeric then we check to see if it is
// positive (as the price of an item can't be negative)
if(numPrice < 0){
errors.setPriceNegative(true);
return false;
}
}catch(NumberFormatException e){
errors.setPriceNotNumeric(true);
return false;
}
}
return true;
}
// Has the user entered the Insole information?
public static boolean validateInsole(String insole, ShoesErrorList errors)
{
if(insole == null || insole.equals("select insole"))
{
errors.setInsoleMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered the Material information?
public static boolean validateMaterial(String material, ShoesErrorList errors)
{
if(material == null || material.equals("select material"))
{
errors.setMaterialMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered the Occasion information?
public static boolean validateOccasion(String occasion, ShoesErrorList errors)
{
if(occasion == null || occasion.equals("select occasion"))
{
errors.setOccasionMissing(true);
return false;
}
else{
return true;
}
}
// Has the user entered NON-EMPTY, INTEGER quantity?
public static boolean validateQuantity(String quantity, ShoesErrorList errors)
{
if("".equals(quantity.trim()))
{
errors.setQuantityMissing(true);
return false;
}
// check to ensure numeric input is entered by the user
else{
// we attempt to parse the price to int
try{
int numQuantity = Integer.parseInt(quantity);
// If the price is numeric then we check to see if it is
// positive (as the Quantity of an item can't be negative)
if(numQuantity < 0){
errors.setQuantityNegative(true);
return false;
}
}catch(NumberFormatException e){
errors.setQuantityNotNumeric(true);
return false;
}
}
return true;
}
}
| true |
952393fdf76f435ab3fb6b8852c9e0a8a4ade727 | Java | luoxue1107/java | /JavaEE/Nov/day02/src/main/java/cn/kgc/tangcco/dao/impl/CourseDaoImpl.java | UTF-8 | 2,778 | 2.59375 | 3 | [] | no_license | package cn.kgc.tangcco.dao.impl;
import cn.kgc.tangcco.dao.CourseDao;
import cn.kgc.tangcco.pojo.Course;
import cn.kgc.tangcco.util.jdbcUtil.JDBCUtil;
import com.alibaba.fastjson.JSON;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author 李庆华
* @Description
* @date 2020/11/2 20:10
*/
public class CourseDaoImpl implements CourseDao {
@Override
public List<Course> selectAllCourse() {
List<Course> courseList = new ArrayList<>();
JDBCUtil jdbcUtil = new JDBCUtil();
String sql = "select * from course";
ResultSet resultSet = jdbcUtil.executeQuery(sql);
try {
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
System.out.println(resultSet.getInt("id"));
courseList.add(new Course(resultSet.getInt("id"), resultSet.getString("name")));
}
courseList.forEach(course -> System.out.println(JSON.toJSONString(course)));
return courseList;
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
jdbcUtil.close();
}
return courseList;
}
@Override
public Course selectCourseById(Integer id) {
JDBCUtil jdbcUtil = new JDBCUtil();
String sql = "select * from course where id=?";
ResultSet resultSet = jdbcUtil.executeQuery(sql, id);
Course course = null;
try {
if (resultSet.next()) {
course = new Course(resultSet.getInt("id"), resultSet.getString("name"));
}
return course;
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
jdbcUtil.close();
}
return course;
}
@Override
public Integer insertCourse(Course course) {
JDBCUtil jdbcUtil = new JDBCUtil();
String sql ="insert into class(name) values (?)";
Integer integer = jdbcUtil.executeUpdate(sql, course.getId(), course.getName());
jdbcUtil.close();
return integer;
}
@Override
public Integer updateCourse(Course course) {
JDBCUtil jdbcUtil = new JDBCUtil();
String sql ="update course set name = ? where id = ?";
Integer integer = jdbcUtil.executeUpdate(sql, course.getName(), course.getId());
jdbcUtil.close();
return integer;
}
@Override
public Integer deleteCourse(Integer id) {
JDBCUtil jdbcUtil= new JDBCUtil();
String sql = "delete from course where id = ?";
Integer integer = jdbcUtil.executeUpdate(sql, id);
jdbcUtil.close();
return integer;
}
}
| true |
6c15aae524662885554d8fd21e029788f071100a | Java | limkokwing-lesotho/gradebook | /src/luct/utils/TypeUtils.java | UTF-8 | 2,871 | 2.90625 | 3 | [] | no_license | package luct.utils;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.apache.commons.lang3.math.NumberUtils;
public class TypeUtils {
public static boolean isString(Class<?> type) {
return String.class.equals(type);
}
public static boolean isLocalDate(Field field){
return isLocalDate(field.getType());
}
public static boolean isLocalDate(Class<?> type){
return LocalDate.class.isAssignableFrom(type);
}
public static boolean isLocalDateTime(Field field){
return isLocalDateTime(field.getType());
}
public static boolean isLocalDateTime(Class<?> type){
return LocalDateTime.class.isAssignableFrom(type);
}
public static boolean isEnum(Field field){
return isEnum(field.getType());
}
public static boolean isEnum(Class<?> type){
return type.isEnum();
}
public static boolean isBoolean(Field field) {
return isBoolean(field.getType());
}
public static boolean isBoolean(Class<?> type) {
return Boolean.class.equals(type)
|| boolean.class.equals(type);
}
public static boolean isNumeric(Field field){
return isNumeric(field.getType());
}
public static boolean isNumeric(Class<?> type){
return Byte.class.equals(type)
|| byte.class.equals(type)
|| Short.class.equals(type)
|| short.class.equals(type)
|| Integer.class.equals(type)
|| int.class.equals(type)
|| Long.class.equals(type)
|| long.class.equals(type)
|| Float.class.equals(type)
|| float.class.equals(type)
|| Double.class.equals(type)
|| double.class.equals(type);
}
public static Object castType(Object value, Class<?> type) {
Object o = null;
try {
if(type == String.class){
o = String.valueOf(value);
}
else if(type == Double.class || type == Double.TYPE){
o = numericCast(value, type, 0.0);
}
else if (type == Float.class ||type == Float.TYPE){
o = numericCast(value, type, 0.0);
}
else if(type == Integer.class || type == Integer.TYPE){
o = Integer.valueOf(String.valueOf(value));
}
else if(type == Long.class || type == Long.TYPE){
o = Long.valueOf(String.valueOf(value));
}
else if(type == Boolean.class || type == Boolean.TYPE){
o = Boolean.valueOf(String.valueOf(value));
}
else{
o = type.cast(value);
}
}
catch (NumberFormatException e) {
o = 0;
}
catch(ClassCastException e) {
e.printStackTrace();
}
return o;
}
private static Object numericCast(Object value, Class<?> type, Object defaultValue) {
Object o;
if(Double.class.equals(value.getClass())){
o = value;
}
else if(String.class.equals(value.getClass())){
String str = (String) value;
if(NumberUtils.isCreatable(str)){
o = Double.valueOf(str);
}
else{
o = defaultValue;
}
}
else{
o = type.cast(value);
}
return o;
}
}
| true |
92c93ec13a67f279b68e4094d7b941d942093c00 | Java | technocode/com.wa_2.21.2 | /src/main/java/X/C235516j.java | UTF-8 | 394 | 1.703125 | 2 | [] | no_license | package X;
import com.google.android.gms.common.api.Scope;
import java.util.Comparator;
/* renamed from: X.16j reason: invalid class name and case insensitive filesystem */
public final class C235516j implements Comparator {
@Override // java.util.Comparator
public final int compare(Object obj, Object obj2) {
return ((Scope) obj).A01.compareTo(((Scope) obj2).A01);
}
}
| true |
f24da87505fbcbcc4a7f4b2022fd1f4652a4a360 | Java | JBOuser/M06_acces_a_dades-Activitat1 | /src/activitat_1_1/CheckIfFileExists.java | UTF-8 | 520 | 3.296875 | 3 | [] | no_license | package activitat_1_1;
import java.io.File;
import java.util.Scanner;
public class CheckIfFileExists
{
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter a path of folder/file: ");
String path1 = scanner1.next();
scanner1.close();
File dir1 = new File(path1);
if (dir1.exists() == true)
{
System.out.println("'"+dir1+"' found :D");
}
else
{
System.out.println("'"+dir1+"' not found XD");
}
}
}
| true |
ca13bd692d1f5c954c5fcc6c225526f5a1bbf1d3 | Java | ChrisHadzhikolev/S3-CB03-Group3 | /PAAS/src/main/java/com/video/recognition/VideoStream.java | UTF-8 | 1,182 | 2.28125 | 2 | [] | no_license | package com.video.recognition;
import org.opencv.core.Core;
import org.opencv.osgi.OpenCVNativeLoader;
import org.opencv.videoio.VideoCapture;
public class VideoStream {
static{
String osName = System.getProperty("os.name");
String opencvpath = System.getProperty("user.dir");
if(osName.startsWith("Windows")) {
int bitness = Integer.parseInt(System.getProperty("sun.arch.data.model"));
if(bitness == 32) {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
else if (bitness == 64) {
opencvpath=opencvpath+"\\opencv\\x64\\";
} else {
opencvpath=opencvpath+"\\opencv\\x86\\";
}
}
else if(osName.equals("Mac OS X")){
opencvpath = opencvpath+"Your path to .dylib";
}
System.out.println(opencvpath);
System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
System.load(opencvpath + "opencv_ffmpeg300_64" + ".dll");
}
public static void main(String[] args){
VideoCapture capture = new VideoCapture();
capture.open("http://192.168.11.3:8081/video");
}
} | true |
afbbca0dabafe93bc626ca543ac0c2771c254467 | Java | alphakys/chapter05 | /src/com/javaex/ex01/ByteStreamApp.java | UTF-8 | 683 | 3.125 | 3 | [] | no_license | package com.javaex.ex01;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteStreamApp {
public static void main(String[] args) throws IOException{
InputStream in = new FileInputStream("C:\\Users\\gys11\\OneDrive\\바탕 화면\\JavaStudy\\img.jpg");
OutputStream out = new FileOutputStream("C:\\Users\\gys11\\OneDrive\\바탕 화면\\JavaStudy\\byteimg.jpg");
while(true) {
int bData = in.read();
out.write(bData);
if(bData==-1) {
break;
}
}
out.close();
in.close();
}
}
| true |
f0b8d2e39efc0ada17d8d477b4de43c1a4b19309 | Java | iris61/PicMask | /app/src/main/java/com/lovecoding/yangying/ImageDetail/CommentsInfo.java | UTF-8 | 2,234 | 2.421875 | 2 | [] | no_license | package com.lovecoding.yangying.ImageDetail;
/**
* Created by yangying on 18/2/26.
*/
public class CommentsInfo {
private int commentId = 0;
private String userName;
private int imageId;
private int replyToComment;
private String replyToCommentUser = null;
private String content;
private String time;
private int hostComment = 0;
public CommentsInfo(int commentId, String userName, int imageId, int replyToComment, String content, String time, int hostComment) {
this.commentId = commentId;
this.userName = userName;
this.imageId = imageId;
this.replyToComment = replyToComment;
this.content = content;
this.time = time;
this.hostComment = hostComment;
}
public CommentsInfo(String userName, int imageId, int replyToComment, String content, String time, int hostComment) {
this.userName = userName;
this.imageId = imageId;
this.replyToComment = replyToComment;
this.content = content;
this.time = time;
this.hostComment = hostComment;
}
public CommentsInfo() {}
public void setCommentId (int commentId) {this.commentId = commentId; }
public void setImageId (int imageId) {this.imageId = imageId; }
public void setUserName (String userName) {this.userName = userName; }
public void setReplyToComment (int replyToComment) {this.replyToComment = replyToComment; }
public void setContent (String content) {this.content = content;}
public void setTime (String time) {this.time = time;}
public void setHostComment (int hostComment) {this.hostComment = hostComment;}
public void setReplyToCommentUser (String replyToCommentUser) {this.replyToCommentUser = replyToCommentUser; }
public int getCommentId() {return this.commentId;}
public int getImageId() {return this.imageId;}
public String getUserName() {return this.userName;}
public int getReplyToComment() {return this.replyToComment;}
public String getContent() {return this.content;}
public String getTime() {return this.time;}
public int getHostComment() {return this.hostComment;}
public String getReplyToCommentUser() {return this.replyToCommentUser;}
}
| true |
338d1ead35a6b6990c406ec1b61eb14e1c971ffa | Java | Bendar01/JavaRush-2 | /2.JavaCore/src/com/javarush/task/task14/task1413/CompItem.java | UTF-8 | 139 | 1.851563 | 2 | [] | no_license | package com.javarush.task.task14.task1413;
/**
* Created by Admin on 15.08.2017.
*/
public interface CompItem {
String getName();
}
| true |
186ad54075f2e7aec9905736135615f7b40106d2 | Java | mihilt/lemon-biz | /lemon-biz/src/main/java/com/lemon/lemonbiz/approval/model/vo/Approval.java | UTF-8 | 482 | 1.585938 | 2 | [] | no_license | package com.lemon.lemonbiz.approval.model.vo;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Approval {
private String key;
private int typeKey;
private String memId;
private String title;
private String content;
private Date draftDate;
private Date writeDate;
private String status;
private int IsDeleted;
}
| true |
eb52a18ef20e1bb749cd139c7d2ac37f4b8e019a | Java | moutainhigh/payment-11 | /payment-infrastructure/src/main/java/com/ymatou/payment/infrastructure/db/model/BussinessOrderPo.java | UTF-8 | 13,865 | 1.8125 | 2 | [] | no_license | package com.ymatou.payment.infrastructure.db.model;
import java.math.BigDecimal;
import java.util.Date;
public class BussinessOrderPo {
/**
* CHAR(36) 默认值[(newid())] 必填<br>
*
*/
private String bussinessOrderId;
/**
* VARCHAR(16) 必填<br>
*
*/
private String appId;
/**
* VARCHAR(16) 必填<br>
*
*/
private String originAppId;
/**
* VARCHAR(32) 必填<br>
*
*/
private String orderId;
/**
* VARCHAR(16) 必填<br>
*
*/
private String payType;
/**
* DECIMAL(18,4) 必填<br>
*
*/
private BigDecimal orderPrice;
/**
* VARCHAR(3) 必填<br>
*
*/
private String currencyType;
/**
* INTEGER(10)<br>
*
*/
private Integer userId;
/**
* INTEGER(10) 必填<br>
*
*/
private Integer version;
/**
* VARCHAR(36) 必填<br>
*
*/
private String traceId;
/**
* VARCHAR(16) 必填<br>
*
*/
private String orderTime;
/**
* VARCHAR(64)<br>
*
*/
private String thirdPartyUserId;
/**
* INTEGER(10)<br>
*
*/
private Integer thirdPartyUserType;
/**
* VARCHAR(16) 必填<br>
*
*/
private String clientIp;
/**
* VARCHAR(256)<br>
*
*/
private String callbackUrl;
/**
* VARCHAR(256) 必填<br>
*
*/
private String notifyUrl;
/**
* VARCHAR(64) 必填<br>
*
*/
private String productName;
/**
* VARCHAR(512)<br>
*
*/
private String productDesc;
/**
* VARCHAR(512)<br>
*
*/
private String productUrl;
/**
* INTEGER(10) 必填<br>
*
*/
private Integer codePage;
/**
* VARCHAR(512)<br>
*
*/
private String ext;
/**
* VARCHAR(512)<br>
*
*/
private String memo;
/**
* VARCHAR(8) 必填<br>
*
*/
private String signMethod;
/**
* INTEGER(10) 必填<br>
*
*/
private Integer bizCode;
/**
* TIMESTAMP(23,3) 默认值[(getdate())] 必填<br>
*
*/
private Date createdTime;
/**
* TIMESTAMP(23,3)<br>
*
*/
private Date lastUpdatedTime;
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*
*/
private Integer orderStatus;
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*
*/
private Integer notifyStatus;
/**
* TIMESTAMP(23,3)<br>
*
*/
private Date notifyTime;
/**
* BINARY(8) 必填<br>
*
*/
private byte[] dataVersion;
/**
* CHAR(36) 默认值[(newid())] 必填<br>
*/
public String getBussinessOrderId() {
return bussinessOrderId;
}
/**
* CHAR(36) 默认值[(newid())] 必填<br>
*/
public void setBussinessOrderId(String bussinessOrderId) {
this.bussinessOrderId = bussinessOrderId == null ? null : bussinessOrderId.trim();
}
/**
* VARCHAR(16) 必填<br>
*/
public String getAppId() {
return appId;
}
/**
* VARCHAR(16) 必填<br>
*/
public void setAppId(String appId) {
this.appId = appId == null ? null : appId.trim();
}
/**
* VARCHAR(16) 必填<br>
*/
public String getOriginAppId() {
return originAppId;
}
/**
* VARCHAR(16) 必填<br>
*/
public void setOriginAppId(String originAppId) {
this.originAppId = originAppId == null ? null : originAppId.trim();
}
/**
* VARCHAR(32) 必填<br>
*/
public String getOrderId() {
return orderId;
}
/**
* VARCHAR(32) 必填<br>
*/
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
/**
* VARCHAR(16) 必填<br>
*/
public String getPayType() {
return payType;
}
/**
* VARCHAR(16) 必填<br>
*/
public void setPayType(String payType) {
this.payType = payType == null ? null : payType.trim();
}
/**
* DECIMAL(18,4) 必填<br>
*/
public BigDecimal getOrderPrice() {
return orderPrice;
}
/**
* DECIMAL(18,4) 必填<br>
*/
public void setOrderPrice(BigDecimal orderPrice) {
this.orderPrice = orderPrice;
}
/**
* VARCHAR(3) 必填<br>
*/
public String getCurrencyType() {
return currencyType;
}
/**
* VARCHAR(3) 必填<br>
*/
public void setCurrencyType(String currencyType) {
this.currencyType = currencyType == null ? null : currencyType.trim();
}
/**
* INTEGER(10)<br>
*/
public Integer getUserId() {
return userId;
}
/**
* INTEGER(10)<br>
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
* INTEGER(10) 必填<br>
*/
public Integer getVersion() {
return version;
}
/**
* INTEGER(10) 必填<br>
*/
public void setVersion(Integer version) {
this.version = version;
}
/**
* VARCHAR(36) 必填<br>
*/
public String getTraceId() {
return traceId;
}
/**
* VARCHAR(36) 必填<br>
*/
public void setTraceId(String traceId) {
this.traceId = traceId == null ? null : traceId.trim();
}
/**
* VARCHAR(16) 必填<br>
*/
public String getOrderTime() {
return orderTime;
}
/**
* VARCHAR(16) 必填<br>
*/
public void setOrderTime(String orderTime) {
this.orderTime = orderTime == null ? null : orderTime.trim();
}
/**
* VARCHAR(64)<br>
*/
public String getThirdPartyUserId() {
return thirdPartyUserId;
}
/**
* VARCHAR(64)<br>
*/
public void setThirdPartyUserId(String thirdPartyUserId) {
this.thirdPartyUserId = thirdPartyUserId == null ? null : thirdPartyUserId.trim();
}
/**
* INTEGER(10)<br>
*/
public Integer getThirdPartyUserType() {
return thirdPartyUserType;
}
/**
* INTEGER(10)<br>
*/
public void setThirdPartyUserType(Integer thirdPartyUserType) {
this.thirdPartyUserType = thirdPartyUserType;
}
/**
* VARCHAR(16) 必填<br>
*/
public String getClientIp() {
return clientIp;
}
/**
* VARCHAR(16) 必填<br>
*/
public void setClientIp(String clientIp) {
this.clientIp = clientIp == null ? null : clientIp.trim();
}
/**
* VARCHAR(256)<br>
*/
public String getCallbackUrl() {
return callbackUrl;
}
/**
* VARCHAR(256)<br>
*/
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl == null ? null : callbackUrl.trim();
}
/**
* VARCHAR(256) 必填<br>
*/
public String getNotifyUrl() {
return notifyUrl;
}
/**
* VARCHAR(256) 必填<br>
*/
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl == null ? null : notifyUrl.trim();
}
/**
* VARCHAR(64) 必填<br>
*/
public String getProductName() {
return productName;
}
/**
* VARCHAR(64) 必填<br>
*/
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
/**
* VARCHAR(512)<br>
*/
public String getProductDesc() {
return productDesc;
}
/**
* VARCHAR(512)<br>
*/
public void setProductDesc(String productDesc) {
this.productDesc = productDesc == null ? null : productDesc.trim();
}
/**
* VARCHAR(512)<br>
*/
public String getProductUrl() {
return productUrl;
}
/**
* VARCHAR(512)<br>
*/
public void setProductUrl(String productUrl) {
this.productUrl = productUrl == null ? null : productUrl.trim();
}
/**
* INTEGER(10) 必填<br>
*/
public Integer getCodePage() {
return codePage;
}
/**
* INTEGER(10) 必填<br>
*/
public void setCodePage(Integer codePage) {
this.codePage = codePage;
}
/**
* VARCHAR(512)<br>
*/
public String getExt() {
return ext;
}
/**
* VARCHAR(512)<br>
*/
public void setExt(String ext) {
this.ext = ext == null ? null : ext.trim();
}
/**
* VARCHAR(512)<br>
*/
public String getMemo() {
return memo;
}
/**
* VARCHAR(512)<br>
*/
public void setMemo(String memo) {
this.memo = memo == null ? null : memo.trim();
}
/**
* VARCHAR(8) 必填<br>
*/
public String getSignMethod() {
return signMethod;
}
/**
* VARCHAR(8) 必填<br>
*/
public void setSignMethod(String signMethod) {
this.signMethod = signMethod == null ? null : signMethod.trim();
}
/**
* INTEGER(10) 必填<br>
*/
public Integer getBizCode() {
return bizCode;
}
/**
* INTEGER(10) 必填<br>
*/
public void setBizCode(Integer bizCode) {
this.bizCode = bizCode;
}
/**
* TIMESTAMP(23,3) 默认值[(getdate())] 必填<br>
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* TIMESTAMP(23,3) 默认值[(getdate())] 必填<br>
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* TIMESTAMP(23,3)<br>
*/
public Date getLastUpdatedTime() {
return lastUpdatedTime;
}
/**
* TIMESTAMP(23,3)<br>
*/
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*/
public Integer getOrderStatus() {
return orderStatus;
}
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*/
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*/
public Integer getNotifyStatus() {
return notifyStatus;
}
/**
* INTEGER(10) 默认值[((0))] 必填<br>
*/
public void setNotifyStatus(Integer notifyStatus) {
this.notifyStatus = notifyStatus;
}
/**
* TIMESTAMP(23,3)<br>
*/
public Date getNotifyTime() {
return notifyTime;
}
/**
* TIMESTAMP(23,3)<br>
*/
public void setNotifyTime(Date notifyTime) {
this.notifyTime = notifyTime;
}
/**
* BINARY(8) 必填<br>
*/
public byte[] getDataVersion() {
return dataVersion;
}
/**
* BINARY(8) 必填<br>
*/
public void setDataVersion(byte[] dataVersion) {
this.dataVersion = dataVersion;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table PP_BussinessOrder
*
* @mbggenerated Mon Feb 27 18:24:23 CST 2017
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", bussinessOrderId=").append(bussinessOrderId);
sb.append(", appId=").append(appId);
sb.append(", originAppId=").append(originAppId);
sb.append(", orderId=").append(orderId);
sb.append(", payType=").append(payType);
sb.append(", orderPrice=").append(orderPrice);
sb.append(", currencyType=").append(currencyType);
sb.append(", userId=").append(userId);
sb.append(", version=").append(version);
sb.append(", traceId=").append(traceId);
sb.append(", orderTime=").append(orderTime);
sb.append(", thirdPartyUserId=").append(thirdPartyUserId);
sb.append(", thirdPartyUserType=").append(thirdPartyUserType);
sb.append(", clientIp=").append(clientIp);
sb.append(", callbackUrl=").append(callbackUrl);
sb.append(", notifyUrl=").append(notifyUrl);
sb.append(", productName=").append(productName);
sb.append(", productDesc=").append(productDesc);
sb.append(", productUrl=").append(productUrl);
sb.append(", codePage=").append(codePage);
sb.append(", ext=").append(ext);
sb.append(", memo=").append(memo);
sb.append(", signMethod=").append(signMethod);
sb.append(", bizCode=").append(bizCode);
sb.append(", createdTime=").append(createdTime);
sb.append(", lastUpdatedTime=").append(lastUpdatedTime);
sb.append(", orderStatus=").append(orderStatus);
sb.append(", notifyStatus=").append(notifyStatus);
sb.append(", notifyTime=").append(notifyTime);
sb.append(", dataVersion=").append(dataVersion);
sb.append("]");
return sb.toString();
}
} | true |
f3298d24be2fd92274b9a78f6a54ec580ee25ebe | Java | bflowtoolbox/app | /plugins/org.bflow.toolbox.diagram.extensions/src/org/bflow/toolbox/extensions/IDiagramCreationWizard.java | UTF-8 | 783 | 2.171875 | 2 | [] | no_license | package org.bflow.toolbox.extensions;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.ui.IWorkbench;
/**
* Describes a wizard that creates a Bflow*-related diagram.
*
* @author Arian Storch<arian.storch@bflow.org>
* @since 2019-01-27
*
*/
public interface IDiagramCreationWizard extends IWizard {
/**
* Notifies the instance to initialize itself.
*
* @param workbench Workbench
* @param selection Selection
*/
void init(IWorkbench workbench, IStructuredSelection selection);
/** Returns a short hint that describes the diagram the wizard creates. */
String getShortHint();
/** Returns the created diagram */
Resource getDiagram();
} | true |
a75d56450cd834ed3d1157900e69776bbc9bc85f | Java | acierto/aws-chat | /aws-chat-client/src/main/java/com.acierto.awschat.client/ScheduledMessageSender.java | UTF-8 | 5,112 | 2.546875 | 3 | [
"MIT"
] | permissive | package com.acierto.awschat.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
@Component
public class ScheduledMessageSender {
private static final Logger log = LoggerFactory.getLogger(ScheduledMessageSender.class);
private static final int MAX_RECONNECT_ATTEMPTS = 5;
private static final int NUM_OF_NAMES = 1006;
private static final int NUM_OF_MESSAGES = 531;
@Value("${aws.server.url}")
private String serverUrl;
private final List<String> messages;
private final List<String> names;
private final RestTemplate restTemplate;
private final String userName;
private boolean isConnected;
private String token;
public ScheduledMessageSender() throws IOException {
messages = readResource("messages.txt");
names = readResource("names.txt");
restTemplate = new RestTemplate();
userName = getRandomUserName();
}
@Scheduled(fixedRateString = "${aws.chat.message.scheduled-interval}")
public void sendMessages() {
if (!isConnected) {
repeatableConnect(userName, MAX_RECONNECT_ATTEMPTS);
}
sendMessage(token, getRandomMessage());
}
@Scheduled(initialDelayString = "${aws.chat.message.stop-after}", fixedDelay = Long.MAX_VALUE)
public void stopMessaging() {
scheduledTasks.forEach((k, v) -> {
if (k instanceof ScheduledMessageSender) {
disconnect(token);
v.cancel(false);
System.exit(0);
}
});
}
@Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}
private String getRandomUserName() {
return pickRandomly(names, 0, NUM_OF_NAMES);
}
private String getRandomMessage() {
return pickRandomly(messages, 0, NUM_OF_MESSAGES);
}
private String pickRandomly(List<String> list, int min, int max) {
int nameOrder = new Random().ints(min, max).findFirst().getAsInt();
return list.get(nameOrder);
}
private List<String> readResource(String fileName) throws IOException {
byte[] content = Files.readAllBytes(ResourceUtils.getFile(String.format("classpath:%s", fileName)).toPath());
return Arrays.asList(new String(content).split("\\r?\\n"));
}
private void repeatableConnect(String name, int maxAttempts) {
int attempt = 0;
ResponseEntity<String> connectResponse;
while (attempt < maxAttempts) {
connectResponse = connect(name);
if (connectResponse.getStatusCode() != HttpStatus.OK) {
attempt++;
} else {
isConnected = true;
token = connectResponse.getBody();
return;
}
}
throw new RuntimeException("Couldn't connect");
}
private ResponseEntity<String> connect(String name) {
String url = String.format("%s/connect?name=%s", serverUrl, name);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
log.info("[{}] Received response {}", response.getStatusCode(), response.getBody());
return response;
}
private void sendMessage(String token, String message) {
String url = String.format("%s/send?token=%s", serverUrl, token);
ResponseEntity<String> response = restTemplate.postForEntity(url, message, String.class);
log.info("[{}] Received response {}", response.getStatusCode(), response.getBody());
}
private void disconnect(String token) {
String url = String.format("%s/disconnect?token=%s", serverUrl, token);
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
log.info("[{}] Received response {}", response.getStatusCode(), response.getBody());
}
private final Map<Object, ScheduledFuture<?>> scheduledTasks = new IdentityHashMap<>();
private class CustomTaskScheduler extends ThreadPoolTaskScheduler {
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
}
}
| true |
56448416a6ad46972c02adc9a7c9687708665a33 | Java | easyGuyLyn/lt_b_pai | /app/src/main/java/com/dawoo/lotterybox/adapter/hall/parent/MarqueeTextViewHolder.java | UTF-8 | 1,333 | 2.03125 | 2 | [] | no_license | package com.dawoo.lotterybox.adapter.hall.parent;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.dawoo.lotterybox.R;
import com.dawoo.lotterybox.adapter.hall.child.BaseViewHolder;
import com.dawoo.lotterybox.bean.Bulletin;
import com.dawoo.lotterybox.util.NoticeDialog;
import com.dawoo.lotterybox.util.SoundUtil;
import com.dawoo.lotterybox.view.view.MarqueeTextView;
import com.dawoo.lotterybox.view.view.UserNoticeDialog;
import java.util.ArrayList;
import java.util.List;
/**
* Created by b on 18-4-12.
* 公告
*/
public class MarqueeTextViewHolder extends BaseViewHolder {
private final Context mContext;
MarqueeTextView mNoticeTv;
public MarqueeTextViewHolder(Context context, View itemView) {
super(itemView);
mContext = context;
mNoticeTv = itemView.findViewById(R.id.notice_tv);
}
public void bindView(List<Bulletin> bulletins) {
ArrayList<String> titleList = new ArrayList<>();
for (Bulletin bean : bulletins)
titleList.add(bean.getContent());
mNoticeTv.setTextArraysAndClickListener(titleList, view -> {
SoundUtil.getInstance().playVoiceOnclick();
UserNoticeDialog dialog = new UserNoticeDialog(mContext, titleList);
});
}
}
| true |
a6ce2069d6ab915978f306416bcbd10b4cddf6ee | Java | atulspatil/RN_Android_Native | /android/app/src/main/java/com/sample_android_ui/sample/CustomView.java | UTF-8 | 2,983 | 2.421875 | 2 | [] | no_license | package com.sample_android_ui.sample;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.react.views.image.ReactImageView;
import com.sample_android_ui.R;
/**
* Created by mmpkl05 on 12/14/17.
*/
public class CustomView extends LinearLayout{
private Context context;
private String message = "NOT SET";
public CustomView(Context context, String message) {
super(context);
this.context = context;
this.message = message;
init();
}
public void init() {
//Part 1: Don't need to copy BONUS part, this alone already integrate Android UI to RN native.
inflate(this.context, R.layout.multiplecamerastreamlayout, this);
//This can be viewed in Android Studio's Log Cat.
Log.i("Inflated XML", "ANDROID_SAMPLE_UI");
//BONUS: Create a button that writes a toast.
Button clickButton = (Button) findViewById(R.id.multipleCameraButton);
final Context _context = context;
clickButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
//Log into the Logcat of android studio. Filter by Info and ANDROID_SAMPLE_UI.
Log.i("Button get clicked", "ANDROID_SAMPLE_UI");
Toast toast = Toast.makeText(_context, message, Toast.LENGTH_LONG);
toast.show();
//PART 3: This is a sample to receive callback/events from Android to RN's JS and visa versa.
//Save to remove if don't need to care events sent
callNativeEvent();
//END OF PART 3
}
});
}
public void setMessage(String message) {
this.message = message;
}
//PART 3: Added Receive Event.
public void callNativeEvent() {
Log.i("Call Native Event", "ANDROID_SAMPLE_UI");
//This output a message to Javascript as an event.
WritableMap event = Arguments.createMap();
event.putString("customNativeEventMessage", "Emitted an event"); //Emmitting an event to Javascript
//Create a listener where that emits/send the text to JS when action is taken.
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"nativeClick", //name has to be same as getExportedCustomDirectEventTypeConstants in MyCustomReactViewManager
event);
}
}
| true |
85eb41e0fc36e3a371774bc99a81e2a6eae828a2 | Java | Chickenpowerrr/languagehelper | /src/main/java/com/gmail/chickenpowerrr/languagehelper/LanguageFile.java | UTF-8 | 1,860 | 2.75 | 3 | [] | no_license | package com.gmail.chickenpowerrr.languagehelper;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class LanguageFile extends LanguageContainer {
private final LanguageResource languageResource;
private final File file;
public LanguageFile(File file, LanguageResource languageResource) throws IOException {
super(file.getName().replace(".txt", ""), new FileInputStream(file));
this.file = file;
this.languageResource = languageResource;
updateTranslations();
}
private void updateTranslations() {
if (this.languageResource != null) {
addLines(this.languageResource.getTranslations().stream().filter(key -> !hasTranslation(key))
.map(key -> new HashMap.SimpleEntry<>(key, this.languageResource.getTranslation(key)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
}
private void addLines(Map<String, String> translations) {
try (FileOutputStream fileOutputStream = new FileOutputStream(this.file, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,
StandardCharsets.UTF_8);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
translations.forEach(this::addLine);
if (translations.size() > 0) {
bufferedWriter.write(
translations.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining(System.lineSeparator(), System.lineSeparator(), "")));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
266082358c6ad947fd97b9c56337fcda163a6180 | Java | dobulekill/jun_springcloud | /springloud_practice/common-domain/src/main/java/org/nr/tour/domain/util/EntityUtils.java | UTF-8 | 385 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | package org.nr.tour.domain.util;
import org.nr.tour.domain.IDEntity;
import org.springframework.util.StringUtils;
import java.util.UUID;
/**
* @author Wujun
*/
public class EntityUtils {
public static void preSave(IDEntity entity) {
if (StringUtils.isEmpty(entity.getId())) {
entity.setId(UUID.randomUUID().toString().replace("-", ""));
}
}
}
| true |
0e0918f346648a748037ec56d9ee5bef8dd0d849 | Java | Invictus252/JavaII_Final | /src/mclamud/Area.java | UTF-8 | 394 | 1.804688 | 2 | [] | no_license | package mclamud;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Area {
public String title = "";
public String gfx = "";
public ArrayList<String> items = new ArrayList<>();
public int[] exits = {0,0,0,0,0,0};
public Map<String, Player> players = new HashMap<>();
public String description = "";
String description2 = "";
} | true |
436b0f7ada0f5dc6dfc5ae06df970ddd74dd4ced | Java | wjq1028/zongsOpenGatewaySdk | /src/main/java/com/zongs365/open/api/response/order/OrderShippingResponse.java | UTF-8 | 666 | 1.835938 | 2 | [] | no_license | package com.zongs365.open.api.response.order;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zongs365.open.api.response.base.BaseResponse;
import com.zongs365.open.api.response.base.BaseResponseBody;
import lombok.Data;
public class OrderShippingResponse extends BaseResponse<OrderShippingResponse.OrderShippingResponseBody> {
@Override
public OrderShippingResponseBody getBody(){
return JSON.parseObject(getBodyStr(),new TypeReference<OrderShippingResponseBody>(){});
}
@Data
public static class OrderShippingResponseBody extends BaseResponseBody {
private Boolean success;
}
}
| true |
3e9c501d97a726024472c1d805a284351f438b09 | Java | k-gawel/FridgeApi | /src/main/java/org/california/service/model/WishListService.java | UTF-8 | 1,741 | 2.25 | 2 | [] | no_license | package org.california.service.model;
import org.california.model.entity.Account;
import org.california.model.entity.WishList;
import org.california.model.entity.utils.AccountDate;
import org.california.model.transfer.request.forms.WishListForm;
import org.california.repository.wishlist.WishListRepository;
import org.california.service.getter.GetterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class WishListService {
private final WishListRepository wishListRepository;
private final GetterService getterService;
@Autowired
public WishListService(WishListRepository wishListRepository, GetterService getterService) {
this.wishListRepository = wishListRepository;
this.getterService = getterService;
}
public WishList create(WishListForm form) {
WishList wishList = fromForm(form);
return wishListRepository.save(wishList);
}
public boolean archive(Account account, WishList wishList) {
if (!wishList.isStatus()) return false;
wishList.setStatus(false);
wishList.setArchived(new AccountDate(account));
return save(wishList);
}
public boolean save(WishList wishList) {
return wishListRepository.save(wishList) != null;
}
private WishList fromForm(WishListForm form) {
WishList wishList = new WishList();
wishList.setCreated(new AccountDate(form.author));
System.out.println("Created WishList " + wishList.getCreated().toString());
wishList.setDescription(form.description);
wishList.setName(form.name);
wishList.setPlace(form.place);
return wishList;
}
}
| true |
4b3aeddd9f3e4888ca2248a523d0733ea853a743 | Java | 14erHiker/Algorithms | /BT.java | UTF-8 | 4,116 | 3.265625 | 3 | [] | no_license | class BT {
public class Node {
T key;
Node parent = null;
Node right = null;
Node left = null;
public Node(T key){
this.key = key;
}
}
Node root = null;
int length = 0;
int height = 0;
T lastPrinted;
public int height(Node node) {
if(node == null) return -1;
int hl = height(node.left);
int hr = height(node.right);
int h = 1 + Math.max(hl, hr);
return h;
}
public void insert(T key){
Node n = new Node(key);
if(this.root == null){
root = n;
} else {
insertNode(this.root, n);
}
this.length++;
}
public void insertNode(Node current, Node node){
int cmp = node.key.compareTo(current.key);
if(cmp < 0){
if(current.left == null){
current.left = node;
node.parent = current;
} else {
insertNode(current.left, node);
}
} else {
if(current.right == null){
current.right = node;
node.parent = current;
} else {
insertNode(current.right, node);
}
}
}
public Node findNode(T key){
Node n = this.root;
while(n.key != key){
int cmp = key.compareTo(n.key);
if(cmp < 0){
n = n.left;
} else if(cmp > 0){
n = n.right;
}
}
return n;
}
public boolean contains(Node r, T key){
if(r == null) return false;
int cmp = key.compareTo(r.key);
if(r.key == key) return true;
else if(cmp < 0) return contains(r.left, key);
else return contains(r.right, key);
}
public boolean remove(T key){
Node nodeToRemove = this.findNode(key);
if(nodeToRemove == null) return false;
Node parent = nodeToRemove.parent;
if(this.length == 1){
this.root = null;
} else if(nodeToRemove.left == null && nodeToRemove.right == null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = null;
} else {
parent.right = null;
}
} else if(nodeToRemove.left == null && nodeToRemove.right != null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = nodeToRemove.right;
nodeToRemove.right.parent = parent;
} else {
parent.right = nodeToRemove.right;
nodeToRemove.right.parent = parent;
}
} else if(nodeToRemove.left != null && nodeToRemove.right == null){
int cmp = nodeToRemove.key.compareTo(parent.key);
if(cmp < 0){
parent.left = nodeToRemove.left;
nodeToRemove.left.parent = parent;
} else {
parent.right = nodeToRemove.left;
nodeToRemove.left.parent = parent;
}
} else {
Node largest = nodeToRemove.left;
while(largest.right != null){
largest = largest.right;
}
largest.parent.right = null;
nodeToRemove.key = largest.key;
nodeToRemove.parent = largest.parent;
}
this.length--;
return true;
}
public void preOrder(Node r){
if(r != null){
System.out.println(r.key);
preOrder(r.left);
preOrder(r.right);
}
}
public void inOrder(Node r){
if(r != null){
inOrder(r.left);
System.out.println(r.key);
inOrder(r.right);
}
}
public void postOrder(Node r){
if(r != null){
postOrder(r.left);
postOrder(r.right);
System.out.println(r.key);
}
}
public void breadthFirst(Node r){
Queue<Node> Q = new LinkedList<Node>();
while(r != null){
System.out.println(r.key);
if(r.left != null) Q.add(r.left);
if(r.right != null) Q.add(r.right);
if(!Q.isEmpty()) r = Q.remove();
else r = null;
}
}
public void leftRotation(Node node){
Node rightNode = node.right;
node.right = rightNode.left;
rightNode.left = node;
}
public void rightRotation(Node node){
Node leftNode = node.left;
node.left = leftNode.right;
leftNode.right = node;
}
public boolean checkBinary(Node n){
if(n != null){
checkBinary(n.left);
if(lastPrinted != null && n.key.compareTo(lastPrinted) <= 0) return false;
lastPrinted = n.key;
checkBinary(n.right);
return true;
}
return false;
}
public void minHeight(ArrayList<T> arr, int min, int max){
if(min <= max){
int mid = (min + max)/2;
insert(arr.get(mid));
minHeight(arr, min, mid-1);
minHeight(arr, mid+1, max);
}
}
public static void main(String[] args) {
}
} | true |
1de17b67667552e481aa573872649b73adf510d2 | Java | rolandyuwy/ip | /src/main/java/duke/command/FindCommand.java | UTF-8 | 1,290 | 3.109375 | 3 | [] | no_license | package duke.command;
import duke.task.TaskList;
import duke.ui.Ui;
import duke.util.Storage;
/**
* Represents a find command to find tasks which match a particular search description.
*/
public class FindCommand extends Command {
private String[] searchKeywords;
/**
* Initializes a find command.
*
* @param searchKeywords The search keywords stored as a String array.
*/
public FindCommand(String[] searchKeywords) {
this.searchKeywords = searchKeywords;
}
/**
* Generates a task list with descriptions containing the search description and
* prints each task in the list.
*
* @param taskList The existing task list.
* @param ui The UI instance which handles Duke's user interface.
* @param storage The existing storage for Duke.
*/
@Override
public void execute(TaskList taskList, Ui ui, Storage storage) {
ui.processResultTaskList(taskList.generateResultTaskList(searchKeywords));
}
/**
* Returns if the program should continue running at the current point in time.
* If not, the program should be exited.
*
* @return If the program should continue running.
*/
@Override
public boolean isInProgram() {
return true;
}
}
| true |
3eff71db5b1ea0afd8f78e2968679a1700eaea4e | Java | DemoXinMC/MoreEnchants | /src/main/java/com/demoxin/minecraft/moreenchants/melee/EnchantmentExecution.java | UTF-8 | 2,209 | 2.359375 | 2 | [] | no_license | package com.demoxin.minecraft.moreenchants.melee;
import com.demoxin.minecraft.moreenchants.MoreEnchants;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class EnchantmentExecution extends Enchantment
{
public EnchantmentExecution(int fId, int fWeight)
{
super(fId, fWeight, EnumEnchantmentType.weapon);
this.setName("execute");
addToBookList(this);
}
@Override
public int getMaxLevel()
{
return 1;
}
@Override
public int getMinEnchantability(int par1)
{
return 5 + 20 * (par1 - 1);
}
@Override
public int getMaxEnchantability(int par1)
{
return super.getMinEnchantability(par1) + 50;
}
@Override
public boolean canApplyTogether(Enchantment fTest)
{
if(fTest == MoreEnchants.enchantMending || fTest == MoreEnchants.enchantLeech || fTest == MoreEnchants.enchantExecution)
return false;
if(fTest == Enchantment.knockback || fTest == Enchantment.fireAspect || fTest == MoreEnchants.enchantIceAspect || fTest == MoreEnchants.enchantVenom)
return false;
return true;
}
@Override
public boolean canApply(ItemStack fTest)
{
return Enchantment.sharpness.canApply(fTest);
}
@SubscribeEvent
public void HandleEnchant(LivingHurtEvent fEvent)
{
if(fEvent.source.damageType != "player" && fEvent.source.damageType != "mob")
return;
if(!(fEvent.source.getSourceOfDamage() instanceof EntityLivingBase))
return;
EntityLivingBase attacker = (EntityLivingBase)fEvent.source.getSourceOfDamage();
ItemStack weapon = attacker.getHeldItem();
if(weapon == null)
return;
if(EnchantmentHelper.getEnchantmentLevel(effectId, weapon) != 0)
{
float defenderHealthPercent = fEvent.entityLiving.getHealth() / fEvent.entityLiving.getMaxHealth();
float dmgMod = 1.0f - defenderHealthPercent;
dmgMod = 1.0F + dmgMod;
fEvent.ammount = fEvent.ammount * dmgMod;
}
}
}
| true |
2f9b64f0a5367ee62d5d001d974cc7c746ed0904 | Java | alipay/alipay-sdk-java-all | /v2/src/main/java/com/alipay/api/domain/AlipayUserBenefitCreateModel.java | UTF-8 | 5,791 | 1.929688 | 2 | [
"Apache-2.0"
] | permissive | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 蚂蚁会员合作权益创建接口
*
* @author auto create
* @since 1.0, 2020-08-17 21:22:07
*/
public class AlipayUserBenefitCreateModel extends AlipayObject {
private static final long serialVersionUID = 4458824477484953516L;
/**
* 权益专区码,在创建权益前应该先向蚂蚁会员平台申请一个合适的专区码。 专区必须存在。
*/
@ApiField("benefit_area_code")
private String benefitAreaCode;
/**
* 权益图标地址
*/
@ApiField("benefit_icon_url")
private String benefitIconUrl;
/**
* 权益的名称
*/
@ApiField("benefit_name")
private String benefitName;
/**
* 是否将权益的名称用作专区的副标题, 若为true,则会使用该权益的名称自动覆盖所属专区的副标题(暂未实现)
*/
@ApiField("benefit_name_as_area_subtitle")
private Boolean benefitNameAsAreaSubtitle;
/**
* 权益详情页面地址
*/
@ApiField("benefit_page_url")
private String benefitPageUrl;
/**
* 权益兑换消耗的积分数
*/
@ApiField("benefit_point")
private Long benefitPoint;
/**
* 权益使用场景索引ID,接入时需要咨询@田豫如何取值
*/
@ApiField("benefit_rec_biz_id")
private String benefitRecBizId;
/**
* 支付宝商家券 ALIPAY_MERCHANT_COUPON
口碑商家券 KOUBEI_MERCHANT_COUPON
花呗分期免息券 HUABEI_FENQI_FREE_INTEREST_COUP
淘系通用券 TAOBAO_COMMON_COUPON
淘系商家券 TAOBAO_MERCHANT_COUPON
国际线上商家券 INTER_ONLINE_MERCHANT_COUPON
国际线下商家券 INTER_OFFLINE_MERCHANT_COUPON
通用商户权益 COMMON_MERCHANT_GOODS
其它 OTHERS, 接入是需要咨询@田豫如何选值
*/
@ApiField("benefit_rec_type")
private String benefitRecType;
/**
* 权益的副标题,用于补充描述权益
*/
@ApiField("benefit_subtitle")
private String benefitSubtitle;
/**
* 支付宝的营销活动id,若不走支付宝活动,则不需要填
*/
@ApiField("camp_id")
private String campId;
/**
* primary,golden,platinum,diamond分别对应大众、黄金、铂金、钻石会员等级。eligible_grade属性用于限制能够兑换当前权益的用户等级,用户必须不低于配置的等级才能进行兑换。如果没有等级要求,则不要填写该字段。
*/
@ApiField("eligible_grade")
private String eligibleGrade;
/**
* 权益展示结束时间,使用Date.getTime()。结束时间必须大于起始时间。
*/
@ApiField("end_time")
private Long endTime;
/**
* 兑换规则以及不满足该规则后给用户的提示文案,规则id和文案用:分隔;可配置多个,多个之间用,分隔。(分隔符皆是英文半角字符)规则id联系蚂蚁会员pd或运营提供
*/
@ApiField("exchange_rule_ids")
private String exchangeRuleIds;
/**
* 该权益对应每个等级会员的兑换折扣。等级和折扣用:分隔,多组折扣规则用:分隔。折扣0~1。分隔符皆为英文半角字符
*/
@ApiField("grade_discount")
private String gradeDiscount;
/**
* 权益展示起始时间, 使用Date.getTime()。开始时间必须大于当前时间,且结束时间需要大于开始时间
*/
@ApiField("start_time")
private Long startTime;
public String getBenefitAreaCode() {
return this.benefitAreaCode;
}
public void setBenefitAreaCode(String benefitAreaCode) {
this.benefitAreaCode = benefitAreaCode;
}
public String getBenefitIconUrl() {
return this.benefitIconUrl;
}
public void setBenefitIconUrl(String benefitIconUrl) {
this.benefitIconUrl = benefitIconUrl;
}
public String getBenefitName() {
return this.benefitName;
}
public void setBenefitName(String benefitName) {
this.benefitName = benefitName;
}
public Boolean getBenefitNameAsAreaSubtitle() {
return this.benefitNameAsAreaSubtitle;
}
public void setBenefitNameAsAreaSubtitle(Boolean benefitNameAsAreaSubtitle) {
this.benefitNameAsAreaSubtitle = benefitNameAsAreaSubtitle;
}
public String getBenefitPageUrl() {
return this.benefitPageUrl;
}
public void setBenefitPageUrl(String benefitPageUrl) {
this.benefitPageUrl = benefitPageUrl;
}
public Long getBenefitPoint() {
return this.benefitPoint;
}
public void setBenefitPoint(Long benefitPoint) {
this.benefitPoint = benefitPoint;
}
public String getBenefitRecBizId() {
return this.benefitRecBizId;
}
public void setBenefitRecBizId(String benefitRecBizId) {
this.benefitRecBizId = benefitRecBizId;
}
public String getBenefitRecType() {
return this.benefitRecType;
}
public void setBenefitRecType(String benefitRecType) {
this.benefitRecType = benefitRecType;
}
public String getBenefitSubtitle() {
return this.benefitSubtitle;
}
public void setBenefitSubtitle(String benefitSubtitle) {
this.benefitSubtitle = benefitSubtitle;
}
public String getCampId() {
return this.campId;
}
public void setCampId(String campId) {
this.campId = campId;
}
public String getEligibleGrade() {
return this.eligibleGrade;
}
public void setEligibleGrade(String eligibleGrade) {
this.eligibleGrade = eligibleGrade;
}
public Long getEndTime() {
return this.endTime;
}
public void setEndTime(Long endTime) {
this.endTime = endTime;
}
public String getExchangeRuleIds() {
return this.exchangeRuleIds;
}
public void setExchangeRuleIds(String exchangeRuleIds) {
this.exchangeRuleIds = exchangeRuleIds;
}
public String getGradeDiscount() {
return this.gradeDiscount;
}
public void setGradeDiscount(String gradeDiscount) {
this.gradeDiscount = gradeDiscount;
}
public Long getStartTime() {
return this.startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
}
| true |
71dc8edad3196ed44b752b8daef79c6c3363c68a | Java | ecclesia/kipeto | /kipeto-core/src/main/java/de/ecclesia/kipeto/engine/Engine.java | UTF-8 | 3,698 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*
* #%L
* Kipeto Core
* %%
* Copyright (C) 2010 - 2011 Ecclesia Versicherungsdienst GmbH
* %%
* 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.
* #L%
*/
package de.ecclesia.kipeto.engine;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import de.ecclesia.kipeto.common.util.Assert;
import de.ecclesia.kipeto.repository.ReadingRepository;
/**
* @author Daniel Hintze
* @since 03.02.2010
*/
public abstract class Engine {
private final ReadingRepository repository;
public Engine(ReadingRepository repository) {
Assert.isNotNull(repository);
this.repository = repository;
}
protected ReadingRepository getRepository() {
return repository;
}
private List<ActionListener> listeners = new ArrayList<ActionListener>();
protected abstract void handle(InstallFileAction action) throws IOException;
protected abstract void handle(UpdateFileMetadataAction action);
protected abstract void handle(UpdateFileAction action) throws IOException;
protected abstract void handle(MakeDirAction action);
protected abstract void handle(RemoveDirAction action);
protected abstract void handle(RemoveFileAction action);
public void process(Plan plan) throws IOException {
int workedTotal = 0;
int i = 0;
for (RemoveFileAction action : plan.getRemoveFileActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<RemoveFileAction>(action, plan, ++i, ++workedTotal));
}
i = 0;
for (RemoveDirAction action : plan.getRemoveDirActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<RemoveDirAction>(action, plan, ++i, ++workedTotal));
}
i = 0;
for (MakeDirAction action : plan.getMakeDirActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<MakeDirAction>(action, plan, ++i, ++workedTotal));
}
i = 0;
for (UpdateFileMetadataAction action : plan.getUpdateFileMetadataActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<UpdateFileMetadataAction>(action, plan, ++i, ++workedTotal));
}
i = 0;
for (UpdateFileAction action : plan.getUpdateFileActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<UpdateFileAction>(action, plan, ++i, ++workedTotal));
}
i = 0;
for (InstallFileAction action : plan.getInstallFileActions()) {
fireActionEvent(new ActionProgressEvent<Action>(action, 0, 0));
handle(action);
fireActionEvent(new ActionCompletedEvent<InstallFileAction>(action, plan, ++i, ++workedTotal));
}
}
public void addActionListener(ActionListener listener) {
listeners.add(listener);
}
public void removeActionListener(ActionListener listener) {
listeners.remove(listener);
}
protected void fireActionEvent(ActionEvent<?> completedEvent) {
for (ActionListener listener : listeners) {
listener.handleActionEvent(completedEvent);
}
}
}
| true |
d5d7c02f48aaf94cc7c668fbf15f819bf2513c09 | Java | MaisonWan/WeatherMan | /app/src/main/java/com/domker/weather/api/RxSingleObserver.java | UTF-8 | 408 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package com.domker.weather.api;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
/**
* 对于返回结果的封装
* <p>
* Created by wanlipeng on 2019/2/10 12:36 AM
*/
public abstract class RxSingleObserver<T> implements SingleObserver<T> {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onError(Throwable e) {
}
}
| true |
1ff40c1ce29edd16cd87c5ca165d27d32f630408 | Java | klmDF14J/GameJam | /src/hsim/util/SysInfo.java | UTF-8 | 111 | 1.695313 | 2 | [] | no_license | package hsim.util;
public class SysInfo {
public static String userDir = System.getProperty("user.dir");
}
| true |
259df60798ba120eabb8aeafcf45ec3f28536a7f | Java | BDS-CoPilot/blackduck-alert | /src/test/java/com/blackducksoftware/integration/hub/alert/channel/hipchat/controller/distribution/HipChatConfigRestModelTest.java | UTF-8 | 1,769 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2017 Black Duck Software Inc.
* http://www.blackducksoftware.com/
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Black Duck Software ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Black Duck Software.
*/
package com.blackducksoftware.integration.hub.alert.channel.hipchat.controller.distribution;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import com.blackducksoftware.integration.hub.alert.channel.hipchat.mock.MockHipChatRestModel;
import com.blackducksoftware.integration.hub.alert.web.model.CommonDistributionRestModelTest;
public class HipChatConfigRestModelTest extends CommonDistributionRestModelTest<HipChatDistributionRestModel> {
@Override
public void assertRestModelFieldsNull(final HipChatDistributionRestModel restModel) {
assertNull(restModel.getRoomId());
assertFalse(restModel.getNotify());
assertNull(restModel.getColor());
}
@Override
public void assertRestModelFieldsFull(final HipChatDistributionRestModel restModel) {
assertEquals(getMockUtil().getRoomId(), restModel.getRoomId());
assertEquals(getMockUtil().getNotify(), restModel.getNotify());
assertEquals(getMockUtil().getColor(), restModel.getColor());
}
@Override
public Class<HipChatDistributionRestModel> getRestModelClass() {
return HipChatDistributionRestModel.class;
}
@Override
public MockHipChatRestModel getMockUtil() {
return new MockHipChatRestModel();
}
}
| true |
d301bd6ab61806a6ddbee7c646516d87a6759229 | Java | JasperBouwman/TPort | /tport/src/main/java/com/spaceman/tport/commands/tport/pa/oldAndNew/Test.java | UTF-8 | 1,611 | 2.375 | 2 | [
"MIT"
] | permissive | package com.spaceman.tport.commands.tport.pa.oldAndNew;
import com.spaceman.tport.commandHandler.SubCommand;
import com.spaceman.tport.commands.tport.ParticleAnimationCommand;
import com.spaceman.tport.tpEvents.TPEManager;
import org.bukkit.entity.Player;
import static com.spaceman.tport.fancyMessage.colorTheme.ColorTheme.formatInfoTranslation;
import static com.spaceman.tport.fancyMessage.colorTheme.ColorTheme.sendErrorTranslation;
public class Test extends SubCommand {
private final ParticleAnimationCommand.AnimationType type;
public Test(ParticleAnimationCommand.AnimationType type) {
this.type = type;
this.setPermissions("TPort.particleAnimation." + this.type + ".test");
this.setCommandDescription(formatInfoTranslation("tport.command.particleAnimationCommand." + this.type + ".test"));
}
@Override
public void run(String[] args, Player player) {
// tport particleAnimation new|old test
if (args.length == 4) {
if (!this.hasPermissionToRun(player, true)) {
return;
}
if (this.type == ParticleAnimationCommand.AnimationType.NEW) {
TPEManager.getNewLocAnimation(player.getUniqueId()).show(player, player.getLocation());
} else {
TPEManager.getOldLocAnimation(player.getUniqueId()).show(player, player.getLocation());
}
} else {
sendErrorTranslation(player, "tport.command.wrongUsage", "/tport particleAnimation " + this.type + " test");
}
}
}
| true |
025e24e8f2144d13e77b1597f43daba28243604f | Java | LC1258/MyJob | /src/com/lwj/codeexamination/aqiyi/Main3.java | UTF-8 | 1,267 | 3.234375 | 3 | [] | no_license | package com.lwj.codeexamination.aqiyi;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean res = isPathCrossing(s);
if (res == true) {
System.out.println("True");
} else {
System.out.println("False");
}
}
private static boolean isPathCrossing(String s) {
if (s == null || "".equals(s)) {
return false;
}
int x = 0;
int y = 0;
Set<String> set = new HashSet<>();
set.add("0,0");
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'N' :
y++;
break;
case 'S' :
y--;
break;
case 'E' :
x++;
break;
case 'W' :
x--;
break;
default:
break;
}
if (!set.add(x + "," + y)) {
return true;
}
}
return false;
}
}
| true |
23be5f2bb93d8252704ae42791687933808e5eda | Java | tomerbendror/practicer | /src/main/java/com/practice/jira/JiraSubtask.java | UTF-8 | 987 | 2.21875 | 2 | [] | no_license | package com.practice.jira;
import com.practice.jira.enums.IssueTypeName;
/**
* Created by Tomer.Ben-Dror on 2/13/2017
*/
public class JiraSubtask {
private String key;
private String summary;
private IssueTypeName typeName;
private TimeEstimation estimateStatistic;
public JiraSubtask() {
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public IssueTypeName getTypeName() {
return typeName;
}
public void setTypeName(IssueTypeName typeName) {
this.typeName = typeName;
}
public TimeEstimation getEstimateStatistic() {
return estimateStatistic;
}
public void setEstimateStatistic(TimeEstimation estimateStatistic) {
this.estimateStatistic = estimateStatistic;
}
}
| true |
5bcb9716936bbbfc8afb43de2934361e416ebbe1 | Java | goodgga/qns | /src/qns/tools/other/Encryption.java | GB18030 | 246 | 2.34375 | 2 | [] | no_license | package qns.tools.other;
import java.util.UUID;
public class Encryption {
/**
* 36λkey
* @return 36λkey
*/
public static final String makeKey(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
}
| true |
775dfd3be4ca0579d8913f2a3acfc83b0da1ba6f | Java | zr00555/GroupGames | /src/com/groupgames/web/core/Card.java | UTF-8 | 438 | 2.96875 | 3 | [] | no_license | package com.groupgames.web.core;
public class Card {
int cardID;
String cardText;
public Card(int cardID, String cardText) {
this.cardID = cardID;
this.cardText = cardText;
}
public int getCardID() {
return this.cardID;
}
public String getCardText() {
return this.cardText;
}
public boolean equals(Card c){
return this.getCardID() == c.getCardID();
}
}
| true |
a49aa38d730f20ab73dad9507004b40c3904215a | Java | jquintanas/cloud | /cloudsimex-web/src/test/java/org/cloudbus/cloudsim/ex/web/StatGeneratorTest.java | UTF-8 | 5,318 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package org.cloudbus.cloudsim.ex.web;
import static org.cloudbus.cloudsim.ex.util.helpers.TestUtil.createSeededGaussian;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.cloudbus.cloudsim.ex.disk.DataItem;
import org.cloudbus.cloudsim.ex.web.StatGenerator;
import org.cloudbus.cloudsim.ex.web.WebCloudlet;
import org.junit.Before;
import org.junit.Test;
import org.uncommons.maths.number.NumberGenerator;
/**
*
* @author nikolay.grozev
*
*/
public class StatGeneratorTest {
private static final int GEN_RAM_MEAN = 200;
private static final int GEN_RAM_STDEV = 10;
private NumberGenerator<Double> genRAM;
private static final int GEN_CPU_MEAN = 25;
private static final int GEN_CPU_STDEV = 2;
private NumberGenerator<Double> genCPU;
private Map<String, NumberGenerator<Double>> testGenerators = new HashMap<>();
private static final DataItem data = new DataItem(65);
@Before
public void setUp() {
genRAM = createSeededGaussian(GEN_RAM_MEAN, GEN_RAM_STDEV);
genCPU = createSeededGaussian(GEN_CPU_MEAN, GEN_CPU_STDEV);
testGenerators = new HashMap<>();
testGenerators.put(StatGenerator.CLOUDLET_LENGTH, genCPU);
testGenerators.put(StatGenerator.CLOUDLET_RAM, genRAM);
}
@Test
public void testHandlingEmptyAndNonemtpyCases() {
// Should be empty in the start
StatGenerator generator = new StatGenerator(testGenerators, data);
assertTrue(generator.isEmpty());
assertNull(generator.peek());
assertNull(generator.poll());
generator.notifyOfTime(15);
// Should not be empty now
assertFalse(generator.isEmpty());
Object peeked = generator.peek();
Object peekedAgain = generator.peek();
Object polled = generator.poll();
assertNotNull(peeked);
assertTrue(peeked == peekedAgain);
assertTrue(peeked == polled);
// Should be empty again
assertTrue(generator.isEmpty());
assertNull(generator.peek());
assertNull(generator.poll());
}
@Test
public void testHandlingTimeConstraints() {
// Should be empty in the start
StatGenerator generator = new StatGenerator(testGenerators, 3, 12, data);
// Notify for times we are not interested in (they are outside [3;12])
generator.notifyOfTime(2);
generator.notifyOfTime(15);
generator.notifyOfTime(17);
// Should be empty now...
assertTrue(generator.isEmpty());
assertNull(generator.peek());
assertNull(generator.poll());
// Notify for times again.
generator.notifyOfTime(2); // Not Interested - outside [3;12]
generator.notifyOfTime(5); // Interested
generator.notifyOfTime(5); // Not Interested - it is repeated
generator.notifyOfTime(7); // Interested
generator.notifyOfTime(10); // Interested
generator.notifyOfTime(10); // Not Interested - it is repeated
generator.notifyOfTime(18); // Not Interested
// Should not be empty now
assertFalse(generator.isEmpty());
Object peeked = generator.peek();
Object peekedAgain = generator.peek();
assertTrue(peeked == peekedAgain);
// Check if we have 3 things in the generator
int i = 0;
while (!generator.isEmpty()) {
peeked = generator.peek();
peekedAgain = generator.peek();
Object polled = generator.poll();
assertNotNull(peeked);
assertTrue(peeked == peekedAgain);
assertTrue(peeked == polled);
i++;
}
assertEquals(3, i);
// Should be empty again... we polled everything
assertTrue(generator.isEmpty());
assertNull(generator.peek());
assertNull(generator.poll());
}
@Test
public void testStatisticsAreUsedOK() {
StatGenerator generator = new StatGenerator(testGenerators, data);
DescriptiveStatistics ramStat = new DescriptiveStatistics();
DescriptiveStatistics cpuStat = new DescriptiveStatistics();
// Generate 100 values
int size = 100;
for (int i = 0; i < size; i++) {
generator.notifyOfTime(i + 5);
}
// Compute descriptive statistics
for (int i = 0; i < size; i++) {
WebCloudlet c = generator.poll();
ramStat.addValue(c.getRam());
cpuStat.addValue(c.getCloudletLength());
}
// Allow for delta, because of using doubles, and rounding some of the
// numbers
double delta = 10;
assertEquals(GEN_RAM_MEAN, ramStat.getMean(), delta);
assertEquals(GEN_RAM_STDEV, ramStat.getStandardDeviation(), delta);
assertEquals(GEN_CPU_MEAN, cpuStat.getMean(), delta);
assertEquals(GEN_CPU_STDEV, cpuStat.getStandardDeviation(), delta);
// Assert we have exhausted the generator
assertTrue(generator.isEmpty());
}
}
| true |
0681e309f82b1572d118c1e96bc3713cc58d2b63 | Java | DevHossamHassan/TaxiOneCall | /androidapp/customer_app/src/main/java/com/hkm/taxicallandroid/schema/Call.java | UTF-8 | 1,418 | 2.21875 | 2 | [] | no_license | package com.hkm.taxicallandroid.schema;
import android.content.Context;
import com.asynhkm.productchecker.Model.CallTask;
import com.google.gson.JsonParseException;
import org.json.JSONException;
import org.json.JSONObject;
public class Call extends CallTask {
private static String data_object = "holder";
public Call(Context ccc, callback cb) {
super(ccc, cb);
TAG = "call.api.taxi";
}
public Call setDataObject(final String txt) {
data_object = txt;
return this;
}
@Override
protected void onPostExecute(String resultString) {
try {
if (isError) {
if (mcallback != null) mcallback.onFailure(errorMessage);
} else {
final JSONObject Jr = new JSONObject(resultString);
JSONObject data = Jr.getJSONObject(data_object);
if (mcallback != null) mcallback.onSuccess(data.toString());
}
} catch (JsonParseException e) {
if (mcallback != null) mcallback.onFailure(e.getMessage());
} catch (JSONException e) {
if (mcallback != null) mcallback.onFailure(e.getMessage());
} catch (NullPointerException e) {
if (mcallback != null) mcallback.onFailure(e.getMessage());
} catch (Exception e) {
if (mcallback != null) mcallback.onFailure(e.getMessage());
}
}
}
| true |
ae85f896bdc07881f755bda6a0c5e88566de8353 | Java | eliharush/SurgeryWarehouse | /SIC_Web/src/il/swhm/web/rest/TransmitResource.java | UTF-8 | 1,997 | 2.265625 | 2 | [] | no_license | package il.swhm.web.rest;
import il.swhm.data.dao.impl.GeneralDao;
import il.swhm.shared.entities.Transmitable;
import il.swhm.shared.enums.EntityType;
import il.swhm.web.config.SICConfiguration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
@Path("/transmit")
public class TransmitResource {
private static String DELIMITER="_";
private static Logger logger=Logger.getLogger(TransmitResource.class);
@Context UriInfo ui;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response transmitICS(){
try{
List<String> entitiesStr= ui.getQueryParameters().get("entity");
Map<Integer,EntityType> entities=new HashMap<Integer,EntityType>();
for(String entityStr:entitiesStr){
String[] arr = entityStr.split(DELIMITER);
entities.put(Integer.valueOf(arr[1]),EntityType.valueOf(arr[0]));
}
GeneralDao dao=new GeneralDao();
String user=(SICConfiguration.getInstance().getUser().equals(""))?"mobile" : SICConfiguration.getInstance().getUser();
boolean res=dao.transmitCounts(SICConfiguration.getInstance().getStationId(), entities,user);
if(res){
return Response.ok().build();
}
else{
return Response.serverError().build();
}
}
catch (Exception e) {
logger.error("Exception occured",e);
return Response.serverError().build();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getEntitiesForTtransmit(){
try{
GeneralDao dao=new GeneralDao();
List<Transmitable> ics=dao.getEntitiesForTransmit(SICConfiguration.getInstance().getStationId());
return Response.ok().entity(ics).build();
}
catch (Exception e) {
logger.error("Exception occured",e);
return Response.serverError().build();
}
}
}
| true |
acd49f58d301d9fa4494e913e43f50b8074c97c0 | Java | KasHald/Flow4d2 | /src/THEPackage/QuizControlInterface.java | UTF-8 | 2,172 | 2.65625 | 3 | [] | no_license | package THEPackage;
public interface QuizControlInterface {
// rev chu 18-04-2013
/**
* THA: 31-10-2013: This is a change to the original interface
* Pre:
* Post:
* Loading all games from file: quizzConfigurations.txt
*/
boolean loadGames();
/**
* Pre:
* Post:
* Returns a list of names of selectable games
*/
String[] getGameNames();
/**
* Pre: The name passed corresponds to a selectable game
* Post: The existing collection of word pairs is cleared.
*/
void selectGame(String gameName);
/**
* Pre:
* Post:
* Returns the name of the game presently selected. If no game is selected it returns null.
*/
String getSelectedGameName();
/**
* Pre:
* Post:
* Returns an appropriate text for a label placed next to a “question field�
* corresponding to the selected game.
* If no game is selected it returns null
*/
String getQuestionLabelText();
/**
* Pre:
* Post:
* Returns an appropriate text for a label placed next to an "answer field"
* corresponding to the selected game.
* If no game is selected it returns null
*/
String getAnswerLabelText();
/**
* Pre:
* Post:
* Returns an appropriate text for a button used to request a new random question
* corresponding to the selected game.
* If no game is selected it returns null
*/
String getQuestionButtonText();
/**
* Pre:
* Post:
* Returns an appropriate text for a button used to submit an answer (quess)
* corresponding to the selected game.
* If no game is selected it returns null
*/
String getAnswerButtonText();
/**
* Pre:
* Post:
* Returns an appropriate text for a button used to lookup an answer
* corresponding to the selected game.
* If no game is selected it returns null
*/
String getLookupButtonText();
/**
* Pre: Post: A new quizz is added to the existing collection of quizzes
*/
void addQuizz(String quizzName, String questionButtonText, String answerButtonText, String lookupButtonText, String questionLabelText, String answerLabelText);
/**
* Pre: Post: All the quizzes configuration data are save to the file
* "quizzConfigurations.txt". Returns true if successfully done. Otherwise false.
*/
boolean saveQuizz();
Game currentGame();
} | true |
4cb1d90891dcabbbe6b53b3ff2a68de4e97280c6 | Java | ctrekker/TopologicalComputer | /Renderer/src/com/burnscoding/tc/GradientFunction.java | UTF-8 | 3,511 | 3.1875 | 3 | [] | no_license | package com.burnscoding.tc;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.util.*;
import java.util.Timer;
import javax.swing.*;
public class GradientFunction extends JFrame {
public static void main(String[] args) {
GradientFunction gradientFunction = new GradientFunction();
}
private RenderCanvas canvas;
private static int w = 640;
private static int h = 640;
public GradientFunction() {
setTitle("Gradient Function");
setSize(w, h);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
addWindowStateListener(e -> {
Dimension d = e.getWindow().getSize();
w = d.width;
h = d.height;
});
canvas = new RenderCanvas();
add(canvas);
setVisible(true);
}
private class RenderCanvas extends Component {
private Timer animationTimer;
private int[][] points = {
{ 10, 2 },
{ 20, 3 }
};
public RenderCanvas() {
animationTimer = new Timer();
// animationTimer.scheduleAtFixedRate(new TimerTask() {
// @Override
// public void run() {
// repaint();
// }
// }, 0, 1000/60);
}
public double gf(double xp, double yp) {
double yIntercept = points[0][0];
double slopeX = points[1][0] - points[0][0];
double slopeY = points[0][1] - points[0][0];
return xp*slopeX + yp*slopeY + yIntercept;
}
double map(double x, double in_min, double in_max, double out_min, double out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int inset = 50;
int startX = inset;
int startY = inset;
int endX = w - inset * 2;
int endY = h - inset * 2;
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.BLACK);
g2.drawRect(startX, startY, endX - startX, endY - startY);
double min = 3;
double max = 1;
for(double x = 0; x < 1.0; x += 1.0 / (endX - startX)) {
for (double y = 0; y < 1.0; y += 1.0 / (endY - startY)) {
double z = gf(x, y);
if (z < min) {
min = z;
}
if (z > max) {
max = z;
}
}
}
int xCoord = startX;
int yCoord = startY;
for(double x = 0; x < 1.0; x += 1.0 / (endX - startX)) {
for(double y = 0; y < 1.0; y += 1.0 / (endY - startY)) {
double z = gf(x, y);
z = map(z, min, max, 0, 255);
if(z < 0 || z > 255) {
g2.setPaint(new Color(0, 0, 255));
}
else {
g2.setPaint(new Color((int)z, (int)z, (int)z));
}
g2.fillRect(xCoord, yCoord, 1, 1);
yCoord++;
}
xCoord++;
yCoord = startY;
}
System.out.println("Min:"+min);
System.out.println("Max:"+max);
}
}
}
| true |