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
55aa4a48a57d3c28fbc48414eca566bbdfc414fa
1,963
package com.konnectkode.liquibase.runtime; import io.agroal.api.AgroalDataSource; import liquibase.Liquibase; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.sql.SQLException; @ApplicationScoped public class LiquibaseProducer { @Inject AgroalDataSource dataSource; private LiquibaseBuildConfig liquibaseBuildConfig; @Produces @Dependent public Liquibase produceLiquibase() { ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(Thread.currentThread().getContextClassLoader()); try { DatabaseConnection databaseConnection = new JdbcConnection(dataSource.getConnection()); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection); if (liquibaseBuildConfig.defaultSchema.isPresent()) { database.setDefaultSchemaName(liquibaseBuildConfig.defaultSchema.get()); } liquibaseBuildConfig.databaseChangeLogLockTable.ifPresent(database::setDatabaseChangeLogLockTableName); liquibaseBuildConfig.databaseChangeLogTable.ifPresent(database::setDatabaseChangeLogTableName); return new Liquibase(liquibaseBuildConfig.changelog, resourceAccessor, database); } catch (SQLException | DatabaseException e) { throw new RuntimeException(e); } } public void setLiquibaseBuildConfig(LiquibaseBuildConfig liquibaseBuildConfig) { this.liquibaseBuildConfig = liquibaseBuildConfig; } }
35.690909
124
0.776872
52a9f207d1d51ffc3ea415367b040474ce2fa70d
2,128
package com.classpath.ordersapi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; @Configuration public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login/**", "/register/**", "/logout/**", "/contact-us/**", "/h2-console/**") .permitAll() .antMatchers(HttpMethod.GET, "/api/v1/orders/**") .hasAnyAuthority("ROLE_Everyone", "ROLE_super_admins", "ROLE_admins") .antMatchers(HttpMethod.POST, "/api/v1/orders/**") .hasAnyAuthority("ROLE_super_admins", "ROLE_admins") .antMatchers(HttpMethod.DELETE, "/api/v1/orders/**") .hasAuthority("ROLE_super_admins") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt(); } @Bean public JwtAuthenticationConverter jwtAuthenticationConverter(){ final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); final JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); grantedAuthoritiesConverter.setAuthoritiesClaimName("groups"); grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); return jwtAuthenticationConverter; } }
50.666667
112
0.707237
80515baa43c6705b50cbfd22b8cd1c2264745426
1,156
package com.emramirez.islandtrip.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.util.Set; import java.util.UUID; @Data @Entity public class Reservation { @Id @GeneratedValue @JsonProperty(access = JsonProperty.Access.READ_ONLY) private UUID id; @Version @JsonIgnore private Long version; @Column @NotNull(message = "Please provide the arrival date") private LocalDate arrivalDate; @Column @NotNull(message = "Please provide the departure date") private LocalDate departureDate; @Column @NotNull(message = "Please provide the customer email") private String customerEmail; @Column @NotNull(message = "Please provide the customer name") private String customerName; @Enumerated(value = EnumType.STRING) private ReservationStatus status; @JsonIgnore @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private Set<CalendarDate> calendarDates; }
23.591837
63
0.737889
ac4759f7caa4672cd43174c944e2724380316de2
1,566
package org.hisp.dhis.client.sdk.ui.bindings.commons; import android.content.Context; import android.support.annotation.NonNull; import org.hisp.dhis.client.sdk.android.api.D2; import org.hisp.dhis.client.sdk.android.api.utils.LoggerImpl; import org.hisp.dhis.client.sdk.ui.AppPreferences; import org.hisp.dhis.client.sdk.ui.AppPreferencesImpl; import org.hisp.dhis.client.sdk.utils.Logger; import static org.hisp.dhis.client.sdk.utils.Preconditions.isNull; final class DefaultAppModuleImpl implements DefaultAppModule { @NonNull private final Context context; public DefaultAppModuleImpl(Context context) { this.context = isNull(context, "Context must not be null"); D2.init(context); } @Override public Context providesContext() { return context; } @Override public ApiExceptionHandler providesApiExceptionHandler(Context context, Logger logger) { return new ApiExceptionHandlerImpl(context, logger); } @Override public AppPreferences providesApplicationPreferences(Context context) { return new AppPreferencesImpl(context); } @Override public SessionPreferences providesSessionPreferences(Context context) { return new SessionPreferencesImpl(context); } @Override public SyncDateWrapper providesSyncDateWrapper(Context context, AppPreferences preferences, Logger logger) { return new SyncDateWrapper(context, preferences); } @Override public Logger providesLogger() { return new LoggerImpl(); } }
27.964286
112
0.739464
dc0c8a878a37640832ec2d3bc36870446b030f50
2,139
package com.focus.cos.api.email.io; import java.io.IOException; import java.io.InputStream; public class InputStreamResource extends AbstractResource { private final InputStream inputStream; private final String description; private boolean read = false; /** * Create a new InputStreamResource. * * @param inputStream the InputStream to use */ public InputStreamResource(InputStream inputStream) { this(inputStream, "resource loaded through InputStream"); } /** * Create a new InputStreamResource. * * @param inputStream the InputStream to use * @param description where the InputStream comes from */ public InputStreamResource(InputStream inputStream, String description) { if (inputStream == null) { throw new IllegalArgumentException("InputStream must not be null"); } this.inputStream = inputStream; this.description = (description != null ? description : ""); } /** * This implementation always returns <code>true</code>. */ public boolean exists() { return true; } /** * This implementation always returns <code>true</code>. */ public boolean isOpen() { return true; } /** * This implementation throws IllegalStateException if attempting to read * the underlying stream multiple times. */ public InputStream getInputStream() throws IOException, IllegalStateException { if (this.read) { throw new IllegalStateException("InputStream has already been read - " + "do not use InputStreamResource if a stream needs to be read multiple times"); } this.read = true; return this.inputStream; } /** * This implementation returns the passed-in description, if any. */ public String getDescription() { return this.description; } /** * This implementation compares the underlying InputStream. */ public boolean equals(Object obj) { return (obj == this || (obj instanceof InputStreamResource && ((InputStreamResource) obj).inputStream.equals(this.inputStream))); } /** * This implementation returns the hash code of the underlying InputStream. */ public int hashCode() { return this.inputStream.hashCode(); } }
22.515789
131
0.719028
4abcb59f3fd6fe026d8f57cdc52b1ed2fa12713a
934
package tutorials.daysofcode30; import java.util.Scanner; import java.util.regex.Pattern; public class DataTypes { public static void main(String[] args) { try(Scanner scan = new Scanner(System.in)) { int i = 4; double d = 4.0; String s = "HackerRank "; final Pattern DOUBLE_PATTERN = Pattern.compile("\\d*+.\\d+"); final Pattern INTEGER_PATTERN = Pattern.compile("\\d+"); for (int j = 0; j < 3; j++) { String text = scan.nextLine(); if (DOUBLE_PATTERN.matcher(text).matches()) { System.out.println(d + Double.valueOf(text)); } else if (INTEGER_PATTERN.matcher(text).matches()) { System.out.println(i + Integer.valueOf(text)); } else { System.out.println(s + text); } } } } }
26.685714
73
0.505353
8190f1776656f4aa8146a22376b7b65d9decc625
195
class EntryPoint { public static void main(String[] args) { Point p = new Point(); Point q = new Point(); } } class Point extends DoesNotExist {} class Point {} class Point {}
16.25
42
0.625641
55d1043a5b62f942e11cd4f2d9618f2343db7e9a
809
package xyz.hcworld.hcwblog.service; import xyz.hcworld.hcwblog.commont.lang.Result; import xyz.hcworld.hcwblog.entity.UserCollection; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author Kenith-Zhang * @since 2020-07-12 */ public interface UserCollectionService extends IService<UserCollection> { /** * 增加收藏 * @param pid 文章id * @param userId 要收藏文章的用户 * @return */ Result addCollection(Long pid, Long userId); /** * 取消收藏 * @param pid 文章id * @param userId 要取消收藏文章的用户 * @return */ Result removeCollection(Long pid, Long userId); /** * 查询用户是否收藏该文章 * @param pid 文章id * @param userId 要收藏文章的用户 * @return */ Result collectionExistence(Long pid, Long userId); }
19.261905
73
0.636588
bc8a261cc9e78157d4735e7e0c71ed2c601b2a28
145
package io.vertx.core.eventbus; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public interface Copyable { public Object copy(); }
14.5
48
0.648276
fce5289cf0f4fb91c2324edd423b6e819eeee40a
1,051
package com.tresorit.zerokitsdk.component; import android.content.Context; import android.content.SharedPreferences; import com.tresorit.zerokit.Zerokit; import com.tresorit.zerokitsdk.module.AdminApiModule; import com.tresorit.zerokitsdk.module.ApplicationModule; import com.tresorit.zerokitsdk.module.EventBusModule; import com.tresorit.zerokitsdk.module.SharedPreferencesModule; import com.tresorit.zerokitsdk.module.ZerokitSdkModule; import com.tresorit.zerokitsdk.scopes.ApplicationScope; import com.tresorit.zerokit.AdminApi; import org.greenrobot.eventbus.EventBus; import dagger.Component; @ApplicationScope @Component( modules = { ApplicationModule.class, EventBusModule.class, AdminApiModule.class, ZerokitSdkModule.class, SharedPreferencesModule.class } ) public interface ApplicationComponent { Context context(); EventBus eventbus(); AdminApi adminApi(); Zerokit zerokit(); SharedPreferences sharedpreferences(); }
27.657895
62
0.749762
6946ecb8748bd5f86278048ab628dd762f86b4b6
909
package io.github.glytching.junit.extension.testname; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; @ExtendWith(TestNameExtension.class) public class TestNameExtensionTest { @TestName private String testName; @BeforeEach public void testNameIsOnlyPopulatedOnTestInvocation() { assertThat(testName, nullValue()); } @AfterEach public void testNameIsDiscardedBetweenTests() { assertThat(testName, nullValue()); } @Test public void canSetTestName() { assertThat(testName, is("canSetTestName")); } @Test public void canSetADifferentTestName() { assertThat(testName, is("canSetADifferentTestName")); } }
24.567568
57
0.773377
f439d43603715f791349dc3858ee309de08bd81c
11,431
package com.mx.pro.lib.fragmentation.support; import android.app.Activity; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import com.mx.pro.lib.fragmentation.ExtraTransaction; import com.mx.pro.lib.fragmentation.ISupportFragment; import com.mx.pro.lib.fragmentation.SupportFragmentDelegate; import com.mx.pro.lib.fragmentation.SupportHelper; import com.mx.pro.lib.fragmentation.anim.FragmentAnimator; import com.umeng.analytics.MobclickAgent; import static android.view.View.NO_ID; /** * @author Charlie * supportFragment implements ISupportFragment, */ public abstract class SupportFragment extends Fragment implements ISupportFragment { final SupportFragmentDelegate mDelegate = new SupportFragmentDelegate(this); protected FragmentActivity mFragmentActivity; protected View mView; @Override public SupportFragmentDelegate getSupportDelegate() { return mDelegate; } @Override public ExtraTransaction extraTransaction() { return mDelegate.extraTransaction(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mDelegate.onAttach(activity); mFragmentActivity = mDelegate.getActivity(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDelegate.onCreate(savedInstanceState); } @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { return mDelegate.onCreateAnimation(transit, enter, nextAnim); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mDelegate.onActivityCreated(savedInstanceState); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mDelegate.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); mDelegate.onResume(); MobclickAgent.onResume(mFragmentActivity); } @Override public void onPause() { super.onPause(); hideSoftInput(); mDelegate.onPause(); MobclickAgent.onPause(mFragmentActivity); } @Override public void onDestroyView() { super.onDestroyView(); mDelegate.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); mDelegate.onDestroy(); } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); mDelegate.onHiddenChanged(hidden); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); mDelegate.setUserVisibleHint(isVisibleToUser); } @Override public void enqueueAction(Runnable runnable) { mDelegate.enqueueAction(runnable); } @Override public void post(Runnable runnable) { mDelegate.post(runnable); } @Override public void onEnterAnimationEnd(@Nullable Bundle savedInstanceState) { mDelegate.onEnterAnimationEnd(savedInstanceState); } @Override public void onLazyInitView(@Nullable Bundle savedInstanceState) { mDelegate.onLazyInitView(savedInstanceState); } @Override public void onSupportVisible() { mDelegate.onSupportVisible(); } @Override public void onSupportInvisible() { mDelegate.onSupportInvisible(); } @Override public boolean isSupportVisible() { return mDelegate.isSupportVisible(); } @Override public FragmentAnimator onCreateFragmentAnimator() { return mDelegate.onCreateFragmentAnimator(); } @Override public FragmentAnimator getFragmentAnimator() { return mDelegate.getFragmentAnimator(); } @Override public void setFragmentAnimator(FragmentAnimator fragmentAnimator) { mDelegate.setFragmentAnimator(fragmentAnimator); } @Override public void setFragmentResult(int resultCode, Bundle bundle) { mDelegate.setFragmentResult(resultCode, bundle); } @Override public void onFragmentResult(int requestCode, int resultCode, Bundle data) { mDelegate.onFragmentResult(requestCode, resultCode, data); } @Override public void onNewBundle(Bundle args) { mDelegate.onNewBundle(args); } @Override public void putNewBundle(Bundle newBundle) { mDelegate.putNewBundle(newBundle); } @Override public boolean onBackPressedSupport() { return mDelegate.onBackPressedSupport(); } /** * 隐藏软键盘 */ protected void hideSoftInput() { mDelegate.hideSoftInput(); } /** * 显示软键盘,调用该方法后,会在onPause时自动隐藏软键盘 */ protected void showSoftInput(final View view) { mDelegate.showSoftInput(view); } /** * 加载根Fragment, 即Activity内的第一个Fragment 或 Fragment内的第一个子Fragment * * @param containerId 容器id * @param toFragment 目标Fragment */ public void loadRootFragment(int containerId, ISupportFragment toFragment) { mDelegate.loadRootFragment(containerId, toFragment); } public void loadRootFragment(int containerId, ISupportFragment toFragment, boolean addToBackStack, boolean allowAnim) { mDelegate.loadRootFragment(containerId, toFragment, addToBackStack, allowAnim); } /** * 加载多个同级根Fragment,类似Wechat, QQ主页的场景 */ public void loadMultipleRootFragment(int containerId, int showPosition, ISupportFragment... toFragments) { mDelegate.loadMultipleRootFragment(containerId, showPosition, toFragments); } /** * show一个Fragment,hide其他同栈所有Fragment * 使用该方法时,要确保同级栈内无多余的Fragment,(只有通过loadMultipleRootFragment()载入的Fragment) * <p> * 建议使用更明确的{@link #showHideFragment(ISupportFragment, ISupportFragment)} * * @param showFragment 需要show的Fragment */ public void showHideFragment(ISupportFragment showFragment) { mDelegate.showHideFragment(showFragment); } /** * show一个Fragment,hide一个Fragment ; 主要用于类似微信主页那种 切换tab的情况 */ public void showHideFragment(ISupportFragment showFragment, ISupportFragment hideFragment) { mDelegate.showHideFragment(showFragment, hideFragment); } public void start(ISupportFragment toFragment) { mDelegate.start(toFragment); } /** * @param launchMode Similar to Activity's LaunchMode. */ public void start(final ISupportFragment toFragment, @LaunchMode int launchMode) { mDelegate.start(toFragment, launchMode); } /** * Launch an fragment for which you would like a result when it poped. */ public void startForResult(ISupportFragment toFragment, int requestCode) { mDelegate.startForResult(toFragment, requestCode); } /** * Start the target Fragment and pop itself */ public void startWithPop(ISupportFragment toFragment) { mDelegate.startWithPop(toFragment); } /** * @see #popTo(Class, boolean) * + * @see #start(ISupportFragment) */ public void startWithPopTo(ISupportFragment toFragment, Class<?> targetFragmentClass, boolean includeTargetFragment) { mDelegate.startWithPopTo(toFragment, targetFragmentClass, includeTargetFragment); } public void replaceFragment(ISupportFragment toFragment, boolean addToBackStack) { mDelegate.replaceFragment(toFragment, addToBackStack); } public void pop() { mDelegate.pop(); } /** * Pop the child fragment. */ public void popChild() { mDelegate.popChild(); } /** * Pop the last fragment transition from the manager's fragment * back stack. * <p> * 出栈到目标fragment * * @param targetFragmentClass 目标fragment * @param includeTargetFragment 是否包含该fragment */ public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment) { mDelegate.popTo(targetFragmentClass, includeTargetFragment); } /** * If you want to begin another FragmentTransaction immediately after popTo(), use this method. * 如果你想在出栈后, 立刻进行FragmentTransaction操作,请使用该方法 */ public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable) { mDelegate.popTo(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable); } public void popTo(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable, int popAnim) { mDelegate.popTo(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable, popAnim); } public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment) { mDelegate.popToChild(targetFragmentClass, includeTargetFragment); } public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable) { mDelegate.popToChild(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable); } public void popToChild(Class<?> targetFragmentClass, boolean includeTargetFragment, Runnable afterPopTransactionRunnable, int popAnim) { mDelegate.popToChild(targetFragmentClass, includeTargetFragment, afterPopTransactionRunnable, popAnim); } /** * 得到位于栈顶Fragment */ public ISupportFragment getTopFragment() { return SupportHelper.getTopFragment(getFragmentManager()); } public ISupportFragment getTopChildFragment() { return SupportHelper.getTopFragment(getChildFragmentManager()); } /** * @return 位于当前Fragment的前一个Fragment */ public ISupportFragment getPreFragment() { return SupportHelper.getPreFragment(this); } /** * 获取栈内的fragment对象 */ public <T extends ISupportFragment> T findFragment(Class<T> fragmentClass) { return SupportHelper.findFragment(getFragmentManager(), fragmentClass); } /** * 获取栈内的fragment对象 */ public <T extends ISupportFragment> T findChildFragment(Class<T> fragmentClass) { return SupportHelper.findFragment(getChildFragmentManager(), fragmentClass); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = inflater.inflate(getLayout(), container, false); return mView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(); } public void initView() { } @Nullable public abstract int getLayout(); @NonNull public final <T extends View> T findViewById(@IdRes int id) { if (mView == null || id == NO_ID) { return null; } return mView.findViewById(id); } }
28.939241
140
0.700901
c28f24d9d8fb62e5db04afa28619d1f09bbc543f
17,335
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication3; import javax.swing.JOptionPane; /** * * @author kauha */ public class TelaCadastroCliente extends javax.swing.JFrame { /** * Creates new form TelaCadastroCliente */ public TelaCadastroCliente() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel3 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); tfNome = new javax.swing.JTextField(); jFormattedTextField1 = new javax.swing.JFormattedTextField(); jFormattedTextField2 = new javax.swing.JFormattedTextField(); jcSexo = new javax.swing.JComboBox<>(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jFormattedTextField3 = new javax.swing.JFormattedTextField(); jFormattedTextField4 = new javax.swing.JFormattedTextField(); jTextField7 = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel3.setText("jLabel1"); jLabel6.setText("jLabel6"); jTextField3.setText("jTextField3"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados Pessoais")); try { jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/###"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { jFormattedTextField2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jcSexo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Selecione", "Masculino", "Feminino" })); jLabel1.setText("Nome: "); jLabel2.setText("CPF: "); jLabel4.setText("Data: "); jLabel5.setText("Sexo: "); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jFormattedTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE) .addComponent(tfNome)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addGap(128, 128, 128)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5) .addGap(128, 128, 128)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(52, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Contato")); jLabel7.setText("Endereço: "); jLabel8.setText("Telefone: "); jLabel9.setText("Cidade: "); jLabel10.setText("Numero: "); try { jFormattedTextField3.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jLabel11.setText("E-mail"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel11) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel7) .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE) .addComponent(jLabel9) .addComponent(jLabel10) .addComponent(jTextField2)) .addGap(44, 44, 44)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(57, 291, Short.MAX_VALUE)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addComponent(jLabel11) .addGap(18, 18, 18) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(24, Short.MAX_VALUE)) ); jButton1.setText("Cadastrar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(59, 59, 59)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: JOptionPane.showMessageDialog(null,"Nome: "+tfNome.getText()+" Sexo: "+jcSexo.getSelectedItem().toString()); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaCadastroCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaCadastroCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaCadastroCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastroCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaCadastroCliente().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JFormattedTextField jFormattedTextField1; private javax.swing.JFormattedTextField jFormattedTextField2; private javax.swing.JFormattedTextField jFormattedTextField3; private javax.swing.JFormattedTextField jFormattedTextField4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField7; private javax.swing.JComboBox<String> jcSexo; private javax.swing.JTextField tfNome; // End of variables declaration//GEN-END:variables }
54.857595
174
0.66184
66ab655c751df13b554b0bad6a13979aa2b0a1d5
3,574
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.convert.mojo.rxnorm.propertyTypes; //~--- JDK imports ------------------------------------------------------------ import java.util.ArrayList; import sh.isaac.convert.mojo.rxnorm.rrf.RXNSAT; import sh.isaac.converters.sharedUtils.propertyTypes.Property; import sh.isaac.converters.sharedUtils.propertyTypes.ValuePropertyPair; import sh.isaac.converters.sharedUtils.umlsUtils.ValuePropertyPairWithAttributes; //~--- classes ---------------------------------------------------------------- /** * The Class ValuePropertyPairWithSAB. */ public class ValuePropertyPairWithSAB extends ValuePropertyPairWithAttributes { /** The sab. */ private final String sab; /** The sat data. */ private final ArrayList<RXNSAT> satData; //~--- constructors -------------------------------------------------------- /** * Instantiates a new value property pair with SAB. * * @param value the value * @param property the property * @param sab the sab * @param satData the sat data */ public ValuePropertyPairWithSAB(String value, Property property, String sab, ArrayList<RXNSAT> satData) { super(value, property); this.sab = sab; this.satData = satData; } //~--- methods ------------------------------------------------------------- /** * Compare to. * * @param o the o * @return the int */ @Override public int compareTo(ValuePropertyPair o) { // Boosting descriptions that come from RXNORM up to the very top. if (this.sab.equals("RXNORM") &&!((ValuePropertyPairWithSAB) o).sab.equals("RXNORM")) { return -1; } else if (!this.sab.equals("RXNORM") && ((ValuePropertyPairWithSAB) o).sab.equals("RXNORM")) { return 1; } return super.compareTo(o); } //~--- get methods --------------------------------------------------------- /** * Gets the sab. * * @return the sab */ public String getSab() { return this.sab; } /** * Gets the sat data. * * @return the sat data */ public ArrayList<RXNSAT> getSatData() { return this.satData; } }
29.783333
108
0.627868
42621d4eeef1023cd60f0cc56a0ad208ad6fa0b1
3,065
/* * 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.isis.applib.adapters; import java.math.BigDecimal; import org.apache.isis.applib.annotation.Defaulted; import org.apache.isis.applib.annotation.EqualByContent; import org.apache.isis.applib.annotation.Value; /** * Provides a mechanism for providing a set of value semantics. * * <p> * As explained in the Javadoc of the {@link Value} annotation, value semantics * only actually implies that the type is {@link Aggregated aggregated}. * However, values are very often * {@link Immutable} and implement {@link EqualByContent} semantics. In * addition, there may be a {@link Defaulted default value}. * * <p> * This interface is used by {@link Value} to allow these semantics to be * provided through a single point. Alternatively, {@link Value} supports this * information being provided via the configuration files. * * <p> * Whatever the class that implements this interface, it must also expose either * a <tt>public</tt> no-arg constructor, or (for implementations that also are * <tt>Facet</tt>s) a <tt>public</tt> constructor that accepts a * <tt>FacetHolder</tt>, and <tt>IsisConfiguration</tt> and a * <tt>ValueSemanticsProviderContext</tt>. This constructor is then used by the * framework to instantiate the object reflectively. * * @see Parser * @see EncoderDecoder * @see DefaultsProvider */ public interface ValueSemanticsProvider<T> { /** * The {@link Parser}, if any. */ Parser<T> getParser(); /** * The {@link EncoderDecoder}, if any. */ EncoderDecoder<T> getEncoderDecoder(); /** * The {@link DefaultsProvider}, if any. * * <p> * If not <tt>null</tt>, implies that the value has (or may have) a default. */ DefaultsProvider<T> getDefaultsProvider(); /** * Whether the value is {@link Immutable}. */ boolean isImmutable(); /** * Whether the value has {@link EqualByContent equal by content} semantics. * * <p> * If so, then it must implement <tt>equals(Object)</tt> and * <tt>hashCode()</tt> consistently. Examples in the Java language that do * this are {@link String} and {@link BigDecimal}, for example. */ boolean isEqualByContent(); }
33.681319
80
0.696574
3def7828a51694424f585dcba32aaa68304b7ce9
2,927
/* You have to represent a point in 2D space. Write a class with the name Point. The class needs two fields (instance variables) with name x and y of type int. The class needs to have two constructors. The first constructor does not have any parameters (no-arg constructor). The second constructor has parameters x and y of type int and it needs to initialize the fields. Write the following methods (instance methods): * Method named getX without any parameters, it needs to return the value of x field. * Method named getY without any parameters, it needs to return the value of y field. * Method named setX with one parameter of type int, it needs to set the value of the x field. * Method named setY with one parameter of type int, it needs to set the value of the y field. * Method named distance without any parameters, it needs to return the distance between this Point and Point 0,0 as double. * Method named distance with two parameters x, y both of type int, it needs to return the distance between this Point and Point x,y as double. * Method named distance with parameter another of type Point, it needs to return the distance between this Point and another Point as double. How to find the distance between two points?To find a distance between points A(xA,yA) and B(xB,yB), we use the formula: d(A,B)=√ (xB − xA) * (xB - xA) + (yB − yA) * (yB - yA) Where √ represents square root. */ package com.bartoszdopke; public class Point { private int x; private int y; public Point() { this(0,0); } public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } //* Method named distance without any parameters, it needs to return the distance between this Point and Point 0,0 as double public double distance() { //d(A,B)=√ (xB − xA) * (xB - xA) + (yB − yA) * (yB - yA) double dist = Math.sqrt((0.0 - this.x) * (0.0 - this.x) + (0.0 - this.y) * (0.0 - this.y)); return dist; } //* Method named distance with two parameters x, y both of type int, it needs to return the distance between this Point and Point x,y as double. public double distance(int x, int y) { double dist = Math.sqrt((x - this.x) * (x - this.x) + (y - this.y) * (y - this.y)); return dist; } //* Method named distance with parameter another of type Point, it needs to return the distance between this Point and another Point as double. public double distance(Point point) { double dist = Math.sqrt((this.x - point.getX()) * (this.x - point.getX()) + (this.y - point.getY()) * (this.y - point.getY())); return dist; } }
39.026667
157
0.640929
029d4c7fa2fb4e07807218088346a75a00edf8ac
6,601
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.car.navigationbar; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.WindowInsets; import android.widget.LinearLayout; import com.android.systemui.Dependency; import com.android.systemui.R; import com.android.systemui.car.navigationbar.CarNavigationBarController.NotificationsShadeController; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.phone.StatusBarIconController; /** * A custom navigation bar for the automotive use case. * <p> * The navigation bar in the automotive use case is more like a list of shortcuts, rendered * in a linear layout. */ public class CarNavigationBarView extends LinearLayout { private final boolean mConsumeTouchWhenPanelOpen; private View mNavButtons; private CarNavigationButton mNotificationsButton; private NotificationsShadeController mNotificationsShadeController; private View mLockScreenButtons; // used to wire in open/close gestures for notifications private OnTouchListener mStatusBarWindowTouchListener; public CarNavigationBarView(Context context, AttributeSet attrs) { super(context, attrs); mConsumeTouchWhenPanelOpen = getResources().getBoolean( R.bool.config_consumeNavigationBarTouchWhenNotificationPanelOpen); } @Override public void onFinishInflate() { mNavButtons = findViewById(R.id.nav_buttons); mLockScreenButtons = findViewById(R.id.lock_screen_nav_buttons); mNotificationsButton = findViewById(R.id.notifications); if (mNotificationsButton != null) { mNotificationsButton.setOnClickListener(this::onNotificationsClick); } View mStatusIcons = findViewById(R.id.statusIcons); if (mStatusIcons != null) { // Attach the controllers for Status icons such as wifi and bluetooth if the standard // container is in the view. StatusBarIconController.DarkIconManager mDarkIconManager = new StatusBarIconController.DarkIconManager( mStatusIcons.findViewById(R.id.statusIcons), Dependency.get(CommandQueue.class)); mDarkIconManager.setShouldLog(true); Dependency.get(StatusBarIconController.class).addIconGroup(mDarkIconManager); } // Needs to be clickable so that it will receive ACTION_MOVE events. setClickable(true); // Needs to not be focusable so rotary won't highlight the entire nav bar. setFocusable(false); } @Override public WindowInsets onApplyWindowInsets(WindowInsets windowInsets) { return windowInsets; } // Used to forward touch events even if the touch was initiated from a child component @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mStatusBarWindowTouchListener != null) { boolean shouldConsumeEvent = mNotificationsShadeController == null ? false : mNotificationsShadeController.isNotificationPanelOpen(); // Forward touch events to the status bar window so it can drag // windows if required (Notification shade) mStatusBarWindowTouchListener.onTouch(this, ev); if (mConsumeTouchWhenPanelOpen && shouldConsumeEvent) { return true; } } return super.onInterceptTouchEvent(ev); } /** Sets the notifications panel controller. */ public void setNotificationsPanelController(NotificationsShadeController controller) { mNotificationsShadeController = controller; } /** Gets the notifications panel controller. */ public NotificationsShadeController getNotificationsPanelController() { return mNotificationsShadeController; } /** * Sets a touch listener that will be called from onInterceptTouchEvent and onTouchEvent * * @param statusBarWindowTouchListener The listener to call from touch and intercept touch */ public void setStatusBarWindowTouchListener(OnTouchListener statusBarWindowTouchListener) { mStatusBarWindowTouchListener = statusBarWindowTouchListener; } /** Gets the touch listener that will be called from onInterceptTouchEvent and onTouchEvent. */ public OnTouchListener getStatusBarWindowTouchListener() { return mStatusBarWindowTouchListener; } @Override public boolean onTouchEvent(MotionEvent event) { if (mStatusBarWindowTouchListener != null) { mStatusBarWindowTouchListener.onTouch(this, event); } return super.onTouchEvent(event); } protected void onNotificationsClick(View v) { if (mNotificationsShadeController != null) { mNotificationsShadeController.togglePanel(); } } /** * If there are buttons declared in the layout they will be shown and the normal * Nav buttons will be hidden. */ public void showKeyguardButtons() { if (mLockScreenButtons == null) { return; } mLockScreenButtons.setVisibility(View.VISIBLE); mNavButtons.setVisibility(View.GONE); } /** * If there are buttons declared in the layout they will be hidden and the normal * Nav buttons will be shown. */ public void hideKeyguardButtons() { if (mLockScreenButtons == null) return; mNavButtons.setVisibility(View.VISIBLE); mLockScreenButtons.setVisibility(View.GONE); } /** * Toggles the notification unseen indicator on/off. * * @param hasUnseen true if the unseen notification count is great than 0. */ public void toggleNotificationUnseenIndicator(Boolean hasUnseen) { if (mNotificationsButton == null) return; mNotificationsButton.setUnseen(hasUnseen); } }
37.72
102
0.706105
59bfcfaa8dfb4c06fc225e187e2359143f360057
5,154
package eu.bcvsolutions.idm.vs.event.processor; import java.util.List; import java.util.Objects; import org.apache.commons.codec.binary.StringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import eu.bcvsolutions.idm.vs.TestHelper; import eu.bcvsolutions.idm.vs.entity.VsAccount; import eu.bcvsolutions.idm.vs.service.api.VsSystemService; import eu.bcvsolutions.idm.acc.dto.SysSystemDto; import eu.bcvsolutions.idm.acc.event.SystemEvent; import eu.bcvsolutions.idm.acc.event.SystemEvent.SystemEventType; import eu.bcvsolutions.idm.acc.service.api.SysSystemService; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto; import eu.bcvsolutions.idm.core.eav.api.service.FormService; import eu.bcvsolutions.idm.test.api.AbstractIntegrationTest; /** * VS specific duplication processor test * * @author Ondrej Husnik * */ public class VsSpecificDuplicationProcessorIntegrationTest extends AbstractIntegrationTest { @Autowired private TestHelper helper; @Autowired private SysSystemService systemService; @Autowired private VsSystemService vsSystemService; @Autowired private FormService formService; @Before public void init() { loginAsAdmin(); } @After public void logout() { super.logout(); } @Test public void testVsConfigurationDuplication() { SysSystemDto origSystem = helper.createVirtualSystem(helper.createName()); EntityEvent<SysSystemDto> event = new SystemEvent(SystemEventType.DUPLICATE, origSystem); SysSystemDto newSystem = systemService.publish(event).getContent(); Assert.assertNotNull(newSystem); Assert.assertNotEquals(origSystem.getId(), newSystem.getId()); String type = VsAccount.class.getName(); String origKey = vsSystemService.createVsFormDefinitionKey(origSystem); String newKey = vsSystemService.createVsFormDefinitionKey(newSystem); IdmFormDefinitionDto origFormDef = formService.getDefinition(type, origKey); IdmFormDefinitionDto newFormDef = formService.getDefinition(type, newKey); Assert.assertNotNull(origFormDef); Assert.assertNotNull(newFormDef); Assert.assertNotEquals(origFormDef.getId(), newFormDef.getId()); Assert.assertTrue(compareFormDefinition(newFormDef, origFormDef)); List<IdmFormAttributeDto> origFormAttrs = formService.getAttributes(origFormDef); List<IdmFormAttributeDto> newFormAttrs = formService.getAttributes(newFormDef); Assert.assertEquals(origFormAttrs.size(), newFormAttrs.size()); Assert.assertTrue(compareFormAttributeLists(origFormAttrs, newFormAttrs)); } /** * Compare form definition if equivalent * @param def1 * @param def2 * @return */ private boolean compareFormDefinition(IdmFormDefinitionDto def1, IdmFormDefinitionDto def2) { return StringUtils.equals(def1.getType(), def2.getType()) && StringUtils.equals(def1.getDescription(), def2.getDescription()) && StringUtils.equals(def1.getModule(), def2.getModule()) && def1.isMain() == def2.isMain() && def1.isUnmodifiable() == def2.isUnmodifiable(); } /** * Compare lists of form attributes if equivalent * @param attrs1 * @param attrs2 * @return */ private boolean compareFormAttributeLists(List<IdmFormAttributeDto> attrs1, List<IdmFormAttributeDto> attrs2) { for (IdmFormAttributeDto attr1: attrs1) { boolean exists = attrs2.stream() .filter((attr2) -> {return compareFormAttribute(attr1, attr2);}) .count() != 0; if (!exists) { return false; } } return true; } /** * Form attribute comparison predicate * * @param attr1 * @param attr2 * @return */ private boolean compareFormAttribute(IdmFormAttributeDto attr1, IdmFormAttributeDto attr2) { return StringUtils.equals(attr1.getCode(), attr2.getCode()) && StringUtils.equals(attr1.getName(), attr2.getName()) && StringUtils.equals(attr1.getDescription(), attr2.getDescription()) && StringUtils.equals(attr1.getPlaceholder(), attr2.getPlaceholder()) && StringUtils.equals(attr1.getFaceType(), attr2.getFaceType()) && StringUtils.equals(attr1.getDefaultValue(), attr2.getDefaultValue()) && StringUtils.equals(attr1.getRegex(), attr2.getRegex()) && StringUtils.equals(attr1.getValidationMessage(), attr2.getValidationMessage()) && StringUtils.equals(attr1.getModule(), attr2.getModule()) && attr1.isMultiple() == attr2.isMultiple() && attr1.isRequired() == attr2.isRequired() && attr1.isReadonly() == attr2.isReadonly() && attr1.isConfidential() == attr2.isConfidential() && attr1.isUnmodifiable() == attr2.isUnmodifiable() && attr1.isUnique() == attr2.isUnique() && Objects.equals(attr1.getMin(), attr2.getMin()) && Objects.equals(attr1.getMax(), attr2.getMax()) && Objects.equals(attr1.getSeq(), attr2.getSeq()) && Objects.equals(attr1.getPersistentType(), attr2.getPersistentType()) && Objects.equals(attr1.getProperties().toMap(), attr2.getProperties().toMap()); } }
35.061224
112
0.752425
5e4bd2e40fed9fb235309b71c61fe01a75d04b4c
1,034
package com.github.czyzby.lml.parser.impl.attribute.building; import com.github.czyzby.lml.parser.LmlParser; import com.github.czyzby.lml.parser.impl.tag.builder.AlignedLmlActorBuilder; import com.github.czyzby.lml.parser.tag.LmlBuildingAttribute; import com.github.czyzby.lml.parser.tag.LmlTag; /** Allows to build widgets that need the horizontal or vertical setting in the constructor (especially since their * default style varies according to this setting). Expects a boolean. By default, mapped to "horizontal". * * @author MJ */ public class HorizontalLmlAttribute implements LmlBuildingAttribute<AlignedLmlActorBuilder> { @Override public Class<AlignedLmlActorBuilder> getBuilderType() { return AlignedLmlActorBuilder.class; } @Override public boolean process(final LmlParser parser, final LmlTag tag, final AlignedLmlActorBuilder builder, final String rawAttributeData) { builder.setHorizontal(parser.parseBoolean(rawAttributeData)); return FULLY_PARSED; } }
41.36
115
0.774662
38dad1754b55253f7525ddcd825b356d0e71e5cb
5,694
/* * This file is a component of thundr, a software library from 3wks. * Read more: http://www.3wks.com.au/thundr * Copyright (C) 2013 3wks, <[email protected]> * * 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.threewks.thundr.user.jpa; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.threewks.thundr.user.jpa.converter.DateConverter; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import javax.persistence.*; import java.util.*; @Entity @Table(name="user", indexes = {@Index(columnList = "username")}, uniqueConstraints = @UniqueConstraint(columnNames = "username")) public class User implements com.threewks.thundr.user.User { public static class Fields { public final static String Id = "id"; public final static String Username = "username"; public final static String Email = "email"; public final static String Created = "created"; public final static String LastLogin = "lastLogin"; private Fields() {} } /** * Default constructor for JPA/Hibernate only */ public User() { } @Id @Column(name = "user_id") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name="email") private String email; @Column(name="username") private String username; @Column(name="created") @Convert(converter = DateConverter.class) private DateTime created; @Column(name="last_login") @Convert(converter = DateConverter.class) private DateTime lastLogin; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "user_properties", joinColumns = @JoinColumn(name="user_id")) @MapKeyColumn(name="name") @Column(name = "value") private Map<String, String> properties = Maps.newHashMap(); @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name="user_role", joinColumns = @JoinColumn(name="user_id")) @Column(name="role_name") private Set<String> roles = Sets.newHashSet(); public User(String username, String email) { this.created = DateTime.now(DateTimeZone.UTC); this.username = username; this.email = email; } public Long getId() { return id; } @Override public String getUsername() { return username; } @Override public void setUsername(String username) { this.username = username; } @Override public void setEmail(String email) { this.email = email; } @Override public String getEmail() { return email; } @Override public Map<String, String> getProperties() { return Collections.unmodifiableMap(properties); } @Override public String getProperty(String property) { return properties.get(property); } @Override public void setProperty(String key, String value) { properties.put(key, value); } @Override public void removeProperty(String key) { properties.remove(key); } @Override public DateTime getCreated() { return created; } @Override public DateTime getLastLogin() { return lastLogin; } @Override public void setLastLogin(DateTime dateTime) { lastLogin = dateTime; } @Override public Set<String> getRoles() { return Collections.unmodifiableSet(roles); } @Override public void setRoles(Collection<String> roles) { this.roles = Sets.newHashSet(roles); } @Override public boolean hasRole(String role) { return roles.contains(role); } @Override public boolean hasRoles(String... roles) { return hasRoles(Arrays.asList(roles)); } @Override public boolean hasRoles(Collection<String> roles) { for (String role : roles) { if (!hasRole(role)) { return false; } } return true; } @Override public void addRole(String role) { roles.add(role); } @Override public void removeRole(String role) { roles.remove(role); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return new EqualsBuilder() .append(username, user.username) .append(email, user.email) .append(created, user.created) .append(lastLogin, user.lastLogin) .append(properties, user.properties) .append(roles, user.roles) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(username) .append(email) .append(created) .append(lastLogin) .append(properties) .append(roles) .toHashCode(); } }
26
89
0.626976
5665bcfa4a9e55d1f0b30f33bf9c7c9bd7d7a996
1,082
package io.github.bloodbitt.facecraft.init; import io.github.bloodbitt.facecraft.FaceCraft; import io.github.bloodbitt.facecraft.blocks.BaldFaceBlock; import io.github.bloodbitt.facecraft.blocks.FaceBlock; import io.github.bloodbitt.facecraft.blocks.FaceOre; import io.github.bloodbitt.facecraft.blocks.Oven; import net.minecraft.block.Block; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; public class ModBlocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, FaceCraft.MOD_ID); //blocks public static final RegistryObject<Block> FACE_BLOCK = BLOCKS.register("face_block", FaceBlock::new); public static final RegistryObject<Block> FACE_ORE = BLOCKS.register("face_ore", FaceOre::new); public static final RegistryObject<Block> OVEN = BLOCKS.register("oven", Oven::new); public static final RegistryObject<Block> BALD_FACE_BLOCK = BLOCKS.register("bald_face_block", BaldFaceBlock::new); }
43.28
123
0.808688
347a55037b56a976c0e565e50ae4d2b4b4254ff2
1,091
package P00_ShapesDrawing; public class Rectangle implements Drawable { private int height; private int width; public Rectangle(int height, int width) { this.height = height; this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } @Override public void draw() { for (int i = 0; i < this.getHeight(); i++) { System.out.print("*"); for (int j = 0; j < this.getWidth() - 1; j++) { System.out.print(" "); if (i == 0 || i == (this.height - 1)) { System.out.print("*"); }else { System.out.print(" "); } } System.out.print(" "); System.out.print("*"); System.out.println(); } } }
23.212766
60
0.444546
14fb43f5201ce2150d30d0a8319b5fddbc7fb77f
1,221
package com.zhzx.ims.mapper; import com.zhzx.ims.domain.CustomerInfo; import java.util.List; /** * 客户信息Mapper接口 * * @author kiver * @date 2019-12-04 */ public interface CustomerInfoMapper { /** * 查询客户信息 * * @param customerInfoId 客户信息ID * @return 客户信息 */ public CustomerInfo selectCustomerInfoById(Long customerInfoId); /** * 查询客户信息列表 * * @param customerInfo 客户信息 * @return 客户信息集合 */ public List<CustomerInfo> selectCustomerInfoList(CustomerInfo customerInfo); /** * 新增客户信息 * * @param customerInfo 客户信息 * @return 结果 */ public int insertCustomerInfo(CustomerInfo customerInfo); /** * 修改客户信息 * * @param customerInfo 客户信息 * @return 结果 */ public int updateCustomerInfo(CustomerInfo customerInfo); /** * 删除客户信息 * * @param customerInfoId 客户信息ID * @return 结果 */ public int deleteCustomerInfoById(Long customerInfoId); /** * 批量删除客户信息 * * @param customerInfoIds 需要删除的数据ID * @return 结果 */ public int deleteCustomerInfoByIds(String[] customerInfoIds); }
19.693548
81
0.580672
cd42f6d4049dbf721fdef046f6d625af1a0fa910
664
package com.readlearncode.lesson1.section2.subsection4; /** * Source code github.com/readlearncode * * @author Alex Theedom www.readlearncode.com * @version 1.0 */ public class PrimitiveWrapper { public static void main(String... args){ Integer score = new Integer(1_000_00); byte result = score.byteValue(); System.out.println(result); short lucky = Short.parseShort("777"); long lotto = Long.parseLong("2311234534"); Short luck = Short.valueOf("777"); Long lottery = Long.valueOf("2311234534"); Double price = new Double("5_300.45"); String cost = price.toString(); } }
23.714286
55
0.64006
ee7fcb9a3c66c4a92905f9038728edb19e23ec7f
2,585
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Day10 { public static void main(String[] args) { ArrayList<CodeLine> lineList; if (args.length >= 2) { lineList = parseDataFile(args[1]); } else { lineList = parseDataFile("Day10/Day10_Input.csv"); } System.out.println("Part 1 Answer: " + part1(lineList)); System.out.println("Part 2 Answer: " + part2(lineList)); } static public ArrayList<CodeLine> parseDataFile(String filePath) { ArrayList<CodeLine> lineList = new ArrayList<CodeLine>(); try { Scanner scanner = new Scanner(new File(filePath)); while (scanner.hasNextLine()) { lineList.add(new CodeLine(scanner.nextLine())); } } catch (FileNotFoundException e) { e.printStackTrace(); } return lineList; } /** * Part 1 of Day 10 Challenge. * * @param lineList List of code line objects containing the parsed data from the * input file. * @return The answer for part 1. */ static public int part1(ArrayList<CodeLine> lineList) { int total = 0; for (CodeLine line : lineList) { CodeLine.Bracket returnedResult = line.findCurroptedBracket(); if (returnedResult != null) { total += returnedResult.getCorruptedScore(); } } return total; } /** * Part 2 of Day 10 Challenge. * * @param lineList List of code line objects containing the parsed data from the * input file. * @return The answer for part 2. */ static public long part2(ArrayList<CodeLine> lineList) { ArrayList<Long> totals = new ArrayList<Long>(); for (CodeLine line : lineList) { CodeLine.Bracket returnedResult = line.findCurroptedBracket(); if (returnedResult == null) { ArrayList<CodeLine.Bracket> missingBrackets = line.findMissingBrackets(); long total = 0; for (CodeLine.Bracket bracket : missingBrackets) { total *= 5; total += bracket.getIncompleteScore(); } totals.add(Long.valueOf(total)); } } Collections.sort(totals); int index = Math.floorDiv(totals.size(), 2); return totals.get(index); } }
29.375
89
0.566731
2b3226c21ddd7a340b56c6dec8202a033ae19d6d
1,976
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.atlas.impala.model; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * This represents optional metadata in Impala's lineage vertex entity. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class LineageVertexMetadata { // specify the name of the table private String tableName; // the create time of the table. Its unit is in seconds. private Long tableCreateTime; public String getTableName() { return tableName; } public Long getTableCreateTime() { return tableCreateTime; } public void setTableName(String tableName) { this.tableName = tableName; } public void setTableCreateTime(Long createTime) { this.tableCreateTime = createTime; } }
40.326531
97
0.779858
12934534b3381b36719af7bf400a1309040ce9aa
2,745
/* * Copyright (c) 2017 Tran Le Duy * * 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.duy.ide.themefont.activities; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.duy.ide.R; import com.duy.ide.activities.AbstractAppCompatActivity; import com.duy.ide.themefont.adapter.SectionPageAdapter; import com.duy.ide.themefont.themes.ThemeFragment; import com.google.firebase.analytics.FirebaseAnalytics; /** * Created by Duy on 12-Mar-17. */ @SuppressWarnings("DefaultFileTemplate") public class ThemeFontActivity extends AbstractAppCompatActivity implements ThemeFragment.OnThemeSelectListener { private Toolbar toolbar; private ViewPager viewPager; private SectionPageAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_theme_font); toolbar = (Toolbar) findViewById(R.id.toolbar); setupToolbar(); FirebaseAnalytics.getInstance(this).logEvent("open_choose_font_theme", new Bundle()); viewPager = (ViewPager) findViewById(R.id.view_pager); adapter = new SectionPageAdapter(getSupportFragmentManager(), this); viewPager.setAdapter(adapter); viewPager.setOffscreenPageLimit(3); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager); } public void setupToolbar() { setSupportActionBar(toolbar); setTitle(R.string.theme); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } @Override public void onThemeSelect(String name) { } }
30.164835
93
0.726776
efe0485d05ff16504edb3e544e625905b665ea5a
795
package com.ps.repos.impl; import com.ps.ents.User; import com.ps.repos.UserRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.util.Set; /** * Created by iuliana.cosmina on 3/21/16. */ @Repository("userRepo") public class JdbcUserRepo extends JdbcAbstractRepo<User> implements UserRepo { @Autowired public JdbcUserRepo(JdbcTemplate jdbcTemplate) { super(jdbcTemplate); } @Override public Set<User> findAllByUserName(String username, boolean exactMatch) { return null; } @Override public Set<User> findByRating(double startRating, double endRating) { return null; } }
24.090909
78
0.737107
41d26a4dcc090e663cf80238eec1b4ed179de676
277
package com.example.springboot.mapper; import com.example.springboot.entity.Menu; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author zengzl * @since 2022-03-23 */ public interface MenuMapper extends BaseMapper<Menu> { }
16.294118
55
0.714801
b88c4f2333a448e0998ca12dd42289cf949b3666
2,174
/** * Copyright © 2017 Jeremy Custenborder ([email protected]) * * 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.github.jcustenborder.kafka.serialization.jackson; import com.google.common.collect.ImmutableMap; import org.apache.kafka.common.serialization.Serde; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class JacksonSerdeTest { @Test public void of() { Serde<TestPojo> serde = JacksonSerde.of(TestPojo.class); serde.configure(ImmutableMap.of(), false); TestPojo expected = new TestPojo(); expected.firstName = "first"; expected.lastName = "last"; byte[] buffer = serde.serializer().serialize("topic", expected); TestPojo actual = serde.deserializer().deserialize("topic", buffer); assertNotNull(actual); assertEquals(expected.firstName, expected.firstName); assertEquals(expected.lastName, expected.lastName); serde.close(); } @Test public void configured() { Serde<TestPojo> serde = new JacksonSerde<>(); serde.configure(ImmutableMap.of( JacksonDeserializerConfig.OUTPUT_CLASS_CONFIG, TestPojo.class.getName() ), false); TestPojo expected = new TestPojo(); expected.firstName = "first"; expected.lastName = "last"; byte[] buffer = serde.serializer().serialize("topic", expected); TestPojo actual = serde.deserializer().deserialize("topic", buffer); assertNotNull(actual); assertEquals(expected.firstName, expected.firstName); assertEquals(expected.lastName, expected.lastName); serde.close(); } }
34.507937
79
0.731371
ee63075d41088f3dff87cdf4207a2fc8d79c9961
20,699
/** * */ package com.github.jearls.SPRaceTracker.ui; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import javax.swing.GroupLayout; import javax.swing.InputVerifier; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.text.NavigationFilter; import javax.swing.text.Position.Bias; /** * <p> * This presents a dialog box to choose the database directory for the * SPRaceTracker data store. The dialog box allows a directory name to be * entered - but forces the last component (specified in the * chooseDatabaseDirectory method as the "dbDirName") to be left unmodified. * There is also a button to bring up a directory file chooser dialog to locate * the parent of the database directory. * </p> * <p> * Sample usage is: * </p> * * <pre> * File dbDir = * DatabaseDirectoryChooser.chooseDatabaseDirectory(&quot;DatabaseDirectory&quot;); * if (dbDir == null) { * System.err.println(&quot;Cancelled by user&quot;); * } else { * System.err.println(&quot;User chose: &quot; + dbDir.getAbsolutePath()); * } * </pre> * * @author jearls * */ /** * @author jearls * */ public class DatabaseDirectoryChooser extends JDialog implements ActionListener { public static final long serialVersionUID = 1L; /** * This filter ensures that the caret in the text field is never allowed to * enter the final component of the directory name. * * @author jearls * */ class DirectoryNavigationFilter extends NavigationFilter { JTextField inputField; public DirectoryNavigationFilter(JTextField inputField) { this.inputField = inputField; } /** * Ensures that the caret ("dot") is not moved beyond the final * occurrence of the file separator. * * @see javax.swing.text.NavigationFilter#setDot(javax.swing.text.NavigationFilter.FilterBypass, * int, javax.swing.text.Position.Bias) */ @Override public void setDot(FilterBypass fb, int dot, Bias bias) { String path = inputField.getText(); int inviolateSection = path.lastIndexOf(File.separator); if (dot > inviolateSection) dot = inviolateSection; super.setDot(fb, dot, bias); } /** * Ensures that the caret ("dot") is not moved beyond the final * occurrence of the file separator. * * @see javax.swing.text.NavigationFilter#moveDot(javax.swing.text.NavigationFilter.FilterBypass, * int, javax.swing.text.Position.Bias) */ @Override public void moveDot(FilterBypass fb, int dot, Bias bias) { String path = inputField.getText(); int inviolateSection = path.lastIndexOf(File.separator); if (dot > inviolateSection) dot = inviolateSection; super.moveDot(fb, dot, bias); } } /** * The verifier for the full directory name. Ensures that the parent * directory exists and that the final component of the path does not. When * verified, this also leaves the File to the full path behind in the public * fullPath variable. * * @author jearls * */ class DirectoryVerifier extends InputVerifier { /** * The full path as verified. */ public File fullPath; /** * The component in which to report verification failures */ public JLabel status; public DirectoryVerifier(JLabel status) { super(); this.status = status; } /** * Verifies that the JTextField input records a path whose parent * directory exists. * * @param input * The JTextField input holding the directory name * @return true if the parent directory is valid. * @see javax.swing.InputVerifier#verify(javax.swing.JComponent) */ @Override public boolean verify(JComponent input) { return verify(input, false); } /** * Verifies that the JTextField input records a path whose parent * directory exists. If fullPathMustNotExist is true, then also verifies * that the full path does not exist. * * @param input * The JTextField input holding the directory name * @param fullPathMustNotExist * If false, only checks the parent directory. If true, also * checks that the full path does not exist. * @return true if the parent directory is valid and, if * fullPathMustNotExist is true, that the full path does not * exist. */ public boolean verify(JComponent input, boolean fullPathMustNotExist) { fullPath = new File(((JTextField) input).getText()); if (!fullPath.getParentFile().isDirectory()) { status.setText(fullPath.getParentFile().toString() + " does not exist."); return false; } else if (fullPathMustNotExist && fullPath.exists()) { status.setText(fullPath.toString() + " already exists."); return false; } return true; } } class EscapeOrEnterKeyListener extends KeyAdapter { JButton invokedOnEnter; JButton invokedOnEscape; public EscapeOrEnterKeyListener(JButton invokedOnEnter, JButton invokedOnEscape) { super(); this.invokedOnEnter = invokedOnEnter; this.invokedOnEscape = invokedOnEscape; } @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) { invokedOnEscape.doClick(); } else if (e.getKeyChar() == KeyEvent.VK_ENTER) { invokedOnEnter.doClick(); } else { super.keyPressed(e); } } } /* convenience constants for later. these should be i18n'd and l10n'd */ static final String chooseButtonText = "Browse"; static final String okButtonText = "OK"; static final String useExistingButtonText = "Use Existing"; static final String cancelButtonText = "Cancel"; static final String directoryLabelText = "Database Directory:"; static final String instructionLabelText = "<html><p>Choose the directory which will hold the database. The last portion of the database path (&quot;.../" + "%1$s" + "&quot;) cannot be modified.</p><p>Alternately, use the " + chooseButtonText + " button to bring up a directory selection dialog where you can choose in which directory the &quot;" + "%1$s" + "&quot; database directory will be created</p></html>"; static final String fileChooserTitle = "Choose where to create the \"%1$s\" directory"; /* the UI components and assistant classes */ JButton chooseButton = null; JButton okButton = null; JButton useExistingButton = null; JButton cancelButton = null; JTextField directoryEntry = null; DirectoryVerifier directoryVerifier = null; /* The dialog components */ String dbDirName; public File dbDir; /** * Creates a new DatabaseDirectoryChooser dialog and displays it as a modal * dialog. * * @param dbDirName * The last component of the database directory, which is fixed * and cannot be changed by the user. * @param defaultParentDir * The default parent directory which will contain the * "dbDirName" directory. */ public DatabaseDirectoryChooser(String dbDirName, File defaultParentDir) { // initialize the basic JDialog super(); // verify that the dbDirName is a valid name try { new File(dbDirName).getCanonicalFile(); if (dbDirName.indexOf(File.separator) > -1) { throw new IOException(); } } catch (IOException e) { throw new IllegalArgumentException("Invalid dbDirName \"" + dbDirName + "\""); } // save the constructor parameters this.dbDirName = dbDirName; this.dbDir = defaultParentDir; // everything else gets put into a different method, in case I need // multiple constructors setupUI(); } /** * Creates a new DatabaseDirectoryChooser dialog and displays it as a modal * dialog. Defaults to the user's home directory, or "." if the user's home * directory cannot be determined. * * @param dbDirName * The last component of the database directory, which is fixed * and cannot be changed by the user. */ public DatabaseDirectoryChooser(String dbDirName) { this(dbDirName, new File(System.getProperty("user.home", "."))); } /** * Set up the dialog box components */ void setupUI() { // set my title setTitle("Choose where to create the \"" + dbDirName + "\" directory"); // make sure I'm a modal dialog setModal(true); // set the window close action to nothing setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // but catch the window closing event and have it invoke the cancel // button, if it exists. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); if (cancelButton == null) { e.getWindow().dispose(); } else { cancelButton.doClick(); } } }); // Create the individual components that will be added to the dialog JLabel instructionLabel = new JLabel(String.format(instructionLabelText, dbDirName)); JLabel directoryLabel = new JLabel(directoryLabelText); JLabel statusLabel = new JLabel(" "); // The buttons: Each button gets this class as an action listener, and // an EscapeOrEnterKeyListener to invoke that button on enter or the // cancel button on escape. // The cancel button must be created first, as it's used in the key // listeners for the rest. cancelButton = new JButton(cancelButtonText); cancelButton.addActionListener(this); cancelButton.addKeyListener(new EscapeOrEnterKeyListener(cancelButton, cancelButton)); okButton = new JButton(okButtonText); okButton.addActionListener(this); okButton.addKeyListener(new EscapeOrEnterKeyListener(okButton, cancelButton)); useExistingButton = new JButton(useExistingButtonText); useExistingButton.addActionListener(this); useExistingButton.addKeyListener(new EscapeOrEnterKeyListener( useExistingButton, cancelButton)); chooseButton = new JButton(chooseButtonText); chooseButton.addActionListener(this); chooseButton.addKeyListener(new EscapeOrEnterKeyListener(chooseButton, cancelButton)); // the text field is more complicated: it needs to have both the // escapeOrEnterKeyListener, as well as an input verifier and a // navigation filter to prevent the cursor from being placed in the // dbDirName portion of the path. directoryEntry = new JTextField(); directoryEntry.setColumns(40); directoryEntry.setText(dbDir.getAbsolutePath() + File.separator + dbDirName); directoryEntry.addKeyListener(new EscapeOrEnterKeyListener( useExistingButton, cancelButton)); directoryVerifier = new DirectoryVerifier(statusLabel); directoryEntry.setInputVerifier(directoryVerifier); directoryEntry.setNavigationFilter(new DirectoryNavigationFilter( directoryEntry)); // now we have to put this stuff together :P // whee, I get to learn about the GroupLayout manager GroupLayout gl = new GroupLayout(getContentPane()); getContentPane().setLayout(gl); gl.setAutoCreateContainerGaps(true); ; gl.setAutoCreateGaps(true); gl.setHorizontalGroup(gl .createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(instructionLabel) .addGroup( gl.createSequentialGroup().addComponent(directoryLabel) .addComponent(directoryEntry) .addComponent(chooseButton)) .addGroup( gl.createSequentialGroup().addComponent(cancelButton) .addComponent(okButton) .addComponent(useExistingButton)) .addComponent(statusLabel)); gl.setVerticalGroup(gl .createSequentialGroup() .addComponent(instructionLabel) .addGroup( gl.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(directoryLabel) .addComponent(directoryEntry) .addComponent(chooseButton)) .addGroup( gl.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton) .addComponent(useExistingButton)) .addComponent(statusLabel)); gl.linkSize(SwingConstants.HORIZONTAL, cancelButton, okButton, chooseButton); // pack the layout pack(); // center it on the screen DisplayMode dm = this.getGraphicsConfiguration().getDevice().getDisplayMode(); int screenWidth = dm.getWidth(); int screenHeight = dm.getHeight(); Dimension windowSize = getSize(); setLocation((screenWidth - windowSize.width) / 2, (screenHeight - windowSize.height) / 2); // and show it to run the dialog setVisible(true); } /** * <p> * Listens for button presses and takes action according to which button: * </p> * <dl> * <dt>cancelButton</dt> * <dd>Shows a confirmation dialog asking if the user really wants to exit.</dd> * <dt>okButton</dt> * <dd>Runs the verifier and, if it's okay, uses its verified file to record * into dbDir.</dd> * <dt>chooseButton</dt> * <dd>Creates the JFileChooser dialog and then transfers the resulting * information back into the ui components.</dd> * </dl> * * @param e * The ActionEvent triggered by the button press. * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { if (e.getSource() == cancelButton) { // use a confirmation dialog to make sure the user really wants to // exit int response = JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?", "Are you sure you want to exit?", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) { // set the dbDir to null to indicate the dialog was cancelled this.dbDir = null; // dispose the dialog this.dispose(); } } else if (e.getSource() == okButton) { // use the directory verifier to make sure we're valid. For this // verification, the full path must not exist. if (directoryVerifier.verify(directoryEntry, true)) { // save the verified directory file this.dbDir = directoryVerifier.fullPath; // and dispose the dialog this.dispose(); } } else if (e.getSource() == useExistingButton) { // use the directory verifier to make sure we're valid. For this // verification, we don't check the full path. if (directoryVerifier.verify(directoryEntry, false)) { // save the verified directory file this.dbDir = directoryVerifier.fullPath; // and dispose the dialog this.dispose(); } } else if (e.getSource() == chooseButton) { // create the JFileChooser dialog JFileChooser fc = new JFileChooser(); fc.setDialogTitle(String.format(fileChooserTitle, dbDirName)); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setCurrentDirectory(dbDir); // bring up the dialog int response = fc.showSaveDialog(this); // if the user approved the selection, copy the information back to // the ui components if (response == JFileChooser.APPROVE_OPTION) { dbDir = fc.getSelectedFile(); if (dbDir.getName().equals(dbDirName)) { directoryEntry.setText(dbDir.getAbsolutePath()); } else { directoryEntry.setText(dbDir.getAbsolutePath() + File.separator + dbDirName); } directoryEntry.requestFocusInWindow(); directoryEntry.setCaretPosition(directoryEntry.getText() .length()); } } } /** * A convenience function that creates the dialog and returns the resulting * dbDir File. * * @param dbDirName * The database directory name that will be created. * @param defaultDir * The default directory in which the database directory will be * created. * @return the dbDir File. */ public static File chooseDatabaseDirectory(String dbDirName, File defaultDir) { DatabaseDirectoryChooser dialog = new DatabaseDirectoryChooser(dbDirName, defaultDir); return dialog.dbDir; } /** * A convenience function that creates the dialog and returns the resulting * dbDir File. The default parent directory is either the user's home * directory or, if that cannot be determined, the current directory when * the application was started. * * @param dbDirName * The database directory name that will be created. * @return the dbDir File. */ public static File chooseDatabaseDirectory(String dbDirName) { DatabaseDirectoryChooser dialog = new DatabaseDirectoryChooser(dbDirName); return dialog.dbDir; } }
41.731855
167
0.570414
091fabee78586c25fc60a16bcae3f90ff7fa61d8
937
package com.yolosh.android.model; public class CollectionObject { private String urlImage; private int imageId; private String likeNumber; private String ViewNumber; public CollectionObject(String urlImage, int imageId, String likeNumber, String viewNumber) { super(); this.urlImage = urlImage; this.imageId = imageId; this.likeNumber = likeNumber; this.ViewNumber = viewNumber; } public String getUrlImage() { return urlImage; } public void setUrlImage(String urlImage) { this.urlImage = urlImage; } public int getImageId() { return imageId; } public void setImageId(int imageId) { this.imageId = imageId; } public String getLikeNumber() { return likeNumber; } public void setLikeNumber(String likeNumber) { this.likeNumber = likeNumber; } public String getViewNumber() { return ViewNumber; } public void setViewNumber(String viewNumber) { this.ViewNumber = viewNumber; } }
18.372549
73
0.734258
4727dd80d0835420f286ad24a3c328a364864f49
3,407
/* * Latke - 一款以 JSON 为主的 Java Web 框架 * Copyright (c) 2009-present, b3log.org * * Latke is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.b3log.latke.cache.redis; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.b3log.latke.Latkes; import org.b3log.latke.util.CollectionUtils; import redis.clients.jedis.*; import java.util.Set; /** * Redis connection utilities. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.1.0.1, Dec 9, 2019 * @since 2.3.13 */ public final class Connections { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Connections.class); /** * Pool. */ private static JedisPoolAbstract pool; static { try { final Latkes.RuntimeCache runtimeCache = Latkes.getRuntimeCache(); if (Latkes.RuntimeCache.REDIS == runtimeCache) { final JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); final int minConnCnt = Integer.parseInt(Latkes.getLocalProperty("redis.minConnCnt")); jedisPoolConfig.setMinIdle(minConnCnt); final int maxConnCnt = Integer.parseInt(Latkes.getLocalProperty("redis.maxConnCnt")); jedisPoolConfig.setMaxTotal(maxConnCnt); String password = Latkes.getLocalProperty("redis.password"); if (StringUtils.isBlank(password)) { password = null; } final long waitTime = Long.parseLong(Latkes.getLocalProperty("redis.waitTime")); jedisPoolConfig.setMaxWaitMillis(waitTime); final String masterName = Latkes.getLocalProperty("redis.master"); if (StringUtils.isNotBlank(masterName)) { final String[] sentinelArray = Latkes.getLocalProperty("redis.sentinels").split(","); final Set<String> sentinels = CollectionUtils.arrayToSet(sentinelArray); pool = new JedisSentinelPool(masterName, sentinels, jedisPoolConfig, password); } else { final String host = Latkes.getLocalProperty("redis.host"); final int port = Integer.parseInt(Latkes.getLocalProperty("redis.port")); pool = new JedisPool(jedisPoolConfig, host, port, Protocol.DEFAULT_TIMEOUT, password); } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Initializes redis connection pool failed", e); } } /** * Gets a jedis. * * @return jedis */ public static Jedis getJedis() { return pool.getResource(); } /** * Shutdowns pool. */ static void shutdown() { pool.close(); } /** * Private constructor. */ private Connections() { } }
35.123711
204
0.627532
57ef6425d99c11fe60ffc0633f4cc9da3bcdd7fc
931
package com.mongodb; public class BulkWriteUpsert { private final int index; private final Object id; public BulkWriteUpsert(int index, Object id) { this.index = index; this.id = id; } public int getIndex() { return index; } public Object getId() { return id; } public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } BulkWriteUpsert that = (BulkWriteUpsert)o; if (index != index) { return false; } if (!id.equals(id)) { return false; } return true; } public int hashCode() { int result = index; result = 31 * result + id.hashCode(); return result; } public String toString() { return "BulkWriteUpsert{index=" + index + ", id=" + id + '}'; } }
9.8
65
0.522019
35a62f174f27ad461aebbe85e1e847960c0b374a
158
package trabalhofinal.diego.nathan.otes06.udesc.trabalho_final_android.ui; public interface OnDirectorClickListener<T> { void onDirectorClick(T item); }
26.333333
74
0.816456
958cc12f0d8016b011977ad53de6fbeff920cae1
1,602
package io.dazraf.vertx.futures.filters; import java.util.function.Consumer; import io.dazraf.vertx.consumer.Consumer2; import io.dazraf.vertx.consumer.Consumer3; import io.dazraf.vertx.consumer.Consumer4; import io.dazraf.vertx.consumer.Consumer5; import io.dazraf.vertx.tuple.Tuple2; import io.dazraf.vertx.tuple.Tuple3; import io.dazraf.vertx.tuple.Tuple4; import io.dazraf.vertx.tuple.Tuple5; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /** * Filters the state of a Future for successful completion, calling a handler function */ public interface SuccessFilter<T> extends Handler<AsyncResult<T>> { static <T> SuccessFilter<T> success(Consumer<T> consumer) { return result -> { if (result.succeeded()) { consumer.accept(result.result()); } }; } static <T> Handler<AsyncResult<T>> success(Runnable runnable) { return success(result -> runnable.run()); } static <T1, T2> Handler<AsyncResult<Tuple2<T1, T2>>> success(Consumer2<T1, T2> consumer) { return success(tuple -> tuple.accept(consumer)); } static <T1, T2, T3> Handler<AsyncResult<Tuple3<T1, T2, T3>>> success(Consumer3<T1, T2, T3> consumer) { return success(tuple -> tuple.accept(consumer)); } static <T1, T2, T3, T4> Handler<AsyncResult<Tuple4<T1, T2, T3, T4>>> success(Consumer4<T1, T2, T3, T4> consumer) { return success(tuple -> tuple.accept(consumer)); } static <T1, T2, T3, T4, T5> Handler<AsyncResult<Tuple5<T1, T2, T3, T4, T5>>> success(Consumer5<T1, T2, T3, T4, T5> consumer) { return success(tuple -> tuple.accept(consumer)); } }
32.04
128
0.706617
b7eaec75581c7d511a92437322565df269ebf2ee
1,341
package com.hebaja.auction.model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; class PlayerTest { private Player player1; private Player player2; private Lot lot; @BeforeEach void init() { Auctioneer auctioneer = new Auctioneer("auctioneer", "[email protected]"); GroupPlayer groupPlayer = new GroupPlayer("group_test"); groupPlayer.setAuctioneer(auctioneer); player1 = new Player("player1", new BigDecimal("200.0"), groupPlayer); player2 = new Player("player2", new BigDecimal("100.0"), groupPlayer); lot = new Lot(); lot.setTitle("My Lot"); lot.setDescription("My lot description"); } @Test void playerBidShouldNotBeNullCasePlayerHasEnoughMoneyInWallet() { player1.getWallet().setMoney(new BigDecimal("200.0")); Bid bid = player1.makeBid(new BigDecimal("100.0"), lot); assertNotNull(bid); } @Test void playerBidShouldBeNullCasePlayerHasNotEnoughMoneyInWallet() { player2.getWallet().setMoney(new BigDecimal("100.0")); Bid bid = player2.makeBid(new BigDecimal("200.0"), lot); assertNull(bid); } }
29.8
78
0.683072
cc9fada10db5d6f77aa115991df89d9a42801dce
195
package com.windea.java.annotation; import java.lang.annotation.*; /** * 已测试的代码的注解。 */ @Documented @Retention(RetentionPolicy.SOURCE) public @interface Tested { String value() default ""; }
15
35
0.728205
a7fc18afa5c7c2a035d63735684b3c0aa16e1fcc
362
package com.example.vidbregar.bluepodcast.dagger.provider; import com.example.vidbregar.bluepodcast.ui.main.favorites.FavoritesFragment; import dagger.Module; import dagger.android.ContributesAndroidInjector; @Module public abstract class FavoritesFragmentProvider { @ContributesAndroidInjector abstract FavoritesFragment bindFavoritesFragment(); }
24.133333
77
0.839779
2ca4ae6bce26e078bf4f28758ac7567a3a8c3753
363
package com.hyrax.microservice.project.rest.api.security; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component public class AuthenticationUserDetailsHelper { public String getUsername() { return SecurityContextHolder.getContext().getAuthentication().getName(); } }
27.923077
80
0.801653
5a881ffb4824fcc9d5e198d713575c303d829ad0
3,299
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.lacv.marketplatform.controllers.rest.process; import com.lacv.marketplatform.dtos.process.BasicResultDto; import com.lacv.marketplatform.entities.LogProcess; import com.lacv.marketplatform.entities.User; import com.lacv.marketplatform.services.LogProcessService; import com.lacv.marketplatform.services.UserService; import com.lacv.marketplatform.services.security.SecurityService; import com.dot.gcpbasedot.annotation.DoProcess; import com.dot.gcpbasedot.controller.RestProcessController; import com.lacv.marketplatform.dtos.process.ActivationProductPDto; import com.lacv.marketplatform.services.mail.MailingService; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author nalvarez */ @Controller @RequestMapping(value="/rest/processProduct") public class ProductProcessController extends RestProcessController { @Autowired UserService userService; @Autowired LogProcessService logProcessService; @Autowired SecurityService securityService; @Autowired MailingService mailingService; @PostConstruct public void init(){ super.addControlProcess("processProduct", LogProcess.class, logProcessService); } @Override public String getClientId(){ User user= securityService.getCurrentUser(); return user.getUsername(); } @DoProcess public BasicResultDto activarProducto(ActivationProductPDto activationProductPDto){ BasicResultDto result= new BasicResultDto(); Map<String, String> data= new HashMap<>(); data.put("nombreUsuario", activationProductPDto.getContactUser().getUserName()); data.put("correoUsuario", activationProductPDto.getContactUser().getMail()); data.put("numeroCelular", activationProductPDto.getContactUser().getCellPhone()); String comments= activationProductPDto.getContactUser().getComments(); comments+="<br><br><b>productId:</b> "+activationProductPDto.getProductId(); comments+="<br><br><b>productCode:</b> "+activationProductPDto.getProductCode(); comments+="<br><br><b>brand:</b> "+activationProductPDto.getBrand(); comments+="<br><br><b>registerDate:</b> "+activationProductPDto.getRegisterDate().toString(); data.put("comentarios", comments); boolean sent= mailingService.sendTemplateMail(activationProductPDto.getContactUser().getMail(), "contact_user", "Contacto de Usuario", data); result.setUsername(activationProductPDto.getContactUser().getMail()); result.setSuccess(sent); if(sent){ result.setMessage("Producto Activado Correctamente"); }else{ result.setMessage("Error al activar el Producto"); } return result; } }
37.488636
150
0.7087
ed6cad4935978c0e325423ed4c3546d52ba79f37
484
package com.frank.user.api.ip.ali.bean; import com.alibaba.fastjson.annotation.JSONField; public class FSIPResult { @JSONField(name="ret") private String ret; @JSONField(name="data") private FSIPData data; public String getRet() { return ret; } public void setRet(String ret) { this.ret = ret; } public FSIPData getData() { return data; } public void setData(FSIPData data) { this.data = data; } }
17.925926
49
0.613636
c1f43fb4ac211c010a57095d9f93d39742db8739
15,311
/** *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.gora.jet.generated; public class ResultPageView extends org.apache.gora.persistency.impl.PersistentBase implements org.apache.avro.specific.SpecificRecord, org.apache.gora.persistency.Persistent { public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ResultPageView\",\"namespace\":\"org.apache.gora.jet.generated\",\"fields\":[{\"name\":\"url\",\"type\":[\"null\",\"string\"],\"default\":null},{\"name\":\"timestamp\",\"type\":\"long\",\"default\":0},{\"name\":\"ip\",\"type\":[\"null\",\"string\"],\"default\":null}],\"default\":null}"); private static final long serialVersionUID = -7453871077431322534L; /** Enum containing all data bean's fields. */ public static enum Field { URL(0, "url"), TIMESTAMP(1, "timestamp"), IP(2, "ip"), ; /** * Field's index. */ private int index; /** * Field's name. */ private String name; /** * Field's constructor * @param index field's index. * @param name field's name. */ Field(int index, String name) {this.index=index;this.name=name;} /** * Gets field's index. * @return int field's index. */ public int getIndex() {return index;} /** * Gets field's name. * @return String field's name. */ public String getName() {return name;} /** * Gets field's attributes to string. * @return String field's attributes to string. */ public String toString() {return name;} }; public static final String[] _ALL_FIELDS = { "url", "timestamp", "ip", }; /** * Gets the total field count. * @return int field count */ public int getFieldsCount() { return ResultPageView._ALL_FIELDS.length; } private java.lang.CharSequence url; private long timestamp; private java.lang.CharSequence ip; public org.apache.avro.Schema getSchema() { return SCHEMA$; } // Used by DatumWriter. Applications should not call. public java.lang.Object get(int field$) { switch (field$) { case 0: return url; case 1: return timestamp; case 2: return ip; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } // Used by DatumReader. Applications should not call. @SuppressWarnings(value="unchecked") public void put(int field$, java.lang.Object value) { switch (field$) { case 0: url = (java.lang.CharSequence)(value); break; case 1: timestamp = (java.lang.Long)(value); break; case 2: ip = (java.lang.CharSequence)(value); break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } /** * Gets the value of the 'url' field. */ public java.lang.CharSequence getUrl() { return url; } /** * Sets the value of the 'url' field. * @param value the value to set. */ public void setUrl(java.lang.CharSequence value) { this.url = value; setDirty(0); } /** * Checks the dirty status of the 'url' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isUrlDirty() { return isDirty(0); } /** * Gets the value of the 'timestamp' field. */ public java.lang.Long getTimestamp() { return timestamp; } /** * Sets the value of the 'timestamp' field. * @param value the value to set. */ public void setTimestamp(java.lang.Long value) { this.timestamp = value; setDirty(1); } /** * Checks the dirty status of the 'timestamp' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isTimestampDirty() { return isDirty(1); } /** * Gets the value of the 'ip' field. */ public java.lang.CharSequence getIp() { return ip; } /** * Sets the value of the 'ip' field. * @param value the value to set. */ public void setIp(java.lang.CharSequence value) { this.ip = value; setDirty(2); } /** * Checks the dirty status of the 'ip' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isIpDirty() { return isDirty(2); } /** Creates a new ResultPageView RecordBuilder */ public static org.apache.gora.jet.generated.ResultPageView.Builder newBuilder() { return new org.apache.gora.jet.generated.ResultPageView.Builder(); } /** Creates a new ResultPageView RecordBuilder by copying an existing Builder */ public static org.apache.gora.jet.generated.ResultPageView.Builder newBuilder(org.apache.gora.jet.generated.ResultPageView.Builder other) { return new org.apache.gora.jet.generated.ResultPageView.Builder(other); } /** Creates a new ResultPageView RecordBuilder by copying an existing ResultPageView instance */ public static org.apache.gora.jet.generated.ResultPageView.Builder newBuilder(org.apache.gora.jet.generated.ResultPageView other) { return new org.apache.gora.jet.generated.ResultPageView.Builder(other); } @Override public org.apache.gora.jet.generated.ResultPageView clone() { return newBuilder(this).build(); } private static java.nio.ByteBuffer deepCopyToReadOnlyBuffer( java.nio.ByteBuffer input) { java.nio.ByteBuffer copy = java.nio.ByteBuffer.allocate(input.capacity()); int position = input.position(); input.reset(); int mark = input.position(); int limit = input.limit(); input.rewind(); input.limit(input.capacity()); copy.put(input); input.rewind(); copy.rewind(); input.position(mark); input.mark(); copy.position(mark); copy.mark(); input.position(position); copy.position(position); input.limit(limit); copy.limit(limit); return copy.asReadOnlyBuffer(); } /** * RecordBuilder for ResultPageView instances. */ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<ResultPageView> implements org.apache.avro.data.RecordBuilder<ResultPageView> { private java.lang.CharSequence url; private long timestamp; private java.lang.CharSequence ip; /** Creates a new Builder */ private Builder() { super(org.apache.gora.jet.generated.ResultPageView.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(org.apache.gora.jet.generated.ResultPageView.Builder other) { super(other); } /** Creates a Builder by copying an existing ResultPageView instance */ private Builder(org.apache.gora.jet.generated.ResultPageView other) { super(org.apache.gora.jet.generated.ResultPageView.SCHEMA$); if (isValidValue(fields()[0], other.url)) { this.url = (java.lang.CharSequence) data().deepCopy(fields()[0].schema(), other.url); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.timestamp)) { this.timestamp = (java.lang.Long) data().deepCopy(fields()[1].schema(), other.timestamp); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.ip)) { this.ip = (java.lang.CharSequence) data().deepCopy(fields()[2].schema(), other.ip); fieldSetFlags()[2] = true; } } /** Gets the value of the 'url' field */ public java.lang.CharSequence getUrl() { return url; } /** Sets the value of the 'url' field */ public org.apache.gora.jet.generated.ResultPageView.Builder setUrl(java.lang.CharSequence value) { validate(fields()[0], value); this.url = value; fieldSetFlags()[0] = true; return this; } /** Checks whether the 'url' field has been set */ public boolean hasUrl() { return fieldSetFlags()[0]; } /** Clears the value of the 'url' field */ public org.apache.gora.jet.generated.ResultPageView.Builder clearUrl() { url = null; fieldSetFlags()[0] = false; return this; } /** Gets the value of the 'timestamp' field */ public java.lang.Long getTimestamp() { return timestamp; } /** Sets the value of the 'timestamp' field */ public org.apache.gora.jet.generated.ResultPageView.Builder setTimestamp(long value) { validate(fields()[1], value); this.timestamp = value; fieldSetFlags()[1] = true; return this; } /** Checks whether the 'timestamp' field has been set */ public boolean hasTimestamp() { return fieldSetFlags()[1]; } /** Clears the value of the 'timestamp' field */ public org.apache.gora.jet.generated.ResultPageView.Builder clearTimestamp() { fieldSetFlags()[1] = false; return this; } /** Gets the value of the 'ip' field */ public java.lang.CharSequence getIp() { return ip; } /** Sets the value of the 'ip' field */ public org.apache.gora.jet.generated.ResultPageView.Builder setIp(java.lang.CharSequence value) { validate(fields()[2], value); this.ip = value; fieldSetFlags()[2] = true; return this; } /** Checks whether the 'ip' field has been set */ public boolean hasIp() { return fieldSetFlags()[2]; } /** Clears the value of the 'ip' field */ public org.apache.gora.jet.generated.ResultPageView.Builder clearIp() { ip = null; fieldSetFlags()[2] = false; return this; } @Override public ResultPageView build() { try { ResultPageView record = new ResultPageView(); record.url = fieldSetFlags()[0] ? this.url : (java.lang.CharSequence) defaultValue(fields()[0]); record.timestamp = fieldSetFlags()[1] ? this.timestamp : (java.lang.Long) defaultValue(fields()[1]); record.ip = fieldSetFlags()[2] ? this.ip : (java.lang.CharSequence) defaultValue(fields()[2]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } public ResultPageView.Tombstone getTombstone(){ return TOMBSTONE; } public ResultPageView newInstance(){ return newBuilder().build(); } private static final Tombstone TOMBSTONE = new Tombstone(); public static final class Tombstone extends ResultPageView implements org.apache.gora.persistency.Tombstone { private Tombstone() { } /** * Gets the value of the 'url' field. */ public java.lang.CharSequence getUrl() { throw new java.lang.UnsupportedOperationException("Get is not supported on tombstones"); } /** * Sets the value of the 'url' field. * @param value the value to set. */ public void setUrl(java.lang.CharSequence value) { throw new java.lang.UnsupportedOperationException("Set is not supported on tombstones"); } /** * Checks the dirty status of the 'url' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isUrlDirty() { throw new java.lang.UnsupportedOperationException("IsDirty is not supported on tombstones"); } /** * Gets the value of the 'timestamp' field. */ public java.lang.Long getTimestamp() { throw new java.lang.UnsupportedOperationException("Get is not supported on tombstones"); } /** * Sets the value of the 'timestamp' field. * @param value the value to set. */ public void setTimestamp(java.lang.Long value) { throw new java.lang.UnsupportedOperationException("Set is not supported on tombstones"); } /** * Checks the dirty status of the 'timestamp' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isTimestampDirty() { throw new java.lang.UnsupportedOperationException("IsDirty is not supported on tombstones"); } /** * Gets the value of the 'ip' field. */ public java.lang.CharSequence getIp() { throw new java.lang.UnsupportedOperationException("Get is not supported on tombstones"); } /** * Sets the value of the 'ip' field. * @param value the value to set. */ public void setIp(java.lang.CharSequence value) { throw new java.lang.UnsupportedOperationException("Set is not supported on tombstones"); } /** * Checks the dirty status of the 'ip' field. A field is dirty if it represents a change that has not yet been written to the database. * @param value the value to set. */ public boolean isIpDirty() { throw new java.lang.UnsupportedOperationException("IsDirty is not supported on tombstones"); } } private static final org.apache.avro.io.DatumWriter DATUM_WRITER$ = new org.apache.avro.specific.SpecificDatumWriter(SCHEMA$); private static final org.apache.avro.io.DatumReader DATUM_READER$ = new org.apache.avro.specific.SpecificDatumReader(SCHEMA$); /** * Writes AVRO data bean to output stream in the form of AVRO Binary encoding format. This will transform * AVRO data bean from its Java object form to it s serializable form. * * @param out java.io.ObjectOutput output stream to write data bean in serializable form */ @Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { out.write(super.getDirtyBytes().array()); DATUM_WRITER$.write(this, org.apache.avro.io.EncoderFactory.get() .directBinaryEncoder((java.io.OutputStream) out, null)); } /** * Reads AVRO data bean from input stream in it s AVRO Binary encoding format to Java object format. * This will transform AVRO data bean from it s serializable form to deserialized Java object form. * * @param in java.io.ObjectOutput input stream to read data bean in serializable form */ @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { byte[] __g__dirty = new byte[getFieldsCount()]; in.read(__g__dirty); super.setDirtyBytes(java.nio.ByteBuffer.wrap(__g__dirty)); DATUM_READER$.read(this, org.apache.avro.io.DecoderFactory.get() .directBinaryDecoder((java.io.InputStream) in, null)); } }
32.646055
418
0.658873
ad3f4a4bb8326a905e76e822ce0d56c034cd6e3f
1,794
package org.apache.catalina.ssi; import java.io.IOException; import java.io.PrintWriter; /** * Implements the Server-side #include command * * @author Bip Thelin * @author Paul Speed * @author Dan Sandberg * @author David Becker */ public final class SSIInclude implements SSICommand { /** * @see SSICommand */ @Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) { long lastModified = 0; String configErrMsg = ssiMediator.getConfigErrMsg(); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; String substitutedValue = ssiMediator .substituteVariables(paramValue); try { if (paramName.equalsIgnoreCase("file") || paramName.equalsIgnoreCase("virtual")) { boolean virtual = paramName.equalsIgnoreCase("virtual"); lastModified = ssiMediator.getFileLastModified( substitutedValue, virtual); String text = ssiMediator.getFileText(substitutedValue, virtual); writer.write(text); } else { ssiMediator.log("#include--Invalid attribute: " + paramName); writer.write(configErrMsg); } } catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); } } return lastModified; } }
35.176471
76
0.548495
0bd736c6171c08dbccc66d819cc1ba8be981a3a1
799
/** */ package org.eclipse.epf.uma.tests; import org.eclipse.epf.uma.VariabilityElement; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Variability Element</b></em>'. * <!-- end-user-doc --> * @generated */ public abstract class VariabilityElementTest extends MethodElementTest { /** * Constructs a new Variability Element test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public VariabilityElementTest(String name) { super(name); } /** * Returns the fixture for this Variability Element test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected VariabilityElement getFixture() { return (VariabilityElement)fixture; } } //VariabilityElementTest
21.594595
74
0.659574
eef69661fb7c994030637e03f071cf5ace689a20
1,671
package com.il360.xiaofeiyu.model.order; import java.io.Serializable; import java.math.BigDecimal; public class PayFeeOrder implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Integer payFeeId;//缴费订单id private Integer userId;//用户ID private String payFeeOrderNo;//缴费订单号 private Integer type;//1续费 2赎回 3超时缴费 private Integer stageId;//续费套餐id private BigDecimal fee;//费用金额 private Integer status;//0未缴费 1已缴费 private String createTime;//创建时间 private BigDecimal overFee;//超时费 public BigDecimal getOverFee() { return overFee; } public void setOverFee(BigDecimal overFee) { this.overFee = overFee; } public Integer getPayFeeId() { return payFeeId; } public void setPayFeeId(Integer payFeeId) { this.payFeeId = payFeeId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getPayFeeOrderNo() { return payFeeOrderNo; } public void setPayFeeOrderNo(String payFeeOrderNo) { this.payFeeOrderNo = payFeeOrderNo; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getStageId() { return stageId; } public void setStageId(Integer stageId) { this.stageId = stageId; } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } }
20.62963
53
0.728306
72a76634f51193486daf8ee4134a11cd9ffaa58e
16,853
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.welcome.wizard.deprecated; import static com.android.tools.idea.welcome.wizard.SdkComponentsStepKt.getDiskSpace; import static com.android.tools.idea.welcome.wizard.SdkComponentsStepKt.getTargetFilesystem; import static com.android.tools.idea.welcome.wizard.SdkComponentsStepKt.isExistingSdk; import static com.android.tools.idea.welcome.wizard.SdkComponentsStepKt.isNonEmptyNonSdk; import com.android.tools.adtui.validation.Validator; import com.android.tools.idea.ui.validation.validators.PathValidator; import com.android.tools.idea.welcome.config.FirstRunWizardMode; import com.android.tools.idea.welcome.install.ComponentTreeNode; import com.android.tools.idea.welcome.install.InstallableComponent; import com.android.tools.idea.welcome.wizard.WelcomeUiUtils; import com.android.tools.idea.wizard.WizardConstants; import com.android.tools.idea.wizard.dynamic.ScopedStateStore; import com.intellij.openapi.Disposable; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.JBLoadingPanel; import com.intellij.ui.table.JBTable; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.StartupUiUtil; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.accessibility.AccessibleContextDelegate; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.event.KeyEvent; import java.io.File; import java.util.Set; import javax.accessibility.AccessibleContext; import javax.swing.AbstractCellEditor; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Wizard page for selecting SDK components to download. * @deprecated use {@link com.android.tools.idea.welcome.wizard.SdkComponentsStep} */ @Deprecated public class SdkComponentsStep extends FirstRunWizardStep implements Disposable { @NotNull private final ComponentTreeNode myRootNode; @NotNull private final FirstRunWizardMode myMode; @NotNull private final ScopedStateStore.Key<Boolean> myKeyCustomInstall; private final ScopedStateStore.Key<String> mySdkDownloadPathKey; private final com.android.tools.idea.welcome.wizard.SdkComponentsStep.ComponentsTableModel myTableModel; private JPanel myContents; private JBTable myComponentsTable; private JTextPane myComponentDescription; private JLabel myNeededSpace; private JLabel myAvailableSpace; private JLabel myErrorMessage; private TextFieldWithBrowseButton myPath; @SuppressWarnings("unused") private JPanel myBody; private JBLoadingPanel myContentPanel; private boolean myUserEditedPath = false; private PathValidator.Result mySdkDirectoryValidationResult; private boolean myWasVisible = false; private boolean myLoading; public SdkComponentsStep(@NotNull ComponentTreeNode rootNode, @NotNull ScopedStateStore.Key<Boolean> keyCustomInstall, @NotNull ScopedStateStore.Key<String> sdkDownloadPathKey, @NotNull FirstRunWizardMode mode, @NotNull Disposable parent) { super("SDK Components Setup"); Disposer.register(parent, this); // Since we create and initialize a new AndroidSdkHandler/RepoManager for every (partial) // path that's entered, disallow direct editing of the path. myPath.setEditable(false); myRootNode = rootNode; myMode = mode; myKeyCustomInstall = keyCustomInstall; myPath.addBrowseFolderListener("Android SDK", "Select Android SDK install directory", null, FileChooserDescriptorFactory.createSingleFolderDescriptor()); mySdkDownloadPathKey = sdkDownloadPathKey; Font smallLabelFont = JBUI.Fonts.smallFont(); myNeededSpace.setFont(smallLabelFont); myAvailableSpace.setFont(smallLabelFont); myErrorMessage.setText(null); myTableModel = new com.android.tools.idea.welcome.wizard.SdkComponentsStep.ComponentsTableModel(rootNode); myComponentsTable.setModel(myTableModel); myComponentsTable.setTableHeader(null); myComponentsTable.getSelectionModel().addListSelectionListener(e -> { int row = myComponentsTable.getSelectedRow(); myComponentDescription.setText(row < 0 ? "" : myTableModel.getComponentDescription(row)); }); TableColumn column = myComponentsTable.getColumnModel().getColumn(0); column.setCellRenderer(new SdkComponentRenderer()); column.setCellEditor(new SdkComponentRenderer()); setComponent(myContents); } @Override public void dispose() {} public void startLoading() { myContentPanel.startLoading(); myLoading = true; invokeUpdate(null); } public void stopLoading() { myContentPanel.stopLoading(); myLoading = false; invokeUpdate(null); } public void loadingError() { myContentPanel.setLoadingText("Error loading components"); myLoading = false; invokeUpdate(null); } @Override public boolean validate() { @NotNull String path = StringUtil.notNullize(myState.get(mySdkDownloadPathKey)); if (!StringUtil.isEmpty(path)) { myUserEditedPath = true; } mySdkDirectoryValidationResult = PathValidator.forAndroidSdkLocation().validate(new File(path)); @NotNull Validator.Severity severity = mySdkDirectoryValidationResult.getSeverity(); boolean ok = severity == Validator.Severity.OK; @Nullable String message = ok ? null : mySdkDirectoryValidationResult.getMessage(); if (ok) { File filesystem = getTargetFilesystem(path); if (!(filesystem == null || filesystem.getFreeSpace() > getComponentsSize())) { severity = Validator.Severity.ERROR; message = "Target drive does not have enough free space."; } else if (isNonEmptyNonSdk(path)) { severity = Validator.Severity.WARNING; message = "Target folder is neither empty nor does it point to an existing SDK installation."; } else if (isExistingSdk(path)) { severity = Validator.Severity.WARNING; message = "An existing Android SDK was detected. The setup wizard will only download missing or outdated SDK components."; } } myErrorMessage.setIcon(severity.getIcon()); setErrorHtml(myUserEditedPath ? message : null); if (myLoading) { return false; } return mySdkDirectoryValidationResult.getSeverity() != Validator.Severity.ERROR; } @Override public void deriveValues(Set<? extends ScopedStateStore.Key> modified) { super.deriveValues(modified); String path = myState.get(mySdkDownloadPathKey); myAvailableSpace.setText(getDiskSpace(path)); long selected = getComponentsSize(); myNeededSpace.setText(String.format("Total download size: %s", WelcomeUiUtils.getSizeLabel(selected))); } private long getComponentsSize() { long size = 0; for (InstallableComponent component : myRootNode.getChildrenToInstall()) { size += component.getDownloadSize(); } return size; } @Override public void init() { register(mySdkDownloadPathKey, myPath); if (!myRootNode.getImmediateChildren().isEmpty()) { myComponentsTable.getSelectionModel().setSelectionInterval(0, 0); } } @NotNull @Override public JLabel getMessageLabel() { return myErrorMessage; } @Override public JComponent getPreferredFocusedComponent() { return myComponentsTable; } @Override public boolean isStepVisible() { if (myWasVisible) { // If we showed it once (e.g. if we had a invalid path on the standard setup path) we want to be sure it shows again (e.g. if we // fix the path and then go backward and forward). Otherwise the experience is confusing. return true; } else if (myMode.hasValidSdkLocation()) { return false; } if (myState.getNotNull(myKeyCustomInstall, true)) { myWasVisible = true; return true; } validate(); myWasVisible = mySdkDirectoryValidationResult.getSeverity() != Validator.Severity.OK; return myWasVisible; } private void createUIComponents() { Splitter splitter = new Splitter(false, 0.5f, 0.2f, 0.8f); myBody = splitter; myComponentsTable = new JBTable(); myComponentDescription = new JTextPane(); splitter.setShowDividerIcon(false); splitter.setShowDividerControls(false); myContentPanel = new JBLoadingPanel(new BorderLayout(), this); myContentPanel.add(myComponentsTable, BorderLayout.CENTER); splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myContentPanel, false)); splitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myComponentDescription, false)); myComponentDescription.setFont(StartupUiUtil.getLabelFont()); myComponentDescription.setEditable(false); myComponentDescription.setBorder(BorderFactory.createEmptyBorder(WizardConstants.STUDIO_WIZARD_INSET_SIZE, WizardConstants.STUDIO_WIZARD_INSET_SIZE, WizardConstants.STUDIO_WIZARD_INSET_SIZE, WizardConstants.STUDIO_WIZARD_INSET_SIZE)); } private final class SdkComponentRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor { private final RendererPanel myPanel; private final RendererCheckBox myCheckBox; private Border myEmptyBorder; SdkComponentRenderer() { myPanel = new RendererPanel(); myCheckBox = new RendererCheckBox(); myCheckBox.setOpaque(false); myCheckBox.addActionListener(e -> { if (myComponentsTable.isEditing()) { // Stop cell editing as soon as the SPACE key is pressed. This allows the SPACE key // to toggle the checkbox while allowing the other navigation keys to function as // soon as the toggle action is finished. // Note: This calls "setValueAt" on "myTableModel" automatically. stopCellEditing(); } else { // This happens when the "pressed" action is invoked programmatically through // accessibility, so we need to call "setValueAt" manually. myTableModel.setValueAt(myCheckBox.isSelected(), myCheckBox.getRow(), 0); } }); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setupControl(table, value, row, isSelected, hasFocus); return myPanel; } private void setupControl(JTable table, Object value, int row, boolean isSelected, boolean hasFocus) { myCheckBox.setRow(row); myPanel.setBorder(getCellBorder(table, isSelected && hasFocus)); Color foreground; Color background; if (isSelected) { background = table.getSelectionBackground(); foreground = table.getSelectionForeground(); } else { background = table.getBackground(); foreground = table.getForeground(); } myPanel.setBackground(background); myCheckBox.setForeground(foreground); myPanel.remove(myCheckBox); //noinspection unchecked Pair<ComponentTreeNode, Integer> pair = (Pair<ComponentTreeNode, Integer>)value; int indent = 0; if (pair != null) { ComponentTreeNode node = pair.getFirst(); myCheckBox.setEnabled(node.isEnabled()); myCheckBox.setText(node.getLabel()); myCheckBox.setSelected(node.isChecked()); indent = pair.getSecond(); } myPanel.add(myCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, indent * 2)); } private Border getCellBorder(JTable table, boolean isSelectedFocus) { Border focusedBorder = UIUtil.getTableFocusCellHighlightBorder(); Border border; if (isSelectedFocus) { border = focusedBorder; } else { if (myEmptyBorder == null) { myEmptyBorder = new EmptyBorder(focusedBorder.getBorderInsets(table)); } border = myEmptyBorder; } return border; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { setupControl(table, value, row, true, true); return myPanel; } @Override public Object getCellEditorValue() { return myCheckBox.isSelected(); } /** * A specialization of {@link JPanel} that provides complete accessibility support by * delegating most of its behavior to {@link #myCheckBox}. */ protected class RendererPanel extends JPanel { public RendererPanel() { super(new GridLayoutManager(1, 1)); } @Override protected void processKeyEvent(KeyEvent e) { if (myComponentsTable.isEditing()) { myCheckBox._processKeyEvent(e); } else { super.processKeyEvent(e); } } @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (myComponentsTable.isEditing()) { return myCheckBox._processKeyBinding(ks, e, condition, pressed); } else { return super.processKeyBinding(ks, e, condition, pressed); } } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleRendererPanel(); } return accessibleContext; } /** * Delegate accessible implementation to the embedded {@link #myCheckBox}. */ protected class AccessibleRendererPanel extends AccessibleContextDelegate { public AccessibleRendererPanel() { super(myCheckBox.getAccessibleContext()); } @Override protected Container getDelegateParent() { return RendererPanel.this.getParent(); } @Override public String getAccessibleDescription() { return myTableModel.getComponentDescription(myCheckBox.getRow()); } } } /** * A specialization of {@link JCheckBox} that provides keyboard friendly behavior * when contained inside {@link RendererPanel} inside a table cell editor. */ protected class RendererCheckBox extends JCheckBox { private int myRow; public int getRow() { return myRow; } public void setRow(int row) { myRow = row; } public boolean _processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { return super.processKeyBinding(ks, e, condition, pressed); } public void _processKeyEvent(KeyEvent e) { super.processKeyEvent(e); } @Override public void requestFocus() { // Ignore focus requests when editing cells. If we were to accept the focus request // the focus manager would move the focus to some other component when the checkbox // exits editing mode. if (myComponentsTable.isEditing()) { return; } super.requestFocus(); } } } }
37.203091
139
0.708183
b3973d03a4158109c4427b8a8a3be82dac1a4606
4,144
package artisynth.tools.rotation; import maspack.matrix.Point3d; import maspack.matrix.Vector3d; import artisynth.core.mechmodels.Frame; import artisynth.core.modelbase.MonitorBase; import artisynth.core.util.TimeBase; import artisynth.tools.rotation.RotationAxis.AxisValidity; public class Rotation2DComputer extends MonitorBase implements RotationAxisComputer { public static double DEFAULT_EPSILON = 1e-10; public static int DEFAULT_AVERAGE_POINTS = 10; public static double DEFAULT_UPDATE_RATE = 0; public double eps = DEFAULT_EPSILON; public int nAverage = DEFAULT_AVERAGE_POINTS; public double updateRate = DEFAULT_UPDATE_RATE; private static class Storage { public double t; public Vector3d w; public Point3d p; } int storageIdx=0; public Storage[] storage; public RotationAxis2D RA; boolean follow; // not yet implemented Frame myFrame = null; public Rotation2DComputer(Frame frame, Point3d pnt, Vector3d normal, int nAverage) { myFrame = frame; // initialize plane // RA = new PlaneIntersectionRotationAxis(normal, pnt); RA = new PlaneProjectionRotationAxis(normal, pnt); this.nAverage = nAverage; storage = new Storage[nAverage]; } public Rotation2DComputer (Frame frame, Point3d pnt, Vector3d normal) { this(frame, pnt, normal, DEFAULT_AVERAGE_POINTS); } public Frame getFrame() { return myFrame; } public void setNumAverage(int nAverage) { this.nAverage = nAverage; storage = new Storage[nAverage]; } public void apply(double t0, double t1) { if (updateRate <=0 || TimeBase.modulo(t0, updateRate)==0) { Vector3d w = myFrame.getVelocity().w; if (w.norm ()<eps) { RA.invalidate(); return; } Vector3d v0 = myFrame.getVelocity().v; Vector3d p0 = myFrame.getPosition(); Point3d icr_prev = new Point3d(); RA.getICR(icr_prev); RA.compute (w, v0, p0); // store information Storage storeThis = new Storage(); storeThis.p = new Point3d(); RA.getICR(storeThis.p); storeThis.t = t0; storeThis.w = new Vector3d(w); storage[storageIdx] = storeThis; storageIdx = (storageIdx+1) % nAverage; } } public void setUpdateRate(double rate) { updateRate = rate; } public double getUpdateRate() { return updateRate; } public void setThreshold(double epsilon) { eps = epsilon; } public AxisValidity getRotationAxis(Vector3d axis, Point3d pnt) { RA.getDirection (axis); return RA.getICR (pnt); } /** * Returns time of estimated CoR * @param pnt average CoR based on nAverage time steps * @return the time of the CoR, which is the mean simulation time * for which we have stored values */ public double getAverageCoR(Point3d pnt) { double wTotal = 0; double minT = Double.POSITIVE_INFINITY; double maxT = 0; Point3d cor = new Point3d(); Point3d pMax = cor; double wMax = 0; for (int i=0; i<storage.length; i++) { if (storage[i] != null) { if (storage[i].t < minT) { minT = storage[i].t; } else if (storage[i].t > maxT) { maxT = storage[i].t; } double w = storage[i].w.norm(); if (w > wMax) { wMax = w; pMax = storage[i].p; } wTotal += w; cor.scaledAdd(w, storage[i].p); // System.out.println("w: " + w + ", p: " + storage[i].p.toString()); } } if (wTotal < eps) { cor.set(pMax); } else { cor.scale(1.0/wTotal); } double t = (maxT+minT)/2; // mean time pnt.set(cor); return t; } public RotationAxis getRotationAxis() { return RA; } }
25.73913
87
0.574566
76b9e6144644a81b46683a315dc8ebb7f2f5a050
1,474
/* * Mckoi Software ( http://www.mckoi.com/ ) * Copyright (C) 2000 - 2015 Diehl and Associates, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mckoi.network; /** * A status element of a block server in the network. * * @author Tobias Downer */ public class BlockServerElement { /** * The address of the block server. */ private final ServiceAddress address; /** * The status of the block server. */ private final String status; /** * Constructs the element. */ public BlockServerElement(ServiceAddress address, String status) { this.address = address; this.status = status; } /** * Returns the address of the block server. */ public ServiceAddress getAddress() { return address; } /** * Returns true if the status report of the server from this element says * that the server is UP. */ public boolean isStatusUp() { return status.startsWith("U"); } }
23.774194
75
0.683853
73222ae6493fa886db096e0eacf3a948c2cb79dc
6,787
/* *BSD 2-Clause License * *Copyright (c) 2019, itinordic All rights reserved. * *Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following *conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 2. 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 ca.uhn.fhir.jpa.starter.util2; import ca.uhn.fhir.rest.api.QualifiedParamList; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.ParameterUtil; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.interceptor.auth.AuthorizedList; import ca.uhn.fhir.rest.server.interceptor.auth.SearchNarrowingInterceptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections4.ListUtils; import org.hl7.fhir.instance.model.Patient; /** * * @author developer */ public class DhisSearchNarrowingInterceptor extends SearchNarrowingInterceptor { @Override protected AuthorizedList buildAuthorizedList(RequestDetails theRequestDetails) { if ("Organization".equalsIgnoreCase(theRequestDetails.getResourceName())) { return new AuthorizedList().addResources( getRestrictedOrganizations(theRequestDetails).toArray(new String[0])); } return null; } @Override public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException { if (getAuthorizedUser(theRequestDetails).isAdmin()) { return true; } if (!super.incomingRequestPostProcessed(theRequestDetails, theRequest, theResponse)) { return false; } if (theRequestDetails.getRestOperationType() != RestOperationTypeEnum.SEARCH_TYPE) { return true; } final Map<String, List<String>> parameterToOrValues = new HashMap<>(); if ("Patient".equalsIgnoreCase(theRequestDetails.getResourceName())) { processReferencedResources(theRequestDetails, parameterToOrValues, Patient.SP_ORGANIZATION, getRestrictedOrganizations(theRequestDetails)); } if (!parameterToOrValues.isEmpty()) { theRequestDetails.setParameters(addReferencedResources(parameterToOrValues, new HashMap<>(theRequestDetails.getParameters()))); } return true; } @Nonnull private Map<String, String[]> addReferencedResources(@Nonnull Map<String, List<String>> parameterToOrValues, @Nonnull Map<String, String[]> newParameters) { parameterToOrValues.forEach((nextParamName, nextAllowedValues) -> { if (newParameters.containsKey(nextParamName)) { String[] existingValues = newParameters.get(nextParamName); boolean restrictedExistingList = false; for (int i = 0; i < existingValues.length; i++) { String nextExistingValue = existingValues[i]; List<String> nextRequestedValues = QualifiedParamList.splitQueryStringByCommasIgnoreEscape(null, nextExistingValue); List<String> nextPermittedValues = ListUtils.intersection(nextRequestedValues, nextAllowedValues); if (nextPermittedValues.size() > 0) { restrictedExistingList = true; existingValues[i] = ParameterUtil.escapeAndJoinOrList(nextPermittedValues); } } if (!restrictedExistingList) { String[] newValues = Arrays.copyOf(existingValues, existingValues.length + 1); newValues[existingValues.length] = ParameterUtil.escapeAndJoinOrList(nextAllowedValues); newParameters.put(nextParamName, newValues); } } else { String nextValuesJoined = ParameterUtil.escapeAndJoinOrList(nextAllowedValues); String[] paramValues = {nextValuesJoined}; newParameters.put(nextParamName, paramValues); } }); return newParameters; } private void processReferencedResources(@Nonnull RequestDetails requestDetails, @Nonnull Map<String, List<String>> parameterToOrValues, @Nonnull String searchParamName, @Nonnull Collection<String> resourceReferences) { if (!resourceReferences.isEmpty()) { final List<String> orValues = parameterToOrValues.computeIfAbsent(searchParamName, spn -> new ArrayList<>()); orValues.addAll(resourceReferences); } } @Nonnull private Collection<String> getRestrictedOrganizations(@Nonnull RequestDetails requestDetails) { final AuthorizedUser authorizedUser = getAuthorizedUser(requestDetails); return authorizedUser.getOrganizationIds().stream() .map(id -> "Organization/" + id).collect(Collectors.toList()); } @Nonnull private AuthorizedUser getAuthorizedUser(@Nonnull RequestDetails requestDetails) { final AuthorizedUser authorizedUser = (AuthorizedUser) requestDetails.getUserData().get(AuthorizedUser.ATTRIBUTE_NAME); if (authorizedUser == null) { throw new IllegalStateException("Authorized user has not been set."); } return authorizedUser; } }
44.94702
222
0.706498
3de65af0402c4b73dfaa7500114ccfa27a463137
541
// Copyright 2013 Square, Inc. package org.assertj.android.api.animation; import android.animation.Animator; import android.annotation.TargetApi; import static android.os.Build.VERSION_CODES.HONEYCOMB; /** * Assertions for {@link Animator} instances. * <p> * This class is final. To extend use {@link AbstractAnimatorAssert}. */ @TargetApi(HONEYCOMB) public final class AnimatorAssert extends AbstractAnimatorAssert<AnimatorAssert, Animator> { public AnimatorAssert(Animator actual) { super(actual, AnimatorAssert.class); } }
27.05
92
0.774492
af3485e79401e4885e3a28247c0892029191aeae
3,366
package com.secuconnect.demo.api_integration_of_smart_checkout; import com.secuconnect.client.ApiException; import com.secuconnect.client.Environment; import com.secuconnect.client.api.SmartTransactionsApi; import com.secuconnect.client.model.*; import com.secuconnect.demo.Globals; /** * API Integration of Smart Checkout * * Step 3: Get the details of a completed smart transaction * * @see <a href="https://developer.secuconnect.com/integration/API_Integration_of_Smart_Checkout.html">API Integration of Smart Checkout</a> */ public class Step3 { public static void main(String[] args) { try { // init env Environment.getGlobalEnv().setCredentials(Globals.O_AUTH_CLIENT_CREDENTIALS); // run api call SmartTransactionsProductModel response = new SmartTransactionsApi().getOne("STX_NPNF3464P2X4YJ5RABEHH3SGZJXWAH"); System.out.println(response.toString()); response.paymentInstructions(new PaymentInstructions()).id(""); /* * Sample output: * ============== * class SmartTransactionsProductModel { * class BaseProductModel { * object: smart.transactions * id: STX_NPNF3464P2X4YJ5RABEHH3SGZJXWAH * } * created: 2021-04-28T12:00:00+02:00 * updated: 2021-04-28T12:05:00+02:00 * status: received * customer: class PaymentCustomersProductModel { * class BaseProductModel { * object: payment.customers * id: PCU_WMZDQQSRF2X4YJ67G997YE8Y26XSAW * } * contact: class Contact { * forename: Max * surname: Muster * email: [email protected] * phone: +4912342134123 * address: class Address { * street: Kolumbastr. * streetNumber: 3TEST * city: Köln * postalCode: 50667 * country: DE * } * } * } * container: class SmartTransactionsContainer { * class ProductInstanceUID { * object: payment.containers * id: PCT_WCB4H23TW2X4YJ6Y8B7FD5N5MS8NA2 * } * type: bank_account * } * transId: 40015106 * paymentMethod: debit * transactions: [class PaymentTransactionsProductModel { * class BaseProductModel { * object: payment.transactions * id: PCI_WP7AEW23T2SMTJ0MCJTTXQ5002K8N6 * } * transId: 40015106 * transactionHash: qkglowlxxbyz4972791 * }] * ... * } */ } catch (ApiException e) { e.printStackTrace(); // show the error message from the api System.out.println("ERROR: " + e.getResponseBody()); } } }
40.071429
140
0.497623
3f9ac738da1b3c96c5a2e3c6657b9bee476d7fea
2,268
package com.akshatjain.codepath.tweeter.data; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; /** * Created by akshatjain on 8/4/16. */ @Parcel public class User { @SerializedName("id") public long id; @SerializedName("name") public String name; @SerializedName("favourites_count") public int likes; @SerializedName("screen_name") public String screenName; @SerializedName("description") public String description; @SerializedName("profile_image_url_https") public String profileImageUrl; @SerializedName("followers_count") public long followersCnt; @SerializedName("friends_count") public long friendsCnt; public User() { } public User(long id, String name, int likes, String screenName, String description, String profileImageUrl) { this.id = id; this.name = name; this.likes = likes; this.screenName = screenName; this.description = description; this.profileImageUrl = profileImageUrl; } public String getProfileImageUrl() { return profileImageUrl; } public void setProfileImageUrl(String profileImageUrl) { this.profileImageUrl = profileImageUrl; } public String getScreenName() { return screenName; } public void setScreenName(String screenName) { this.screenName = screenName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getId() { return id; } public void setId(long id) { this.id = id; } @Override public String toString() { return "User{" + "name='" + name + '\'' + // ", likes=" + likes + // ", description='" + description + '\'' + ", screen name='" + screenName +'\'' + '}'; } }
21
113
0.601852
45930520a66381fde4f6b2485958c0d88188db56
184
package ru.iopump.qa.allure.entity; import org.junit.Test; public class ReportEntityTest { @Test public void sizeKB() { } @Test public void checkUrl() { } }
13.142857
35
0.630435
4f47e0baa0c4053bc06aef25c89e10e8f04ce3af
1,165
package AllClasses; import javafx.scene.layout.AnchorPane; import javafx.scene.shape.Rectangle; import java.util.ArrayList; public class Fight extends Rectangle { public static ArrayList<Fight> fights=new ArrayList<>(); public static ArrayList<FightAnimation> fightAnimations =new ArrayList<>(); public int index; AnchorPane anchorPane; public Fight(double v, double v1, double v2, double v3,AnchorPane anchorPane) { super(v-50,v1-50,200,200); this.anchorPane=anchorPane; fights.add(this); this.index=fights.size()-1; fightAnimations.add(new FightAnimation(this)); fightAnimations.get(fightAnimations.size()-1).play(); anchorPane.getChildren().add(this); } public void move(double dx,double dy) { this.setX(this.getX()+dx); this.setY(this.getY()+dy); } public void remove(Fight fight) { fights.remove(0); fightAnimations.get(0).stop(); fightAnimations.remove(0); anchorPane.getChildren().remove(fight); } public boolean hitRightWall(double x) { return x+85 >= 1100;} }
31.486486
84
0.642918
8cf50f550a6f4de620ca0054d953bbf42a447635
2,400
package com.cool.util; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.github.pagehelper.PageInfo; /** * 页面工具类 */ public class HtmlUtil { /** * * <br> * <b>功能:</b>输出json格式<br> * @param response * @param jsonStr * @throws Exception */ public static void writerJson(HttpServletResponse response, String jsonStr) { writer(response, jsonStr); } public static void writerJson(HttpServletResponse response, Object object) { try { response.setContentType("application/json;charset=UTF-8"); writer(response, JSON.toJSONString(object)); } catch (JSONException e) { e.printStackTrace(); } } public static void writerJson(HttpServletResponse response, PageInfo<?> pageList) { try { response.setContentType("application/json;charset=UTF-8"); Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("total", pageList.getTotal()); jsonMap.put("rows", pageList.getList()); writer(response, JSON.toJSONString(jsonMap)); } catch (JSONException e) { e.printStackTrace(); } } /** * * <br> * <b>功能:</b>输出HTML代码<br> * @param response * @param htmlStr * @throws Exception */ public static void writerHtml(HttpServletResponse response, String htmlStr) { writer(response, htmlStr); } private static void writer(HttpServletResponse response, String str) { try { //设置页面不缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = null; out = response.getWriter(); out.print(str); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } /** * * 写json数据 SPMS3.0 ADDED BY LWS 20160415 * * @param response * @param str */ public static void writeGson(HttpServletResponse response, Map<String, Object> contentMap) { PrintWriter out = null; try { //设置页面不缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("charset=UTF-8"); out = response.getWriter(); String content = JSON.toJSONString(contentMap); out.write(content); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
23.076923
93
0.685833
5c1fe0be2939fd8a5d73fbe75c706fd086184985
2,045
package beforeApril.firstDay; import java.util.HashMap; import java.util.HashSet; import java.util.Map; /** * Created by Alex_Xie on 12/01/2017. * Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. */ public class LongestPalindrome { public static int longestPalindrome(String s) { if (s.length() == 0) { return 0; } Map<Character, Integer> map = new HashMap<>(); int cnt = 0; for (Character ch: s.toCharArray()) { if (map.get(ch) == null ) { map.put(ch, 1); } else { map.put(ch, map.get(ch) +1); if (map.get(ch) %2 == 0) { cnt++; } } } // including "abcba", "abbd" two situation if (cnt == s.length()/2) { return s.length(); } else if (cnt != 0) { return cnt*2+1; } return 1; } public int longestPalindrome1(String s) { if(s==null || s.length()==0) return 0; HashSet<Character> hs = new HashSet<>(); int count = 0; for(int i = 0; i < s.length(); i++){ if(hs.contains(s.charAt(i))){ hs.remove(s.charAt(i)); count++; }else{ hs.add(s.charAt(i)); } } if(!hs.isEmpty()) { return count * 2 + 1; } return count * 2; } public static void main(String[] args) { System.out.println(longestPalindrome("abccccdd")); System.out.println(longestPalindrome("aabb")); System.out.println(longestPalindrome("bb")); } }
23.505747
146
0.526161
0ba556f322fd649906fc8beb0b98c049bf6d2c05
200
package com.mit.community.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.mit.community.entity.ConfigInfo; public interface ConfigInfoMapper extends BaseMapper<ConfigInfo>{ }
22.222222
65
0.835
1dfba5fa3a9c11bad70361b557c1ce6e0b92595f
816
package handymods.block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockEnderBoxed extends BlockEnderBox { public BlockEnderBoxed() { super(); setBlockUnbreakable(); setResistance(1000F); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { return false; } @Override protected ItemStack getDroppedItem(IBlockAccess world, BlockPos pos) { return ItemStack.EMPTY; } }
27.2
171
0.792892
f2048e69c0bbed21b1c354698a1f42d6bfc24923
835
package chris.HackerRank; import java.util.Scanner; import java.util.stream.IntStream; public class HrPlusMinus { static void plusMinus(int[] arr) { double n = arr.length; long pos = IntStream.of(arr).filter(x -> x > 0).count(); long neg = IntStream.of(arr).filter(x -> x < 0).count(); long zero = IntStream.of(arr).filter(x -> x == 0).count(); System.out.printf("%1.6f\n", pos / n); System.out.printf("%1.6f\n", neg / n); System.out.printf("%1.6f\n", zero / n); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for (int arr_i = 0; arr_i < n; arr_i++) { arr[arr_i] = in.nextInt(); } plusMinus(arr); in.close(); } }
29.821429
66
0.542515
785aebe3790ae779b0279158fd86c4f9241619c7
6,080
package com.github.hinaser.gfma.browser; import com.github.hinaser.gfma.settings.ApplicationSettingsService; import com.github.hinaser.gfma.template.ErrorTemplate; import com.github.hinaser.gfma.template.MarkdownTemplate; import org.apache.commons.lang.exception.ExceptionUtils; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; public class MarkdownParsedAdapter implements MarkdownParsedListener { protected ApplicationSettingsService settings; protected IBrowser browser; protected String filename; public MarkdownParsedAdapter(IBrowser browser, String filename) { this.settings = ApplicationSettingsService.getInstance(); this.browser = browser; this.filename = filename; } public void setBrowser(IBrowser browser) { this.browser = browser; } public void setFilename(String filename) { this.filename = filename; } @Override public void onMarkdownParseDone(String html) { try { // If any html content is not loaded into the browser, load it. // Otherwise, set parsed markdown html via javascript for faster loading. if(!browser.isJsReady()) { MarkdownTemplate template = MarkdownTemplate.getInstance(); String appliedHtml = template.getGitHubFlavoredHtml(filename, html); /* * When load string html directly like below, non-ascii multi byte string will be converted to '?'(u+003F) * So instead of loadContent, create temporary html file encoded as UTF-8 and load that file to browser. */ // browser.loadContent(appliedHtml); File file = File.createTempFile("markdown", ".html"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); writer.write(appliedHtml); writer.close(); browser.loadFile(file); } else { String parser = settings.isUseGitHubMarkdownAPI() ? "GitHub Markdown API" : "Flexmark-java"; String accessTokenVerified = settings.getGitHubAccessToken().isEmpty() ? "not-set" : settings.isGitHubAccessTokenValid() ? "verified" : "invalid"; String rateLimit = !settings.isUseGitHubMarkdownAPI() ? "" : "X-RateLimit-Limit = " + settings.getRateLimitLimit().toString() + "\\n" + "X-RateLimit-Remaining = " + settings.getRateLimitRemaining().toString() + "\\n" + "X-RateLimit-Reset = " + settings.getRateLimitReset().toString() ; String showActiveParser = settings.isShowActiveParser() ? "true" : "false"; String isFallbackToOfflineParser = settings.isFallingBackToOfflineParser() ? "true" : "false"; // Escape emojis, quotations, new lines // @See https://github.com/Hinaser/gfm-advanced/issues/5 String escapedHtml = getEscapedHtmlString(html); String javascript = "" + "window.reloadHtml = function(){\n" + " document.getElementById('title').innerText = \"" + filename + "\";\n" + " document.querySelector('.markdown-body.entry-content').innerHTML = \"" + escapedHtml + "\";\n" + " document.querySelectorAll('pre code').forEach(function(block){\n" + " hljs.highlightBlock(block);\n" + " });\n" + " document.getElementById('gfmA-parser').innerText = \"" + parser + "\";\n" + " document.querySelectorAll('[data-gfmaparser]').forEach(function(el){\n" + " el.dataset.gfmaparser = \"" + parser + "\"\n;" + " });\n" + " document.querySelectorAll('[data-gfmaverified]').forEach(function(el){\n" + " el.dataset.gfmaverified = \"" + accessTokenVerified + "\"\n;" + " });\n" + " document.getElementById('gfmA-parser').title = \"" + rateLimit + "\";\n" + " document.getElementById('gfmA-show-active-parser').dataset.show = \"" + showActiveParser + "\";\n" + " document.getElementById('gfmA-fallback').dataset.gfmafallback = \"" + isFallbackToOfflineParser + "\";\n" + "};\n" + "reloadHtml();\n" ; browser.executeJavaScript(javascript); } } catch(Exception e) { onMarkdownParseFailed(e.getLocalizedMessage(), ExceptionUtils.getStackTrace(e)); } } public String getEscapedHtmlString(String html){ html = html.replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n"); StringBuilder escapedHtml = new StringBuilder(); for(int i=0; i<html.length(); i++){ int cp = html.codePointAt(i); // Handle emoji or character represented by surrogate pair. if(cp > 65535){ StringBuilder sb = new StringBuilder(); sb.append("&#"); sb.append(cp); sb.append(";"); escapedHtml.append(sb); i++; // It seems low surrogate value is included in `html.codePointAt(high_surrogate_index)`, so skip it. } else{ escapedHtml.appendCodePoint(cp); } } return escapedHtml.toString(); } @Override public void onMarkdownParseFailed(String errorMessage, String stackTrace) { ErrorTemplate template = ErrorTemplate.getInstance(); String errorHtml = template.getErrorHtml(errorMessage, stackTrace); browser.loadContent(errorHtml); } }
47.131783
134
0.567763
66ae6e588adca60ad46f01c2a518f6a0acb3e54e
2,012
package com.letv.core.parser; import com.letv.core.bean.TicketShowListBean; import com.sina.weibo.sdk.component.WidgetRequestParam; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; public class TicketShowListParser extends LetvMasterParser<TicketShowListBean> { protected boolean canParse(String data) { return true; } protected JSONObject getData(String data) throws Exception { return new JSONObject(data); } public TicketShowListBean parse(JSONObject data) throws Exception { int i; TicketShowListBean list = new TicketShowListBean(); if (data.has("code")) { list.code = getString(data, "code"); } if (data.has("ServletInfo")) { JSONObject servletInfo = data.getJSONObject("ServletInfo"); if (servletInfo.has(WidgetRequestParam.REQ_PARAM_COMMENT_CONTENT)) { JSONArray contentArray = servletInfo.getJSONArray(WidgetRequestParam.REQ_PARAM_COMMENT_CONTENT); ArrayList<String> contentList = new ArrayList(); for (i = 0; i < contentArray.length(); i++) { contentList.add(contentArray.getString(i)); } list.content = contentList; } if (servletInfo.has("mobilePic")) { list.mobilePic = getString(servletInfo, "mobilePic"); } } if (has(data, "values")) { JSONObject values = getJSONObject(data, "values"); if (values.has("totalSize")) { list.totalSize = getString(values, "totalSize"); } if (values.has("ticketShows")) { JSONArray ticketShowsArray = getJSONArray(values, "ticketShows"); for (i = 0; i < ticketShowsArray.length(); i++) { list.add(new TicketShowParser().parse(ticketShowsArray.getJSONObject(i))); } } } return list; } }
37.962264
112
0.597416
3cb9804134bb3a87123386f4f766ecffb62a7177
175
package poussecafe.source.models.p214; import poussecafe.util.StringId; public class A2Id extends StringId { public A2Id(String value) { super(value); } }
14.583333
38
0.697143
4b2a754e499810dbe67cd093bbe76e76b6780ab8
478
package com.github.zuihou.gateway.feign; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * TODO 日志接口 待实现 * * @author zuihou * @createTime 2017-12-13 15:09 */ @FeignClient("zuihou-admin-server") public interface LogService { @RequestMapping(value = "/api/log/save", method = RequestMethod.POST) void saveLog(LogDto log); }
26.555556
73
0.763598
7288c1f56b3388c461e8c37ec782045a5e9064ea
999
package buildInPresets; import presets.AbstractMieParticlePreset; public class NaCLInAir extends AbstractMieParticlePreset { public NaCLInAir() { setName("NaCl in Air"); checkForWavelengthMismatch=false; //how to use wavelength sensitive refractive indices: refractiveIndexMedium.put(0.673, 1d); refractiveIndexMedium.put(0.818, 1d); refractiveIndexMedium.put(0.844, 1d); refractiveIndexMedium.put(1.313, 1d); refractiveIndexMedium.put(1.324, 1d); refractiveIndexSphereReal.put(0.673, 1.5397); refractiveIndexSphereReal.put(0.818, 1.5352); refractiveIndexSphereReal.put(0.844, 1.5346); refractiveIndexSphereReal.put(1.313, 1.5292); refractiveIndexSphereReal.put(1.324, 1.5292); refractiveIndexSphereImaginary.put(0.673, 0d); refractiveIndexSphereImaginary.put(0.818, 0d); refractiveIndexSphereImaginary.put(0.844, 0d); refractiveIndexSphereImaginary.put(1.313, 0d); refractiveIndexSphereImaginary.put(1.324, 0d); } }
31.21875
59
0.747748
750e81fe2e18df0e4e7de51b2ae33d8c8ce55084
1,837
/* */ package org.apache.commons.collections.primitives.adapters; /* */ /* */ import java.io.Serializable; /* */ import java.util.Collection; /* */ import org.apache.commons.collections.primitives.LongCollection; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final class LongCollectionCollection /* */ extends AbstractLongCollectionCollection /* */ implements Serializable /* */ { /* */ private LongCollection _collection; /* */ /* */ public static Collection wrap(LongCollection collection) { /* 51 */ if (null == collection) /* 52 */ return null; /* 53 */ if (collection instanceof Serializable) { /* 54 */ return new LongCollectionCollection(collection); /* */ } /* 56 */ return new NonSerializableLongCollectionCollection(collection); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public LongCollectionCollection(LongCollection collection) { /* 74 */ this._collection = null; /* */ this._collection = collection; /* */ } /* */ /* */ protected LongCollection getLongCollection() { /* */ return this._collection; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/commons/collections/primitives/adapters/LongCollectionCollection.class * Java compiler version: 2 (46.0) * JD-Core Version: 1.1.3 */
21.114943
134
0.443114
820b530226122563c94bb9f2d40c69515227e072
3,442
/* * Copyright 2010 Last.fm * * 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 fm.last.citrine.jobs; import static fm.last.citrine.scheduler.SchedulerConstants.SYS_ERR; import static fm.last.citrine.scheduler.SchedulerConstants.SYS_OUT; import static fm.last.citrine.scheduler.SchedulerConstants.TASK_COMMAND; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import fm.last.citrine.service.LogFileManager; import fm.last.citrine.service.TaskRunManager; /** * Job implementation for performing common Citrine admin tasks. */ public class AdminJob implements Job { private static Logger log = Logger.getLogger(AdminJob.class); public static final String COMMAND_CLEAR_TASK_RUNS = "clear_task_runs"; public static final String COMMAND_CLEAR_LOG_FILES = "clear_log_files"; private TaskRunManager taskRunManager; private LogFileManager logFileManager; @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String commandString = jobDataMap.getString(TASK_COMMAND); if (StringUtils.isEmpty(commandString)) { throw new JobExecutionException("Received empty admin command"); } String[] command = commandString.split("\\s+"); if (command.length != 2) { throw new JobExecutionException("Did not receive command and param"); } String commandType = command[0]; String argument = command[1]; if (COMMAND_CLEAR_TASK_RUNS.equals(commandType)) { int days = Integer.parseInt(argument); DateTime deleteBefore = new DateTime().minusDays(days); taskRunManager.deleteBefore(deleteBefore); jobDataMap.put(SYS_OUT, "Deleted task runs on and before " + deleteBefore); } else if (COMMAND_CLEAR_LOG_FILES.equals(commandType)) { int days = Integer.parseInt(argument); DateTime deleteBefore = new DateTime().minusDays(days); try { logFileManager.deleteBefore(deleteBefore); jobDataMap.put(SYS_OUT, "Deleted log files older than " + deleteBefore); } catch (IOException e) { log.error("Error deleting log files", e); jobDataMap.put(SYS_ERR, "Error deleting log files " + e.getMessage()); } } else { throw new JobExecutionException("Invalid command type '" + commandType + "'"); } } /** * @param taskRunManager the taskRunManager to set */ public void setTaskRunManager(TaskRunManager taskRunManager) { this.taskRunManager = taskRunManager; } /** * @param logFileManager the logFileManager to set */ public void setLogFileManager(LogFileManager logFileManager) { this.logFileManager = logFileManager; } }
35.854167
84
0.737071
be3239111462e01a04c372aada6905841c53e47b
1,237
/* */ package multiplechoiceprototype.controllers; import java.util.ArrayList; import java.util.List; /** * * @author MP */ public class DBController implements DBInterface { public DBController() { } @Override public List<String> getQuestions(String subject) { List<String> questions = new ArrayList<>(); questions.add("Test1"); questions.add("Test2"); questions.add("Test3"); questions.add("Test4"); questions.add("Test5"); return questions; } @Override public List<String[]> getAnswers(String subject) { List<String[]> answers = new ArrayList<>(); answers.add(new String[]{"Test1Answer1", "Test1Answer2", "Test1Answer3", "Test1Answer4"}); answers.add(new String[]{"Test2Answer1", "Test2Answer2", "Test2Answer3", "Test2Answer4"}); answers.add(new String[]{"Test3Answer1", "Test3Answer2", "Test3Answer3", "Test3Answer4"}); answers.add(new String[]{"Test4Answer1", "Test4Answer2", "Test4Answer3", "Test4Answer4"}); answers.add(new String[]{"Test5Answer1", "Test5Answer2", "Test5Answer3", "Test5Answer4"}); return answers; } }
27.488889
98
0.611156
d0b90f9578f893bb73d7a382da8c0dce4916c3af
446
package technology.dice.dicewhere.downloader.md5; public class MD5ChecksumResult { MD5Checksum originalChecksum; MD5Checksum processedChecksum; public MD5ChecksumResult(MD5Checksum originalChecksum, MD5Checksum processedChecksum) { this.originalChecksum = originalChecksum; this.processedChecksum = processedChecksum; } public boolean checksumMatch() { return this.originalChecksum.matches(this.processedChecksum); } }
27.875
89
0.802691
8be5f864c24be2d0b2e52bc80956b4a808c6ba50
1,469
package _leetcode._CONTEST._biweekly._75; import java.util.Arrays; /** * @Description: 6035. 选择建筑的方案数 * 给你一个下标从 0 开始的二进制字符串 s ,它表示一条街沿途的建筑类型,其中: * s[i] = '0' 表示第 i 栋建筑是一栋办公楼, * s[i] = '1' 表示第 i 栋建筑是一间餐厅。 * 作为市政厅的官员,你需要随机 选择 3 栋建筑。然而,为了确保多样性,选出来的 3 栋建筑 相邻 的两栋不能是同一类型。 * 比方说,给你 s = "001101" ,我们不能选择第 1 ,3 和 5 栋建筑,因为得到的子序列是 "011" ,有相邻两栋建筑是同一类型,所以 不合 题意。 * 请你返回可以选择 3 栋建筑的 有效方案数 。 * 提示: * 3 <= s.length <= 10^15 * s[i] 要么是 '0' ,要么是 '1' * @Date: 2022/4/3 */ public class Solution3 { public static long numberOfWays(String s) { long res101 = 0; long res010 = 0; int n = s.length(); int[] cnt0 = new int[n];// 统计前缀0的个数 int[] cnt1 = new int[n];// 统计前缀1的个数 if (s.charAt(0) == '0') cnt0[0] = 1; else cnt1[0] = 1; for (int i = 1; i < n; i++) { if (s.charAt(i) == '0') { cnt0[i] = cnt0[i - 1] + 1; cnt1[i] = cnt1[i - 1]; } else { cnt1[i] = cnt1[i - 1] + 1; cnt0[i] = cnt0[i - 1]; } } for (int i = 1; i < n - 1; i++) { if (s.charAt(i) == '1') { res010 += (long) cnt0[i] * (cnt0[n - 1] - cnt0[i]); } else { res101 += (long) cnt1[i] * (cnt1[n - 1] - cnt1[i]); } } return res010 + res101; } public static void main(String[] args) { System.out.println(numberOfWays("001101")); } }
28.25
84
0.470388
b8ff9f35842a9bcd269d84a22b10dded0bac2730
1,801
/** * Copyright Indra Soluciones Tecnologías de la Información, S.L.U. * 2013-2019 SPAIN * * 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.minsait.onesait.platform.videobroker.processor; import java.sql.Timestamp; import org.opencv.core.Mat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @JsonInclude(Include.NON_NULL) @AllArgsConstructor public abstract class VideoProcessorResults { @Getter @Setter private String ipCamera; // ip camera (used as ID) @Getter @Setter private String captureName; @Getter @Setter private Mat frame; // Frame when detected @Getter @Setter private long timestamp; @Getter @Setter private String result = ""; @Getter @Setter private String processingType = ""; @Getter @Setter private String extraInfo = ""; @Getter @Setter private boolean isThereResults = false; @Getter @Setter private boolean isReady = true; @Getter @Setter private String ontology; public void setCurrentTime() { setTimestamp((new Timestamp(System.currentTimeMillis())).getTime()); } public void generateResult() { setResult(""); } }
24.013333
75
0.757357
35953e8b355cb1e6be4b238a0717842aa5872b12
153
public class ChunkRenderDispatcher$3 { // Failed to decompile, took too long to decompile: net/minecraft/client/renderer/chunk/ChunkRenderDispatcher$3 }
51
112
0.816993
8233dcf9c661cc373d17bceb818e9ee7a1e7835d
5,760
package org.square.qa.utilities.fileParsers; import org.apache.log4j.Logger; import org.square.qa.utilities.constructs.GeneralUtils; import org.square.qa.utilities.constructs.workersDataStruct; import java.io.File; import java.io.IOException; import java.util.*; public class FileParserJStrings { private static Logger log = Logger.getLogger(FileParserJStrings.class); public boolean coloumnSwitch = false; private static class parseTypeGS{ private static String question = null; private static String response = null; } private static class parseTypeWR{ private static String workerId = null; private static String question = null; private static String response = null; } private static class parseTypeCategories{ private static String category = null; private static Double prior = -1.0d; } private String fileName; /** * Set filename * @param fileName is a String */ public void setFileName(String fileName){ this.fileName = fileName; } /** * Get filename * @param fileName is a String */ public void getFileName(String fileName){ this.fileName = fileName; } /** * Parse worker labels from worker responses file -- last line cannot be a blank line * @return worker responses stored as a Map from workers to responses * @throws IOException */ public Map<String,workersDataStruct<String,String> > parseWorkerLabels() throws IOException{ log.info("Parsing worker labels from file: "+fileName); Map<String,workersDataStruct<String,String> > workersMap = new HashMap<String, workersDataStruct<String,String>>(); File file = new File(fileName); Scanner lineScan = new Scanner(file); boolean fileEnd = true; while(fileEnd){ fileEnd = lineParseWR(lineScan); fileEnd = lineScan.hasNextLine(); log.debug("Parsing response by "+parseTypeWR.workerId); if(workersMap.containsKey(parseTypeWR.workerId)){ workersDataStruct<String,String> currentWorkerStruct = workersMap.get(parseTypeWR.workerId); currentWorkerStruct.insertWorkerResponse(parseTypeWR.question, parseTypeWR.response); workersMap.put(parseTypeWR.workerId, currentWorkerStruct); } else{ workersDataStruct<String,String> newWorker = new workersDataStruct<String,String>(); newWorker.insertWorkerResponse(parseTypeWR.question, parseTypeWR.response); workersMap.put(parseTypeWR.workerId, newWorker); } } log.info("Number of workers: "+workersMap.size()); log.info("Number of questions: "+GeneralUtils.getQuestions(workersMap).size()); log.info("Finished loading worker labels from file: "+fileName); return workersMap; } /** * Parse gold data from gold standard file * @return gold responses as a Map from questions to responses * @throws IOException */ public Map<String,String> parseGoldStandard() throws IOException{ log.info("Parsing gold/groundTruth labels from file: "+fileName); File file = new File(fileName); Scanner lineScan = new Scanner(file); Map<String,String> goldResponses = new HashMap<String, String>(); boolean fileEnd = true; while(fileEnd){ fileEnd = lineParseGS(lineScan); fileEnd = lineScan.hasNextLine(); goldResponses.put(parseTypeGS.question, parseTypeGS.response); } lineScan.close(); log.info("Number of gold responses: "+goldResponses.size()); log.info("Done loading gold labels from file: "+fileName); return goldResponses; } /** * Parse classes/categories with priors from input file * @return categories and priors as a Map * @throws IOException */ public Map<String,Double> parseCategoriesWPrior() throws IOException{ log.info("Parsing Categories and Priors from file: "+fileName); File file = new File(fileName); Scanner lineScan = new Scanner(file); Map<String,Double> categories = new HashMap<String, Double>(); boolean fileEnd = true; while(fileEnd){ fileEnd = lineParseCategories(lineScan,true); fileEnd = lineScan.hasNextLine(); categories.put(parseTypeCategories.category, parseTypeCategories.prior); log.info("Category: " + parseTypeCategories.category + " Prior: " + parseTypeCategories.prior); } lineScan.close(); log.info("Done Loading Categories and Priors"); return categories; } /** * Parse classes/categories/classes from input file * @return categories as a Set * @throws IOException */ public Set<String> parseCategories() throws IOException{ log.info("Parsing Categories and Priors from file: "+fileName); File file = new File(fileName); Scanner lineScan = new Scanner(file); Set<String> categories = new HashSet<String>(); boolean fileEnd = true; while(fileEnd){ fileEnd = lineParseCategories(lineScan,false); fileEnd = lineScan.hasNextLine(); categories.add(parseTypeCategories.category); log.info("Category: " + parseTypeCategories.category); } lineScan.close(); log.info("Done Loading Categories"); return categories; } private boolean lineParseGS(Scanner lineScan){ parseTypeGS.question = lineScan.next(); parseTypeGS.response = lineScan.next(); return lineScan.hasNextLine(); } private boolean lineParseWR(Scanner lineScan){ if(!coloumnSwitch){ parseTypeWR.workerId = lineScan.next(); parseTypeWR.question = lineScan.next(); parseTypeWR.response = lineScan.next(); } else { parseTypeWR.question = lineScan.next(); parseTypeWR.workerId = lineScan.next(); parseTypeWR.response = lineScan.next(); } return lineScan.hasNextLine(); } private boolean lineParseCategories(Scanner lineScan, boolean wPrior){ if(wPrior){ parseTypeCategories.category = lineScan.next(); parseTypeCategories.prior = lineScan.nextDouble(); } else { parseTypeCategories.category = lineScan.next(); } return lineScan.hasNextLine(); } }
32.178771
117
0.736111
9601bd7e66d788d19d810d1a381532c685887c6a
374
package net.minestom.server.event.player; import net.minestom.server.entity.Player; import net.minestom.server.event.PlayerEvent; import org.jetbrains.annotations.NotNull; /** * Called when a player stops sneaking. */ public class PlayerStopSneakingEvent extends PlayerEvent { public PlayerStopSneakingEvent(@NotNull Player player) { super(player); } }
23.375
60
0.764706
c2032021e476766db06d4fae1d7df06edeb4d45a
22,982
package com.shu.alogrithm.test; import com.shu.aleetcode.LeetCode; import org.junit.Test; import java.util.*; /** * @author shuxibing * @date 2019/8/9 21:15 * @uint d9lab * @Description: */ public class Solution { /** * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, * 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. * @param matrix * @return */ public ArrayList<Integer> printMatrix(int [][] matrix) { int[][] arr=new int[matrix.length][matrix.length]; ArrayList<Integer> list=new ArrayList<>(); for (int i=0;i<matrix.length;i++){ for (int j=0;j<matrix.length;j++){ } } return list; } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } @Override public String toString() { return "TreeNode{" + "val=" + val + ", left=" + left + ", right=" + right + '}'; } } public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>> arrayList=new ArrayList<>(); ArrayList<Integer> list=new ArrayList<>(); ArrayList<ArrayList<Integer>> dfs = dfs(root, arrayList, list, target); return dfs; } public static ArrayList<ArrayList<Integer>> dfs(TreeNode root, ArrayList<ArrayList<Integer>> arrayList,ArrayList<Integer> list,int target){ if (root==null){ return arrayList; } System.out.println(root.val); target=target- root.val; list.add(root.val); //边界条件 if (root.left==null&&root.right==null&&target==0){ //新建一个表,防止他们的引用地址是一样的 arrayList.add(new ArrayList<>(list)); } if (root.left!=null){ dfs(root.left,arrayList,list,target); } if (root.right!=null){ dfs(root.right,arrayList,list,target); } list.remove(list.size()-1); return arrayList; } public ListNode Merge(ListNode list1,ListNode list2) { ListNode list=new ListNode(0); while(true){ if (list1==null&&list2==null){ break; } if (list1.val>=list2.val||(list1==null&&list2!=null)){ list.next=new ListNode(list2.val); list2=list2.next; } if (list1.val<list2.val||(list1!=null&&list2==null)){ list.next=new ListNode(list1.val); list1=list1.next; } } return list.next; } /** * 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc, * 则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 * @param str * @return */ public ArrayList<String> Permutation(String str) { ArrayList<String> result = new ArrayList<String>() ; if(str==null || str.length()==0) { return result ; } char[] chars = str.toCharArray() ; TreeSet<String> temp = new TreeSet<>() ; Permutation(chars, 0, temp); result.addAll(temp) ; return result ; } public void Permutation(char[] chars, int begin, TreeSet<String> result) { if(chars==null || chars.length==0 || begin<0 || begin>chars.length-1) { return ; } if(begin == chars.length-1) { //自动去重而且排序 result.add(String.valueOf(chars)) ; }else { for(int i=begin ; i<=chars.length-1 ; i++) { swap(chars, begin, i) ; Permutation(chars, begin+1, result); //复原数组 swap(chars, begin, i) ; } } } public void swap(char[] x, int a, int b) { char t = x[a]; x[a] = x[b]; x[b] = t; } /** * 把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是, * 因为它包含质因子7。 * 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 * * 递增查找数字 * @param index * @return */ public int GetUglyNumber_Solution(int index) { if(index<=0){ return 0; } int[] result = new int[index]; int count = 0; int i2 = 0; int i3 = 0; int i5 = 0; result[0] = 1; int tmp = 0; while (count < index-1) { tmp = min(result[i2] * 2, min(result[i3] * 3, result[i5] * 5)); if(tmp==result[i2] * 2){ i2++;//三条if防止值是一样的,不要改成else的 } if(tmp==result[i3] * 3){ i3++; } if(tmp==result[i5]*5){ i5++; } result[++count]=tmp; } return result[index - 1]; } public int InversePairs(int [] array) { int count=0; for (int i=0;i<array.length;i++){ for (int j=i+1;j<array.length;j++){ if (array[i]>array[j]){ count++; } } } return count%1000000007; } private int min(int a, int b) { return (a > b) ? b : a; } public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if (pHead1 == null || pHead2 == null){ return null; } while (pHead1.val!=pHead2.val){ pHead1=(pHead1==null? null:pHead1.next); pHead2=(pHead2==null? null:pHead2.next); } return pHead1; } public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } @Override public String toString() { return super.toString(); } } public boolean duplicate(int numbers[],int length,int [] duplication) { Set<Integer> set=new HashSet<>(); for (int i=0;i<numbers.length;i++){ if (!set.contains(numbers[i])){ set.add(numbers[i]); }else{ duplication[0]=numbers[i]; return true; } } return false; } public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) { ArrayList<Integer> list=new ArrayList<>(); int i=0; int j=array.length-1; while (i<j){ if (array[i]+array[j]==sum){ list.add(array[i]); list.add(array[j]); return list; } if (array[i]+array[j]>sum){ j--; }if (array[i]+array[j]<sum){ i++; } } return list; } public String LeftRotateString(String str,int n) { if (str==null||"".equals(str)){ return str; } //取余数真正循环移位的数字 n=n%str.length(); String str1=str.substring(0,n-1); String str2=str.substring(n-1); return str2+str1; } public String ReverseSentence(String str) { if (str==null||"".equals(str)){ return str; } int index=str.indexOf("."); String str2=str.substring(index); String str1=""; for (int i=str2.length()-1;i>0;i--){ str1+=str2.charAt(i); } return str1+str.substring(0,index); } public int maxSubArray(int[] nums) { int n = nums.length; int currSum = nums[0], maxSum = nums[0]; for(int i = 1; i < n; ++i) { currSum = Math.max(nums[i], currSum + nums[i]); maxSum = Math.max(maxSum, currSum); } return maxSum; } public int lengthOfLastWord(String s) { s=s.trim(); String[] s1 = s.split(" "); return s1[s1.length-1].length(); } public void rotate(int[] nums, int k) { for (int i=0;i<k;i++){ int last=nums[nums.length-1]; for (int j=nums.length-1;j>0;j--){ nums[j]=nums[j-1]; } nums[0]=last; } } /** * dfs * @param root * @return */ public int sumNumbers(TreeNode root) { if (root==null){ return 0; } ArrayList<String> leaf = isLeaf(new ArrayList<>(), root, ""); Integer sum=0; for (String s : leaf) { Integer s1 = Integer.valueOf(s); sum+=s1; } return sum; } public ArrayList<String> isLeaf(ArrayList<String> list,TreeNode treeNode,String s){ s+=treeNode.val; if (treeNode.left==null&&treeNode.right==null){ list.add(new String(s)); } if (treeNode.left!=null){ isLeaf(list,treeNode.left,s); } if (treeNode.right!=null){ isLeaf(list,treeNode.right,s); } return list; } /** * 这道题我们拿到基本就可以确定是图的 dfs、bfs 遍历的题目了。题目中解释说被包围的区间不会存在于边界上,所以我们会想到边界上的 OO 要特殊处理,只要把边界上的 OO 特殊处理了,那么剩下的 OO 替换成 XX 就可以了。问题转化为,如何寻找和边界联通的 OO,我们需要考虑如下情况。 * * 作者:Ac_pipe * 链接:https://leetcode-cn.com/problems/surrounded-regions/solution/bfsdi-gui-dfsfei-di-gui-dfsbing-cha-ji-by-ac_pipe/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * @param board * @param i * @param j * * 思路:将边界的O设置成# */ public void dfs(char[][] board,int i,int j){ if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]=='X'||board[i][j]=='#'){ //跳出边界条件 return; } //将边界的O设置成# board[i][j]='#'; dfs(board,i--,j); dfs(board,i++,j); dfs(board,i,j--); dfs(board,i,j++); } public int canCompleteCircuit(int[] gas, int[] cost) { for (int i=0;i<gas.length;i++){ int pass = isPass(i, gas, cost); if (pass!=-1){ return pass; } } return -1; } /** * 将数组变成环 * @param i * @param gas * @param cost * @return */ public int isPass(int i,int[] gas,int[] cost){ int num=i; int len=cost.length; int count=0; int oil=0; int j=i; while (true){ if (count==cost.length){ break; } int index=j%gas.length; oil=oil+gas[index]-cost[index]; if (oil<0){ return -1; } count++; j++; } if (oil>=0){ return num; } return -1; } public int[] singleNumber(int[] nums) { List<Integer> list=new ArrayList<>(); Map<Integer,Integer> map=new HashMap<>(); for (int i=0;i<nums.length;i++){ int num=nums[i]; if (map.containsKey(num)){ map.put(num,map.get(num)+1); }else { map.put(num,1); } } for (Integer key : map.keySet()) { if (map.get(key)==1){ list.add(key); } } Object[] objects = list.toArray(); int[] arr={(int)objects[0],(int)objects[1]}; return arr; } public boolean isSameTree(TreeNode p, TreeNode q) { if (q==null&&p==null){ return true; } if((p!=null&&q==null)||(q!=null&&p==null)||(p.val!=q.val)){ return false; } return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); } public static int[][] calucateNum(int[][] arr,int m,int n){ int[][] newArr=new int[m][n]; for (int i=0;i<m;i++){ for (int j=0;j<n;j++){ if (arr[i][j]==1){ int num = calucateMinLen(arr, m, n, i, j); newArr[i][j]=num; } } } return newArr; } public static int calucateMinLen(int[][] arr, int m,int n,int x,int y){ int min=m+n; for (int i=0;i<m;i++){ for (int j=0;j<n;j++){ boolean flag=!(i==x&&j==y); if (flag&&arr[i][j]==0){ int tempLen=Math.abs(i+j-x-y); if (tempLen<min){ min=tempLen; } } } } return min; } /** * 输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。 * * 可以这样想:固定第一个字符a,求后面两个字符bc的排列。当两个字符bc的排列求好之后,我们把第一个字符a和后面的b交换,得到bac; * 接着我们固定第一个字符b,求后面两个字符ac的排列。现在是把c放到第一位置的时候了。记住前面我们已经把原先的第一个字符a和后面的b做了交换, * 为了保证这次c仍然是和原先处在第一位置的a交换,我们在拿c和第一个字符交换之前,先要把b和a交换回来。在交换b和a之后,再拿c和处在第一位置的a进行交换,得到cba。 * 我们再次固定第一个字符c,求后面两个字符b、a的排列。这样写成递归程序如下: * @param strArrs * @param i */ public static void permutateSequence(char[] strArrs,int i){ if (strArrs==null||i>strArrs.length||i<0){ return; }else if (i==strArrs.length){ System.out.println(strArrs); }else { //交换生成排列组合 char temp; for(int j=i;j<strArrs.length;j++){ //固定前面的字符串,然后交换出新的组合 temp = strArrs[j];// strArrs[j] = strArrs[i]; strArrs[i] = temp; permutateSequence(strArrs, i+1); //字符串还原 temp = strArrs[j];// strArrs[j] = strArrs[i]; strArrs[i] = temp; } } } public static int uniquePaths(int m, int n) { int[][] num=new int[m][n]; for(int i=0;i<m;i++){ num[i][0]=1; } for(int j=0;j<n;j++){ num[0][j]=1; } for (int i=1;i<m;i++){ for(int j=1;j<n;j++){ //典型的动态规划,由之前的状态决定 num[i][j]=num[i-1][j]+num[i][j-1]; } } return num[m-1][n-1]; } /** * 找出他们前n个字符串的共有的长度 * @param strs * @return */ public String longestCommonPrefix(String[] strs) { if (strs.length == 0){ return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { while (strs[i].indexOf(prefix) != 0) { //慢慢缩减长度 prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) { return ""; } } } return prefix; } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; int length = 0; ListNode first = head; while (first != null) { length++; first = first.next; } length -= n; first = dummy; while (length > 0) { length--; first = first.next; } first.next = first.next.next; return dummy.next; } public static boolean isPalindrome(int x) { String s=String.valueOf(x); int i=0; int j=s.length()-1; while (i<j){ if (s.charAt(i)==s.charAt(j)){ i++; j--; }else { return false; } } return true; } public boolean isValid(String s) { if (s.length()%2==1){ return false; } Stack<Character> stack=new Stack<Character>(); for (int i=0;i<s.length();i++){ if (s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){ stack.push(s.charAt(i)); continue; } if (s.charAt(i)==')'){ if (stack.empty()||stack.pop()!='('){ return false; } } if (s.charAt(i)=='}'){ if (stack.empty()||stack.pop()!='{'){ return false; } } if (s.charAt(i)==']'){ if (stack.empty()||stack.pop()!='['){ return false; } } } if (stack.empty()){ return true; } return false; } public static int cutRope(int target) { int max=0; for(int i=2;i<target;i++){ int n = target / i; int y=target%i; int temp=(int)(Math.pow(n,i-y)*Math.pow(n+1,y)); max=Math.max(temp,max); } return max; } public static int count(int[][] data,int num){ int len=data.length; Set<Integer> set=new HashSet<>(); for (int i=0;i<data.length;i++){ for (int j=0;j<data[i].length;j++){ //顺时针的多只兔子 for (int n=i+1;n<i+num;n++){ //取模进行计算,形成环状 for (int m=0;m<data[n%len].length;m++){ //两只兔子进行比较 if (data[i][j] == data[n%len][m]){ set.add(data[i][j]); } } } } } return set.size(); } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode out=new ListNode(0); ListNode head=out; int in=0; while (!(l1 == null && l2 == null)) { int x = (l1 == null ? 0 : l1.val); int y = (l2 == null ? 0 : l2.val); int sum = x + y + in; in = sum / 10; ListNode listNode = new ListNode(sum % 10); out.next = listNode; out = out.next; if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } if (in >0){ ListNode listNode = new ListNode(in); out.next = listNode; } return head.next; } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode out=new ListNode(0); ListNode head=out; while(l1 != null || l2 !=null){ int x=(l1 == null?Integer.MAX_VALUE:l1.val); int y=(l2 == null?Integer.MAX_VALUE:l2.val); if (y < x){ ListNode listNode=new ListNode(y); out.next=listNode; out=out.next; if (l2 != null){ l2=l2.next; } }else { ListNode listNode=new ListNode(x); out.next=listNode; out=out.next; if (l1 != null){ l1=l1.next; } } } return head.next; } public ListNode mergeKLists(ListNode[] lists) { ListNode head =null; for (int i=0; i< lists.length;i++){ head=mergeTwoLists(head,lists[i]); } return head; } public int[][] merge(int[][] intervals) { for(int i=0; i< intervals.length; i++){ } return intervals; } public int numIslands(char[][] grid) { int count=0; for(int i=0;i<grid.length; i++){ for (int j=0; j<grid[i].length ;j++){ if (grid[i][j] == '1'){ count++; dfs(i,j,grid); } } } return count; } public void dfs(int i, int j, char[][] data){ if (i<0 || i>=data.length || j<0 || j>= data[i].length || data[i][j] !='1'){ return; } data[i][j]='0'; dfs(i,j-1,data); dfs(i,j+1,data); dfs(i-1,j,data); dfs(i+1,j,data); } public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); return nums[nums.length-1-k]; } public boolean canJump(int[] nums) { int max=0; for(int i=0; i<nums.length;i++){ if (i<=max){ max=Math.max(max,i+nums[i]); if (max>=nums.length-1){ return true; } } } return false; } public boolean searchMatrix(int[][] matrix, int target) { Integer m=null; Integer n=null; for (int i=0;i<matrix.length;i++){ for (int j=0;j<matrix[i].length;j++){ if (matrix[i][j] == target){ m=i; n=j; } } } if (n==null && m==null){ //没有找到元素 return false; } return true; } public int lengthOfLIS(int[] nums) { if (nums.length<2){ return nums.length; } //动态规划备忘录,表示包含i的最大长度 int[] out=new int[nums.length]; int max=1; for (int i=0;i<nums.length;i++){ out[i]=1; for (int j=0;j<i;j++){ if (nums[i]>nums[j]){ out[i]=Math.max(out[i],out[j]+1); } max=Math.max(max,out[i]); } } return max; } public String decodeString(String s) { String out=""; boolean instack=false; Stack<Character> stack=new Stack<>(); for (int i=0;i<s.length();i++){ char c = s.charAt(i); if (c>='0' && c<='9'){ instack=true; } //出栈 if (c==']'){ instack=false; //开始出栈 String pingjie=""; String temp=""; char pop=stack.pop(); while(pop!='['){ temp=pop+temp; pop=stack.pop(); } //开始出栈数字 String num=""; pop=stack.pop(); while (!stack.empty() && (pop>='0'&& pop<='9')){ num=pop+num; pop=stack.pop(); if (!(pop>='0'&& pop<='9')){ stack.push(pop); } } Integer n=Integer.valueOf(num); //开始拼接字符串 while (n>0){ // System.out.println(n); pingjie=pingjie+temp; n--; } //如果栈不为空,继续入栈 if (!stack.empty()){ for (int k=0;k<pingjie.length();k++){ stack.push(pingjie.charAt(k)); } }else { //为空直接拼接到out out=out+pingjie; } continue; } //进站 if (instack){ stack.push(c); }else{ out=out+c; } } return out; } @Test public void test1111(){ System.out.println(decodeString("3[a2[c]]")); } }
25.062159
151
0.436777
1fbb44346a84d4a30af8a4a73951daeaa6708053
11,901
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.bubbles.animation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.verify; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Point; import android.graphics.PointF; import android.testing.AndroidTestingRunner; import android.view.View; import android.widget.FrameLayout; import androidx.dynamicanimation.animation.DynamicAnimation; import androidx.test.filters.SmallTest; import com.android.systemui.R; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.Spy; @SmallTest @RunWith(AndroidTestingRunner.class) public class ExpandedAnimationControllerTest extends PhysicsAnimationLayoutTestCase { private int mDisplayWidth = 500; private int mDisplayHeight = 1000; private int mExpandedViewPadding = 10; private int mOrientation = Configuration.ORIENTATION_PORTRAIT; private float mLauncherGridDiff = 30f; @Spy private ExpandedAnimationController mExpandedController = new ExpandedAnimationController( new Point(mDisplayWidth, mDisplayHeight) /* displaySize */, mExpandedViewPadding, mOrientation); private int mStackOffset; private float mBubblePaddingTop; private float mBubbleSize; private PointF mExpansionPoint; @Before public void setUp() throws Exception { super.setUp(); addOneMoreThanBubbleLimitBubbles(); mLayout.setActiveController(mExpandedController); Resources res = mLayout.getResources(); mStackOffset = res.getDimensionPixelSize(R.dimen.bubble_stack_offset); mBubblePaddingTop = res.getDimensionPixelSize(R.dimen.bubble_padding_top); mBubbleSize = res.getDimensionPixelSize(R.dimen.individual_bubble_size); mExpansionPoint = new PointF(100, 100); } @Test public void testExpansionAndCollapse() throws InterruptedException { Runnable afterExpand = Mockito.mock(Runnable.class); mExpandedController.expandFromStack(afterExpand); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); testBubblesInCorrectExpandedPositions(); verify(afterExpand).run(); Runnable afterCollapse = Mockito.mock(Runnable.class); mExpandedController.collapseBackToStack(mExpansionPoint, afterCollapse); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); testStackedAtPosition(mExpansionPoint.x, mExpansionPoint.y, -1); verify(afterExpand).run(); } @Test public void testOnChildAdded() throws InterruptedException { expand(); // Add another new view and wait for its animation. final View newView = new FrameLayout(getContext()); mLayout.addView(newView, 0); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); testBubblesInCorrectExpandedPositions(); } @Test public void testOnChildRemoved() throws InterruptedException { expand(); // Remove some views and see if the remaining child views still pass the expansion test. mLayout.removeView(mViews.get(0)); mLayout.removeView(mViews.get(3)); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); testBubblesInCorrectExpandedPositions(); } @Test public void testBubbleDraggedNotDismissedSnapsBack() throws InterruptedException { expand(); final View draggedBubble = mViews.get(0); mExpandedController.prepareForBubbleDrag(draggedBubble); mExpandedController.dragBubbleOut(draggedBubble, 500f, 500f); assertEquals(500f, draggedBubble.getTranslationX(), 1f); assertEquals(500f, draggedBubble.getTranslationY(), 1f); // Snap it back and make sure it made it back correctly. mExpandedController.snapBubbleBack(draggedBubble, 0f, 0f); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); testBubblesInCorrectExpandedPositions(); } @Test public void testBubbleDismissed() throws InterruptedException { expand(); final View draggedBubble = mViews.get(0); mExpandedController.prepareForBubbleDrag(draggedBubble); mExpandedController.dragBubbleOut(draggedBubble, 500f, 500f); assertEquals(500f, draggedBubble.getTranslationX(), 1f); assertEquals(500f, draggedBubble.getTranslationY(), 1f); mLayout.removeView(draggedBubble); waitForLayoutMessageQueue(); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); assertEquals(-1, mLayout.indexOfChild(draggedBubble)); testBubblesInCorrectExpandedPositions(); } @Test @Ignore("Flaky") public void testMagnetToDismiss_dismiss() throws InterruptedException { expand(); final View draggedOutView = mViews.get(0); final Runnable after = Mockito.mock(Runnable.class); mExpandedController.prepareForBubbleDrag(draggedOutView); mExpandedController.dragBubbleOut(draggedOutView, 25, 25); // Magnet to dismiss, verify the bubble is at the dismiss target and the callback was // called. mExpandedController.magnetBubbleToDismiss( mViews.get(0), 100 /* velX */, 100 /* velY */, 1000 /* destY */, after); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); verify(after).run(); assertEquals(1000, mViews.get(0).getTranslationY(), .1f); // Dismiss the now-magneted bubble, verify that the callback was called. final Runnable afterDismiss = Mockito.mock(Runnable.class); mExpandedController.dismissDraggedOutBubble(draggedOutView, afterDismiss); waitForPropertyAnimations(DynamicAnimation.ALPHA); verify(after).run(); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); assertEquals(mBubblePaddingTop, mViews.get(1).getTranslationX(), 1f); } @Test @Ignore("Flaky") public void testMagnetToDismiss_demagnetizeThenDrag() throws InterruptedException { expand(); final View draggedOutView = mViews.get(0); final Runnable after = Mockito.mock(Runnable.class); mExpandedController.prepareForBubbleDrag(draggedOutView); mExpandedController.dragBubbleOut(draggedOutView, 25, 25); // Magnet to dismiss, verify the bubble is at the dismiss target and the callback was // called. mExpandedController.magnetBubbleToDismiss( draggedOutView, 100 /* velX */, 100 /* velY */, 1000 /* destY */, after); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); verify(after).run(); assertEquals(1000, mViews.get(0).getTranslationY(), .1f); // Demagnetize the bubble towards (25, 25). mExpandedController.demagnetizeBubbleTo(25 /* x */, 25 /* y */, 100, 100); // Start dragging towards (20, 20). mExpandedController.dragBubbleOut(draggedOutView, 20, 20); // Since we just demagnetized, the bubble shouldn't be at (20, 20), it should be animating // towards it. assertNotEquals(20, draggedOutView.getTranslationX()); assertNotEquals(20, draggedOutView.getTranslationY()); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); // Waiting for the animations should result in the bubble ending at (20, 20) since the // animation end value was updated. assertEquals(20, draggedOutView.getTranslationX(), 1f); assertEquals(20, draggedOutView.getTranslationY(), 1f); // Drag to (30, 30). mExpandedController.dragBubbleOut(draggedOutView, 30, 30); // It should go there instantly since the animations finished. assertEquals(30, draggedOutView.getTranslationX(), 1f); assertEquals(30, draggedOutView.getTranslationY(), 1f); } /** Expand the stack and wait for animations to finish. */ private void expand() throws InterruptedException { mExpandedController.expandFromStack(Mockito.mock(Runnable.class)); waitForPropertyAnimations(DynamicAnimation.TRANSLATION_X, DynamicAnimation.TRANSLATION_Y); } /** Check that children are in the correct positions for being stacked. */ private void testStackedAtPosition(float x, float y, int offsetMultiplier) { // Make sure the rest of the stack moved again, including the first bubble not moving, and // is stacked to the right now that we're on the right side of the screen. for (int i = 0; i < mLayout.getChildCount(); i++) { assertEquals(x + i * offsetMultiplier * mStackOffset, mLayout.getChildAt(i).getTranslationX(), 2f); assertEquals(y, mLayout.getChildAt(i).getTranslationY(), 2f); assertEquals(1f, mLayout.getChildAt(i).getAlpha(), .01f); } } /** Check that children are in the correct positions for being expanded. */ private void testBubblesInCorrectExpandedPositions() { // Check all the visible bubbles to see if they're in the right place. for (int i = 0; i < mLayout.getChildCount(); i++) { assertEquals(getBubbleLeft(i), mLayout.getChildAt(i).getTranslationX(), 2f); assertEquals(mExpandedController.getExpandedY(), mLayout.getChildAt(i).getTranslationY(), 2f); } } /** * @param index Bubble index in row. * @return Bubble left x from left edge of screen. */ public float getBubbleLeft(int index) { final float bubbleLeft = index * (mBubbleSize + getSpaceBetweenBubbles()); return getRowLeft() + bubbleLeft; } private float getRowLeft() { if (mLayout == null) { return 0; } int bubbleCount = mLayout.getChildCount(); final float totalBubbleWidth = bubbleCount * mBubbleSize; final float totalGapWidth = (bubbleCount - 1) * getSpaceBetweenBubbles(); final float rowWidth = totalGapWidth + totalBubbleWidth; final float centerScreen = mDisplayWidth / 2f; final float halfRow = rowWidth / 2f; final float rowLeft = centerScreen - halfRow; return rowLeft; } /** * @return Space between bubbles in row above expanded view. */ private float getSpaceBetweenBubbles() { final float rowMargins = (mExpandedViewPadding + mLauncherGridDiff) * 2; final float maxRowWidth = mDisplayWidth - rowMargins; final float totalBubbleWidth = mMaxBubbles * mBubbleSize; final float totalGapWidth = maxRowWidth - totalBubbleWidth; final int gapCount = mMaxBubbles - 1; final float gapWidth = totalGapWidth / gapCount; return gapWidth; } }
39.936242
98
0.701454
c501720d6c43b4cd1d1b2b00f9857d88411e80b0
1,014
package com.wxmp.core.page; public class Pagination<E> extends AbstractPage<E> { protected int start; protected int totalItemsCount; protected int totalPageCount; public Pagination(){} public int getTotalItemsCount() { return totalItemsCount; } public void setTotalItemsCount(int totalItemsCount) { this.totalItemsCount = totalItemsCount; this.totalPageCount = (getTotalItemsCount() - 1) / getPageSize() + getFirstPageNum(); } @Override public boolean isLastPage() { return getLastPageNum() <= getPageNum(); } @Override public int getLastPageNum() { return this.totalPageCount; } @Override public String toString() { return String.format("Page[%d] of [%d] in total [%d] :%s", this.getPageNum(), this.getLastPageNum(), this.getTotalItemsCount(), items.toString()); } public int getTotalPageCount() { return totalPageCount; } public int getStart() { this.start = (this.pageNum - 1) * this.pageSize; return start; } }
21.125
154
0.684418
f686ead2b41e84723e7c70284a0e43875567317c
5,086
/* * Copyright © 2017 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.master.startup; import com.google.common.base.Throwables; import com.google.inject.Inject; import io.cdap.cdap.common.conf.CConfiguration; import io.cdap.cdap.common.lang.ClassLoaders; import io.cdap.cdap.logging.LoggingUtil; import io.cdap.cdap.logging.framework.InvalidPipelineException; import io.cdap.cdap.logging.framework.LogPipelineLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * Checks for log appender configurations. This class will be automatically picked up by the MasterStartupTool. */ @SuppressWarnings("unused") class LogPipelineCheck extends AbstractMasterCheck { private static final Logger LOG = LoggerFactory.getLogger(LogPipelineCheck.class); @Inject LogPipelineCheck(CConfiguration cConf) { super(cConf); } @Override public void run() throws Exception { // Because the logging framework supports usage of addition jars to host appender classes, // for validations, we need to construct a new classloader using all system jars plus the configured // additional log library jars. // A new classloader is needed because the logback doesn't support context classloader and requires the // LoggerContext class needs to be loaded from the same classloader as all appender classes. // We need to use reflection to load the LogPipelineLoader class and call validate on it // Collects all URLS used by the CDAP system classloader List<URL> urls = ClassLoaders.getClassLoaderURLs(getClass().getClassLoader(), new ArrayList<URL>()); for (File libJar : LoggingUtil.getExtensionJars(cConf)) { urls.add(libJar.toURI().toURL()); } // Serialize the cConf to a String. This is needed because the cConf field is // loaded from the CDAP system classloader and cannot be passed directly to the // LogPipelineLoader class that loaded from the new ClassLoader constructed above. StringWriter writer = new StringWriter(); this.cConf.writeXml(writer); // Create a new classloader and run the following code using reflection // // CConfiguration cConf = CConfiguration.create(); // cConf.clear(); // cConf.addResource(inputStream); // new LogPipelineLoader(cConf).validate(); ClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null); Class<?> cConfClass = classLoader.loadClass(CConfiguration.class.getName()); Object cConf = cConfClass.getMethod("create").invoke(null); cConfClass.getMethod("clear").invoke(cConf); InputStream input = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8)); cConfClass.getMethod("addResource", InputStream.class).invoke(cConf, input); Class<?> loaderClass = classLoader.loadClass(LogPipelineLoader.class.getName()); Object loader = loaderClass.getConstructor(cConfClass).newInstance(cConf); try { loaderClass.getMethod("validate").invoke(loader); } catch (InvocationTargetException e) { // Translate the exception throw by the reflection call Throwable cause = e.getCause(); // Because the "InvalidPipelineException" throw from the reflection call is actually loaded by a different // classloader, we need to recreate a new one with the current classloader using the original cause // and stacktrace to allow easy debugging. // From the perspective of the caller to this method, it doesn't see any classloader trick being done in here. // Ideally we should do it for any cause class that is loaded from the classloader constructed above, but // that would make the code unnecessarily complicate since we know that only InvalidPipelineException // will be throw from the validate method. if (InvalidPipelineException.class.getName().equals(cause.getClass().getName())) { InvalidPipelineException ex = new InvalidPipelineException(cause.getMessage(), cause.getCause()); ex.setStackTrace(cause.getStackTrace()); throw ex; } Throwables.propagateIfPossible(cause, Exception.class); throw new RuntimeException(cause); } LOG.info("Log pipeline configurations verified."); } }
43.844828
116
0.748525
091fb04be9056a438010bd52bf675f2dd9d3cc23
849
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.view.treemap.listener; import org.caleydo.core.event.AEvent; import org.caleydo.core.event.AEventListener; import org.caleydo.view.treemap.GLTreeMap; /** * Listener for switch label on/off. * * @author Michael Lafer * */ public class ToggleLabelListener extends AEventListener<GLTreeMap> { @Override public void handleEvent(AEvent event) { ToggleLabelEvent tlevent = (ToggleLabelEvent) event; handler.setDrawLabel(tlevent.isDrawLabel()); } }
29.275862
80
0.616019
e529919003d62983b32009ba3a5cc40ceb083217
3,915
package com.github.pcimcioch.memorystore.header; import com.github.pcimcioch.memorystore.encoder.ObjectPoolEncoder; import com.github.pcimcioch.memorystore.encoder.UnsignedIntegerEncoder; import java.util.Objects; import static com.github.pcimcioch.memorystore.encoder.UnsignedIntegerEncoder.MAX_BIT_COUNT; import static com.github.pcimcioch.memorystore.encoder.UnsignedIntegerEncoder.MAX_LAST_BIT; import static com.github.pcimcioch.memorystore.encoder.UnsignedIntegerEncoder.MIN_BIT_COUNT; import static com.github.pcimcioch.memorystore.util.Utils.assertArgument; import static java.util.Objects.requireNonNull; /** * ObjectPoolHeaders represent data that is stored in memory as java objects pooled so that equal objects are stored only once. * Each record stores the index to individual java object * * @param <T> ObjectPoolHeaders are supported by ObjectPoolEncoders */ public class ObjectPoolHeader<T> extends Header<ObjectPoolEncoder<T>> { private static final String POOL_INDEX_SUFFIX = "-index"; private final PoolDefinition poolDefinition; private final BitHeader<UnsignedIntegerEncoder> poolIndexHeader; /** * Constructor * * @param name header name * @param poolDefinition definition of object pool */ public ObjectPoolHeader(String name, PoolDefinition poolDefinition) { super(name); this.poolDefinition = requireNonNull(poolDefinition); this.poolIndexHeader = new BitHeader<>(name + POOL_INDEX_SUFFIX, poolDefinition.poolBits, MAX_LAST_BIT, UnsignedIntegerEncoder::new); } /** * BitHeader that is used to store java object index on fixed number of bits * * @return header to store object index */ public BitHeader<UnsignedIntegerEncoder> poolIndexHeader() { return poolIndexHeader; } /** * @return pool definition */ public PoolDefinition poolDefinition() { return poolDefinition; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ObjectPoolHeader<?> that = (ObjectPoolHeader<?>) o; return poolDefinition.equals(that.poolDefinition) && poolIndexHeader.equals(that.poolIndexHeader); } @Override public int hashCode() { return Objects.hash(super.hashCode(), poolDefinition, poolIndexHeader); } /** * Definition describing how to store java objects in the pool */ public static final class PoolDefinition { private final String name; private final int poolBits; /** * Constructor * * @param name name of the pool * @param poolBits how many bits should be used to store index of the object */ public PoolDefinition(String name, int poolBits) { assertArgument(poolBits >= MIN_BIT_COUNT && poolBits <= MAX_BIT_COUNT, "Pool Bits Count must be between %d and %d", MIN_BIT_COUNT, MAX_BIT_COUNT); this.name = requireNonNull(name); this.poolBits = poolBits; } /** * @return name of the pool */ public String name() { return name; } /** * @return how many bits should be used to store index of the object */ public int poolBits() { return poolBits; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PoolDefinition that = (PoolDefinition) o; return poolBits == that.poolBits && name.equals(that.name); } @Override public int hashCode() { return Objects.hash(name, poolBits); } } }
32.89916
141
0.655172
44a4c398ef730953f4770bba5884461d72e1db6d
26,392
/* * FileName: PaginationDalClient.java * Author: v_qinyuchen * Date: 2016年3月30日 下午6:00:07 * Description: //模块目的、功能描述 * History: //修改记录 * <author> <time> <version> <desc> * 修改人姓名 修改时间 版本号 描述 */ package org.alljet.dal.client.support; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.alljet.dal.Pagination; import org.alljet.dal.PaginationResult; import org.alljet.dal.client.IPaginationDalClient; import org.alljet.dal.client.support.rowmapper.RowMapperFactory; import org.alljet.dal.dialect.Dialect; import org.alljet.dal.dialect.DialectFactory; import org.alljet.dal.resource.XmlResource; import org.alljet.dal.sql.FreeMakerParser; import org.alljet.dal.sql.SqlParser; import org.alljet.dal.sql.SqlParserManager; import org.alljet.dal.sql.ValueParser; import org.alljet.dal.util.DalUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.object.GenericStoredProcedure; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; /** * 〈一句话功能简述〉<br> * 〈功能详细描述〉 * * @author v_qinyuchen * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ public class PaginationDalClient extends XmlResource implements IPaginationDalClient { /** log */ private static final Logger log = LoggerFactory.getLogger(PaginationDalClient.class); /** SQL失效时间 */ private final Long sqlTimeOut = 100L; /** * 指定记录数 */ private final String LIMIT = "_limit"; private String dbType; /** * 数据库方言工厂 */ @Autowired private DialectFactory dialectFactory; private NamedParameterJdbcTemplate template; // private JdbcTemplate jdbcTemplate; private DataSource dataSource; public void afterPropertiesSet() throws Exception { parseResource(); } public void setDataSource(DataSource dataSource) throws SQLException, Exception { this.template = new NamedParameterJdbcTemplate(dataSource); // this.jdbcTemplate = new JdbcTemplate(dataSource); DatabaseMetaData md = dataSource.getConnection().getMetaData(); this.dbType = md.getDatabaseProductName(); log.info("This db type is {}", this.dbType); this.dataSource = dataSource; afterPropertiesSet(); } /** * 执行查询,返回结果集记录数目 * * @param sqlId SQLID * @param paramMap 执行参数 * @return 查询结果 */ @Override public int execute(String sqlId, Map<String, Object> paramMap) { // Integer count = template.execute(sqlId, paramMap, new PreparedStatementCallback<Integer>() { // // public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { // ps.execute(); // return ps.getUpdateCount(); // } // // }); // if (count != null && count > 0) // return count; // else // return 0; String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 调用JDBCTemplate实现更新,返回更新成功的记录数 */ int result = template.update(sql, DalUtils.mapIfNull(paramMap)); return result; } /** * 执行查询,execute重载方法 * * @param sqlId SQLID * @param param 执行参数 * @return 查询结果 */ @Override public int execute(String sqlId, Object param) { // SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(param); // Integer count = template.execute(sqlId, sqlParameterSource, new PreparedStatementCallback<Integer>() { // // public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { // ps.execute(); // return ps.getUpdateCount(); // } // // }); // if (count != null && count > 0) // return count; // else // return 0; return this.execute(sqlId, DalUtils.convertToMap(param)); } /** * 查询并返回分页结果,pagesize为负数时,返回所有记录 * * @param sqlId SQLID * @param paramMap 查询参数 * @param pagination 分页 * @return 分页查询结果 */ @Override public PaginationResult<List<Map<String, Object>>> queryForList(String sqlId, Map<String, Object> paramMap, Pagination pagination) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 装配分页信息 */ if (paramMap == null) { paramMap = new HashMap<String, Object>(); } /** 当pagesize为负数时 ,查询该表中的所有记录 */ List<Map<String, Object>> list = null; if (pagination.getPagesize() < 0) { list = queryForList(sqlId, paramMap); pagination.setTotalRows(list.size()); } else { paramMap.put(LIMIT, pagination.getPagesize()); paramMap.put("_offset", pagination.getFirstRowIndex()); this.configurePagination(template, sql, paramMap, pagination, this.dbType); list = template.queryForList(generatePaginationSql(sql, this.dbType), paramMap); } /** 执行分页查询 */ return new PaginationResult<List<Map<String, Object>>>(list, pagination); } /** * 查询并返回分页结果 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param pagination 分页 * @return 分页查询结果 */ @Override public PaginationResult<List<Map<String, Object>>> queryForList(String sqlId, Object param, Pagination pagination) { return queryForList(sqlId, DalUtils.convertToMap(param), pagination); } /** * 查询并返回分页结果 * * @param sqlId SQLID * @param paramMap 查询参数 * @param rowMapper 翻页处理规则 * @param pagination 分页 * @param <T> 泛型对象 * @return 分页查询结果 */ @Override public <T> PaginationResult<List<T>> queryForList(String sqlId, Map<String, Object> paramMap, RowMapper<T> rowMapper, Pagination pagination) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 装配分页信息 */ if (paramMap == null) { paramMap = new HashMap<String, Object>(); } List<T> list = null; /** 当pagesize为负数时 ,查询该表中的所有记录 */ if (pagination.getPagesize() < 0) { list = queryForList(sqlId, paramMap, rowMapper); pagination.setTotalRows(list.size()); } else { paramMap.put(LIMIT, pagination.getPagesize()); paramMap.put("_offset", pagination.getFirstRowIndex()); this.configurePagination(template, sql, paramMap, pagination, this.dbType); list = template.query(generatePaginationSql(sql, this.dbType), paramMap, rowMapper); } /** 执行分页查询 */ return new PaginationResult<List<T>>(list, pagination); } /** * 查询并返回分页结果 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param rowMapper 翻页处理规则 * @param pagination 分页 * @param <T> 泛型对象 * @return 分页查询结果 */ @Override public <T> PaginationResult<List<T>> queryForList(String sqlId, Object param, RowMapper<T> rowMapper, Pagination pagination) { return queryForList(sqlId, DalUtils.convertToMap(param), rowMapper, pagination); } /** * 查询并返回分页结果 重载方法 * * @param sqlId SQLID * @param paramMap 查询参数 * @param requiredType 需要操作的类型 * @param pagination 分页 * @param <T> 泛型对象 * @return 分页查询结果 */ @Override public <T> PaginationResult<List<T>> queryForList(String sqlId, Map<String, Object> paramMap, Class<T> requiredType, Pagination pagination) { return this.queryForList(sqlId, paramMap, new RowMapperFactory<T>(requiredType).getRowMapper(), pagination); } /** * 查询并返回分页结果 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param requiredType 需要操作的类型 * @param pagination 分页 * @param <T> 泛型对象 * @return 分页查询结果 */ @Override public <T> PaginationResult<List<T>> queryForList(String sqlId, Object param, Class<T> requiredType, Pagination pagination) { return queryForList(sqlId, DalUtils.convertToMap(param), requiredType, pagination); } /** * 数据持久化操作 * * @param entity 实体对象 * @return 持久化操作成功记录id */ @Override public Number persist(Object entity) { return persist(entity, Number.class); } /** * 数据持久化 * * @param entity 数据实体 * @param requiredType 需要处理的类型 * @param <T> 泛型对象 * @return 持久化操作成功记录id(支持Number,Long) */ @Override public <T> T persist(Object entity, Class<T> requiredType) { SqlParser sqlParser = SqlParserManager.getSqlParser(entity.getClass()); String insertSQL = sqlParser.getInsert(); Map<String, Object> paramMap = ValueParser.parser(entity); KeyHolder keyHolder = new GeneratedKeyHolder(); logMessage("persist", insertSQL, paramMap); long beginDate = System.currentTimeMillis(); /** 渲染后获取JDBC模板 */ template.update(insertSQL, new MapSqlParameterSource(paramMap), keyHolder, new String[] { sqlParser.getIdName() }); Object key = paramMap.get(sqlParser.getId()); if (key == null || (key instanceof Number && ((Number) key).doubleValue() == 0.0d)) { return (T) keyHolder.getKey(); } logMessage("persist", insertSQL, paramMap, System.currentTimeMillis() - beginDate); return (T) key; } /** * 数据合并与更新 * * @param entity 更新的数据实体 * @return 数据更新后的结果 */ @Override public int merge(Object entity) { String updateSql = SqlParserManager.getSqlParser(entity.getClass()).getUpdate(); Map<String, Object> paramMap = ValueParser.parser(entity); logMessage("merge", updateSql, paramMap); long beginDate = System.currentTimeMillis(); /** 调用JDBCTemplate实现更新,返回更新成功的记录数 */ int result = template.update(updateSql, paramMap); logMessage("merge", updateSql, paramMap, System.currentTimeMillis() - beginDate); return result; } /** * 动态更新 * * @param entity 更新的数据实体 * @return 返回更新的记录数目 */ @Override public int dynamicMerge(Object entity) { Map<String, Object> paramMap = ValueParser.parser(entity); String updateSql = SqlParserManager.getSqlParser(entity.getClass()).getDynamicUpdate(paramMap); logMessage("dynamicMerge", updateSql, paramMap); long beginDate = System.currentTimeMillis(); /** 调用JDBCTemplate实现更新,返回更新成功的记录数 */ int result = template.update(updateSql, paramMap); logMessage("dynamicMerge", updateSql, paramMap, System.currentTimeMillis() - beginDate); return result; } /** * 数据删除 * * @param entity 删除的数据实体 * @return 返回删除的记录数目 */ @Override public int remove(Object entity) { String removeSql = SqlParserManager.getSqlParser(entity.getClass()).getDelete(); Map<String, Object> paramMap = ValueParser.parser(entity); logMessage("remove", removeSql, paramMap); long beginDate = System.currentTimeMillis(); /** 调用JDBCTemplate实现更新,返回更新成功的记录数 */ int result = template.update(removeSql, paramMap); logMessage("remove", removeSql, paramMap, System.currentTimeMillis() - beginDate); return result; } /** * 根据传入实体类查询单个记录 * * @param entityClass 实体类 * @param entity 查询对象 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> T find(Class<T> entityClass, Object entity) { String findSql = SqlParserManager.getSqlParser(entity.getClass()).getSelect(); Map<String, Object> paramMap = ValueParser.parser(entity); logMessage("find", findSql, paramMap); long beginDate = System.currentTimeMillis(); /** 调用JDBCTemplate实现单记录查询,并返回查询结果 */ List<T> resultList = template.query(findSql, paramMap, new RowMapperFactory<T>(entityClass).getRowMapper()); logMessage("find", findSql, paramMap, System.currentTimeMillis() - beginDate); return singleResult(resultList); } /** * 批量更新 * * @param sqlId SQLID * @param batchValues 需要批处理的集合 * @return 批处理成功记录数 */ @Override public int[] batchUpdate(String sqlId, Map<String, Object>[] batchValues) { /** FreeMarker模板渲染 */ String sql = getSQL(sqlId); int[] result; /** 调用JDBCTemplate批量更新,返回更新成功的记录数 */ result = template.batchUpdate(sql, batchValues); return result; } /** * 调存储过程 * * @param sqlId SQLID * @param paramMap 执行参数 * @param sqlParameters sqlcommand参数的对象 * @return 存储过程执行结果 */ @Override public Map<String, Object> call(String sqlId, Map<String, Object> paramMap, List<SqlParameter> sqlParameters) { Map<String, Object> paramMapTmp = DalUtils.mapIfNull(paramMap); String sql = getSQL(sqlId); /** 调用存储过程 */ GenericStoredProcedure storedProcedure = new GenericStoredProcedure(); /** 放入数据源 */ storedProcedure.setDataSource(dataSource); /** 放入SQL */ storedProcedure.setSql(sql); for (SqlParameter sqlParameter : sqlParameters) { storedProcedure.declareParameter(sqlParameter); } return storedProcedure.execute(paramMapTmp); } /** * 查询单个记录 * * @param sqlId SQLID * @param paramMap 查询参数 * @param requiredType 需要处理的类型 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> T queryForObject(String sqlId, Map<String, Object> paramMap, Class<T> requiredType) { return this.queryForObject(sqlId, paramMap, new RowMapperFactory<T>(requiredType).getRowMapper()); } /** * 查询单个记录 * * @param sqlId SQLID * @param param 查询参数 * @param requiredType 需要处理的类型 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> T queryForObject(String sqlId, Object param, Class<T> requiredType) { return this.queryForObject(sqlId, DalUtils.convertToMap(param), requiredType); } /** * 根据sqlId查询单条记录 * * @param sqlId SQLID * @param paramMap 查询参数 * @param rowMapper 翻页处理规则 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> T queryForObject(String sqlId, Map<String, Object> paramMap, RowMapper<T> rowMapper) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 调用JDBCTemplate实现查询,并返回查询结果 */ List<T> resultList = template.query(sql, paramMap, rowMapper); return singleResult(resultList); } /** * queryForObject重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param rowMapper 翻页处理规则 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> T queryForObject(String sqlId, Object param, RowMapper<T> rowMapper) { return this.queryForObject(sqlId, DalUtils.convertToMap(param), rowMapper); } /** * 查询并返回映射集 * * @param sqlId SQLID * @param paramMap 查询参数 * @return 查询结果 */ @Override public Map<String, Object> queryForMap(String sqlId, Map<String, Object> paramMap) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 调用JDBCTemplate实现查询,并返回查询结果 */ Map<String, Object> map = singleResult(template.queryForList(sql, paramMap)); return map; } /** * queryForMap重载方法 * * @param sqlId SQLID * @param param 查询参数 * @return 查询结果 */ @Override public Map<String, Object> queryForMap(String sqlId, Object param) { return this.queryForMap(sqlId, DalUtils.convertToMap(param)); } /** * queryForList重载方法 * * @param sqlId SQLID * @param paramMap 查询参数 * @param requiredType 需要处理的类型 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Map<String, Object> paramMap, Class<T> requiredType) { return this.queryForList(sqlId, paramMap, new RowMapperFactory<T>(requiredType).getRowMapper()); } /** * queryForList重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param requiredType 需要处理的类型 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Object param, Class<T> requiredType) { return queryForList(sqlId, DalUtils.convertToMap(param), requiredType); } /** * 根据sqlId查询多条记录,返回List<Map<String, Object>>型结果集,queryForList重载方法 * * @param sqlId SQLID * @param paramMap 查询参数 * @return 查询结果 */ @Override public List<Map<String, Object>> queryForList(String sqlId, Map<String, Object> paramMap) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); long beginDate = System.currentTimeMillis(); /** 调用JDBCTemplate实现多记录查询,并返回查询结果 */ List<Map<String, Object>> list = template.queryForList(sql, DalUtils.mapIfNull(paramMap)); return list; } /** * queryForList重载方法 * * @param sqlId SQLID * @param param 查询参数 * @return 查询结果 */ @Override public List<Map<String, Object>> queryForList(String sqlId, Object param) { return queryForList(sqlId, DalUtils.convertToMap(param)); } /** * 根据sqlId查询多条记录,返回list型结果集 * * @param sqlId SQLID * @param paramMap 查询参数 * @param rowMapper 翻页处理规则 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Map<String, Object> paramMap, RowMapper<T> rowMapper) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); /** 调用JDBCTemplate实现查询,并返回查询结果 */ List<T> list = template.query(sql, DalUtils.mapIfNull(paramMap), rowMapper); return list; } /** * 查询并返回结果集,queryForList重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param rowMapper 翻页处理规则 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Object param, RowMapper<T> rowMapper) { return queryForList(sqlId, DalUtils.convertToMap(param), rowMapper); } /** * 查询并返回结果集 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param num 随机数 * @return 查询结果 */ @Override public List<Map<String, Object>> queryForList(String sqlId, Object param, int num) { return queryForList(sqlId, DalUtils.convertToMap(param), num); } /** * 查询并返回结果集,num为负数时,返回所有记录 * * @param sqlId SQLID * @param paramMap 查询参数 * @param num 随机数 * @return 查询结果 */ @Override public List<Map<String, Object>> queryForList(String sqlId, Map<String, Object> paramMap, int num) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); if (paramMap == null) { paramMap = new HashMap<String, Object>(); } List<Map<String, Object>> list; if (num < 0) { list = queryForList(sqlId, paramMap); } else { paramMap.put(LIMIT, num); list = template.queryForList(generatePaginationSqlForRandom(sql, this.dbType), paramMap); } /** 执行分页查询 */ return list; } /** * 查询并返回结果集 重载方法 * * @param sqlId SQLID * @param paramMap 查询参数 * @param requiredType 需要操作的类型 * @param num 随机数 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Map<String, Object> paramMap, Class<T> requiredType, int num) { return queryForList(sqlId, paramMap, new RowMapperFactory<T>(requiredType).getRowMapper(), num); } /** * 查询并返回结果集 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param requiredType 需要操作的类型 * @param num 随机数 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Object param, Class<T> requiredType, int num) { return queryForList(sqlId, DalUtils.convertToMap(param), requiredType, num); } /** * 查询并返回结果集 重载方法 * * @param sqlId SQLID * @param param 查询参数 * @param rowMapper 翻页处理规则 * @param num 随机数 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Object param, RowMapper<T> rowMapper, int num) { return queryForList(sqlId, DalUtils.convertToMap(param), rowMapper, num); } /** * 查询并返回结果集 * * @param sqlId SQLID * @param paramMap 查询参数 * @param rowMapper 翻页处理规则 * @param num 随机数 * @param <T> 泛型对象 * @return 查询结果 */ @Override public <T> List<T> queryForList(String sqlId, Map<String, Object> paramMap, RowMapper<T> rowMapper, int num) { String sql = FreeMakerParser.process(paramMap, getSQL(sqlId), sqlId); if (paramMap == null) { paramMap = new HashMap<String, Object>(); } List<T> list; if (num < 0) { list = queryForList(sqlId, paramMap, rowMapper); } else { paramMap.put(LIMIT, num); list = template.query(generatePaginationSqlForRandom(sql, this.dbType), paramMap, rowMapper); } return list; } /** * 装配分页信息 * * @param template 模板 * @param sql SQL语句 * @param paramMap 查询参数 * @param pagination 分页 * @param dbType 数据源类型 */ private void configurePagination(NamedParameterJdbcTemplate template, String sql, Map<String, Object> paramMap, Pagination pagination, String dbType) { if (pagination.getTotalRows() == 0 || pagination.getTotalRows() == -1) { /** 获取数据总数 */ int totalRows = template.queryForObject(generateCountSql(sql, dbType), DalUtils.mapIfNull(paramMap), Integer.class); pagination.setTotalRows(totalRows); } } private void configurePaginationTotalrows(NamedParameterJdbcTemplate template, String sql, Map<String, Object> paramMap, Pagination pagination, String dbType) { if (pagination.getTotalRows() == 0 || pagination.getTotalRows() == -1) { /** 获取数据总数 */ int totalRows = template.queryForObject(sql, DalUtils.mapIfNull(paramMap), Integer.class); pagination.setTotalRows(totalRows); } } /** * 查询指定SQL的总记录数 * * @param sql SQL语句 * @param dbType 数据源类型 * @return 统计SQL串 */ private String generateCountSql(String sql, String dbType) { Dialect dialect = dialectFactory.getDBDialect(dbType); if (dialect == null) { throw new RuntimeException("error.dal.002"); } return dialect.getCountString(sql); } /** * 生成分页sql,查询指定位置、指定行数的记录 * * @param sql SQL语句 * @param dbType 数据源类型 * @return 分页SQL串 */ private String generatePaginationSql(String sql, String dbType) { Dialect dialect = dialectFactory.getDBDialect(dbType); if (dialect == null) { throw new RuntimeException("error.dal.002"); } return dialect.getLimitString(sql); } /** * 生成分页sql,查询前几行记录 * * @param sql SQL语句 * @param dbType 数据源类型 * @return 分页SQL串 */ private String generatePaginationSqlForRandom(String sql, String dbType) { Dialect dialect = dialectFactory.getDBDialect(dbType); if (dialect == null) { throw new RuntimeException("error.dal.002"); } return dialect.getLimitStringForRandom(sql); } /** * 返回结果集中的第一条记录 * * @param resultList 结果集 * @param <T> 泛型对象 * @return 结果集中的第一条记录 */ private <T> T singleResult(List<T> resultList) { if (resultList != null) { int size = resultList.size(); if (size > 0) { return resultList.get(0); } if (size == 0) { return null; } } return null; } /** * 打印sql的执行信息 * * @param method 方法名 * @param sql SQL串 * @param object 对象 */ private void logMessage(String method, String sql, Object object) { if (log.isDebugEnabled()) { log.debug(method + " method SQL: [" + sql + "]"); log.debug(method + " method parameter:" + object); } } /** * 打印超时sql的执行时间 * * @param method 方法名 * @param sql SQL串 * @param object 对象 * @param executeTime 执行时间 */ private void logMessage(String method, String sql, Object object, long executeTime) { /** 打印超时sql的执行时间 */ if (executeTime >= sqlTimeOut) { if (log.isDebugEnabled()) { log.error(method + " method executeTime:" + executeTime + "ms"); } } } }
31.456496
121
0.591694
8b7d78039ffa615f441118702e68aba2e66e103e
5,729
/** * Given a string S, find the number of different non-empty palindromic subsequences in S, * and return that number modulo 10^9 + 7. * * A subsequence of a string S is obtained by deleting 0 or more characters from S. * A sequence is palindromic if it is equal to the sequence reversed. * * Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i. * * Example 1: * * Input: * S = 'bccb' * Output: 6 * Explanation: * The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. * Note that 'bcb' is counted only once, even though it occurs twice. * * Example 2: * * Input: * S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' * Output: 104860361 * Explanation: * There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7. * * Note: * The length of S will be in the range [1, 1000]. * Each character S[i] will be in the set {'a', 'b', 'c', 'd'}. * * Approach * * Initial Values : i= 0, j= n-1; * * CountPS(i,j) * // Every single character of a string is a palindrome * // subsequence * if i == j * return 1 // palindrome of length 1 * * // If first and last characters are same, then we * // consider it as palindrome subsequence and check * // for the rest subsequence (i+1, j), (i, j-1) * Else if (str[i] == str[j)] * return countPS(i+1, j) + countPS(i, j-1) + 1; * * else * // check for rest sub-sequence and remove common * // palindromic subsequences as they are counted * // twice when we do countPS(i+1, j) + countPS(i,j-1) * return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1, j-1) * * resources/DistinctPalindromicSubsequences.jpg * resources/DistinctPalindromicSubsequencesRecursion.jpg * * Recursion: * Time Complexity: O(3^(n - 2)) = O(3^n) * Space Complexity: O(n - 2) = O(n) * * DP: * Time Complexity: O(n^2) * Space Complexity: O(n^2) * */ public class DistinctPalindromicSubsequence { private static int moduloValue = 1000000007; private static int countPalindromicSubsequencesRecursion(String s) { return countPalindromicSubsequencesRecursionHelper(s, 0, s.length() - 1) % moduloValue; } private static int countPalindromicSubsequencesRecursionHelper(String s, int i, int j) { //Base Case if (i == j) { //Only one character left return 1; } //Two characters left if (i - j == -1 || i - j == 1) { if(s.charAt(i) == s.charAt(j)) { //aa = return 3 return 2; } else { return 2; //return 2 if s[i] != s[j] for example: bc and return 3 if s[i] == s[j] if you are not counting distinct } } if(s.charAt(i) == s.charAt(j)) { return 1 + countPalindromicSubsequencesRecursionHelper(s, i + 1, j) + countPalindromicSubsequencesRecursionHelper(s, i, j - 1) - countPalindromicSubsequencesRecursionHelper(s, i + 1, j - 1); //- is for duplicates } else { return countPalindromicSubsequencesRecursionHelper(s, i + 1, j) + countPalindromicSubsequencesRecursionHelper(s, i, j - 1) - countPalindromicSubsequencesRecursionHelper(s, i + 1, j - 1); } } private static int countPalindromicSubsequencesDp(String s) { //Identify the dp table - two params changing i and j int[][] dp = new int[s.length()][s.length()]; //Initialize the dp table //Two base cases for(int i = 0; i < dp.length; i++) { for(int j = 0; j < dp.length; j++) { if (i == j) { dp[i][j] = 1; } if(i - j == -1 || i - j == 1) { if(s.charAt(i) == s.charAt(j)) { dp[i][j] = 3; } else { dp[i][j] = 2; } } } } //Traversal Direction Recursion i = 0 and j = n - 1 //opposite of recursion for (int i = s.length() - 3; i >= 0; i--) { for(int j = i + 2; j < s.length(); j++) { //Populate dp table if(s.charAt(i) == s.charAt(j)) { dp[i][j] = (1 + dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % 1000000007; } else { dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % 1000000007; } } } return dp[0][dp.length - 1]; } private static int noOfUniqueChar(String s) { char c = s.charAt(0); for(int i = 1; i < s.length(); i++) { if(s.charAt(i) != c) { return 2; } } return 1; } public static void main(String[] args) { String s = "bccb"; System.out.println("Distinct palindromic subsequences using recursion: " + countPalindromicSubsequencesRecursion(s)); s = "abcb"; System.out.println("Distinct palindromic subsequences using recursion: " + countPalindromicSubsequencesRecursion(s)); s = "bccb"; System.out.println("Distinct palindromic subsequences using DP: " + countPalindromicSubsequencesDp(s)); s = "abcb"; System.out.println("Distinct palindromic subsequences using DP: " + countPalindromicSubsequencesDp(s)); s = "aa"; System.out.println("Distinct palindromic subsequences using DP: " + countPalindromicSubsequencesDp(s)); s = "aaa"; System.out.println("Distinct palindromic subsequences using DP: " + countPalindromicSubsequencesDp(s)); } }
34.305389
138
0.561005
b60b40e1e08cef7ee4d7b3636a90da899e259710
350
package takmela.viz.webdoc.tdom.datalog; import takmelogic.engine.Call; import takmelogic.engine.Cont; public class CallAsFact implements ProcessingOp { public Call callee; public Call caller; public Cont cont; public CallAsFact(Call callee, Call caller, Cont cont) { this.callee = callee; this.caller = caller; this.cont = cont; } }
18.421053
55
0.751429
a0086470603ad43bf1e1144c400fdefc1e88e924
677
/* Leola Programming Language Author: Tony Sparks See license.txt */ package leola.ast; import leola.vm.EvalException; /** * @author Tony * */ public class NamespaceGetExpr extends Expr { private VarExpr namespace; private String identifier; public NamespaceGetExpr(VarExpr namespace, String identifier) { this.namespace = namespace; this.identifier = identifier; } @Override public void visit(ASTNodeVisitor v) throws EvalException { v.visit(this); } public VarExpr getNamespace() { return namespace; } public String getIdentifier() { return identifier; } }
16.512195
67
0.644018
f7b20dd90d8b60ae65858877c022c745325bd51d
542
package com.sxjs.jd.composition.login; import android.os.Bundle; import android.support.annotation.Nullable; import com.alibaba.android.arouter.facade.annotation.Route; import com.sxjs.jd.R; import com.sxjs.common.base.BaseActivity; /** * @author:admin on 2017/4/10 15:23. */ @Route(path = "/test/login") public class LoginActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); } }
25.809524
66
0.747232
c9edcd4b4bf881e4d308a79c26cf2f5e86011ca1
1,889
package com.googlecode.jmeter.plugins.webdriver.config; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.Capabilities; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.googlecode.jmeter.plugins.webdriver.config.RemoteCapability; import com.googlecode.jmeter.plugins.webdriver.config.RemoteDesiredCapabilitiesFactory; import com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig; public class RemoteDriverConfig extends WebDriverConfig<RemoteWebDriver> { private static final long serialVersionUID = 100L; private static final String REMOTE_SELENIUM_GRID_URL = "RemoteDriverConfig.general.selenium.grid.url"; private static final String REMOTE_CAPABILITY = "RemoteDriverConfig.general.selenium.capability"; Capabilities createCapabilities() { DesiredCapabilities capabilities = RemoteDesiredCapabilitiesFactory.build(getCapability()); capabilities.setCapability(CapabilityType.PROXY, createProxy()); capabilities.setJavascriptEnabled(true); return capabilities; } @Override protected RemoteWebDriver createBrowser() { try { return new RemoteWebDriver(new URL(getSeleniumGridUrl()), createCapabilities()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public void setSeleniumGridUrl(String seleniumUrl) { setProperty(REMOTE_SELENIUM_GRID_URL, seleniumUrl); } public String getSeleniumGridUrl() { return getPropertyAsString(REMOTE_SELENIUM_GRID_URL); } public RemoteCapability getCapability(){ return RemoteCapability.valueOf(getPropertyAsString(REMOTE_CAPABILITY)); } public void setCapability(RemoteCapability selectedCapability) { setProperty(REMOTE_CAPABILITY, selectedCapability.name()); } }
35.641509
106
0.802012
01ae1b0bfcc041e6acf365789e32bb2ff6b293b4
351
package me.learn.spring.learn1.bean; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; /** * Created by oneday on 2016/7/13 0013. */ @Data public class Student { @Autowired ClassRoom classRoom; private String name; public Student(String name) { this.name = name; } }
18.473684
63
0.655271
cbd64be0578f660ed4ccdd32a3bbecccb478fa21
7,336
/* * 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.geode.internal.cache.execute; import org.junit.experimental.categories.Category; import org.junit.Test; import static org.junit.Assert.*; import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase; import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase; import org.apache.geode.test.junit.categories.DistributedTest; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.junit.Ignore; import org.apache.geode.cache.Region; import org.apache.geode.cache.client.internal.ClientMetadataService; import org.apache.geode.cache.client.internal.ClientPartitionAdvisor; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.test.dunit.Assert; import org.apache.geode.test.dunit.Wait; import org.apache.geode.test.dunit.WaitCriterion; @Category(DistributedTest.class) public class SingleHopGetAllPutAllDUnitTest extends PRClientServerTestBase { private static final long serialVersionUID = 3873751456134028508L; public SingleHopGetAllPutAllDUnitTest() { super(); } /* * Do a getAll from client and see if all the values are returned. Will also have to see if the * function was routed from client to all the servers hosting the data. */ @Ignore("Disabled due to bug #50618") @Test public void testServerGetAllFunction() { createScenario(); client.invoke(() -> SingleHopGetAllPutAllDUnitTest.getAll()); } private void createScenario() { ArrayList commonAttributes = createCommonServerAttributes("TestPartitionedRegion", null, 1, 13, null); createClientServerScenarioSingleHop(commonAttributes, 20, 20, 20); } public static void getAll() { Region region = cache.getRegion(PartitionedRegionName); assertNotNull(region); final List testValueList = new ArrayList(); final List testKeyList = new ArrayList(); for (int i = (totalNumBuckets.intValue() * 3); i > 0; i--) { testValueList.add("execKey-" + i); } DistributedSystem.setThreadsSocketPolicy(false); try { int j = 0; Map origVals = new HashMap(); for (Iterator i = testValueList.iterator(); i.hasNext();) { testKeyList.add(j); Integer key = new Integer(j++); Object val = i.next(); origVals.put(key, val); region.put(key, val); } // check if the client meta-data is in synch verifyMetadata(); // check if the function was routed to pruned nodes Map resultMap = region.getAll(testKeyList); assertTrue(resultMap.equals(origVals)); Wait.pause(2000); Map secondResultMap = region.getAll(testKeyList); assertTrue(secondResultMap.equals(origVals)); } catch (Exception e) { Assert.fail("Test failed after the getAll operation", e); } } private static void verifyMetadata() { Region region = cache.getRegion(PartitionedRegionName); ClientMetadataService cms = ((GemFireCacheImpl) cache).getClientMetadataService(); cms.getClientPRMetadata((LocalRegion) region); final Map<String, ClientPartitionAdvisor> regionMetaData = cms.getClientPRMetadata_TEST_ONLY(); WaitCriterion wc = new WaitCriterion() { public boolean done() { return (regionMetaData.size() == 1); } public String description() { return "Region metadat size is not 1. Exisitng size of regionMetaData is " + regionMetaData.size(); } }; Wait.waitForCriterion(wc, 5000, 200, true); assertTrue(regionMetaData.containsKey(region.getFullPath())); final ClientPartitionAdvisor prMetaData = regionMetaData.get(region.getFullPath()); wc = new WaitCriterion() { public boolean done() { return (prMetaData.getBucketServerLocationsMap_TEST_ONLY().size() == 13); } public String description() { return "Bucket server location map size is not 13. Exisitng size is :" + prMetaData.getBucketServerLocationsMap_TEST_ONLY().size(); } }; Wait.waitForCriterion(wc, 5000, 200, true); for (Entry entry : prMetaData.getBucketServerLocationsMap_TEST_ONLY().entrySet()) { assertEquals(2, ((List) entry.getValue()).size()); } } /* * Do a getAll from client and see if all the values are returned. Will also have to see if the * function was routed from client to all the servers hosting the data. */ @Test public void testServerPutAllFunction() { createScenario(); client.invoke(() -> SingleHopGetAllPutAllDUnitTest.putAll()); } public static void putAll() { Region<String, String> region = cache.getRegion(PartitionedRegionName); assertNotNull(region); final Map<String, String> keysValuesMap = new HashMap<String, String>(); final List<String> testKeysList = new ArrayList<String>(); for (int i = (totalNumBuckets.intValue() * 3); i > 0; i--) { testKeysList.add("execKey-" + i); keysValuesMap.put("execKey-" + i, "values-" + i); } DistributedSystem.setThreadsSocketPolicy(false); try { // check if the client meta-data is in synch // check if the function was routed to pruned nodes region.putAll(keysValuesMap); // check the listener // check how the function was executed Wait.pause(2000); region.putAll(keysValuesMap); // check if the client meta-data is in synch verifyMetadata(); // check if the function was routed to pruned nodes Map<String, String> resultMap = region.getAll(testKeysList); assertTrue(resultMap.equals(keysValuesMap)); Wait.pause(2000); Map<String, String> secondResultMap = region.getAll(testKeysList); assertTrue(secondResultMap.equals(keysValuesMap)); // Now test removeAll region.removeAll(testKeysList); HashMap<String, Object> noValueMap = new HashMap<String, Object>(); for (String key : testKeysList) { noValueMap.put(key, null); } assertEquals(noValueMap, region.getAll(testKeysList)); Wait.pause(2000); // Why does this test keep pausing for 2 seconds and then do the exact same // thing? region.removeAll(testKeysList); assertEquals(noValueMap, region.getAll(testKeysList)); } catch (Exception e) { Assert.fail("Test failed after the putAll operation", e); } } }
36.497512
100
0.704471
4a0747749eb6e36ec3897a1bc5aadd1af71b7b00
2,052
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.debug.jdi.tests; import com.sun.jdi.ShortValue; /** * Tests for JDI com.sun.jdi.ShortValue. */ public class ShortValueTest extends AbstractJDITest { private ShortValue fValue; /** * Creates a new test. */ public ShortValueTest() { super(); } /** * Init the fields that are used by this test only. */ @Override public void localSetUp() { // Get short value for 12345 fValue = fVM.mirrorOf((short) 12345); } /** * Run all tests and output to standard output. * @param args */ public static void main(java.lang.String[] args) { new ShortValueTest().runSuite(args); } /** * Gets the name of the test case. * @see junit.framework.TestCase#getName() */ @Override public String getName() { return "com.sun.jdi.ShortValue"; } /** * Test JDI equals() and hashCode(). */ public void testJDIEquality() { assertTrue("1", fValue.equals(fVM.mirrorOf((short) 12345))); assertTrue("2", !fValue.equals(fVM.mirrorOf((short) 54321))); assertTrue("3", !fValue.equals(new Object())); assertTrue("4", !fValue.equals(null)); assertEquals("5", fValue.hashCode(), fVM.mirrorOf((short) 12345).hashCode()); assertTrue("6", fValue.hashCode() != fVM.mirrorOf((short) 54321).hashCode()); } /** * Test JDI value(). */ public void testJDIValue() { assertTrue("1", (short) 12345 == fValue.value()); } }
27.72973
85
0.57846
62e5acd8c6ed8bbd8ba3a844d47604d49e26a1f3
524
//generated by abstract-syntax-gen package minillvm.ast; import java.util.*; public interface TypeArray extends Element, Type { void setOf(Type of); Type getOf(); void setSize(int size); int getSize(); Element getParent(); TypeArray copy(); TypeArray copyWithRefs(); void clearAttributes(); void clearAttributesLocal(); /** */ public abstract String toString(); /** "checks, whether this type is equal to another type"*/ public abstract boolean equalsType(Type other); }
26.2
62
0.679389
a452f5e72821a1bd5bf0cdc7b77d39e0dafef17d
6,221
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.commons.java.nio.fs.file; import java.io.File; import org.junit.Test; import org.kie.commons.java.nio.IOException; import org.kie.commons.java.nio.base.GeneralPathImpl; import org.kie.commons.java.nio.file.FileStore; import org.kie.commons.java.nio.file.FileSystem; import org.kie.commons.java.nio.file.Path; import org.kie.commons.java.nio.file.attribute.BasicFileAttributeView; import org.kie.commons.java.nio.file.attribute.BasicFileAttributes; import org.kie.commons.java.nio.file.attribute.FileAttributeView; import org.kie.commons.java.nio.file.attribute.FileStoreAttributeView; import org.kie.commons.java.nio.file.attribute.FileTime; import org.kie.commons.java.nio.file.spi.FileSystemProvider; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.*; public class SimpleWindowsFileStoreTest { final FileSystemProvider fsProvider = mock( FileSystemProvider.class ); final File[] roots = new File[]{ new File( "c:\\" ), new File( "a:\\" ) }; final FileSystem fileSystem = new SimpleWindowsFileSystem( roots, fsProvider, "c:\\" ); final Path nonNullPath = GeneralPathImpl.create( fileSystem, "c:\\something", false ); @Test public void simpleTests() { final Path path = GeneralPathImpl.create( fileSystem, "something", false ); final FileStore fileStore = new SimpleWindowsFileStore( roots, path ); assertThat( fileStore.name() ).isNotNull().isEqualTo( "c:\\" ); assertThat( fileStore.type() ).isNull(); assertThat( fileStore.isReadOnly() ).isFalse(); assertThat( fileStore.getTotalSpace() ).isEqualTo( 0L ); assertThat( fileStore.getUsableSpace() ).isEqualTo( 0L ); assertThat( fileStore.supportsFileAttributeView( BasicFileAttributeView.class ) ).isTrue(); assertThat( fileStore.supportsFileAttributeView( MyFileAttributeView.class ) ).isFalse(); assertThat( fileStore.supportsFileAttributeView( MyAlsoInvalidFileAttributeView.class ) ).isFalse(); assertThat( fileStore.supportsFileAttributeView( "basic" ) ).isTrue(); assertThat( fileStore.supportsFileAttributeView( "any" ) ).isFalse(); assertThat( fileStore.supportsFileAttributeView( BasicFileAttributeView.class.getName() ) ).isFalse(); assertThat( fileStore.supportsFileAttributeView( MyAlsoInvalidFileAttributeView.class.getName() ) ).isFalse(); assertThat( fileStore.getFileStoreAttributeView( FileStoreAttributeView.class ) ).isNull(); assertThat( fileStore.getAttribute( "name" ) ).isNotNull().isEqualTo( fileStore.name() ); assertThat( fileStore.getAttribute( "totalSpace" ) ).isNotNull().isEqualTo( fileStore.getTotalSpace() ); assertThat( fileStore.getAttribute( "usableSpace" ) ).isNotNull().isEqualTo( fileStore.getUsableSpace() ); assertThat( fileStore.getAttribute( "readOnly" ) ).isNotNull().isEqualTo( fileStore.isReadOnly() ); } @Test(expected = IllegalArgumentException.class) public void contructorWithNullRootsAndPath() { new SimpleWindowsFileStore( (File[]) null, (Path) null ); } @Test(expected = IllegalStateException.class) public void contructorWithEmptyRoots() { new SimpleWindowsFileStore( new File[]{ }, null ); } @Test(expected = UnsupportedOperationException.class) public void getUnallocatedSpaceUnsupportedOp() { new SimpleWindowsFileStore( roots, nonNullPath ).getUnallocatedSpace(); } @Test(expected = UnsupportedOperationException.class) public void getAttributeUnsupportedOp() { new SimpleWindowsFileStore( roots, nonNullPath ).getAttribute( "someValueHere" ); } @Test(expected = IllegalArgumentException.class) public void supportsFileAttributeViewNull1() { new SimpleWindowsFileStore( roots, nonNullPath ).supportsFileAttributeView( (Class<? extends FileAttributeView>) null ); } @Test(expected = IllegalArgumentException.class) public void supportsFileAttributeViewNull2() { new SimpleWindowsFileStore( roots, nonNullPath ).supportsFileAttributeView( (String) null ); } @Test(expected = IllegalArgumentException.class) public void supportsFileAttributeViewEmpty() { new SimpleWindowsFileStore( roots, nonNullPath ).supportsFileAttributeView( "" ); } @Test(expected = IllegalArgumentException.class) public void getFileStoreAttributeViewNull() { new SimpleWindowsFileStore( roots, nonNullPath ).getFileStoreAttributeView( null ); } @Test(expected = IllegalArgumentException.class) public void getAttributeNull() { new SimpleWindowsFileStore( roots, nonNullPath ).getAttribute( null ); } @Test(expected = IllegalArgumentException.class) public void getAttributeEmpty() { new SimpleWindowsFileStore( roots, nonNullPath ).getAttribute( "" ); } private static class MyFileAttributeView implements FileAttributeView { @Override public String name() { return null; } } private static class MyAlsoInvalidFileAttributeView implements BasicFileAttributeView { @Override public BasicFileAttributes readAttributes() throws IOException { return null; } @Override public void setTimes( FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime ) throws IOException { } @Override public String name() { return null; } } }
42.033784
128
0.708889
0ba42fc3132ae047f89123dc01fb106860ba78a7
2,047
/* * Copyright (c) 2016 EMC Corporation * All Rights Reserved */ package com.emc.storageos.management.backup.util; import java.io.IOException; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProcessInputStream extends InputStream { private static final Logger log = LoggerFactory.getLogger(ProcessInputStream.class); InputStream stdinStream; ProcessRunner processor; StringBuilder errText = new StringBuilder(); public ProcessInputStream(ProcessRunner processor) { this.processor = processor; this.stdinStream = processor.getStdOut(); processor.captureAllTextInBackground(processor.getStdErr(), this.errText); } public ProcessInputStream(Process childProcess) throws IOException { this(new ProcessRunner(childProcess, true)); } @Override public int read() throws IOException { return this.stdinStream.read(); } @Override public int read(byte b[]) throws IOException { return stdinStream.read(b); } @Override public int read(byte b[], int off, int len) throws IOException { return stdinStream.read(b, off, len); } @Override public void close() throws IOException { if (this.stdinStream != null) { int remains; while (( remains = stdinStream.available()) > 0) { stdinStream.skip(remains); } this.stdinStream.close(); this.stdinStream = null; } if (this.processor != null) { int exitCode = 0; try { exitCode = this.processor.join(); } catch (InterruptedException e) { log.error("Interrupted when waiting for process", e); } this.processor.close(); this.processor = null; if (exitCode != 0) { throw new IOException(errText.length() > 0 ? errText.toString() : Integer.toString(exitCode)); } } } }
27.662162
110
0.615046
f692d8f388f3950e37889d4650b4e48db7fe12f4
353
/** * <p> * Provides implementation to make formula evaluation result "flat", i.e. to agreggate * operands for AND or OR logical operations. * <p> * This can be used for formula presentation as "flat" formula is not as deep as basic * SPL formula with binary AND or OR logical operations. */ package cz.cuni.mff.spl.evaluator.output.flatformula;
39.222222
87
0.736544
6e4a40e5be5df1fdd824c5400488514ee9bd9ce1
280
package com.venky.swf.plugins.collab.extensions.beforesave; import com.venky.swf.plugins.collab.db.model.user.UserPhone; public class BeforeValidateUserPhone extends BeforeValidatePhone<UserPhone> { static { registerExtension(new BeforeValidateUserPhone()); } }
28
77
0.782143
766c28bd9695104fee90f7ac63453fcffa8ec7e6
240
package hkube.storage; import hkube.utils.Config; public interface IStorageConfig { public String getStorageType(); public String getClusterName(); public Config getTypeSpecificConfig(); public String getEncodingType(); }
21.818182
42
0.758333
f89fefb4037bd425a81e18efe25bfd9fe7e09eea
29,625
/* * Copyright (C) 2019 Google 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 com.google.cloud.teleport.v2.transforms; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull; import com.google.api.client.json.JsonFactory; import com.google.api.services.bigquery.model.TableRow; import com.google.auto.value.AutoValue; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.LegacySQLTypeName; import com.google.cloud.teleport.v2.options.BigQueryCommonOptions.WriteOptions; import com.google.cloud.teleport.v2.transforms.JavascriptTextTransformer.JavascriptTextTransformerOptions; import com.google.cloud.teleport.v2.utils.SerializableSchemaSupplier; import com.google.cloud.teleport.v2.values.FailsafeElement; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.Coder.Context; import org.apache.beam.sdk.extensions.gcp.util.Transport; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryInsertError; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryUtils; import org.apache.beam.sdk.io.gcp.bigquery.InsertRetryPolicy; import org.apache.beam.sdk.io.gcp.bigquery.TableRowJsonCoder; import org.apache.beam.sdk.metrics.Counter; import org.apache.beam.sdk.metrics.Metrics; import org.apache.beam.sdk.options.Default; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.schemas.utils.AvroUtils; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.Flatten; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionList; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.POutput; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.CharMatcher; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Splitter; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Supplier; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Suppliers; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Throwables; import org.apache.commons.text.StringSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Common transforms for Teleport BigQueryIO. */ public class BigQueryConverters { /* Logger for class. */ private static final Logger LOG = LoggerFactory.getLogger(BigQueryConverters.class); private static final JsonFactory JSON_FACTORY = Transport.getJsonFactory(); /** * Converts a JSON string to a {@link TableRow} object. If the data fails to convert, a {@link * RuntimeException} will be thrown. * * @param json The JSON string to parse. * @return The parsed {@link TableRow} object. */ public static TableRow convertJsonToTableRow(String json) { TableRow row; // Parse the JSON into a {@link TableRow} object. try (InputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) { row = TableRowJsonCoder.of().decode(inputStream, Context.OUTER); } catch (IOException e) { throw new RuntimeException("Failed to serialize json to table row: " + json, e); } return row; } /** * Creates a {@link Write} transform based on {@code options}. * * <p>Along with the values in {@code options}, the following are set by default: * * <ul> * <li>{@link InsertRetryPolicy#retryTransientErrors()} * <li>{@link Write#withExtendedErrorInfo()} * </ul> * * <p>It is the responsibility of the caller to set the schema and write method on the returned * value. * * @param options The options for configuring this write transform. * @param <T> The {@link POutput} type of this write. Since type inference does not work when * setting a schema on the returned {@link Write}, this value must be explicitly set. * @return The write transform, which can be further configured as needed. */ public static <T> Write<T> createWriteTransform(WriteOptions options) { return BigQueryIO.<T>write() .to(options.getOutputTableSpec()) .withWriteDisposition(WriteDisposition.valueOf(options.getWriteDisposition())) .withCreateDisposition(CreateDisposition.valueOf(options.getCreateDisposition())) .withFailedInsertRetryPolicy(InsertRetryPolicy.retryTransientErrors()) .withExtendedErrorInfo(); } /** * The {@link TableRowToJsonFn} class converts a tableRow to Json using {@link * #tableRowToJson(TableRow)}. */ public static class TableRowToJsonFn extends DoFn<TableRow, String> { @ProcessElement public void processElement(ProcessContext context) { TableRow row = context.element(); context.output(tableRowToJson(row)); } } /** Converts a {@link TableRow} into a Json string using {@link Gson}. */ public static String tableRowToJson(TableRow row) { return new Gson().toJson(row, TableRow.class); } /** * The {@link BigQueryReadOptions} interface contains option necessary to interface with BigQuery. */ public interface BigQueryReadOptions extends PipelineOptions { @Description("BigQuery table to export from in the form <project>:<dataset>.<table>") String getInputTableSpec(); void setInputTableSpec(String inputTableSpec); @Description( "The dead-letter table to output to within BigQuery in <project-id>:<dataset>.<table> " + "format. If it doesn't exist, it will be created during pipeline execution.") String getOutputDeadletterTable(); void setOutputDeadletterTable(String outputDeadletterTable); @Description("Optional: Query to run against input table") String getQuery(); void setQuery(String query); @Description("Set to true to use legacy SQL. Default:false") @Default.Boolean(false) Boolean getUseLegacySql(); void setUseLegacySql(Boolean useLegacySql); } /** * The {@link FailsafeJsonToTableRow} transform converts JSON strings to {@link TableRow} objects. * The transform accepts a {@link FailsafeElement} object so the original payload of the incoming * record can be maintained across multiple series of transforms. */ @AutoValue public abstract static class FailsafeJsonToTableRow<T> extends PTransform<PCollection<FailsafeElement<T, String>>, PCollectionTuple> { public static <T> Builder<T> newBuilder() { return new AutoValue_BigQueryConverters_FailsafeJsonToTableRow.Builder<>(); } public abstract TupleTag<TableRow> successTag(); public abstract TupleTag<FailsafeElement<T, String>> failureTag(); @Override public PCollectionTuple expand(PCollection<FailsafeElement<T, String>> failsafeElements) { return failsafeElements.apply( "JsonToTableRow", ParDo.of( new DoFn<FailsafeElement<T, String>, TableRow>() { @ProcessElement public void processElement(ProcessContext context) { FailsafeElement<T, String> element = context.element(); String json = element.getPayload(); try { TableRow row = convertJsonToTableRow(json); context.output(row); } catch (Exception e) { context.output( failureTag(), FailsafeElement.of(element) .setErrorMessage(e.getMessage()) .setStacktrace(Throwables.getStackTraceAsString(e))); } } }) .withOutputTags(successTag(), TupleTagList.of(failureTag()))); } /** Builder for {@link FailsafeJsonToTableRow}. */ @AutoValue.Builder public abstract static class Builder<T> { public abstract Builder<T> setSuccessTag(TupleTag<TableRow> successTag); public abstract Builder<T> setFailureTag(TupleTag<FailsafeElement<T, String>> failureTag); public abstract FailsafeJsonToTableRow<T> build(); } } /** * The {@link ReadBigQuery} class reads from BigQuery using {@link BigQueryIO}. The transform * returns a {@link PCollection} of {@link TableRow}. */ @AutoValue public abstract static class ReadBigQuery extends PTransform<PBegin, PCollection<TableRow>> { public static Builder newBuilder() { return new AutoValue_BigQueryConverters_ReadBigQuery.Builder(); } public abstract BigQueryReadOptions options(); @Override public PCollection<TableRow> expand(PBegin pipeline) { if (options().getQuery() == null) { LOG.info("No query provided, reading directly from: " + options().getInputTableSpec()); return pipeline.apply( "ReadFromBigQuery", BigQueryIO.readTableRows() .from(options().getInputTableSpec()) .withTemplateCompatibility() .withMethod(Method.DIRECT_READ) .withCoder(TableRowJsonCoder.of())); } else { LOG.info("Using query: " + options().getQuery()); if (!options().getUseLegacySql()) { LOG.info("Using Standard SQL"); return pipeline.apply( "ReadFromBigQueryWithQuery", BigQueryIO.readTableRows() .fromQuery(options().getQuery()) .withTemplateCompatibility() .usingStandardSql() .withCoder(TableRowJsonCoder.of())); } else { LOG.info("Using Legacy SQL"); return pipeline.apply( "ReadFromBigQueryWithQuery", BigQueryIO.readTableRows() .fromQuery(options().getQuery()) .withTemplateCompatibility() .withCoder(TableRowJsonCoder.of())); } } } /** Builder for {@link ReadBigQuery}. */ @AutoValue.Builder public abstract static class Builder { public abstract Builder setOptions(BigQueryReadOptions options); abstract ReadBigQuery autoBuild(); public ReadBigQuery build() { ReadBigQuery readBigQuery = autoBuild(); if (readBigQuery.options().getInputTableSpec() == null) { checkArgument( readBigQuery.options().getQuery() != null, "If no inputTableSpec is provided then a query is required."); } if (readBigQuery.options().getQuery() == null) { checkArgument( readBigQuery.options().getInputTableSpec() != null, "If no query is provided then an inputTableSpec is required."); } return readBigQuery; } } } /** * The {@link TableRowToFailsafeJsonDocument} class is a {@link PTransform} which transforms * {@link TableRow} objects into Json documents for insertion into Elasticsearch. Optionally a * javascript UDF can be supplied to parse the {@link TableRow} object. The executions of the UDF * and transformation to {@link TableRow} objects is done in a fail-safe way by wrapping the * element with it's original payload inside the {@link FailsafeElement} class. The {@link * TableRowToFailsafeJsonDocument} transform will output a {@link PCollectionTuple} which contains * all output and dead-letter {@link PCollection}. * * <p>The {@link PCollectionTuple} output will contain the following {@link PCollection}: * * <ul> * <li>{@link TableRowToFailsafeJsonDocument#transformOutTag()} - Contains all records * successfully converted from JSON to {@link TableRow} objects. * <li>{@link TableRowToFailsafeJsonDocument#transformDeadletterOutTag()} - Contains all {@link * FailsafeElement} records which couldn't be converted to table rows. * </ul> */ @AutoValue public abstract static class TableRowToFailsafeJsonDocument extends PTransform<PCollection<TableRow>, PCollectionTuple> { public static Builder newBuilder() { return new AutoValue_BigQueryConverters_TableRowToFailsafeJsonDocument.Builder(); } public abstract JavascriptTextTransformerOptions options(); public abstract TupleTag<FailsafeElement<TableRow, String>> udfOutTag(); public abstract TupleTag<FailsafeElement<TableRow, String>> udfDeadletterOutTag(); public abstract TupleTag<FailsafeElement<TableRow, String>> transformOutTag(); public abstract TupleTag<FailsafeElement<TableRow, String>> transformDeadletterOutTag(); @Override public PCollectionTuple expand(PCollection<TableRow> input) { PCollectionTuple udfOut; PCollectionTuple failsafeTableRows = input.apply( "TableRowToFailsafeElement", ParDo.of(new TableRowToFailsafeElementFn(transformDeadletterOutTag())) .withOutputTags(transformOutTag(), TupleTagList.of(transformDeadletterOutTag()))); // Use Udf to parse table rows if supplied. if (options().getJavascriptTextTransformGcsPath() != null) { udfOut = failsafeTableRows .get(transformOutTag()) .apply( "ProcessFailsafeRowsUdf", JavascriptTextTransformer.FailsafeJavascriptUdf.<TableRow>newBuilder() .setFileSystemPath(options().getJavascriptTextTransformGcsPath()) .setFunctionName(options().getJavascriptTextTransformFunctionName()) .setSuccessTag(udfOutTag()) .setFailureTag(udfDeadletterOutTag()) .build()); PCollection<FailsafeElement<TableRow, String>> failedOut = PCollectionList.of(udfOut.get(udfDeadletterOutTag())) .and(failsafeTableRows.get(transformDeadletterOutTag())) .apply("FlattenFailedOut", Flatten.pCollections()); return PCollectionTuple.of(transformOutTag(), udfOut.get(udfOutTag())) .and(transformDeadletterOutTag(), failedOut); } else { return failsafeTableRows; } } /** Builder for {@link TableRowToFailsafeJsonDocument}. */ @AutoValue.Builder public abstract static class Builder { public abstract Builder setOptions(JavascriptTextTransformerOptions options); public abstract Builder setTransformOutTag( TupleTag<FailsafeElement<TableRow, String>> transformOutTag); public abstract Builder setTransformDeadletterOutTag( TupleTag<FailsafeElement<TableRow, String>> transformDeadletterOutTag); public abstract Builder setUdfOutTag(TupleTag<FailsafeElement<TableRow, String>> udfOutTag); public abstract Builder setUdfDeadletterOutTag( TupleTag<FailsafeElement<TableRow, String>> udfDeadletterOutTag); public abstract TableRowToFailsafeJsonDocument build(); } } /** * The {@link TableRowToFailsafeElementFn} wraps an {@link TableRow} with the {@link * FailsafeElement} class so errors can be recovered from and the original message can be output * to a error records table. */ static class TableRowToFailsafeElementFn extends DoFn<TableRow, FailsafeElement<TableRow, String>> { private final TupleTag<FailsafeElement<TableRow, String>> transformDeadletterOutTag; /** {@link Counter} for successfully processed elements. */ private Counter successCounter = Metrics.counter(TableRowToFailsafeElementFn.class, "SuccessProcessCounter"); /** {@link Counter} for un-successfully processed elements. */ private Counter failedCounter = Metrics.counter(TableRowToFailsafeElementFn.class, "FailedProcessCounter"); TableRowToFailsafeElementFn( TupleTag<FailsafeElement<TableRow, String>> transformDeadletterOutTag) { this.transformDeadletterOutTag = transformDeadletterOutTag; } @ProcessElement public void processElement(ProcessContext context) { TableRow row = context.element(); try { context.output(FailsafeElement.of(row, tableRowToJson(row))); successCounter.inc(); } catch (Exception e) { context.output( this.transformDeadletterOutTag, FailsafeElement.of(row, row.toString()) .setErrorMessage(e.getMessage()) .setStacktrace(Throwables.getStackTraceAsString(e))); failedCounter.inc(); } } } /** * The {@link FailsafeTableRowToFailsafeStringFn} converts a {@link FailsafeElement} containing a * {@link TableRow} and string into a {@link FailsafeElement} containing two strings. The output * {@link FailsafeElement#getOriginalPayload()} will return {@link TableRow#toString()}. */ public static class FailsafeTableRowToFailsafeStringFn extends DoFn<FailsafeElement<TableRow, String>, FailsafeElement<String, String>> { @ProcessElement public void processElement(ProcessContext context) { FailsafeElement<TableRow, String> element = context.element(); context.output( FailsafeElement.of(element.getOriginalPayload().toString(), element.getPayload())); } } /** * Method to wrap a {@link BigQueryInsertError} into a {@link FailsafeElement}. * * @param insertError BigQueryInsert error. * @return FailsafeElement object. * @throws IOException */ public static FailsafeElement<String, String> wrapBigQueryInsertError( BigQueryInsertError insertError) { FailsafeElement<String, String> failsafeElement; try { String rowPayload = JSON_FACTORY.toString(insertError.getRow()); String errorMessage = JSON_FACTORY.toString(insertError.getError()); failsafeElement = FailsafeElement.of(rowPayload, rowPayload); failsafeElement.setErrorMessage(errorMessage); } catch (IOException e) { throw new RuntimeException(e); } return failsafeElement; } /** * Returns {@code String} using Key/Value style formatting. * * <p>Extracts TableRow fields and applies values to the formatTemplate. ie. * formatStringTemplate("I am {key}"{"key": "formatted"}) -> "I am formatted" * * @param formatTemplate a String with bracketed keys to apply "I am a {key}" * @param row is a TableRow object which is used to supply key:values to the template */ public static String formatStringTemplate(String formatTemplate, TableRow row) { // Key/Value Map used to replace values in template Map<String, String> values = new HashMap<>(); // Put all column/value pairs into key/value map Set<String> rowKeys = row.keySet(); for (String rowKey : rowKeys) { // Only String types can be used in comparison if (row.get(rowKey) instanceof String) { values.put(rowKey, (String) row.get(rowKey)); } } // Substitute any templated values in the template String result = StringSubstitutor.replace(formatTemplate, values, "{", "}"); return result; } /** A {@link SerializableFunction} to convert a {@link TableRow} to a {@link GenericRecord}. */ public static class TableRowToGenericRecordFn implements SerializableFunction<TableRow, GenericRecord> { /** * Creates a {@link SerializableFunction} that uses a {@link Schema} to translate a {@link * TableRow} into a {@link GenericRecord}. * * @param avroSchema schema to be used for the {@link GenericRecord} * @return a {@link GenericRecord} based on the {@link TableRow} */ public static TableRowToGenericRecordFn of(Schema avroSchema) { checkNotNull(avroSchema, "avroSchema is required."); return new TableRowToGenericRecordFn(avroSchema); } private final org.apache.beam.sdk.schemas.Schema beamSchema; private final Supplier<Schema> avroSchemaSupplier; private TableRowToGenericRecordFn(Schema avroSchema) { avroSchemaSupplier = Suppliers.memoize(SerializableSchemaSupplier.of(avroSchema)); beamSchema = AvroUtils.toBeamSchema(avroSchema); } @Override public GenericRecord apply(TableRow tableRow) { Row row = BigQueryUtils.toBeamRow(beamSchema, tableRow); return AvroUtils.toGenericRecord(row, avroSchemaSupplier.get()); } } /** * The {@link BigQueryTableConfigManager} POJO Class to manage the BigQuery Output Table * configurations. It allows for a full table path or a set of table template params to be * supplied interchangeably. * * <p>Optionally supply projectIdVal, datasetTemplateVal, and tableTemplateVal or the config * manager will default to using outputTableSpec. */ public static class BigQueryTableConfigManager { public String projectId; public String datasetTemplate; public String tableTemplate; /** * Build a {@code BigQueryTableConfigManager} for use in pipelines. * * @param projectIdVal The Project ID for the GCP BigQuery project. * @param datasetTemplateVal The BQ Dataset value or a templated value. * @param tableTemplateVal The BQ Table value or a templated value. * @param outputTableSpec The full path of a BQ Table ie. `project:dataset.table` * <p>Optionally supply projectIdVal, datasetTemplateVal, and tableTemplateVal or the config * manager will default to using outputTableSpec. */ public BigQueryTableConfigManager( String projectIdVal, String datasetTemplateVal, String tableTemplateVal, String outputTableSpec) { if (datasetTemplateVal == null || tableTemplateVal == null) { // Legacy Config Option List<String> tableObjs = Splitter.on(CharMatcher.anyOf(":.")).splitToList(outputTableSpec); this.projectId = tableObjs.get(0); this.datasetTemplate = tableObjs.get(1); this.tableTemplate = tableObjs.get(2); // this.projectId = outputTableSpec.split(":", 2)[0]; // this.datasetTemplate = outputTableSpec.split(":", 2)[1].split("\\.")[0]; // this.tableTemplate = outputTableSpec.split(":", 2)[1].split("\\.", 2)[1]; } else { this.projectId = projectIdVal; this.datasetTemplate = datasetTemplateVal; this.tableTemplate = tableTemplateVal; } } public String getProjectId() { return this.projectId; } public String getDatasetTemplate() { return this.datasetTemplate; } public String getTableTemplate() { return this.tableTemplate; } public String getOutputTableSpec() { String tableSpec = String.format("%s:%s.%s", this.projectId, this.datasetTemplate, this.tableTemplate); return tableSpec; } } /** * If deadletterTable is available, it is returned as is, otherwise outputTableSpec + * defaultDeadLetterTableSuffix is returned instead. */ /** * Return a {@code String} table name to be used as a dead letter queue. * * @param deadletterTable Default dead letter table to use. * @param outputTableSpec Name of the BigQuery output table for successful rows. * @param defaultDeadLetterTableSuffix An optional suffix off the successful table. */ public static String maybeUseDefaultDeadletterTable( String deadletterTable, String outputTableSpec, String defaultDeadLetterTableSuffix) { if (deadletterTable == null) { return outputTableSpec + defaultDeadLetterTableSuffix; } else { return deadletterTable; } } public static final Map<String, LegacySQLTypeName> BQ_TYPE_STRINGS = new HashMap<String, LegacySQLTypeName>() { { put("BOOLEAN", LegacySQLTypeName.BOOLEAN); put("BYTES", LegacySQLTypeName.BYTES); put("DATE", LegacySQLTypeName.DATE); put("DATETIME", LegacySQLTypeName.DATETIME); put("FLOAT", LegacySQLTypeName.FLOAT); put("INTEGER", LegacySQLTypeName.INTEGER); put("NUMERIC", LegacySQLTypeName.NUMERIC); put("RECORD", LegacySQLTypeName.RECORD); put("STRING", LegacySQLTypeName.STRING); put("TIME", LegacySQLTypeName.TIME); put("TIMESTAMP", LegacySQLTypeName.TIMESTAMP); } }; /** * The {@link SchemaUtils} Class to easily convert from a json string to a BigQuery List<Field>. */ public static class SchemaUtils { private static final Type gsonSchemaType = new TypeToken<List<Map>>() {}.getType(); private static Field mapToField(Map fMap) { String typeStr = fMap.get("type").toString(); String nameStr = fMap.get("name").toString(); String modeStr = fMap.get("mode").toString(); LegacySQLTypeName type = BQ_TYPE_STRINGS.get(typeStr); if (type == null) { type = LegacySQLTypeName.STRING; } return Field.newBuilder(nameStr, type).setMode(Field.Mode.valueOf(modeStr)).build(); } private static List<Field> listToFields(List<Map> jsonFields) { List<Field> fields = new ArrayList(jsonFields.size()); for (Map m : jsonFields) { fields.add(mapToField(m)); } return fields; } /** * Return a {@code List<Field>} extracted from a json string. * * @param schemaStr JSON String with BigQuery schema fields. */ public static List<Field> schemaFromString(String schemaStr) { if (schemaStr == null) { return null; } else { Gson gson = new Gson(); List<Map> jsonFields = gson.fromJson(schemaStr, gsonSchemaType); return listToFields(jsonFields); } } } /** Converts a row to tableRow via {@link BigQueryUtils#toTableRow()}. */ public static SerializableFunction<Row, TableRow> rowToTableRowFn = BigQueryUtils::toTableRow; /** * The {@link FailsafeRowToTableRow} transform converts {@link Row} to {@link TableRow} objects. * The transform accepts a {@link FailsafeElement} object so the original payload of the incoming * record can be maintained across multiple series of transforms. */ @AutoValue public abstract static class FailsafeRowToTableRow<T> extends PTransform<PCollection<FailsafeElement<T, Row>>, PCollectionTuple> { public static <T> Builder<T> newBuilder() { return new AutoValue_BigQueryConverters_FailsafeRowToTableRow.Builder<>(); } public abstract TupleTag<TableRow> successTag(); public abstract TupleTag<FailsafeElement<T, Row>> failureTag(); @Override public PCollectionTuple expand(PCollection<FailsafeElement<T, Row>> failsafeElements) { return failsafeElements.apply( "FailsafeRowToTableRow", ParDo.of( new DoFn<FailsafeElement<T, Row>, TableRow>() { @ProcessElement public void processElement(ProcessContext context) { FailsafeElement<T, Row> element = context.element(); Row row = element.getPayload(); try { TableRow tableRow = BigQueryUtils.toTableRow(row); context.output(tableRow); } catch (Exception e) { context.output( failureTag(), FailsafeElement.of(element) .setErrorMessage(e.getMessage()) .setStacktrace(Throwables.getStackTraceAsString(e))); } } }) .withOutputTags(successTag(), TupleTagList.of(failureTag()))); } /** Builder for {@link FailsafeRowToTableRow}. */ @AutoValue.Builder public abstract static class Builder<T> { public abstract Builder<T> setSuccessTag(TupleTag<TableRow> successTag); public abstract Builder<T> setFailureTag(TupleTag<FailsafeElement<T, Row>> failureTag); public abstract FailsafeRowToTableRow<T> build(); } } }
39.083113
106
0.685637
b42434b7021834d824b4d9507b82fd7df2db81ae
302
package creational.builder.sample4; class SubaruBuilder extends CarBuilder { void buildMake() { car.setMake("Subaru Forester"); } void buildTransmission() { car.setTransmission(Transmission.MANUAL); } void buildMaxSpeed() { car.setMaxSpeed(270); } }
17.764706
49
0.642384
cfa2e7cf1d399173d552a851220d3c00c5858c6b
3,560
/******************************************************************************* * Copyright (c) 2010 Haifeng Li * * 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 smile.feature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import smile.data.Attribute; import smile.math.Math; /** * Normalize samples individually to unit norm. Each sample (i.e. each row of * the data matrix) with at least one non zero component is rescaled * independently of other samples so that its norm (L1 or L2) equals one. * <p> * Scaling inputs to unit norms is a common operation for text * classification or clustering for instance. * * @author Haifeng Li */ public class Normalizer extends FeatureTransform { private static final Logger logger = LoggerFactory.getLogger(Normalizer.class); /** * The types of data scaling. */ public static enum Norm { /** * L1 vector norm. */ L1, /** * L2 vector norm. */ L2, /** * L-infinity vector norm. Maximum absolute value. */ Inf } /** The type of norm .*/ private Norm norm = Norm.L2; /** Default constructor with L2 norm. */ public Normalizer() { } /** * Constructor with L2 norm. * @param copy If false, try to avoid a copy and do inplace scaling instead. */ public Normalizer(boolean copy) { super(copy); } /** * Constructor. * @param norm The norm to use to normalize each non zero sample. */ public Normalizer(Norm norm) { this.norm = norm; } /** * Constructor. * @param norm The norm to use to normalize each non zero sample. * @param copy If false, try to avoid a copy and do inplace scaling instead. */ public Normalizer(Norm norm, boolean copy) { super(copy); this.norm = norm; } @Override public void learn(Attribute[] attributes, double[][] data) { logger.info("Normalizer is stateless and learn() does nothing."); } @Override public double[] transform(double[] x) { double scale; switch (norm) { case L1: scale = Math.norm1(x); break; case L2: scale = Math.norm2(x); break; case Inf: scale = Math.normInf(x); break; default: throw new IllegalStateException("Unknown type of norm: " + norm); } double[] y = copy ? new double[x.length] : x; if (Math.isZero(scale)) { if (y != x) { System.arraycopy(x, 0, y, 0, x.length); } } else { for (int i = 0; i < x.length; i++) { y[i] = x[i] / scale; } } return y; } @Override public String toString() { return "Normalizer()"; } }
27.175573
83
0.548596
c8781a414da344e2430f62c54e4f31fcace79ec2
2,367
package org.wiztools.restclient.idea; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.project.Project; import com.intellij.testFramework.LightVirtualFile; import org.wiztools.restclient.ui.ScriptEditor; import javax.swing.*; /** * response viewer */ public class ResponseViewerScriptEditor implements ScriptEditor { private JComponent editorComponent; private boolean initialized = false; private Editor editor; private Project project; public ResponseViewerScriptEditor(Project project) { this.project = project; } public void init() { LightVirtualFile groovyVirtualFile = new LightVirtualFile("response.html", ""); TextEditorProvider editorProvider = TextEditorProvider.getInstance(); FileEditor fileEditor = editorProvider.createEditor(project, groovyVirtualFile); if (fileEditor instanceof TextEditor) { editor = ((TextEditor) fileEditor).getEditor(); } this.editorComponent = fileEditor.getComponent(); } /** * view component for test script editor * * @return JComponent object */ public JComponent getEditorView() { if (!initialized) { init(); } return editorComponent; } /** * get test script code * * @return script */ public String getText() { return editor.getDocument().getText(); } /** * set text script code * * @param text script code */ public void setText(final String text) { final String text2 = text.replace("\r", ""); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { editor.getDocument().setText(text2); } }); } /** * set caret position * * @param offset offset */ public void setCaretPosition(int offset) { editor.getCaretModel().moveToOffset(offset); } /** * set editable mark * * @param editable editable mark */ public void setEditable(boolean editable) { } }
26.3
88
0.651035
ba9b0aa7e4bd4e09ad8a1024f0145676e375f507
4,459
/** * MIT License * * Copyright (c) 2017 Wolf Angelo * * 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 com.github.angelowolf.validacion; import java.util.ArrayList; import java.util.List; /** * * @author Angelo Wolf [email protected] */ public class ListaMensaje { private List<MensajeError> listaErrores; private List<MensajeValidacion> listaValidaciones; public ListaMensaje() { this.listaErrores = new ArrayList<>(); this.listaValidaciones = new ArrayList<>(); } public ListaMensaje(List<MensajeError> listaErrores, List<MensajeValidacion> listaValidaciones) { this.listaErrores = listaErrores; this.listaValidaciones = listaValidaciones; } public List<MensajeError> getListaErrores() { return listaErrores; } public void setListaErrores(List<MensajeError> listaErrores) { this.listaErrores = listaErrores; } public List<MensajeValidacion> getListaValidaciones() { return listaValidaciones; } public void setListaValidaciones(List<MensajeValidacion> listaValidaciones) { this.listaValidaciones = listaValidaciones; } /** * Agrega el objeto MensajeError a la lista de mensajes de errores. * * @param mensajeError */ public void agregarMensajeError(MensajeError mensajeError) { this.listaErrores.add(mensajeError); } /** * Crea un objeto MensajeError y lo agrega a la lista de mensajes de * errores. * * @param mensajeError */ public void agregarMensajeError(String mensajeError) { this.listaErrores.add(new MensajeError(mensajeError)); } /** * Agrega el objeto MensajeValidacion a la lista de mensajes de validacion. * * @param mensajeValidacion Objeto a agegar. */ public void agregarMensajeValidacion(MensajeValidacion mensajeValidacion) { this.listaValidaciones.add(mensajeValidacion); } /** * Crea un objeto MensajeValidacion y lo agrega a la lista de mensajes de * validacion. * * @param campo El nombre del campo. * @param mensajeError El mensaje de error a mostrar. */ public void agregarMensajeValidacion(String campo, String mensajeError) { this.listaValidaciones.add(new MensajeValidacion(campo, mensajeError)); } /** * Limpia todos los errores. */ public void limpiarMensajeError() { this.listaErrores.clear(); } /** * limpia todos los errores de validacion. */ public void limpiarMensajeValidacion() { this.listaValidaciones.clear(); } /** * Limpia todos los errores y errores de validacion. */ public void limpiarMensajes() { this.limpiarMensajeError(); this.limpiarMensajeValidacion(); } /** * Verifica si contiene errores de validacion o errores. * * @return True si NO tiene errores. false lo contrario. */ public boolean isEmpty() { return this.listaErrores.isEmpty() && this.listaValidaciones.isEmpty(); } /** * Agrega los mensajes de error y validacion a esta ListaMensaje * * @param listaMensaje */ public void agregarListaMensaje(ListaMensaje listaMensaje) { this.listaErrores.addAll(listaMensaje.getListaErrores()); this.listaValidaciones.addAll(listaMensaje.getListaValidaciones()); } }
30.965278
101
0.690738