hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
ed82798a71efe22bd16dd4d645d136015dc36c92
| 32,610
|
package com.example.music_player.ui;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.RequestManager;
import com.example.music_player.AddToPlaylistActivity;
import com.example.music_player.AlbumGroupActivity;
import com.example.music_player.AlbumViewActivity;
import com.example.music_player.Classes.PlaylistSong;
import com.example.music_player.Classes.Song;
import com.example.music_player.EditActivity;
import com.example.music_player.MusicService.PlayMusicService;
import com.example.music_player.PlaylistViewActivity;
import com.example.music_player.R;
import com.example.music_player.SearchActivity;
import com.example.music_player.enums.AdapterType;
import com.example.music_player.interfaces.UpdateQueueListener;
import com.example.music_player.interfaces.AlbumClickListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static com.example.music_player.Classes.Singleton.getPlayInstance;
public class ViewPagerAdapter extends PagerAdapter implements AlbumClickListener, AllSongsClickListener {
Context context;
List<String> titles;
RequestManager requestManager;
RecyclerView.LayoutManager recentsLayoutManager;
public AlbumAdapter recentsAdapter;
RecyclerView.LayoutManager albumLayoutManager;
public AlbumAdapter albumAdapter;
LinearLayoutManager songLayoutManager;
public AllSongsAdapter songAdapter;
RecyclerView.LayoutManager playlistLayoutManager;
public PlaylistAdapter playlistAdapter;
RecyclerView.LayoutManager genreLayoutManager;
public GroupAdapter genreAdapter;
RecyclerView.LayoutManager artistLayoutManager;
public GroupAdapter artistAdapter;
UpdateQueueListener updateQueueListener;
public ViewPagerAdapter(Context context, List<String> titles, RequestManager requestManager) {
super();
this.context = context;
this.titles = titles;
this.requestManager = requestManager;
}
public void setUpdateQueueListener(UpdateQueueListener updateQueueListener) {
this.updateQueueListener = updateQueueListener;
}
@Override
public int getCount() {
return titles.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
//return super.getPageTitle(position);
return new String(titles.get(position));
}
@Override
public void destroyItem(@NonNull View container, int position, @NonNull Object object) {
//super.destroyItem(container, position, object);
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
//RecyclerView recyclerView = new RecyclerView(context);
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(container.getContext()).inflate(R.layout.recycler_with_fast_scroll, container, false);
RecyclerView recyclerView = linearLayout.findViewById(R.id.recyclerView);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) recyclerView.getLayoutParams();
switch (position){
case 0:
recyclerView.setAdapter(null);
recentsLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(recentsLayoutManager);
recentsAdapter = new AlbumAdapter(getPlayInstance().recents, requestManager, context, this, AdapterType.RECENT);
recyclerView.setAdapter(recentsAdapter);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
layoutParams.rightMargin = 0;
layoutParams.leftMargin = 0;
break;
case 1:
recyclerView.setAdapter(null);
playlistLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(playlistLayoutManager);
playlistAdapter = new PlaylistAdapter(getPlayInstance().playlists, context, this);
recyclerView.setAdapter(playlistAdapter);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
layoutParams.rightMargin = 0;
layoutParams.leftMargin = 0;
break;
case 2:
recyclerView.setAdapter(null);
artistLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(artistLayoutManager);
artistAdapter = new GroupAdapter(getPlayInstance().artists, context, this, AdapterType.ARTIST);
recyclerView.setAdapter(artistAdapter);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
layoutParams.rightMargin = 0;
layoutParams.leftMargin = 0;
break;
case 3:
recyclerView.setAdapter(null);
albumLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(albumLayoutManager);
albumAdapter = new AlbumAdapter(getPlayInstance().albums, requestManager, context, this, AdapterType.ALBUM);
recyclerView.setAdapter(albumAdapter);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
layoutParams.rightMargin = 0;
layoutParams.leftMargin = 0;
break;
case 4:
recyclerView.setAdapter(null);
songLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(songLayoutManager);
//songAdapter = new AllSongsAdapter(MainActivity.songs, context, this);
songAdapter = new AllSongsAdapter(getPlayInstance().songs, context, this);
recyclerView.setAdapter(songAdapter);
layoutParams.rightMargin = 30;
layoutParams.leftMargin = 30;
break;
case 5:
recyclerView.setAdapter(null);
genreLayoutManager = new GridLayoutManager(context, 2);
recyclerView.setLayoutManager(genreLayoutManager);
genreAdapter = new GroupAdapter(getPlayInstance().genres, context, this, AdapterType.GENRE);
recyclerView.setAdapter(genreAdapter);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, 30, true));
layoutParams.rightMargin = 0;
layoutParams.leftMargin = 0;
break;
}
ViewPager viewPager = (ViewPager) container;
viewPager.addView(linearLayout);
return linearLayout;
}
@Override
public void onOverflowClicked(int position, View view, AdapterType type) {
PopupMenu popupMenu = new PopupMenu(context, view.findViewById(R.id.OverflowMenu));
MenuInflater inflater = popupMenu.getMenuInflater();
switch (type) {
case RECENT:
getPlayInstance().selectedAlbum = getPlayInstance().recents.get(position);
inflater.inflate(R.menu.album_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<Song>();
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().selectedAlbum.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetSongNumberInt()));
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetDiscNumberInt()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.ALBUM);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, false);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
case R.id.action_AddtoPlaylist:
getPlayInstance().itemToAdd = getPlayInstance().recents.get(position);
Intent intent = new Intent(context, AddToPlaylistActivity.class);
context.startActivity(intent);
break;
case R.id.action_GotoArtist:
getPlayInstance().selectedGroup = getPlayInstance().artists.stream().filter(x -> x.GetName().equals(getPlayInstance().albums.get(position).GetAlbumArtist())).findFirst().get();
Intent artist = new Intent(context, AlbumGroupActivity.class);
context.startActivity(artist);
break;
case R.id.action_Edit:
getPlayInstance().itemToEdit = getPlayInstance().recents.get(position);
Intent edit = new Intent(context, EditActivity.class);
context.startActivity(edit);
break;
case R.id.action_Delete:
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Delete")
.setMessage("Delete " + getPlayInstance().recents.get(position).GetName())
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getPlayInstance().deleteAlbum(getPlayInstance().albums.get(position), getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().albums.get(position).Name)).collect(Collectors.toList()));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
break;
}
return true;
}
});
popupMenu.show();
break;
case ALBUM:
getPlayInstance().selectedAlbum = getPlayInstance().albums.get(position);
inflater.inflate(R.menu.album_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<Song>();
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().selectedAlbum.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetSongNumberInt()));
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetDiscNumberInt()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.ALBUM);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, false);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
case R.id.action_AddtoPlaylist:
getPlayInstance().itemToAdd = getPlayInstance().albums.get(position);
Intent intent = new Intent(context, AddToPlaylistActivity.class);
context.startActivity(intent);
break;
case R.id.action_GotoArtist:
getPlayInstance().selectedGroup = getPlayInstance().artists.stream().filter(x -> x.GetName().equals(getPlayInstance().albums.get(position).GetAlbumArtist())).findFirst().get();
Intent artist = new Intent(context, AlbumGroupActivity.class);
context.startActivity(artist);
break;
case R.id.action_Edit:
getPlayInstance().itemToEdit = getPlayInstance().albums.get(position);
Intent edit = new Intent(context, EditActivity.class);
context.startActivity(edit);
break;
case R.id.action_Delete:
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Delete")
.setMessage("Delete " + getPlayInstance().albums.get(position).GetName())
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getPlayInstance().deleteAlbum(getPlayInstance().albums.get(position), getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().albums.get(position).Name)).collect(Collectors.toList()));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
break;
}
return true;
}
});
popupMenu.show();
break;
case ARTIST:
getPlayInstance().selectedGroup = getPlayInstance().artists.get(position);
inflater.inflate(R.menu.group_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<Song>();
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Artist.equals(getPlayInstance().selectedGroup.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparing(p -> p.Title.toLowerCase()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, false);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
}
return true;
}
});
popupMenu.show();
break;
case GENRE:
getPlayInstance().selectedGroup = getPlayInstance().genres.get(position);
inflater.inflate(R.menu.group_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<Song>();
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Genre.equals(getPlayInstance().selectedGroup.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparing(p -> p.Title.toLowerCase()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, false);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
}
return true;
}
});
popupMenu.show();
break;
case PLAYLIST:
getPlayInstance().selectedPlaylist = getPlayInstance().playlists.get(position);
inflater.inflate(R.menu.playlist_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<Song>();
Collections.sort(getPlayInstance().selectedPlaylist.PlaylistSongs, Comparator.comparingInt(p -> p.PlaylistSort));
for (PlaylistSong playlistSong : getPlayInstance().selectedPlaylist.PlaylistSongs){
Song song = getPlayInstance().songs.stream().filter(x -> x.SongID.equals(playlistSong.SongID)).findFirst().get();
song.SetNowPlayingSource(AdapterType.PLAYLIST);
selectedSongs.add(song);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, false);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
case R.id.action_Edit:
// getPlayInstance().itemToEdit = getPlayInstance().playlists.get(Position);
// Intent edit = new Intent(context, EditActivity.class);
// context.startActivity(edit);
break;
case R.id.action_Delete:
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Delete")
.setMessage("Delete " + getPlayInstance().playlists.get(position).GetName())
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getPlayInstance().deletePlaylist(getPlayInstance().playlists.get(position));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
break;
}
return true;
}
});
popupMenu.show();
break;
}
}
@Override
public void onPlayButtonClicked(int position, AdapterType type) {
List<Song> selectedSongs = new ArrayList<Song>();
switch(type){
case RECENT:
getPlayInstance().selectedAlbum = getPlayInstance().recents.get(position);
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().selectedAlbum.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetSongNumberInt()));
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetDiscNumberInt()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.ALBUM);
}
break;
case ALBUM:
getPlayInstance().selectedAlbum = getPlayInstance().albums.get(position);
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Album.equals(getPlayInstance().selectedAlbum.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetSongNumberInt()));
Collections.sort(selectedSongs, Comparator.comparingInt(p -> p.GetDiscNumberInt()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.ALBUM);
}
break;
case ARTIST:
getPlayInstance().selectedGroup = getPlayInstance().artists.get(position);
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Artist.equals(getPlayInstance().selectedGroup.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparing(p -> p.Title.toLowerCase()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
break;
case GENRE:
getPlayInstance().selectedGroup = getPlayInstance().genres.get(position);
selectedSongs = getPlayInstance().songs.stream().filter((x) -> x.Genre.equals(getPlayInstance().selectedGroup.GetName())).collect(Collectors.toList());
Collections.sort(selectedSongs, Comparator.comparing(p -> p.Title.toLowerCase()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
break;
case PLAYLIST:
getPlayInstance().selectedPlaylist = getPlayInstance().playlists.get(position);
Collections.sort(getPlayInstance().selectedPlaylist.PlaylistSongs, Comparator.comparingInt(p -> p.PlaylistSort));
for (PlaylistSong playlistSong : getPlayInstance().selectedPlaylist.PlaylistSongs){
Song song = getPlayInstance().songs.stream().filter(x -> x.SongID.equals(playlistSong.SongID)).findFirst().get();
song.SetNowPlayingSource(AdapterType.PLAYLIST);
selectedSongs.add(song);
}
break;
}
if(selectedSongs.size() != 0){
playMusic(selectedSongs, false);
}
}
@Override
public void onItemViewClicked(int position, AdapterType type) {
switch(type){
case RECENT:
getPlayInstance().selectedAlbum = getPlayInstance().recents.get(position);
Intent recentAlbum = new Intent(context, AlbumViewActivity.class);
context.startActivity(recentAlbum);
break;
case ALBUM:
getPlayInstance().selectedAlbum = getPlayInstance().albums.get(position);
Intent album = new Intent(context, AlbumViewActivity.class);
context.startActivity(album);
break;
case ARTIST:
getPlayInstance().selectedGroup = getPlayInstance().artists.get(position);
Intent artist = new Intent(context, AlbumGroupActivity.class);
context.startActivity(artist);
break;
case GENRE:
getPlayInstance().selectedGroup = getPlayInstance().genres.get(position);
Intent genre = new Intent(context, AlbumGroupActivity.class);
context.startActivity(genre);
break;
case PLAYLIST:
getPlayInstance().selectedPlaylist = getPlayInstance().playlists.get(position);
Intent playlist = new Intent(context, PlaylistViewActivity.class);
context.startActivity(playlist);
break;
}
}
void shuffled(List<Song> selectedSongs, boolean keepFirst){
getPlayInstance().shuffled(selectedSongs, keepFirst);
}
void playNext(List<Song> selectedSongs){
if (getPlayInstance().playNext(selectedSongs)) {
updateQueueListener.onUpdated(true);
}
}
void addToQueue(List<Song> selectedSongs){
if (getPlayInstance().addToQueue(selectedSongs)){
updateQueueListener.onUpdated(true);
}
}
void playMusic(List<Song> selectedSongs, boolean keepFirst){
getPlayInstance().playMusic(selectedSongs, keepFirst);
}
@Override
public void onOverflowClicked(int position, View view) {
PopupMenu popupMenu = new PopupMenu(context, view.findViewById(R.id.OverflowMenu));
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(R.menu.song_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
List<Song> selectedSongs = new ArrayList<>();
selectedSongs = getPlayInstance().songs.subList(position, getPlayInstance().songs.size());
Collections.sort(selectedSongs, Comparator.comparing(p -> p.Title.toLowerCase()));
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
switch (item.getItemId()) {
case R.id.action_Shuffle:
shuffled(selectedSongs, true);
break;
case R.id.action_PlayNext:
playNext(selectedSongs);
break;
case R.id.action_AddtoQueue:
addToQueue(selectedSongs);
break;
case R.id.action_AddtoPlaylist:
getPlayInstance().itemToAdd = getPlayInstance().songs.get(position);
Intent intent = new Intent(context, AddToPlaylistActivity.class);
context.startActivity(intent);
break;
case R.id.action_GotoArtist:
getPlayInstance().selectedGroup = getPlayInstance().artists.stream().filter(x -> x.GetName().equals(getPlayInstance().songs.get(position).GetArtist())).findFirst().get();
Intent artist = new Intent(context, AlbumGroupActivity.class);
context.startActivity(artist);
break;
case R.id.action_GotoAlbum:
getPlayInstance().selectedAlbum = getPlayInstance().albums.stream().filter(x -> x.GetName().equals(getPlayInstance().songs.get(position).GetAlbum())).findFirst().get();
Intent album = new Intent(context, AlbumViewActivity.class);
context.startActivity(album);
break;
case R.id.action_Edit:
getPlayInstance().itemToEdit = getPlayInstance().songs.get(position);
Intent edit = new Intent(context, EditActivity.class);
context.startActivity(edit);
break;
case R.id.action_Delete:
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("Delete")
.setMessage("Delete " + getPlayInstance().songs.get(position).GetTitle())
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getPlayInstance().deleteSong(getPlayInstance().songs.get(position));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
break;
}
return true;
}
});
popupMenu.show();
}
@Override
public void onItemViewClicked(int position, View view) {
List<Song> selectedSongs = getPlayInstance().songs.subList(position, getPlayInstance().songs.size());
for (Song song : selectedSongs){
song.SetNowPlayingSource(AdapterType.SONG);
}
playMusic(selectedSongs, true);
}
}
| 51.354331
| 256
| 0.538148
|
49edd98831e2c61be9acb5dafae14493f0681cba
| 874
|
package nerd.utopian.completablefuture.springboot;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorConfig {
@Bean("customThreadPoolTaskExecutor")
public Executor getThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(2);
threadPoolTaskExecutor.setMaxPoolSize(2);
threadPoolTaskExecutor.setQueueCapacity(100);
threadPoolTaskExecutor.setThreadNamePrefix("utopian-thread-");
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
| 36.416667
| 81
| 0.83524
|
f6bf62493e487eba062cf1e362f9718aa12d8750
| 1,199
|
package com.example.eokuu;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Ayarlar extends Activity {
Button btnDisplaySetting;
Intent intentDisplaySetting;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ayarlar);
btnDisplaySetting = (Button) findViewById(R.id.Ayarlar);
intentDisplaySetting = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(
intentDisplaySetting, 0);
if (resolveInfo == null) {
Toast.makeText(Ayarlar.this, "Not Support!", Toast.LENGTH_LONG)
.show();
btnDisplaySetting.setEnabled(false);
} else {
btnDisplaySetting.setEnabled(true);
}
btnDisplaySetting.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(intentDisplaySetting);
}
});
}
}
| 27.25
| 70
| 0.766472
|
c36dd6ffd7c7a4a6ff2adfb32c5e2a248bd0a185
| 54,934
|
/*
* Copyright (c) 2008-2019 Geode Systems LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ramadda.geodata.model;
import org.ramadda.geodata.cdmdata.CdmDataOutputHandler;
import org.ramadda.geodata.cdmdata.OpendapApiHandler;
import org.ramadda.repository.Association;
import org.ramadda.repository.Entry;
import org.ramadda.repository.Repository;
import org.ramadda.repository.RepositoryManager;
import org.ramadda.repository.Request;
import org.ramadda.repository.Resource;
import org.ramadda.repository.database.Tables;
import org.ramadda.repository.job.JobManager;
import org.ramadda.repository.type.CollectionTypeHandler;
import org.ramadda.repository.type.Column;
import org.ramadda.repository.type.GranuleTypeHandler;
import org.ramadda.repository.type.TypeHandler;
import org.ramadda.repository.util.RequestArgument;
import org.ramadda.service.Service;
import org.ramadda.service.ServiceInput;
import org.ramadda.service.ServiceOperand;
import org.ramadda.util.HtmlUtils;
import org.ramadda.util.sql.Clause;
import ucar.nc2.dt.grid.GridDataset;
import ucar.nc2.time.Calendar;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarDateRange;
import ucar.unidata.util.IOUtil;
import ucar.unidata.util.StringUtil;
import ucar.unidata.util.TwoFacedObject;
import ucar.visad.data.CalendarDateTime;
import visad.util.ThreadManager;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
/**
* Base class for CDO data services
*/
public abstract class CDODataService extends Service {
/** months */
protected static final String[] MONTHS = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"
};
/** localhost name */
public static final String CDO_SERVICE_LOCALHOSTNAME =
"service.cdo.localhostname";
/** climate dataset number */
public static final String ARG_CLIMATE_DATASET_NUMBER =
"clim_dataset_number";
/** _more_ */
public static final String ARG_TIME_AVERAGE = "time_average";
/** the type handler associated with this */
private CDOOutputHandler outputHandler;
/**
* Create a CDO Data Service
*
* @param repository the repository
* @param id an id for this service
* @param label a label for this service
*
* @throws Exception problem creating service
*/
public CDODataService(Repository repository, String id, String label)
throws Exception {
super(repository, id, label);
outputHandler = new CDOOutputHandler(repository);
}
/**
* Is this enabled?
*
* @return true if it is
*/
public boolean isEnabled() {
return outputHandler.isEnabled();
}
/**
* Find the associated climatology for the input
*
* @param request the Request
* @param granule the entry
*
* @return the climatology entry or null
*
* @throws Exception problems
*/
protected List<Entry> findClimatology(Request request, Entry granule)
throws Exception {
return findStatisticEntry(request, granule, "clim");
}
/**
* Find the associated stat (e.g., clim or sprd) for the input
*
* @param request the Request
* @param granule the entry
* @param stat the stat type (sprd, clim, etc)
*
* @return the stat entry or null
*
* @throws Exception problems
*/
protected List<Entry> findStatisticEntry(Request request, Entry granule,
String stat)
throws Exception {
TypeHandler gh = granule.getTypeHandler();
if ( !(gh instanceof ClimateModelFileTypeHandler)) {
return null;
}
Entry collection = GranuleTypeHandler.getCollectionEntry(request,
granule);
CollectionTypeHandler ctypeHandler =
(CollectionTypeHandler) collection.getTypeHandler();
List<Clause> clauses = new ArrayList<Clause>();
List<Column> columns = ctypeHandler.getGranuleColumns();
HashSet<String> seenTable = new HashSet<String>();
Object[] values = granule.getValues();
for (int colIdx = 0; colIdx < columns.size(); colIdx++) {
Column column = columns.get(colIdx);
// first column is the collection ID
int valIdx = colIdx + 1;
String dbTableName = column.getTableName();
if ( !seenTable.contains(dbTableName)) {
clauses.add(
Clause.eq(
ctypeHandler.getCollectionIdColumn(column),
collection.getId()));
clauses.add(Clause.join(Tables.ENTRIES.COL_ID,
dbTableName + ".id"));
seenTable.add(dbTableName);
}
String v = values[valIdx].toString();
if (column.getName().equals("ensemble")) {
clauses.add(Clause.eq(column.getName(), stat));
} else {
if (v.length() > 0) {
clauses.add(Clause.eq(column.getName(), v));
}
}
}
List[] pair = outputHandler.getEntryManager().getEntries(request,
clauses, ctypeHandler.getGranuleTypeHandler());
return pair[1];
}
/**
* Make a climatology for the given entry
* @param request the request
* @param entry the entry
* @param dpi the service input
* @param tail the tail for the new enty file
*
* @return A new entry for the climatology or null
*
* @throws Exception problems creating climatology
*/
protected Entry makeClimatology(Request request, Entry entry,
ServiceInput dpi, String tail)
throws Exception {
return makeClimatology(
request, entry, dpi, tail,
ClimateModelApiHandler.DEFAULT_CLIMATE_START_YEAR,
ClimateModelApiHandler.DEFAULT_CLIMATE_END_YEAR);
}
/**
* Make a climatology for the given entry
* @param request the request
* @param entry the entry
* @param dpi the service input
* @param tail the tail for the new enty file
* @param start start year
* @param end end year
*
* @return A new entry for the climatology or null
*
* @throws Exception problems creating climatology
*/
protected Entry makeClimatology(Request request, Entry entry,
ServiceInput dpi, String tail,
String start, String end)
throws Exception {
return makeStatistic(request, entry, dpi, tail, "clim", start, end);
}
/**
* Make the standard deviation of the anomaly
*
* @param request the request
* @param mean the file for the statistic to work on
* @param dpi the input
* @param tail the file tail
* @param stat the statistic to create (mean, sprd, climo)
* @param startYear start year
* @param endYear end year
*
* @return the anomaly standard deviation
*
* @throws Exception problems
*/
protected Entry makeStatistic(Request request, Entry mean,
ServiceInput dpi, String tail, String stat,
String startYear, String endYear)
throws Exception {
Object[] values = mean.getValues();
String model = values[1].toString();
String statName = IOUtil.stripExtension(tail) + "_" + model + "_"
+ stat + "_" + startYear + "-" + endYear + ".nc";
File statFile = new File(IOUtil.joinDir(dpi.getProcessDir(),
statName));
if ( !statFile.exists()) { // make the file
List<String> commands = initCDOService();
boolean spanYear = doMonthsSpanYearEnd(request, mean);
if ( !spanYear) {
String statCmd = "-ymonmean";
if (stat.equals("sprd") || stat.equals("smegma")) {
statCmd = "-yearmean";
}
commands.add(statCmd);
} else {
int startMonth =
request.get(CDOOutputHandler.ARG_CDO_STARTMONTH, 1);
int endMonth = request.get(CDOOutputHandler.ARG_CDO_ENDMONTH,
startMonth);
int totalMonths = ((12 - startMonth) + 1) + endMonth;
commands.add("-timselmean," + totalMonths);
}
if ( !spanYear) {
String selyears =
ModelUtil.buildClimateYearsString(startYear, endYear,
"/");
commands.add(CDOOutputHandler.OP_SELYEAR + "," + selyears);
} else {
// Start in the previous year if possible since DJF in year starts in December year-1
String seldate = makeDateSelectString(request, mean,
Integer.parseInt(startYear),
Integer.parseInt(endYear));
commands.add(CDOOutputHandler.OP_SELDATE + "," + seldate);
}
getOutputHandler().addMonthSelectServices(request, mean,
commands);
getOutputHandler().addLevelSelectServices(request, mean,
commands, CdmDataOutputHandler.ARG_LEVEL);
commands.add(getPath(request, mean));
commands.add(statFile.toString());
//System.err.println("stat command: "+commands);
runCommands(commands, dpi.getProcessDir(), statFile);
}
Object[] newValues = new Object[values.length];
System.arraycopy(values, 0, newValues, 0, values.length);
newValues[3] = stat;
Resource resource = new Resource(statFile, Resource.TYPE_LOCAL_FILE);
TypeHandler myHandler = getRepository().getTypeHandler("file", true);
Entry statEntry = new Entry(myHandler, true, statFile.toString());
statEntry.setResource(resource);
statEntry.setValues(newValues);
statEntry.addAssociation(new Association(getRepository().getGUID(),
"generated product", "product generated from", mean.getId(),
statEntry.getId()));
return statEntry;
}
/**
* Make a date select string for request spanning the end of the year
*
* @param request the request
* @param sample sample file for dates
* @param start start year
* @param end end year
*
* @return the date select string
*
* @throws Exception problems reading data
*/
protected String makeDateSelectString(Request request, Entry sample,
int start, int end)
throws Exception {
int requestStartMonth =
request.get(CDOOutputHandler.ARG_CDO_STARTMONTH, 1);
int requestEndMonth = request.get(CDOOutputHandler.ARG_CDO_ENDMONTH,
1);
CdmDataOutputHandler dataOutputHandler =
getOutputHandler().getDataOutputHandler();
GridDataset dataset =
dataOutputHandler.getCdmManager().getGridDataset(sample,
getPath(request, sample));
CalendarDateRange dateRange = dataset.getCalendarDateRange();
dataset.close();
int firstDataYearMM = Integer.parseInt(
new CalendarDateTime(
dateRange.getStart()).formattedString(
"yyyyMM",
CalendarDateTime.DEFAULT_TIMEZONE));
int firstDataYear = firstDataYearMM / 100;
int firstDataMonth = firstDataYearMM % 100;
int lastDataYearMM = Integer.parseInt(
new CalendarDateTime(
dateRange.getEnd()).formattedString(
"yyyyMM",
CalendarDateTime.DEFAULT_TIMEZONE));
int lastDataYear = lastDataYearMM / 100;
int lastDataMonth = lastDataYearMM % 100;
// can't go back before the beginning of data or past the last data
if (start <= firstDataYear) {
start = firstDataYear + 1;
}
if (end > lastDataYear) {
end = lastDataYear;
}
if ((end == lastDataYear) && (requestEndMonth > lastDataMonth)) {
end = lastDataYear - 1;
}
StringBuilder yearString = new StringBuilder();
yearString.append(start - 1); // startyear
yearString.append("-");
yearString.append(StringUtil.padZero(requestStartMonth, 2)); // startmonth
yearString.append("-");
yearString.append("01"); // startday
yearString.append("T00:00:00"); // starttime
yearString.append(",");
yearString.append(end); //endyear
yearString.append("-");
yearString.append(StringUtil.padZero(requestEndMonth, 2)); // endmonth
yearString.append("-");
yearString.append(
"" + CDOOutputHandler.DAYS_PER_MONTH[requestEndMonth - 1]); // endday
yearString.append("T23:59:59"); // endtime
return yearString.toString();
}
/**
* Get the output handler
*
* @return the output handler
*/
protected CDOOutputHandler getOutputHandler() {
return outputHandler;
}
/**
* Initialize the CDO command list
*
* @return the initial list of CDO commands
*/
protected List<String> initCDOService() {
List<String> newServices = new ArrayList<String>();
newServices.add(getOutputHandler().getCDOPath());
newServices.add("-L");
newServices.add("-s");
newServices.add("-O");
return newServices;
}
/**
* Run the process
*
* @param commands the list of commands to run
* @param processDir the processing directory
* @param outFile the outfile
*
* @throws Exception problem running commands
*/
protected void runCommands(List<String> commands, File processDir,
File outFile)
throws Exception {
//System.out.println(commands);
// Have to add this for our stupid system
Map<String, String> envMap = new HashMap<String, String>();
envMap.put("HDF5_USE_FILE_LOCKING", "FALSE");
//envMap.put("HDF5_DISABLE_VERSION_CHECK", "2");
long millis = System.currentTimeMillis();
JobManager.CommandResults results =
getRepository().getJobManager().executeCommand(commands, envMap,
processDir, 60);
//System.out.println("processing took: " + (System.currentTimeMillis()-millis));
String errorMsg = results.getStderrMsg();
String outMsg = results.getStdoutMsg();
if ( !outFile.exists()) {
if (outMsg.length() > 0) {
throw new IllegalArgumentException(outMsg);
}
if (errorMsg.length() > 0) {
throw new IllegalArgumentException(errorMsg);
}
if ( !outFile.exists()) {
throw new IllegalArgumentException("Error processing data.");
}
}
}
/**
* Add the statitics widget - use instead of CDOOutputHandler
*
* @param request the Request
* @param sb the HTML
*
* @throws Exception problem adding the statistics widget
*/
public void addStatsWidget(Request request, Appendable sb)
throws Exception {
addStatsWidget(request, sb, null);
}
/**
* Add the statistics widget - use instead of CDOOutputHandler to only show avg/anom
*
* @param request the Request
* @param sb the HTML
* @param si the input
*
* @throws Exception problem adding the statistics widget
*/
public void addStatsWidget(Request request, Appendable sb,
ServiceInput si)
throws Exception {
StringBuilder mysb = new StringBuilder();
mysb.append(
HtmlUtils.radio(
CDOOutputHandler.ARG_CDO_STAT, CDOOutputHandler.STAT_MEAN,
RepositoryManager.getShouldButtonBeSelected(
request, CDOOutputHandler.ARG_CDO_STAT,
CDOOutputHandler.STAT_MEAN, true)));
mysb.append(HtmlUtils.space(1));
mysb.append(Repository.msg("Average"));
mysb.append(HtmlUtils.space(2));
boolean anomSelected =
RepositoryManager.getShouldButtonBeSelected(request,
CDOOutputHandler.ARG_CDO_STAT, CDOOutputHandler.STAT_ANOM,
false);
String anomRB = HtmlUtils.radio(CDOOutputHandler.ARG_CDO_STAT,
CDOOutputHandler.STAT_ANOM,
anomSelected);
mysb.append(anomRB);
mysb.append(HtmlUtils.space(1));
mysb.append(Repository.msg("Anomaly"));
StringBuilder climyearsSB = new StringBuilder();
String type =
si.getProperty(
"type", ClimateModelApiHandler.ARG_ACTION_COMPARE).toString();
mysb.append(HtmlUtils.br());
if (type.equals(ClimateModelApiHandler.ARG_ACTION_ENS_COMPARE)
|| (type.equals(ClimateModelApiHandler.ARG_ACTION_COMPARE)
&& (si.getOperands().size() == 2))) {
climyearsSB.append(Repository.msgLabel("Relative to"));
climyearsSB.append(HtmlUtils.radio(ARG_CLIMATE_DATASET_NUMBER,
"1",
RepositoryManager.getShouldButtonBeSelected(request,
ARG_CLIMATE_DATASET_NUMBER, "1", false)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Dataset 1"));
climyearsSB.append(HtmlUtils.space(2));
climyearsSB.append(HtmlUtils.radio(ARG_CLIMATE_DATASET_NUMBER,
"2",
RepositoryManager.getShouldButtonBeSelected(request,
ARG_CLIMATE_DATASET_NUMBER, "2", false)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Dataset 2"));
climyearsSB.append(HtmlUtils.space(2));
climyearsSB.append(HtmlUtils.radio(ARG_CLIMATE_DATASET_NUMBER,
"0",
RepositoryManager.getShouldButtonBeSelected(request,
ARG_CLIMATE_DATASET_NUMBER, "0", true)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Own Dataset"));
climyearsSB.append(HtmlUtils.br());
}
climyearsSB.append(Repository.msgLabel("Reference Period"));
climyearsSB.append(HtmlUtils.space(1));
addClimYearsWidget(request, climyearsSB, si);
mysb.append(HtmlUtils.div(climyearsSB.toString(),
HtmlUtils.cssClass("ref-years")));
mysb.append(
HtmlUtils.script(
"$('input[name=\"" + CDOOutputHandler.ARG_CDO_STAT
+ "\"]').on('change', function() {\n"
+ " $('.ref-years').toggle(this.value === \""
+ CDOOutputHandler.STAT_ANOM + "\" && this.checked);\n"
+ "}).change();"));
sb.append(HtmlUtils.formEntry(Repository.msgLabel("Statistic"),
mysb.toString()));
}
/**
* Add a widget for selecting the climatology years
* @param request the request
* @param sb the form to add to
* @param si the ServiceInput with all the grids
* @throws Exception problems
*/
protected void addClimYearsWidget(Request request, Appendable sb,
ServiceInput si)
throws Exception {
List<List<ServiceOperand>> sortedOps =
ModelUtil.sortOperandsByCollection(request, si.getOperands());
int numOps = sortedOps.size();
List<List<String>> dataYears = new ArrayList<List<String>>(numOps);
for (List<ServiceOperand> ops : sortedOps) {
List<String> years = new ArrayList<String>();
Entry first = ops.get(0).getEntries().get(0);
//TODO: Get the intersection of all the grid times
CdmDataOutputHandler dataOutputHandler =
getOutputHandler().getDataOutputHandler();
GridDataset dataset =
dataOutputHandler.getCdmManager().getGridDataset(first,
first.getResource().getPath());
if (dataset != null) {
List<CalendarDate> dates =
CdmDataOutputHandler.getGridDates(dataset);
SortedSet<String> uniqueYears =
Collections.synchronizedSortedSet(new TreeSet<String>());
if ((dates != null) && !dates.isEmpty()) {
for (CalendarDate d : dates) {
try { // shouldn't get an exception
String year =
new CalendarDateTime(d).formattedString(
"yyyy",
CalendarDateTime.DEFAULT_TIMEZONE);
uniqueYears.add(year);
} catch (Exception e) {}
}
}
if ( !uniqueYears.isEmpty()) {
years.addAll(uniqueYears);
}
dataset.close();
}
// TODO: make a better list of years
if (years.isEmpty()) {
for (int i =
Integer.parseInt(ClimateModelApiHandler
.DEFAULT_CLIMATE_START_YEAR);
i <= Integer.parseInt(
ClimateModelApiHandler.DEFAULT_CLIMATE_END_YEAR);
i++) {
years.add(String.valueOf(i));
}
}
dataYears.add(years);
}
List<String> commonYears = new ArrayList<String>();
for (int opNum = 0; opNum < sortedOps.size(); opNum++) {
List<String> years = dataYears.get(opNum);
if (opNum == 0) {
commonYears.addAll(years);
} else {
commonYears.retainAll(years);
}
}
StringBuilder yearsWidget = new StringBuilder();
yearsWidget.append(
HtmlUtils.select(
CDOOutputHandler.ARG_CDO_CLIM_STARTYEAR, commonYears,
ClimateModelApiHandler.DEFAULT_CLIMATE_START_YEAR,
HtmlUtils.title("Select the starting reference year")));
yearsWidget.append(Repository.msg(" to "));
yearsWidget.append(
HtmlUtils.select(
CDOOutputHandler.ARG_CDO_CLIM_ENDYEAR, commonYears,
ClimateModelApiHandler.DEFAULT_CLIMATE_END_YEAR,
HtmlUtils.title("Select the ending reference year")));
sb.append(yearsWidget.toString());
}
/**
* Add the statitics widget - use instead of CDOOutputHandler
*
* @param request the Request
* @param sb the HTML
* @param addPct true add a percent normal option
* @param isAnom is this an anomaly file
* @param haveClimo true if we have a climatology
* @throws Exception problem creating widget
*/
public void addStatsWidget(Request request, Appendable sb,
boolean addPct, boolean isAnom,
boolean haveClimo)
throws Exception {
addStatsWidget(request, sb, addPct, isAnom, haveClimo, null,
ClimateModelApiHandler.ARG_ACTION_COMPARE);
}
/**
* Add the statitics widget - use instead of CDOOutputHandler
*
* @param request the Request
* @param sb the HTML
* @param addPct true add a percent normal option
* @param isAnom is this an anomaly file
* @param haveClimo true if we have a climatology
* @param si the input
* @param type the request type
* @throws Exception problem creating widget
*/
public void addStatsWidget(Request request, Appendable sb,
boolean addPct, boolean isAnom,
boolean haveClimo, ServiceInput si,
String type)
throws Exception {
if ( !isAnom) {
List<TwoFacedObject> stats = new ArrayList<TwoFacedObject>();
stats.add(new TwoFacedObject("Average",
CDOOutputHandler.STAT_MEAN));
if (haveClimo) {
stats.add(new TwoFacedObject("Anomaly",
CDOOutputHandler.STAT_ANOM));
stats.add(new TwoFacedObject("Standardized Anomaly",
CDOOutputHandler.STAT_STDANOM));
if (addPct) {
stats.add(new TwoFacedObject("Percent of Normal",
CDOOutputHandler.STAT_PCTANOM));
}
}
StringBuilder statForm = new StringBuilder();
statForm.append(
HtmlUtils.select(
CDOOutputHandler.ARG_CDO_STAT, stats,
request.getString(
CDOOutputHandler.ARG_CDO_STAT,
CDOOutputHandler.STAT_MEAN)));
if ((si != null)
&& (type
.equals(ClimateModelApiHandler
.ARG_ACTION_ENS_COMPARE) || type
.equals(ClimateModelApiHandler
.ARG_ACTION_MULTI_TIMESERIES) || (type
.equals(ClimateModelApiHandler
.ARG_ACTION_COMPARE) && (si
.getOperands()
.size() <= 2)))) {
StringBuilder climyearsSB = new StringBuilder();
statForm.append(HtmlUtils.br());
if (type.equals(ClimateModelApiHandler
.ARG_ACTION_ENS_COMPARE) || (type
.equals(ClimateModelApiHandler
.ARG_ACTION_COMPARE) && (si.getOperands()
.size() == 2))) {
climyearsSB.append(Repository.msgLabel("Relative to"));
climyearsSB.append(
HtmlUtils.radio(
ARG_CLIMATE_DATASET_NUMBER, "1",
RepositoryManager.getShouldButtonBeSelected(
request, ARG_CLIMATE_DATASET_NUMBER, "1",
false)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Dataset 1"));
climyearsSB.append(HtmlUtils.space(2));
climyearsSB.append(
HtmlUtils.radio(
ARG_CLIMATE_DATASET_NUMBER, "2",
RepositoryManager.getShouldButtonBeSelected(
request, ARG_CLIMATE_DATASET_NUMBER, "2",
false)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Dataset 2"));
climyearsSB.append(HtmlUtils.space(2));
climyearsSB.append(
HtmlUtils.radio(
ARG_CLIMATE_DATASET_NUMBER, "0",
RepositoryManager.getShouldButtonBeSelected(
request, ARG_CLIMATE_DATASET_NUMBER, "0",
true)));
climyearsSB.append(HtmlUtils.space(1));
climyearsSB.append(Repository.msg("Own Dataset"));
climyearsSB.append(HtmlUtils.br());
}
climyearsSB.append(Repository.msgLabel("Reference Period"));
climyearsSB.append(HtmlUtils.space(1));
addClimYearsWidget(request, climyearsSB, si);
statForm.append(HtmlUtils.div(climyearsSB.toString(),
HtmlUtils.cssClass("ref-years")));
statForm.append(HtmlUtils.script("$('select[name=\""
+ CDOOutputHandler.ARG_CDO_STAT
+ "\"]').on('change', function() {\n"
+ "$('.ref-years').toggle($(this).val() != \""
+ CDOOutputHandler.STAT_MEAN + "\");\n"
+ "}).change();\n"));
}
sb.append(HtmlUtils.formEntry(Repository.msgLabel("Statistic"),
statForm.toString()));
} else {
sb.append(HtmlUtils.hidden(CDOOutputHandler.ARG_CDO_STAT,
CDOOutputHandler.STAT_ANOM));
}
}
/**
* Can we handle this input
*
* @param input the input
*
* @return true if we can, otherwise false
*/
public boolean canHandle(ServiceInput input) {
if ( !getOutputHandler().isEnabled()) {
return false;
}
for (ServiceOperand op : input.getOperands()) {
if (checkForValidEntries(op.getEntries())) {
continue;
} else {
return false;
}
}
return true;
}
/**
* Check for valid entries. Subclasses need override as necessary
* @param entries list of entries
* @return
*/
protected abstract boolean checkForValidEntries(List<Entry> entries);
/**
* Make a years string for CDO for the list of years
*
* @param years list of years
* @param offset offset
*
* @return a string representation of the years
*/
protected String makeCDOYearsString(List<Integer> years, int offset) {
StringBuilder buf = new StringBuilder();
for (int year = 0; year < years.size(); year++) {
buf.append(years.get(year) + offset);
if (year < years.size() - 1) {
buf.append(",");
}
}
return buf.toString();
}
/**
* Do the months span the year end (e.g. DJF)
*
* @param request the request
* @param oneOfThem a sample file
*
* @return true if they do
*
* @throws Exception problem reading the data
*/
protected static boolean doMonthsSpanYearEnd(Request request,
Entry oneOfThem)
throws Exception {
if (request.defined(CDOOutputHandler.ARG_CDO_MONTHS)
&& request.getString(
CDOOutputHandler.ARG_CDO_MONTHS).equalsIgnoreCase(
"all")) {
return false;
}
// Can't handle years requests yet.
//if (request.defined(CDOOutputHandler.ARG_CDO_YEARS)
// || request.defined(CDOOutputHandler.ARG_CDO_YEARS + "1")) {
// return false;
//}
if (request.defined(CDOOutputHandler.ARG_CDO_STARTMONTH)
|| request.defined(CDOOutputHandler.ARG_CDO_ENDMONTH)) {
int startMonth =
request.defined(CDOOutputHandler.ARG_CDO_STARTMONTH)
? request.get(CDOOutputHandler.ARG_CDO_STARTMONTH, 1)
: 1;
int endMonth = request.defined(CDOOutputHandler.ARG_CDO_ENDMONTH)
? request.get(CDOOutputHandler.ARG_CDO_ENDMONTH,
startMonth)
: startMonth;
// if they requested all months, no need to do a select on month
if ((startMonth == 1) && (endMonth == 12)) {
return false;
}
if (endMonth > startMonth) {
return false;
} else if (startMonth > endMonth) {
return true;
}
}
return false;
}
/**
* Get the path of the entry
* @param r request
* @param e entry
* @return either the file name or the opendap url if ncml
*/
protected String getPath(Request r, Entry e) {
String path = e.getResource().getPath();
if (IOUtil.hasSuffix(path, "ncml")) {
// Handle ncml files through OPeNDAP so programs like CDO can use it
OpendapApiHandler oah =
(OpendapApiHandler) getRepository().getApiManager()
.getApiHandler(OpendapApiHandler.API_ID);
if (oah != null) {
String odapUrl = oah.getOpendapUrl(e);
//path = r.getAbsoluteUrl(odapUrl);
path = getLocalhostUrl(r, odapUrl);
}
}
//System.out.println(path);
return path;
}
/**
* Get the localhost URL
*
* @param r the request
* @param url the URL tail
*
* @return the complete URL pointing to localhost
*/
public String getLocalhostUrl(Request r, String url) {
int port = r.getServerPort();
String protocol = "http";
String localhost = repository.getProperty(CDO_SERVICE_LOCALHOSTNAME,
"localhost");
HttpServletRequest httpServletRequest = r.getHttpServletRequest();
if (httpServletRequest != null) {
protocol = StringUtil.split(httpServletRequest.getScheme(), "/",
true, true).get(0);
}
// System.err.println("Request.getAbsoluteUrl:" + protocol +" port:" + port);
if (port == 80) {
return protocol + "://" + localhost + url;
} else {
return protocol + "://" + localhost + ":" + port + url;
}
}
/**
* Adjust the input to handle operands with multiple files
*
* @param request the request
* @param input the old input
* @return a new input or the old
*
* @throws Exception problem adjusting the input
*/
protected ServiceInput adjustInput(Request request, ServiceInput input)
throws Exception {
ServiceInput newInput = new ServiceInput(input.getProcessDir());
List<ServiceOperand> newOps =
new ArrayList<ServiceOperand>(input.getOperands().size());
for (ServiceOperand so : input.getOperands()) {
List<Entry> opEntries = so.getEntries();
Entry oneOfThem = opEntries.get(0);
if (oneOfThem.getTypeHandler()
instanceof ClimateModelFileTypeHandler) {
if (opEntries.size() == 1) {
newOps.add(so);
} else {
String id =
ModelUtil.makeValuesKey(oneOfThem.getValues(), true);
Entry agg = ModelUtil.aggregateEntriesByTime(request,
opEntries, id, input.getProcessDir());
List<Entry> newEntries = new ArrayList<Entry>();
newEntries.add(agg);
ServiceOperand newOp =
new ServiceOperand(so.getDescription(), newEntries);
copyServiceOperandProperties(so, newOp);
newOps.add(newOp);
}
} else {
newOps.add(so);
}
}
newInput.setOperands(newOps);
// make sure to set the type of service if not null
if (input.getProperty("type") != null) {
newInput.putProperty("type", input.getProperty("type"));
}
return newInput;
}
/**
* Copy over the service operand properties to the new ServiceOperand
*
* @param oldOp old operand
* @param newOp new operand
*/
protected void copyServiceOperandProperties(ServiceOperand oldOp,
ServiceOperand newOp) {
String prop = oldOp.getProperty(
ClimateModelApiHandler.ARG_COLLECTION).toString();
//System.err.println(prop);
if (prop != null) {
newOp.putProperty(ClimateModelApiHandler.ARG_COLLECTION, prop);
for (Entry e : newOp.getEntries()) {
e.putTransientProperty(ClimateModelApiHandler.ARG_COLLECTION,
prop);
}
}
}
/**
* Check to see if this is a model grid
* @param e the entry
* @return return true if climate model type
*/
protected boolean isClimateModelType(Entry e) {
TypeHandler type = e.getTypeHandler();
return (type instanceof ClimateModelFileTypeHandler);
}
/**
* Common code for cdo evaluations
*
* @param request the request
* @param input the input
* @param argPrefix argument prefix
* @param name name of the service
* @param type type of request
*
* @return list of output operands
*
* @throws Exception problems
*/
protected List<ServiceOperand> evaluateInner(Request request,
ServiceInput input, String argPrefix, String name, String type)
throws Exception {
final Request myRequest = request;
final ServiceInput myInput = adjustInput(request, input);
final String argP = argPrefix;
if ( !canHandle(myInput)) {
throw new Exception("Illegal data type");
}
final String myType =
myInput.getProperty(
"type", ClimateModelApiHandler.ARG_ACTION_COMPARE).toString();
final List<ServiceOperand> outputEntries =
new ArrayList<ServiceOperand>();
int opNum = 0;
int numProcs = Runtime.getRuntime().availableProcessors();
long millis = System.currentTimeMillis();
//System.out.println("num Ops = " + myInput.getOperands().size() + ", num processors = " + numProcs);
int numThreads = Math.min(myInput.getOperands().size(), numProcs);
boolean useThreads = (numThreads > 2) && true;
//System.err.println("Using threads: " + useThreads);
ThreadManager threadManager = new ThreadManager(name + ".evaluate");
String stat = request.getString(CDOOutputHandler.ARG_CDO_STAT);
// If we need an anomaly, we run the first evaluation not in a thread so that the climatology
// can get created first and there is no interference with other threads
boolean needAnom = stat.equals(CDOOutputHandler.STAT_ANOM)
|| stat.equals(CDOOutputHandler.STAT_STDANOM)
|| stat.equals(CDOOutputHandler.STAT_PCTANOM);
if (needAnom
&& type.equals(
ClimateModelApiHandler.ARG_ACTION_MULTI_COMPARE)) {
useThreads = false;
}
List<List<ServiceOperand>> sortedOps =
ModelUtil.sortOperandsByCollection(request,
myInput.getOperands());
Entry climSample = null;
if (needAnom && (type.equals(
ClimateModelApiHandler.ARG_ACTION_ENS_COMPARE) || type.equals(
ClimateModelApiHandler.ARG_ACTION_COMPARE))) {
int climDatasetNumber = request.get(ARG_CLIMATE_DATASET_NUMBER,
0);
//sortedOps = sortOpsByModelExperiment(request,
// myInput.getOperands());
//sortedOps = sortOperandsByCollection(request,
// myInput.getOperands());
if ((sortedOps.size() > 1) && (climDatasetNumber > 0)) {
String climKey =
ModelUtil.getModelExperimentString(myRequest,
climDatasetNumber);
for (List<ServiceOperand> myOp : sortedOps) {
Entry firstOne = myOp.get(0).getEntries().get(0);
Object[] values = firstOne.getValues();
String myKey = values[1].toString() + " "
+ values[2].toString();
if (myKey.equals(climKey)) {
climSample = firstOne;
break;
}
}
}
} else {
//sortedOps.add(myInput.getOperands());
}
final Entry myClimSample = climSample;
for (List<ServiceOperand> ops : sortedOps) {
int threadNum = 0;
for (final ServiceOperand op : ops) {
Entry oneOfThem = op.getEntries().get(0);
Entry collection =
GranuleTypeHandler.getCollectionEntry(request, oneOfThem);
String frequency = "Monthly";
if (collection != null) {
//frequency = collection.getValues()[0].toString();
frequency = collection.getValue(0).toString();
}
boolean isMonthly = frequency.toLowerCase().indexOf("mon")
>= 0;
if ( !useThreads || ((threadNum == 0) && needAnom)) {
if (isMonthly) {
outputEntries.add(evaluateMonthlyRequest(request,
myInput, op, opNum, myType, myClimSample));
} else {
outputEntries.add(evaluateDailyRequest(request,
myInput, op, opNum, myType, myClimSample));
}
} else {
final int myOp = opNum;
final boolean myIsMonthly = isMonthly;
//System.out.println("making thread " + opNum);
threadManager.addRunnable(new ThreadManager.MyRunnable() {
public void run() throws Exception {
try {
ServiceOperand so;
if (myIsMonthly) {
so = evaluateMonthlyRequest(myRequest,
myInput, op, myOp, myType,
myClimSample);
} else {
so = evaluateDailyRequest(myRequest,
myInput, op, myOp, myType,
myClimSample);
}
if (so != null) {
synchronized (outputEntries) {
outputEntries.add(so);
}
}
} catch (Exception ve) {
ve.printStackTrace();
}
}
});
}
//if (myInput.getOperands().size() <= 2) {
// opNum++;
//}
threadNum++;
}
opNum++;
}
if (useThreads) {
try {
//System.out.println("Running in " + numThreads + " threads");
threadManager.runInParallel(numThreads);
} catch (Exception ve) {
ve.printStackTrace();
}
}
List<ServiceOperand> output =
new ArrayList<ServiceOperand>(outputEntries.size());
output.addAll(outputEntries);
return output;
}
/**
* Sort the operands by model and experiment
*
* @param request the request
* @param operands all the operands from the ServiceInput
*
* @return sorted list
*
* @throws Exception problems sorting
*/
private List<List<ServiceOperand>> sortOpsByModelExperiment(
Request request, List<ServiceOperand> operands)
throws Exception {
List<List<ServiceOperand>> sortedList =
new ArrayList<List<ServiceOperand>>();
Map<String, List<ServiceOperand>> opMap = new HashMap<String,
List<ServiceOperand>>();
for (ServiceOperand op : operands) {
Entry sample = op.getEntries().get(0);
Object[] values = sample.getValues();
String key = values[1].toString() + " " + values[2].toString();
List<ServiceOperand> myList = opMap.get(key);
if (myList == null) {
myList = new ArrayList<ServiceOperand>();
}
myList.add(op);
opMap.put(key, myList);
}
// check to see if the collections are the same
int numcollections = 2;
if (ModelUtil.getModelExperimentString(request,
1).equals(ModelUtil.getModelExperimentString(request, 2))) {
numcollections = 1;
}
for (int i = 0; i < numcollections; i++) {
List<ServiceOperand> ops =
opMap.get(ModelUtil.getModelExperimentString(request, i + 1));
if (ops != null) {
sortedList.add(ops);
}
}
return sortedList;
}
/**
* Process the monthly request
*
* @param request the request
* @param dpi the ServiceInput
* @param op the operand
* @param opNum the operand number
* @param type the type of request
* @param climSample sample for finding climate entry
*
* @return some output
*
* @throws Exception Problem processing the monthly request
*/
protected abstract ServiceOperand evaluateMonthlyRequest(Request request,
ServiceInput dpi, ServiceOperand op, int opNum, String type,
Entry climSample)
throws Exception;
/**
* Process the daily data request
*
* @param request the request
* @param dpi the ServiceInput
* @param op _more_
* @param opNum _more_
* @param type _more_
* @param climSample _more_
*
* @return some output
*
* @throws Exception problem processing the daily data
*/
protected abstract ServiceOperand evaluateDailyRequest(Request request,
ServiceInput dpi, ServiceOperand op, int opNum, String type,
Entry climSample)
throws Exception;
/**
* Get the climatology entry
*
* @param request the request
* @param dpi the input
* @param oneOfThem a sample from the input
* @param climstartYear starting year for climatology
* @param climendYear ending year for climatology
* @param climType _more_
*
* @return the entry or null
*
* @throws Exception problems
*/
protected Entry getClimatologyEntry(Request request, ServiceInput dpi,
Entry oneOfThem,
String climstartYear,
String climendYear, String climType)
throws Exception {
Entry climEntry = null;
String climFileToUse = null;
if ( !(climstartYear
.equals(ClimateModelApiHandler
.DEFAULT_CLIMATE_START_YEAR) && climendYear
.equals(ClimateModelApiHandler
.DEFAULT_CLIMATE_END_YEAR))) {
if (climFileToUse == null) {
Entry meanEntry = null;
List<Entry> mean = findStatisticEntry(request, oneOfThem,
"mean");
if ((mean == null) || mean.isEmpty()) {
System.out.println("Couldn't find mean, using entry");
meanEntry = oneOfThem;
} else {
if (mean.size() == 1) {
meanEntry = mean.get(0);
} else {
String id =
ModelUtil.makeValuesKey(oneOfThem.getValues(),
true);
meanEntry = ModelUtil.aggregateEntriesByTime(request,
mean, id, dpi.getProcessDir());
}
}
//meanEntry = oneOfThem;
//Object[] mvals = meanEntry.getValues();
//String climTail = mvals[4] + "_" + mvals[1] + "_" + mvals[2];
String mtail =
getOutputHandler().getStorageManager().getFileTail(
meanEntry);
climEntry = makeClimatology(request, meanEntry, dpi, mtail,
climstartYear, climendYear);
if (climEntry != null) {
climFileToUse =
getOutputHandler().getStorageManager().getFileTail(
climEntry);
}
}
} else {
List<Entry> climo = findClimatology(request, oneOfThem);
if ((climo == null) || climo.isEmpty()) {
if (climFileToUse == null) {
Entry meanEntry = null;
List<Entry> mean = findStatisticEntry(request, oneOfThem,
"mean");
if ((mean == null) || mean.isEmpty()) {
System.out.println("Couldn't find mean, using entry");
meanEntry = oneOfThem;
} else {
if (mean.size() == 1) {
meanEntry = mean.get(0);
} else {
String id = ModelUtil.makeValuesKey(
oneOfThem.getValues(), true);
meanEntry =
ModelUtil.aggregateEntriesByTime(request,
mean, id, dpi.getProcessDir());
}
}
//Object[] mvals = meanEntry.getValues();
//String climTail = mvals[4] + "_" + mvals[1] + "_" + mvals[2];
String mtail =
getOutputHandler().getStorageManager().getFileTail(
meanEntry);
climEntry = makeClimatology(request, meanEntry, dpi,
mtail);
//throw new Exception("Unable to find climatology for "
// + oneOfThem.getName());
if (climEntry != null) {
climFileToUse =
getOutputHandler().getStorageManager()
.getFileTail(climEntry);
}
}
System.err.println(
"Couldn't find one - making climo for entry "
+ oneOfThem);
String tail =
getOutputHandler().getStorageManager().getFileTail(
oneOfThem);
climEntry = makeClimatology(request, oneOfThem, dpi, tail);
//throw new Exception("Unable to find climatology for "
// + oneOfThem.getName());
} else if (climo.size() > 1) {
System.err.println("found too many");
} else {
climEntry = climo.get(0);
//System.err.println("found climo: " + climEntry);
}
}
return climEntry;
}
/**
* Get the spread (smegma) entry for the climatology
*
* @param request the request
* @param dpi the input
* @param sample a sample grid
* @param climstartYear starting year for climatology
* @param climendYear ending year for climatology
*
* @return an entry or null
*
* @throws Exception problems
*/
protected Entry getSpreadEntry(Request request, ServiceInput dpi,
Entry sample, String climstartYear,
String climendYear)
throws Exception {
Entry sprdEntry = null;
//System.err.println("Creating spread");
//String statName = "mean";
String statName = "ens01"; // per Marty hoerling - just use the spread of one member
// Find the mean
List<Entry> mean = findStatisticEntry(request, sample, statName);
if ((mean == null) || mean.isEmpty()) {
//System.err.println("Couldn't find " + statName);
// TODO: Should we just exit if no mean?
sprdEntry = sample;
} else if (mean.size() > 1) {
System.err.println("found too many");
} else {
sprdEntry = mean.get(0);
//System.err.println("found mean: " + sprdEntry);
}
//sprdEntry = sample;
// Now make the spread from the mean
String stail =
getOutputHandler().getStorageManager().getFileTail(sprdEntry);
sprdEntry = makeStatistic(request, sprdEntry, dpi, stail, "smegma",
climstartYear, climendYear);
return sprdEntry;
}
}
| 39.634921
| 109
| 0.533094
|
9c73ace07f26feed4c8fb4a0e6c1d284cc256bc2
| 299
|
package io.student.modules.datacenter.dao;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import io.student.modules.datacenter.entity.CameraroomEntity;
@Mapper
public interface CameraroomDao extends BaseMapper<CameraroomEntity> {
}
| 23
| 71
| 0.799331
|
8d8b473fb5ea03c73abc5c67abb6290cb24af6db
| 2,273
|
package org.mapfish.print.attribute;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.Template;
import org.mapfish.print.wrapper.PArray;
import org.mapfish.print.wrapper.PObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Attribute representing the headers from the request.
* <p>
* This is an internal attribute and is added to the system automatically. It does not need to be added in
* the config.yaml file.
*/
@InternalAttribute
public final class HttpRequestHeadersAttribute
extends ReflectiveAttribute<HttpRequestHeadersAttribute.Value> {
/**
* Constructor that calls init.
*/
public HttpRequestHeadersAttribute() {
init();
}
@Override
public Class<Value> getValueType() {
return Value.class;
}
@Override
public Value createValue(final Template template) {
return new Value();
}
@Override
public void validate(final List<Throwable> validationErrors, final Configuration configuration) {
// nothing to do
}
/**
* The object containing the attribute data.
*/
public static final class Value {
/**
* The headers from the request.
*/
public PObject requestHeaders;
/**
* Get all the headers in map form.
*/
public Map<String, List<String>> getHeaders() {
Map<String, List<String>> headerMap = new HashMap<>();
final Iterator<String> keys = this.requestHeaders.keys();
while (keys.hasNext()) {
List<String> valuesAsList = new ArrayList<>();
String headerName = keys.next();
final PArray values = this.requestHeaders.optArray(headerName);
if (values != null) {
for (int i = 0; i < values.size(); i++) {
valuesAsList.add(values.getString(i));
}
} else {
valuesAsList.add(this.requestHeaders.getString(headerName));
}
headerMap.put(headerName, valuesAsList);
}
return headerMap;
}
}
}
| 27.719512
| 107
| 0.603168
|
9f61ca9b6c0e11c57451c373f0efc669642913b1
| 4,518
|
package controllers;
import java.util.ArrayList;
import java.util.Observable;
import algorithms.AbstractAlgorithm;
import algorithms.BinarisationAlgorithm;
import process.AbstractProcessAdapter;
import process.IProcessAdapter;
import process.ProcessThreadAdapter;
import process.ProcessWorkerAdapter;
import tools.StatisticsRecorder;
import views.AbstractView;
import views.MainWindowView;
import models.AbstractModel;
import models.PictureParts;
import models.ProgressionContainer;
/**
* The main controller of the application.
*
* @author Guillaume Cornet
* @author Corentin Legros
*/
public class AppController extends AbstractController {
/**
* The chosen algorithm type
*/
protected int algorithmType;
/**
* The chosen process type
*/
protected int processType;
/**
* Available process adapters
*/
protected ArrayList<AbstractProcessAdapter<PictureParts>> availableAdapters;
/**
* Available algorithms (used by process)
*/
protected ArrayList<AbstractAlgorithm> availableAlgorithms;
protected StatisticsRecorder statisticsRecorder;
protected int tmpLastPercent;
/**
* Reference on the container used for reports
*/
protected ProgressionContainer progressionContainer;
public AppController(AbstractModel model, AbstractView view) {
super(model, view);
// adding available Adapters
availableAdapters = new ArrayList<AbstractProcessAdapter<PictureParts>>();
availableAdapters.add(IProcessAdapter.PROCESS_TYPE_UNSELECTED, null); // ugly way, but it works.
availableAdapters.add(IProcessAdapter.PROCESS_TYPE_THREAD, new ProcessThreadAdapter());
availableAdapters.add(IProcessAdapter.PROCESS_TYPE_FORKJOIN, new ProcessWorkerAdapter());
// adding available algorithms
availableAlgorithms = new ArrayList<AbstractAlgorithm>();
availableAlgorithms.add(AbstractAlgorithm.ALGORITHM_TYPE_UNSELECTED, null); // ugly way, but it works.
availableAlgorithms.add(AbstractAlgorithm.ALGORITHM_TYPE_BINARISATION, new BinarisationAlgorithm());
statisticsRecorder = StatisticsRecorder.getInstance();
statisticsRecorder.setPickUpRange(5);
tmpLastPercent = 0;
}
/**
* @return the algorithmType
*/
public int getAlgorithmType() {
return algorithmType;
}
/**
* @param algorithmType the algorithmType to set
*/
public void setAlgorithmType(int algorithmType) {
this.algorithmType = algorithmType;
}
/**
* @return the processType
*/
public int getProcessType() {
return processType;
}
/**
* @param processType the processType to set
*/
public void setProcessType(int processType) {
this.processType = processType;
}
/**
* This method is in charge of launching the process.
* It sets all data to chosen algorithm and specified process adapter
*
* @see ProcessButtonListener.actionPerformed()
*/
public void launchProcess() {
AbstractProcessAdapter<PictureParts> adapter;
adapter = availableAdapters.get(processType);
adapter.setData((PictureParts) refModel.getData());
availableAlgorithms.get(algorithmType).setDataContainer((PictureParts) refModel.getData());
// this line is here in order to set a valid algorithm state to clone it and then change the working part (for each thread/worker)
availableAlgorithms.get(algorithmType).setData(((PictureParts) refModel.getData()).getPart(0));
adapter.setAlgorithm(availableAlgorithms.get(algorithmType));
statisticsRecorder.start(processType, ((MainWindowView) refView).getChosenFileLabel().getText(), ((MainWindowView) refView).getNWComboBox().getSelectedIndex());
adapter.execute();
statisticsRecorder.stop();
((MainWindowView) refView).getExportButton().setEnabled(true);
}
public void update(Observable o, Object arg) {
// here will be the timer management
// and all statistics generation of timing measures
progressionContainer = (ProgressionContainer) arg;
if (progressionContainer.getPercent() == 0 || progressionContainer.getPercent() > progressionContainer.getLastPercent()
||
(progressionContainer.getPercent() <= progressionContainer.getLastPercent() && progressionContainer.getPercent() >= 100 - statisticsRecorder.getPickUpRange())) {
statisticsRecorder.addData(
progressionContainer.getPartNumber()
);
progressionContainer.setLastPercent(progressionContainer.getLastPercent() + statisticsRecorder.getPickUpRange());
}
}
}
| 31.375
| 166
| 0.747233
|
183f4bd9453e4b5944901568c9bc54392b8ede6e
| 6,639
|
package sk.bpositive.bcommon.firebase;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
import java.math.BigInteger;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import sk.bpositive.bcommon.BCommonExtension;
/**
* Created by jhorvath on 14/12/2017.
*/
public class Utils {
public static Integer safeGetColorFromHex(String colorString)
{
if(colorString == null){
return null;
}
try
{
return new BigInteger(colorString, 16).intValue();
}
catch (Throwable t) {
BCommonExtension.debug("Cannot parse color string: " + colorString, t);
}
return null;
}
public static CharSequence getTitle(Context context, String title)
{
if (title != null) {
return title;
}
return context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
}
private static boolean isValidResourceName(String name)
{
return (name != null) && (!name.matches("^[0-9]"));
}
public static Bitmap getLargeIcon(Context context, String largeIcon)
{
Bitmap bitmap = getBitmap(context, largeIcon);
if (bitmap == null) {
return null;
}
return resizeBitmapForLargeIconArea(context.getResources(), bitmap);
}
private static Bitmap resizeBitmapForLargeIconArea(Resources resources, Bitmap bitmap)
{
if (bitmap == null) {
return null;
}
try
{
int systemLargeIconHeight = (int)resources.getDimension(android.R.dimen.notification_large_icon_height);
int systemLargeIconWidth = (int)resources.getDimension(android.R.dimen.notification_large_icon_width);
int bitmapHeight = bitmap.getHeight();
int bitmapWidth = bitmap.getWidth();
if ((bitmapWidth > systemLargeIconWidth) || (bitmapHeight > systemLargeIconHeight))
{
int newWidth = systemLargeIconWidth;int newHeight = systemLargeIconHeight;
if (bitmapHeight > bitmapWidth)
{
float ratio = bitmapWidth / bitmapHeight;
newWidth = (int)(newHeight * ratio);
}
else if (bitmapWidth > bitmapHeight)
{
float ratio = bitmapHeight / bitmapWidth;
newHeight = (int)(newWidth * ratio);
}
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
}
catch (Throwable localThrowable) {}
return bitmap;
}
public static Bitmap getBitmapFromAssetsOrResourceName(Context context, String bitmapStr)
{
try
{
Bitmap bitmap = null;
try
{
bitmap = BitmapFactory.decodeStream(context.getAssets().open(bitmapStr));
}
catch (Throwable localThrowable) {}
if (bitmap != null) {
return bitmap;
}
List<String> image_extensions = Arrays.asList(".png", ".webp", ".jpg", ".gif", ".bmp");
for (String extension : image_extensions)
{
try
{
bitmap = BitmapFactory.decodeStream(context.getAssets().open(bitmapStr + extension));
}
catch (Throwable localThrowable1) {}
if (bitmap != null) {
return bitmap;
}
}
int bitmapId = getResourceIcon(context, bitmapStr);
if (bitmapId != 0) {
return BitmapFactory.decodeResource(context.getResources(), bitmapId);
}
}
catch (Throwable localThrowable2) {}
return null;
}
private static Bitmap getBitmapFromURL(String location)
{
try
{
return BitmapFactory.decodeStream(new URL(location).openConnection().getInputStream());
}
catch (Throwable t)
{
BCommonExtension.debug("Could not download image!", t);
}
return null;
}
public static Bitmap getBitmap(Context context, String name)
{
if (name == null) {
return null;
}
String trimmedName = name.trim();
if ((trimmedName.startsWith("http://")) || (trimmedName.startsWith("https://"))) {
return getBitmapFromURL(trimmedName);
}
return getBitmapFromAssetsOrResourceName(context, name);
}
private static int getResourceIcon(Context context, String iconName)
{
if (iconName == null) {
return 0;
}
String trimmedIconName = iconName.trim();
if (!isValidResourceName(trimmedIconName)) {
return 0;
}
int notificationIcon = getDrawableId(context, trimmedIconName);
if (notificationIcon != 0) {
return notificationIcon;
}
try
{
return android.R.drawable.class.getField(iconName).getInt(null);
}
catch (Throwable localThrowable) {}
return 0;
}
public static int getSmallIconId(Context context, String smallIconId)
{
int notificationIcon = getResourceIcon(context, smallIconId);
if (notificationIcon != 0) {
return notificationIcon;
}
return android.R.drawable.ic_popup_reminder;
}
private static int getDrawableId(Context context, String name)
{
BCommonExtension.debug("getDrawableId " + name);
return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
}
public static Uri getSoundUri(Context context, String sound) {
if (sound == null){
return null;
}
Resources resources = context.getResources();
String packageName = context.getPackageName();
int soundId;
if (isValidResourceName(sound)) {
soundId = resources.getIdentifier(sound, "raw", packageName);
if (soundId != 0)
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/" + soundId);
}
return null;
}
}
| 31.023364
| 116
| 0.586534
|
092d237f71eef8369bffa978a4395b7d6b89f077
| 4,144
|
/*
Copyright (c) 2012, Apps4Av Inc. (apps4av.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ds.avare.position;
import com.ds.avare.utils.BitmapHolder;
/**
*
* @author zkhan
*
*/
public class Pan {
/**
* Current x mMovement pan
*/
private float mMoveX;
/**
* Current y mMovement pan
*/
private float mMoveY;
/**
* X and Y params for tiles outside of current area.
* For panning beyond current tiles.
*/
private int mMoveXTile;
private int mMoveYTile;
private float mMoveXTileOld;
private float mMoveYTileOld;
/**
*
*/
public Pan() {
mMoveX = 0;
mMoveY = 0;
mMoveXTile = 0;
mMoveYTile = 0;
mMoveXTileOld = 0;
mMoveYTileOld = 0;
}
/**
*
*
* @param p
*/
public Pan(Pan p) {
mMoveX = p.mMoveX;
mMoveY = p.mMoveY;
mMoveXTile = p.mMoveXTile;
mMoveYTile = p.mMoveYTile;
mMoveXTileOld = p.mMoveXTileOld;
mMoveYTileOld = p.mMoveYTileOld;
}
/**
*
* @param x
* @param y
* @return
*/
public boolean setMove(float x, float y) {
mMoveX = x;
mMoveY = y;
/*
* Find if moving out of current area.
*/
boolean update = false;
/*
* Update tiles if we pan outside of current area.
* But do not update right now so we reduce tearing.
*/
float mMoveXTilexOld = -(int)Math.round(mMoveX / BitmapHolder.WIDTH);
if(mMoveXTilexOld != mMoveXTileOld) {
mMoveXTileOld = mMoveXTilexOld;
update = true;
}
int mMoveYTileyOld = -(int)Math.round(mMoveY / BitmapHolder.HEIGHT);
if(mMoveYTileyOld != mMoveYTileOld) {
mMoveYTileOld = mMoveYTileyOld;
update = true;
}
return update;
}
/**
*
* @param x
* @param y
*/
public void setTileMove(int x, int y) {
mMoveXTile = x;
mMoveYTile = y;
}
/**
*
* @return
*/
public float getMoveX() {
return mMoveX;
}
/**
*
* @return
*/
public float getMoveY() {
return mMoveY;
}
/**
*
* @return
*/
public int getTileMoveX() {
return mMoveXTile;
}
/**
*
* @return
*/
public int getTileMoveY() {
return mMoveYTile;
}
/**
*
* @return
*/
public int getTileMoveXWithoutTear() {
return (int)mMoveXTileOld;
}
/**
*
* @return
*/
public int getTileMoveYWithoutTear() {
return (int)mMoveYTileOld;
}
}
| 26.062893
| 765
| 0.572394
|
8548ce7f28513750a5b368ec911875abba249ef4
| 197
|
public class Countdown {
// Counts down from 10 to 0, then prints "DONE!"
public static void main(String[] args) {
for (int i = 10; i >= 0; i--) {
System.out.println(i);
}
}
}
| 19.7
| 50
| 0.568528
|
0c018c5ba33128d1905387b7cafae89c7e959bae
| 288
|
package com.Stevedores.Stevedores.repository;
import com.Stevedores.Stevedores.dto.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
| 28.8
| 70
| 0.847222
|
636646c000f9e57070f1d1f4f090f06b7ee19063
| 2,809
|
package ch.ethz.karto.map3d;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.media.nativewindow.AbstractGraphicsDevice;
import javax.media.opengl.GL;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLPbuffer;
import javax.media.opengl.GLProfile;
/**
* Provides information about the OpenGL systems that support pbuffers. Older
* Windows systems do not support pbuffers, for these systems, use
* the OpenGLCapabilitiesWindowsNoPBuffer class that overwrites pbuffer specific
* methods.
* All methods must be called from the OpenGL thread.
* @author Bernhard Jenny, Institute of Cartography, ETH Zurich
*/
public class OpenGLCapabilities {
protected GLContext lastContext, newContext;
private final GLPbuffer buffer;
protected OpenGLCapabilities(GLProfile profile, AbstractGraphicsDevice graphicsDevice) {
GLDrawableFactory factory = GLDrawableFactory.getFactory(profile);
GLCapabilities caps = new GLCapabilities(profile);
caps.setDoubleBuffered(false);
// createGLPbuffer throws a GLException if pbuffers are not supported.
buffer = factory.createGLPbuffer(graphicsDevice, caps, null, 1, 1, null);
}
protected GL getGL() {
try {
switchToNewContext(buffer.getContext());
return buffer.getGL();
} catch (Throwable e) {
}
return null;
}
/**
* Releases the current context, and makes the passed context the current one.
* @param context
*/
protected void switchToNewContext(final GLContext context) {
lastContext = GLContext.getCurrent();
if (context == lastContext) {
newContext = null;
return;
}
if (lastContext != null) {
lastContext.release();
}
newContext = context;
newContext.makeCurrent();
}
/**
* Switch back to previous context: Reverts to the previously replaced
* context and distroys the current one.
*/
protected void restoreLastGLContext() {
if (newContext != null) {
newContext.release();
}
if (lastContext != null) {
lastContext.makeCurrent();
}
if (newContext != null) {
if (!isMacOS()) {
newContext.destroy(); // causes flickering on Mac
}
}
if (buffer != null) {
if (!isMacOS()) {
buffer.destroy(); // causes flickering on Mac
}
}
}
private boolean isMacOS() {
String osName = System.getProperty("os.name");
return osName.startsWith("Mac OS");
}
}
| 30.204301
| 92
| 0.641153
|
6c244602286af7449cd962cf8d06a8190c7fca2c
| 1,872
|
package com.ultramixer.jtimezone.mac;
import com.ultramixer.jtimezone.JTimeZoneChangeListener;
import com.ultramixer.jtimezone.JTimeZoneProvider;
import org.joda.time.DateTimeZone;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* Created by TB on 10.04.15.
*/
public class MacJTimeZoneProvider implements JTimeZoneProvider
{
private ArrayList<JTimeZoneChangeListener> timeZoneChangeListeners = new ArrayList<JTimeZoneChangeListener>(1);
private Logger logger = Logger.getLogger(getClass().getName());
public void addTimeZoneChangeListener(JTimeZoneChangeListener listener)
{
timeZoneChangeListeners.add(listener);
if (timeZoneChangeListeners.size() == 1)
{
startTimeZoneChangeListening();
}
}
private void startTimeZoneChangeListening()
{
NSSystemTimeZoneDidChangeNotificationManager.getInstance().setListeners(timeZoneChangeListeners);
}
private void stopTimeZoneChangeListening()
{
if (NSSystemTimeZoneDidChangeNotificationManager.instance != null)
{
NSSystemTimeZoneDidChangeNotificationManager.getInstance().setListeners(null);
}
}
public boolean removeTimeZoneChangeListener(JTimeZoneChangeListener listener)
{
return timeZoneChangeListeners.remove(listener);
}
public String getDefaultTimeZoneName()
{
return NSTimeZone.defaultTimeZone().getName();
}
public DateTimeZone getDefaultTimeZone()
{
//String timeZoneName = this.getDefaultTimeZoneName();
//return DateTimeZone.forID(timeZoneName);
return DateTimeZone.forOffsetMillis(getDefaultTimeZoneOffsetInMillis().intValue());
}
public Long getDefaultTimeZoneOffsetInMillis()
{
return NSTimeZone.defaultTimeZone().getSecondsFromGMT() * (long) 1000;
}
}
| 27.529412
| 115
| 0.725427
|
9c38ce4f0543542e6b4f0a5f7417b41e5bca808a
| 1,441
|
package com.danilov.supermanga.core.theme;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.util.TypedValue;
/**
* Created by Semyon on 21.03.2016.
*/
public class ThemeUtils {
public static int getReferencedResource(@AttrRes final int attr, final Context context) {
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
public static Drawable getReferencedDrawable(@AttrRes final int attr, final Context context) {
// Create an array of the attributes we want to resolve
// using values from a theme
int[] attrs = new int[]{attr};
// Obtain the styled attributes. 'themedContext' is a context with a
// theme, typically the current Activity (i.e. 'this')
TypedArray ta = context.obtainStyledAttributes(attrs);
// To get the value of the 'listItemBackground' attribute that was
// set in the theme used in 'themedContext'. The parameter is the index
// of the attribute in the 'attrs' array. The returned Drawable
// is what you are after
Drawable drawableFromTheme = ta.getDrawable(0);
// Finally, free the resources used by TypedArray
ta.recycle();
return drawableFromTheme;
}
}
| 35.146341
| 98
| 0.692575
|
e1f8ac26fd7c3c56fef60d7b650f5ec5c99897f3
| 1,635
|
package com.sivc.webapp.controller;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {
@InjectMocks
private UserController controller;
@Mock
private UserManager userManager;
private MockMvc mockMvc;
@Before
@SuppressWarnings("unchecked")
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
// set expected behavior on manager
User user1 = new User();
user1.setFirstName("ControllerTest");
final List<User> users = new ArrayList<User>();
users.add(user1);
when(userManager.getUsers()).thenReturn(users);
}
@Test
public void testGetUsers() throws Exception {
mockMvc.perform(post("/users"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("userList"))
.andExpect(view().name("userList"));
}
}
| 30.277778
| 87
| 0.727829
|
06671e4c8c2e7e79f253821c43fb1570240a2c86
| 678
|
package ru.mytasks.models;
public class Sock {
private String color;
private int cottonPart;
private int quantity;
public Sock() {
}
public Sock(String color, int cottonPart, int quantity) {
this.setColor(color);
this.setCottonPart(cottonPart);
this.setQuantity(quantity);
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getCottonPart() {
return cottonPart;
}
public void setCottonPart(int cottonPart) {
this.cottonPart = cottonPart;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
| 15.767442
| 58
| 0.69764
|
6ee070af3f5275eb4a38157a78d1f07541446b2c
| 488
|
package ua.com.fielden.platform.sample.domain;
import com.google.inject.Inject;
import ua.com.fielden.platform.dao.CommonEntityDao;
import ua.com.fielden.platform.entity.annotation.EntityType;
import ua.com.fielden.platform.entity.query.IFilter;
@EntityType(TgModelYearCount.class)
public class TgModelYearCountDao extends CommonEntityDao<TgModelYearCount> implements ITgModelYearCount {
@Inject
protected TgModelYearCountDao(IFilter filter) {
super(filter);
}
}
| 27.111111
| 105
| 0.79918
|
0cc92a635ab60167ef587d5415d64d385feeaa26
| 1,440
|
package de.hft_stuttgart.sw.projectindoorapp.models.external;
/**
* Created by usman on 04-Dec-17.
*/
public class RssiSignal {
private Long id;
private double appTimestamp;
private double rssiSignalStrength;
private boolean averagedSignalStrength;
private WifiAccessPoint wifiAccessPoint;
public WifiAccessPoint getWifiAccessPoint() {
return wifiAccessPoint;
}
public RssiSignal setWifiAccessPoint(WifiAccessPoint wifiAccessPoint) {
this.wifiAccessPoint = wifiAccessPoint;
return this;
}
protected RssiSignal(){}
public Long getId() {
return id;
}
public RssiSignal setId(Long id) {
this.id = id;
return this;
}
public double getAppTimestamp() {
return appTimestamp;
}
public RssiSignal setAppTimestamp(double appTimestamp) {
this.appTimestamp = appTimestamp;
return this;
}
public double getRssiSignalStrength() {
return rssiSignalStrength;
}
public RssiSignal setRssiSignalStrength(double rssiSignalStrength) {
this.rssiSignalStrength = rssiSignalStrength;
return this;
}
public boolean isAveragedSignalStrength() {
return averagedSignalStrength;
}
public RssiSignal setAveragedSignalStrength(boolean averagedSignalStrength) {
this.averagedSignalStrength = averagedSignalStrength;
return this;
}
}
| 23.606557
| 81
| 0.686111
|
4195a3ec41c1a81c36b7e77286610127ac44f3e1
| 918
|
package org.dainst.chronontology.config;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Properties;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* @author Daniel M. de Oliveira
*/
public class ElasticsearchDatastoreConfigTest {
Properties props = null;
@BeforeMethod
public void before() {
props= new Properties();
}
@Test
public void test() {
props.put("datastore.elasticsearch.indexName",ConfigConstants.ES_INDEX_NAME);
props.put("datastore.elasticsearch.url","http://localhost:9200");
ElasticsearchDatastoreConfig config= new ElasticsearchDatastoreConfig();
assertTrue(config.validate(props));
assertEquals(config.getIndexName(),ConfigConstants.ES_INDEX_NAME);
assertEquals(config.getUrl(),"http://localhost:9200");
}
}
| 25.5
| 85
| 0.721133
|
82e7864f11b625845f6c4e476d8d84b8e8b1fb21
| 1,338
|
package com.telecominfraproject.wlan.equipment.models;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.telecominfraproject.wlan.core.model.json.JsonDeserializationUtils;
public enum TunnelIndicator {
no(0L),
primary(1L),
secondary(2L),
UNSUPPORTED(-1L);
private final long id;
private static final Map<Long, TunnelIndicator> ELEMENTS = new HashMap<>();
private TunnelIndicator(long id) {
this.id = id;
}
public long getId() {
return this.id;
}
public static TunnelIndicator getById(long enumId) {
if (ELEMENTS.isEmpty()) {
synchronized (ELEMENTS) {
if (ELEMENTS.isEmpty()) {
//initialize elements map
for(TunnelIndicator met : TunnelIndicator.values()) {
ELEMENTS.put(met.getId(), met);
}
}
}
}
return ELEMENTS.get(enumId);
}
@JsonCreator
public static TunnelIndicator getByName(String value) {
return JsonDeserializationUtils.deserializEnum(value, TunnelIndicator.class, UNSUPPORTED);
}
public static boolean isUnsupported(TunnelIndicator value) {
return UNSUPPORTED.equals(value);
}
}
| 26.235294
| 98
| 0.617339
|
1c33640c893348a5863759b88df2995605b6a519
| 6,077
|
package org.opensha.commons.geo;
/**
* This class encapsulates information describing a vector between two
* <code>Location</code>s. This vector is defined by the azimuth (bearing) from
* a point p1 to a point p2, and also by the horizontal and vertical separation
* between the points. Note that a <code>LocationVector</code> from point A to
* point B is not the complement of that from point B to A. Although the
* horizontal and vertical components will be the same, the azimuth will likely
* change by some value other than 180°.<br/>
* <br/>
* <b>Note:</b> Although a <code>LocationVector</code> will function in any
* reference frame, the convention in seismology and that adopted in OpenSHA is
* for depth to be positive down.<br/>
*
* @author Peter Powers
* @author Sid Hellman
* @author Steven W. Rock
* @version $Id: LocationVector.java 9760 2012-12-05 18:32:55Z pmpowers $
*/
// TODO refactor horx vert method names
// TODO should store azimuth in radians
// <b>Note:</b> Azimuth is stored internally in radians for computational
// convenience. Be sure to use the {@link #getAzimuth()} (decimal-degrees) or
// {@link #getAzimuthRad()} (radians) where appropriate.
public class LocationVector {
/*
* Developer Notes: The previous version of this class as 'LocationVector'
* included back azimuth. There are (were) instances in OpenSHA where this
* was taken to be the azimuth from point B to A (for an azimuth from point
* A to B). As Back azimuth is generally defined, this interp is incorrect.
* Back azimuth is the 180 degree complement of the azimuth at an origin
* point. Under the assumed interpretation, each LocationVector was
* implicitely Location dependent, but that information was never stored as
* part of this class. Furthermore, the onus was on the user to provide the
* correct value for back azimuth. This property of the class has been
* removed and users are directed in LocationUtils.azimuth() to simply
* reverse the points of interest if the bearing from B to A is required.
*/
private double azimuth;
private double vertical;
private double horizontal;
/**
* Initializes a new <code>LocationVector</code> with azimuth and horizontal
* and vertical components all initialized to 0.
*/
public LocationVector() {}
/**
* Initializes a new <code>LocationVector</code> with the supplied values.
* Note that <code>azimuth</code> is expected in <i>decimal degrees</i>.
*
* @param azimuth value to set in <i>decimal degrees</i>
* @param horizontal component value to set
* @param vertical component value to set
*/
public LocationVector(double azimuth, double horizontal, double vertical) {
set(azimuth, horizontal, vertical);
}
/**
* Sets this <code>LocationVector</code>'s internal fields to the supplied
* values. Note that <code>azimuth</code> is expected in <i>decimal
* degrees</i>.
*
* @param azimuth value to set in <i>decimal degrees</i>
* @param horizontal component value to set
* @param vertical component value to set
*/
public void set(double azimuth, double horizontal, double vertical) {
this.azimuth = azimuth;
this.horizontal = horizontal;
this.vertical = vertical;
}
/**
* Reverses the azimuth (to 'back-azimuth') and flips the sign of the
* vertical component of this <code>LocationVector</code>.
*/
public void reverse() {
azimuth = (azimuth + 180) % 360;
vertical = -vertical;
}
/**
* Returns the azimuth of this <code>LocationVector</code> in decimal
* degrees.
* @return the azimuth value in decimal degrees
* @see #getAzimuthRad()
*/
public double getAzimuth() {
return azimuth;
// return azimuth * LocationUtils.TO_DEG;
}
/**
* Returns the azimuth of this <code>LocationVector</code> in radians.
* @return the azimuth value in radians
* @see #getAzimuth()
*/
public double getAzimuthRad() {
return azimuth * GeoTools.TO_RAD;
}
/**
* Sets the azimuth of this <code>LocationVector</code>.
* @param azimuth value to set in <i>decimal degrees</i>
*/
public void setAzimuth(double azimuth) {
this.azimuth = azimuth;
}
/**
* Returns the angle (in decimal degrees) between this vector and the
* horizontal based on the current internal vertical and horizontal
* separation values. This method is intended for use at relatively short
* separations ( e.g. <eq; 200km) as it degrades at large distances where
* curvature is not considered. Note that positive angles are down, negative
* angles are up.
* @return the plunge of this vector
*/
public double getPlunge() {
return Math.atan(vertical / horizontal) * GeoTools.TO_DEG;
}
/**
* Gets the vertical component of this <code>LocationVector</code>.
* @return the vertical component value in km
*/
public double getVertDistance() {
return vertical;
}
/**
* Sets the vertical component of this <code>LocationVector</code>.
* @param vertical component value to set in km
*/
public void setVertDistance(double vertical) {
this.vertical = vertical;
}
/**
* Gets the horizontal component of this <code>LocationVector</code>.
* @return the horizontal component value in km
*/
public double getHorzDistance() {
return horizontal;
}
/**
* Sets the horizontal component of this <code>LocationVector</code>.
* @param horizontal component value to set in km
*/
public void setHorzDistance(double horizontal) {
this.horizontal = horizontal;
}
@Override
public String toString() {
StringBuffer b = new StringBuffer();
b.append(this.getClass().getSimpleName());
b.append(": az = ");
b.append(getAzimuth());
b.append(" dH = ");
b.append(horizontal);
b.append(" dV = ");
b.append(vertical);
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LocationVector) {
LocationVector dir = (LocationVector) obj;
if (horizontal != dir.horizontal) return false;
if (vertical != dir.vertical) return false;
if (azimuth != dir.azimuth) return false;
return true;
}
return false;
}
}
| 32.497326
| 79
| 0.7117
|
7c6f68a1b0d72010d76d9bf7023d3bd77ff3e0a0
| 4,500
|
package com.sms.msgsend.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.sms.msgsend.constants.SystemConstant;
import com.sms.msgsend.enums.ResultCodeEnum;
import com.sms.msgsend.exception.DecryptionException;
import com.sms.msgsend.exception.EncryptionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.sms.msgsend.enums.EncryptionMethodEnum.*;
/**
* desc 工具类
* 封装 hutool 没有的工具类
*
* @author ${user}
* @date 2020/12/14
*/
public class Util {
private static final Logger logger = LoggerFactory.getLogger(Util.class);
/**
* desc 简单判断是否是XML类型
*
* @param str
* @return
*/
public static boolean isXMLType(String str) {
boolean result = false;
if (StrUtil.isNotBlank(str)) {
str = str.trim();
if (XML.LT.equals(str.charAt(SystemConstant.ZERO)) && XML.GT.equals(str.charAt(str.length() - SystemConstant.ONE))) {
result = true;
}
}
return result;
}
/**
* 解密方法
*
* @param contents
* @return
*/
public static String decrypt(String encryptionMethod, String encryptionKey, String password, String contents) {
String decryptStr = "";
try {
// 解密
if (AESMethod.getCode().equals(encryptionMethod)) {
//构建
AES aes = SecureUtil.aes(encryptionKey.getBytes());
decryptStr = aes.decryptStr(contents);
}
if (DESMethod.getCode().equals(encryptionMethod)) {
DES des = SecureUtil.des(encryptionKey.getBytes());
decryptStr = des.decryptStr(contents);
}
if (MD5Method.getCode().equals(encryptionMethod)) {
decryptStr = SecureUtil.md5(contents);
if (password.equals(decryptStr) == false) {
logger.error("MD5验签校验失败");
throw new DecryptionException(ResultCodeEnum.DecryptionError.getvalue());
}
decryptStr = contents;
}
if (StrUtil.isBlank(decryptStr)) {
logger.error("解密校验失败");
throw new DecryptionException(ResultCodeEnum.DecryptionError.getvalue());
}
System.out.println("decryptStr:" + decryptStr);
} catch (Exception e) {
e.printStackTrace();
throw new DecryptionException(ResultCodeEnum.DecryptionError.getvalue());
}
return decryptStr;
}
/**
* 加密方法
*
* @param contents
* @return
*/
public static String encrypt(String encryptionMethod, String encryptionKey, String contents) {
String encryptStr = "";
try {
// 解密
if (AESMethod.getCode().equals(encryptionMethod)) {
//构建
AES aes = SecureUtil.aes(encryptionKey.getBytes());
encryptStr = aes.encryptHex(contents);
}
if (DESMethod.getCode().equals(encryptionMethod)) {
DES des = SecureUtil.des(encryptionKey.getBytes());
encryptStr = des.encryptHex(contents);
}
if (MD5Method.getCode().equals(encryptionMethod)) {
encryptStr = SecureUtil.md5(contents);
}
if (StrUtil.isBlank(encryptStr)) {
logger.error("加密校验失败");
throw new EncryptionException(ResultCodeEnum.EncryptionError.getvalue());
}
System.out.println("encryptStr:" + encryptStr);
} catch (Exception e) {
throw new EncryptionException(ResultCodeEnum.EncryptionError.getvalue());
}
return encryptStr;
}
/**
* 得到json内容
*
* @param shortMessageVO
* @return
*/
public static JSONObject getJsonMsg(String shortMessageVO) {
JSONObject jsonObject = null;
// 判断是否为XML
if (Util.isXMLType(shortMessageVO)) {
// XML转为JSON处理
jsonObject = XML.toJSONObject(shortMessageVO);
}
// 判断其是否为JSON
if (JSONUtil.isJson(shortMessageVO)) {
jsonObject = JSONUtil.parseObj(shortMessageVO);
}
// todo 接收其他方式报文体
return jsonObject;
}
}
| 30.201342
| 129
| 0.582222
|
cf005c1baa9b8624897a8aabe87830c40bc028ec
| 1,101
|
package com.example.android.tourguide;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Created by benwong on 2016-07-09.
*/
public class EventFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_event, container, false);
ArrayList<LocationImage> arrayOfLocationImages = new ArrayList<LocationImage>();
LocationImageAdapter adapter = new LocationImageAdapter(getActivity(), arrayOfLocationImages);
ListView listView = (ListView) v.findViewById(R.id.eventlvItems);
listView.setAdapter(adapter);
LocationImage newLocation1 = new LocationImage(getActivity().getString(R.string.stampedeName), getActivity().getString(R.string.stampedeAddress), R.drawable.stampedeimg);
adapter.add(newLocation1);
return v;
}
}
| 29.756757
| 178
| 0.751135
|
67b2cbd6262c31bcf9fd1f203b5305dba01feb3a
| 808
|
package com.onevgo.springboot.security.entity;
import java.util.List;
public class SysRole {
private String role;
private String name;
private List<SysPermission> permissionList;
public SysRole() {
}
public SysRole(String role, String name) {
this.role = role;
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<SysPermission> getPermissionList() {
return permissionList;
}
public void setPermissionList(List<SysPermission> permissionList) {
this.permissionList = permissionList;
}
}
| 18.790698
| 71
| 0.623762
|
4048dfb75bc4d7569aa81418f77d3ceb1113c44c
| 2,691
|
/*
* Copyright [2012-2015] PayPal Software Foundation
*
* 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 ml.shifu.shifu.core.varselect;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Writable;
/**
* Column info for sensitivity analysis.
*
* <p>
* Includes info for mean, RMS and variance computation.
*
* @author Zhang David (pengzhang@paypal.com)
*/
public class ColumnInfo implements Writable {
private double sumScoreDiff;
private long count;
private double sumSquareScoreDiff;
/**
* @return the sumScoreDiff
*/
public double getSumScoreDiff() {
return sumScoreDiff;
}
/**
* @param sumScoreDiff
* the sumScoreDiff to set
*/
public void setSumScoreDiff(double sumScoreDiff) {
this.sumScoreDiff = sumScoreDiff;
}
/**
* @return the count
*/
public long getCount() {
return count;
}
/**
* @param count
* the count to set
*/
public void setCount(long count) {
this.count = count;
}
/**
* @return the sumSquareScoreDiff
*/
public double getSumSquareScoreDiff() {
return sumSquareScoreDiff;
}
/**
* @param sumSquareScoreDiff
* the sumSquareScoreDiff to set
*/
public void setSumSquareScoreDiff(double sumSquareScoreDiff) {
this.sumSquareScoreDiff = sumSquareScoreDiff;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeDouble(sumScoreDiff);
out.writeLong(count);
out.writeDouble(sumSquareScoreDiff);
}
@Override
public void readFields(DataInput in) throws IOException {
this.sumScoreDiff = in.readDouble();
this.count = in.readLong();
this.sumSquareScoreDiff = in.readDouble();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ColumnInfo [sumScoreDiff=" + sumScoreDiff + ", count=" + count + ", sumSquareScoreDiff="
+ sumSquareScoreDiff + "]";
}
}
| 24.688073
| 104
| 0.643255
|
6c70f1bfe842dc4a278357f2f430ecf80914a36b
| 630
|
package io.ebean.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Deprecated migrate to <code>@WhenModified</code>.
* <p>
* For a timestamp property that is set to the datetime when the entity was last
* updated.
* <p>
* This is effectively an alias for @WhenModified which was added as it hints
* towards a better naming convention (WhenCreated, WhenModified).
* </p>
*/
@Deprecated
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UpdatedTimestamp {
}
| 26.25
| 80
| 0.763492
|
9648894b4f06d49fe02c5de58cd3d2c2a67fe66b
| 6,105
|
package com.skytala.eCommerce.domain.content.relations.content.control.assocPredicate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.base.Splitter;
import com.skytala.eCommerce.domain.content.relations.content.command.assocPredicate.AddContentAssocPredicate;
import com.skytala.eCommerce.domain.content.relations.content.command.assocPredicate.DeleteContentAssocPredicate;
import com.skytala.eCommerce.domain.content.relations.content.command.assocPredicate.UpdateContentAssocPredicate;
import com.skytala.eCommerce.domain.content.relations.content.event.assocPredicate.ContentAssocPredicateAdded;
import com.skytala.eCommerce.domain.content.relations.content.event.assocPredicate.ContentAssocPredicateDeleted;
import com.skytala.eCommerce.domain.content.relations.content.event.assocPredicate.ContentAssocPredicateFound;
import com.skytala.eCommerce.domain.content.relations.content.event.assocPredicate.ContentAssocPredicateUpdated;
import com.skytala.eCommerce.domain.content.relations.content.mapper.assocPredicate.ContentAssocPredicateMapper;
import com.skytala.eCommerce.domain.content.relations.content.model.assocPredicate.ContentAssocPredicate;
import com.skytala.eCommerce.domain.content.relations.content.query.assocPredicate.FindContentAssocPredicatesBy;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Scheduler;
import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*;
@RestController
@RequestMapping("/content/content/contentAssocPredicates")
public class ContentAssocPredicateController {
private static Map<String, RequestMethod> validRequests = new HashMap<>();
public ContentAssocPredicateController() {
validRequests.put("find", RequestMethod.GET);
validRequests.put("add", RequestMethod.POST);
validRequests.put("update", RequestMethod.PUT);
validRequests.put("removeById", RequestMethod.DELETE);
}
/**
*
* @param allRequestParams
* all params by which you want to find a ContentAssocPredicate
* @return a List with the ContentAssocPredicates
* @throws Exception
*/
@GetMapping("/find")
public ResponseEntity<List<ContentAssocPredicate>> findContentAssocPredicatesBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception {
FindContentAssocPredicatesBy query = new FindContentAssocPredicatesBy(allRequestParams);
if (allRequestParams == null) {
query.setFilter(new HashMap<>());
}
List<ContentAssocPredicate> contentAssocPredicates =((ContentAssocPredicateFound) Scheduler.execute(query).data()).getContentAssocPredicates();
return ResponseEntity.ok().body(contentAssocPredicates);
}
/**
* creates a new ContentAssocPredicate entry in the ofbiz database
*
* @param contentAssocPredicateToBeAdded
* the ContentAssocPredicate thats to be added
* @return true on success; false on fail
*/
@RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ContentAssocPredicate> createContentAssocPredicate(@RequestBody ContentAssocPredicate contentAssocPredicateToBeAdded) throws Exception {
AddContentAssocPredicate command = new AddContentAssocPredicate(contentAssocPredicateToBeAdded);
ContentAssocPredicate contentAssocPredicate = ((ContentAssocPredicateAdded) Scheduler.execute(command).data()).getAddedContentAssocPredicate();
if (contentAssocPredicate != null)
return successful(contentAssocPredicate);
else
return conflict(null);
}
/**
* Updates the ContentAssocPredicate with the specific Id
*
* @param contentAssocPredicateToBeUpdated
* the ContentAssocPredicate thats to be updated
* @return true on success, false on fail
* @throws Exception
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{contentAssocPredicateId}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> updateContentAssocPredicate(@RequestBody ContentAssocPredicate contentAssocPredicateToBeUpdated,
@PathVariable String contentAssocPredicateId) throws Exception {
contentAssocPredicateToBeUpdated.setContentAssocPredicateId(contentAssocPredicateId);
UpdateContentAssocPredicate command = new UpdateContentAssocPredicate(contentAssocPredicateToBeUpdated);
try {
if(((ContentAssocPredicateUpdated) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
@GetMapping("/{contentAssocPredicateId}")
public ResponseEntity<ContentAssocPredicate> findById(@PathVariable String contentAssocPredicateId) throws Exception {
HashMap<String, String> requestParams = new HashMap<String, String>();
requestParams.put("contentAssocPredicateId", contentAssocPredicateId);
try {
List<ContentAssocPredicate> foundContentAssocPredicate = findContentAssocPredicatesBy(requestParams).getBody();
if(foundContentAssocPredicate.size()==1){ return successful(foundContentAssocPredicate.get(0));
}else{
return notFound();
}
} catch (RecordNotFoundException e) {
return notFound();
}
}
@DeleteMapping("/{contentAssocPredicateId}")
public ResponseEntity<String> deleteContentAssocPredicateByIdUpdated(@PathVariable String contentAssocPredicateId) throws Exception {
DeleteContentAssocPredicate command = new DeleteContentAssocPredicate(contentAssocPredicateId);
try {
if (((ContentAssocPredicateDeleted) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
}
| 40.973154
| 169
| 0.807535
|
887e6ba870930ad1270c58d13dd81c89bf09adce
| 2,740
|
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - info@scireum.de
*/
package sirius.kernel.health;
import sirius.kernel.nls.NLS;
import java.time.Instant;
import java.util.logging.Level;
/**
* Contains a log message passed from {@link Log} to {@link LogTap}.
*/
public class LogMessage {
private String message;
private long timestamp;
private Level logLevel;
private Log receiver;
private StackTraceElement caller;
private String thread;
/**
* Creates a new log message based on the given parameters.
*
* @param message the message to log
* @param logLevel the level of the message
* @param receiver the original receiver
* @param caller the stack frame where the log message was issued
* @param thread the thread in which the message was logged
*/
public LogMessage(String message, Level logLevel, Log receiver, StackTraceElement caller, String thread) {
this.caller = caller;
this.thread = thread;
this.timestamp = System.currentTimeMillis();
this.message = message;
this.logLevel = logLevel;
this.receiver = receiver;
}
/**
* Contains the logged message.
*
* @return the message sent to the logger
*/
public String getMessage() {
return message;
}
/**
* Contains the log level used for this message.
*
* @return the log level of this message
*/
public Level getLogLevel() {
return logLevel;
}
/**
* Returns the logger used to handle this message.
*
* @return the logger used to handle this message
*/
public Log getReceiver() {
return receiver;
}
/**
* Returns the timestamp when this message was created as string.
*
* @return the timestamp when this message was created, formatted as string
*/
public String getTimestampAsString() {
return NLS.toUserString(Instant.ofEpochMilli(timestamp));
}
/**
* Returns the timestamp when this message was created.
*
* @return the timestamp when this message was created
*/
public long getTimestamp() {
return timestamp;
}
/**
* Returns the name of the thread which logged the message.
*
* @return the name of the thread which logged the message
*/
public String getThread() {
return thread;
}
/**
* Returns the stack frame of the method which issued the log message
*
* @return the stack frame which issued the log message
*/
public StackTraceElement getCaller() {
return caller;
}
}
| 25.37037
| 110
| 0.633212
|
6d45651e786e2fb5a79a66cd09d3a9599183f401
| 1,349
|
package com.xiaoyuzhuanqian.mvp.ui.activity.invitation.presenter;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.xiaoyuzhuanqian.api.retrofit.BaseObserver;
import com.xiaoyuzhuanqian.api.retrofit.NewTransformerManager;
import com.xiaoyuzhuanqian.api.retrofit.RetrofitUtils;
import com.xiaoyuzhuanqian.model.InviteMsgBean;
import com.xiaoyuzhuanqian.mvp.presenter.BasePresenter;
import com.xiaoyuzhuanqian.mvp.ui.activity.invitation.contract.MobileContract;
/**
* Created by joshuayingwhat on 2018/11/14.
*/
public class MobileFragmentPresenter
extends BasePresenter<MobileContract.Model, MobileContract.View> {
public MobileFragmentPresenter(
MobileContract.Model mModel,
MobileContract.View rootView) {
super(mModel, rootView);
}
/**
* 邀请好友
*/
public void inviteRelative(String number,String checkName,String phone) {
RetrofitUtils.getInstance().retrofitServer()
.inviteMsg(number, checkName,0).compose(NewTransformerManager.observableSchedulers(
(LifecycleProvider) mRootView,
FragmentEvent.STOP))
.subscribe(new BaseObserver<InviteMsgBean>("invite_msg") {
@Override protected void onSuccess(InviteMsgBean bean) {
mRootView.shareRelative(bean,phone);
}
});
}
}
| 34.589744
| 91
| 0.761305
|
bdb8d27683460934ddeca946d84b37acb06a7eee
| 2,311
|
package org.bbs.apklauncher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import dalvik.system.DexClassLoader;
import dalvik.system.DexFile;
public class TargetFirstClassLoader extends
ClassLoader
//DexClassLoader
{
private static final String TAG = TargetFirstClassLoader.class.getSimpleName();
public static /*final*/ boolean DEBUG = false;
private DexFile mHostDexFile;
private DexFile mTargetDexFile;
private int mLevel;
public TargetFirstClassLoader(String dexPath, String optimizedDirectory,
String libraryPath, ClassLoader parent, String targetPackageName, Context hostContext) {
// super(dexPath, optimizedDirectory, libraryPath, parent);
super(parent);
try {
String hostApkPath = hostContext.getApplicationInfo().publicSourceDir;
String hostPName = hostContext.getPackageName();
mHostDexFile = DexFile.loadDex(hostApkPath, optimizedDirectory + "/" + hostPName + ".dex", 0);
mTargetDexFile = DexFile.loadDex(dexPath, optimizedDirectory + "/" + targetPackageName + ".dex", 0);
} catch (IOException e) {
e.printStackTrace();
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected Class<?> loadClass(String className, boolean resolve)
throws ClassNotFoundException {
if (DEBUG) {
mLevel++;
Log.d(TAG, makePrefix(mLevel) + className);
}
Class<?> c = null;
if (c == null ) {
c = mTargetDexFile.loadClass(className, this);
if (c != null) {
// Log.d(TAG, "/\\/\\/\\" + className + " ==> " + c.getClassLoader());
}
}
if (c == null){
c = mHostDexFile.loadClass(className, this);
if (c != null) {
// Log.d(TAG, "/\\ /\\ /\\" + className + " ==> " + c.getClassLoader());
}
}
if (c == null) {
c = super.loadClass(className, resolve);
}
if (resolve){
resolveClass(c);
}
if (DEBUG) {
if (c != null) {
Log.d(TAG, makePrefix(mLevel) + className + " ==> " + c.getClassLoader());
mLevel--;
}
}
return c;
}
String makePrefix(int level){
String str = "";
for (int i = 1; i < level; i++){
str += " ";
}
return str;
// return (level == 1 ? "\n" : "") + level;
}
}
| 25.677778
| 103
| 0.667676
|
9da685bca8763d2373a48201d3baee0d718a460d
| 1,322
|
package com.blackboard.www.controller;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.blackboard.www.dao.UserDAO;
import com.blackboard.www.pojo.Email;
import com.blackboard.www.pojo.User;
@Controller
public class AjaxController {
ArrayList<String> courseList;
public AjaxController() {
}
@RequestMapping(value = "/usernameavailability.htm", method = RequestMethod.POST)
@ResponseBody
public String ajaxCheckusername(HttpServletRequest request, UserDAO userDao) {
String queryString = request.getParameter("username");
User u = userDao.getUsername(queryString);
if (u != null) {
return "Username already exists";
} else
return "Username available";
}
@RequestMapping(value = "/emailavailability.htm", method = RequestMethod.POST)
@ResponseBody
public String ajaxCheckemail(HttpServletRequest request, UserDAO userDao) {
String queryString = request.getParameter("email");
Email e = userDao.getEmail(queryString);
if (e != null) {
return "Email already exists";
} else
return "Email available";
}
}
| 27.541667
| 82
| 0.776097
|
1d04db63d869827f99540d27b5169c2ecb0571de
| 230
|
package common;
public class EuclideanDistance implements DistanceFunction {
@Override
public double compute(double[] p, double[] q) {
return new org.apache.commons.math3.ml.distance.EuclideanDistance().compute(p, q);
}
}
| 20.909091
| 84
| 0.756522
|
82b3cf952cd10b8b27505a6553da40b3475b5801
| 1,751
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datastream/v1alpha1/datastream_resources.proto
package com.google.cloud.datastream.v1alpha1;
public interface OracleRdbmsOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.datastream.v1alpha1.OracleRdbms)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Oracle schemas/databases in the database server.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleSchema oracle_schemas = 1;</code>
*/
java.util.List<com.google.cloud.datastream.v1alpha1.OracleSchema>
getOracleSchemasList();
/**
* <pre>
* Oracle schemas/databases in the database server.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleSchema oracle_schemas = 1;</code>
*/
com.google.cloud.datastream.v1alpha1.OracleSchema getOracleSchemas(int index);
/**
* <pre>
* Oracle schemas/databases in the database server.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleSchema oracle_schemas = 1;</code>
*/
int getOracleSchemasCount();
/**
* <pre>
* Oracle schemas/databases in the database server.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleSchema oracle_schemas = 1;</code>
*/
java.util.List<? extends com.google.cloud.datastream.v1alpha1.OracleSchemaOrBuilder>
getOracleSchemasOrBuilderList();
/**
* <pre>
* Oracle schemas/databases in the database server.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleSchema oracle_schemas = 1;</code>
*/
com.google.cloud.datastream.v1alpha1.OracleSchemaOrBuilder getOracleSchemasOrBuilder(
int index);
}
| 32.425926
| 95
| 0.712736
|
4c7ff3aba64dd48399c95447354514e91838c96e
| 4,837
|
package io.apigee.trireme.kernel.test;
import io.apigee.trireme.kernel.NodeVersion;
import org.junit.Test;
import static org.junit.Assert.*;
public class VersionTest
{
@Test
public void testOneDigit()
{
NodeVersion v = new NodeVersion("10");
assertEquals(10, v.getMajor());
assertEquals("10.x.x", v.toString());
}
@Test
public void testOneDigitWild()
{
NodeVersion v = new NodeVersion("x");
assertTrue(v.getMajor() < 0);
assertEquals("x.x.x", v.toString());
}
@Test
public void testOneDigitInvalid()
{
try {
NodeVersion v = new NodeVersion("foo");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testOneDigitInvalid2()
{
try {
NodeVersion v = new NodeVersion("xx");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testTwoDigit()
{
NodeVersion v = new NodeVersion("10.1");
assertEquals(10, v.getMajor());
assertEquals(1, v.getMinor());
assertEquals("10.1.x", v.toString());
}
@Test
public void testTwoDigitWild()
{
NodeVersion v = new NodeVersion("10.x");
assertEquals(10, v.getMajor());
assertTrue(v.getMinor() < 0);
assertEquals("10.x.x", v.toString());
}
@Test
public void testTwoDigitInvalid()
{
try {
NodeVersion v = new NodeVersion("10.foo");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testTwoDigitInvalid2()
{
try {
NodeVersion v = new NodeVersion("1.xx");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testThreeDigit()
{
NodeVersion v = new NodeVersion("10.1.2");
assertEquals(10, v.getMajor());
assertEquals(1, v.getMinor());
assertEquals(2, v.getRelease());
assertEquals("10.1.2", v.toString());
}
@Test
public void testThreeDigitWild()
{
NodeVersion v = new NodeVersion("10.1.x");
assertEquals(10, v.getMajor());
assertEquals(1, v.getMinor());
assertTrue(v.getRelease() < 0);
assertEquals("10.1.x", v.toString());
}
@Test
public void testThreeDigitInvalid()
{
try {
NodeVersion v = new NodeVersion("10.1.xx");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testThreeDigitInvalid2()
{
try {
NodeVersion v = new NodeVersion("1.xx.2");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testThreeDigitInvalid3()
{
try {
NodeVersion v = new NodeVersion("1.2.3.4");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testThreeDigitInvalid4()
{
try {
NodeVersion v = new NodeVersion("Foo1.1.2Bar");
assertFalse(true);
} catch (IllegalArgumentException ie) {
}
}
@Test
public void testCompare()
{
assertTrue(new NodeVersion("1.1.1").compareTo(new NodeVersion("0.1.1")) > 0);
assertTrue(new NodeVersion("1.1.1").compareTo(new NodeVersion("2.1.1")) < 0);
assertTrue(new NodeVersion("1.2.1").compareTo(new NodeVersion("1.1.1")) > 0);
assertTrue(new NodeVersion("1.2.1").compareTo(new NodeVersion("1.3.1")) < 0);
assertTrue(new NodeVersion("1.1.1").compareTo(new NodeVersion("1.1.0")) > 0);
assertTrue(new NodeVersion("1.1.1").compareTo(new NodeVersion("1.1.2")) < 0);
assertTrue(new NodeVersion("1.1.1").compareTo(new NodeVersion("1.1.1")) == 0);
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("1.1.1"));
assertNotEquals(new NodeVersion("1.1.1"), new NodeVersion("0.1.1"));
}
@Test
public void testMatch()
{
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("1.1.x"));
assertNotEquals(new NodeVersion("1.1.1"), new NodeVersion("1.2.x"));
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("1.x.x"));
assertEquals(new NodeVersion("1.2.1"), new NodeVersion("1.x.x"));
assertNotEquals(new NodeVersion("2.1.1"), new NodeVersion("1.x.x"));
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("1.x"));
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("1"));
assertEquals(new NodeVersion("1.1.1"), new NodeVersion("x"));
assertNotEquals(new NodeVersion("2.1.1"), new NodeVersion("1"));
}
}
| 27.959538
| 86
| 0.567707
|
1c45d2f22736abc02fc0c5fe8bb47a99639ee6c5
| 4,934
|
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.docs.v1.model;
/**
* Update the styling of all paragraphs that overlap with the given range.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Docs API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class UpdateParagraphStyleRequest extends com.google.api.client.json.GenericJson {
/**
* The fields that should be updated.
*
* At least one field must be specified. The root `paragraph_style` is implied and should not be
* specified.
*
* For example, to update the paragraph style's alignment property, set `fields` to `"alignment"`.
*
* To reset a property to its default value, include its field name in the field mask but leave
* the field itself unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String fields;
/**
* The styles to set on the paragraphs.
*
* Certain paragraph style changes may cause other changes in order to mirror the behavior of the
* Docs editor. See the documentation of ParagraphStyle for more information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ParagraphStyle paragraphStyle;
/**
* The range overlapping the paragraphs to style.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Range range;
/**
* The fields that should be updated.
*
* At least one field must be specified. The root `paragraph_style` is implied and should not be
* specified.
*
* For example, to update the paragraph style's alignment property, set `fields` to `"alignment"`.
*
* To reset a property to its default value, include its field name in the field mask but leave
* the field itself unset.
* @return value or {@code null} for none
*/
public String getFields() {
return fields;
}
/**
* The fields that should be updated.
*
* At least one field must be specified. The root `paragraph_style` is implied and should not be
* specified.
*
* For example, to update the paragraph style's alignment property, set `fields` to `"alignment"`.
*
* To reset a property to its default value, include its field name in the field mask but leave
* the field itself unset.
* @param fields fields or {@code null} for none
*/
public UpdateParagraphStyleRequest setFields(String fields) {
this.fields = fields;
return this;
}
/**
* The styles to set on the paragraphs.
*
* Certain paragraph style changes may cause other changes in order to mirror the behavior of the
* Docs editor. See the documentation of ParagraphStyle for more information.
* @return value or {@code null} for none
*/
public ParagraphStyle getParagraphStyle() {
return paragraphStyle;
}
/**
* The styles to set on the paragraphs.
*
* Certain paragraph style changes may cause other changes in order to mirror the behavior of the
* Docs editor. See the documentation of ParagraphStyle for more information.
* @param paragraphStyle paragraphStyle or {@code null} for none
*/
public UpdateParagraphStyleRequest setParagraphStyle(ParagraphStyle paragraphStyle) {
this.paragraphStyle = paragraphStyle;
return this;
}
/**
* The range overlapping the paragraphs to style.
* @return value or {@code null} for none
*/
public Range getRange() {
return range;
}
/**
* The range overlapping the paragraphs to style.
* @param range range or {@code null} for none
*/
public UpdateParagraphStyleRequest setRange(Range range) {
this.range = range;
return this;
}
@Override
public UpdateParagraphStyleRequest set(String fieldName, Object value) {
return (UpdateParagraphStyleRequest) super.set(fieldName, value);
}
@Override
public UpdateParagraphStyleRequest clone() {
return (UpdateParagraphStyleRequest) super.clone();
}
}
| 33.337838
| 182
| 0.710174
|
d20306b15324f7d98d13a4c9ceb42ad1eeebb01e
| 5,064
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.alert.plugin;
import org.apache.dolphinscheduler.alert.manager.EmailManager;
import org.apache.dolphinscheduler.alert.manager.EnterpriseWeChatManager;
import org.apache.dolphinscheduler.alert.utils.Constants;
import org.apache.dolphinscheduler.alert.utils.EnterpriseWeChatUtils;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
import org.apache.dolphinscheduler.plugin.model.AlertData;
import org.apache.dolphinscheduler.plugin.model.AlertInfo;
import org.apache.dolphinscheduler.plugin.model.PluginName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* EmailAlertPlugin
*
* This plugin is a default plugin, and mix up email and enterprise wechat, because adapt with former alert behavior
*/
public class EmailAlertPlugin implements AlertPlugin {
private static final Logger logger = LoggerFactory.getLogger(EmailAlertPlugin.class);
private PluginName pluginName;
private static final EmailManager emailManager = new EmailManager();
private static final EnterpriseWeChatManager weChatManager = new EnterpriseWeChatManager();
public EmailAlertPlugin() {
this.pluginName = new PluginName();
this.pluginName.setEnglish(Constants.PLUGIN_DEFAULT_EMAIL_EN);
this.pluginName.setChinese(Constants.PLUGIN_DEFAULT_EMAIL_CH);
}
@Override
public String getId() {
return Constants.PLUGIN_DEFAULT_EMAIL;
}
@Override
public PluginName getName() {
return pluginName;
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> process(AlertInfo info) {
Map<String, Object> retMaps = new HashMap<>();
AlertData alert = info.getAlertData();
List<String> receviersList = (List<String>) info.getProp(Constants.PLUGIN_DEFAULT_EMAIL_RECEIVERS);
// receiving group list
// custom receiver
String receivers = alert.getReceivers();
if (StringUtils.isNotEmpty(receivers)) {
String[] splits = receivers.split(",");
receviersList.addAll(Arrays.asList(splits));
}
List<String> receviersCcList = new ArrayList<>();
// Custom Copier
String receiversCc = alert.getReceiversCc();
if (StringUtils.isNotEmpty(receiversCc)) {
String[] splits = receiversCc.split(",");
receviersCcList.addAll(Arrays.asList(splits));
}
if (CollectionUtils.isEmpty(receviersList) && CollectionUtils.isEmpty(receviersCcList)) {
logger.warn("alert send error : At least one receiver address required");
retMaps.put(Constants.STATUS, "false");
retMaps.put(Constants.MESSAGE, "execution failure,At least one receiver address required.");
return retMaps;
}
retMaps = emailManager.send(receviersList, receviersCcList, alert.getTitle(), alert.getContent(),
alert.getShowType());
//send flag
boolean flag = false;
if (retMaps == null) {
retMaps = new HashMap<>();
retMaps.put(Constants.MESSAGE, "alert send error.");
retMaps.put(Constants.STATUS, "false");
logger.info("alert send error : {}", retMaps.get(Constants.MESSAGE));
return retMaps;
}
flag = Boolean.parseBoolean(String.valueOf(retMaps.get(Constants.STATUS)));
if (flag) {
logger.info("alert send success");
retMaps.put(Constants.MESSAGE, "email send success.");
if (EnterpriseWeChatUtils.isEnable()) {
logger.info("Enterprise WeChat is enable!");
try {
String token = EnterpriseWeChatUtils.getToken();
weChatManager.send(info, token);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
} else {
retMaps.put(Constants.MESSAGE, "alert send error.");
logger.info("alert send error : {}", retMaps.get(Constants.MESSAGE));
}
return retMaps;
}
}
| 37.791045
| 116
| 0.67733
|
1406822c253d5be849a152ddc23dd70afc907fcf
| 4,368
|
/**
* Tencent is pleased to support the open source community by making TDW available.
* Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.apache.hadoop.hive.ql.session;
import org.apache.hadoop.fs.FSDataOutputStream;
public class DataImport {
private String dbName;
private String userName;
private String tableName;
private String loaderID;
private String tableDDL;
private boolean isPart;
private boolean isFormated;
private boolean isRCFile;
private String tempTableName;
private String tempTableSavePath;
private FSDataOutputStream tempTableOs;
private FSDataOutputStream tableOs;
private boolean isOverWrited;
public DataImportState state;
private int initTime;
private int uploadIdleTime;
public enum DataImportState {
INIT, UPLOADING, INSERTING, ERROR, ENDED, COMPLETE
}
public DataImport() {
dbName = null;
tableName = null;
loaderID = null;
isPart = false;
isFormated = false;
isRCFile = false;
tempTableName = null;
tempTableSavePath = null;
tempTableOs = null;
tableOs = null;
isOverWrited = false;
state = DataImportState.INIT;
initTime = 0;
uploadIdleTime = 0;
}
public void serDBName(String name) {
dbName = name;
}
public void setTableName(String name) {
tableName = name;
}
public void setLoaderID(String id) {
loaderID = id;
}
public void setTableDDL(String ddl) {
tableDDL = ddl;
}
public void setIsPart(boolean part) {
isPart = part;
}
public void setIsFormated(boolean format) {
isFormated = format;
}
public void setIsRCFile(boolean rcfile) {
isRCFile = rcfile;
}
public void setTempTableName(String name) {
tempTableName = name;
}
public void setTempTableSavePath(String name) {
tempTableSavePath = name;
}
public void setTempTableOs(FSDataOutputStream os) {
tempTableOs = os;
}
public void setTableOs(FSDataOutputStream os) {
tableOs = os;
}
public void setIsOverWrite(boolean is) {
isOverWrited = is;
}
public void setUserName(String user) {
userName = user;
}
public void setDIState(DataImportState st) {
state = st;
if (state == DataImportState.INIT)
initTime = 0;
if (state == DataImportState.UPLOADING)
uploadIdleTime = 0;
}
public void setInitTime(int time) {
initTime = time;
}
public void setUploadIdleTime(int time) {
uploadIdleTime = time;
}
public String getDBName() {
return dbName;
}
public String getTableName() {
return tableName;
}
public String getLoaderID() {
return loaderID;
}
public String getTableDDL() {
return tableDDL;
}
public boolean getIsPart() {
return isPart;
}
public boolean getIsFormated() {
return isFormated;
}
public boolean getIsRCFile() {
return isRCFile;
}
public FSDataOutputStream getTableOs() {
return tableOs;
}
public FSDataOutputStream getTempTableOs() {
return tempTableOs;
}
public boolean getIsOverWrite() {
return isOverWrited;
}
public String getTempTableName() {
return tempTableName;
}
public String getTempTableSavePath() {
return tempTableSavePath;
}
public DataImportState getDIState() {
return state;
}
public String getUserName() {
return userName;
}
public int getInitTime() {
return initTime;
}
public int getUploadIdleTime() {
return uploadIdleTime;
}
public void reset() {
dbName = null;
userName = null;
tableName = null;
loaderID = null;
isPart = false;
isFormated = false;
isRCFile = false;
tempTableName = null;
tempTableSavePath = null;
tempTableOs = null;
tableOs = null;
isOverWrited = false;
state = DataImportState.INIT;
}
}
| 21.307317
| 93
| 0.690476
|
de19b2994c9458eee4fa75cfc572b36411f4475c
| 5,903
|
/*
* Marketing API
* Marketing API
*
* OpenAPI spec version: 1.3
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.tencent.ads.model;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/** 回传信息结构 */
@ApiModel(description = "回传信息结构")
public class OuterLeadsStatusInfoStruct {
@SerializedName("outer_leads_id")
private String outerLeadsId = null;
@SerializedName("leads_id")
private Long leadsId = null;
@SerializedName("leads_tel")
private String leadsTel = null;
@SerializedName("leads_qq")
private Long leadsQq = null;
@SerializedName("leads_wechat")
private String leadsWechat = null;
@SerializedName("click_id")
private String clickId = null;
@SerializedName("outer_leads_convert_type")
private String outerLeadsConvertType = null;
@SerializedName("outer_leads_ineffect_reason")
private String outerLeadsIneffectReason = null;
public OuterLeadsStatusInfoStruct outerLeadsId(String outerLeadsId) {
this.outerLeadsId = outerLeadsId;
return this;
}
/**
* Get outerLeadsId
*
* @return outerLeadsId
*/
@ApiModelProperty(value = "")
public String getOuterLeadsId() {
return outerLeadsId;
}
public void setOuterLeadsId(String outerLeadsId) {
this.outerLeadsId = outerLeadsId;
}
public OuterLeadsStatusInfoStruct leadsId(Long leadsId) {
this.leadsId = leadsId;
return this;
}
/**
* Get leadsId
*
* @return leadsId
*/
@ApiModelProperty(value = "")
public Long getLeadsId() {
return leadsId;
}
public void setLeadsId(Long leadsId) {
this.leadsId = leadsId;
}
public OuterLeadsStatusInfoStruct leadsTel(String leadsTel) {
this.leadsTel = leadsTel;
return this;
}
/**
* Get leadsTel
*
* @return leadsTel
*/
@ApiModelProperty(value = "")
public String getLeadsTel() {
return leadsTel;
}
public void setLeadsTel(String leadsTel) {
this.leadsTel = leadsTel;
}
public OuterLeadsStatusInfoStruct leadsQq(Long leadsQq) {
this.leadsQq = leadsQq;
return this;
}
/**
* Get leadsQq
*
* @return leadsQq
*/
@ApiModelProperty(value = "")
public Long getLeadsQq() {
return leadsQq;
}
public void setLeadsQq(Long leadsQq) {
this.leadsQq = leadsQq;
}
public OuterLeadsStatusInfoStruct leadsWechat(String leadsWechat) {
this.leadsWechat = leadsWechat;
return this;
}
/**
* Get leadsWechat
*
* @return leadsWechat
*/
@ApiModelProperty(value = "")
public String getLeadsWechat() {
return leadsWechat;
}
public void setLeadsWechat(String leadsWechat) {
this.leadsWechat = leadsWechat;
}
public OuterLeadsStatusInfoStruct clickId(String clickId) {
this.clickId = clickId;
return this;
}
/**
* Get clickId
*
* @return clickId
*/
@ApiModelProperty(value = "")
public String getClickId() {
return clickId;
}
public void setClickId(String clickId) {
this.clickId = clickId;
}
public OuterLeadsStatusInfoStruct outerLeadsConvertType(String outerLeadsConvertType) {
this.outerLeadsConvertType = outerLeadsConvertType;
return this;
}
/**
* Get outerLeadsConvertType
*
* @return outerLeadsConvertType
*/
@ApiModelProperty(value = "")
public String getOuterLeadsConvertType() {
return outerLeadsConvertType;
}
public void setOuterLeadsConvertType(String outerLeadsConvertType) {
this.outerLeadsConvertType = outerLeadsConvertType;
}
public OuterLeadsStatusInfoStruct outerLeadsIneffectReason(String outerLeadsIneffectReason) {
this.outerLeadsIneffectReason = outerLeadsIneffectReason;
return this;
}
/**
* Get outerLeadsIneffectReason
*
* @return outerLeadsIneffectReason
*/
@ApiModelProperty(value = "")
public String getOuterLeadsIneffectReason() {
return outerLeadsIneffectReason;
}
public void setOuterLeadsIneffectReason(String outerLeadsIneffectReason) {
this.outerLeadsIneffectReason = outerLeadsIneffectReason;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OuterLeadsStatusInfoStruct outerLeadsStatusInfoStruct = (OuterLeadsStatusInfoStruct) o;
return Objects.equals(this.outerLeadsId, outerLeadsStatusInfoStruct.outerLeadsId)
&& Objects.equals(this.leadsId, outerLeadsStatusInfoStruct.leadsId)
&& Objects.equals(this.leadsTel, outerLeadsStatusInfoStruct.leadsTel)
&& Objects.equals(this.leadsQq, outerLeadsStatusInfoStruct.leadsQq)
&& Objects.equals(this.leadsWechat, outerLeadsStatusInfoStruct.leadsWechat)
&& Objects.equals(this.clickId, outerLeadsStatusInfoStruct.clickId)
&& Objects.equals(
this.outerLeadsConvertType, outerLeadsStatusInfoStruct.outerLeadsConvertType)
&& Objects.equals(
this.outerLeadsIneffectReason, outerLeadsStatusInfoStruct.outerLeadsIneffectReason);
}
@Override
public int hashCode() {
return Objects.hash(
outerLeadsId,
leadsId,
leadsTel,
leadsQq,
leadsWechat,
clickId,
outerLeadsConvertType,
outerLeadsIneffectReason);
}
@Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 23.612
| 100
| 0.697611
|
c53bb264607483a6c68939cc4e492f8206136ee0
| 631
|
package com.skytala.eCommerce.domain.order.relations.orderType.event.attr;
import com.skytala.eCommerce.framework.pubsub.Event;
import com.skytala.eCommerce.domain.order.relations.orderType.model.attr.OrderTypeAttr;
public class OrderTypeAttrAdded implements Event{
private OrderTypeAttr addedOrderTypeAttr;
private boolean success;
public OrderTypeAttrAdded(OrderTypeAttr addedOrderTypeAttr, boolean success){
this.addedOrderTypeAttr = addedOrderTypeAttr;
this.success = success;
}
public boolean isSuccess() {
return success;
}
public OrderTypeAttr getAddedOrderTypeAttr() {
return addedOrderTypeAttr;
}
}
| 25.24
| 87
| 0.81458
|
82ece60158d7a45cc720925c282838f2902c924c
| 1,996
|
package rocks.inspectit.server.util;
import org.apache.commons.lang.ArrayUtils;
import org.hibernate.Hibernate;
import org.hibernate.collection.internal.PersistentList;
import org.hibernate.collection.internal.PersistentMap;
import org.hibernate.collection.internal.PersistentSet;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.stereotype.Component;
import rocks.inspectit.shared.all.util.IHibernateUtil;
/**
* Our own Hibernate utility class.
*
* @author Ivan Senic
*
*/
@Component
public class HibernateUtil implements IHibernateUtil {
/**
* {@inheritDoc}
*/
@Override
public boolean isInitialized(Object proxy) {
return Hibernate.isInitialized(proxy);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPersistentCollection(Class<?> collectionClass) {
return PersistentCollection.class.isAssignableFrom(collectionClass);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPersistentMap(Class<?> collectionClass) {
return PersistentMap.class.isAssignableFrom(collectionClass);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPersistentList(Class<?> collectionClass) {
return PersistentList.class.isAssignableFrom(collectionClass);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPersistentSet(Class<?> collectionClass) {
return PersistentSet.class.isAssignableFrom(collectionClass);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isProxy(Class<?> proxyClass) {
return ArrayUtils.contains(proxyClass.getInterfaces(), HibernateProxy.class);
}
/**
* {@inheritDoc}
*/
@Override
public Object getUnproxiedObject(Object proxy) {
// getImplementation will try to initialize the object
// but our objects should already be initialized, thus should work with no problem
if (proxy instanceof HibernateProxy) {
return ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation();
}
return proxy;
}
}
| 23.482353
| 85
| 0.75501
|
68e9eefb7d38cfcf0ba0b2b563bcea349073980f
| 1,802
|
package ua.com.foxminded.division.maths;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class BarDividingTest {
BarDividing barDividing = new BarDividing();
@Test
void shouldReturn3StepsWhen785DivideBy4() {
List<Step> actual = barDividing.calculate(785, 4);
List<Step> expected = new ArrayList<>();
Step step1 = new Step(785, 4, 3, 4, 196, 0, 0, 0, "");
Step step2 = new Step(38, 36, 2, 0, 0, 0, 0, 0, "");
Step step3 = new Step(25, 24, 1, 0, 0, 1, 1, 2, "");
expected.add(step1);
expected.add(step2);
expected.add(step3);
assertThat(actual, is(expected));
}
@Test
void shouldReturn1StepWhen10DivideBy2() {
List<Step> actual = barDividing.calculate(10, 2);
List<Step> expected = new ArrayList<>();
Step step1 = new Step(10, 10, 0, 2, 5, 0, 0, 1, "");
expected.add(step1);
assertThat(actual, is(expected));
}
@Test
public void shouldThrowsExceptionWhen2DividedBy0(){
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
barDividing.calculate(2, 0);
});
assertEquals("Attempt to divide by zero", exception.getMessage());
}
@Test
public void shouldThrowsExceptionWhen2DividedBy10(){
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
barDividing.calculate(2, 10);
});
assertEquals("Dividend can not be less then divider!", exception.getMessage());
}
}
| 33.37037
| 87
| 0.645394
|
4a04787c35d2afed3c35846798c8d4d659e6009a
| 2,385
|
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.reactivex.internal.operators.completable;
import io.reactivex.*;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.Function;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.subjects.CompletableSubject;
import io.reactivex.testsupport.TestHelper;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
public class CompletableHideTest {
@Test
public void never() {
Completable.never()
.hide()
.test()
.assertNotComplete()
.assertNoErrors();
}
@Test
public void complete() {
Completable.complete()
.hide()
.test()
.assertResult();
}
@Test
public void error() {
Completable.error(new TestException())
.hide()
.test()
.assertFailure(TestException.class);
}
@Test
public void hidden() {
assertFalse(CompletableSubject.create().hide() instanceof CompletableSubject);
}
@Test
public void dispose() {
TestHelper.checkDisposedCompletable(new Function<Completable, CompletableSource>() {
@Override
public CompletableSource apply(Completable m) throws Exception {
return m.hide();
}
});
}
@Test
public void isDisposed() {
PublishProcessor<Integer> pp = PublishProcessor.create();
TestHelper.checkDisposed(pp.ignoreElements().hide());
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeCompletable(new Function<Completable, Completable>() {
@Override
public Completable apply(Completable f) throws Exception {
return f.hide();
}
});
}
}
| 27.732558
| 112
| 0.658281
|
42e23d298f33ede841bc84202dcab45a6d83ecce
| 3,525
|
package com.brainpg.teddystoy.activity;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.TextView;
import com.brainpg.teddystoy.R;
import com.brainpg.teddystoy.adapter.RecyclerViewDemoAdapter;
import java.util.ArrayList;
import java.util.List;
public class CoordinatorLayoutActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coordinator_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.activity_common_base_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
setToolbarTitle("CoordinatorLayoutActivity");
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// 콘텐츠가 변화해도 RecyclerView의 레이아웃 크기가 변경되지 않을 경우
// 성능 향상을 위해 이 설정을 사용
recyclerView.setHasFixedSize(true);
// use a linear layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
// specify an adapter (see also next example)
RecyclerViewDemoAdapter adapter = new RecyclerViewDemoAdapter(this, getListData());
recyclerView.setAdapter(adapter);
}
public void setToolbarTitle(String title) {
TextView textView = (TextView) findViewById(R.id.action_bar_title);
textView.setText(title);
}
private List<String> getListData() {
List<String> list = new ArrayList<>();
list.add("빨");
list.add("주");
list.add("노");
list.add("초");
list.add("파");
list.add("남");
list.add("보");
return list;
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_coordinator_layout, menu);
return true;
}
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
}
| 36.340206
| 147
| 0.693901
|
284a13ba669f24073044491a9bde9edf0ba9f87f
| 1,162
|
package junit.proxy;
import proxy.PacketQueue;
import proxy.UDPDatagram;
import junit.framework.TestCase;
public class TestPacketQueue extends TestCase {
PacketQueue queue;
public void setUp() {
queue = new PacketQueue();
}
public void testQueue() {
UDPDatagram packet1 = new UDPDatagram(null, 1, null, 2, null);
UDPDatagram packet2 = new UDPDatagram(null, 3, null, 4, null);
assertEquals(queue.size(), 0);
queue.addPacket(packet1);
assertEquals(queue.size(), 1);
queue.addPacket(packet2);
assertEquals(queue.size(), 2);
try {
assertEquals(queue.removePacket(), packet1);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(queue.size(), 1);
try {
assertEquals(queue.removePacket(), packet2);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals(queue.size(), 0);
}
}
| 26.409091
| 71
| 0.567126
|
220e20bbd810ebc27aae8a801fdde0840382b390
| 1,263
|
package com.xinfan.wxshop.business.vo;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.xinfan.wxshop.business.util.XStreamCDATA;
@XStreamAlias("xml")
public class OutputMessage {
@XStreamAlias("ToUserName")
@XStreamCDATA
private String ToUserName;
@XStreamAlias("FromUserName")
@XStreamCDATA
private String FromUserName;
@XStreamAlias("CreateTime")
private Long CreateTime;
@XStreamAlias("MsgType")
@XStreamCDATA
private String MsgType = "text";
@XStreamAlias("Content")
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public Long getCreateTime() {
return CreateTime;
}
public void setCreateTime(Long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
}
| 18.573529
| 58
| 0.707838
|
4ea0ec67a9bbf80298f5b96b4df96c5f23f3bda6
| 1,186
|
package net.yoonaxes.auth.configuration.impl;
import eu.okaeri.configs.OkaeriConfig;
import eu.okaeri.configs.annotation.*;
import net.yoonaxes.auth.security.SecurityConfiguration;
@Names(
modifier = NameModifier.TO_LOWER_CASE,
strategy = NameStrategy.HYPHEN_CASE
)
public class PluginConfiguration extends OkaeriConfig {
@Comment("Mojang Authentication")
@Comment("If value is false, all players will be connected to server in offline mode and premium accounts will not be logged automatically.")
public boolean mojangAuthentication = true;
@Comment("Repeat Password")
@Comment("If value is true the player need to repeat password when creating a new account or changing old password.")
@Comment("You must remember to need change usage of commands in language.yml!")
public boolean mustRepeatPassword = true;
@Comment("Suggest repeat password")
@Comment("If value is true a tab completion suggest a password to repeat.")
public boolean suggestRepeatPassword = true;
@Comment("Security Configuration")
@Comment("A security configuration.")
public SecurityConfiguration security = new SecurityConfiguration();
}
| 38.258065
| 145
| 0.75801
|
0fb6ad89500d592fbdb1459991ff49a62f4caf42
| 1,968
|
package es.ucm.abd.practica2.controller;
import es.ucm.abd.practica2.dao.AbedemonDAO;
import es.ucm.abd.practica2.model.Abedemon;
import es.ucm.abd.practica2.model.AbedemonTableModel;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
/**
* Controlador de los paneles de búsqueda
*
* @author Manuel Montenegro (mmontene@ucm.es)
*/
public class SearchPanelController {
private final DefaultComboBoxModel<String> types;
private final AbedemonTableModel abedemons;
private final AbedemonDAO dao;
public SearchPanelController(
List<String> types,
List<Abedemon> abedemons,
AbedemonDAO dao) {
this.types = new DefaultComboBoxModel<>(types.toArray(new String[types.size()]));
this.types.insertElementAt("[Seleccionar]", 0);
this.abedemons = new AbedemonTableModel();
this.abedemons.changeModel(abedemons);
this.dao = dao;
}
public void searchAbedemonsOf(int typeIndex) {
if (typeIndex != 0) {
String type = types.getElementAt(typeIndex);
List<Abedemon> abedemonsList = dao.getAbedemonsOf(type);
if (abedemonsList != null) {
abedemons.changeModel(abedemonsList);
}
}
}
public String getAbedemonInfo(int rowIndex) {
if (rowIndex != -1) {
String id = (String) abedemons.getValueAt(rowIndex, 0);
return getAbedemonInfo(id);
}
return "";
}
public String getAbedemonInfo(String id) {
String description = dao.getAbedemonDescription(id);
return (description == null ? "" : description);
}
public DefaultComboBoxModel<String> getTypes() {
return types;
}
public Abedemon getAbedemon(int index) {
return index == -1 ? null : abedemons.getAbedemon(index);
}
public AbedemonTableModel getAbedemons() {
return abedemons;
}
}
| 29.818182
| 89
| 0.639736
|
c669272db7dc4f6dcb4032ed86a7092c3e5780a8
| 4,209
|
package com.wnp.lqmall.activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.simplexx.wnp.presenter.LoginPresenter;
import com.simplexx.wnp.util.ToastUtils;
import com.simplexx.wnp.util.ui.StatusBarUtil;
import com.simplexx.wnp.util.ui.widget.BlurringView;
import com.wnp.lqmall.R;
import com.wnp.lqmall.base.BasePresenterActivity;
import com.wnp.lqmall.ioc.component.PresenterComponent;
import com.wnp.lqmall.loader.ImageLoaderUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
/**
* Created by wnp on 2018/7/2.
*/
@RuntimePermissions
public class LoginActivity extends BasePresenterActivity<LoginPresenter, LoginPresenter.ILoginView>
implements LoginPresenter.ILoginView {
@BindView(R.id.tv_content)
TextView mTvContent;
@BindView(R.id.image)
ImageView imageView;
@BindView(R.id.blur)
BlurringView blurringView;
@BindView(R.id.editText)
EditText editText;
@Override
protected void initView(Bundle savedInstanceState) {
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
ImageLoaderUtil.INSTANT.loadImage(Uri.parse("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1532000455&di=90bc26ca2b75f28115f93cc48425a969&src=http://s1.sinaimg.cn/mw690/006LDoUHzy7auXElZGE40&690"
), imageView);
mTvContent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
startActivity(intent);
}
});
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(false);
blurringView.setBlurredView(imageView);
}
@NeedsPermission(Manifest.permission.CAMERA)
public void showCamera() {
ToastUtils.showShort(LoginActivity.this, "显示出相机");
}
@OnShowRationale(Manifest.permission.CAMERA)
void showRationaleCamera(PermissionRequest request) {
new AlertDialog.Builder(this)
.setMessage("需要请求相机权限")
.setPositiveButton("允许", (dialog, button) -> request.proceed())
.setNegativeButton("拒绝", (dialog, button) -> request.cancel())
.show();
}
@OnPermissionDenied(Manifest.permission.CAMERA)
void showDeniedForCamera() {
ToastUtils.showShort(LoginActivity.this, "请求权限失败");
}
@OnNeverAskAgain(Manifest.permission.CAMERA)
void showNeverAskForCamera() {
ToastUtils.showShort(LoginActivity.this, "请求权限失败,不允许在被请求");
}
@Override
protected void injectPresenter(PresenterComponent component, LoginPresenter preseneter) {
component.inject(preseneter);
}
@SuppressLint("NeedOnRequestPermissionsResult")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
@Override
protected void onForceLogout() {
}
@Override
protected void onTokenOutDate() {
}
@Override
public void onTestRepository(String flag) {
editText.setText(flag);
}
}
| 34.219512
| 252
| 0.741981
|
f5791696239dedacf07b42bcc373c190c34ac8ba
| 895
|
package dev.magicmq.pyspigot.event;
import dev.magicmq.pyspigot.managers.script.Script;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class ScriptLoadEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Script script;
private boolean cancelled;
public ScriptLoadEvent(Script script) {
this.script = script;
}
public Script getScript() {
return script;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| 21.829268
| 67
| 0.688268
|
6c02ba355b0e85c6f9e3186310cfb55d7c3cea93
| 822
|
package May2021PrepLeetcode;
public class _0073SetMatrixZeroes {
public static void main(String[] args) {
setZeroes(new int[][] { new int[] { 1, 1, 1 }, new int[] { 1, 0, 1 }, new int[] { 1, 1, 1 }, });
setZeroes(new int[][] { new int[] { 0, 1, 2, 0 }, new int[] { 3, 4, 5, 2 }, new int[] { 1, 3, 1, 5 }, });
}
public static void setZeroes(int[][] matrix) {
boolean[] rowArr = new boolean[matrix.length];
boolean[] colArr = new boolean[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
rowArr[i] = true;
colArr[j] = true;
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (rowArr[i] || colArr[j]) {
matrix[i][j] = 0;
}
}
}
}
}
| 25.6875
| 107
| 0.519465
|
02c031791e556d7c28c2d6c3b2f93a0110c14376
| 437
|
package com.github.thorbenkuck.netcom2.exceptions;
public class PipelineAccessException extends NetComRuntimeException {
public PipelineAccessException() {
}
public PipelineAccessException(String s) {
super(s);
}
public PipelineAccessException(String s, Throwable throwable) {
super(s, throwable);
}
public PipelineAccessException(Throwable throwable) {
super(throwable);
}
}
| 21.85
| 69
| 0.704805
|
47dea4c11f830ab7af5d167b87edbb10e7f50592
| 2,958
|
/*
* Copyright 2009-2014 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.showcase.view.button;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
@Named
@RequestScoped
public class ButtonView {
private MenuModel model;
@PostConstruct
public void init() {
model = new DefaultMenuModel();
//First submenu
DefaultMenuItem item = DefaultMenuItem.builder()
.value("External")
.url("http://www.primefaces.org")
.icon("pi pi-home")
.build();
DefaultSubMenu firstSubmenu = DefaultSubMenu.builder()
.label("Dynamic Submenu")
.addElement(item)
.build();
model.getElements().add(firstSubmenu);
//Second submenu
item = DefaultMenuItem.builder()
.value("Save")
.icon("pi pi-save")
.function((i) -> save())
.update("messages")
.build();
DefaultSubMenu secondSubmenu = DefaultSubMenu.builder()
.label("Dynamic Actions")
.addElement(item)
.build();
item = DefaultMenuItem.builder()
.value("Delete")
.icon("pi pi-times")
.command("#{buttonView.delete}")
.ajax(false)
.build();
secondSubmenu.getElements().add(item);
model.getElements().add(secondSubmenu);
}
public MenuModel getModel() {
return model;
}
public String save() {
addMessage("Data saved");
return null;
}
public void update() {
addMessage("Data updated");
}
public void delete() {
addMessage("Data deleted");
}
public void buttonAction() {
addMessage("Welcome to PrimeFaces!!");
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
| 28.442308
| 91
| 0.620352
|
f4616908dddafce60bb517bc4e32c5c1ae0b188d
| 3,319
|
package com.github.pozo.game.server;
import com.github.pozo.game.server.model.DefaultGameModel;
import com.github.pozo.game.server.model.GameModel;
import com.github.pozo.game.server.model.objects.meta.Player;
import com.github.pozo.game.server.model.unit.time.TimeUnits;
import com.github.pozo.game.server.model.unit.time.modelevents.types.TimeChange;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Game {
public static final int PHYSICS_LOOP = 15;
public static final int UPDATE_LOOP = 1000;
private static Game instance;
private final Clock clock;
private final GameModel gameModel;
private boolean isRunning;
private Game(GameModel gameModel, Clock clock) {
this.gameModel = gameModel;
this.clock = clock;
}
public static Game getInstance() {
if (instance == null) {
synchronized (Game.class) {
if (instance == null) {
instance = createGameWithDefaultParameters();
}
}
}
return instance;
}
private static Game createGameWithDefaultParameters() {
final Clock clock = new Clock();
final GameModel gameModel = new DefaultGameModel();
return new Game(gameModel, clock);
}
private void startUpdateScheduler() {
final ScheduledExecutorService updateScheduler = Executors.newScheduledThreadPool(1);
updateScheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
if (isRunning()) {
for (Player player : gameModel.getPlayers()) {
player.update(gameModel);
}
} else {
updateScheduler.shutdown();
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}, UPDATE_LOOP, UPDATE_LOOP, TimeUnit.MILLISECONDS);
}
private void startPhisicsScheduler() {
final ScheduledExecutorService physicsScheduler = Executors.newScheduledThreadPool(1);
physicsScheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
if (isRunning()) {
TimeChange timeEvent = new TimeChange(new TimeUnits(1));
clock.produce(timeEvent);
} else {
physicsScheduler.shutdown();
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}, PHYSICS_LOOP, PHYSICS_LOOP, TimeUnit.MILLISECONDS);
}
public void start() {
clock.addAllConsumer(gameModel.getModelEventConsumers());
setIsRunning(true);
startPhisicsScheduler();
startUpdateScheduler();
}
private void stop() {
setIsRunning(false);
}
public GameModel getGameModel() {
return gameModel;
}
public void setIsRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public boolean isRunning() {
return isRunning;
}
}
| 31.018692
| 94
| 0.582706
|
285bf61c09aeabf228886f0cfae62b1174cff5d7
| 6,570
|
package com.ming.biz.controller;
import com.ming.biz.service.ArticleService;
import com.ming.biz.utils.TransCodingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;
/**
* @author: wellfuture
* @Date: 2018/5/17 19:24
* Describe: 所有页面跳转
*/
@Controller
public class BackControl {
@Autowired
ArticleService articleService;
/**
* 跳转首页
*/
@GetMapping("/")
public String index(HttpServletRequest request, HttpServletResponse response,
@AuthenticationPrincipal Principal principal){
String username = null;
try {
username = principal.getName();
} catch (NullPointerException e){
request.getSession().removeAttribute("lastUrl");
return "index";
}
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("lastUrl", (String) request.getSession().getAttribute("lastUrl"));
return "index";
}
/**
* 跳转我的女孩页
*/
@GetMapping("/mylove")
public String myLove(){
return "mylove";
}
/**
* 跳转我的藏心阁页
*/
@GetMapping("/myheart")
public String myheart(){
return "myheart";
}
/**
* 跳转我的故事页
*/
@GetMapping("/mystory")
public String mystory(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "mystory";
}
/**
* 跳转登录页
*/
@GetMapping("/login")
public String login(){
return "login";
}
/**
* 登录前尝试保存上一个页面的url
*/
@GetMapping("/toLogin")
public @ResponseBody void toLogin(HttpServletRequest request){
//保存跳转页面的url
request.getSession().setAttribute("lastUrl", request.getHeader("Referer"));
}
/**
* 跳转注册页
*/
@GetMapping("/register")
public String register(){
return "register";
}
/**
* 跳转关于我页面
*/
@GetMapping("/aboutme")
public String aboutme(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "aboutme";
}
/**
* 跳转更新页
*/
@GetMapping("/aboutus")
public String update(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "aboutus";
}
/**
* 跳转友链页
*/
@GetMapping("/friendlylink")
public String friendlylink(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "friendlylink";
}
/**
* 跳转到用户页
*/
@GetMapping("/user")
public String user(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "user";
}
/**
* 跳转到文章编辑页
*/
@GetMapping("/editor")
public String editor(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
String id = request.getParameter("id");
if(!"".equals(id)){
request.getSession().setAttribute("id", id);
}
return "editor";
}
/**
* 跳转到文章显示页
*/
@GetMapping("/article/{articleId}")
public String show(@PathVariable("articleId") long articleId,
HttpServletResponse response,
Model model,
HttpServletRequest request){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
request.getSession().removeAttribute("lastUrl");
Map<String, String> articleMap = articleService.findArticleTitleByArticleId(articleId);
if(articleMap.get("articleTitle") != null){
model.addAttribute("articleTitle",articleMap.get("articleTitle"));
String articleTabloid = articleMap.get("articleTabloid");
if(articleTabloid.length() <= 110){
model.addAttribute("articleTabloid",articleTabloid);
} else {
model.addAttribute("articleTabloid",articleTabloid.substring(0,110));
}
}
//将文章id存入响应头
response.setHeader("articleId",String.valueOf(articleId));
return "show";
}
/**
* 跳转到归档页
*/
@GetMapping("/archives")
public String archives(HttpServletResponse response,
HttpServletRequest request){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
request.getSession().removeAttribute("lastUrl");
String archive = request.getParameter("archive");
try {
response.setHeader("archive",TransCodingUtil.stringToUnicode(archive));
} catch (Exception e){
}
return "archives";
}
/**
* 跳转到分类页
*/
@GetMapping("/categories")
public String categories(HttpServletResponse response,
HttpServletRequest request){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
request.getSession().removeAttribute("lastUrl");
String category = request.getParameter("category");
try {
response.setHeader("category",TransCodingUtil.stringToUnicode(category));
} catch (Exception e){
}
return "categories";
}
/**
* 跳转到标签页
*/
@GetMapping("/tags")
public String tags(HttpServletResponse response,
HttpServletRequest request){
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
request.getSession().removeAttribute("lastUrl");
String tag = request.getParameter("tag");
try {
response.setHeader("tag",TransCodingUtil.stringToUnicode(tag));
} catch (Exception e){
}
return "tags";
}
/**
* 跳转到超级管理员页
*/
@GetMapping("/superadmin")
public String superadmin(HttpServletRequest request){
request.getSession().removeAttribute("lastUrl");
return "superadmin";
}
}
| 27.375
| 95
| 0.611416
|
a2f55f73b0603808db95fc468b360f3375c7f346
| 30,858
|
/*
* Copyright (C) 2019 Alberto Irurueta Carro (alberto@irurueta.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irurueta.navigation.frames.converters;
import com.irurueta.algebra.Matrix;
import com.irurueta.geometry.InvalidRotationMatrixException;
import com.irurueta.geometry.Quaternion;
import com.irurueta.geometry.RotationException;
import com.irurueta.navigation.frames.CoordinateTransformation;
import com.irurueta.navigation.frames.ECEFFrame;
import com.irurueta.navigation.frames.ECIFrame;
import com.irurueta.navigation.frames.FrameType;
import com.irurueta.navigation.frames.InvalidSourceAndDestinationFrameTypeException;
import com.irurueta.navigation.geodesic.Constants;
import com.irurueta.statistics.UniformRandomizer;
import com.irurueta.units.Time;
import com.irurueta.units.TimeUnit;
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.*;
public class ECItoECEFFrameConverterTest {
private static final double ABSOLUTE_ERROR = 1e-8;
private static final double TIME_INTERVAL_SECONDS = 0.02;
private static final double MIN_ANGLE_DEGREES = -45.0;
private static final double MAX_ANGLE_DEGREES = 45.0;
private static final double MIN_POSITION_VALUE =
Constants.EARTH_EQUATORIAL_RADIUS_WGS84 - 50.0;
private static final double MAX_POSITION_VALUE =
Constants.EARTH_EQUATORIAL_RADIUS_WGS84 + 50.0;
private static final double MIN_Z_VALUE = -50.0;
private static final double MAX_Z_VALUE = 50.0;
private static final double MIN_VELOCITY_VALUE = -2.0;
private static final double MAX_VELOCITY_VALUE = 2.0;
private static final int TIMES = 100;
@Test
public void testConstants() {
assertEquals(ECItoECEFFrameConverter.EARTH_ROTATION_RATE, Constants.EARTH_ROTATION_RATE, 0.0);
}
@Test
public void testConstructor() {
final ECItoECEFFrameConverter converter = new ECItoECEFFrameConverter();
// check
assertEquals(converter.getSourceType(),
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
assertEquals(converter.getDestinationType(),
FrameType.EARTH_CENTERED_EARTH_FIXED_FRAME);
}
@Test
public void testConvertAndReturnNewWithSecondsTimeInterval() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECItoECEFFrameConverter converter1 = new ECItoECEFFrameConverter();
final ECEFFrame ecefFrame = converter1.convertAndReturnNew(TIME_INTERVAL_SECONDS, eciFrame1);
// convert back to ECI
final ECEFtoECIFrameConverter converter2 = new ECEFtoECIFrameConverter();
final ECIFrame eciFrame2 = converter2.convertAndReturnNew(TIME_INTERVAL_SECONDS, ecefFrame);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertWithSecondsTimeInterval() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECItoECEFFrameConverter converter1 = new ECItoECEFFrameConverter();
final ECEFFrame ecefFrame = new ECEFFrame();
converter1.convert(TIME_INTERVAL_SECONDS, eciFrame1, ecefFrame);
// convert back to ECI
final ECEFtoECIFrameConverter converter2 = new ECEFtoECIFrameConverter();
final ECIFrame eciFrame2 = new ECIFrame();
converter2.convert(TIME_INTERVAL_SECONDS, ecefFrame, eciFrame2);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertECIToECEFAndReturnNewWithSecondsTimeInterval() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECEFFrame ecefFrame = ECItoECEFFrameConverter.convertECItoECEFAndReturnNew(
TIME_INTERVAL_SECONDS, eciFrame1);
// convert back to ECI
final ECIFrame eciFrame2 = ECEFtoECIFrameConverter.convertECEFtoECIAndReturnNew(
TIME_INTERVAL_SECONDS, ecefFrame);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertECItoECEFWithSecondsTimeInterval() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECEFFrame ecefFrame = new ECEFFrame();
ECItoECEFFrameConverter.convertECItoECEF(TIME_INTERVAL_SECONDS, eciFrame1, ecefFrame);
// convert back to ECI
final ECIFrame eciFrame2 = new ECIFrame();
ECEFtoECIFrameConverter.convertECEFtoECI(TIME_INTERVAL_SECONDS, ecefFrame, eciFrame2);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertAndReturnNew() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
final Time timeInterval = new Time(TIME_INTERVAL_SECONDS, TimeUnit.SECOND);
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECItoECEFFrameConverter converter1 = new ECItoECEFFrameConverter();
final ECEFFrame ecefFrame = converter1.convertAndReturnNew(timeInterval, eciFrame1);
// convert back to ECI
final ECEFtoECIFrameConverter converter2 = new ECEFtoECIFrameConverter();
final ECIFrame eciFrame2 = converter2.convertAndReturnNew(timeInterval, ecefFrame);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvert() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
final Time timeInterval = new Time(TIME_INTERVAL_SECONDS, TimeUnit.SECOND);
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECItoECEFFrameConverter converter1 = new ECItoECEFFrameConverter();
final ECEFFrame ecefFrame = new ECEFFrame();
converter1.convert(timeInterval, eciFrame1, ecefFrame);
// convert back to ECI
final ECEFtoECIFrameConverter converter2 = new ECEFtoECIFrameConverter();
final ECIFrame eciFrame2 = new ECIFrame();
converter2.convert(timeInterval, ecefFrame, eciFrame2);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertECIToECEFAndReturnNew() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
final Time timeInterval = new Time(TIME_INTERVAL_SECONDS, TimeUnit.SECOND);
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECEFFrame ecefFrame = ECItoECEFFrameConverter.convertECItoECEFAndReturnNew(
timeInterval, eciFrame1);
// convert back to ECI
final ECIFrame eciFrame2 = ECEFtoECIFrameConverter.convertECEFtoECIAndReturnNew(
timeInterval, ecefFrame);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
@Test
public void testConvertECItoECEF() throws InvalidRotationMatrixException,
InvalidSourceAndDestinationFrameTypeException, RotationException {
final Time timeInterval = new Time(TIME_INTERVAL_SECONDS, TimeUnit.SECOND);
int numValid = 0;
for (int t = 0; t < TIMES; t++) {
final UniformRandomizer randomizer = new UniformRandomizer(new Random());
final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE);
final double z = randomizer.nextDouble(MIN_Z_VALUE, MAX_Z_VALUE);
final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE);
final double roll = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double pitch = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final double yaw = Math.toRadians(
randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES));
final Quaternion q = new Quaternion(roll, pitch, yaw);
final Matrix m = q.asInhomogeneousMatrix();
final CoordinateTransformation c = new CoordinateTransformation(
m, FrameType.BODY_FRAME,
FrameType.EARTH_CENTERED_INERTIAL_FRAME);
final ECIFrame eciFrame1 = new ECIFrame(x, y, z, vx, vy, vz, c);
final ECEFFrame ecefFrame = new ECEFFrame();
ECItoECEFFrameConverter.convertECItoECEF(timeInterval, eciFrame1, ecefFrame);
// convert back to ECI
final ECIFrame eciFrame2 = new ECIFrame();
ECEFtoECIFrameConverter.convertECEFtoECI(timeInterval, ecefFrame, eciFrame2);
// check
assertEquals(eciFrame1.getX(), eciFrame2.getX(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getY(), eciFrame2.getY(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getZ(), eciFrame2.getZ(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVx(), eciFrame2.getVx(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVy(), eciFrame2.getVy(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getVz(), eciFrame2.getVz(), ABSOLUTE_ERROR);
assertEquals(eciFrame1.getCoordinateTransformation().getSourceType(),
eciFrame2.getCoordinateTransformation().getSourceType());
assertEquals(eciFrame1.getCoordinateTransformation().getDestinationType(),
eciFrame2.getCoordinateTransformation().getDestinationType());
final Quaternion q1 = new Quaternion();
eciFrame1.getCoordinateTransformation().asRotation(q1);
final Quaternion q2 = new Quaternion();
eciFrame2.getCoordinateTransformation().asRotation(q2);
assertTrue(q1.equals(q2, ABSOLUTE_ERROR));
// velocity norm is not the same on ECEF and ECI because ECI takes into account
// Earth rotation
assertNotEquals(eciFrame1.getVelocityNorm(), ecefFrame.getVelocityNorm(), ABSOLUTE_ERROR);
numValid++;
}
assertEquals(numValid, TIMES);
}
}
| 47.693972
| 112
| 0.672111
|
df864bec142ea1d0608498cf72a83a0efba62e05
| 876
|
import maow.pojobuilder.PojoWriter;
import maow.pojobuilder.pojo.PojoObject;
public class Test {
public static void main(String[] args) {
// PojoObject object = new PojoObject.Builder().addField("field", "test").addField("array", new String[]{"test1","test2"}).build();
// object.to("json.json");
//
// PojoObject object2 = PojoObject.from("json.json");
// System.out.println(object2.getField("field"));
// System.out.println(object2.getField("array"));
//
// PojoWriter.toSource("maow.testpojo", "TestPojo", object, "./");
PojoObject object = PojoObject.from("test.json");
for (String key : object.getKeys()) {
System.out.println("Key: " + key + "\nData: " + object.getField(key) + "\n");
}
PojoWriter.toSource("example.test", "TestJson", object, "./");
}
}
| 39.818182
| 139
| 0.597032
|
1d568be060c0387561dc7317ae29726e88544b5c
| 7,982
|
package org.iplantc.service.apps.model;
import org.apache.commons.collections.CollectionUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Created with IntelliJ IDEA.
* User: steve
* Date: 4/5/12
* Time: 12:50 PM
* To change this template use File | Settings | File Templates.
*/
@Test(groups={"unit"})
public class GSoftwareOutputTest extends GModelTestCommon{
SoftwareOutput output = new SoftwareOutput();
@BeforeClass
public void setUp() throws Exception {
super.setUp();
}
@DataProvider(name = "dataTestOutput")
public Object[][] createData1() {
Object[][] mydata = jtd.dataTestOutput ;
return mydata;
}
@DataProvider(name = "dataTestOutputValue")
public Object[][] createData2() {
Object[][] mydata = jtd.dataTestOutputValue;
return mydata;
}
@DataProvider(name = "dataTestOutputDetails")
public Object[][] createData3() {
Object[][] mydata = jtd.dataTestOutputDetails;
return mydata;
}
@DataProvider(name = "dataTestOutputSemantics")
public Object[][] createData4() {
Object[][] mydata = jtd.dataTestOutputSemantics;
return mydata;
}
@Test (dataProvider="dataTestOutput")
public void outputFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeOutputs.toString());
jsonTree.put(name,changeValue);
super.commonSoftwareFromJSON(output,jsonTree, name,changeValue,message,expectExceptionThrown);
}
@Test (groups="model", dataProvider="dataTestOutputValue")
public void outputValueFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeOutputs.toString());
jsonTree.getJSONObject("value").put(name,changeValue);
super.commonSoftwareFromJSON(output,jsonTree,name,changeValue,message,expectExceptionThrown);
}
@Test (groups="model", dataProvider="dataTestOutputDetails")
public void outputDetailsFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeOutputs.toString());
jsonTree.getJSONObject("details").put(name,changeValue);
super.commonSoftwareFromJSON(output,jsonTree, name,changeValue,message,expectExceptionThrown);
}
@Test (groups="model", dataProvider="dataTestOutputSemantics")
public void outputSemanticsFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeOutputs.toString());
jsonTree.getJSONObject("semantics").put(name,changeValue);
super.commonSoftwareFromJSON(output,jsonTree,name,changeValue,message,expectExceptionThrown);
}
@Test(groups="model")
public void outputCloneCopiesEverything()
throws Exception
{
try {
// create a software object for the original output parameter's reference
Software software = new Software();
software.setId(new Long(1));
// set fields to positive values to ensure we do not get false positives during clone.
SoftwareInput output = new SoftwareInput();
output.setId(new Long(1));
output.setArgument("fooargument");
output.setEnquote(true);
output.setFileTypes("foo,bar,bat");
output.setKey("fookey");
output.setLabel("foolabel");
output.setMaxCardinality(12);
output.setMinCardinality(1);
output.setOntology(new JSONArray().put("xs:string").put("xs:foo").toString());
output.setOrder(6);
output.setRepeatArgument(true);
output.setRequired(false);
output.setShowArgument(true);
output.setSoftware(software);
output.setValidator(".*");
output.setVisible(false);
software.addInput(output);
// create a new software object to assign during the clone
Software clonedSoftware = new Software();
clonedSoftware.setId(new Long(2));
// run the clone
SoftwareInput clonedParameter = output.clone(clonedSoftware);
// validate every field was copied
Assert.assertEquals(clonedParameter.getArgument(), output.getArgument(), "Argument was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getDefaultValueAsJsonArray().toString(), output.getDefaultValueAsJsonArray().toString(), "defaultValue attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getDescription(), output.getDescription(), "description attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.isEnquote(), output.isEnquote(), "enquote attribute was not cloned from one software output to another");
Assert.assertNull(clonedParameter.getId(), "id attribute should not be cloned from one software output to another");
Assert.assertEquals(clonedParameter.getKey(), output.getKey(), "key attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getLabel(), output.getLabel(), "lable attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getMaxCardinality(), output.getMaxCardinality(), "maxCardinality attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getMinCardinality(), output.getMinCardinality(), "minCardinality attribute was not cloned from one software output to another");
Assert.assertTrue(CollectionUtils.isEqualCollection(clonedParameter.getOntologyAsList(), output.getOntologyAsList()), "ontology attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getOrder(), output.getOrder(), "order attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.isRepeatArgument(), output.isRepeatArgument(), "repeatArgument attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.isRequired(), output.isRequired(), "required attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.isShowArgument(), output.isShowArgument(), "showArgument attribute was not cloned from one software output to another");
Assert.assertNotNull(clonedParameter.getSoftware(), "Sofware reference was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getSoftware().getId(), clonedSoftware.getId(), "Wrong software reference was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.isVisible(), output.isVisible(), "visible attribute was not cloned from one software output to another");
Assert.assertEquals(clonedParameter.getValidator(), output.getValidator(), "Argument was not cloned from one software output to another");
// do a sanity check by serializing the json as well
Assert.assertEquals(output.toJSON(), clonedParameter.toJSON(), "cloned output serialized to different value than original output.");
} catch (Exception e) {
Assert.fail("Cloning software output should not throw exception",e);
}
}
}
| 54.29932
| 214
| 0.701829
|
3b2a5248e4a387a61b9d8d91aec502ba0c3a5379
| 442
|
package org.la4j;
import java.util.Arrays;
public final class V {
public static Vector v(double... values) {
return Vector.fromArray(values);
}
public static Iterable<Vector> vs(double... values) {
return Arrays.asList(
v(values).to(Vectors.BASIC),
v(values).to(Vectors.COMPRESSED)
);
}
public static Vector vz(int length) {
return Vector.zero(length);
}
}
| 20.090909
| 57
| 0.599548
|
37d5ed0e92f681d6d87a4215cc40a01faf2a213d
| 1,365
|
package com.beiing.baseframe.utils;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Created by chenliu on 2016/5/19.<br/>
* 描述:
* </br>
*/
public final class NumberUtil {
private NumberUtil() {
}
/**
* 货币格式化。
* 给两个小数点,并且隔三个数加个逗号
*
* @param money
* @return
*/
public static String formatMoney(double money) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.CHINA);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
return nf.format(money);
}
/**
* 分转换为元
*
* @param fen
* @return
*/
public static String fenToYuan(int fen) {
return String.valueOf(fen / 100f);
}
/**
* 分转换为元
*
* @param fen
* @return
*/
public static String fenToYuanWithPre(int fen) {
return String.valueOf("¥" + fen / 100f);
}
/**
*
*/
public static String yuanWithPre(int yuan) {
return String.valueOf("¥" + yuan);
}
/**
* 距离处理
* @param m
* @return 距离字符串
*/
public static String getDistanceStr(int m){
String disStr = "";
if(m < 1000){
disStr = "<" + m + "m";
} else {
m = m / 1000;
disStr = "<" + m + "km";
}
return disStr;
}
}
| 16.058824
| 71
| 0.506227
|
6981525aa67edd1dde26ca8539f5cd589141dd3e
| 8,673
|
package service;
import helper.JSONHelper;
import helper.WSHelper;
import model.json.input.Coord;
import model.json.input.geocode.AddressResponse;
import model.json.input.place.Address;
import model.json.input.place.AddressPlace;
import model.json.input.place.PlaceResponse;
import model.json.input.velib.VelibResponse;
import model.json.output.Data;
import model.json.output.Place;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.Minutes;
import play.Logger;
import play.libs.ws.WSResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MapService {
private static List<Place> staticParks;
private static List<Place> staticMuseums;
private static List<Place> staticVelibs;
private static Instant lastCheck;
public static void retrieveMap() {
PlaceResponse parkResponse = retrievePark();
staticParks = transformPlace(parkResponse.getAddresses());
PlaceResponse museumResponse = retrieveMuseum();
staticMuseums = transformPlace(museumResponse.getAddresses());
List<VelibResponse> velibResponses = retrieveVelib();
staticVelibs = transformVelib(velibResponses);
lastCheck = Instant.now();
}
private static PlaceResponse retrievePark() {
String url = "https://api.paris.fr:3000/data/1.0/Equipements/get_equipements/";
String token = "2e9e21d281009d7c585dfd981ced7c52baf0c3bd9f7b23ebb41960d2c954df9e32404d83c7ab86d1e6ef77c0dfd94730";
String cid = "7";
String offset = "10";
String limit = "100";
WSResponse wsResponse = WSHelper.ask(url, "token", token, "cid", cid, "offset", offset, "limit", limit);
Logger.debug("park URL : " + wsResponse.getUri().toString());
PlaceResponse parkResponse = JSONHelper.convertToObject(wsResponse.asJson(), PlaceResponse.class);
return parkResponse;
}
private static List<VelibResponse> retrieveVelib() {
String url = "https://api.jcdecaux.com/vls/v1/stations";
String apiKey = "a56c9c8e11df2ff056888f0add2da816c3a41c91";
String contract = "Paris";
WSResponse wsResponse = WSHelper.ask(url, "apiKey", apiKey, "contract", contract);
Logger.debug("velib URL : " + wsResponse.getUri().toString());
VelibResponse[] velibResponse = JSONHelper.convertToObject(wsResponse.asJson(), VelibResponse[].class);
return Arrays.asList(velibResponse);
}
private static PlaceResponse retrieveMuseum() {
String url = "https://api.paris.fr:3000/data/1.0/Equipements/get_equipements/";
String token = "2e9e21d281009d7c585dfd981ced7c52baf0c3bd9f7b23ebb41960d2c954df9e32404d83c7ab86d1e6ef77c0dfd94730";
String cid = "68";
String offset = "10";
String limit = "100";
WSResponse wsResponse = WSHelper.ask(url, "token", token, "cid", cid, "offset", offset, "limit", limit);
Logger.debug("museum URL : " + wsResponse.getUri().toString());
PlaceResponse museumResponse = JSONHelper.convertToObject(wsResponse.asJson(), PlaceResponse.class);
return museumResponse;
}
private static synchronized void updateVelibs() {
final Instant now = Instant.now();
Duration duration = new Duration(lastCheck, now);
if (duration.isLongerThan(Minutes.THREE.toStandardDuration())) {
List<VelibResponse> velibResponses = retrieveVelib();
staticVelibs = transformVelib(velibResponses);
}
}
public static Data associate(double rad, double lat, double lng, String type, boolean all) {
// check if update velib is needed
//updateVelibs();
List<Place> places = new ArrayList<>();
Data data = new Data();
// specific place around me
if (rad != 0 && lat != 0 && lng != 0 || type != null) {
if (rad != 0 && lat != 0 && lng != 0 && type != null) {
if ("park".equals(type)) {
places.addAll(findPlace(staticParks, rad, lat, lng));
} else if ("museum".equals(type)) {
places.addAll(findPlace(staticMuseums, rad, lat, lng));
}
// wher i am
} else if (rad != 0 && lat != 0 && lng != 0) {
Place place = new Place(0, "My place", lat, lng);
places.add(place);
} else if (type != null) {
if ("park".equals(type)) {
places.addAll(staticParks);
} else if ("museum".equals(type)) {
places.addAll(staticMuseums);
}
}
data = associate(places, rad, all);
} else {
data.addDate(lastCheck.toDateTime());
data.getVelibs().addAll(staticVelibs);
}
return data;
}
public static List<Place> findPlace(List<Place> places, double radius, double lat, double lng) {
List<Place> result = new ArrayList<>();
Coord myCoord = new Coord(lat, lng);
for (Place place : places) {
Coord coordPlace = new Coord(place.getLat(), place.getLng());
double distance = calculate(myCoord, coordPlace);
if (distance < radius) {
result.add(place);
}
}
return result;
}
public static Data associate(List<Place> places, double radius, boolean all) {
Data data = new Data();
data.addDate(lastCheck.toDateTime());
for (Place place : places) {
data.getPlaces().add(place);
Coord coordPlace = new Coord(place.getLat(), place.getLng());
for (Place velib : staticVelibs) {
Coord coordVelib = new Coord(velib.getLat(), velib.getLng());
double distance = calculate(coordPlace, coordVelib);
if (distance < radius) {
velib.setDistance(distance);
place.addVelib(velib.getAll(), velib.getLeft());
data.getVelibs().add(velib);
} else if (all) {
velib.setDistance(0);
data.getOthers().add(velib);
}
}
}
data.getOthers().removeAll(data.getVelibs());
return data;
}
private static double calculate(Coord coordPlace, Coord coordVelib) {
double distance;
int R = 6371; // km
double dLat = Math.toRadians(coordVelib.getLat() - coordPlace.getLat());
double dLon = Math.toRadians(coordVelib.getLng() - coordPlace.getLng());
double lat1 = Math.toRadians(coordVelib.getLat());
double lat2 = Math.toRadians(coordPlace.getLat());
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance = R * c;
return distance;
}
private static AddressResponse retrieveCoord(Address placeAddress) {
String url = "https://api.paris.fr:3000/data/1.0/Equipements/get_equipement/";
String token = "2e9e21d281009d7c585dfd981ced7c52baf0c3bd9f7b23ebb41960d2c954df9e32404d83c7ab86d1e6ef77c0dfd94730";
String id = String.valueOf(placeAddress.getId());
WSResponse wsResponse = WSHelper.ask(url, "token", token, "id", id);
AddressResponse addressResponse = JSONHelper.convertToObject(wsResponse.asJson(), AddressResponse.class);
return addressResponse;
}
private static List<Place> transformPlace(List<Address> addresses) {
List<Place> places = new ArrayList<>(addresses.size());
for (Address address : addresses) {
AddressResponse addressResponse = retrieveCoord(address);
AddressPlace addressPlace = addressResponse.getAddresses().get(0);
Place place = new Place(addressPlace.getIdEquipement(), address.getName(), addressPlace.getLat(), addressPlace.getLon());
places.add(place);
}
return places;
}
private static List<Place> transformVelib(List<VelibResponse> velibResponses) {
List<Place> velibs = new ArrayList<>(velibResponses.size());
for (VelibResponse velibResponse : velibResponses) {
Place velib = new Place(velibResponse.getNumber(), velibResponse.getName(), velibResponse.getPosition().getLat(), velibResponse.getPosition().getLng());
velib.addVelib(velibResponse.getBikeStands(), velibResponse.getAvailableBikes());
velibs.add(velib);
}
return velibs;
}
}
| 37.873362
| 164
| 0.62585
|
6d640751da0082d5b773a915466b78c03d0a78c2
| 6,853
|
/*
* Copyright 2011 Mikhail Lopatkin
*
* 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 name.mlopatkin.andlogview.widgets;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.FlowView;
import javax.swing.text.FlowView.FlowStrategy;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
// This is an old-style code, I'll fix issues eventually.
@SuppressWarnings("NullAway")
public class StyledLabel extends JTextPane {
public StyledLabel() {
setEditorKit(new WrapEditorKit());
}
private static class WrapEditorKit extends StyledEditorKit {
ViewFactory defaultFactory = new WrapColumnFactory();
@Override
public ViewFactory getViewFactory() {
return defaultFactory;
}
}
private static class WrapColumnFactory implements ViewFactory {
@Override
public View create(Element elem) {
String kind = elem.getName();
if (kind != null) {
switch (kind) {
case AbstractDocument.ContentElementName:
return new CroppingLabelView(elem);
case AbstractDocument.ParagraphElementName:
return new NoWrapParagraphView(elem);
case AbstractDocument.SectionElementName:
return new CenteredBoxView(elem, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(elem);
case StyleConstants.IconElementName:
return new IconView(elem);
}
}
return new LabelView(elem);
}
}
private static final FlowStrategy CROPPING_STRATEGY = new FlowStrategy() {
@Override
protected int layoutRow(FlowView fv, int rowIndex, int pos) {
super.layoutRow(fv, rowIndex, pos);
return fv.getEndOffset();
}
};
private static class NoWrapParagraphView extends ParagraphView {
public NoWrapParagraphView(Element elem) {
super(elem);
strategy = CROPPING_STRATEGY;
}
}
private static class CenteredBoxView extends BoxView {
public CenteredBoxView(Element elem, int axis) {
super(elem, axis);
}
@Override
protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
super.layoutMajorAxis(targetSpan, axis, offsets, spans);
int textBlockHeight = 0;
for (int span : spans) {
textBlockHeight = span;
}
int offset = (targetSpan - textBlockHeight) / 2;
for (int i = 0; i < offsets.length; i++) {
offsets[i] += offset;
}
}
}
private static class CroppingLabelView extends LabelView {
public CroppingLabelView(Element elem) {
super(elem);
}
private FontMetrics fm;
private static final String ELLIPSIS = "...";
@SuppressWarnings("deprecation")
private float getEllipsisWidth() {
if (fm == null) {
fm = Toolkit.getDefaultToolkit().getFontMetrics(getFont());
}
return fm.stringWidth(ELLIPSIS);
}
@Override
public int getBreakWeight(int axis, float pos, float len) {
len = len - getEllipsisWidth();
if (len <= 0) {
return BadBreakWeight;
}
int bw = super.getBreakWeight(axis, pos, len);
if (bw != BadBreakWeight) {
return GoodBreakWeight;
} else {
return bw;
}
}
private boolean isEllipsisShown;
@Override
public View breakView(int axis, int p0, float pos, float len) {
if (axis == View.X_AXIS) {
checkPainter();
float l = len - getEllipsisWidth();
if (l < 0) {
l = 0.0F;
}
int p1 = getGlyphPainter().getBoundedPosition(this, p0, pos, l);
// else, no break in the region, return a fragment of the
// bounded region.
isEllipsisShown = true;
if (p0 == getStartOffset() && p1 == getEndOffset()) {
return this;
}
return createFragment(p0, p1);
}
return this;
}
@Override
public float getPreferredSpan(int axis) {
float span = super.getPreferredSpan(axis);
if (axis == View.X_AXIS && isEllipsisShown) {
span += getEllipsisWidth();
}
return span;
}
@Override
public void paint(Graphics g, Shape a) {
super.paint(g, a);
if (isEllipsisShown) {
Rectangle alloc = a instanceof Rectangle ? (Rectangle) a : a.getBounds();
int last = (int) (getPreferredSpan(View.X_AXIS) - getEllipsisWidth());
Rectangle clip = new Rectangle(alloc.x + last, alloc.y, (int) getEllipsisWidth(), alloc.height);
Shape oldClip = g.getClip();
g.setClip(clip);
g.setFont(getFont());
int charHeight = 0;
if (getContainer() != null) {
charHeight = getContainer().getFontMetrics(getFont()).getHeight();
g.drawString(ELLIPSIS, alloc.x + last,
alloc.y + fm.getMaxAscent() + (alloc.height - charHeight) / 2);
} else {
g.drawString(ELLIPSIS, alloc.x + last, alloc.y + alloc.height - fm.getMaxDescent());
}
g.setClip(oldClip);
}
}
}
}
| 34.786802
| 112
| 0.572304
|
18cc9cf4927794e2abbbf731e84b86aec53ae253
| 610
|
import java.util.Arrays;
public class Solution {
public void hanota(int[] A, int[] B, int[] C) {
int len = A.length;
System.out.println(len);
C = new int[len];
System.out.println(Arrays.toString(C));
System.arraycopy(A, 0, C, 0, len);
System.out.println(Arrays.toString(C));
Arrays.fill(A, 0);
}
public static void main(String[] args) {
int[] A = {0};
int[] B = {};
int[] C = {};
Solution solution = new Solution();
solution.hanota(A,B,C);
System.out.println(Arrays.toString(C));
}
}
| 22.592593
| 51
| 0.529508
|
175bb6530652b487a8732dc907521c158341ff02
| 4,949
|
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Jimfs;
import com.google.common.truth.Truth;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for the AndroidManifest class */
@RunWith(JUnit4.class)
public class AndroidManifestTest {
private FileSystem fileSystem;
@Before
public void setUp() throws Exception {
fileSystem = Jimfs.newFileSystem();
}
@Test
public void parseMinSdkAndPackageName() throws Exception {
final String packageName = "com.google.wooga";
final String minSdk = "26";
final AndroidManifest androidManifest =
AndroidManifest.parseFrom(manifest(packageName, minSdk).write(fileSystem.getPath("tmp")));
Truth.assertThat(androidManifest).isEqualTo(AndroidManifest.of(packageName, minSdk));
}
@Test
public void parseMissingMinSdk() throws Exception {
final String packageName = "com.google.wooga";
final AndroidManifest androidManifest =
AndroidManifest.parseFrom(manifest(packageName).write(fileSystem.getPath("tmp")));
Truth.assertThat(androidManifest).isEqualTo(AndroidManifest.of(packageName, "1"));
}
@Test
public void writeDummyManifestWithoutPlaceholdersNoMinSdk() throws Exception {
final String packageName = "${applicationId}.wooga";
final String packageForR = "com.google.android.wooga";
final AndroidManifest androidManifest =
AndroidManifest.parseFrom(manifest(packageName).write(fileSystem.getPath("tmp")));
Truth.assertThat(
Files.readAllLines(
androidManifest.writeDummyManifestForAapt(
fileSystem.getPath("dummy-manifest"), packageForR),
StandardCharsets.UTF_8))
.containsExactly(
"<?xml version='1.0' encoding='utf-8'?>",
"<manifest xmlns:android='http://schemas.android.com/apk/res/android'",
"package='com.google.android.wooga'>",
"<application/>",
"<uses-sdk android:minSdkVersion='1'/>",
"</manifest>")
.inOrder();
}
@Test
public void writeDummyManifestWithoutPlaceholdersAndMinSdk() throws Exception {
final String packageName = "${applicationId}.wooga";
final String packageForR = "com.google.android.wooga";
final AndroidManifest androidManifest =
AndroidManifest.parseFrom(manifest(packageName, "26").write(fileSystem.getPath("tmp")));
Truth.assertThat(
Files.readAllLines(
androidManifest.writeDummyManifestForAapt(
fileSystem.getPath("dummy-manifest"), packageForR),
StandardCharsets.UTF_8))
.containsExactly(
"<?xml version='1.0' encoding='utf-8'?>",
"<manifest xmlns:android='http://schemas.android.com/apk/res/android'",
"package='com.google.android.wooga'>",
"<application/>",
"<uses-sdk android:minSdkVersion='26'/>",
"</manifest>")
.inOrder();
}
private static Manifest manifest(String pkg) {
return manifest(pkg, "");
}
private static Manifest manifest(String pkg, String minSdk, String... lines) {
return parent ->
Files.write(
Files.createDirectories(parent).resolve("AndroidManifest.xml"),
ImmutableList.<String>builder()
.add(
"<?xml version='1.0' encoding='utf-8'?>",
"<manifest",
" xmlns:android='http://schemas.android.com/apk/res/android'",
String.format(" package='%s'>", pkg),
"<application>",
(minSdk == null || minSdk.isEmpty())
? ""
: String.format("<uses-sdk android:minSdkVersion='%s'/>", minSdk))
.add(lines)
.add("</application>", "</manifest>")
.build(),
CREATE_NEW);
}
private interface Manifest {
Path write(Path parent) throws IOException;
}
}
| 37.492424
| 98
| 0.653667
|
241254ebfa044c4d0cd7adbd40fe555b0e0977d4
| 713
|
package me.apjung.backend.service.shop;
import me.apjung.backend.domain.shop.ShopSafeLevel;
import me.apjung.backend.domain.user.User;
import me.apjung.backend.dto.request.ShopRequest;
import me.apjung.backend.dto.response.ShopResponse;
import java.util.List;
public interface ShopService {
ShopResponse.Create create(ShopRequest.Create request);
ShopResponse.Safe safe(Long shopId, ShopSafeLevel level);
ShopResponse.GET get(Long shopId, User user);
// 쇼핑몰 즐겨찾기 관련 서비스
ShopResponse.CreatePin createPin(Long shopId, User currentUser) throws Exception;
ShopResponse.DeletePin deletePin(Long shopPinId, User currentUser);
List<ShopResponse.GET> getMyPinnedShops(User currentUser);
}
| 35.65
| 85
| 0.791024
|
a1d3f38719d24dada38e15fff9e541abe727d562
| 449
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base;
import org.chromium.base.annotations.UsedByReflection;
/**
* Class only compiled into android app bundles but not into APKs. Used to determine whether a build
* is a bundle.
*/
@UsedByReflection("BundleUtils.java")
/* package */ class BundleCanary {}
| 29.933333
| 100
| 0.755011
|
9fd43de157a7b8beb30725452a145a736f0de2a6
| 13,212
|
package com.ivanov.tech.profile.ui;
import java.util.ArrayList;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.ivanov.tech.profile.R;
import com.ivanov.tech.profile.provider.DBContentProvider;
import com.ivanov.tech.profile.provider.DBContract;
import com.ivanov.tech.session.Session;
import com.meetme.android.horizontallistview.HorizontalListView;
/**
* Created by Igor on 09.05.15.
*/
public class FragmentSelectUsers extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener{
private static final String TAG = FragmentSelectUsers.class
.getSimpleName();
protected static final int LOADER_USER = 1;
MenuItem menuOK=null;
ArrayList<UserData> users=new ArrayList<UserData>();
ArrayList<UserData> users_selected=new ArrayList<UserData>();
UsersAdapter adapter_users;
HorizontalAdapter adapter_horizontal;
ListView listview;
HorizontalListView horizontal;
TextView textview_empty;
String tittle;
ResultListener resultlistener;
public static FragmentSelectUsers newInstance(String tittle,ResultListener resultlistener) {
FragmentSelectUsers f = new FragmentSelectUsers();
f.tittle=tittle;
f.resultlistener=resultlistener;
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.d(TAG, "onCreate");
adapter_users=new UsersAdapter(getActivity(),users);
adapter_horizontal=new HorizontalAdapter(getActivity(),users_selected);
getLoaderManager().initLoader(LOADER_USER, null, this);
setHasOptionsMenu(true);
}
@Override
public void onStart() {
super.onStart();
//Log.d(TAG, "onStart");
}
@Override
public void onStop() {
super.onStop();
//Log.d(TAG, "onStop");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = null;
view=inflater.inflate(R.layout.selectusers, container, false);
listview = (ListView)view.findViewById(R.id.selectusers_listview);
listview.setEmptyView(view.findViewById(R.id.selectusers_textview_listview_is_empty));
listview.setAdapter(adapter_users);
listview.setOnItemClickListener(this);
listview.setClickable(true);
horizontal = (HorizontalListView)view.findViewById(R.id.selectusers_horizontal);
horizontal.setAdapter(adapter_horizontal);
horizontal.setOnItemClickListener(this);
horizontal.setClickable(true);
textview_empty=(TextView)view.findViewById(R.id.selectusers_textview_empty);
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(parent==listview){
//Log.d(TAG, "onItemClick listview position="+position);
users.get(position).checked=!users.get(position).checked;
if(users.get(position).checked) users_selected.add(users.get(position));
else users_selected.remove(users.get(position));
}else if(parent==horizontal){
//Log.d(TAG, "onItemClick horizontal position="+position);
users_selected.get(position).checked=!users_selected.get(position).checked;
users_selected.remove(position);
}
adapter_users.notifyDataSetChanged();
adapter_horizontal.notifyDataSetChanged();
updateViewsState();
String menuTittle=getActivity().getResources().getString(R.string.menu_ok);
if(users_selected.size()>0)
menuTittle=menuTittle+"("+users_selected.size()+")";
menuOK.setTitle(menuTittle);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
menuOK=menu.add(R.string.menu_ok);
menuOK.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
((AppCompatActivity)getActivity()).getSupportActionBar().show();
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(tittle);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==menuOK.getItemId()){
//Log.d(TAG, "onOptionsItemSelected menuOK");
SuccessAndClose();
return true;
}
if(id==android.R.id.home){
//Log.d(TAG, "onOptionsItemSelected menuHome");
Close();
return true;
}
return false;
}
//-----------UI ViewsState Utils----------------------------
void updateViewsState(){
if(users_selected.size()==0){
menuOK.setEnabled(false);
textview_empty.setVisibility(View.VISIBLE);
}else{
menuOK.setEnabled(true);
textview_empty.setVisibility(View.INVISIBLE);
}
}
//---------------Input&Output----------------------
void createUsersData(Cursor cursor){
//Log.d(TAG, "createUsersData");
users.clear();
if(cursor.getCount()==0)return;
cursor.moveToFirst();
do{
UserData user=new UserData();
user.user_id=cursor.getInt(cursor.getColumnIndex(DBContract.User.COLUMN_NAME_SERVER_ID));
user.name=cursor.getString(cursor.getColumnIndex(DBContract.User.COLUMN_NAME_NAME));
user.icon_url=cursor.getString(cursor.getColumnIndex(DBContract.User.COLUMN_NAME_URL_ICON));
user.checked=false;
users.add(user);
}while((cursor.moveToNext()));
adapter_users.notifyDataSetChanged();
adapter_horizontal.notifyDataSetChanged();
updateViewsState();
}
void SuccessAndClose(){
final ArrayList<Integer> result=new ArrayList<Integer>();
for(int i=0;i<users_selected.size();i++){
result.add(users_selected.get(i).user_id);
}
getFragmentManager().popBackStack();
resultlistener.onSuccess(result);
}
void Close(){
getFragmentManager().popBackStack();
}
//-------------Adapters----------------------
public class UsersAdapter extends ArrayAdapter<UserData> {
private LayoutInflater mInflater;
public UsersAdapter(Context context, ArrayList<UserData> values) {
super(context, R.layout.selectusers_listview_item, values);
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
// Inflate the view since it does not exist
convertView = mInflater.inflate(R.layout.selectusers_listview_item, parent, false);
// Create and save off the holder in the tag so we get quick access to inner fields
// This must be done for performance reasons
holder = new Holder();
holder.textview = (TextView) convertView.findViewById(R.id.selectusers_listview_item_name);
holder.imageview = (ImageView) convertView.findViewById(R.id.selectusers_listview_item_icon);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.selectusers_listview_item_check);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.textview.setText(getItem(position).name);
holder.checkbox.setChecked(getItem(position).checked);
Glide.with(getActivity()).load(getItem(position).icon_url).placeholder(R.drawable.ic_no_icon).error(R.drawable.ic_no_icon).into(holder.imageview);
return convertView;
}
/** View holder for the views we need access to */
private class Holder {
public TextView textview;
public CheckBox checkbox;
public ImageView imageview;
}
}
public class HorizontalAdapter extends ArrayAdapter<UserData> {
private LayoutInflater mInflater;
public HorizontalAdapter(Context context, ArrayList<UserData> values) {
super(context, R.layout.selectusers_horizontal_item, values);
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
// Inflate the view since it does not exist
convertView = mInflater.inflate(R.layout.selectusers_horizontal_item, parent, false);
// Create and save off the holder in the tag so we get quick access to inner fields
// This must be done for performance reasons
holder = new Holder();
holder.imageview = (ImageView) convertView.findViewById(R.id.selectusers_horizontal_item_imageview);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
Glide.with(getActivity()).load(getItem(position).icon_url).placeholder(R.drawable.ic_no_icon).error(R.drawable.ic_no_icon).into(holder.imageview);
return convertView;
}
/** View holder for the views we need access to */
protected class Holder {
public ImageView imageview;
}
}
//------------UserData-----------------------------
public class UserData{
public int user_id;
public String icon_url;
public String name;
public boolean checked;
}
//-------------Loader<Cursor>------------------
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection=null;
Uri uri=null;
switch(id) {
case LOADER_USER:
projection = new String[]{
DBContract.User._ID,
DBContract.User.COLUMN_NAME_SERVER_ID,
DBContract.User.COLUMN_NAME_NAME,
DBContract.User.COLUMN_NAME_URL_ICON
};
uri = DBContentProvider.URI_USER;
break;
}
//Log.d(TAG, "onCreateLoader uri="+uri.toString());
CursorLoader cursorLoader = new CursorLoader(getActivity(),
uri, projection, null, null, null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//Log.d(TAG, "onLoadFinished uri="+data.toString());
switch(loader.getId()){
case LOADER_USER:
createUsersData(data);
break;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
//Log.d(TAG, "onLoaderReset");
}
//---------Callback listener to get list of users------------------------------
public interface ResultListener{
public void onSuccess(ArrayList<Integer> usersid);
}
}
| 32.145985
| 158
| 0.645474
|
ba05b5d82d390af97ac43ff01b2afff422f3043b
| 426
|
package me.mrdaniel.npcs.catalogtypes.horsecolor;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.util.annotation.CatalogedBy;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@CatalogedBy(HorseColors.class)
public class HorseColor implements CatalogType {
@Getter private final String name;
@Getter private final String id;
@Getter private final int nbtId;
}
| 26.625
| 57
| 0.830986
|
2a2d2eaee423de46897f652d212fbdba2a140229
| 2,590
|
/*
* Copyright (C) Lightbend Inc. <https://www.lightbend.com>
*/
package play.mvc;
import akka.stream.IOResult;
import akka.stream.Materializer;
import akka.stream.javadsl.FileIO;
import akka.stream.javadsl.Sink;
import akka.util.ByteString;
import play.api.http.HttpConfiguration;
import play.core.parsers.Multipart;
import play.http.HttpErrorHandler;
import play.libs.streams.Accumulator;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
public class DummyDelegatingMultipartFormDataBodyParser
extends BodyParser.DelegatingMultipartFormDataBodyParser<File> {
@Inject
public DummyDelegatingMultipartFormDataBodyParser(
Materializer materializer,
long maxMemoryBufferSize,
long maxLength,
HttpErrorHandler errorHandler) {
super(materializer, maxMemoryBufferSize, maxLength, errorHandler);
}
@Override
public Function<Multipart.FileInfo, Accumulator<ByteString, Http.MultipartFormData.FilePart<File>>>
createFilePartHandler() {
return (Multipart.FileInfo fileInfo) -> {
final String filename = fileInfo.fileName();
final String partname = fileInfo.partName();
final String contentType = fileInfo.contentType().getOrElse(null);
final File file = generateTempFile();
final String dispositionType = fileInfo.dispositionType();
final Sink<ByteString, CompletionStage<IOResult>> sink = FileIO.toPath(file.toPath());
return Accumulator.fromSink(
sink.mapMaterializedValue(
completionStage ->
completionStage.thenApplyAsync(
results ->
new Http.MultipartFormData.FilePart<>(
partname,
filename,
contentType,
file,
results.getCount(),
dispositionType))));
};
}
private File generateTempFile() {
try {
final Path path = Files.createTempFile("multipartBody", "tempFile");
return path.toFile();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| 36.478873
| 101
| 0.599228
|
c6b2e22c7a79b98d8912162260a9c8a1c455c034
| 698
|
class BullshitReturnDemo {
//定义特殊的返回值
public static final String ERROR_MSG = "Error:getHttpByPostBody exception";
public static String getHttpByPostBody(String url, String data) throws IOException{
Request request = Request.of(url).setBody(data).setConnectionTimeout(CONNECT_TIMEOUT).setReadTimeout(READ_TIMEOUT);
request.addHeader("Content-type" , HttpConstants.FORM_URLENCODED_WITH_DEFAULT_CHARSET);
Response response = SMART_HTTP_CLIENT.post(request);
if(HttpStatus.HTTP_OK == response.getStatusCode()){
return response.getBody();
}else {
///返回这种特定的值,改变http的语义,很不规范,很不好统一
return ERROR_MSG;
}
}
}
| 46.533333
| 123
| 0.700573
|
1b9817ab9c72816a442daca2d7dc23ebe736e5f4
| 5,328
|
/**
* Copyright (C) 2002-2015 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.io.IOException;
import org.junit.*;
import org.junit.Test;
import net.sf.freecol.util.test.FreeColTestCase;
public class ModTest extends FreeColTestCase {
public void testMakeFileFilter_1()
throws Exception {
String requiredFile = "";
FileFilter result = FreeColDataFile.makeFileFilter(requiredFile);
// add additional test code here
assertNotNull(result);
}
public void testGetRuleSets() {
Set<String> ids = new HashSet<String>();
for (FreeColModFile mod : Mods.getRuleSets()) {
assertNotNull("Null identifier for " + mod, mod.getId());
ids.add(mod.getId());
}
assertTrue(ids.contains("freecol"));
assertTrue(ids.contains("classic"));
assertFalse(ids.contains("testing"));
}
public void testMods_1()
throws Exception {
Mods result = new Mods();
assertNotNull(result);
}
/**
* Run the Collection<FreeColModFile> getAllMods() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 5/16/17 12:31 AM
*/
@Test
public void testGetAllMods_1()
throws Exception {
Collection<FreeColModFile> result = Mods.getAllMods();
assertNotNull(result);
}
/**
* Run the FreeColModFile getFreeColModFile(String) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 5/16/17 12:31 AM
*/
@Test
public void testGetFreeColModFile_1()
throws Exception {
String id = "";
FreeColModFile result = Mods.getFreeColModFile(id);
assertEquals(null, result);
}
/**
* Run the FreeColModFile getModFile(String) method test.
*
* @throws Exception
*
* @generatedBy CodePro at 5/16/17 12:31 AM
*/
@Test
public void testGetModFile_1()
throws Exception {
String id = "";
FreeColModFile result = Mods.getModFile(id);
assertEquals(null, result);
}
/**
* Run the List<FreeColTcFile> getRuleSets() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 5/16/17 12:31 AM
*/
@Test
public void testGetRuleSets_1()
throws Exception {
List<FreeColTcFile> result = Mods.getRuleSets();
assertNotNull(result);
}
public void testLoadMods_1()
throws Exception {
Mods.loadMods();
}
/**
* Run the FileFilter getFileFilter() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 5/16/17 12:31 AM
*/
@Test
public void testGetFileFilter_1()
throws Exception {
FileFilter result = FreeColSavegameFile.getFileFilter();
assertNotNull(result);
}
public void testGetFileNames_1()
throws Exception {
String prefix = "";
String suffix = "";
Locale locale = Locale.getDefault();
List<String> result = FreeColDataFile.getFileNames(prefix, suffix, locale);
assertNotNull(result);
assertEquals(3, result.size());
assertTrue(result.contains(""));
assertTrue(result.contains("_en"));
assertTrue(result.contains("_en_US"));
}
public void testGetFileNames_2()
throws Exception {
String prefix = "";
String suffix = "";
Locale locale = Locale.getDefault();
List<String> result = FreeColDataFile.getFileNames(prefix, suffix, locale);
assertNotNull(result);
assertEquals(3, result.size());
assertTrue(result.contains(""));
assertTrue(result.contains("_en"));
assertTrue(result.contains("_en_US"));
}
@Test
public void testGetResourceFileNames_1()
throws Exception {
List<String> result = FreeColDataFile.getResourceFileNames();
assertNotNull(result);
assertEquals(3, result.size());
assertTrue(result.contains("resources.properties"));
assertTrue(result.contains("resources_en.properties"));
assertTrue(result.contains("resources_en_US.properties"));
}
}
| 23.575221
| 81
| 0.62988
|
b2d84d21a3e8dd9bee30d6f92198e8797e544342
| 245
|
package ge.btu.lecture10.service;
import ge.btu.lecture10.DTO.comment.AddCommentInput;
import ge.btu.lecture10.DTO.comment.AddCommentOutput;
public interface CommentService {
AddCommentOutput addComment(AddCommentInput addCommentInput);
}
| 27.222222
| 65
| 0.832653
|
cd2aed5d39f4bf846cdb19a82b67de3e8564b519
| 10,503
|
package notaql.engines.mongodb;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
/**
* Collection of frequently used methods for MongoDB.
*/
public class MongoApi {
// Configuration
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 27017;
// Object variables
private final String host;
private final int port;
private MongoClient mongoClient;
/**
* Initializes the API with the default host and default port.
*/
public MongoApi() {
this(DEFAULT_HOST, DEFAULT_PORT);
}
/**
* Initializes the API with the given host and the default port.
*
* @param host
*/
public MongoApi(String host) {
this(host, DEFAULT_PORT);
}
/**
* Initializes the API with the default host and the given port.
*
* @param port
*/
public MongoApi(int port) {
this(DEFAULT_HOST, port);
}
/**
* Initializes the API with the given host and the given port.
*
* @param host
* @param port
*/
public MongoApi(String host, int port) {
this.host = host;
this.port = port;
}
/**
* @return the hostname
*/
public String getHost() {
return this.host;
}
/**
* @return the port
*/
public int getPort() {
return this.port;
}
/**
* Gets a MongoClient instance.
*
* @return
* @throws IOException
*/
public MongoClient getMongo() throws IOException {
if (mongoClient == null)
mongoClient = new MongoClient(this.host, this.port);
return mongoClient;
}
/**
* Closes the MongoClient instance (if any).
* @throws IOException
*/
public void close() throws IOException {
if (mongoClient != null)
mongoClient.close();
}
/**
* Gets the database with the given name.
*
* MongoDB creates the db on the first method call if it does not exist (only getting it won't create it).
*
* @param databaseName
* @return
* @throws IOException
*/
public DB getDatabase(String databaseName) throws IOException {
// Get a MongoDB-Connection
MongoClient mongo = getMongo();
return mongo.getDB(databaseName);
}
/**
* Gets the collection with the given name.
*
* @param collectionName
* @param databaseName
* @return
*/
public DBCollection getCollection(String databaseName, String collectionName) throws IOException {
return getCollection(databaseName, collectionName, false);
}
/**
* Gets the collection with the given name.
*
* @param collectionName
* @param databaseName
* @param sharded
* @return
*/
public DBCollection getCollection(String databaseName, String collectionName, boolean sharded) throws IOException {
// Get a MongoDB-Connection
MongoClient mongo = getMongo();
DBCollection collection = mongo.getDB(databaseName).getCollection(collectionName);
// Shard the collection
if (sharded) {
// Hashed index on collection
BasicDBObject index = new BasicDBObject("_id", "hashed");
collection.createIndex(index);
// Sharded DB?
BasicDBObject shardCommandDb = new BasicDBObject("enableSharding", databaseName);
mongo.getDB("admin").command(shardCommandDb);
// Sharded collection
BasicDBObject shardCommandCollection = new BasicDBObject("shardCollection", databaseName + "." + collectionName).append("key", index);
mongo.getDB("admin").command(shardCommandCollection);
}
return collection;
}
/**
* Drops the database with the given name.
*
* @param databaseName
* @throws IOException
*/
public void dropDatabase(String databaseName) throws IOException {
// Get a MongoDB-Connection
MongoClient mongo = getMongo();
mongo.dropDatabase(databaseName);
}
/**
* Deletes an object with the given object id from the collection.
*
* @param collection
* @param objectId
*/
public void delete(DBCollection collection, String objectId) {
delete(collection, "_id", objectId);
}
/**
* Deletes objects from the given collection.
*
* @param collection
* @param key
* @param value
*/
public void delete(DBCollection collection, String key, String value) {
BasicDBObject searchQuery = new BasicDBObject().append(key, value);
collection.remove(searchQuery);
}
/**
* Gets a value from the given collection by object-id and key.
*
* @param collection
* @param objectId
* @param value
* @return the data
*/
public Object get(DBCollection collection, String objectId, String key) {
List<Object> list = getMulti(collection, "_id", objectId, key);
if (list.isEmpty())
return null;
else
return list.get(0);
}
/**
* Gets a value from the given collection by searching for a specific key/value combination
*
* @param collection
* @param key
* @param value
* @param keyInsideObject
* @return the data
*/
public Object get(DBCollection collection, String key, String value, String keyInsideObject) {
List<Object> list = getMulti(collection, key, value, keyInsideObject);
if (list.isEmpty())
return null;
else
return list.get(0);
}
/**
* Gets values from the given collection by searching for a specific key/value combination
*
* @param collection
* @param key
* @param value
* @param keyInsideObject
* @return the data
*/
public List<Object> getMulti(DBCollection collection, String key, String value, String keyInsideObject) {
BasicDBObject searchQuery = new BasicDBObject().append(key, value);
DBCursor cursor = collection.find(searchQuery);
if (!cursor.hasNext())
return Collections.emptyList();
else {
List<Object> list = new ArrayList<Object>();
while (cursor.hasNext())
list.add(((BasicDBObject) cursor.next()).get(keyInsideObject));
return list;
}
}
/**
* Checks if the given query returns at least one object.
*
* @param collection
* @param searchQuery
* @return
*/
public boolean exists(DBCollection collection, BasicDBObject searchQuery) {
DBCursor cursor = collection.find(searchQuery).limit(1);
if (cursor.hasNext())
return true;
else
return false;
}
/**
* Puts (as upsert) an object to the object in the given collection.
*
* @param databaseName
* @param objectId
* @param key
* @param value
*/
public void put(DBCollection collection, Object objectId, String key, Object value) {
put(collection, objectId, key, value, true);
}
/**
* Puts an object to the object in the given collection.
*
* @param databaseName
* @param objectId
* @param key
* @param value
* @param upsert
*/
public void put(DBCollection collection, Object objectId, String key, Object value, boolean upsert) {
put(collection, "_id", objectId, key, value, upsert);
}
/**
* Puts (as upsert) an object to the object in the given collection.
*
* @param databaseName
* @param key
* @param value
* @param keyInsideObject
* @param valueInsideObject
*/
public void put(DBCollection collection, String key, Object value, String keyInsideObject, Object valueInsideObject) {
put(collection, key, value, keyInsideObject, valueInsideObject, true);
}
/**
* Puts an object to the object in the given collection.
*
* @param databaseName
* @param key
* @param value
* @param keyInsideObject
* @param valueInsideObject
* @param updateOne
*/
public void put(DBCollection collection, String key, Object value, String keyInsideObject, Object valueInsideObject, boolean updateOne) {
put(collection, key, value, keyInsideObject, valueInsideObject, updateOne, true);
}
/**
* Puts an object to the object in the given collection.
*
* @param databaseName
* @param key
* @param value
* @param keyInsideObject
* @param valueInsideObject
* @param updateOne
* @param upsert
*/
public void put(DBCollection collection, String key, Object value, String keyInsideObject, Object valueInsideObject, boolean updateOne, boolean upsert) {
put(collection, key, value, keyInsideObject, valueInsideObject, updateOne, upsert, null);
}
/**
* Puts an object to the object in the given collection.
*
* @param databaseName
* @param key
* @param value
* @param keyInsideObject
* @param valueInsideObject
* @param updateOne
* @param upsert
* @param bulk
*/
public void put(DBCollection collection, String key, Object value, String keyInsideObject, Object valueInsideObject, boolean updateOne, boolean upsert, BulkWriteOperation bulk) {
if (upsert) {
// Create an object with the new values
BasicDBObject newObject = new BasicDBObject().append("$set", new BasicDBObject().append(keyInsideObject, valueInsideObject));
// Do an upsert
BasicDBObject searchQuery = new BasicDBObject().append(key, value);
if (bulk != null) {
if (updateOne)
bulk.find(searchQuery).upsert().updateOne(newObject);
else
bulk.find(searchQuery).upsert().update(newObject);
}
else
collection.update(searchQuery, newObject, true, updateOne);
}
else {
// Create an object with the new values
BasicDBObject newObject = new BasicDBObject();
newObject.put(key, value);
newObject.put(keyInsideObject, valueInsideObject);
// Insert
if (bulk != null)
bulk.insert(newObject);
else
collection.insert(newObject);
}
}
/**
* Copies the existing collection to a new collection in the same db.
*
* Any contained documents will be overwritten.
*
* @param collection
* @param newCollectionName
* @return the new collection
* @throws IOException
*/
public DBCollection copyCollection(DBCollection collection, String newCollectionName) throws IOException {
DBCollection newCollection = getCollection(collection.getDB().getName(), newCollectionName);
truncate(newCollection);
// Available for version >= 2.6
collection.aggregate(Arrays.asList(new BasicDBObject("$out", newCollectionName)));
// Available for version < 2.6
// DBCursor cursor = collection.find();
// while (cursor.hasNext())
// newCollection.insert(cursor.next());
return newCollection;
}
/**
* Truncates the given collection.
*
* @param collection
*/
public void truncate(DBCollection collection) {
collection.remove(new BasicDBObject());
}
}
| 23.444196
| 179
| 0.692374
|
8aefbf058864907019a8f191f65010814ddb7581
| 667
|
package com.adaptris.mgmt.kubernetes.metrics;
import java.util.Properties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class KubernetesMetricsComponentTest {
private KubernetesMetricsComponent component;
@BeforeEach
public void setUp() throws Exception {
component = new KubernetesMetricsComponent();
}
@AfterEach
public void tearDown() throws Exception {
}
@Test
public void testNoImplementationsNoError() throws Exception {
component.init(new Properties());
component.start();
component.stop();
component.destroy();
}
}
| 20.212121
| 63
| 0.730135
|
1a95c5fc6c81eb3c058bf977b0e01d40dc43a906
| 948
|
package com.example.z.oldprojectgoogle.fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import static android.content.ContentValues.TAG;
/**
* Created by z on 2018/4/20.
*/
public class ApkPageFragment extends BaseFragment {
@Override
protected View showSuccessView() {
TextView textView = new TextView(getContext());
textView.setText("哈哈哈");
textView.setGravity(Gravity.CENTER);
return textView;
}
@Override
public int requestInternet() {
Log.e(TAG, "哈哈哈哈哈奥或或或或或或或或或或或或或或或或或或或" );
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return 0;
}
}
| 23.121951
| 55
| 0.584388
|
1b56f42b0876a7aec4b08eecc0483d17378a5e66
| 487
|
import java.util.ArrayList;
import java.util.List;
public class FizzBuzz_412 {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>(n);
for (int i = 1; i <= n; ++i) {
StringBuilder sb = new StringBuilder();
if (i % 3 == 0) sb.append("Fizz");
if (i % 5 == 0) sb.append("Buzz");
if (sb.length() == 0) sb.append(i);
result.add(sb.toString());
}
return result;
}
}
| 25.631579
| 51
| 0.50924
|
6b77d22618bf5a868b705a7220ef50f6ca474924
| 1,334
|
package org.conqueror.cat.analysis;
import com.typesafe.config.ConfigFactory;
import org.conqueror.cat.config.KeywordAnalyzerConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class KomoranKeywordAnalyzerTest {
private KomoranKeywordAnalyzer analyzer;
@Before
public void setUp() throws Exception {
KeywordAnalyzerConfig config = new KeywordAnalyzerConfig(ConfigFactory.parseString(
"analyzer {\n" +
" conf-file-path = \"G:\\\\workspace\\\\thunder\\\\data\\\\conf\\\\analyzer\\\\komoran.conf\"\n" +
" refine {\n" +
" remove-url = true\n" +
" remove-email = true\n" +
" }\n" +
" analysis {\n" +
" types = [\"noun\", \"number\", \"english\"]\n" +
" }\n" +
"}\n"
));
analyzer = new KomoranKeywordAnalyzer(config);
}
@Test
public void analyze() {
KeywordResult result = analyzer.analyze("");
for (String term : result.getTerms()) {
System.out.println(term);
}
System.out.println(result);
}
@After
public void tearDown() throws Exception {
analyzer.close();
}
}
| 29
| 116
| 0.550225
|
e3456d60ffeffbce0d14b88b5ecfcf04c00becab
| 1,494
|
/*
535. Encode and Decode TinyURL
TinyURL is a URL shortening service where you enter a URL such as
https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on
how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
*/
public class Codec {
List<String> urls = new ArrayList<String>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
urls.add(longUrl);
return String.valueOf(urls.size()-1);
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int index = Integer.valueOf(shortUrl);
return (index<urls.size())?urls.get(index):"";
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
public class Codec {
Map<Integer, String> map = new HashMap<>();
Random r=new Random();
int key=r.nextInt(10000);
public String encode(String longUrl) {
while(map.containsKey(key))
key= r.nextInt(10000);
map.put(key,longUrl);
return "http://tinyurl.com/"+key;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}
| 34.744186
| 162
| 0.67336
|
d7d91670c737664ff9eea66b3cc84c766f8cc6e0
| 638
|
package com.indignado.logicbricks.core;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.assets.AssetManager;
import com.indignado.logicbricks.utils.builders.LBBuilders;
/**
* @author Rubentxu.
*/
public abstract class EntityFactory {
protected String tag = this.getClass().getSimpleName();
protected LBBuilders builders;
protected AssetManager assetManager;
public EntityFactory(LBBuilders builders, AssetManager assetManager) {
this.builders = builders;
this.assetManager = assetManager;
}
public abstract void loadAssets();
public abstract Entity createEntity();
}
| 22.785714
| 74
| 0.744514
|
9840a969ef199ece3a4a2f3b0c51a9f7b0f35370
| 477
|
package com.qzing.ddd.classic.demo.domain.exchange.account.dto;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
/**
* @author yangyanze
*/
@Data
public class WithdrawalDto {
/**
* gid
*/
@NotNull
@Size(max = 32)
private String gid;
/**
* 金额
*/
@NotNull
@Min(0)
private BigDecimal amount;
}
| 16.448276
| 63
| 0.66457
|
4dac67d95622836cfd9d23f0651bf1fe29be5fb2
| 828
|
package io.mdsl.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class URITemplateHelper {
/*
public static void main(String[] args) {
String text = "Test string, with occurrences of {id}/{subid}.";
List<String> strarr = findTemplateParameters(text);
strarr.forEach(template->System.out.println("Template: " + template));
}
*/
public static List<String> findTemplateParameters(String uriSnippet) {
List<String> result = new ArrayList<String>();
String regex = "\\{\\w*\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(uriSnippet);
while(matcher.find()) {
String nextTemplate = uriSnippet.substring(matcher.start(), matcher.end());
result.add(nextTemplate);
}
return result;
}
}
| 25.875
| 78
| 0.716184
|
0904d401ec93364438de67a3fe5115e43ae8ab9a
| 8,050
|
package com.cocos2dj.module.base2d.framework.common;
import java.util.Arrays;
import java.util.Collection;
/**
* 缓存ArrayList<p>
*
* 基本功能与arrayList相同,在执行删除操作是,采用标记的方式一次性更新内容,
* 而非一个一个删除。<p><pre>
* Object temp = tempArray.beginRemove();//获取副本开始修改
* tempArray.keepElement(0);//保留元素0、1
* tempArray.keepElement(1);
* tempArray.endRemove();//保存修改
*
* </pre>
*/
public class TempArray<E> {
private Object[] elementData;
private Object[] tempElementData;
private int size;
/**获取建议TempArray信息 */
public String toSimpleString() {
StringBuilder sb = new StringBuilder();
sb.append("TempArray [size = " + size +"]").append('\n');
if(tempElementData == null) {
sb.append("no tempElementData").append('\n');
}
else {
sb.append("tempElementData : ").append('\n');
for(int i = 0; i < tempElementData.length; ++i) {
sb.append("["+i+"] ").append(tempElementData[i]).append('\n');
}
}
return sb.toString();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TempArray [size = " + size +"]").append('\n');
for(int i = 0; i < size; ++i) {
sb.append("["+i+"] ").append(elementData[i]).append('\n');
}
if(tempElementData == null) {
sb.append("no tempElementData").append('\n');
}
else {
sb.append("tempElementData : ").append('\n');
for(int i = 0; i < tempElementData.length; ++i) {
sb.append("["+i+"] ").append(tempElementData[i]).append('\n');
}
}
return sb.toString();
}
public TempArray(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public TempArray() {
this(8);
}
private boolean removing = false;
private int tempCount = 0;
public final Object[] beginRemove() {
if(!removing) {
removing = true;
tempCount = 0;
initTempElementData();
//替换缓存
final Object[] temp = elementData;
elementData = tempElementData;
tempElementData = temp;
return temp;
}
else throw new RuntimeException("TempArray正处于移除状态,无法执行beginRemove");
}
public final void keepElement(final int index) {
// tempElementData
if(removing) {
elementData[tempCount++] = tempElementData[index];
}
else throw new RuntimeException("TempArray没有处于移除状态,无法执行keepElement");
}
public final void endRemove() {
if(removing) {
removing = false;
size = tempCount;
//在这里清空数据 let gc work
for(int i = 0, n = tempElementData.length; i < n; ++i) {
tempElementData[i] = null;
}
}
else throw new RuntimeException("TempArray没有处于移除状态,无法执行endRemove");
}
/**初始化 缓存元素数据 */
final void initTempElementData() {
if(tempElementData == null) {
tempElementData = new Object[elementData.length];
}
else if(elementData.length > tempElementData.length) {
tempElementData = new Object[elementData.length];
}
}
public final void trimToSize() {
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
public void ensureCapacity(int minCapacity) {
if (minCapacity > 0)
ensureCapacityInternal(minCapacity);
}
private void ensureCapacityInternal(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
// Positional Access Operations
@SuppressWarnings("unchecked")
final E elementData(final int index) {
return (E) elementData[index];
}
public final E get(final int index) {
return elementData(index);
}
// public final E set(int index, E element) {
// E oldValue = elementData(index);
// elementData[index] = element;
// return oldValue;
// }
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
public void clear() {
// Let gc do its work
removing = false;
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
tempElementData = null;
size = 0;
}
// public static void main(String[] s) {
// TempArray ta = new TempArray();;
//
// System.out.println(ta);
//
// Object[] src = new Object[10];
// for(int i = 0; i < src.length; ++i) {
// final int n = i;
// src[i] = new Object() {
// public String toString() {
// return " "+n;
// }
// };
// }
//
// ta.add(src[3]); ta.add(src[6]); ta.add(src[9]);
// ta.add(src[1]); ta.add(src[0]); ta.add(src[2]);
// System.out.println(ta);
//
// Object[] elements = ta.beginRemove(); //读入新的object缓存,将源数据剔除
//
//// for(int i = 0; i < ta.size; ++i) {
//// if(elements[i] == null) {
//// ta.keepElement(i);
//// }
//// }
// ta.keepElement(0);
// ta.keepElement(2);
// ta.keepElement(3);
// ta.keepElement(4);
//
// ta.endRemove(); //将新的数据写入, 将temp缓存交换
// System.out.println(ta);
//
// elements = ta.beginRemove(); //读入新的object缓存,将源数据剔除
//
//// for(int i = 0; i < ta.size; ++i) {
//// if(elements[i] == null) {
//// ta.keepElement(i);
//// }
//// }
// ta.keepElement(0);
// ta.keepElement(2);
//
// ta.endRemove(); //将新的数据写入, 将temp缓存交换
// System.out.println(ta);
//
// ta.clear();
// System.out.println(ta);
// }
}
| 26.744186
| 75
| 0.561988
|
24cd409ce2e39838119bea83b6ba44f3f577c192
| 562
|
package hu.ibello.demo.pages;
import hu.ibello.core.Name;
import hu.ibello.elements.WebElement;
import hu.ibello.search.By;
import hu.ibello.search.Find;
@Name("Registration page")
public class RegistrationPage extends AbstractPage {
private static final String url = "/clients/#registration";
@Find(by = By.CSS_SELECTOR, using = "registration-lane")
private WebElement registrationLane;
@Override
public void i_am_on_the_page() {
expect_url_is_$(url);
expectations().expect(registrationLane).toBe().displayed();
}
}
| 25.545455
| 67
| 0.725979
|
b5f159648424fd576894aee2bef29e6513a8a6d2
| 13,642
|
/**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.transaction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transaction;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.kernel.DeadlockDetectedException;
import org.neo4j.kernel.impl.util.StringLogger;
import org.neo4j.kernel.info.LockInfo;
import org.neo4j.kernel.info.LockingTransaction;
import org.neo4j.kernel.info.WaitingThread;
import org.neo4j.kernel.logging.Logging;
/**
* The LockManager can lock resources for reading or writing. By doing this one
* may achieve different transaction isolation levels. A resource can for now be
* any object (but null).
* <p>
* When acquiring a lock you have to release it. Failure to do so will result in
* the resource being blocked to all other transactions. Put all locks in a try -
* finally block.
* <p>
* Multiple locks on the same resource held by the same transaction requires the
* transaction to invoke the release lock method multiple times. If a tx has
* invoked <CODE>getReadLock</CODE> on the same resource x times in a row it
* must invoke <CODE>releaseReadLock</CODE> x times to release all the locks.
* <p>
* LockManager just maps locks to resources and they do all the hard work
* together with a resource allocation graph.
*/
public class LockManagerImpl implements LockManager
{
private final Map<Object,RWLock> resourceLockMap =
new HashMap<Object,RWLock>();
private final RagManager ragManager;
public LockManagerImpl( RagManager ragManager )
{
this.ragManager = ragManager;
}
public long getDetectedDeadlockCount()
{
return ragManager.getDeadlockCount();
}
/**
* Calls {{@link #getReadLock(Object, Transaction)} with parameters
* that will make the call try to get the read lock for the transaction
* associated with the current thread.
*
* @param resource
* @throws DeadlockDetectedException
* @throws IllegalResourceException
*/
@Override
public void getReadLock( Object resource )
throws DeadlockDetectedException, IllegalResourceException
{
getReadLock( resource, null );
}
/**
* Tries to acquire read lock on <CODE>resource</CODE> for a given
* transaction. If read lock can't be acquired the transaction will wait for
* the transaction until it can acquire it. If waiting leads to dead lock a
* {@link DeadlockDetectedException} will be thrown.
*
* @param resource
* The resource
* @throws DeadlockDetectedException
* If a deadlock is detected
* @throws IllegalResourceException
*/
@Override
public void getReadLock( Object resource, Transaction tx )
throws DeadlockDetectedException, IllegalResourceException
{
if ( resource == null )
{
throw new IllegalResourceException( "Null parameter" );
}
RWLock lock = null;
synchronized ( resourceLockMap )
{
lock = resourceLockMap.get( resource );
if ( lock == null )
{
lock = new RWLock( resource, ragManager );
resourceLockMap.put( resource, lock );
}
lock.mark();
}
lock.acquireReadLock(tx);
}
/**
* Calls {{@link #getWriteLock(Object, Transaction)} with parameters
* that will make the call try to get the write lock for the transaction
* associated with the current thread.
*
* @param resource
* @throws DeadlockDetectedException
* @throws IllegalResourceException
*/
@Override
public void getWriteLock( Object resource )
throws DeadlockDetectedException, IllegalResourceException
{
getWriteLock( resource, null );
}
/**
* Tries to acquire write lock on <CODE>resource</CODE> for a given
* transaction. If write lock can't be acquired the transaction will wait
* for the lock until it can acquire it. If waiting leads to dead lock a
* {@link DeadlockDetectedException} will be thrown.
*
* @param resource
* The resource
* @throws DeadlockDetectedException
* If a deadlock is detected
* @throws IllegalResourceException
*/
@Override
public void getWriteLock( Object resource, Transaction tx )
throws DeadlockDetectedException, IllegalResourceException
{
if ( resource == null )
{
throw new IllegalResourceException( "Null parameter" );
}
RWLock lock = null;
synchronized ( resourceLockMap )
{
lock = resourceLockMap.get( resource );
if ( lock == null )
{
lock = new RWLock( resource, ragManager );
resourceLockMap.put( resource, lock );
}
lock.mark();
}
lock.acquireWriteLock(tx);
}
/**
* Releases a read lock held by the current transaction on <CODE>resource</CODE>.
* If current transaction don't have read lock a
* {@link LockNotFoundException} will be thrown.
*
* @param resource
* The resource
* @throws IllegalResourceException
* @throws LockNotFoundException
*/
@Override
public void releaseReadLock( Object resource, Transaction tx )
throws LockNotFoundException, IllegalResourceException
{
if ( resource == null )
{
throw new IllegalResourceException( "Null parameter" );
}
RWLock lock = null;
synchronized ( resourceLockMap )
{
lock = resourceLockMap.get( resource );
if ( lock == null )
{
throw new LockNotFoundException( "Lock not found for: "
+ resource + " tx:" + tx );
}
if ( !lock.isMarked() && lock.getReadCount() == 1 &&
lock.getWriteCount() == 0 &&
lock.getWaitingThreadsCount() == 0 )
{
resourceLockMap.remove( resource );
}
lock.releaseReadLock(tx);
}
}
/**
* Releases a write lock held by the current transaction on <CODE>resource</CODE>.
* If current transaction don't have read lock a
* {@link LockNotFoundException} will be thrown.
*
* @param resource
* The resource
* @throws IllegalResourceException
* @throws LockNotFoundException
*/
@Override
public void releaseWriteLock( Object resource, Transaction tx )
throws LockNotFoundException, IllegalResourceException
{
if ( resource == null )
{
throw new IllegalResourceException( "Null parameter" );
}
RWLock lock = null;
synchronized ( resourceLockMap )
{
lock = resourceLockMap.get( resource );
if ( lock == null )
{
throw new LockNotFoundException( "Lock not found for: "
+ resource + " tx:" + tx );
}
if ( !lock.isMarked() && lock.getReadCount() == 0 &&
lock.getWriteCount() == 1 &&
lock.getWaitingThreadsCount() == 0 )
{
resourceLockMap.remove( resource );
}
lock.releaseWriteLock(tx);
}
}
/**
* Utility method for debugging. Dumps info to console of txs having locks
* on resources.
*
* @param resource
*/
public void dumpLocksOnResource( Object resource, Logging logging )
{
StringLogger logger = logging.getLogger( LockManager.class );
RWLock lock = null;
synchronized ( resourceLockMap )
{
if ( !resourceLockMap.containsKey( resource ) )
{
logger.info( "No locks on " + resource );
return;
}
lock = resourceLockMap.get( resource );
}
logger.logLongMessage( "Dump locks on resource " + resource, lock );
}
public List<LockInfo> getAllLocks()
{
return eachLock( new ListAppendingVisitor() ).result;
}
public List<LockInfo> getAwaitedLocks( long minWaitTime )
{
return eachAwaitedLock( new ListAppendingVisitor(), minWaitTime ).result;
}
/**
* Visit all locks.
*
* The supplied visitor may not block.
*
* @param visitor visitor for visiting each lock.
*/
private <V extends Visitor<LockInfo>> V eachLock( V visitor )
{
synchronized ( resourceLockMap )
{
for ( RWLock lock : resourceLockMap.values() )
{
if ( visitor.visit( lock.info() ) ) break;
}
}
return visitor;
}
/**
* Visit all locks that some thread has been waiting for at least the
* supplied number of milliseconds.
*
* The supplied visitor may not block.
*
* @param visitor visitor for visiting each lock that has had a thread
* waiting at least the specified time.
* @param minWaitTime the number of milliseconds a thread should have waited
* on a lock for it to be visited.
*/
private <V extends Visitor<LockInfo>> V eachAwaitedLock( V visitor, long minWaitTime )
{
long waitStart = System.currentTimeMillis() - minWaitTime;
synchronized ( resourceLockMap )
{
for ( RWLock lock : resourceLockMap.values() )
{
if ( lock.acceptVisitorIfWaitedSinceBefore( visitor, waitStart ) ) break;
}
}
return visitor;
}
/**
* Utility method for debugging. Dumps the resource allocation graph to
* console.
*/
public void dumpRagStack( Logging logging )
{
logging.getLogger( getClass() ).logLongMessage( "RAG stack", ragManager );
}
/**
* Utility method for debugging. Dumps info about each lock to console.
*/
public void dumpAllLocks( Logging logging )
{
DumpVisitor dump = new DumpVisitor( logging );
eachLock( dump );
dump.done();
}
private static class ListAppendingVisitor implements Visitor<LockInfo>
{
private final List<LockInfo> result = new ArrayList<LockInfo>();
@Override
public boolean visit( LockInfo element )
{
result.add( element );
return false;
}
}
private static class DumpVisitor implements Visitor<LockInfo>
{
private final StringLogger logger;
DumpVisitor( Logging logging )
{
logger = logging.getLogger( LockManager.class );
}
int emptyLockCount = 0;
@Override
public boolean visit( LockInfo lock )
{
if ( lock.getWriteCount() > 0 || lock.getReadCount() > 0 )
{
dumpStack( lock );
}
else
{
if ( lock.getWaitingThreadsCount() > 0 )
{
dumpStack( lock );
}
emptyLockCount++;
}
return false;
}
private void dumpStack( LockInfo lock )
{
logger.info( "Total lock count: readCount=" + lock.getReadCount() + " writeCount="
+ lock.getWriteCount() + " for "
+ lock.getResourceType().toString( lock.getResourceId() ) );
logger.info( "Waiting list:" );
StringBuilder waitlist = new StringBuilder();
String sep = "";
for ( WaitingThread we : lock.getWaitingThreads() )
{
waitlist.append( sep ).append( "[tid=" ).append( we.getThreadId() ).append( "(" ).append(
we.getReadCount() ).append( "r," ).append( we.getWriteCount() ).append( "w )," ).append(
we.isWaitingOnWriteLock() ? "Write" : "Read" ).append( "Lock]" );
sep = ", ";
}
logger.info( waitlist.toString() );
for ( LockingTransaction tle : lock.getLockingTransactions() )
{
logger.info( "" + tle.getTransaction() + "(" + tle.getReadCount() + "r," + tle.getWriteCount()
+ "w)" );
}
}
void done()
{
if ( emptyLockCount > 0 )
{
logger.info( "There are " + emptyLockCount + " empty locks" );
}
else
{
logger.info( "There are no empty locks" );
}
}
}
}
| 32.480952
| 112
| 0.582759
|
1175497686297aa234f1d0e807fea8a99ca0acb8
| 7,051
|
package com.gutotech.narutogame.ui.adapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.gutotech.narutogame.R;
import com.gutotech.narutogame.data.firebase.StorageUtils;
import com.gutotech.narutogame.data.model.CharOn;
import com.gutotech.narutogame.data.model.Character;
import com.gutotech.narutogame.data.model.Title;
import com.gutotech.narutogame.databinding.DialogRankCharacterBinding;
import com.gutotech.narutogame.utils.DateCustom;
import java.util.ArrayList;
import java.util.List;
public class RankingNinjasAdapter extends RecyclerView.Adapter<RankingNinjasAdapter.MyViewHolder> {
private Context mContext;
private List<Character> mNinjas;
private final Title[] TITLES = Title.values();
public RankingNinjasAdapter(Context context) {
mContext = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.adapter_ninja_item, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int i) {
if (mNinjas != null) {
final Character character = mNinjas.get(i);
StorageUtils.loadDojo(mContext, holder.characterImageView, character.getNinja().getId());
holder.positionTextView.setText(mContext.getString(R.string.rank_position, i + 1));
holder.nickTextView.setText(character.getNick());
holder.levelTextView.setText(String.valueOf(character.getLevel()));
holder.scoreTextView.setText(String.valueOf(character.getScore()));
holder.nickTextView.setOnClickListener(v -> showDetails(character));
if (character.getSelectedTitle() != 0) {
holder.titleTextView.setVisibility(View.VISIBLE);
holder.titleTextView.setText(
mContext.getString(TITLES[character.getSelectedTitleIndex()].getText()));
} else {
holder.titleTextView.setVisibility(View.GONE);
}
if (character.isOnline()) {
holder.nickTextView.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.layout_on, 0, 0, 0);
} else {
holder.nickTextView.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.layout_off, 0, 0, 0);
}
holder.villageImageView.setImageResource(character.getVillage().bandanaResId);
if (i < 3) {
holder.positionTextView.setTypeface(null, Typeface.BOLD);
holder.nickTextView.setTypeface(null, Typeface.BOLD);
holder.positionTextView.setTextColor(mContext.getResources().getColor(R.color.colorYellowLight));
holder.nickTextView.setTextColor(mContext.getResources().getColor(R.color.colorYellowLight));
} else {
holder.positionTextView.setTypeface(null, Typeface.NORMAL);
holder.nickTextView.setTypeface(null, Typeface.NORMAL);
holder.positionTextView.setTextColor(mContext.getResources().getColor(R.color.colorText));
holder.nickTextView.setTextColor(mContext.getResources().getColor(android.R.color.holo_blue_light));
}
if (character.equals(CharOn.character)) {
holder.bgConstraint.setBackgroundColor(
mContext.getResources().getColor(R.color.colorLogPurple));
} else if (i % 2 == 0) {
holder.bgConstraint.setBackgroundColor(
mContext.getResources().getColor(R.color.colorItem1));
} else {
holder.bgConstraint.setBackgroundColor(
mContext.getResources().getColor(R.color.colorItem2));
}
}
}
@Override
public int getItemCount() {
return mNinjas != null ? mNinjas.size() : 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView positionTextView;
private TextView nickTextView;
private TextView titleTextView;
private TextView levelTextView;
private TextView scoreTextView;
private ImageView villageImageView;
private ImageView characterImageView;
private ConstraintLayout bgConstraint;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
positionTextView = itemView.findViewById(R.id.positionTextView);
nickTextView = itemView.findViewById(R.id.nickTextView);
titleTextView = itemView.findViewById(R.id.titleTextView);
levelTextView = itemView.findViewById(R.id.levelTextView);
scoreTextView = itemView.findViewById(R.id.scoreTextView);
villageImageView = itemView.findViewById(R.id.villageImageView);
characterImageView = itemView.findViewById(R.id.characterImageView);
bgConstraint = itemView.findViewById(R.id.bgConstraint);
}
}
public void setNinjas(List<Character> ninjas) {
mNinjas = ninjas;
notifyDataSetChanged();
}
private void showDetails(Character character) {
Dialog profileDialog = new Dialog(mContext);
DialogRankCharacterBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext),
R.layout.dialog_rank_character, null, false);
binding.setTitles(Title.values());
binding.setCharacter(character);
profileDialog.setContentView(binding.getRoot());
List<String> titles = new ArrayList<>();
for (int titleIndex : character.getTitles()) {
titles.add(mContext.getString(TITLES[titleIndex].getText()));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext,
android.R.layout.simple_spinner_item, titles);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.titlesSpinner.setAdapter(adapter);
long timestamp = character.getLastSeenInMillis();
binding.lastSeenTextView.setText(
mContext.getString(R.string.date_and_time_format,
DateCustom.getDate(timestamp), DateCustom.getTime(timestamp))
);
profileDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
profileDialog.show();
}
}
| 40.994186
| 116
| 0.677634
|
880b10fb591e744c776cd59647aa08e178a1daf7
| 448
|
package com.jeffdisher.membrane.store.connection;
import java.io.Closeable;
import com.jeffdisher.laminar.types.CommitInfo;
import com.jeffdisher.laminar.types.TopicName;
public interface IWritingConnection extends Closeable {
CommitInfo synchronousCreateTopic(TopicName name, byte[] code, byte[] arguments);
CommitInfo synchronousPut(TopicName name, byte[] key, byte[] value);
CommitInfo synchronousDelete(TopicName name, byte[] key);
}
| 26.352941
| 82
| 0.803571
|
8f4b5221265cf9670086b9f0726296d043e70492
| 304
|
package de.sebb767.pvs.helper;
/**
* Created by proj on 3/23/17.
*/
public class ThreadCountHelper {
public static int getCpuCount()
{
return Runtime.getRuntime().availableProcessors();
}
public static int getIdealThreadCount()
{
return getCpuCount() * 2;
}
}
| 17.882353
| 58
| 0.634868
|
2889a68c7c40c52b8fc8d97909f4f9a324fe4135
| 1,242
|
/*
* Copyright (C) 2008-2013 VMware, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wavemaker.tools.common;
import com.wavemaker.common.util.SpringUtils;
/**
* Entry point for bootstrapping the system. Knows about other Bootstrap classes in the system.
*
* @author Simon Toens
*/
public class Bootstrap {
private static boolean hasRun = false;
public synchronized static void main(String[] args) {
if (hasRun) {
return;
}
SpringUtils.initSpringConfig();
com.wavemaker.tools.data.Bootstrap.main(args);
com.wavemaker.tools.ws.Bootstrap.main(args);
hasRun = true;
}
private Bootstrap() {
}
}
| 27
| 95
| 0.689211
|
2413d45141c608c0d3436e758e7af38361fc5083
| 49,721
|
// ______________________________________________________
// Generated by sql2java - https://github.com/10km/sql2java-2-6-7 (custom branch)
// modified by guyadong from
// sql2java original version https://sourceforge.net/projects/sql2java/
// JDBC driver used at code generation time: com.mysql.jdbc.Driver
// template: manager.java.vm
// ______________________________________________________
package net.gdface.facelog.db.mysql;
import java.util.concurrent.Callable;
import net.gdface.facelog.db.Constant;
import net.gdface.facelog.db.DeviceBean;
import net.gdface.facelog.db.IBeanConverter;
import net.gdface.facelog.db.IDbConverter;
import net.gdface.facelog.db.TableManager;
import net.gdface.facelog.db.IDeviceManager;
import net.gdface.facelog.db.ImageBean;
import net.gdface.facelog.db.LogBean;
import net.gdface.facelog.db.DeviceGroupBean;
import net.gdface.facelog.db.TableListener;
import net.gdface.facelog.db.exception.RuntimeDaoException;
import net.gdface.facelog.db.exception.ObjectRetrievalException;
import net.gdface.facelog.dborm.exception.DaoException;
/**
* Handles database calls (save, load, count, etc...) for the fl_device table.<br>
* all {@link DaoException} be wrapped as {@link RuntimeDaoException} to throw.<br>
* Remarks: 前端设备基本信息<br>
* @author guyadong
*/
public class DeviceManager extends TableManager.BaseAdapter<DeviceBean> implements IDeviceManager
{
private net.gdface.facelog.dborm.device.FlDeviceManager nativeManager = net.gdface.facelog.dborm.device.FlDeviceManager.getInstance();
private IDbConverter<
net.gdface.facelog.dborm.device.FlDeviceBean,
net.gdface.facelog.dborm.device.FlDeviceGroupBean,
net.gdface.facelog.dborm.face.FlFaceBean,
net.gdface.facelog.dborm.face.FlFeatureBean,
net.gdface.facelog.dborm.image.FlImageBean,
net.gdface.facelog.dborm.log.FlLogBean,
net.gdface.facelog.dborm.permit.FlPermitBean,
net.gdface.facelog.dborm.person.FlPersonBean,
net.gdface.facelog.dborm.person.FlPersonGroupBean,
net.gdface.facelog.dborm.image.FlStoreBean,
net.gdface.facelog.dborm.log.FlLogLightBean> dbConverter = DbConverter.INSTANCE;
private IBeanConverter<DeviceBean,net.gdface.facelog.dborm.device.FlDeviceBean> beanConverter = dbConverter.getDeviceBeanConverter();
private static DeviceManager singleton = new DeviceManager();
protected DeviceManager(){}
protected ImageManager instanceOfImageManager(){
return ImageManager.getInstance();
}
protected LogManager instanceOfLogManager(){
return LogManager.getInstance();
}
protected DeviceGroupManager instanceOfDeviceGroupManager(){
return DeviceGroupManager.getInstance();
}
@Override
public String getTableName() {
return this.nativeManager.getTableName();
}
@Override
public String getFields() {
return this.nativeManager.getFields();
}
@Override
public String getFullFields() {
return this.nativeManager.getFullFields();
}
@Override
public String[] getPrimarykeyNames() {
return this.nativeManager.getPrimarykeyNames();
}
@Override
public int columnIDOf(String column){
return DeviceBean.columnIDOf(column);
}
@Override
public Class<?> typeOf(int columnId){
return DeviceBean.typeOf(columnId);
}
/**
* Get the {@link DeviceManager} singleton.
*
* @return {@link DeviceManager}
*/
public static DeviceManager getInstance()
{
return singleton;
}
@Override
protected Class<DeviceBean> beanType(){
return DeviceBean.class;
}
@Override
protected String columnNameOf(int columnId){
return DeviceBean.columnNameOf(columnId);
}
//////////////////////////////////////
// PRIMARY KEY METHODS
//////////////////////////////////////
//1 override IDeviceManager
@Override
public DeviceBean loadByPrimaryKey(Integer id)
{
try{
return loadByPrimaryKeyChecked(id);
}catch(ObjectRetrievalException e){
// not found
return null;
}
}
//1.1 override IDeviceManager
@Override
public DeviceBean loadByPrimaryKeyChecked(Integer id) throws ObjectRetrievalException
{
try{
return this.beanConverter.fromRight(nativeManager.loadByPrimaryKeyChecked(id));
}catch(net.gdface.facelog.dborm.exception.ObjectRetrievalException e){
throw new ObjectRetrievalException();
}catch(DaoException e){
throw new RuntimeDaoException(e);
}
}
//1.2
@Override
public DeviceBean loadByPrimaryKey(DeviceBean bean)
{
return bean==null?null:loadByPrimaryKey(bean.getId());
}
//1.2.2
@Override
public DeviceBean loadByPrimaryKeyChecked(DeviceBean bean) throws ObjectRetrievalException
{
if(null == bean){
throw new NullPointerException();
}
return loadByPrimaryKeyChecked(bean.getId());
}
//1.3
@Override
public DeviceBean loadByPrimaryKey(Object ...keys){
try{
return loadByPrimaryKeyChecked(keys);
}catch(ObjectRetrievalException e){
// not found
return null;
}
}
//1.3.2
@Override
public DeviceBean loadByPrimaryKeyChecked(Object ...keys) throws ObjectRetrievalException{
if(null == keys){
throw new NullPointerException();
}
if(keys.length != FL_DEVICE_PK_COUNT){
throw new IllegalArgumentException("argument number mismatch with primary key number");
}
if(! (keys[0] instanceof Integer)){
throw new IllegalArgumentException("invalid type for the No.1 argument,expected type:Integer");
}
return loadByPrimaryKeyChecked((Integer)keys[0]);
}
//1.4 override IDeviceManager
@Override
public boolean existsPrimaryKey(Integer id)
{
try{
return nativeManager.existsPrimaryKey(id);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//1.6
@Override
public boolean existsByPrimaryKey(DeviceBean bean)
{
return null == bean ? false : existsPrimaryKey(bean.getId());
}
//1.7
@Override
public DeviceBean checkDuplicate(DeviceBean bean)throws ObjectRetrievalException{
if(null != bean){
checkDuplicate(bean.getId());
}
return bean;
}
//1.4.1 override IDeviceManager
@Override
public Integer checkDuplicate(Integer id)throws ObjectRetrievalException{
try{
return this.nativeManager.checkDuplicate(id);
}catch(net.gdface.facelog.dborm.exception.ObjectRetrievalException e){
throw new ObjectRetrievalException(e);
}catch(DaoException e){
throw new RuntimeDaoException(e);
}
}
//1.8 override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByPrimaryKey(int... keys){
if(null == keys){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(keys.length);
for(int i = 0 ;i< keys.length;++i){
list.add(loadByPrimaryKey(keys[i]));
}
return list;
}
//1.9 override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByPrimaryKey(java.util.Collection<Integer> keys){
if(null == keys ){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(keys.size());
if(keys instanceof java.util.List){
for(Integer key: keys){
list.add(loadByPrimaryKey(key));
}
}else{
DeviceBean bean;
for(Integer key: keys){
if(null != (bean = loadByPrimaryKey(key))){
list.add(bean);
}
}
}
return list;
}
//2 override IDeviceManager
@Override
public int deleteByPrimaryKey(Integer id)
{
try
{
return nativeManager.deleteByPrimaryKey(id);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//2
@Override
public int delete(DeviceBean bean){
try
{
return nativeManager.delete(this.beanConverter.toRight(bean));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//2.1
@Override
public int deleteByPrimaryKey(Object ...keys){
if(null == keys){
throw new NullPointerException();
}
if(keys.length != FL_DEVICE_PK_COUNT){
throw new IllegalArgumentException("argument number mismatch with primary key number");
}
if(! (keys[0] instanceof Integer)){
throw new IllegalArgumentException("invalid type for the No.1 argument,expected type:Integer");
}
return deleteByPrimaryKey((Integer)keys[0]);
}
//2.2 override IDeviceManager
@Override
public int deleteByPrimaryKey(int... keys){
int count = 0;
if(null != keys){
for(int key:keys){
count += deleteByPrimaryKey(key);
}
}
return count;
}
//2.3 override IDeviceManager
@Override
public int deleteByPrimaryKey(java.util.Collection<Integer> keys){
int count = 0;
if(null != keys){
for(Integer key :keys){
count += deleteByPrimaryKey(key);
}
}
return count;
}
//2.4 override IDeviceManager
@Override
public int delete(DeviceBean... beans){
int count = 0;
if(null != beans){
for(DeviceBean bean :beans){
count += delete(bean);
}
}
return count;
}
//2.5 override IDeviceManager
@Override
public int delete(java.util.Collection<DeviceBean> beans){
int count = 0;
if(null != beans){
for(DeviceBean bean :beans){
count += delete(bean);
}
}
return count;
}
//////////////////////////////////////
// IMPORT KEY GENERIC METHOD
//////////////////////////////////////
private static final Class<?>[] IMPORTED_BEAN_TYPES = new Class<?>[]{ImageBean.class,LogBean.class};
/**
* @see #getImportedBeansAsList(DeviceBean,int)
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>> T[] getImportedBeans(DeviceBean bean, int ikIndex){
return getImportedBeansAsList(bean, ikIndex).toArray((T[])java.lang.reflect.Array.newInstance(IMPORTED_BEAN_TYPES[ikIndex],0));
}
/**
* Retrieves imported T objects by ikIndex.<br>
* @param <T>
* <ul>
* <li> {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID} TO {@link ImageBean}</li>
* <li> {@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID} TO {@link LogBean}</li>
* </ul>
* @param bean the {@link DeviceBean} object to use
* @param ikIndex valid values: {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID},{@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID}
* @return the associated T beans or {@code null} if {@code bean} is {@code null}
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>> java.util.List<T> getImportedBeansAsList(DeviceBean bean,int ikIndex){
switch(ikIndex){
case FL_DEVICE_IK_FL_IMAGE_DEVICE_ID:
return (java.util.List<T>)this.getImageBeansByDeviceIdAsList(bean);
case FL_DEVICE_IK_FL_LOG_DEVICE_ID:
return (java.util.List<T>)this.getLogBeansByDeviceIdAsList(bean);
default:
throw new IllegalArgumentException(String.format("invalid ikIndex %d", ikIndex));
}
}
/**
* Set the T objects as imported beans of bean object by ikIndex.<br>
* @param <T>
*
* <ul>
* <li> {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID} TO {@link ImageBean}</li>
* <li> {@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID} TO {@link LogBean}</li>
* </ul>
* @param bean the {@link DeviceBean} object to use
* @param importedBeans the FlLogBean array to associate to the {@link DeviceBean}
* @param ikIndex valid values: {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID},{@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID}
* @return importedBeans always
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>> T[] setImportedBeans(DeviceBean bean,T[] importedBeans,int ikIndex){
switch(ikIndex){
case FL_DEVICE_IK_FL_IMAGE_DEVICE_ID:
return (T[])setImageBeansByDeviceId(bean,(ImageBean[])importedBeans);
case FL_DEVICE_IK_FL_LOG_DEVICE_ID:
return (T[])setLogBeansByDeviceId(bean,(LogBean[])importedBeans);
default:
throw new IllegalArgumentException(String.format("invalid ikIndex %d", ikIndex));
}
}
/**
* Set the importedBeans associates to the bean by ikIndex<br>
* @param <T>
* <ul>
* <li> {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID} TO {@link ImageBean}</li>
* <li> {@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID} TO {@link LogBean}</li>
* </ul>
* @param bean the {@link DeviceBean} object to use
* @param importedBeans the T object to associate to the {@link DeviceBean}
* @param ikIndex valid values: {@link Constant#FL_DEVICE_IK_FL_IMAGE_DEVICE_ID},{@link Constant#FL_DEVICE_IK_FL_LOG_DEVICE_ID}
* @return importedBeans always
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>,C extends java.util.Collection<T>> C setImportedBeans(DeviceBean bean,C importedBeans,int ikIndex){
switch(ikIndex){
case FL_DEVICE_IK_FL_IMAGE_DEVICE_ID:
return (C)setImageBeansByDeviceId(bean,(java.util.Collection<ImageBean>)importedBeans);
case FL_DEVICE_IK_FL_LOG_DEVICE_ID:
return (C)setLogBeansByDeviceId(bean,(java.util.Collection<LogBean>)importedBeans);
default:
throw new IllegalArgumentException(String.format("invalid ikIndex %d", ikIndex));
}
}
//////////////////////////////////////
// GET/SET IMPORTED KEY BEAN METHOD
//////////////////////////////////////
//3.1 GET IMPORTED override IDeviceManager
@Override
public ImageBean[] getImageBeansByDeviceId(DeviceBean bean)
{
return this.getImageBeansByDeviceIdAsList(bean).toArray(new ImageBean[0]);
}
//3.1.2 GET IMPORTED override IDeviceManager
@Override
public ImageBean[] getImageBeansByDeviceId(Integer idOfDevice)
{
DeviceBean bean = new DeviceBean();
bean.setId(idOfDevice);
return getImageBeansByDeviceId(bean);
}
//3.2 GET IMPORTED override IDeviceManager
@Override
public java.util.List<ImageBean> getImageBeansByDeviceIdAsList(DeviceBean bean)
{
return getImageBeansByDeviceIdAsList(bean,1,-1);
}
//3.2.2 GET IMPORTED override IDeviceManager
@Override
public java.util.List<ImageBean> getImageBeansByDeviceIdAsList(Integer idOfDevice)
{
DeviceBean bean = new DeviceBean();
bean.setId(idOfDevice);
return getImageBeansByDeviceIdAsList(bean);
}
//3.2.3 DELETE IMPORTED override IDeviceManager
@Override
public int deleteImageBeansByDeviceId(Integer idOfDevice)
{
java.util.List<ImageBean> list =getImageBeansByDeviceIdAsList(idOfDevice);
return instanceOfImageManager().delete(list);
}
//3.2.4 GET IMPORTED override IDeviceManager
@Override
public java.util.List<ImageBean> getImageBeansByDeviceIdAsList(DeviceBean bean,int startRow, int numRows)
{
try {
return this.dbConverter.getImageBeanConverter().fromRight(nativeManager.getImageBeansByDeviceIdAsList( this.beanConverter.toRight(bean),startRow,numRows));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//3.3 SET IMPORTED override IDeviceManager
@Override
public ImageBean[] setImageBeansByDeviceId(DeviceBean bean , ImageBean[] importedBeans)
{
if(null != importedBeans){
for( ImageBean importBean : importedBeans ){
instanceOfImageManager().setReferencedByDeviceId(importBean , bean);
}
}
return importedBeans;
}
//3.4 SET IMPORTED override IDeviceManager
@Override
public <C extends java.util.Collection<ImageBean>> C setImageBeansByDeviceId(DeviceBean bean , C importedBeans)
{
if(null != importedBeans){
for( ImageBean importBean : importedBeans ){
instanceOfImageManager().setReferencedByDeviceId(importBean , bean);
}
}
return importedBeans;
}
//3.1 GET IMPORTED override IDeviceManager
@Override
public LogBean[] getLogBeansByDeviceId(DeviceBean bean)
{
return this.getLogBeansByDeviceIdAsList(bean).toArray(new LogBean[0]);
}
//3.1.2 GET IMPORTED override IDeviceManager
@Override
public LogBean[] getLogBeansByDeviceId(Integer idOfDevice)
{
DeviceBean bean = new DeviceBean();
bean.setId(idOfDevice);
return getLogBeansByDeviceId(bean);
}
//3.2 GET IMPORTED override IDeviceManager
@Override
public java.util.List<LogBean> getLogBeansByDeviceIdAsList(DeviceBean bean)
{
return getLogBeansByDeviceIdAsList(bean,1,-1);
}
//3.2.2 GET IMPORTED override IDeviceManager
@Override
public java.util.List<LogBean> getLogBeansByDeviceIdAsList(Integer idOfDevice)
{
DeviceBean bean = new DeviceBean();
bean.setId(idOfDevice);
return getLogBeansByDeviceIdAsList(bean);
}
//3.2.3 DELETE IMPORTED override IDeviceManager
@Override
public int deleteLogBeansByDeviceId(Integer idOfDevice)
{
java.util.List<LogBean> list =getLogBeansByDeviceIdAsList(idOfDevice);
return instanceOfLogManager().delete(list);
}
//3.2.4 GET IMPORTED override IDeviceManager
@Override
public java.util.List<LogBean> getLogBeansByDeviceIdAsList(DeviceBean bean,int startRow, int numRows)
{
try {
return this.dbConverter.getLogBeanConverter().fromRight(nativeManager.getLogBeansByDeviceIdAsList( this.beanConverter.toRight(bean),startRow,numRows));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//3.3 SET IMPORTED override IDeviceManager
@Override
public LogBean[] setLogBeansByDeviceId(DeviceBean bean , LogBean[] importedBeans)
{
if(null != importedBeans){
for( LogBean importBean : importedBeans ){
instanceOfLogManager().setReferencedByDeviceId(importBean , bean);
}
}
return importedBeans;
}
//3.4 SET IMPORTED override IDeviceManager
@Override
public <C extends java.util.Collection<LogBean>> C setLogBeansByDeviceId(DeviceBean bean , C importedBeans)
{
if(null != importedBeans){
for( LogBean importBean : importedBeans ){
instanceOfLogManager().setReferencedByDeviceId(importBean , bean);
}
}
return importedBeans;
}
//3.5 SYNC SAVE override IDeviceManager
@Override
public DeviceBean save(DeviceBean bean
, DeviceGroupBean refDevicegroupByGroupId
, ImageBean[] impImageByDeviceId , LogBean[] impLogByDeviceId )
{
if(null == bean){
return null;
}
if(null != refDevicegroupByGroupId){
this.setReferencedByGroupId(bean,refDevicegroupByGroupId);
}
bean = this.save( bean );
if(null != impImageByDeviceId){
this.setImageBeansByDeviceId(bean,impImageByDeviceId);
instanceOfImageManager().save( impImageByDeviceId );
}
if(null != impLogByDeviceId){
this.setLogBeansByDeviceId(bean,impLogByDeviceId);
instanceOfLogManager().save( impLogByDeviceId );
}
return bean;
}
//3.6 SYNC SAVE AS TRANSACTION override IDeviceManager
@Override
public DeviceBean saveAsTransaction(final DeviceBean bean
,final DeviceGroupBean refDevicegroupByGroupId
,final ImageBean[] impImageByDeviceId ,final LogBean[] impLogByDeviceId )
{
return this.runAsTransaction(new Callable<DeviceBean>(){
@Override
public DeviceBean call() throws Exception {
return save(bean , refDevicegroupByGroupId , impImageByDeviceId , impLogByDeviceId );
}});
}
//3.7 SYNC SAVE override IDeviceManager
@Override
public DeviceBean save(DeviceBean bean
, DeviceGroupBean refDevicegroupByGroupId
, java.util.Collection<ImageBean> impImageByDeviceId , java.util.Collection<LogBean> impLogByDeviceId )
{
if(null == bean){
return null;
}
if(null != refDevicegroupByGroupId){
this.setReferencedByGroupId(bean,refDevicegroupByGroupId);
}
bean = this.save( bean );
if(null != impImageByDeviceId){
this.setImageBeansByDeviceId(bean,impImageByDeviceId);
instanceOfImageManager().save( impImageByDeviceId );
}
if(null != impLogByDeviceId){
this.setLogBeansByDeviceId(bean,impLogByDeviceId);
instanceOfLogManager().save( impLogByDeviceId );
}
return bean;
}
//3.8 SYNC SAVE AS TRANSACTION override IDeviceManager
@Override
public DeviceBean saveAsTransaction(final DeviceBean bean
,final DeviceGroupBean refDevicegroupByGroupId
,final java.util.Collection<ImageBean> impImageByDeviceId ,final java.util.Collection<LogBean> impLogByDeviceId )
{
return this.runAsTransaction(new Callable<DeviceBean>(){
@Override
public DeviceBean call() throws Exception {
return save(bean , refDevicegroupByGroupId , impImageByDeviceId , impLogByDeviceId );
}});
}
private static final int SYNC_SAVE_ARG_LEN = 3;
private static final int SYNC_SAVE_ARG_0 = 0;
private static final int SYNC_SAVE_ARG_1 = 1;
private static final int SYNC_SAVE_ARG_2 = 2;
//3.9 SYNC SAVE
/**
* Save the {@link DeviceBean} bean and referenced beans and imported beans into the database.
*
* @param bean the {@link DeviceBean} bean to be saved
* @param inputs referenced beans or imported beans<br>
* see also {@link #save(DeviceBean , DeviceGroupBean , ImageBean[] , LogBean[] )}
* @return the inserted or updated {@link DeviceBean} bean
*/
@Override
public DeviceBean save(DeviceBean bean,Object ...inputs)
{
if(null == inputs){
return save(bean);
}
if(inputs.length > SYNC_SAVE_ARG_LEN){
throw new IllegalArgumentException("too many dynamic arguments,max dynamic arguments number: 3");
}
Object[] args = new Object[SYNC_SAVE_ARG_LEN];
System.arraycopy(inputs, 0, args, 0, inputs.length);
if( null != args[SYNC_SAVE_ARG_0] && !(args[SYNC_SAVE_ARG_0] instanceof DeviceGroupBean)){
throw new IllegalArgumentException("invalid type for the No.1 dynamic argument,expected type:DeviceGroupBean");
}
if( null != args[SYNC_SAVE_ARG_1] && !(args[SYNC_SAVE_ARG_1] instanceof ImageBean[])){
throw new IllegalArgumentException("invalid type for the No.2 argument,expected type:ImageBean[]");
}
if( null != args[SYNC_SAVE_ARG_2] && !(args[SYNC_SAVE_ARG_2] instanceof LogBean[])){
throw new IllegalArgumentException("invalid type for the No.3 argument,expected type:LogBean[]");
}
return save(bean,
(DeviceGroupBean)args[SYNC_SAVE_ARG_0],
(ImageBean[])args[SYNC_SAVE_ARG_1],
(LogBean[])args[SYNC_SAVE_ARG_2]);
}
//3.10 SYNC SAVE
/**
* Save the {@link DeviceBean} bean and referenced beans and imported beans into the database.
*
* @param bean the {@link DeviceBean} bean to be saved
* @param inputs referenced beans or imported beans<br>
* see also {@link #save(DeviceBean , DeviceGroupBean , java.util.Collection , java.util.Collection )}
* @return the inserted or updated {@link DeviceBean} bean
*/
@SuppressWarnings("unchecked")
@Override
public DeviceBean saveCollection(DeviceBean bean,Object ...inputs)
{
if(null == inputs){
return save(bean);
}
if(inputs.length > SYNC_SAVE_ARG_LEN){
throw new IllegalArgumentException("too many dynamic arguments,max dynamic arguments number: 3");
}
Object[] args = new Object[SYNC_SAVE_ARG_LEN];
System.arraycopy(inputs, 0, args, 0, inputs.length);
if( null != args[SYNC_SAVE_ARG_0] && !(args[SYNC_SAVE_ARG_0] instanceof DeviceGroupBean)){
throw new IllegalArgumentException("invalid type for the No.1 dynamic argument,expected type:DeviceGroupBean");
}
if( null != args[SYNC_SAVE_ARG_1] && !(args[SYNC_SAVE_ARG_1] instanceof java.util.Collection)){
throw new IllegalArgumentException("invalid type for the No.2 argument,expected type:java.util.Collection<ImageBean>");
}
if( null != args[SYNC_SAVE_ARG_2] && !(args[SYNC_SAVE_ARG_2] instanceof java.util.Collection)){
throw new IllegalArgumentException("invalid type for the No.3 argument,expected type:java.util.Collection<LogBean>");
}
return save(bean,
(DeviceGroupBean)args[SYNC_SAVE_ARG_0],
(java.util.Collection<ImageBean>)args[SYNC_SAVE_ARG_1],
(java.util.Collection<LogBean>)args[SYNC_SAVE_ARG_2]);
}
//////////////////////////////////////
// FOREIGN KEY GENERIC METHOD
//////////////////////////////////////
/**
* Retrieves the bean object referenced by fkIndex.<br>
* @param <T>
* <ul>
* <li> {@link Constant#FL_DEVICE_FK_GROUP_ID} TO {@link DeviceGroupBean}</li>
* </ul>
* @param bean the {@link DeviceBean} object to use
* @param fkIndex valid values: <br>
* {@link Constant#FL_DEVICE_FK_GROUP_ID}
* @return the associated T bean or {@code null} if {@code bean} or {@code beanToSet} is {@code null}
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>> T getReferencedBean(DeviceBean bean,int fkIndex){
switch(fkIndex){
case FL_DEVICE_FK_GROUP_ID:
return (T)this.getReferencedByGroupId(bean);
default:
throw new IllegalArgumentException(String.format("invalid fkIndex %d", fkIndex));
}
}
/**
* Associates the {@link DeviceBean} object to the bean object by fkIndex field.<br>
*
* @param <T> see also {@link #getReferencedBean(DeviceBean,int)}
* @param bean the {@link DeviceBean} object to use
* @param beanToSet the T object to associate to the {@link DeviceBean}
* @param fkIndex valid values: see also {@link #getReferencedBean(DeviceBean,int)}
* @return always beanToSet saved
*/
@SuppressWarnings("unchecked")
@Override
public <T extends net.gdface.facelog.db.BaseBean<T>> T setReferencedBean(DeviceBean bean,T beanToSet,int fkIndex){
switch(fkIndex){
case FL_DEVICE_FK_GROUP_ID:
return (T)this.setReferencedByGroupId(bean, (DeviceGroupBean)beanToSet);
default:
throw new IllegalArgumentException(String.format("invalid fkIndex %d", fkIndex));
}
}
//////////////////////////////////////
// GET/SET FOREIGN KEY BEAN METHOD
//////////////////////////////////////
//5.1 GET REFERENCED VALUE override IDeviceManager
@Override
public DeviceGroupBean getReferencedByGroupId(DeviceBean bean)
{
if(null == bean){
return null;
}
bean.setReferencedByGroupId(instanceOfDeviceGroupManager().loadByPrimaryKey(bean.getGroupId()));
return bean.getReferencedByGroupId();
}
//5.2 SET REFERENCED override IDeviceManager
@Override
public DeviceGroupBean setReferencedByGroupId(DeviceBean bean, DeviceGroupBean beanToSet)
{
try{
net.gdface.facelog.dborm.device.FlDeviceBean nativeBean = this.beanConverter.toRight(bean);
IBeanConverter<DeviceGroupBean,net.gdface.facelog.dborm.device.FlDeviceGroupBean> foreignConverter = this.dbConverter.getDeviceGroupBeanConverter();
net.gdface.facelog.dborm.device.FlDeviceGroupBean foreignNativeBean = foreignConverter.toRight(beanToSet);
this.nativeManager.setReferencedByGroupId(nativeBean,foreignNativeBean);
this.beanConverter.fromRight(bean, nativeBean);
foreignConverter.fromRight(beanToSet,foreignNativeBean);
return beanToSet;
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//////////////////////////////////////
// SQL 'WHERE' METHOD
//////////////////////////////////////
//11
@Override
public int deleteByWhere(String where)
{
try{
return this.nativeManager.deleteByWhere(where);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//_____________________________________________________________________
//
// SAVE
//_____________________________________________________________________
//13
@Override
protected DeviceBean insert(DeviceBean bean)
{
try{
return this.beanConverter.fromRight(bean,this.nativeManager.insert(this.beanConverter.toRight(bean)));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//14
@Override
protected DeviceBean update(DeviceBean bean)
{
try{
return this.beanConverter.fromRight(bean,this.nativeManager.update(this.beanConverter.toRight(bean)));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//_____________________________________________________________________
//
// USING TEMPLATE
//_____________________________________________________________________
//18
@Override
public DeviceBean loadUniqueUsingTemplate(DeviceBean bean)
{
try{
return this.beanConverter.fromRight(this.nativeManager.loadUniqueUsingTemplate(this.beanConverter.toRight(bean)));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//18-1
@Override
public DeviceBean loadUniqueUsingTemplateChecked(DeviceBean bean) throws ObjectRetrievalException
{
try{
return this.beanConverter.fromRight(this.nativeManager.loadUniqueUsingTemplateChecked(this.beanConverter.toRight(bean)));
}
catch(net.gdface.facelog.dborm.exception.ObjectRetrievalException e)
{
throw new ObjectRetrievalException();
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//20-5
@Override
public int loadUsingTemplate(DeviceBean bean, int[] fieldList, int startRow, int numRows,int searchType, Action<DeviceBean> action)
{
try {
return this.nativeManager.loadUsingTemplate(this.beanConverter.toRight(bean),fieldList,startRow,numRows,searchType,this.toNative(action));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//21
@Override
public int deleteUsingTemplate(DeviceBean bean)
{
try{
return this.nativeManager.deleteUsingTemplate(this.beanConverter.toRight(bean));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//_____________________________________________________________________
//
// USING INDICES
//_____________________________________________________________________
// override IDeviceManager
@Override
public DeviceBean loadByIndexMac(String mac){
try{
return loadByIndexMacChecked(mac);
}catch(ObjectRetrievalException e){
return null;
}
}
// override IDeviceManager
@Override
public DeviceBean loadByIndexMacChecked(String mac)throws ObjectRetrievalException{
if(null == mac){
throw new ObjectRetrievalException(new NullPointerException());
}
DeviceBean bean = new DeviceBean();
bean.setMac(mac);
return loadUniqueUsingTemplateChecked(bean);
}
// override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByIndexMac(String... indexs)
{
if(null == indexs){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(indexs.length);
for(int i = 0 ;i< indexs.length;++i){
list.add(loadByIndexMac(indexs[i]));
}
return list;
}
// override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByIndexMac(java.util.Collection<String> indexs)
{
if(null == indexs ){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(indexs.size());
if(indexs instanceof java.util.List){
for(String key: indexs){
list.add(loadByIndexMac(key));
}
}else{
DeviceBean bean;
for(String key: indexs){
if(null != (bean = loadByIndexMac(key))){
list.add(bean);
}
}
}
return list;
}
// override IDeviceManager
@Override
public int deleteByIndexMac(String... indexs)
{
int count = 0;
if(null != indexs){
for(String index : indexs){
count += deleteByIndexMac(index);
}
}
return count;
}
// override IDeviceManager
@Override
public int deleteByIndexMac(java.util.Collection<String> indexs)
{
int count = 0;
if(null != indexs){
for(String index : indexs){
count += deleteByIndexMac(index);
}
}
return count;
}
// override IDeviceManager
@Override
public int deleteByIndexMac(String mac)
{
try{
return this.nativeManager.deleteByIndexMac(mac);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
// override IDeviceManager
@Override
public DeviceBean loadByIndexSerialNo(String serialNo){
try{
return loadByIndexSerialNoChecked(serialNo);
}catch(ObjectRetrievalException e){
return null;
}
}
// override IDeviceManager
@Override
public DeviceBean loadByIndexSerialNoChecked(String serialNo)throws ObjectRetrievalException{
if(null == serialNo){
throw new ObjectRetrievalException(new NullPointerException());
}
DeviceBean bean = new DeviceBean();
bean.setSerialNo(serialNo);
return loadUniqueUsingTemplateChecked(bean);
}
// override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByIndexSerialNo(String... indexs)
{
if(null == indexs){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(indexs.length);
for(int i = 0 ;i< indexs.length;++i){
list.add(loadByIndexSerialNo(indexs[i]));
}
return list;
}
// override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByIndexSerialNo(java.util.Collection<String> indexs)
{
if(null == indexs ){
return new java.util.ArrayList<DeviceBean>();
}
java.util.ArrayList<DeviceBean> list = new java.util.ArrayList<DeviceBean>(indexs.size());
if(indexs instanceof java.util.List){
for(String key: indexs){
list.add(loadByIndexSerialNo(key));
}
}else{
DeviceBean bean;
for(String key: indexs){
if(null != (bean = loadByIndexSerialNo(key))){
list.add(bean);
}
}
}
return list;
}
// override IDeviceManager
@Override
public int deleteByIndexSerialNo(String... indexs)
{
int count = 0;
if(null != indexs){
for(String index : indexs){
count += deleteByIndexSerialNo(index);
}
}
return count;
}
// override IDeviceManager
@Override
public int deleteByIndexSerialNo(java.util.Collection<String> indexs)
{
int count = 0;
if(null != indexs){
for(String index : indexs){
count += deleteByIndexSerialNo(index);
}
}
return count;
}
// override IDeviceManager
@Override
public int deleteByIndexSerialNo(String serialNo)
{
try{
return this.nativeManager.deleteByIndexSerialNo(serialNo);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
// override IDeviceManager
@Override
public DeviceBean[] loadByIndexGroupId(Integer groupId)
{
return this.loadByIndexGroupIdAsList(groupId).toArray(new DeviceBean[0]);
}
// override IDeviceManager
@Override
public java.util.List<DeviceBean> loadByIndexGroupIdAsList(Integer groupId)
{
try{
return this.beanConverter.fromRight(this.nativeManager.loadByIndexGroupIdAsList(groupId));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
// override IDeviceManager
@Override
public int deleteByIndexGroupId(Integer groupId)
{
try{
return this.nativeManager.deleteByIndexGroupId(groupId);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
/**
* Retrieves a list of DeviceBean using the index specified by keyIndex.
* @param keyIndex valid values: <br>
* {@link Constant#FL_DEVICE_INDEX_MAC},{@link Constant#FL_DEVICE_INDEX_SERIAL_NO},{@link Constant#FL_DEVICE_INDEX_GROUP_ID}
* @param keys key values of index
* @return a list of DeviceBean
*/
@Override
public java.util.List<DeviceBean> loadByIndexAsList(int keyIndex,Object ...keys)
{
try{
return this.beanConverter.fromRight(this.nativeManager.loadByIndexAsList(keyIndex,keys));
}catch(DaoException e){
throw new RuntimeDaoException(e);
}
}
/**
* Deletes rows using key.
* @param keyIndex valid values: <br>
* {@link Constant#FL_DEVICE_INDEX_MAC},{@link Constant#FL_DEVICE_INDEX_SERIAL_NO},{@link Constant#FL_DEVICE_INDEX_GROUP_ID}
* @param keys key values of index
* @return the number of deleted objects
*/
@Override
public int deleteByIndex(int keyIndex,Object ...keys)
{
try{
return this.nativeManager.deleteByIndex(keyIndex,keys);
}catch(DaoException e){
throw new RuntimeDaoException(e);
}
}
//_____________________________________________________________________
//
// COUNT
//_____________________________________________________________________
//25
@Override
public int countWhere(String where)
{
try{
return this.nativeManager.countWhere(where);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//20
@Override
public int countUsingTemplate(DeviceBean bean, int searchType)
{
try{
return this.nativeManager.countUsingTemplate(this.beanConverter.toRight(bean),searchType);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//_____________________________________________________________________
//
// LISTENER
//_____________________________________________________________________
//35
/**
* @return {@link WrapListener} instance
*/
@Override
public TableListener<DeviceBean> registerListener(TableListener<DeviceBean> listener)
{
WrapListener wrapListener;
if(listener instanceof WrapListener){
wrapListener = (WrapListener)listener;
this.nativeManager.registerListener(wrapListener.nativeListener);
}else{
wrapListener = new WrapListener(listener);
this.nativeManager.registerListener(wrapListener.nativeListener);
}
return wrapListener;
}
//36
@Override
public void unregisterListener(TableListener<DeviceBean> listener)
{
if(!(listener instanceof WrapListener)){
throw new IllegalArgumentException("invalid listener type: " + WrapListener.class.getName() +" required");
}
this.nativeManager.unregisterListener(((WrapListener)listener).nativeListener);
}
//37
@Override
public void fire(TableListener.Event event, DeviceBean bean){
fire(event.ordinal(), bean);
}
//37-1
@Override
public void fire(int event, DeviceBean bean){
try{
this.nativeManager.fire(event, this.beanConverter.toRight(bean));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
//37-2
/**
* bind foreign key listener to foreign table for DELETE RULE
*/
void bindForeignKeyListenerForDeleteRule(){
this.nativeManager.bindForeignKeyListenerForDeleteRule();
}
//37-3
/**
* unbind foreign key listener from all of foreign tables <br>
* @see #bindForeignKeyListenerForDeleteRule()
*/
void unbindForeignKeyListenerForDeleteRule(){
this.nativeManager.unbindForeignKeyListenerForDeleteRule();
}
/**
* wrap {@code TableListener<DeviceBean>} as native listener
*/
public class WrapListener implements TableListener<DeviceBean>{
private final TableListener<DeviceBean> listener;
private final net.gdface.facelog.dborm.TableListener<net.gdface.facelog.dborm.device.FlDeviceBean> nativeListener;
private WrapListener(final TableListener<DeviceBean> listener) {
if(null == listener){
throw new NullPointerException();
}
this.listener = listener;
this.nativeListener = new net.gdface.facelog.dborm.TableListener<net.gdface.facelog.dborm.device.FlDeviceBean> (){
@Override
public void beforeInsert(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.beforeInsert(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void afterInsert(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.afterInsert(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void beforeUpdate(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.beforeUpdate(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void afterUpdate(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.afterUpdate(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void beforeDelete(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.beforeDelete(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void afterDelete(net.gdface.facelog.dborm.device.FlDeviceBean bean) throws DaoException {
listener.afterDelete(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public void done() throws DaoException {
listener.done();
}};
}
@Override
public void beforeInsert(DeviceBean bean) {
listener.beforeInsert(bean);
}
@Override
public void afterInsert(DeviceBean bean) {
listener.afterInsert(bean);
}
@Override
public void beforeUpdate(DeviceBean bean) {
listener.beforeUpdate(bean);
}
@Override
public void afterUpdate(DeviceBean bean) {
listener.afterUpdate(bean);
}
@Override
public void beforeDelete(DeviceBean bean) {
listener.beforeDelete(bean);
}
@Override
public void afterDelete(DeviceBean bean) {
listener.afterDelete(bean);
}
@Override
public void done() {
listener.done();
}
}
//_____________________________________________________________________
//
// UTILS
//_____________________________________________________________________
//43
@Override
public boolean isPrimaryKey(String column){
return this.nativeManager.isPrimaryKey(column);
}
@Override
public int loadBySqlForAction(String sql, Object[] argList, int[] fieldList,int startRow, int numRows,Action<DeviceBean> action){
try{
return this.nativeManager.loadBySqlForAction(sql,argList,fieldList,startRow,numRows,this.toNative(action));
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
@Override
public <T>T runAsTransaction(Callable<T> fun) {
try{
return this.nativeManager.runAsTransaction(fun);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
@Override
public void runAsTransaction(Runnable fun) {
try{
this.nativeManager.runAsTransaction(fun);
}
catch(DaoException e)
{
throw new RuntimeDaoException(e);
}
}
private net.gdface.facelog.dborm.TableManager.Action<net.gdface.facelog.dborm.device.FlDeviceBean> toNative(final Action<DeviceBean> action){
if(null == action){
throw new NullPointerException();
}
return new net.gdface.facelog.dborm.TableManager.Action<net.gdface.facelog.dborm.device.FlDeviceBean>(){
@Override
public void call(net.gdface.facelog.dborm.device.FlDeviceBean bean) {
action.call(DeviceManager.this.beanConverter.fromRight(bean));
}
@Override
public net.gdface.facelog.dborm.device.FlDeviceBean getBean() {
return DeviceManager.this.beanConverter.toRight(action.getBean());
}};
}
//45 override IDeviceManager
@Override
public java.util.List<Integer> toPrimaryKeyList(DeviceBean... beans){
if(null == beans){
return new java.util.ArrayList<Integer>();
}
java.util.ArrayList<Integer> list = new java.util.ArrayList<Integer>(beans.length);
for(DeviceBean bean:beans){
list.add(null == bean ? null : bean.getId());
}
return list;
}
//46 override IDeviceManager
@Override
public java.util.List<Integer> toPrimaryKeyList(java.util.Collection<DeviceBean> beans){
if(null == beans){
return new java.util.ArrayList<Integer>();
}
java.util.ArrayList<Integer> list = new java.util.ArrayList<Integer>(beans.size());
for(DeviceBean bean:beans){
list.add(null == bean ? null : bean.getId());
}
return list;
}
}
| 32.993364
| 167
| 0.623077
|
3d82fb492cc381930effaf265e8ad695a5bc3b86
| 1,879
|
package org.udg.pds.todoandroid.fragmentPagerAdapter;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import org.udg.pds.todoandroid.R;
import org.udg.pds.todoandroid.entity.User;
import org.udg.pds.todoandroid.fragment.ProductListFragment;
import org.udg.pds.todoandroid.fragment.ProfileFragment;
import org.udg.pds.todoandroid.fragment.ProfileMapFragment;
import org.udg.pds.todoandroid.fragment.RateListFragment;
import org.udg.pds.todoandroid.fragment.UserProductListFragment;
import org.udg.pds.todoandroid.fragment.whiteFragment;
public class TabsProfilePagerAdapter extends FragmentPagerAdapter {
@StringRes
private static final int[] TAB_TITLES = new int[] { R.string.tab_products, R.string.tab_rates, R.string.tab_location };
private final ProfileFragment mContext;
private User user;
public TabsProfilePagerAdapter(ProfileFragment context, FragmentManager fm, User _u) {
super(fm);
mContext = context;
user = _u;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: //Product
return new UserProductListFragment();
case 1: //Coments
return RateListFragment.newInstance(user);
case 2: //Location
return new ProfileMapFragment(user.location);
default:
return null;
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
| 31.316667
| 123
| 0.710484
|
26f572eaddba2ad8fd6db48559245900c450f052
| 2,519
|
package org.springframework.security.oauth2.provider.exchange;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collections;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
/**
* @author Ryan Murfitt
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultTokenExchangeAuthenticationProviderTests {
@Mock
private TokenExchangeService tokenExchangeService;
@InjectMocks
private DefaultTokenExchangeAuthenticationProvider provider = new DefaultTokenExchangeAuthenticationProvider();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void authenticateIncorrectTokenType() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "KOala");
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Only TokenExchangeAuthenticationToken is supported");
provider.authenticate(token);
verifyZeroInteractions(this.tokenExchangeService);
}
@Test
public void authenticateSuccess() {
TokenExchangeAuthenticationToken token = new TokenExchangeAuthenticationToken(
"token", null);
UserDetails user = new User("bob", "password", Collections.<GrantedAuthority>emptyList());
when(tokenExchangeService.loadUserDetailsFromToken(token)).thenReturn(user);
Authentication result = provider.authenticate(token);
assertTrue(result instanceof TokenExchangeAuthenticationToken);
assertTrue(result.isAuthenticated());
assertSame(result.getPrincipal(), user);
assertSame(result.getCredentials(), token.getPrincipal());
}
@Test
public void supportsIncorrectTokenType() {
assertFalse(provider.supports(UsernamePasswordAuthenticationToken.class));
}
@Test
public void supportsSuccess() {
assertTrue(provider.supports(TokenExchangeAuthenticationToken.class));
}
}
| 33.586667
| 115
| 0.762604
|
5e7e22db3172180c7a587cb96c57ff4ee01bd399
| 3,731
|
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pig.rms.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.rms.api.entity.RawMaterial;
import com.pig4cloud.pig.rms.api.entity.RawMaterialDetails;
import com.pig4cloud.pig.rms.mapper.RawMaterialDetailsMapper;
import com.pig4cloud.pig.rms.service.InventoryService;
import com.pig4cloud.pig.rms.service.RawMaterialDetailsService;
import com.pig4cloud.pig.rms.service.RawMaterialService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 库存明细表
*
* @author 何林
* @date 2021-10-29 23:31:49
*/
@Slf4j
@Service
@AllArgsConstructor
public class RawMaterialDetailsServiceImpl extends ServiceImpl<RawMaterialDetailsMapper, RawMaterialDetails> implements RawMaterialDetailsService {
private final RawMaterialService rawMaterialService;
private final InventoryService inventoryService;
private final RawMaterialDetailsMapper rawMaterialDetailsMapper;
/**
* 新增原料规格
* 更新原料总库存
* 初始化库存记录
*
* @param rawMaterialDetails 原材料规格
* @return
*/
@Transactional
@SneakyThrows
public boolean saveAndUpdateInventory(RawMaterialDetails rawMaterialDetails) {
if (null == rawMaterialDetails.getRawMaterialId()){
throw new Exception("未选择对应的材料");
}
RawMaterial rawMaterial = rawMaterialService.getById(rawMaterialDetails.getRawMaterialId());
if (null == rawMaterial){
throw new Exception("选择的材料不存在");
}
//更新材料总库存
rawMaterial.setRawMaterialAmount(rawMaterial.getRawMaterialAmount() + rawMaterialDetails.getAmount());
rawMaterialService.updateById(rawMaterial);
//保存规格信息
save(rawMaterialDetails);
//初始化库存信息表、并记录操作记录
inventoryService.addInventoryAndChange(rawMaterialDetails.getId(), rawMaterialDetails.getAmount());
return true;
}
@Override
public void queryPageAndUpdateInventory(RawMaterialDetails rawMaterialDetails) {
if (null != rawMaterialDetails.getRawMaterialId() && rawMaterialDetails.getRawMaterialId() != 0) {
//获取原材料数据
RawMaterial rawMaterial = rawMaterialService.getById(rawMaterialDetails.getRawMaterialId());
//获取规格数据
Map hash = new HashMap();
hash.put("raw_material_id", rawMaterialDetails.getRawMaterialId());
hash.put("del_flag", "0");
List<RawMaterialDetails> list = this.listByMap(hash);
if (!list.isEmpty()) {
rawMaterial.setRawMaterialAmount(list.stream().mapToLong(r -> r.getAmount()).sum());
}
rawMaterialService.updateById(rawMaterial);
}
}
@Override
public int getRawMaterialDetailsAmount(Long rawMaterialId) {
return rawMaterialDetailsMapper.getRawMaterialDetailsAmount(rawMaterialId);
}
@Override
public List<RawMaterialDetails> getList() {
return rawMaterialDetailsMapper.getList();
}
}
| 33.612613
| 147
| 0.78692
|
0e5d05405c404de7aa3bac8af5e674a508872bcf
| 5,149
|
package ro.pub.cs.systems.eim.practicaltest01var08;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class PracticalTest01Var08MainActivity extends Activity {
private Button button1, button2, button3, button4, button5, navigateButton;
private TextView textview;
private final static int SECONDARY_ACTIVITY_REQUEST_CODE = 1;
private int nboftries =0;
private int nbsuceeded =0;
private int nboffailers =0;
private boolean isDirty = false;
private ButtonClickListener buttonClickListener = new ButtonClickListener();
private class ButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
textview.setText("Top Left");
break;
case R.id.button2:
textview.setText("Top Right");
break;
case R.id.button3:
textview.setText("Center");
break;
case R.id.button4:
textview.setText("Bottom Left");
break;
case R.id.button5:
textview.setText("Bottom Right");
break;
case R.id.navigate_to_secondary_activity_button:
Intent intent = new Intent(getApplicationContext(), PracticalTest01Var08SecondaryActivity.class);
intent.putExtra("outputView",textview.getText().toString());
startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practical_test01_var08_main);
textview = (TextView) findViewById(R.id.name_text_view);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(buttonClickListener);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(buttonClickListener);
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(buttonClickListener);
button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(buttonClickListener);
button5 = (Button) findViewById(R.id.button5);
button5.setOnClickListener(buttonClickListener);
navigateButton = (Button) findViewById(R.id.navigate_to_secondary_activity_button);
navigateButton.setOnClickListener(buttonClickListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//int result = intent.getIntExtra("result", -1);
if (requestCode == SECONDARY_ACTIVITY_REQUEST_CODE) {
Toast.makeText(this, "Activity returned with result " + resultCode, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("textAll", textview.getText().toString());
savedInstanceState.putInt("nboftries", nboftries);
savedInstanceState.putInt("nbsuceeded", nbsuceeded);
savedInstanceState.putInt("nboffailers", nboffailers);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey("textAll")) {
textview.setText(savedInstanceState.getString("textAll"));
} else {
textview.setText(String.valueOf(""));
}
nboftries = savedInstanceState.getInt("nboftries");
Toast.makeText(getApplicationContext(), "nboftries is restored: " + nboftries, Toast.LENGTH_LONG).show();
nbsuceeded = savedInstanceState.getInt("nbsuceeded");
Toast.makeText(getApplicationContext(), "nbsuceeded is restored: " + nbsuceeded, Toast.LENGTH_LONG).show();
nboffailers = savedInstanceState.getInt("nboffailers");
Toast.makeText(getApplicationContext(), "nboffailers is restored: " + nboffailers, Toast.LENGTH_LONG).show();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
Intent intent = new Intent(this, PracticalTest01Var08MainActivity.class);
//stopService(intent);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.practical_test01_var08_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 30.467456
| 118
| 0.694698
|
afbc5ed4a27a241a596b84264ff2df7ec80ba0e5
| 8,196
|
/**
* I waive copyright and related rights in the this work worldwide through the CC0 1.0 Universal
* public domain dedication. https://creativecommons.org/publicdomain/zero/1.0/legalcode
*/
package gov.usgs.volcanoes.pensive.plot;
import gov.usgs.plot.data.SliceWave;
import gov.usgs.plot.data.Spectrogram;
import gov.usgs.plot.render.BasicFrameRenderer;
import gov.usgs.plot.render.TextRenderer;
import gov.usgs.plot.render.wave.MinuteMarkingWaveRenderer;
import gov.usgs.plot.render.wave.SliceWaveRenderer;
import gov.usgs.plot.render.wave.SpectrogramRenderer;
import gov.usgs.volcanoes.core.configfile.ConfigFile;
import gov.usgs.volcanoes.core.time.J2kSec;
import gov.usgs.volcanoes.core.time.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
/**
* Create a combined wave/spectrogram plot for a single channel.
*
* @author Tom Parker
*
*/
public abstract class ChannelPlotter {
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelPlotter.class);
/** Font used to indicate no data available. */
public static final Color NO_DATA_TEXT_COLOR = new Color(160, 41, 41);
/** The ratio of a waveform plot to its spectrogram plot. */
public static final double WAVE_RATIO = .25;
private static final double DEFAULT_OVERLAP = 0.859375;
private static final boolean DEFAULT_LOG_POWER = true;
private static final double DEFAULT_MIN_FREQ = 0;
private static final double DEFAULT_MAX_FREQ = 10;
private static final int DEFAULT_NFFT = 0;
private static final int DEFAULT_BIN_SIZE = 256;
private static final int DEFAULT_MAX_POWER = 120;
private static final int DEFAULT_MIN_POWER = 30;
/** my wave data. */
protected SliceWave wave;
/** Font to use for no data message. */
protected Font noDataFont;
/** Channel position in plot. */
protected int index;
/** Dimension of channel plot. */
protected Dimension plotDimension;
/** my config stanza. */
protected ConfigFile config;
/** my wave renderer. */
private final SliceWaveRenderer waveRenderer;
/** my spectrogram renderer. */
protected final SpectrogramRenderer spectrogramRenderer;
/** my frame renderer. */
private final BasicFrameRenderer plotFrame;
/** height of the wave panel. */
protected final int waveHeight;
/** spectrogram min power. */
private final int minPower;
/** spectrogram max power. */
private final int maxPower;
/** my name. */
protected final String name;
/** plot end time in ms. */
protected long plotEndMs;
/** make any type-specific modifications to the SpectrogramRenderer. */
protected abstract void tweakSpectrogramRenderer(SpectrogramRenderer spectrogramRenderer);
/** make any type-specific modifications to the SliceWaveRenderer. */
protected abstract void tweakWaveRenderer(SliceWaveRenderer waveRenderer);
/** make any type-specific modifications to the no-data Renderer. */
protected abstract void tweakNoDataRenderer(TextRenderer textRenderer);
/**
* Class constructor.
*
* @param name My name
*
* @param index My position on the subnet plot
*
* @param plotDimension The dimension of the plot
*
* @param config My configuration stanza
*/
public ChannelPlotter(String name, int index, Dimension plotDimension, ConfigFile config) {
this.name = name;
this.index = index;
this.plotDimension = plotDimension;
this.config = config;
waveHeight = (int) (plotDimension.height * WAVE_RATIO);
minPower = config.getInt("minPower", DEFAULT_MIN_POWER);
maxPower = config.getInt("maxPower", DEFAULT_MAX_POWER);
waveRenderer = createWaveRenderer();
spectrogramRenderer = createSpectrogramRenderer(config);
plotFrame = new BasicFrameRenderer();
plotFrame.addRenderer(waveRenderer);
plotFrame.addRenderer(spectrogramRenderer);
}
/**
* Create a SpectrogramRendere and apply my settings.
*
* @param config my config stanza
*
* @return my SpectrogramRenderer
*
*/
protected SpectrogramRenderer createSpectrogramRenderer(ConfigFile config) {
SpectrogramRenderer sr = new SpectrogramRenderer();
// y-axis labels will sometimes not be displayed if x-axis tick marks
// are not displayed. Note sure why.
sr.yTickMarks = false;
sr.yTickValues = false;
sr.xTickMarks = false;
sr.xTickValues = false;
sr.xUnits = false;
sr.xLabel = false;
sr.setOverlap(config.getDouble("overlap", DEFAULT_OVERLAP));
sr.setLogPower(config.getBoolean("logPower", DEFAULT_LOG_POWER));
sr.setMinFreq(config.getDouble("minFreq", DEFAULT_MIN_FREQ));
sr.setMaxFreq(config.getDouble("maxFreq", DEFAULT_MAX_FREQ));
sr.setNfft(config.getInt("nfft", DEFAULT_NFFT));
sr.setBinSize(config.getInt("binSize", DEFAULT_BIN_SIZE));
sr.setMinPower(minPower);
sr.setMaxPower(maxPower);
sr.setTimeZone("UTC");
tweakSpectrogramRenderer(sr);
return sr;
}
/**
* Create a WaveRenderer and apply my settings.
*
* @return my SliceWaveRenderer
*/
protected SliceWaveRenderer createWaveRenderer() {
SliceWaveRenderer wr = new MinuteMarkingWaveRenderer();
wr.xTickMarks = false;
wr.xTickValues = false;
wr.xUnits = false;
wr.xLabel = false;
wr.yTickMarks = false;
wr.yTickValues = false;
wr.setColor(Color.BLACK);
tweakWaveRenderer(wr);
return wr;
}
/**
* wave mutator method.
*
* @param wave wave to plot
*/
public void setWave(SliceWave wave) {
this.wave = wave;
waveRenderer.setWave(wave);
spectrogramRenderer.setWave(wave);
if (wave != null) {
double plotStart = wave.getStartTime();
double plotEnd = wave.getStartTime() + SubnetPlotter.DURATION_S;
waveRenderer.setMinY(wave.min());
waveRenderer.setMaxY(wave.max());
waveRenderer.setWave(wave);
waveRenderer.setViewTimes(plotStart, plotEnd, "UTC");
waveRenderer.update();
spectrogramRenderer.setWave(wave);
spectrogramRenderer.setViewStartTime(plotStart);
spectrogramRenderer.setViewEndTime(plotEnd);
spectrogramRenderer.createDefaultFrameDecorator();
spectrogramRenderer.update();
plotEndMs = J2kSec.asEpoch(plotEnd);
}
}
/**
* Produce the plot.
*
* @return frame renderer containing plot or error message
*/
public BasicFrameRenderer plot() {
if (wave != null && wave.samples() > 0) {
return plotFrame;
} else {
return noDataRenderer();
}
}
/**
* Produce a graphical error message indicating that no data is available.
*
* @return A graphical error message
*/
private BasicFrameRenderer noDataRenderer() {
int top = index * plotDimension.height;
TextRenderer tr = new TextRenderer(plotDimension.width / 2, top + plotDimension.height / 2,
name + " - no data");
tr.horizJustification = TextRenderer.CENTER;
tr.vertJustification = TextRenderer.CENTER;
tr.color = NO_DATA_TEXT_COLOR;
tr.font = noDataFont;
tweakNoDataRenderer(tr);
BasicFrameRenderer fr = new BasicFrameRenderer();
fr.addRenderer(tr);
return fr;
}
/**
* accessor method for plotEndMs.
*
* @return plotEndMs
*/
public long getPlotEndMs() {
return plotEndMs;
}
/**
* Return data as a CSV string.
*
* @param timestampFormat format to use for the timestamp
* @return A string CSV representation of the data
*/
public String getCsv(String timestampFormat) {
Spectrogram spectrogram = spectrogramRenderer.getSpectrogram();
if (spectrogram == null) {
return null;
}
double[][] buffer = spectrogram.getSpectraAmplitude();
long time = plotEndMs - (SubnetPlotter.DURATION_S * 1000);
long incr = (plotEndMs - time) / buffer.length;
StringBuffer sb = new StringBuffer();
for (double[] row : buffer) {
sb.append(Time.format(timestampFormat, time) + ",");
for (double col : row) {
sb.append((int) col + ",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
time += incr;
}
return sb.toString();
}
}
| 28.164948
| 96
| 0.698755
|
6b83c7069220d3c43614b01582d786fcbd64c304
| 1,342
|
package org.openapi4j.parser.validation.v3;
import org.openapi4j.core.validation.ValidationResults;
import org.openapi4j.parser.model.v3.EncodingProperty;
import org.openapi4j.parser.model.v3.OpenApi3;
import org.openapi4j.parser.validation.ValidationContext;
import org.openapi4j.parser.validation.Validator;
import static org.openapi4j.parser.validation.v3.OAI3Keywords.*;
class EncodingPropertyValidator extends Validator3Base<OpenApi3, EncodingProperty> {
private static final Validator<OpenApi3, EncodingProperty> INSTANCE = new EncodingPropertyValidator();
private EncodingPropertyValidator() {
}
public static Validator<OpenApi3, EncodingProperty> instance() {
return INSTANCE;
}
@Override
public void validate(ValidationContext<OpenApi3> context, OpenApi3 api, EncodingProperty encodingProperty, ValidationResults results) {
// VALIDATION EXCLUSIONS :
// explode
validateString(encodingProperty.getContentType(), results, false, CRUMB_CONTENTTYPE);
validateMap(context, api, encodingProperty.getExtensions(), results, false, CRUMB_EXTENSIONS, Regexes.EXT_REGEX, null);
validateMap(context, api, encodingProperty.getHeaders(), results, false, CRUMB_HEADERS, Regexes.NOEXT_REGEX, null);
validateString(encodingProperty.getStyle(), results, false, Regexes.STYLE_REGEX, CRUMB_STYLE);
}
}
| 43.290323
| 137
| 0.802534
|
9c16eaea0dbea372eefc0af6e136de3212612bd3
| 3,449
|
package com.waka.workspace.smalldianping.Activity.Main.Fragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.waka.workspace.smalldianping.Activity.Main.MainActivity;
import com.waka.workspace.smalldianping.DataBase.User;
import com.waka.workspace.smalldianping.DataBase.UserManager;
import com.waka.workspace.smalldianping.R;
/**
* 登录
* Created by waka on 2015/12/22.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "LoginActivity";
private Toolbar mToolbar;
private EditText etUserName,etPassword;
private UserManager userManager;
/**
* onCreate
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
initData();
initEvent();
userManager= new UserManager(this);
// userManager.add(new User(0, "123", "123"));
}
private void initView() {
//设置Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(getString(R.string.activity_login_title));
findViewById(R.id.btnLogin).setOnClickListener(this);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etPassword= (EditText) findViewById(R.id.etPassword);
etUserName= (EditText) findViewById(R.id.etUserName);
}
private void initData() {
}
private void initEvent() {
}
/**
* 标题栏按钮选中事件处理
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//如果是按返回按钮
case android.R.id.home:
finish();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//由左向右滑入的效果
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 监听返回键
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//由左向右滑入的效果
break;
}
//继续执行父类的其他点击事件
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnLogin:
User query = userManager.query(etPassword.getText().toString(), etUserName.getText().toString());
if(query!=null){
Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT).show();
MainActivity.login_user_id=query.getName();
setResult(0x10021);
this.finish();
}else{
Toast.makeText(this,"登陆失败",Toast.LENGTH_SHORT).show();
}
break;
}
}
}
| 28.270492
| 115
| 0.61699
|
9de11202ee573ce9eb8053798a7e783b6b717fa2
| 1,149
|
package stallone.complex.io;
import stallone.api.complex.IComplexArray;
import stallone.api.algebra.*;
/**
*
* @author Martin Senne
*/
public class OutputUtil
{
public static String scalarToEasyString(IComplexNumber s)
{
return(scalarToEasyString(s.getRe(), s.getIm()));
}
public static String scalarToEasyString(double re, double im)
{
if (im == 0)
{
return Double.toString(re);
}
else
{
if (im > 0.0d)
{
return Double.toString(re) + "+" + im + "i";
}
else
{
return Double.toString(re) + im + "i";
}
}
}
public static String vectorToEasyString(IComplexArray v)
{
final StringBuilder builder = new StringBuilder();
int n = v.size();
for (int i = 0; i < n; i++)
{
builder.append(OutputUtil.scalarToEasyString(v.getRe(i), v.getIm(i)));
if (i < (n - 1))
{
builder.append(", ");
}
}
return builder.toString();
}
}
| 20.890909
| 82
| 0.48651
|
616f95a5f55c4cf69bc2c0e4dada2a80f2918f2c
| 814
|
package com.puresoltechnologies.javafx.preferences.serializers;
import com.puresoltechnologies.javafx.extensions.fonts.FontDefinition;
import com.puresoltechnologies.javafx.extensions.properties.PropertyDefinition;
import com.puresoltechnologies.javafx.preferences.PreferencesSerializer;
public class FontDefinitionPreferenceSerializer implements PreferencesSerializer<FontDefinition> {
@Override
public boolean isSuitable(PropertyDefinition<FontDefinition> definition) {
return FontDefinition.class.equals(definition.getType());
}
@Override
public String serialize(FontDefinition object) {
return object.toString();
}
@Override
public FontDefinition deserialize(PropertyDefinition<FontDefinition> definition, String string) {
return FontDefinition.valueOf(string);
}
}
| 33.916667
| 101
| 0.815725
|
44f2da6db1e64222678b4ad0a48fc9498858d0ef
| 5,101
|
package frc.team1138.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import frc.team1138.robot.commands.ClearStickyFaults;
import frc.team1138.robot.commands.CollectCubeRight;
import frc.team1138.robot.commands.CycleArm;
import frc.team1138.robot.commands.EjectCube;
import frc.team1138.robot.commands.TogglePlunger;
import frc.team1138.robot.commands.MoveArmToExchange;
import frc.team1138.robot.commands.PositionLift;
import frc.team1138.robot.commands.ShiftBase;
import frc.team1138.robot.commands.ShiftLift;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OITest
{
// Limit for Xbox joystick axes to get out of the "dead zone"
public static final double KXboxDeadZoneLimit = 0.2;
// Joystick Definitions
public static final int KLogitechController = 0; // Base driver
public static final int KXBoxController = 1; // Arms and lifts driver
// Logitech button definitions - look below for usage
public static final int KButton1 = 1;
public static final int KButton2 = 2;
public static final int KButton3 = 3;
public static final int KButton4 = 4;
public static final int KButton6 = 6;
// XBox button definitions - look below for usage
public static final int KButtonA = 1;
public static final int KButtonB = 2;
public static final int KButtonX = 3;
public static final int KButtonY = 4;
public static final int KLeftBumper = 5;
public static final int KRightBumper = 6;
public static final int KStartButton = 8;
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// Define joysticks and joystick buttons
private Joystick logitechController, xBoxController;
private JoystickButton btn1, btn2, btn3, btn4, btn6; // Logitech Button
private JoystickButton btnA, btnB, btnX, btnY, btnLB, btnRB, btnStrt;
public OITest()
{
logitechController = new Joystick(KLogitechController);
xBoxController = new Joystick(KXBoxController);
// Logitech Buttons
btn1 = new JoystickButton(logitechController, KButton1);
btn2 = new JoystickButton(logitechController, KButton2);
btn3 = new JoystickButton(logitechController, KButton3);
btn4 = new JoystickButton(logitechController, KButton4);
btn6 = new JoystickButton(logitechController, KButton6);
// XBox Definitions (the functions of the buttons will change with time)
btnA = new JoystickButton(xBoxController, KButtonA);
btnB = new JoystickButton(xBoxController, KButtonB);
btnX = new JoystickButton(xBoxController, KButtonX);
btnY = new JoystickButton(xBoxController, KButtonY);
btnLB = new JoystickButton(xBoxController, KLeftBumper);
btnRB = new JoystickButton(xBoxController, KRightBumper);
btnStrt = new JoystickButton(logitechController, KStartButton);
btn1.whenPressed(new ClearStickyFaults()); //Clears sticky faults
// btn2.whenPressed(); //Nothing assigned yet, probably will be when we have the lift mechanism going
btn3.whenPressed(new CollectCubeRight()); // Toggles rollers collecting
btn4.whenPressed(new EjectCube()); // Toggles rollers ejecting
btn6.whenPressed(new ShiftBase()); // Shifts the base
// btnA.whenPressed(new CycleArm()); // Puts the arm through a full cycle
btnB.whenPressed(new MoveArmToExchange()); // Moves the arm to the exchange position
// btnX.whenPressed(new PositionLift(5)); // High position TODO test these values
btnY.whenPressed(new ShiftLift()); // Shifts the lift speed
// btnRB.whenPressed(new PositionLift(3)); // Middle position
// btnLB.whenPressed(new PositionLift(1)); // Low position
btnStrt.whenPressed(new TogglePlunger()); // Kicks the cube when it may be stuck using the plunger
}
public double getRightAxis()
{ // Right axis is right side drive
if (logitechController.getThrottle() < -KXboxDeadZoneLimit
|| logitechController.getThrottle() > KXboxDeadZoneLimit)
{
return logitechController.getThrottle(); // TODO check if it's twist for z-rotate axis
}
else
{
return 0;
}
}
public double getLeftAxis()
{ // Left controller is left side drive
if (logitechController.getY() < -KXboxDeadZoneLimit || logitechController.getY() > KXboxDeadZoneLimit)
{
return logitechController.getY();
}
else
{
return 0;
}
}
public boolean getLeftTrigger()
{ // left controller's trigger is currently unused
return true;
// Add function here, currently this doesn't do much.
}
public boolean getRightTrigger()
{ // right controller's trigger engages the shift on the base
return true;
// Add function here, currently this doesn't do much.
}
public double getLeftXBoxAxis()
{ // left xbox axis controls the linear lift
return (-xBoxController.getRawAxis(1));
}
public double getRightXBoxAxis()
{ // right xbox axis controls the dumper arm
return (-xBoxController.getRawAxis(5));
}
public double getXBoxPOV()
{ // POV left and right is dumper conveyor
return xBoxController.getRawAxis(6);
}
}
| 36.697842
| 104
| 0.757891
|
db2caf5b443720c1645ba6677f34ad4690e874b2
| 5,255
|
/**
* The MIT License
* Copyright (c) 2014 Benoit Lacelle
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.solven.pepper.memory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.CharMatcher;
/**
* This class helps reference-sharing
*
* @author Benoit Lacelle
*
*/
@SuppressWarnings("PMD.GodClass")
public class PepperMemoryHelper implements IPepperMemoryConstants {
protected static final Logger LOGGER = LoggerFactory.getLogger(PepperMemoryHelper.class);
// http://java-performance.info/overview-of-memory-saving-techniques-java/
public static final int JVM_MEMORY_CHUNK = 8;
public static final int JVM_BYTES_PER_CHAR = 2;
public static final int JVM_STRING_HEADER = 45;
private static final long MASK = 0xFFFFFFFFL;
private static final int SHIFT = 32;
protected PepperMemoryHelper() {
// hidden
}
/**
* It might be useful to have an long<->(int,int) packing guaranteeing both integers to be positive if the long is
* positive
*/
public static final long positivePack(int i1, int i2) {
long packed1 = (long) i1 << SHIFT;
long packed2 = Integer.rotateLeft(i2, 1) & MASK;
return Long.rotateRight(packed1 | packed2, 1);
}
public static final int positiveUnpack1(long packed) {
// Move the higher bit as lower bit: if packed >= 0, we then are sure to have a
// 0 as first bit
return (int) (Long.rotateLeft(packed, 1) >>> SHIFT);
}
public static final int positiveUnpack2(long packed) {
// Move the higher bit as lower bit: if packed >= 0, we then are sure to have a
// 0 as first bit
// Then, this 0 bit it put back as last bit: the integer is guaranteed to be
// positive
return Integer.rotateRight((int) (Long.rotateLeft(packed, 1) & MASK), 1);
}
@SuppressWarnings("checkstyle:magicnumber")
public static long memoryAsLong(String targetMax) {
// https://stackoverflow.com/questions/1098488/jvm-heap-parameters
if (targetMax.isEmpty()) {
throw new UnsupportedOperationException("Can not be empty");
}
String digits;
long multiplier;
int lastDigit = targetMax.length();
char lastChar = targetMax.charAt(lastDigit - 1);
if (CharMatcher.javaDigit().matches(lastChar)) {
multiplier = 1L;
digits = targetMax;
} else {
lastDigit -= 1;
if (lastChar == 'b' || lastChar == 'B' || lastChar == 'o') {
if (targetMax.length() <= 1) {
return 0;
}
lastChar = targetMax.charAt(targetMax.length() - 2);
lastDigit -= 1;
}
if (lastChar == 'k' || lastChar == 'K') {
multiplier = IPepperMemoryConstants.KB;
} else if (lastChar == 'm' || lastChar == 'M') {
multiplier = IPepperMemoryConstants.MB;
} else if (lastChar == 'g' || lastChar == 'G') {
multiplier = IPepperMemoryConstants.GB;
} else {
throw new IllegalArgumentException(
"Can not parse " + targetMax + ". It should end by a digit or one of 'k', 'm','g'");
}
digits = targetMax.substring(0, lastDigit).trim();
}
// Something like "123,456" or "123 456"
if (digits.length() >= 5 && !CharMatcher.digit().matches(digits.charAt(digits.length() - 4))) {
// Transform "123,456" to "123" ~ "456"
digits = digits.substring(0, digits.length() - 4) + digits.substring(digits.length() - 3);
}
double parsedAsDouble = Double.parseDouble(digits);
return (long) (parsedAsDouble * multiplier);
}
public static String memoryAsString(long initialBytes) {
long leftBytes = initialBytes;
String string = "";
int unitsDone = 0;
if (unitsDone < 2) {
long gb = leftBytes / IPepperMemoryConstants.GB;
if (gb > 0) {
unitsDone++;
string += gb + "G";
leftBytes -= gb * IPepperMemoryConstants.GB;
}
}
if (unitsDone < 2) {
long mb = leftBytes / IPepperMemoryConstants.MB;
if (mb > 0) {
unitsDone++;
string += mb + "M";
leftBytes -= mb * IPepperMemoryConstants.MB;
}
}
if (unitsDone < 2) {
long kb = leftBytes / IPepperMemoryConstants.KB;
if (kb > 0) {
unitsDone++;
string += kb + "K";
leftBytes -= kb * IPepperMemoryConstants.KB;
}
}
if (unitsDone < 2) {
if (leftBytes > 0) {
string += leftBytes + "B";
} else {
LOGGER.trace("No more bytes");
}
}
return string;
}
}
| 31.094675
| 115
| 0.682969
|
5548b82d2f1bc1d50cc937605231ace17b087aa4
| 5,545
|
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
public class EmptyImmutableTableTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
return "com.google.common.collect.testModule";
}
public void testCellSet() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testCellSet();
}
public void testClear() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testClear();
}
public void testColumn() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testColumn();
}
public void testColumnKeySet() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testColumnKeySet();
}
public void testColumnMap() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testColumnMap();
}
public void testConsistentHashCode() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testConsistentHashCode();
}
public void testConsistentToString() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testConsistentToString();
}
public void testContains() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testContains();
}
public void testContainsColumn() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testContainsColumn();
}
public void testContainsRow() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testContainsRow();
}
public void testContainsValue() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testContainsValue();
}
public void testEqualsObject() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testEqualsObject();
}
public void testGet() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testGet();
}
public void testHashCode() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testHashCode();
}
public void testIsEmpty() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testIsEmpty();
}
public void testPut() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testPut();
}
public void testPutAll() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testPutAll();
}
public void testRemove() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testRemove();
}
public void testRow() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testRow();
}
public void testRowKeySet() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testRowKeySet();
}
public void testRowMap() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testRowMap();
}
public void testSize() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testSize();
}
public void testToString() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testToString();
}
public void testValues() throws Exception {
com.google.common.collect.EmptyImmutableTableTest testCase = new com.google.common.collect.EmptyImmutableTableTest();
testCase.testValues();
}
}
| 39.326241
| 119
| 0.8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.