text
stringlengths
10
2.72M
package com.tencent.adasdemo.activity; import android.app.Activity; import android.graphics.SurfaceTexture; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.TextureView; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import com.tencent.adasdemo.AdasWrap; import com.tencent.adasdemo.CameraWrapper; import com.tencent.adasdemo.Constants; import com.tencent.adasdemo.CoverView; import com.tencent.adasdemo.R; import java.util.Arrays; public class PreviewActivity extends Activity { private static final String TAG = PreviewActivity.class.getSimpleName(); private TextureView mCameraTexturePreview; private AdasWrap mADAS; private Handler mHandler = new Handler(); int screenWidth = Constants.ADAS_WIDTH; int screenHeight = Constants.ADAS_HEIGHT; float widthRatio = 1280.0f / screenWidth; float heightRatio = 720.0f / screenHeight; CoverView coverView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); setContentView(R.layout.activity_preview); TextureListener mTextureListener = new TextureListener(); mCameraTexturePreview = (TextureView) findViewById(R.id.preview); mCameraTexturePreview.setSurfaceTextureListener(mTextureListener); ViewGroup.LayoutParams params = mCameraTexturePreview.getLayoutParams(); DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics(); screenWidth = displayMetrics.widthPixels; screenHeight = displayMetrics.heightPixels; params.width = screenWidth; params.height = screenHeight; mCameraTexturePreview.setLayoutParams(params); if (Constants.CameraHeight == screenHeight) { heightRatio = Constants.CameraHeight / screenHeight; } else { heightRatio = Constants.CameraHeight * 1.0f / screenHeight; } if (Constants.CameraWidth == screenWidth) { widthRatio = Constants.CameraWidth / screenWidth; } else { widthRatio = Constants.CameraWidth * 1.0f / screenWidth; } RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(screenWidth, screenHeight); coverView = (CoverView) findViewById(R.id.coverView); coverView.setLayoutParams(layoutParams); coverView.setRatio(widthRatio, heightRatio); } @Override protected void onResume() { super.onResume(); if (mADAS == null) { mADAS = new AdasWrap(getApplicationContext()); mADAS.init(Constants.CameraWidth, Constants.CameraHeight); } } private class TextureListener implements TextureView.SurfaceTextureListener { private Thread mThread = null; @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureAvailable()"); mThread = new Thread() { @Override public void run() { CameraWrapper.getInstance().openCamera(new CamWrapperCallback()); } }; mThread.start(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { Log.i(TAG, "onSurfaceTextureSizeChanged()"); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { Log.i(TAG, "onSurfaceTextureDestroyed()"); return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } } private class CamWrapperCallback implements CameraWrapper.CamWrapperCallback { public void onCameraOpened(Exception err) { if (null == err) { SurfaceTexture surface = mCameraTexturePreview.getSurfaceTexture(); CameraWrapper.getInstance().initCamera(Constants.CameraWidth, Constants.CameraHeight, new CameraPreviewCallback()); CameraWrapper.getInstance().startPreview(surface, 1); schedulePreview(); } else { err.printStackTrace(); } } public void onCameraStop() { } } private void schedulePreview() { mHandler.post(new Runnable() { @Override public void run() { Log.d(TAG, Thread.currentThread().getName()); CameraWrapper.getInstance().addPreviewBuffer(); } }); } private class CameraPreviewCallback implements android.hardware.Camera.PreviewCallback { RelativeLayout.LayoutParams layoutParams; public CameraPreviewCallback() { layoutParams = new RelativeLayout.LayoutParams(screenWidth, screenHeight); layoutParams.leftMargin = 0; layoutParams.topMargin = 0; } @Override public void onPreviewFrame(byte[] data, android.hardware.Camera camera) { Log.d(TAG, "onPreviewFrame" + Thread.currentThread().getName()); final byte[] source = Arrays.copyOf(data, Constants.CameraWidth * Constants.CameraHeight); new Thread() { @Override public void run() { coverView.clear(); long time = System.currentTimeMillis(); if (mADAS != null) { mADAS.detect(source, coverView); } Log.d("ADAS", "costTime: " + (System.currentTimeMillis() - time)); mHandler.post(new Runnable() { @Override public void run() { coverView.invalidate(); CameraWrapper.getInstance().addPreviewBuffer(); } }); } }.start(); } } @Override protected void onPause() { super.onPause(); CameraWrapper.getInstance().stopCamera(); mHandler.removeCallbacks(null); if (mADAS != null) { mADAS.unInit(); mADAS = null; } } }
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CountSubstringOccurrences { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine().toLowerCase(); String substring = scanner.nextLine().toLowerCase(); Pattern substringPattern = Pattern.compile(substring); Matcher matcher = substringPattern.matcher(text); int occurrenceCount = 0; while(matcher.find()){ occurrenceCount++; } System.out.println(occurrenceCount); } }
/** * Provides an Interface for the Endpoint Service to be used by other bundles.<br /> * <br /> * Copyright 2012 IAAS University of Stuttgart <br /> * <br /> * * @author Matthias Fetzer - fetzerms@studi.informatik.uni-stuttgart.de */ package org.opentosca.core.endpoint.service;
package org.World; import java.util.ArrayList; import java.util.concurrent.ConcurrentLinkedQueue; public class World { private static ConcurrentLinkedQueue<Tile> tiles=new ConcurrentLinkedQueue<Tile>(); private static ConcurrentLinkedQueue<GameObject> gameObjects=new ConcurrentLinkedQueue<GameObject>(); //private static ArrayList<Tile> tiles=new ArrayList<Tile>(); //private static ArrayList<GameObject> gameObjects = new ArrayList<GameObject>(); public static void update(){ //Loop through game objects and update for(GameObject gameObject:gameObjects){ gameObject.update(); } } public static void render(){ //Render tiles for(Tile t:tiles){ t.render(); } //Loop through game objects and render for(GameObject gameObject:gameObjects){ gameObject.render(); } } public static void addObject(GameObject go){ gameObjects.offer(go); } public static void addTile(Tile t){tiles.offer(t);} }
package com.base.common.adapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(WebConfig.class); //@Autowired //LogInterceptor logInterceptor; @Autowired LoginInterceptor loginInterceptor; /** * 不需要登录拦截的url:登录注册和验证码 */ final String[] notLoginInterceptPaths = {"/shutdown","/signin","/login/**","/register/**","/crm_tempaltes/**","/css/**","/js/**","/kaptcha.jpg/**","/kaptcha/**"};//"/", "/login/**", "/person/**", "/register/**", "/validcode", "/captchaCheck", "/file/**", "/contract/htmltopdf", "/questions/**", "/payLog/**", "/error/**" }; @Override public void addInterceptors(InterceptorRegistry registry) { // 日志拦截器 //registry.addInterceptor(logInterceptor).addPathPatterns("/**"); // 登录拦截器 registry.addInterceptor(loginInterceptor).addPathPatterns("/**","","/").excludePathPatterns(notLoginInterceptPaths); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // @Bean // public InternalResourceViewResolver viewResolver() { // InternalResourceViewResolver resolver = new InternalResourceViewResolver(); // resolver.setPrefix("/templates/"); // resolver.setSuffix(".html"); // resolver.setViewClass(JstlView.class); // return resolver; // } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/", "/index"); // registry.addViewController("/").setViewName("/page/index"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); super.addResourceHandlers(registry); } }
/* * Copyright (c) 2012, ubivent GmbH, Thomas Butter, Oliver Seuffert * All right reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. * * This software is based on RFC6386 * * Copyright (c) 2010, 2011, Google Inc. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be * found in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package com.ubivent.vp8; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import static com.ubivent.vp8.PredictionMode.*; public class VP8Decoder { public final static int MAX_MB_SEGMENTS = 4; public final static int MB_FEATURE_TREE_PROBS = 3; public final static int FRAME_HEADER_SZ = 3; public final static int KEYFRAME_HEADER_SZ = 7; public final static int CURRENT_FRAME = 0; public final static int LAST_FRAME = 1; public final static int GOLDEN_FRAME = 2; public final static int ALTREF_FRAME = 3; public final static int NUM_REF_FRAMES = 4; int frameWidth = 0; int frameHeight = 0; int vertScale = 0; int horizScale = 0; boolean frameSizeUpdated = false; int partitions = 0; int partition_sz[]; boolean is_keyframe = false; SegmentHeader segmentHeader = new SegmentHeader(); LoopFilterHeader loopHeader = new LoopFilterHeader(); QuantHeader quantHeader = new QuantHeader(); ReferenceHeader referenceHeader = new ReferenceHeader(); EntropyHeader entropyHeader = new EntropyHeader(); EntropyHeader savedEntropy = new EntropyHeader(); boolean savedEntropy_valid = false; Frame frame_strg[] = new Frame[NUM_REF_FRAMES]; Frame ref_frames[] = new Frame[NUM_REF_FRAMES]; DequantFactors dequant_factors[] = new DequantFactors[MAX_MB_SEGMENTS]; int frame_cnt = 0; int mb_rows; int mb_cols; MB_Info mb_info_storage[]; public VP8Decoder() { dequant_global_init(); } private final boolean getBit(int n, int pos) { return (n & 1 << pos) != 0; } public void decodeFrame(byte buffer[]) throws IOException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream( buffer)); int tmp = dis.read(); // common header is_keyframe = getBit(tmp, 7); if (is_keyframe) System.out.println("keyframe"); else System.out.println("intraframe"); int version = (tmp >> 4) & 7; assert (version < 4); System.out.println("version " + version); boolean showframe = getBit(tmp, 3); System.out.println("showframe " + showframe); int datalen = ((tmp & 7) << 16) | (dis.read() << 8) | dis.read(); System.out.println("datalen " + datalen); BoolDecoder dec = null; if (is_keyframe) { // keyframe if (dis.read() != 0x9d || dis.read() != 0x01 || dis.read() != 0x2a) { System.out.println("wrong keyframe header"); return; } int nextTwo = dis.read() << 8 | dis.read(); frameSizeUpdated = false; tmp = nextTwo & 0x3fff; if (tmp != frameWidth) frameSizeUpdated = true; frameWidth = tmp; tmp = nextTwo >> 14; if (tmp != horizScale) frameSizeUpdated = true; horizScale = tmp; nextTwo = dis.read() << 8 | dis.read(); tmp = nextTwo & 0x3fff; if (tmp != frameHeight) frameSizeUpdated = true; frameHeight = tmp; tmp = nextTwo >> 14; if (tmp != vertScale) frameSizeUpdated = true; vertScale = tmp; mb_cols = (frameWidth + 15) / 16; mb_rows = (frameHeight + 15) / 16; System.out.printf("w: %d %d h: %d %d\n", frameWidth, horizScale, frameHeight, vertScale); } dec = new BoolDecoder(dis); int colorSpace = dec.readLiteral(1); if (colorSpace > 0) { System.out.println("UNKNOWN COLORSPACE"); return; } int clamp = dec.readLiteral(1); assert (clamp == 0); decode_segmentation_header(dec, is_keyframe); decode_loopfilter_header(dec, is_keyframe); decode_and_init_token_partitions(dec, buffer, datalen); decode_quantizer_header(dec); decode_reference_header(dec); /* * Set keyframe entropy defaults. These get updated on keyframes * regardless of the refresh_entropy setting. */ if (is_keyframe) { EntropyHeader.copyArray4(entropyHeader.coeff_probs, ProbData.k_default_coeff_probs); EntropyHeader.copyArray2(entropyHeader.mv_probs, ProbData.k_default_mv_probs); EntropyHeader.copyArray1(entropyHeader.y_mode_probs, ProbData.k_default_y_mode_probs); EntropyHeader.copyArray1(entropyHeader.uv_mode_probs, ProbData.k_default_uv_mode_probs); } if (!referenceHeader.refresh_entropy) { savedEntropy = (EntropyHeader) entropyHeader.clone(); savedEntropy_valid = true; } decode_entropy_header(dec); vp8_dixie_modemv_init(); vp8_dixie_tokens_init(); vp8_dixie_predict_init(); dequant_init(); int row = 0; int partition = 0; for (row = 0, partition = 0; row < mb_rows; row++) { vp8_dixie_modemv_process_row(dec, row, 0, mb_cols); vp8_dixie_tokens_process_row(partition, row, 0, mb_cols); vp8_dixie_predict_process_row(row, 0, mb_cols); if (loopHeader.level != 0 && row != 0) vp8_dixie_loopfilter_process_row(row - 1, 0, mb_cols); if (++partition == partitions) partition = 0; } if (loopHeader.level != 0) vp8_dixie_loopfilter_process_row(row - 1, 0, mb_cols); frame_cnt++; if (referenceHeader.refresh_entropy) { entropyHeader = (EntropyHeader) savedEntropy.clone(); savedEntropy_valid = false; } /* Handle reference frame updates */ if (referenceHeader.copy_arf == 1) { ref_frames[ALTREF_FRAME] = ref_frames[LAST_FRAME]; } else if (referenceHeader.copy_arf == 2) { ref_frames[ALTREF_FRAME] = ref_frames[GOLDEN_FRAME]; } if (referenceHeader.copy_gf == 1) { ref_frames[GOLDEN_FRAME] = ref_frames[LAST_FRAME]; } else if (referenceHeader.copy_gf == 2) { ref_frames[GOLDEN_FRAME] = ref_frames[ALTREF_FRAME]; } if (referenceHeader.refresh_gf) { ref_frames[GOLDEN_FRAME] = ref_frames[CURRENT_FRAME]; } if (referenceHeader.refresh_arf) { ref_frames[ALTREF_FRAME] = ref_frames[CURRENT_FRAME]; } if (referenceHeader.refresh_last) { ref_frames[LAST_FRAME] = ref_frames[CURRENT_FRAME]; } } void vp8_dixie_loopfilter_process_row( int row, int start_col, int num_cols) { if (loopHeader.use_simple) filter_row_simple(row, start_col, num_cols); else filter_row_normal(row, start_col, num_cols); } void vp8_dixie_tokens_process_row( int partition, int row, int start_col, int num_cols) { token_decoder tokens = this.tokens[partition]; short coeffs = tokens.coeffs + 25 * 16 * start_col; int col; token_entropy_ctx_t *above = ctx->above_token_entropy_ctx + start_col; token_entropy_ctx_t *left = &tokens->left_token_entropy_ctx; int mbi = (row+1)*mbi_w + start_col; if (row == 0) reset_above_context(above, num_cols); if (start_col == 0) reset_row_context(left); for (col = start_col; col < start_col + num_cols; col++) { memset(coeffs, 0, 25 * 16 * sizeof(short)); if (mbi->base.skip_coeff) { reset_mb_context(left, above, mbi->base.y_mode); mbi->base.eob_mask = 0; } else { struct dequant_factors *dqf; dqf = ctx->dequant_factors + mbi->base.segment_id; mbi->base.eob_mask = decode_mb_tokens(&tokens->bool, *left, *above, coeffs, mbi->base.y_mode, ctx->entropy_hdr.coeff_probs, dqf->factor); } above++; mbi++; coeffs += 25 * 16; } } int mbi_w, mbi_h; private void vp8_dixie_modemv_init() { mbi_w = mb_cols + 1; /* For left border col */ mbi_h = mb_rows + 1; /* For above border row */ if (frameSizeUpdated) { mb_info_storage = null; } if (mb_info_storage == null) mb_info_storage = new MB_Info[mbi_w * mbi_h]; for(int i = 0; i < mbi_w * mbi_h; i++) { mb_info_storage[i] = new MB_Info(); } } byte read_segment_id(BoolDecoder bool) throws IOException { return (byte) (bool.readBool(segmentHeader.tree_probs[0]) ? 2 + (bool.readBool(segmentHeader.tree_probs[2])?1:0) : (bool.readBool(segmentHeader.tree_probs[1])?1:0)); } void vp8_dixie_modemv_process_row(BoolDecoder bool, int row, int start_col, int num_cols) throws IOException { int above; int current; int col; mv_clamp_rect bounds = new mv_clamp_rect(); current = mbi_w*(row+1) + start_col; above = mbi_w*row + start_col; /* Calculate the eighth-pel MV bounds using a 1 MB border. */ bounds.to_left = -((start_col + 1) << 7); bounds.to_right = (mb_cols - start_col) << 7; bounds.to_top = -((row + 1) << 7); bounds.to_bottom = (mb_rows - row) << 7; for (col = start_col; col < start_col + num_cols; col++) { if (segmentHeader.update_map) mb_info_storage[current].segment_id = read_segment_id(bool); if (entropyHeader.coeff_skip_enabled) mb_info_storage[current].skip_coeff = bool.readBool(entropyHeader.coeff_skip_prob); if (is_keyframe) { if (!segmentHeader.update_map) mb_info_storage[current].segment_id = 0; decode_kf_mb_mode(current, current - 1, above, bool); } /* TODO do keyframes first else { if (bool_get(bool, ctx->entropy_hdr.prob_inter)) decode_mvs(ctx, this, this - 1, above, &bounds, bool); else decode_intra_mb_mode(this, &ctx->entropy_hdr, bool); bounds.to_left -= 16 << 3; bounds.to_right -= 16 << 3; } */ /* Advance to next mb */ current++; above++; } } byte left_block_mode(int current, int left, int b) { if ((b & 3) > 0) { switch (mb_info_storage[left].y_mode) { case DC_PRED: return B_DC_PRED; case V_PRED: return B_VE_PRED; case H_PRED: return B_HE_PRED; case TM_PRED: return B_TM_PRED; case B_PRED: return mb_info_storage[left].modes[b+3]; default: assert(false); } } return mb_info_storage[current].modes[b-1]; } byte above_block_mode(int current, int above, int b) { if (b < 4) { switch (mb_info_storage[above].y_mode) { case DC_PRED: return B_DC_PRED; case V_PRED: return B_VE_PRED; case H_PRED: return B_HE_PRED; case TM_PRED: return B_TM_PRED; case B_PRED: return mb_info_storage[above].modes[b+12]; default: assert(false); // OOPS } } return mb_info_storage[current].modes[b-4]; } void decode_kf_mb_mode(int current, int left, int above, BoolDecoder bool) throws IOException { int y_mode, uv_mode; y_mode = bool.bool_read_tree(ModevData.kf_y_mode_tree, ModevData.kf_y_mode_probs); if (y_mode == PredictionMode.B_PRED) { int i; for (i = 0; i < 16; i++) { byte a = above_block_mode(current, above, i); byte l = left_block_mode(current, left, i); byte b; b = (byte) bool.bool_read_tree(ModevData.b_mode_tree, ModevData.kf_b_mode_probs[a][l]); mb_info_storage[current].modes[i] = b; } } uv_mode = bool.bool_read_tree(ModevData.uv_mode_tree, ModevData.kf_uv_mode_probs); mb_info_storage[current].y_mode = (byte) y_mode; mb_info_storage[current].uv_mode = (byte) uv_mode; mb_info_storage[current].mv.x = mb_info_storage[current].mv.y = 0; mb_info_storage[current].ref_frame = 0; } class token_decoder { BoolDecoder bool; int left_token_entropy_ctx[] = new int[4 + 2 + 2 + 1]; short coeffs[]; } void vp8_dixie_predict_init() { int i; if (frameSizeUpdated) { for (i = 0; i < NUM_REF_FRAMES; i++) { int w = mb_cols * 16 + BORDER_PIXELS * 2; int h = mb_rows * 16 + BORDER_PIXELS * 2; frame_strg[i] = new Frame(w, h); frame_strg[i].vpx_img_set_rect(BORDER_PIXELS, BORDER_PIXELS, frameWidth, frameHeight); } /* * TODO if (ctx->frame_hdr.version) ctx->subpixel_filters = * bilinear_filters; else ctx->subpixel_filters = sixtap_filters; */ } /* Find a free framebuffer to predict into */ ref_frames[CURRENT_FRAME] = null; ref_frames[CURRENT_FRAME] = vp8_dixie_find_free_ref_frame(); } Frame vp8_dixie_find_free_ref_frame() { for (Frame f : frame_strg) { boolean found = false; for (Frame f2 : ref_frames) { if (f2 == f) found = true; } if (!found) return f; } System.out.println("NO FREE FRAME"); return null; } private static int clamp_q(int q) { if (q < 0) return 0; else if (q > 127) return 127; return q; } private static int dc_q(int q) { return DequantData.dc_q_lookup[clamp_q(q)]; } private static int ac_q(int q) { return DequantData.ac_q_lookup[clamp_q(q)]; } private void dequant_init() { int i, q; int factorsOffset = 0; DequantFactors dqf = dequant_factors[factorsOffset++]; for (i = 0; i < (segmentHeader.enabled ? MAX_MB_SEGMENTS : 1); i++) { q = quantHeader.q_index; if (segmentHeader.enabled) q = (!segmentHeader.abs) ? q + segmentHeader.quant_idx[i] : segmentHeader.quant_idx[i]; if (dqf.quant_idx != q || quantHeader.delta_update != 0) { dqf.factor[DequantFactors.TOKEN_BLOCK_Y1][0] = (short) dc_q(q + quantHeader.y1_dc_delta_q); dqf.factor[DequantFactors.TOKEN_BLOCK_Y1][1] = (short) ac_q(q); dqf.factor[DequantFactors.TOKEN_BLOCK_UV][0] = (short) dc_q(q + quantHeader.uv_dc_delta_q); dqf.factor[DequantFactors.TOKEN_BLOCK_UV][1] = (short) ac_q(q + quantHeader.uv_ac_delta_q); dqf.factor[DequantFactors.TOKEN_BLOCK_Y2][0] = (short) (dc_q(q + quantHeader.y2_dc_delta_q) * 2); dqf.factor[DequantFactors.TOKEN_BLOCK_Y2][1] = (short) (ac_q(q + quantHeader.y2_ac_delta_q) * 155 / 100); if (dqf.factor[DequantFactors.TOKEN_BLOCK_Y2][1] < 8) dqf.factor[DequantFactors.TOKEN_BLOCK_Y2][1] = 8; if (dqf.factor[DequantFactors.TOKEN_BLOCK_UV][0] > 132) dqf.factor[DequantFactors.TOKEN_BLOCK_UV][0] = 132; dqf.quant_idx = q; } dqf = dequant_factors[factorsOffset++]; } } public static final int MAX_PARTITIONS = 8; public static final int BORDER_PIXELS = 16; int above_token_entropy_ctx[] = new int[4 + 2 + 2 + 1]; token_decoder tokens[] = new token_decoder[MAX_PARTITIONS]; private void vp8_dixie_tokens_init() { int partitions = this.partitions; if (frameSizeUpdated) { int i; int coeff_row_sz = mb_cols * 25 * 16; for (i = 0; i < partitions; i++) { tokens[i].coeffs = new short[coeff_row_sz]; } } } private void decode_entropy_header(BoolDecoder bool) throws IOException { int i, j, k, l; /* Read coefficient probability updates */ for (i = 0; i < ProbData.BLOCK_TYPES; i++) for (j = 0; j < ProbData.COEFF_BANDS; j++) for (k = 0; k < ProbData.PREV_COEFF_CONTEXTS; k++) for (l = 0; l < ProbData.ENTROPY_NODES; l++) if (bool.readBool(ProbData.k_coeff_entropy_update_probs[i][j][k][l])) entropyHeader.coeff_probs[i][j][k][l] = (short) bool .readLiteral(8); /* Read coefficient skip mode probability */ entropyHeader.coeff_skip_enabled = bool.readBool(); if (entropyHeader.coeff_skip_enabled) entropyHeader.coeff_skip_prob = (short) bool.readLiteral(8); /* Parse interframe probability updates */ if (!is_keyframe) { entropyHeader.prob_inter = (short) bool.readLiteral(8); entropyHeader.prob_last = (short) bool.readLiteral(8); entropyHeader.prob_gf = (short) bool.readLiteral(8); if (bool.readBool()) for (i = 0; i < 4; i++) entropyHeader.y_mode_probs[i] = (short) bool.readLiteral(8); if (bool.readBool()) for (i = 0; i < 3; i++) entropyHeader.uv_mode_probs[i] = (short) bool .readLiteral(8); for (i = 0; i < 2; i++) for (j = 0; j < ProbData.MV_PROB_CNT; j++) if (bool.readBool(ProbData.k_mv_entropy_update_probs[i][j])) { int x = (short) bool.readLiteral(7); entropyHeader.mv_probs[i][j] = (short) ((x != 0) ? (x << 1) : 1); } } } private void decode_reference_header(BoolDecoder bool) throws IOException { referenceHeader.refresh_gf = is_keyframe ? true : bool.readBool(); referenceHeader.refresh_arf = is_keyframe ? true : bool.readBool(); referenceHeader.copy_gf = is_keyframe ? 0 : !referenceHeader.refresh_gf ? bool.readLiteral(2) : 0; referenceHeader.copy_arf = is_keyframe ? 0 : !referenceHeader.refresh_arf ? bool.readLiteral(2) : 0; referenceHeader.sign_bias[GOLDEN_FRAME] = is_keyframe ? false : bool .readBool(); referenceHeader.sign_bias[ALTREF_FRAME] = is_keyframe ? false : bool .readBool(); referenceHeader.refresh_entropy = bool.readBool(); referenceHeader.refresh_last = is_keyframe ? true : bool.readBool(); } void decode_quantizer_header(BoolDecoder bool) throws IOException { int update; int last_q = quantHeader.q_index; quantHeader.q_index = bool.readLiteral(7); update = (last_q != quantHeader.q_index) ? 1 : 0; update |= (quantHeader.y1_dc_delta_q = bool.bool_maybe_get_int(4)); update |= (quantHeader.y2_dc_delta_q = bool.bool_maybe_get_int(4)); update |= (quantHeader.y2_ac_delta_q = bool.bool_maybe_get_int(4)); update |= (quantHeader.uv_dc_delta_q = bool.bool_maybe_get_int(4)); update |= (quantHeader.uv_ac_delta_q = bool.bool_maybe_get_int(4)); quantHeader.delta_update = update; } private void decode_segmentation_header(BoolDecoder bool, boolean isKeyframe) throws IOException { if (isKeyframe) segmentHeader = new SegmentHeader(); segmentHeader.enabled = bool.readBool(); if (segmentHeader.enabled) { int i; segmentHeader.update_map = bool.readBool(); segmentHeader.update_data = bool.readBool(); if (segmentHeader.update_data) { segmentHeader.abs = bool.readBool(); for (i = 0; i < MAX_MB_SEGMENTS; i++) segmentHeader.quant_idx[i] = bool.bool_maybe_get_int(7); for (i = 0; i < MAX_MB_SEGMENTS; i++) segmentHeader.lf_level[i] = bool.bool_maybe_get_int(6); } if (segmentHeader.update_map) { for (i = 0; i < MB_FEATURE_TREE_PROBS; i++) segmentHeader.tree_probs[i] = bool.readBool() ? bool .readLiteral(8) : 255; } } else { segmentHeader.update_map = false; segmentHeader.update_data = false; } } private void decode_loopfilter_header(BoolDecoder bool, boolean isKeyframe) throws IOException { if (isKeyframe) loopHeader = new LoopFilterHeader(); loopHeader.use_simple = bool.readBool(); loopHeader.level = bool.readLiteral(6); loopHeader.sharpness = bool.readLiteral(3); loopHeader.delta_enabled = bool.readBool(); if (loopHeader.delta_enabled && bool.readBool()) { int i; for (i = 0; i < LoopFilterHeader.BLOCK_CONTEXTS; i++) loopHeader.ref_delta[i] = bool.bool_maybe_get_int(6); for (i = 0; i < LoopFilterHeader.BLOCK_CONTEXTS; i++) loopHeader.mode_delta[i] = bool.bool_maybe_get_int(6); } } private void decode_and_init_token_partitions(BoolDecoder bool, byte buffer[], int datalen) throws IOException { int i; partitions = 1 << bool.readLiteral(2); int sz = buffer.length; int dataoffset = FRAME_HEADER_SZ + (is_keyframe ? KEYFRAME_HEADER_SZ : 0) + datalen; sz -= buffer.length - dataoffset; sz -= 3 * (partitions - 1); partition_sz = new int[partitions]; for (i = 0; i < partitions; i++) { if (i < partitions - 1) { partition_sz[i] = (buffer[2 + dataoffset] << 16) | (buffer[1 + dataoffset] << 8) | buffer[dataoffset]; dataoffset += 3; } else partition_sz[i] = sz; if (sz < partition_sz[i]) throw new IOException("ERROR part size"); sz -= partition_sz[i]; } for (i = 0; i < partitions; i++) { tokens[i].bool = new BoolDecoder(new DataInputStream( new ByteArrayInputStream(buffer, dataoffset, partition_sz[i]))); dataoffset += partition_sz[i]; } } void dequant_global_init() { int i; for (i = 0; i < MAX_MB_SEGMENTS; i++) { dequant_factors[i] = new DequantFactors(); dequant_factors[i].quant_idx = -1; } } public void getFrame(ByteBuffer buffer) { return; } }
package pl.sidor.model; import java.io.Serializable; public class User implements Serializable { private int id; private String name; private String lastName; private String email; private Adres adres; public User() { } public User(int id, String name, String lastName, String email, Adres adres) { this.id = id; this.name = name; this.lastName = lastName; this.email = email; this.adres = adres; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Adres getAdres() { return adres; } public void setAdres(Adres adres) { this.adres = adres; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", adres=" + adres + '}'; } }
package es.ubu.lsi.server; import es.ubu.lsi.common.GameElement; /** * Define la signatura de los métodos de arranque, multidifusión y eliminación de clientes. * * @author Antonio de los Mozos Alonso * @author Miguel Angel Leon Bardavio * */ public interface GameServer { /** * Inicia un bucle de espera que acepta peticiones de los clientes. */ public void startup(); /** * Cierra el flujo de entrada/salida del servidor y el correspondiente socket. */ public void shutdown(); /** * Envia el resultado del juego de una sala, a los dos clientes de esa sala. * * @param element Element in the game system. */ public void broadcastRoom(GameElement element); /** * Elimina un cliente especificado por su id, de la lista de clientes. * * @param id Id of the client who will be removed. */ public void remove(int id); }
import javax.swing.*; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class EditMenu extends JMenu{ String text; EditMenu(JTextArea jTextArea, Repo repo){ super("编辑"); JMenuItem addKey = new JMenuItem("添加关键字"); addKey.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //fixme String keybord = JOptionPane.showInputDialog("请输入添加的关键字"); } }); this.add(addKey); JMenuItem deleteKey = new JMenuItem("删除关键字"); deleteKey.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //fixme String keybord = JOptionPane.showInputDialog("请输入删除的关键字"); } }); this.add(deleteKey); JMenuItem versionBack = new JMenuItem("版本回退"); versionBack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //fixme } }); this.add(versionBack); } public static void main(String args[]){ String repoName = JOptionPane.showInputDialog("请输入库名称"); String repoDir = JOptionPane.showInputDialog("请输入库地址"); Repo repo = new Repo(repoName,repoDir); JFrame jFrame = new JFrame("编辑测试"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setSize(300,200); jFrame.setLayout(new BorderLayout()); JTextArea jTextArea = new JTextArea(); jTextArea.setSize(100,200); jFrame.add(jTextArea); EditMenu editMenu = new EditMenu(jTextArea,repo); JMenuBar menuBar = new JMenuBar(); menuBar.add(editMenu); jFrame.add(menuBar,BorderLayout.NORTH); jFrame.setVisible(true); } }
package com.lti.collections; import java.util.*; public class LinkedHashSetExample { public static void main(String[] args) { LinkedHashSet<String> LHSet = new LinkedHashSet<String>(); LHSet.add("C"); LHSet.add("D"); LHSet.add("A"); LHSet.add("B"); LHSet.add("234"); LHSet.add("123"); LHSet.add("111"); System.out.println("The LinkedHashSet elements are: "+LHSet); boolean b1= LHSet.remove("B"); System.out.println(LHSet); boolean b2= LHSet.contains("B"); System.out.println("Is B exists? " +b2); System.out.println("The Elements are "+LHSet); } }
package com.rc.panels; import com.rc.frames.MainFrame; import javax.swing.*; import java.awt.*; /** * @author song * @date 19-9-24 14:42 * @description * @since */ public class LeftPanel extends JPanel { private NavPanel navPanel; private ChatRoomsPanel chatRoomsPanel; public LeftPanel() { initComponents(); initView(); } private void initComponents() { navPanel = new NavPanel(this); chatRoomsPanel = new ChatRoomsPanel(); } private void initView() { this.setPreferredSize(new Dimension(310, MainFrame.DEFAULT_HEIGHT)); this.setLayout(new BorderLayout()); add(navPanel, BorderLayout.WEST); add(chatRoomsPanel, BorderLayout.CENTER); } }
package vanadis.jmx; import vanadis.core.collections.Generic; import javax.management.MBeanAttributeInfo; import java.util.List; import java.util.Map; class MapAttributes { private static final String STRING_TYPE = String.class.getName(); static MBeanAttributeInfo[] attributes(Map<String,Object> map, boolean writable, boolean toString) { List<MBeanAttributeInfo> infos = Generic.list(); for (Map.Entry<String, Object> entry : map.entrySet()) { Class<?> type = entry.getValue().getClass(); String name = entry.getKey(); String typeName = toString ? STRING_TYPE : type.getName(); boolean bool = !toString && type == Boolean.class; String desc = "Key:" + name; infos.add(new MBeanAttributeInfo(name, typeName, desc, true, writable, bool)); } return infos.toArray(new MBeanAttributeInfo[infos.size()]); } }
package com.microsilver.mrcard.basicservice.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class PrctureDto { @ApiModelProperty(value = "图片url") private String pictureUrl; }
package org.holoeverywhere.preference; import org.holoeverywhere.HoloEverywhere; import org.holoeverywhere.HoloEverywhere.PreferenceImpl; import android.content.Context; import android.util.Log; public class PreferenceManagerHelper { static interface PreferenceManagerImpl { SharedPreferences getDefaultSharedPreferences(Context context, PreferenceImpl impl); int obtainThemeTag(); SharedPreferences wrap(Context context, PreferenceImpl impl, String name, int mode); } private static PreferenceManagerImpl IMPL; static { try { Class<?> clazz = Class .forName(HoloEverywhere.PACKAGE + ".preference._PreferenceManagerImpl"); IMPL = (PreferenceManagerImpl) clazz.newInstance(); } catch (Exception e) { IMPL = null; if (HoloEverywhere.DEBUG) { Log.w("HoloEverywhere", "Cannot find PreferenceManager class. Preference framework are disabled.", e); } } } private static void checkImpl() { if (IMPL == null) { throw new UnsatisfiedLinkError("HoloEverywhere: PreferenceFramework not found"); } } public static SharedPreferences getDefaultSharedPreferences(Context context) { return getDefaultSharedPreferences(context, HoloEverywhere.PREFERENCE_IMPL); } public static SharedPreferences getDefaultSharedPreferences(Context context, PreferenceImpl impl) { checkImpl(); return IMPL.getDefaultSharedPreferences(context, impl); } public static int obtainThemeTag() { checkImpl(); return IMPL.obtainThemeTag(); } public static SharedPreferences wrap(Context context, PreferenceImpl impl, String name, int mode) { checkImpl(); return IMPL.wrap(context, impl, name, mode); } public static SharedPreferences wrap(Context context, String name, int mode) { return wrap(context, HoloEverywhere.PREFERENCE_IMPL, name, mode); } private PreferenceManagerHelper() { } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.navigations.service; import de.hybris.platform.catalog.model.CatalogVersionModel; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; import de.hybris.platform.cms2.model.navigation.CMSNavigationEntryModel; import de.hybris.platform.cmsfacades.data.NavigationEntryData; /** * Navigation Entry service interface which deals with methods related to navigation node entries operations. */ public interface NavigationEntryService { /** * Creates a navigation node entry * * @param navigationEntryData * the navigation node entry data with the Item ID and Item Type to be assigned to the navigation node. * @param catalogVersion * the catalog version model in which the node entry will be created. * @return the new Navigation Node Entry assignment. */ CMSNavigationEntryModel createNavigationEntry(final NavigationEntryData navigationEntryData, final CatalogVersionModel catalogVersion); /** * Deletes all navigation entries associated with the given navigation node uid. * * @param navigationNodeUid * the node where the entries will be removed from. * @throws CMSItemNotFoundException * when the navigation node does not exist. */ void deleteNavigationEntries(final String navigationNodeUid) throws CMSItemNotFoundException; }
import java.awt.font.NumericShaper; import java.util.Scanner; public class AngleUnitConverter { //Write a method to convert from degrees to radians. Write a method to convert from radians //to degrees. You are given a number n and n queries for conversion. Each conversion query //will consist of a number + space + measure. Measures are "deg" and "rad". //Convert all radians to degrees and all degrees to radians. Print the results as n lines, //each holding a number + space + measure. public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.println("Enter number 'n' to determine the number of entries: "); int n = Integer.parseInt(reader.nextLine()); double[] numbers = new double[n]; String[] measure = new String[n]; //Read the double and store it in the double array //read the next text on the line and store in the String array for (int i = 0; i < n; i++) { if (reader.hasNextDouble()) { numbers[i] = reader.nextDouble(); } if (reader.hasNext()) { measure[i] = reader.next(); } } //Go through both arrays 'n' times check for the string value and invoke one of the methods for (int i = 0; i < n; i++) { if (measure[i].equals("rad")) { radiansToDegrees(numbers[i]); } else if(measure[i].equals("deg")) { degreesToRadians(numbers[i]); } } } //A method to convert degrees to radians public static void degreesToRadians(double degrees){ double radians = (degrees * (double)Math.PI) / 180.0d; System.out.printf("%.6f rad\n",radians); } //A method to convert radians to degrees public static void radiansToDegrees(double radians){ double degrees = radians * (180.0d /(double)Math.PI); System.out.printf("%.6f deg\n ",degrees); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.validator; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.DEFAULT_PAGE_ALREADY_EXIST; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.DEFAULT_PAGE_DOES_NOT_EXIST; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.FIELD_ALREADY_EXIST; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.cms2.model.pages.AbstractPageModel; import de.hybris.platform.cmsfacades.cmsitems.predicates.CloneContextSameAsActiveCatalogVersionPredicate; import de.hybris.platform.cmsfacades.common.validator.ValidationErrors; import de.hybris.platform.cmsfacades.common.validator.ValidationErrorsProvider; import de.hybris.platform.cmsfacades.common.validator.impl.DefaultValidationErrors; import de.hybris.platform.cmsfacades.pages.service.PageVariationResolver; import de.hybris.platform.cmsfacades.pages.service.PageVariationResolverType; import de.hybris.platform.cmsfacades.pages.service.PageVariationResolverTypeRegistry; import de.hybris.platform.cmsfacades.validator.data.ValidationError; import de.hybris.platform.servicelayer.model.ItemModelContext; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class DefaultCreateAbstractPageValidatorTest { private static final String TEST_UID = "test-uid"; private static final String INVALID = "invalid"; @InjectMocks private DefaultCreateAbstractPageValidator validator; @Mock private Predicate<String> pageExistsPredicate; @Mock private PageVariationResolverTypeRegistry pageVariationResolverTypeRegistry; @Mock private PageVariationResolverType pageVariationResolverType; @Mock private PageVariationResolver<AbstractPageModel> pageVariationResolver; @Mock private ItemModelContext itemModelContext; @Mock private ValidationErrorsProvider validationErrorsProvider; @Mock private Predicate<AbstractPageModel> pageCanOnlyHaveOnePrimaryPredicate; @Mock private CloneContextSameAsActiveCatalogVersionPredicate cloneContextSameAsActiveCatalogVersionPredicate; private final List<AbstractPageModel> defaultPages = new ArrayList<>(); private final ValidationErrors validationErrors = new DefaultValidationErrors(); final AbstractPageModel pageModel = new AbstractPageModel(); @Before public void setup() { when(validationErrorsProvider.getCurrentValidationErrors()).thenReturn(validationErrors); when(pageExistsPredicate.test(TEST_UID)).thenReturn(false); when(pageExistsPredicate.test(INVALID)).thenReturn(true); when(pageVariationResolverTypeRegistry.getPageVariationResolverType(AbstractPageModel._TYPECODE)).thenReturn(Optional.of(pageVariationResolverType)); when(pageVariationResolverType.getResolver()).thenReturn(pageVariationResolver); when(pageVariationResolver.findPagesByType(AbstractPageModel._TYPECODE, true)).thenReturn(defaultPages); when(itemModelContext.getItemType()).thenReturn(AbstractPageModel._TYPECODE); when(cloneContextSameAsActiveCatalogVersionPredicate.test(pageModel)).thenReturn(true); } @Test public void testValidatePageExists() { pageModel.setUid(INVALID); pageModel.setDefaultPage(true); validator.validate(pageModel); final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors(); assertEquals(1, errors.size()); assertThat(errors.get(0).getField(), is(AbstractPageModel.UID)); assertThat(errors.get(0).getErrorCode(), is(FIELD_ALREADY_EXIST)); } @Test public void testValidateDefaultPageDoesNotExist_ForPagesThatCanHaveOnlyOnePrimary() { pageModel.setUid(TEST_UID); pageModel.setDefaultPage(false); when(pageCanOnlyHaveOnePrimaryPredicate.test(pageModel)).thenReturn(true); validator.validate(pageModel); final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors(); assertEquals(1, errors.size()); assertThat(errors.get(0).getField(), is(AbstractPageModel.TYPECODE)); assertThat(errors.get(0).getErrorCode(), is(DEFAULT_PAGE_DOES_NOT_EXIST)); } @Test public void testValidateDefaultPageAlreadyExists_ForPagesThatCanHaveOnlyOnePrimary() { pageModel.setUid(TEST_UID); pageModel.setDefaultPage(true); when(pageCanOnlyHaveOnePrimaryPredicate.test(pageModel)).thenReturn(true); defaultPages.add(new AbstractPageModel()); validator.validate(pageModel); final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors(); assertEquals(1, errors.size()); assertThat(errors.get(0).getField(), is(AbstractPageModel.TYPECODE)); assertThat(errors.get(0).getErrorCode(), is(DEFAULT_PAGE_ALREADY_EXIST)); } @Test public void testNoValidateDefaultPageAlreadyExists_IfPageIsCreatedInDifferentCatalogVersion() { pageModel.setUid(TEST_UID); pageModel.setDefaultPage(true); when(cloneContextSameAsActiveCatalogVersionPredicate.test(pageModel)).thenReturn(false); when(pageCanOnlyHaveOnePrimaryPredicate.test(pageModel)).thenReturn(true); defaultPages.add(new AbstractPageModel()); validator.validate(pageModel); final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors(); assertEquals(0, errors.size()); } @Test public void testDoesNotValidateOnDefaultPage_ForPagesThatCanHaveMultiplePrimaryPages() { pageModel.setUid(TEST_UID); pageModel.setDefaultPage(false); when(pageCanOnlyHaveOnePrimaryPredicate.test(pageModel)).thenReturn(false); validator.validate(pageModel); final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors(); assertEquals(0, errors.size()); } }
import java.io.*; import java.util.*; /** * Adjacency list implementation for the AssociationGraph interface. * * Your task is to complete the implementation of this class. You may add * methods, but ensure your modified class compiles and runs. * * @author Jeffrey Chan, 2019. */ public class AdjList extends AbstractAssocGraph { /** * Contructs empty graph. */ MyList[] nodeLists = null; GraphArray<MyList> nodesArray = null; private static final String SOURCE = "S"; private static final String TARGET = "T"; private static final String ROOT = "R"; int size = 0; public AdjList() { nodeLists = new MyList[size]; nodesArray = new GraphArray<>(); } // end of AdjList() public void addVertex(String vertLabel) { size++; MyList nodeList = new MyList(); Node node = new Node(vertLabel, ROOT, -1); nodeList.add(new ListNode(node)); nodesArray.addElement(nodeList); } // end of addVertex() public void addEdge(String srcLabel, String tarLabel, int weight) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); Node src = getMainSoure(list); if (src.data.equals(srcLabel)) { Node node = new Node(tarLabel, TARGET, weight); list.add(new ListNode(node)); } else { boolean flag = false; ListNode point = (ListNode) list.head.data; while (point != null) { Node temp = (Node)point.data; if (temp.data.equals(tarLabel)) { flag = true; break; } point = point.next; } if (flag) { Node node = new Node(srcLabel, SOURCE, weight); list.add(new ListNode(node)); } } } } // end of addEdge() public int getEdgeWeight(String srcLabel, String tarLabel) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { boolean flag = false; MyList list = (MyList) nodesArray.getElement(i); Node node = getMainSoure(list); ListNode point = (ListNode)list.head; if (node.data.equals(srcLabel)) { while (point != null) { Node temp = (Node)((ListNode)(point.data)).data; if (tarLabel.equals(temp.data)) { flag = true; break; } point = point.next; } } if (flag) { return ((Node)((ListNode)(point.data)).data).weight; } } return EDGE_NOT_EXIST; } // end of existEdge() public void updateWeightEdge(String srcLabel, String tarLabel, int weight) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); Node src = getMainSoure(list); if (weight != 0) { if (src.data.equals(srcLabel)) { ListNode point = (ListNode) list.head; while (point != null) { Node node = (Node)((ListNode)point.data).data; if (node.data.equals(tarLabel)) { node.weight = weight; } point = point.next; } } if (src.data.equals(tarLabel)) { ListNode point = (ListNode) list.head; while (point != null) { Node node = (Node)((ListNode)point.data).data; if (node.data.equals(srcLabel) && node.type.equals(SOURCE)) { node.weight = weight; } point = point.next; } } } else { if (src.data.equals(srcLabel)) { ListNode point = (ListNode) list.head; while (point != null) { Node node = (Node)((ListNode)point.data).data; if (node.data.equals(tarLabel)) { break; } point = point.next; } list.deleteNode(point); } if (src.data.equals(tarLabel)) { ListNode point = (ListNode) list.head; while (point != null) { Node node = (Node)((ListNode)point.data).data; if (node.data.equals(srcLabel) && node.type.equals(SOURCE)) { break; } point = point.next; } list.deleteNode(point); } } } } // end of updateWeightEdge() public void removeVertex(String vertLabel) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); Node src = getMainSoure(list); if (src.data.equals(vertLabel)) { int index = nodesArray.indexOf(list); nodesArray.removeAt(index); } } for(int i=0;i<size-1;i++) { MyList list = (MyList) nodesArray.getElement(i); ListNode point = (ListNode) list.head; while (point != null) { Node node = (Node)((ListNode)point.data).data; if (node.data.equals(vertLabel)) { break; } point = point.next; } if(point!=null) { list.deleteNode(point); } } } // end of removeVertex() public List<MyPair> inNearestNeighbours(int k, String vertLabel) { List<MyPair> neighbours = new ArrayList<MyPair>(); int size = nodesArray.size(); int x = 1; for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); sort(list); if (k == -1) { ListNode point = (ListNode) list.head; while (point != null) { Node temp = (Node)((ListNode)point.data).data; if (temp.data.equals(vertLabel) && temp.type.equals(TARGET)) { MyPair myPair = new MyPair(getMainSoure(list).data, temp.weight); neighbours.add(myPair); } point = point.next; } } else { ListNode point = (ListNode) list.head; while (point != null) { Node temp = (Node)((ListNode)point.data).data; if (temp.data.equals(vertLabel) && temp.type.equals(TARGET) && x <= k) { MyPair myPair = new MyPair(getMainSoure(list).data, temp.weight); neighbours.add(myPair); x = x + 1; } point = point.next; } } } return neighbours; } // end of inNearestNeighbours() public List<MyPair> outNearestNeighbours(int k, String vertLabel) { List<MyPair> neighbours = new ArrayList<MyPair>(); int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); sort(list); Node src = getMainSoure(list); if (src.data.equals(vertLabel)) { if (k == -1) { ListNode point = (ListNode) list.head; while (point != null) { Node temp = (Node)((ListNode)point.data).data; if (temp.type.equals(TARGET)) { MyPair myPair = new MyPair(temp.data, temp.weight); neighbours.add(myPair); } point = point.next; } } else { ListNode point = (ListNode) list.head; int x = 1; while (point != null) { Node temp = (Node)((ListNode)point.data).data; if (temp.type.equals(TARGET) && x <= k) { MyPair myPair = new MyPair(temp.data, temp.weight); neighbours.add(myPair); x = x + 1; } point = point.next; } } } } return neighbours; } // end of outNearestNeighbours() public void printVertices(PrintWriter os) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); os.print(getMainSoure(list).data + " "); } } // end of printVertices() public void printEdges(PrintWriter os) { int size = nodesArray.size(); for (int i = 0; i < size; i++) { MyList list = (MyList) nodesArray.getElement(i); ListNode point = (ListNode) list.head; Node src = getMainSoure(list); while (point != null) { Node temp = (Node)((ListNode)point.data).data; if (temp.type.equals(TARGET)) { os.println(src.data + " " + temp.data + " " + temp.weight); } point = point.next; } } } // end of printEdges() private Node getMainSoure(MyList list) { ListNode point = list.head; Node mainNode = null; while(point!=null) { ListNode temp = (ListNode) point.data; Node node = (Node) temp.data; if(node.type.equals(ROOT)) { mainNode = node; break; } point = point.next; }return mainNode; } protected class Node { String data = null; Node next = null; String type = null; int weight = -1; public Node() { } public Node(String data, String type, int weight) { this.data = data; this.next = null; this.type = type; this.weight = weight; } public String toString() { return data + ":" + type + ":" + weight; } } public void sort(MyList list) { mergeSort(list.head); } public ListNode mergeSort(ListNode head) { if (head == null || head.next == null) { return head; } ListNode mid = getMid(head); ListNode nmid = mid.next; mid.next = null; ListNode left = mergeSort(head); ListNode right = mergeSort(nmid); ListNode sortedList = sortedMerge(left, right); return sortedList; } private ListNode sortedMerge(ListNode a, ListNode b) { ListNode result = null; if (a == null) { return b; } if (b == null) { return a; } if (((Node)((ListNode)a.data).data).weight <= ((Node)((ListNode)b.data).data).weight) { result = a; result.next = sortedMerge(a.next, b); } else { result = b; result.next = sortedMerge(a, b.next); } return result; } private ListNode getMid(ListNode head) { if (head == null) { return head; } ListNode fptr = head.next; ListNode sptr = head; while (fptr != null) { fptr = fptr.next; if (fptr != null) { sptr = sptr.next; fptr = fptr.next; } } return sptr; } } // end of class AdjList
package opt.easyjmetal.util.distance; /** * 距离计算 */ @FunctionalInterface public interface Distance<E, J> { double getDistance(E element1, J element2); }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class ll extends b { public a bVN; public ll() { this((byte) 0); } private ll(byte b) { this.bVN = new a(); this.sFm = false; this.bJX = null; } }
package br.com.zup.zupacademy.daniel.mercadolivre.usuario; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping("/usuario") public class UsuarioController { @Autowired UsuarioRepository usuarioRepository; @PostMapping public void cadastraUsuario(@RequestBody @Valid UsuarioRequest usuarioRequest) { usuarioRepository.save(usuarioRequest.converte()); } }
/* * Copyright 2013 James Geboski <jgeboski@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.frdfsnlght.transporter.compatibility; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.bukkit.Bukkit; public class Reflect { public static Object create(String name, Object ... args) { Class c; Constructor s; try { c = Class.forName(name); s = c.getDeclaredConstructor(getTypes(args)); return s.newInstance(args); } catch (Exception e) { e.printStackTrace(); } return null; } public static Object getField(Object obj, String name) { Field f; try { f = field(obj.getClass(), name); } catch (Exception e) { e.printStackTrace(); return null; } try { return f.get(null); } catch (Exception e) { } return null; } public static RMethod getMethod(Object obj, String name, String ... types) { Method m; try { m = method(obj.getClass(), name, getTypes(types)); } catch (Exception e) { e.printStackTrace(); m = null; } return new RMethod(m, obj); } public static RMethod getMethod(String obj, String name, String ... types) { Class c; Method m; try { c = Class.forName(obj); m = method(c, name, getTypes(types)); } catch (Exception e) { e.printStackTrace(); m = null; } return new RMethod(m, null); } public static Object invoke(Object obj, String name, Object ... args) { Method m; try { m = method(obj.getClass(), name, getTypes(args)); return m.invoke(obj, args); } catch (Exception e) { e.printStackTrace(); } return null; } public static Object invoke(String obj, String name, Object ... args) { Class c; Method m; try { c = Class.forName(obj); m = method(c, name, getTypes(args)); return m.invoke(null, args); } catch (Exception e) { e.printStackTrace(); } return null; } public static boolean isInstance(Object obj, String name) { Class c; try { c = Class.forName(name); return c.isInstance(obj); } catch (Exception e) { e.printStackTrace(); } return false; } public static String obcname(String name) { String n; n = Bukkit.getServer().getClass().getPackage().getName(); n = String.format("%s.%s", n, name); return n; } public static String nmsname(String name) { String n; n = Bukkit.getServer().getClass().getPackage().getName(); n = n.substring(n.lastIndexOf('.') + 1); n = String.format("net.minecraft.server.%s.%s", n, name); return n; } private static Field field(Class klass, String name) throws NoSuchFieldException, SecurityException { Field f; while (true) { try { f = klass.getDeclaredField(name); break; } catch (NoSuchFieldException e) { klass = klass.getSuperclass(); if (klass == null) { throw e; } } } if (!f.isAccessible()) f.setAccessible(true); return f; } private static Method method(Class klass, String name, Class ... types) throws NoSuchMethodException, SecurityException { Method m; while (true) { try { m = klass.getDeclaredMethod(name, types); break; } catch (NoSuchMethodException e) { klass = klass.getSuperclass(); if (klass == null) { throw e; } } } if (!m.isAccessible()) m.setAccessible(true); return m; } private static Class[] getTypes(Object objs[]) { Class t[]; Class c; t = new Class[objs.length]; for (int i = 0; i < objs.length; i++) { c = objs[i].getClass(); try { t[i] = (Class) c.getField("TYPE").get(null); } catch (Exception e) { t[i] = c; } } return t; } private static Class[] getTypes(String objs[]) { Class t[]; t = new Class[objs.length]; for (int i = 0; i < objs.length; i++) { try { t[i] = Class.forName(objs[i]); } catch (Exception e) { t[i] = null; } } return t; } } class RMethod { public Method method; public Object object; public RMethod(Method method, Object object) { this.method = method; this.object = object; } public Object invoke(Object ... args) { if (method == null) return null; try { return method.invoke(object, args); } catch (Exception e) { e.printStackTrace(); } return null; } }
package com.mlm.entity; import com.mlm.db.FHistoryBayar; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import java.math.BigDecimal; import java.util.Date; public class HistoryBayar { private Date tglBayar; private BigDecimal jmlBayar; private BigDecimal jmlSisa; private ODocument doc; public HistoryBayar(ODocument doc) { super(); setDoc(doc); } public Date getTglBayar() { return tglBayar; } public void setTglBayar(Date tglBayar) { doc.field(FHistoryBayar.TGL_BAYAR, tglBayar, OType.DATETIME); this.tglBayar = tglBayar; } public BigDecimal getJmlBayar() { return jmlBayar; } public void setJmlBayar(BigDecimal jmlBayar) { doc.field(FHistoryBayar.JML_BAYAR, jmlBayar, OType.DECIMAL); this.jmlBayar = jmlBayar; } public BigDecimal getJmlSisa() { return jmlSisa; } public void setJmlSisa(BigDecimal jmlSisa) { doc.field(FHistoryBayar.JML_SISA, jmlSisa, OType.DECIMAL); this.jmlSisa = jmlSisa; } public ODocument getDoc() { return doc; } public void setDoc(ODocument doc) { this.tglBayar = doc.field(FHistoryBayar.TGL_BAYAR); this.jmlBayar = doc.field(FHistoryBayar.JML_BAYAR); this.jmlSisa = doc.field(FHistoryBayar.JML_SISA); this.doc = doc; } }
package com.oumar.learn.service.impl; import com.oumar.learn.dao.PersonDAO; import com.oumar.learn.model.Person; import com.oumar.learn.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class PersonServiceImpl implements PersonService{ @Autowired private PersonDAO personDAO; @Override public Person saveOrUpdate(Person person){ return personDAO.save(person); } @Override public Person findOne(Integer id){ return personDAO.findOne(id); } @Override public Person getByEmail(String email){ return personDAO.getByEmail(email); } @Override public Person getByUsername(String username) { return personDAO.getByUsername(username); } }
package com.spring.domain.fieldview; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; //sme_field_view_form_data @Entity @Table(name="sme_field_view_form_data") public class FieldViewFormData implements java.io.Serializable{ /** * */ private static final long serialVersionUID = -752882190454393229L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Integer id; @Column(name = "cid1") private String cid1; @Column(name = "cid2") private String cid2; @Column(name = "cid3") private String cid3; @Column(name = "cid4") private String cid4; @Column(name = "cid5") private String cid5; @Column(name = "cid6") private String cid6; @Column(name = "cid7") private String cid7; @Column(name = "cid8") private String cid8; @Column(name = "cid9") private String cid9; @Column(name = "cid10") private String cid10; @Column(name = "cid11") private String cid11; @Column(name = "cid12") private String cid12; @Column(name = "cid13") private String cid13; @Column(name = "cid14") private String cid14; @Column(name = "cid15") private String cid15; @Column(name = "cid16") private String cid16; @Column(name = "cid17") private String cid17; @Column(name = "cid18") private String cid18; @Column(name = "cid19") private String cid19; @Column(name = "cid20") private String cid20; @Column(name = "cid21") private String cid21; public String getCid1() { return cid1; } public void setCid1(String cid1) { this.cid1 = cid1; } public String getCid2() { return cid2; } public void setCid2(String cid2) { this.cid2 = cid2; } public String getCid3() { return cid3; } public void setCid3(String cid3) { this.cid3 = cid3; } public String getCid4() { return cid4; } public void setCid4(String cid4) { this.cid4 = cid4; } public String getCid5() { return cid5; } public void setCid5(String cid5) { this.cid5 = cid5; } public String getCid6() { return cid6; } public void setCid6(String cid6) { this.cid6 = cid6; } public String getCid7() { return cid7; } public void setCid7(String cid7) { this.cid7 = cid7; } public String getCid8() { return cid8; } public void setCid8(String cid8) { this.cid8 = cid8; } public String getCid9() { return cid9; } public void setCid9(String cid9) { this.cid9 = cid9; } public String getCid10() { return cid10; } public void setCid10(String cid10) { this.cid10 = cid10; } public String getCid11() { return cid11; } public void setCid11(String cid11) { this.cid11 = cid11; } public String getCid12() { return cid12; } public void setCid12(String cid12) { this.cid12 = cid12; } public String getCid13() { return cid13; } public void setCid13(String cid13) { this.cid13 = cid13; } public String getCid14() { return cid14; } public void setCid14(String cid14) { this.cid14 = cid14; } public String getCid15() { return cid15; } public void setCid15(String cid15) { this.cid15 = cid15; } public String getCid16() { return cid16; } public void setCid16(String cid16) { this.cid16 = cid16; } public String getCid17() { return cid17; } public void setCid17(String cid17) { this.cid17 = cid17; } public String getCid18() { return cid18; } public void setCid18(String cid18) { this.cid18 = cid18; } public String getCid19() { return cid19; } public void setCid19(String cid19) { this.cid19 = cid19; } public String getCid20() { return cid20; } public void setCid20(String cid20) { this.cid20 = cid20; } public String getCid21() { return cid21; } public void setCid21(String cid21) { this.cid21 = cid21; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "FieldViewFormData [cid1=" + cid1 + ", cid2=" + cid2 + ", cid3=" + cid3 + ", cid4=" + cid4 + ", cid5=" + cid5 + ", cid6=" + cid6 + ", cid7=" + cid7 + ", cid8=" + cid8 + ", cid9=" + cid9 + ", cid10=" + cid10 + ", cid11=" + cid11 + ", cid12=" + cid12 + ", cid13=" + cid13 + ", cid14=" + cid14 + ", cid15=" + cid15 + ", cid16=" + cid16 + ", cid17=" + cid17 + ", cid18=" + cid18 + ", cid19=" + cid19 + ", cid20=" + cid20 + ", cid21=" + cid21 + "]"; } }
package com.osce.api.biz.training.res.room; import com.osce.dto.biz.training.res.room.RoomDto; import com.osce.dto.common.PfBachChangeStatusDto; import com.osce.entity.ErpRoom; import com.osce.entity.ErpRoomDevice; import com.osce.result.PageResult; /** * @ClassName: PfRoomService * @Description: 房间管理 * @Author yangtongbin * @Date 2019-05-10 */ public interface PfRoomService { /** * 房间列表 * * @param dto * @return */ PageResult pageRooms(RoomDto dto); /** * 增加 * * @param dto * @return */ Long addRoom(ErpRoom dto); /** * 删除 * * @param dto * @return */ boolean delRoom(PfBachChangeStatusDto dto); /** * 设备列表 * * @param dto * @return */ PageResult pageDevices(RoomDto dto); /** * 增加设备 * * @param dto * @return */ Long addRoomDevice(ErpRoomDevice dto); /** * 删除设备 * * @param dto * @return */ boolean delRoomDevice(PfBachChangeStatusDto dto); }
package jaja; import com.fasterxml.jackson.annotation.JsonProperty; public class Cita { @JsonProperty("type") private String tipo; @JsonProperty("value") private Valor valor; public Cita() { } public Cita(String tipo, Valor valor) { this.tipo = tipo; this.valor = valor; } /** * @return the tipo */ public String getTipo() { return tipo; } /** * @param tipo the tipo to set */ public void setTipo(String tipo) { this.tipo = tipo; } /** * @return the valor */ public Valor getValor() { return valor; } /** * @param valor the valor to set */ public void setValor(Valor valor) { this.valor = valor; } }
package pl.gabinetynagodziny.officesforrent.service.impl; import org.springframework.stereotype.Service; import pl.gabinetynagodziny.officesforrent.entity.Detail; import pl.gabinetynagodziny.officesforrent.repository.DetailRepository; import pl.gabinetynagodziny.officesforrent.service.DetailService; import java.util.List; import java.util.Optional; @Service public class DetailServiceImpl implements DetailService { private final DetailRepository detailRepository; public DetailServiceImpl(DetailRepository detailRepository){ this.detailRepository = detailRepository; } @Override public Detail mergeDetail(Detail detail) { Detail detailSaved = detailRepository.save(detail); //chyba do listy trzeba to jeszcze dodac dla obiektu return detailSaved; } @Override public List<Detail> findAll() { return detailRepository.findAll(); } @Override public Optional<Detail> findByDetailId(Long detailId) { return detailRepository.findByDetailId(detailId); } }
/* * Copyright (c) 2021. Alpha Coders */ package com.abhishek.Videogy.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.abhishek.Videogy.R; import com.abhishek.Videogy.model.GuideModel; import com.bumptech.glide.Glide; import java.util.List; public class GuideAdapter extends RecyclerView.Adapter<GuideAdapter.GuideHolder> { private final Context context; private final List<GuideModel> list; public GuideAdapter(Context context, List<GuideModel> list) { this.context = context; this.list = list; } @NonNull @Override public GuideHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.guide_item, parent, false); return new GuideHolder(view); } @Override public void onBindViewHolder(@NonNull GuideHolder holder, int position) { if (position != 3) { holder.top.setVisibility(View.VISIBLE); holder.picture.setVisibility(View.VISIBLE); holder.last.setVisibility(View.GONE); Glide.with(holder.picture) .load(list.get(position).getImage()) .into(holder.picture); holder.number.setText(list.get(position).getNumber()); holder.message.setText(list.get(position).getMessage()); } else { holder.top.setVisibility(View.GONE); holder.picture.setVisibility(View.GONE); holder.last.setVisibility(View.VISIBLE); } } @Override public int getItemCount() { return list.size(); } public static class GuideHolder extends RecyclerView.ViewHolder { private final TextView number; private final TextView message; private final ImageView picture; private final LinearLayout last; private final LinearLayout top; public GuideHolder(@NonNull View itemView) { super(itemView); number = itemView.findViewById(R.id.info_number); message = itemView.findViewById(R.id.info_text); picture = itemView.findViewById(R.id.info_image); last = itemView.findViewById(R.id.last); top = itemView.findViewById(R.id.top); } } }
package com.wizhuo.qrcode.util; import com.google.zxing.common.BitMatrix; import com.wizhuo.qrcode.factory.QrCodeFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Objects; /** * @author lizhuo * @since 2019/1/8 15:50 */ public class MatrixToImageWriter { private static Logger LOGGER = LogManager.getLogger(); //用于设置图案的颜色 private static final int BLACK = 0xFF000000; //用于背景色 private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() { } public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE)); } } return image; } /** * 返回图片url * * @param matrix * @param format * @param file * @return * @throws IOException */ public static String writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { LOGGER.info("生成图片失败"); throw new IOException("Could not write an image of format " + format + " to " + file); } else { LOGGER.info("图片生成成功!"); uploadToOss(file); return file.getName(); } } /** * 返回图片url * * @param matrix * @param format * @param file * @param logUri * @throws IOException */ public static String writeToFileWithLogo(BitMatrix matrix, String format, File file, String logUri) throws IOException { BufferedImage image = toBufferedImage(matrix); //设置logo图标 QrCodeFactory logoConfig = new QrCodeFactory(); image = logoConfig.setMatrixLogo(image, logUri); if (!ImageIO.write(image, format, file)) { LOGGER.warn("生成图片失败"); throw new IOException("Could not write an image of format " + format + " to " + file); } else { LOGGER.info("图片生成成功!"); uploadToOss(file); return file.getName(); } } //上传图片到oos private static void uploadToOss(File file) { /* FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); AliyunOssClientTokenUtil aliyunOssClientTokenUtil = new AliyunOssClientTokenUtil(); aliyunOssClientTokenUtil.uploadToAliyunOss(file.getName(), fileInputStream); //关闭流 if (Objects.nonNull(fileInputStream)) { fileInputStream.close(); } } catch (IOException e) { LOGGER.error(e); throw new RuntimeException("上传文件到oss 失败", e); } finally { if (Objects.nonNull(fileInputStream)) { try { fileInputStream.close(); } catch (IOException e) { LOGGER.error(e); throw new RuntimeException("上传文件到oss 失败", e); } } }*/ } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class user { private String UserName; private String Email; private String Password; private String PhnNum; private String Gender; private String trainName; private String trainTime; private String fromStation; private String toStation; private String tDate; public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public String getPhnNum() { return PhnNum; } public void setPhnNum(String phnNum) { PhnNum = phnNum; } public String getGender() { return Gender; } public void setGender(String gender) { Gender = gender; } user (){ }; public user(String userName, String email, String password, String phnNum, String gender,String fromStation,String toStation,String trainName,String TrainTime,String tDate) { super(); setUserName( userName); setEmail(email); setPassword(password); setPhnNum(phnNum); setGender(gender); this.trainName= trainName; trainTime=TrainTime; this.fromStation=fromStation; this.toStation=toStation; this.tDate=tDate; try { Connection conn=DriverManager.getConnection("jdbc:ucanaccess://E://OOP//Railway Reservation System//Database1.accdb"); PreparedStatement s=conn.prepareStatement("INSERT INTO Traveller(Name,Train,Date,Phoneno,Email,Time) VALUES(?,?,?,?,?,?)"); s.setString(1,userName); s.setString(2,trainName); s.setString(3,tDate); s.setString(4,phnNum); s.setString(5,email); s.setString(6,trainTime); s.executeUpdate(); } catch (Exception e) { System.out.println (e.getMessage()); } } }
package thsst.calvis.simulatorvisualizer.animation.instruction.gp; import thsst.calvis.configuration.model.engine.Memory; import thsst.calvis.configuration.model.engine.RegisterList; import thsst.calvis.configuration.model.engine.Token; import javafx.animation.Interpolator; import javafx.animation.TranslateTransition; import javafx.scene.control.ScrollPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.util.Duration; import thsst.calvis.simulatorvisualizer.model.CalvisAnimation; import java.util.Objects; /** * Created by Goodwin Chua on 5 Jul 2016. */ public class Imul extends CalvisAnimation { private RegisterList registers; private Memory memory; private Token[] tokens; private int width = 140; private int height = 70; private int equalPosition; private Rectangle desRectangle, multiplierRectangle, srcRectangle; private Text desLabelText, desValueText; private Text multiplierLabelText, multiplierValueText; private Text srcLabelText, srcValueText; @Override public void animate(ScrollPane scrollPane) { this.root.getChildren().clear(); scrollPane.setContent(root); this.registers = this.currentInstruction.getRegisters(); this.memory = this.currentInstruction.getMemory(); // ANIMATION ASSETS this.tokens = this.currentInstruction.getParameterTokens(); for ( Token token : this.tokens ) { } // CODE HERE switch ( this.tokens.length ) { case 1: this.imulOneOperand(); break; case 2: this.imulTwoOperand(); break; case 3: this.imulThreeOperand(); break; default: } this.desRectangle.setX(X); this.desRectangle.setY(Y); this.desRectangle.setArcWidth(10); this.desRectangle.setArcHeight(10); this.multiplierRectangle.setX(this.desRectangle.xProperty().getValue() + this.desRectangle.getLayoutBounds().getWidth() + X); this.multiplierRectangle.setY(Y); this.multiplierRectangle.setArcWidth(10); this.multiplierRectangle.setArcHeight(10); this.srcRectangle.setX(this.desRectangle.xProperty().getValue() + this.desRectangle.getLayoutBounds().getWidth() + this.multiplierRectangle.getLayoutBounds().getWidth() + X * 2); this.srcRectangle.setY(Y); this.srcRectangle.setArcWidth(10); this.srcRectangle.setArcHeight(10); Circle equalCircle = new Circle(this.desRectangle.xProperty().getValue() + this.desRectangle.getLayoutBounds().getWidth() + 50, 135, 30, Color.web("#798788", 1.0)); Circle multiplyCircle = new Circle(this.desRectangle.xProperty().getValue() + this.desRectangle.getLayoutBounds().getWidth() + this.multiplierRectangle.getLayoutBounds().getWidth() + 150, 135, 30, Color.web("#798788", 1.0)); this.root.getChildren().addAll(this.desRectangle, this.multiplierRectangle, this.srcRectangle, equalCircle, multiplyCircle); String flagsAffected = "Flags Affected: CF, OF"; Text detailsText = new Text(X, Y * 2, flagsAffected); Text equalText = new Text(X, Y, "="); equalText.setFont(Font.font(48)); equalText.setFill(Color.WHITESMOKE); Text multiplierText = new Text(X, Y, "*"); multiplierText.setFont(Font.font(48)); multiplierText.setFill(Color.WHITESMOKE); this.root.getChildren().addAll(detailsText, equalText, multiplierText, desLabelText, desValueText, multiplierLabelText, multiplierValueText, srcLabelText, srcValueText); // ANIMATION LOGIC TranslateTransition desLabelTransition = new TranslateTransition(); TranslateTransition desTransition = new TranslateTransition(new Duration(1000), this.desValueText); TranslateTransition srcLabelTransition = new TranslateTransition(); TranslateTransition srcTransition = new TranslateTransition(); TranslateTransition multiplierLabelTransition = new TranslateTransition(); TranslateTransition multiplierValueTransition = new TranslateTransition(); TranslateTransition equalTransition = new TranslateTransition(); TranslateTransition multiplierTransition = new TranslateTransition(); // Destination label static desLabelTransition.setNode(this.desLabelText); desLabelTransition.fromXProperty().bind(this.desRectangle.translateXProperty() .add((desRectangle.getLayoutBounds().getWidth() - desLabelText.getLayoutBounds().getWidth()) / 2)); desLabelTransition.fromYProperty().bind(this.desRectangle.translateYProperty() .add(desRectangle.getLayoutBounds().getHeight() / 3)); desLabelTransition.toXProperty().bind(desLabelTransition.fromXProperty()); desLabelTransition.toYProperty().bind(desLabelTransition.fromYProperty()); // Destination value moving desTransition.setInterpolator(Interpolator.LINEAR); desTransition.fromXProperty().bind(this.srcRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X) .add((this.srcRectangle.getLayoutBounds().getWidth() - desValueText.getLayoutBounds().getWidth()) / 2)); desTransition.fromYProperty().bind(this.srcRectangle.translateYProperty() .add(this.srcRectangle.getLayoutBounds().getHeight() / 1.5)); desTransition.toXProperty().bind(this.desRectangle.translateXProperty() .add((this.desRectangle.getLayoutBounds().getWidth() - desValueText.getLayoutBounds().getWidth()) / 2)); desTransition.toYProperty().bind(desTransition.fromYProperty()); // Equal sign label static equalTransition.setNode(equalText); equalTransition.fromXProperty().bind(this.desRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + this.equalPosition + this.srcRectangle.getLayoutBounds().getWidth()) .divide(2)); equalTransition.fromYProperty().bind(this.desRectangle.translateYProperty() .add(this.desRectangle.getLayoutBounds().getHeight() / 1.5)); equalTransition.toXProperty().bind(equalTransition.fromXProperty()); equalTransition.toYProperty().bind(equalTransition.fromYProperty()); // Multiplier label static multiplierLabelTransition.setNode(this.multiplierLabelText); multiplierLabelTransition.fromXProperty().bind(this.multiplierRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X) .add((this.multiplierRectangle.getLayoutBounds().getWidth() - multiplierLabelText.getLayoutBounds().getWidth()) / 2)); multiplierLabelTransition.fromYProperty().bind(desLabelTransition.fromYProperty()); multiplierLabelTransition.toXProperty().bind(multiplierLabelTransition.fromXProperty()); multiplierLabelTransition.toYProperty().bind(multiplierLabelTransition.fromYProperty()); // Multiplier value static multiplierValueTransition.setNode(this.multiplierValueText); multiplierValueTransition.fromXProperty().bind(this.multiplierRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X) .add((this.multiplierRectangle.getLayoutBounds().getWidth() - multiplierValueText.getLayoutBounds().getWidth()) / 2)); multiplierValueTransition.fromYProperty().bind(this.multiplierRectangle.translateYProperty() .add(this.multiplierRectangle.getLayoutBounds().getHeight() / 1.5)); multiplierValueTransition.toXProperty().bind(multiplierValueTransition.fromXProperty()); multiplierValueTransition.toYProperty().bind(multiplierValueTransition.fromYProperty()); // Multiply sign label static multiplierTransition.setNode(multiplierText); multiplierTransition.fromXProperty().bind(this.desRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X + this.multiplierRectangle.getLayoutBounds().getWidth() + 40)); multiplierTransition.fromYProperty().bind(equalTransition.fromYProperty().add(12.5)); multiplierTransition.toXProperty().bind(multiplierTransition.fromXProperty()); multiplierTransition.toYProperty().bind(multiplierTransition.fromYProperty()); // Source label static srcLabelTransition.setNode(this.srcLabelText); srcLabelTransition.fromXProperty().bind(this.srcRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X + this.multiplierRectangle.getLayoutBounds().getWidth() + X) .add((this.srcRectangle.getLayoutBounds().getWidth() - srcLabelText.getLayoutBounds().getWidth()) / 2)); srcLabelTransition.fromYProperty().bind(desLabelTransition.fromYProperty()); srcLabelTransition.toXProperty().bind(srcLabelTransition.fromXProperty()); srcLabelTransition.toYProperty().bind(srcLabelTransition.fromYProperty()); // Source value static srcTransition.setNode(this.srcValueText); srcTransition.fromXProperty().bind(this.srcRectangle.translateXProperty() .add(this.desRectangle.getLayoutBounds().getWidth() + X + this.multiplierRectangle.getLayoutBounds().getWidth() + X) .add((this.srcRectangle.getLayoutBounds().getWidth() - srcValueText.getLayoutBounds().getWidth()) / 2)); srcTransition.fromYProperty().bind(desTransition.fromYProperty()); srcTransition.toXProperty().bind(srcTransition.fromXProperty()); srcTransition.toYProperty().bind(srcTransition.fromYProperty()); // Play 1000 milliseconds of animation desLabelTransition.play(); desTransition.play(); equalTransition.play(); multiplierLabelTransition.play(); multiplierValueTransition.play(); multiplierTransition.play(); srcLabelTransition.play(); srcTransition.play(); } private void imulOneOperand() { this.equalPosition = 110; this.desRectangle = this.createRectangle(Token.REG, this.width + 40, this.height); this.multiplierRectangle = this.createRectangle(Token.REG, this.width, this.height); this.srcRectangle = this.createRectangle(this.tokens[0], this.width, this.height); int desSize = 0; if ( Objects.equals(this.tokens[0].getType(), Token.REG) ) { desSize = registers.getBitSize(this.tokens[0]); } else if ( Objects.equals(this.tokens[0].getType(), Token.MEM) ) desSize = memory.getBitSize(this.tokens[0]); this.srcLabelText = this.createLabelText(X, Y, this.tokens[0]); this.srcValueText = this.createValueText(X, Y, this.tokens[0], this.registers, this.memory, desSize); String value; switch ( desSize ) { case 8: this.desLabelText = new Text(X, Y, "AX"); value = "0x" + registers.get("AX"); this.desValueText = new Text(X, Y, value); this.multiplierLabelText = new Text(X, Y, "AL"); value = "0x" + this.finder.getRegister("AL"); this.multiplierValueText = new Text(X, Y, value); break; case 16: this.desLabelText = new Text(X, Y, "DX, AX"); value = "0x" + registers.get("DX") + ", 0x" + registers.get("AX"); this.desValueText = new Text(X, Y, value); this.multiplierLabelText = new Text(X, Y, "AX"); value = "0x" + this.finder.getRegister("AX"); this.multiplierValueText = new Text(X, Y, value); break; case 32: this.desLabelText = new Text(X, Y, "EDX, EAX"); value = "0x" + registers.get("EDX") + ", 0x" + registers.get("EAX"); this.desValueText = new Text(X, Y, value); this.multiplierLabelText = new Text(X, Y, "EAX"); value = "0x" + this.finder.getRegister("EAX"); this.multiplierValueText = new Text(X, Y, value); break; default: this.desLabelText = new Text(); this.desValueText = new Text(); this.multiplierLabelText = new Text(); this.multiplierValueText = new Text(); } } private void imulTwoOperand() { this.equalPosition = 70; this.desRectangle = this.createRectangle(this.tokens[0], this.width, this.height); this.multiplierRectangle = this.createRectangle(this.tokens[0], this.width, this.height); this.srcRectangle = this.createRectangle(this.tokens[1], this.width, this.height); int desSize = 0; if ( tokens[0].getType() == Token.REG ) desSize = registers.getBitSize(tokens[0]); else if ( tokens[0].getType() == Token.MEM && tokens[1].getType() == Token.REG ) desSize = registers.getBitSize(tokens[1]); else desSize = memory.getBitSize(tokens[0]); this.desLabelText = this.createLabelText(X, Y, tokens[0]); this.desValueText = this.createValueText(X, Y, tokens[0], registers, memory, desSize); this.multiplierLabelText = this.createLabelText(X, Y, tokens[0]); this.multiplierValueText = this.createValueTextUsingFinder(X, Y, tokens[0], desSize); this.srcLabelText = this.createLabelText(X, Y, tokens[1]); this.srcValueText = this.createValueText(X, Y, tokens[1], registers, memory, desSize); } private void imulThreeOperand() { this.equalPosition = 70; this.desRectangle = this.createRectangle(this.tokens[0], this.width, this.height); this.multiplierRectangle = this.createRectangle(this.tokens[1], this.width, this.height); this.srcRectangle = this.createRectangle(this.tokens[2], this.width, this.height); int desSize = registers.getBitSize(tokens[0]); int multiplierSize = 0; if ( Objects.equals(this.tokens[1].getType(), Token.REG) ) { multiplierSize = registers.getBitSize(this.tokens[1]); } else if ( Objects.equals(this.tokens[1].getType(), Token.MEM) ) multiplierSize = memory.getBitSize(this.tokens[1]); this.desLabelText = this.createLabelText(X, Y, tokens[0]); this.desValueText = this.createValueText(X, Y, tokens[0], registers, memory, desSize); this.multiplierLabelText = this.createLabelText(X, Y, tokens[1]); this.multiplierValueText = this.createValueText(X, Y, tokens[1], registers, memory, multiplierSize); this.srcLabelText = this.createLabelText(X, Y, tokens[2]); this.srcValueText = new Text(X, Y, "0x" + tokens[2].getValue()); } }
package com.tencent.mm.protocal.c; import f.a.a.c.a; import java.util.LinkedList; public final class bhe extends bhd { public String lMV; public String muA; public String muB; public int mun; public String ref; public int shY; public String shZ; public int sia; public int sib; protected final int a(int i, Object... objArr) { int fS; if (i == 0) { a aVar = (a) objArr[0]; if (this.shX != null) { aVar.fV(1, this.shX.boi()); this.shX.a(aVar); } if (this.muA != null) { aVar.g(2, this.muA); } if (this.muB != null) { aVar.g(3, this.muB); } if (this.lMV != null) { aVar.g(4, this.lMV); } aVar.fT(5, this.mun); aVar.fT(6, this.shY); if (this.shZ != null) { aVar.g(7, this.shZ); } aVar.fT(8, this.sia); aVar.fT(9, this.sib); if (this.ref == null) { return 0; } aVar.g(10, this.ref); return 0; } else if (i == 1) { if (this.shX != null) { fS = f.a.a.a.fS(1, this.shX.boi()) + 0; } else { fS = 0; } if (this.muA != null) { fS += f.a.a.b.b.a.h(2, this.muA); } if (this.muB != null) { fS += f.a.a.b.b.a.h(3, this.muB); } if (this.lMV != null) { fS += f.a.a.b.b.a.h(4, this.lMV); } fS = (fS + f.a.a.a.fQ(5, this.mun)) + f.a.a.a.fQ(6, this.shY); if (this.shZ != null) { fS += f.a.a.b.b.a.h(7, this.shZ); } fS = (fS + f.a.a.a.fQ(8, this.sia)) + f.a.a.a.fQ(9, this.sib); if (this.ref != null) { fS += f.a.a.b.b.a.h(10, this.ref); } return fS; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; bhe bhe = (bhe) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); switch (intValue) { case 1: LinkedList IC = aVar3.IC(intValue); int size = IC.size(); for (intValue = 0; intValue < size; intValue++) { byte[] bArr = (byte[]) IC.get(intValue); fk fkVar = new fk(); f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (boolean z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) { } bhe.shX = fkVar; } return 0; case 2: bhe.muA = aVar3.vHC.readString(); return 0; case 3: bhe.muB = aVar3.vHC.readString(); return 0; case 4: bhe.lMV = aVar3.vHC.readString(); return 0; case 5: bhe.mun = aVar3.vHC.rY(); return 0; case 6: bhe.shY = aVar3.vHC.rY(); return 0; case 7: bhe.shZ = aVar3.vHC.readString(); return 0; case 8: bhe.sia = aVar3.vHC.rY(); return 0; case 9: bhe.sib = aVar3.vHC.rY(); return 0; case 10: bhe.ref = aVar3.vHC.readString(); return 0; default: return -1; } } } }
package com.deltastuido.payment.port.wepay.api.model; import com.deltastuido.payment.port.wepay.api.WepayResponse; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; /** * @author */ @XmlRootElement(name = "xml") @XmlAccessorType(XmlAccessType.PROPERTY) public class PaymentNotifyResponse extends WepayResponse implements Serializable { String return_code;// 返回状态码 return_code 是 String(16) SUCCESS SUCCESS/FAIL SUCCESS表示商户接收通知成功并校验成功 String return_msg;// 返回信息 return_msg 否 String(128) OK 返回信息,如非空,为错误原因: 签名失败 参数格式校验错误 public String getReturn_code() { return return_code; } public void setReturn_code(String return_code) { this.return_code = return_code; } public String getReturn_msg() { return return_msg; } public void setReturn_msg(String return_msg) { this.return_msg = return_msg; } }
/* * 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 AAPA.Entity; import java.util.Date; import java.util.Timer; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author amine */ @Entity public class Alarm { @Id @GeneratedValue (strategy = GenerationType.AUTO) public Long idAlarm; public String title; public String periodicite;//Quotidien, Mensuel, Hebdomadaire, Aucune public String dateDebut; boolean traité; public String dateDernierTraitement; public Alarm(){ } Alarm(String title, String periodicite, String dateDebut){ this.dateDebut=dateDebut; this.periodicite=periodicite; this.title=title; } public Long getidAlarm(){ return this.idAlarm; } public String getdateDebut(){ return this.dateDebut; } public String getdateDernierTraitement(){ return this.dateDernierTraitement; } public String getperiodicite(){ return this.periodicite; } public String gettitle(){ return this.title; } public boolean gettraite(){ return this.traité; } public void setidAlarm(long idAlarm){ this.idAlarm=idAlarm; } public void setdateDebut(String dateDebut){ this.dateDebut=dateDebut; } public void setdateDernierTraitement(String dateDernierTraitement){ this.dateDernierTraitement=dateDernierTraitement; } public void setperiodicite(String periodicite){ this.periodicite=periodicite; } public void settitle(String title){ this.title=title; } public void settraite(boolean traite){ this.traité=traite; } }
package io.github.luanelioliveira.library.repository; import io.github.luanelioliveira.library.model.Book; import java.util.List; import java.util.Optional; public interface BookRepository { Book save(Book book); Optional<Book> getByIsbn(String isbn); List<Book> findAll(); }
package rent.api.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import rent.common.entity.SystemPropertyEntity; import rent.common.enums.SystemPropertyType; import rent.common.repository.SystemPropertyRepository; @Service public class SystemPropertyService { private final SystemPropertyRepository systemPropertyRepository; @Autowired public SystemPropertyService(SystemPropertyRepository systemPropertyRepository) { this.systemPropertyRepository = systemPropertyRepository; } boolean getCalculationIsActive() { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_IS_ACTIVE.getName()); return systemProperty != null && systemProperty.getValue().equals("1"); } void setCalculationActive(Boolean active) { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_IS_ACTIVE.getName()); systemProperty.setValue(active ? "1" : "0"); systemPropertyRepository.save(systemProperty); } public Integer getCalculationAccountsCount() { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_ACCOUNTS_COUNT.getName()); return systemProperty != null ? Integer.valueOf(systemProperty.getValue()) : 0; } void setCalculationAccountsCount(Integer accountsCount) { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_ACCOUNTS_COUNT.getName()); systemProperty.setValue(accountsCount.toString()); systemPropertyRepository.save(systemProperty); } public Integer getCalculationAccountsCalculated() { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_ACCOUNTS_CALCULATED.getName()); return systemProperty != null ? Integer.valueOf(systemProperty.getValue()) : 0; } void setCalculationAccountsCalculated(Integer accountsCalculated) { SystemPropertyEntity systemProperty = systemPropertyRepository.findFirstByNameContaining(SystemPropertyType.CALCULATION_ACCOUNTS_CALCULATED.getName()); systemProperty.setValue(accountsCalculated.toString()); systemPropertyRepository.save(systemProperty); } long getCount() { return systemPropertyRepository.count(); } void save(SystemPropertyEntity systemProperty) { systemPropertyRepository.save(systemProperty); } }
package gof.decorator.example; import java.io.*; public class LowerCaseInputStream extends FileInputStream { // ORIGINAL CODE - doesn't compile - so the default constructor will be placed /*public LowerCaseInputStream(InputStream in) { super(in); }*/ // IMPORTSNT - this constructor is just fake; has been added to make the code compile public LowerCaseInputStream(String name) throws FileNotFoundException { super(name); } public int read() throws IOException { int c = super.read(); return (c == -1 ? c : Character.toLowerCase((char)c)); } public int read(byte[] b, int offset, int len) throws IOException { int result = super.read(b, offset, len); for (int i = offset; i < offset+result; i++) { b[i] = (byte)Character.toLowerCase((char)b[i]); } return result; } }
package com.haibo.service; import com.haibo.pojo.User; /** * Created with IDEA. * User:haibo. * DATE:2018/4/12/012 */ public interface UserService { //用户登录 public User checkLogin(String s_name, String s_password ); //用户注册 public User addUser(User user); }
package pms.dao; import java.util.ArrayList; import org.springframework.stereotype.Repository; import pms.dto.Log; @Repository public interface LogDao { public void taskIns(Log log); public ArrayList<Log> taskLog(int no); // 태스크 추가 public ArrayList<Log> reqLog(int no); // 태스크 완료 승인요청 public ArrayList<Log> projLog(int no); // 프로젝트 인원 할당 }
package com.goodhealth.algorithm.Date; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.util.concurrent.TimeUnit; public class NewDateAPI { public static void main(String[] args){ Instant start = Instant.now(); System.out.println(start); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } Instant end = Instant.now(); Duration duration = Duration.between(start, end); System.out.println(duration.toHours()); System.out.println(duration.toMinutes()); System.out.println(duration.getSeconds()); System.out.println(LocalDate.now()); } }
package com.tencent.mm.g.a; public final class ew$b { public int bMG = 0; public int bMH = 0; public String bMI; }
/** * @Copyright coppermobile pvt. ltd. 2014 * **/ package com.atn.app.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.atn.app.R; import com.atn.app.listener.DialogClickEventListener; import com.atn.app.utils.SharedPrefUtils; /** * Show help screen on first time login user. * **/ @Deprecated public class HelpDialog extends DialogFragment implements OnPageChangeListener ,OnClickListener{ public static final String HELP_DIALOG = "HELP_DIALOG"; private static final String RIGHT_MARGIN = "RIGHT_MARGIN"; private DialogClickEventListener mButtonListener; private ViewPager mPager; private HelpPagerAdapter mPagerAdapter = null; private ImageView mFirstIndicatorImage; private ImageView mSecondIndicatorImage; private Button mAddPhotoButton; private Button mAddReviewButton; private int mBottomMargin = 0; public static HelpDialog newInstance(int margin,DialogClickEventListener mButtonListener) { Bundle bunlde = new Bundle(); bunlde.putInt(RIGHT_MARGIN, margin); HelpDialog fragment = new HelpDialog(); fragment.mButtonListener = mButtonListener; fragment.setArguments(bunlde); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(0,R.style.help_dialog_style); mPagerAdapter = new HelpPagerAdapter(getChildFragmentManager()); mBottomMargin = getArguments().getInt(RIGHT_MARGIN, 0); SharedPrefUtils.setUserFirstTimeLoginStatus(getActivity(), false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout view = (LinearLayout)inflater.inflate(R.layout.help_layout, container, false); View bottomContainer = view.findViewById(R.id.bottom_button_container); LinearLayout.LayoutParams param = (LinearLayout.LayoutParams)bottomContainer.getLayoutParams(); param.setMargins(0, 0, mBottomMargin, 0); bottomContainer.setLayoutParams(param); mFirstIndicatorImage = (ImageView)view.findViewById(R.id.first_image); mSecondIndicatorImage = (ImageView)view.findViewById(R.id.second_image); mAddPhotoButton = (Button)view.findViewById(R.id.help_add_photos_button); mAddReviewButton = (Button)view.findViewById(R.id.help_add_reviews_button); view.findViewById(R.id.help_close_hint_button).setOnClickListener(this); mAddPhotoButton.setVisibility(View.INVISIBLE); mFirstIndicatorImage.setSelected(true); mAddPhotoButton.setOnClickListener(this); mAddReviewButton.setOnClickListener(this); mPager = (ViewPager)view.findViewById(R.id.help_view_pager); mPager.setAdapter(mPagerAdapter); mPager.setOffscreenPageLimit(2); mPager.setOnPageChangeListener(this); return view; } private class ContentFragment extends Fragment { public static final String POSITION = "position"; private int mPosition = 0; @Override public void onCreate(Bundle savedInstanceState) { mPosition = getArguments().getInt(POSITION, 0); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { LinearLayout view = (LinearLayout)inflater.inflate(R.layout.help_content_layout, container, false); ImageView mImageView = (ImageView)view.findViewById(R.id.help_big_image_view); TextView mHelpNameTextView = (TextView)view.findViewById(R.id.hint_name_text_view); TextView mHelpDescriptionTextView = (TextView)view.findViewById(R.id.hint_description_text_view); mImageView.setImageResource(mPosition==0?R.drawable.icn_menu_addreview_hint_big:R.drawable.icn_menu_addphoto_hint_big); mHelpNameTextView.setText(mPosition==0?R.string.add_review_text:R.string.add_photo_text); if(mPosition==0) { mHelpDescriptionTextView.setText(R.string.help_text_add_review_part_1); } else { mHelpDescriptionTextView.setText(R.string.help_text_add_photo); } return view; } } private class HelpPagerAdapter extends FragmentStatePagerAdapter { public HelpPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return 2; } @Override public Fragment getItem(int position) { Bundle bunlde = new Bundle(); bunlde.putInt(ContentFragment.POSITION, position); ContentFragment fragment = new ContentFragment(); fragment.setArguments(bunlde); return fragment; } } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels){ } @Override public void onPageSelected(int position) { mFirstIndicatorImage.setSelected(position==0); mSecondIndicatorImage.setSelected(position==1); if(position==0){ mAddPhotoButton.setVisibility(View.INVISIBLE); mAddReviewButton.setVisibility(View.VISIBLE); }else{ mAddPhotoButton.setVisibility(View.VISIBLE); mAddReviewButton.setVisibility(View.INVISIBLE); } } @Override public void onClick(View v) { dismiss(); if(mButtonListener!=null){ mButtonListener.onClick(v.getId()); } // switch (v.getId()) { // // case R.id.help_add_photos_button: // if(mButtonListener!=null){ // mButtonListener.onClick(R.id.help_add_photos_button); // } // break; // case R.id.help_add_reviews_button: // // if(mButtonListener!=null){ // mButtonListener.onClick(R.id.help_add_reviews_button); // } // // break; // case R.id.help_close_hint_button: // if(mButtonListener!=null){ // mButtonListener.onClick(R.id.help_add_reviews_button); // } // break; // default: // break; // } } }
package com.studio.saradey.aplicationvk.model.countable; /** * @author jtgn on 14.08.2018 */ public interface Countable { int getCount(); }
public class Operation { private String typeAccount; private String accountNumber; private String currency; private String date; private String reference; private String specificationOperation; private double deposit; private double expense; public Operation(String typeAccount, String accountNumber, String currency, String date, String reference, String specificationOperation, double deposit, double expense) { this.typeAccount = typeAccount; this.accountNumber = accountNumber; this.currency = currency; this.date = date; this.reference = reference; String[] specOper = specificationOperation.split(" {4}"); String specOper1 = specOper[1].trim().replaceAll("\\\\", "/"); this.specificationOperation = specOper1.substring(specOper1.lastIndexOf("/") + 1).trim(); this.deposit = deposit; this.expense = expense; } public String toString() { return typeAccount + " - " + accountNumber + " - " + currency + " - " + date + " - " + reference + " - " + specificationOperation + " - " + deposit + " - " + expense; } public String getTypeAccount() { return typeAccount; } public String getAccountNumber() { return accountNumber; } public String getCurrency() { return currency; } public String getDate() { return date; } public String getReference() { return reference; } public String getSpecificationOperation() { return specificationOperation; } public double getDeposit() { return deposit; } public double getExpense() { return expense; } }
package com.example.libroapp; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class resultadosBusqueda extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public resultadosBusqueda() { // Required empty public constructor } public resultadosBusqueda(String busqueda, String filtro) { bus =busqueda; fil =filtro; } String bus; String fil; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_resultados_busqueda, container, false); Resources res = getResources(); String[] Libros; final String[] ISVarray; final String[] Autor; ArrayList<String> titulos = new ArrayList<>(); ArrayList<String> ISBN = new ArrayList<>(); ArrayList<String> autor = new ArrayList<>(); String sql = "select distinct l.nombre , l.ISBN , group_concat(distinct a.nombre)as AUTOR from libro as l inner join genero_libro_relacion glr on glr.idlibro=l.idlibro inner join genero_libro gl on gl.idgenero=glr.idgenero inner join autor_libro al on al.idlibro=l.idlibro inner join autor a on a.idautor=al.idautor where l.nombre like \"%"+bus+"%\" and gl.nombre like \"%"+fil+"%\" group by l.idlibro;"; try { ConnectionSql con = new ConnectionSql(sql, 1); Thread threadQuery = new Thread(con); threadQuery.start(); threadQuery.join(); ResultSet output = con.getOutput(); while (output.next()) { titulos.add(output.getString(1)); System.out.println(output.getString(1)); ISBN.add(output.getString(2)); autor.add(output.getString(3)); } con.desconectar(); } catch (InterruptedException | SQLException e) { e.printStackTrace(); } ListView listview = root.findViewById(R.id.resultados_listview); Libros = titulos.toArray(new String[0]); ISVarray = ISBN.toArray(new String[0]); Autor = autor.toArray(new String[0]); ItemAdapterBusquedaR itemAdapterBusquedaR=new ItemAdapterBusquedaR(requireActivity(),Libros,ISVarray, Autor); listview.setAdapter(itemAdapterBusquedaR); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { FragmentManager manager = getFragmentManager(); String autor=ISVarray[position]; detailAct nuevo=new detailAct(); Bundle Arguments=new Bundle(); Arguments.putInt("INDEX",position); Arguments.putString("ISV",autor); nuevo.setArguments(Arguments); manager.beginTransaction().replace(R.id.nav_host_fragment, nuevo).commit(); } }); return root; } }
package com.commercetools.sunrise.shoppingcart.common; public class PrimaryCartNotFoundException extends RuntimeException { }
package Dessert; /** * Created by Jared Ramirez on 4/4/2015. * Byte-Pushers */ public class Cake implements Dessert { public String getName(){ return "Yummy Cake"; } }
package com.ci.api.block; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class DirectionThree extends ComponentBase { public DirectionThree(String name){super(name);} public static final PropertyInteger FACING = PropertyInteger.create("facing", 0, 2); @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING); } @Override public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing blockFaceClickedOn, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { EnumFacing enumfacing = (placer == null) ? EnumFacing.NORTH : EnumFacing.getDirectionFromEntityLiving(pos, placer); int b; if (enumfacing == EnumFacing.NORTH || enumfacing == EnumFacing.SOUTH){ b = 0; }else if (enumfacing == EnumFacing.WEST || enumfacing == EnumFacing.EAST){ b = 1; }else {b = 2;} return this.getDefaultState().withProperty(FACING, b); } @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState().withProperty(FACING, meta); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING); } public int getFacingNumber(EnumFacing enumFacing){ int b; if (enumFacing == EnumFacing.NORTH || enumFacing == EnumFacing.SOUTH){ b = 0; }else if (enumFacing == EnumFacing.WEST || enumFacing == EnumFacing.EAST){ b = 1; }else{ b = 2; } return b; } public EnumFacing getFacing(int b){ if (b == 0){ return EnumFacing.NORTH; }else if (b == 1){ return EnumFacing.WEST; }else { return EnumFacing.UP; } } public boolean canConnect(EnumFacing enumFacing, int i){ return enumFacing == getFacing(i) || enumFacing == getFacing(i).getOpposite(); } }
/* * Power by www.xiaoi.com */ package com.zokee.servlet; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import com.zokee.FileTransfer; /** * @author <a href="mailto:eko.z@outlook.com">eko.zhan</a> * @date Jul 23, 2015 9:36:25 AM * @version 1.0 */ public class FileAction extends HttpServlet { private static FileTransfer ftpClient = FileTransfer.getInstance(); private final static String FILE_UPLOAD = "FILE_UPLOAD"; private final static String FILE_DOWNLOAD = "FILE_DOWNLOAD"; private final static String FILE_DELETE = "FILE_DELETE"; private final static String Encoding_UTF8 = "UTF-8"; /** * Constructor of the object. */ public FileAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (StringUtils.isBlank(action)){ //附件列表 list(request, response); }else{ if (action.equals(FILE_UPLOAD)){ upload(request, response); }else if (action.equals(FILE_DOWNLOAD)){ download(request, response); }else if (action.equals(FILE_DELETE)){ delete(request, response); } } } private void delete(HttpServletRequest request, HttpServletResponse response) { String filepath = request.getParameter("filepath"); if (filepath.indexOf(ftpClient.getFtpRoot())!=-1){ filepath = filepath.substring(filepath.lastIndexOf(ftpClient.getFtpRoot())+ftpClient.getFtpRoot().length()); } String filename = FilenameUtils.getName(filepath); try { ftpClient.fileDelete(filepath); response.sendRedirect("FileAction"); } catch (Exception e) { e.printStackTrace(); } } private void list(HttpServletRequest request, HttpServletResponse response) { try { List<String> list = ftpClient.listFile(""); request.setAttribute("list", list); RequestDispatcher rd = request.getRequestDispatcher("../upload.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } private void upload(HttpServletRequest request, HttpServletResponse response){ // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart){ try { request.setCharacterEncoding(Encoding_UTF8); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(Encoding_UTF8); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println("Form field [" + name + "] with value " + Streams.asString(stream, Encoding_UTF8) + " detected."); } else { String filename = item.getName(); if (StringUtils.isNotBlank(filename)){ filename = URLDecoder.decode(filename, Encoding_UTF8); System.out.println("File field [" + name + "] with file name " + item.getName() + " detected."); // Process the input stream //这里上传文件 filename = FilenameUtils.getName(filename); ftpClient.fileTransfer(stream, "", filename); } } } response.sendRedirect("FileAction"); } catch (FileUploadException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } private void download(HttpServletRequest request, HttpServletResponse response){ try { InputStream in = null; String filepath = request.getParameter("filepath"); if (filepath.indexOf(ftpClient.getFtpRoot())!=-1){ filepath = filepath.substring(filepath.lastIndexOf(ftpClient.getFtpRoot())+ftpClient.getFtpRoot().length()); } String filename = FilenameUtils.getName(filepath); String filetype = "." + FilenameUtils.getExtension(filename); ServletOutputStream out = response.getOutputStream(); try { in = ftpClient.fileRead(filepath); System.out.println(filename); //文件名乱码问题 if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0){ filename = URLEncoder.encode(filename, Encoding_UTF8);//IE浏览器 }else{ filename = new String(filename.getBytes(Encoding_UTF8), "ISO8859-1");//firefox浏览器 } response.addHeader("Content-Disposition", "attachment;filename=" + filename); // response.addHeader("Content-Length", "" + in.length()); // response.setContentType(MimeUtils.getString(filetype)); response.setContentType("application/x-msdownload"); response.setCharacterEncoding(Encoding_UTF8); IOUtils.copy(in, out); } catch (Exception e) { e.printStackTrace(); } finally{ IOUtils.closeQuietly(in); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.blackvelvet.cybos.bridge.cputil ; import com4j.*; /** */ public enum CPE_LAC_KIND implements ComEnum { /** * <p> * 구분없음 * </p> * <p> * The value of this constant is 0 * </p> */ CPC_LAC_NORMAL(0), /** * <p> * 권리락 * </p> * <p> * The value of this constant is 1 * </p> */ CPC_LAC_EX_RIGHTS(1), /** * <p> * 배당락 * </p> * <p> * The value of this constant is 2 * </p> */ CPC_LAC_EX_DIVIDEND(2), /** * <p> * 분배락 * </p> * <p> * The value of this constant is 3 * </p> */ CPC_LAC_EX_DISTRI_DIVIDEND(3), /** * <p> * 권배락 * </p> * <p> * The value of this constant is 4 * </p> */ CPC_LAC_EX_RIGHTS_DIVIDEND(4), /** * <p> * 중간배당락 * </p> * <p> * The value of this constant is 5 * </p> */ CPC_LAC_INTERIM_DIVIDEND(5), /** * <p> * 권리중간배당락 * </p> * <p> * The value of this constant is 6 * </p> */ CPC_LAC_EX_RIGHTS_INTERIM_DIVIDEND(6), /** * <p> * 액면분할 * </p> * <p> * The value of this constant is 7 * </p> */ CPC_LAC_PAR_DIVIDE(7), /** * <p> * 액면병합 * </p> * <p> * The value of this constant is 8 * </p> */ CPC_LAC_PAR_MERGE(8), /** * <p> * 감자 * </p> * <p> * The value of this constant is 9 * </p> */ CPC_LAC_REDUCTION(9), /** * <p> * 병합 * </p> * <p> * The value of this constant is 10 * </p> */ CPC_LAC_MERGE(10), /** * <p> * 기타 * </p> * <p> * The value of this constant is 99 * </p> */ CPC_LAC_ETC(99), ; private final int value; CPE_LAC_KIND(int value) { this.value=value; } public int comEnumValue() { return value; } }
package br.com.engenharia; public class Pilar { }
package com.tencent.mm.plugin.j.c; import com.tencent.mm.plugin.j.b; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; public final class a implements Runnable { private bd bGS; private int opType; public a(bd bdVar, int i) { this.bGS = bdVar; this.opType = i; x.d("MicroMsg.MsgEventTask", "%d msg id[%d %d] optype[%d]", new Object[]{Integer.valueOf(hashCode()), Long.valueOf(this.bGS.field_msgId), Integer.valueOf(this.bGS.getType()), Integer.valueOf(this.opType)}); } public final void run() { switch (this.opType) { case 1: b.avr().K(this.bGS); return; default: x.w("MicroMsg.MsgEventTask", "%d unknow op type [%d]", new Object[]{Integer.valueOf(hashCode()), Integer.valueOf(this.opType)}); return; } } }
package com.test.demo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentService implements IStudentService { @Autowired private StudentDao dao; @Override public void save(List<Student> students) { dao.save(students); } }
package com.tencent.pb.common.b.a; import com.google.a.a.b; import com.google.a.a.e; import com.tencent.pb.common.b.a.a.at; public final class a$ac extends e { public String groupId; public at vcK; public int ven; public a$ac() { this.groupId = ""; this.vcK = null; this.ven = 0; this.bfP = -1; } public final void a(b bVar) { if (!this.groupId.equals("")) { bVar.g(1, this.groupId); } if (this.vcK != null) { bVar.a(2, this.vcK); } if (this.ven != 0) { bVar.aE(3, this.ven); } super.a(bVar); } protected final int sl() { int sl = super.sl(); if (!this.groupId.equals("")) { sl += b.h(1, this.groupId); } if (this.vcK != null) { sl += b.b(2, this.vcK); } if (this.ven != 0) { return sl + b.aG(3, this.ven); } return sl; } }
package org.inftel.socialwind.client.web.mvp.activities; import java.util.List; import org.inftel.socialwind.client.web.Location; import org.inftel.socialwind.client.web.Utilidades; import org.inftel.socialwind.client.web.mvp.ClientFactory; import org.inftel.socialwind.client.web.mvp.event.AppBusyEvent; import org.inftel.socialwind.client.web.mvp.event.AppFreeEvent; import org.inftel.socialwind.client.web.mvp.places.SpotPlace; import org.inftel.socialwind.client.web.mvp.presenter.PlayasListPresenter; import org.inftel.socialwind.client.web.mvp.view.PlayasListView; import org.inftel.socialwind.shared.domain.SpotProxy; import org.inftel.socialwind.shared.services.SocialwindRequestFactory; import org.inftel.socialwind.shared.services.SpotRequest; import com.google.gwt.activity.shared.AbstractActivity; import com.google.gwt.core.client.GWT; import com.google.gwt.event.shared.EventBus; import com.google.gwt.place.shared.Place; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.ServerFailure; /** * Implementacion del Presenter para el listado de playas * * @author aljiru * */ public class PlayasListActivity extends AbstractActivity implements PlayasListPresenter { private ClientFactory clientFactory = GWT.create(ClientFactory.class); private EventBus eventBus; private PlayasListView playasListView; private SocialwindRequestFactory swrf; private boolean hot; /** * Metodo constructor que inicializa las distintas variables que tienen parte en esta clase * * @param playasListView * Vista del listado de playas */ public void start(AcceptsOneWidget panel, EventBus eventBus) { this.swrf = clientFactory.getSWRF(); this.eventBus = clientFactory.getEventBus(); this.playasListView = clientFactory.getPlayasListView(); if (hot) { onCargarListadoHotspots(); } else { this.onCargarListadoPlayas(); } bind(); panel.setWidget(playasListView.asWidget()); } public PlayasListActivity(Place place, ClientFactory clientFactory, boolean hot) { this.clientFactory = clientFactory; this.hot = hot; } /** * Le pasa a la vista un objeto Presenter */ public void bind() { playasListView.setPresenter(this); } public void goTo(Place place) { clientFactory.getPlaceController().goTo(place); } /** * Metodo encargado de comunicarse con el servidor para obtener el listado de playas a mostrar. */ public void onCargarListadoPlayas() { eventBus.fireEvent(new AppBusyEvent()); SpotRequest sr = swrf.spotRequest(); sr.findAllSpots().with("location").fire(new Receiver<List<SpotProxy>>() { @Override public void onSuccess(List<SpotProxy> response) { playasListView.addPlayas(response); eventBus.fireEvent(new AppFreeEvent()); } @Override public void onFailure(ServerFailure error) { System.out.println(error.getMessage()); eventBus.fireEvent(new AppFreeEvent()); } }); } @Override public void onPlayaSeleccionada(SpotProxy id) { goTo(new SpotPlace(id)); } @Override public void onCargarListadoHotspots() { eventBus.fireEvent(new AppBusyEvent()); SpotRequest sr = swrf.spotRequest(); Location l = Utilidades.DEFAULT_LOCATION; sr.findNearbyHotSpots(l.getLatitud(), l.getLongitud()).with("location") .fire(new Receiver<List<SpotProxy>>() { @Override public void onSuccess(List<SpotProxy> response) { playasListView.addPlayas(response); eventBus.fireEvent(new AppFreeEvent()); } @Override public void onFailure(ServerFailure error) { System.out.println(error.getMessage()); eventBus.fireEvent(new AppFreeEvent()); } }); } }
package cn.com.zjol.userhome.fragment; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.zjrb.core.recycleView.EmptyPageHolder; import com.zjrb.core.recycleView.HeaderRefresh; import com.zjrb.core.ui.divider.ListSpaceDivider; import java.util.List; import cn.com.zjol.biz.core.UserBiz; import cn.com.zjol.biz.core.network.compatible.APIExpandCallBack; import cn.com.zjol.biz.core.network.compatible.LoadViewHolder; import cn.com.zjol.userhome.R; import cn.com.zjol.userhome.adapter.UserWorksAdapter; import cn.com.zjol.userhome.bean.UserVideoResponse; import cn.com.zjol.userhome.callback.OnUserInfoCallback; import cn.com.zjol.userhome.network.task.UserWorksTask; import cn.com.zjol.userhome.viewmodel.UserHomeViewModel; import zjol.com.cn.player.bean.ElementsBean; /** * 用户作品 fragment * Created by wangzhen on 2019-09-05. */ public class UserWorksFragment extends Fragment implements HeaderRefresh.OnRefreshListener { private RecyclerView mRecycler; private HeaderRefresh mRefreshHeader; private UserWorksAdapter mAdapter; private Boolean mCurStatus; private String mAccountId; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user_works, container, false); initView(view); return view; } private void initView(View view) { mRecycler = view.findViewById(R.id.recycler); mRecycler.setLayoutManager(new LinearLayoutManager(getContext())); mRecycler.addItemDecoration(new ListSpaceDivider(1d, R.color.color_eeeeee, 15, true, true)); mRefreshHeader = new HeaderRefresh(mRecycler); mRefreshHeader.setOnRefreshListener(this); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initArgs(); registerViewModel(); request(true); } private void initArgs() { Bundle arguments = getArguments(); if (arguments != null) { mAccountId = arguments.getString("account_id", UserBiz.get().getAccountID()); } } private void registerViewModel() { if (getActivity() == null) return; ViewModelProviders.of(getActivity()).get(UserHomeViewModel.class).getWorkLiveData().observe(getActivity(), new Observer<Boolean>() { @Override public void onChanged(@Nullable Boolean value) { if (mCurStatus != value) { mCurStatus = value; mRefreshHeader.setCanrfresh(mCurStatus == null ? false : mCurStatus); } } }); } private void request(boolean showLoading) { new UserWorksTask(new APIExpandCallBack<UserVideoResponse.DataBean>() { @Override public void onSuccess(UserVideoResponse.DataBean data) { if (data != null && data.elements != null) { bindData(data.elements); if (getActivity() instanceof OnUserInfoCallback) { ((OnUserInfoCallback) getActivity()).updateUserInfo(data); } } } @Override public void onAfter() { if (mRefreshHeader != null) { mRefreshHeader.setRefreshing(false); } } }).setShortestTime(showLoading ? 0 : 1000) .bindLoadViewHolder(showLoading ? new LoadViewHolder(mRecycler, null) : null) .setTag(mRecycler).exe(mAccountId); } private void bindData(List<ElementsBean> data) { mAdapter = new UserWorksAdapter(mRecycler, data); mAdapter.bindAccountId(mAccountId); mAdapter.setEmptyView(new EmptyPageHolder(mRecycler, EmptyPageHolder.ArgsBuilder .newBuilder().content("暂无作品") .resId(R.mipmap.ic_no_video_icon)).getItemView()); mAdapter.setHeaderRefresh(mRefreshHeader.getItemView()); mRecycler.setAdapter(mAdapter); } @Override public void onRefresh() { request(false); } @Override public void onDestroyView() { super.onDestroyView(); if (mAdapter != null) { mAdapter.unregister(); } } }
package com.elvis.domain; import java.util.Date; public class Reservation { private String id; private String roomid; private String userid; private Date createtime; private Date checkintime; private Date checkouttime; private String finalcost; private String roomprice; public String getRoomprice() { return roomprice; } public void setRoomprice(String roomprice) { this.roomprice = roomprice; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRoomid() { return roomid; } public void setRoomid(String roomid) { this.roomid = roomid; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public Date getCheckintime() { return checkintime; } public void setCheckintime(Date checkintime) { this.checkintime = checkintime; } public Date getCheckouttime() { return checkouttime; } public void setCheckouttime(Date checkouttime) { this.checkouttime = checkouttime; } public String getFinalcost() { return finalcost; } public void setFinalcost(String finalcost) { this.finalcost = finalcost; } }
import java.io.File; import java.util.Scanner; class Print { public static void main(String[] args) throws Exception { File file = new File("C:\\Users\\hp\\Desktop\\abc.txt"); Scanner sc = new Scanner(file); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } }
/* * Copyright 2019 Adrian Reimer * * 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.mygdx.camera; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Sprite; import com.mygdx.model.Knight; /** * Orthographic Camera that is focusing on the {@link Knight}. * @author Adrian Reimer * */ public class Camera extends OrthographicCamera{ private OrthographicCamera orthographicCamera; /** * Camera constructor. */ public Camera() { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); orthographicCamera = new OrthographicCamera(w,h); } /** * Updates the camera and focuses on the {@link Knight}. * @param knightSprite | {@link Sprite} of the {@link Knight}. * @return {@link OrthographicCamera}. */ public OrthographicCamera updateCamera (Sprite knightSprite) { orthographicCamera.update(); orthographicCamera.position.x = knightSprite.getOriginX() + knightSprite.getX() ; orthographicCamera.position.y = knightSprite.getOriginY() + knightSprite.getY(); return orthographicCamera; } /** * resizes the camera. * @param width | width of the Screen. * @param height | height of the Screen. */ public void resize(int width, int height) { orthographicCamera = new OrthographicCamera(width,height); } /** * camera getter. * @return {@link OrthographicCamera}. */ public OrthographicCamera getCamera() { return orthographicCamera; } }
package com.selfridges.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.selfridges.util.Constants; public class HomePage { private WebDriver driver; public HomePage(WebDriver dr){ driver=dr; } public String GetHomePageUrl(){ return driver.getCurrentUrl(); } }
package com.ververica.platform.entities; import java.lang.reflect.Type; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.flink.api.common.typeinfo.TypeInfo; import org.apache.flink.api.common.typeinfo.TypeInfoFactory; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeinfo.Types; @Data @NoArgsConstructor @AllArgsConstructor @Builder @TypeInfo(PullRequest.CommitTypeInfoFactory.class) public class PullRequest { private int number; private String state; private String title; private String creator; private String creatorEmail; private LocalDateTime createdAt; private LocalDateTime updatedAt; private LocalDateTime closedAt; private LocalDateTime mergedAt; private boolean isMerged; private String mergedBy; private String mergedByEmail; private int commentsCount; private int reviewCommentCount; private int commitCount; private FileChanged[] filesChanged; private int linesAdded; private int linesRemoved; public static class CommitTypeInfoFactory extends TypeInfoFactory<PullRequest> { @Override public TypeInformation<PullRequest> createTypeInfo( Type t, Map<String, TypeInformation<?>> genericParameters) { Map<String, TypeInformation<?>> fields = new HashMap<String, TypeInformation<?>>() { { put("number", Types.INT); put("state", Types.STRING); put("title", Types.STRING); put("creator", Types.STRING); put("creatorEmail", Types.STRING); put("createdAt", Types.LOCAL_DATE_TIME); put("updatedAt", Types.LOCAL_DATE_TIME); put("closedAt", Types.LOCAL_DATE_TIME); put("mergedAt", Types.LOCAL_DATE_TIME); put("isMerged", Types.BOOLEAN); put("mergedBy", Types.STRING); put("mergedByEmail", Types.STRING); put("commentsCount", Types.INT); put("reviewCommentCount", Types.INT); put("commitCount", Types.INT); put("filesChanged", Types.OBJECT_ARRAY(Types.POJO(FileChanged.class))); put("linesAdded", Types.INT); put("linesRemoved", Types.INT); } }; return Types.POJO(PullRequest.class, fields); } } }
/** * ReservationInfoPriceServiceImpl.java $version 2018. 8. 14. * * Copyright 2018 NAVER Corp. All rights Reserved. * NAVER PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.nts.pjt3.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nts.pjt3.dao.ReservationInfoPriceDao; import com.nts.pjt3.dto.ReservationInfoPrice; import com.nts.pjt3.service.ReservationInfoPriceService; /** * @author Seok Jeongeum * */ @Service public class ReservationInfoPriceServiceImpl implements ReservationInfoPriceService { @Autowired private ReservationInfoPriceDao reservationInfoPriceDao; @Override public List<ReservationInfoPrice> getReservationInfoPrices(int id) { return reservationInfoPriceDao.selectReservationInfoPrices(id); } @Override public void addReservationInfoPrice(List<ReservationInfoPrice> prices) { reservationInfoPriceDao.insertReservationInfoPrices(prices); } }
package com.netflix.ndbench.plugins.janusgraph.configs.cql; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; /** * Specific configs for JanusGraph's CQL backend * @author pencal */ @Configuration(prefix = "ndbench.config.janusgraph.storage.cql") public interface ICQLConfig { @DefaultValue("ndbench_cql") String getKeyspace(); @DefaultValue("na") String getClusterName(); }
package com.myprojects.snake; import javax.swing.*; import java.awt.*; public class Game extends JFrame { public static void main(String[] args) { EventQueue.invokeLater(() -> { var gameFrame = new GameFrame(); gameFrame.setVisible(true); }); } }
package ive.dsa.solitaire; import ive.dsa.linklist.LinkedList; /** * It is an interface for tripleCut. * * @author POON Ngai Kuen (180091780) * @version 1.0 */ public interface InterTripleCut { void tripleCut(); }
package Manufacturing.ProductLine.AbstractCanFactory; import Manufacturing.CanEntity.Can; /** * 罐头抽象工厂 * 抽象工厂模式、单例模式 * @author 汪明杰 */ public abstract class AbstractCanFactory { /** * 创建大罐头 * @return Can 罐头 */ public abstract Can createBigCan(String type); /** * 创建小罐头 * @return Can 罐头 */ public abstract Can createSmallCan(String type); }
package stereo_camera_examples; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import boofcv.abst.feature.detect.interest.ConfigFastHessian; import boofcv.abst.feature.detect.interest.InterestPointDetector; import boofcv.alg.distort.PixelToNormalized_F64; import boofcv.core.image.ConvertBufferedImage; import boofcv.factory.feature.detect.interest.FactoryInterestPoint; import boofcv.gui.feature.FancyInterestPointRender; import boofcv.gui.image.ShowImages; import boofcv.io.image.UtilImageIO; import boofcv.struct.BoofDefaults; import boofcv.struct.distort.PointTransform_F64; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageSingleBand; import georegression.struct.point.Point2D_F64; public class ExampleInterestPoint { public static <T extends ImageSingleBand> void detect(BufferedImage image, Class<T> imageType) { T input = ConvertBufferedImage.convertFromSingle(image, null, imageType); // Create a Fast Hessian detector from the SURF paper. // Other detectors can be used in this example too. InterestPointDetector<T> detector = FactoryInterestPoint .fastHessian(new ConfigFastHessian(10, 2, 100, 2, 9, 3, 4)); // find interest points in the image detector.detect(input); // Show the features displayResults(image, detector); } @SuppressWarnings("deprecation") private static <T extends ImageSingleBand> void displayResults(BufferedImage image, InterestPointDetector<T> detector) { Graphics2D g2 = image.createGraphics(); FancyInterestPointRender render = new FancyInterestPointRender(); ArrayList<Point2D_F64> interestingPoints = new ArrayList<>(); for (int i = 0; i < detector.getNumberOfFeatures(); i++) { Point2D_F64 pt = detector.getLocation(i); // note how it checks the capabilities of the detector if (detector.hasScale()) { double scale = detector.getScale(i); int radius = (int) (scale * BoofDefaults.SCALE_SPACE_CANONICAL_RADIUS); render.addCircle((int) pt.x, (int) pt.y, radius); interestingPoints.add(pt); } else { render.addPoint((int) pt.x, (int) pt.y); } } // make the circle's thicker g2.setStroke(new BasicStroke(3)); // just draw the features onto the input image render.draw(g2); ShowImages.showWindow(image, "Detected Features"); // System.out.println(interestingPoints); Point2D_F64 normalizedPoint = new Point2D_F64(); PointTransform_F64 foo = new PixelToNormalized_F64(); //Ennek kell 1 pont es visszaadja a normalizalt koordinatajat az Intrinsic? parameterek alapjan foo.compute((float) interestingPoints.get(0).x, (float) interestingPoints.get(0).y, normalizedPoint); System.out.println(normalizedPoint); } public static void main(String args[]) { BufferedImage image = UtilImageIO.loadImage("src/main/img/stereo/testImgs/leftTest5.jpg"); detect(image, ImageFloat32.class); } }
package demo; // 假设你是一位很有爱的幼儿园老师,想要给幼儿园的小朋友们一些小糖果。但是,每个孩子最多只能给一块糖果。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的糖果的最小尺寸;并且每块糖果 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个糖果 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 // 注意: // 你可以假设胃口值为正。 // 一个小朋友最多只能拥有一块糖果。 import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class 分糖果 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] ch1 = str.split(" "); String str2 = sc.nextLine(); String[] ch2 = str2.split(" "); int[] kids = new int[ch1.length]; int[] sugs = new int[ch2.length]; for (int i = 0; i < ch1.length; i++) { kids[i] = Integer.parseInt(ch1[i]); } for (int i = 0; i < ch2.length; i++) { sugs[i] = Integer.parseInt(ch2[i]); } // System.out.println(Arrays.toString(kids)); // System.out.println(Arrays.toString(sugs)); Arrays.sort(kids); Arrays.sort(sugs); int i = 0; int j =0; int len1 = kids.length; int len2 = sugs.length; int count = 0; while(i<len1 && j<len2 ){ if(sugs[j] >= kids[i]){ j++;i++;count++; }else { j++; } } System.out.println(count); } }
package aufgabe01; import java.util.Scanner; public class Auf03 { public static void main(String[] args) { // Scanner scan = new Scanner(System.in); System.out.println("lütfen gün giriniz"); String day = scan.nextLine(); if(day.equalsIgnoreCase("cuma") ) { //egualsIgnoreCase() büyük kücük harf dikkate almaz System.out.println("Müslümanlar icin kutsal gün"); }else if(day.equalsIgnoreCase("cumartesi") ) { System.out.println("Yahudiler icin kutsal gün") ; }else if(day.equalsIgnoreCase("pazar") ) { System.out.println("Hiristiyanlar icin kutsal gün"); }else { System.out.println("Bu gün kutsal bir gün degildir"); } scan.close(); } }
/* * created 02.08.2005 by sell * * $Id: Messages.java 90 2006-01-06 19:11:33Z csell $ */ package com.byterefinery.rmbench.database.mysql; import org.eclipse.osgi.util.NLS; /** * translatable strings for dialogs * * @author sell */ public class Messages extends com.byterefinery.rmbench.database.sql99.Messages { private static final String BUNDLE_NAME = "com.byterefinery.rmbench.database.mysql.Messages"; //$NON-NLS-1$ static { NLS.initializeMessages(BUNDLE_NAME, Messages.class); } public static String MySQLWizard_tableType; public static String MySQLEnumFactory_DialogTitle; public static String MySQLSetFactory_DialogTitle; public static String MySQLIntegerDataType_NumberFormatExceptionText; public static String IntegerFlagDialog_AUTO_INCREMENT; public static String IntegerFlagDialog_ZEROFILL; public static String IntegerFlagDialog_UNSIGNED; public static String IntegerFlagDialog_Title; }
package fr.lteconsulting.formations.server.dao; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import fr.lteconsulting.formations.model.Collaborateur; @Stateless public class CollaborateursDao { @PersistenceContext( name = "formations" ) EntityManager em; private BaseDao baseDao = new BaseDao(); public List<Collaborateur> getAll() { return baseDao.getAll( em, Collaborateur.class ); } public Collaborateur getById( int id ) { return baseDao.getById( em, Collaborateur.class, id ); } public Collaborateur createOrUpdate( Collaborateur record ) { return baseDao.createOrUpdate( em, Collaborateur.class, record ); } public void delete( int id ) { baseDao.delete( em, Collaborateur.class, id ); } }
package lab4Zad1; import java.util.Scanner; public class Main { public static void main(String[] args) { CaesarCipher.encrypt("TOY"); CaesarCipher.decrypt("WRB"); Scanner input = new Scanner(System.in); int choice; while (true) { do { System.out.print("Pick 1 for encryption, " + "2 for decryption or 3 for exit: "); choice = input.nextInt(); } while (choice != 1 && choice != 2 && choice != 3); /* if (choice == 1) { System.out.print("Enter word to encrypt: "); String wordToEncrypt = input.next().toUpperCase(); CaesarCipher.encrypt(wordToEncrypt); } else if (choice == 2) { System.out.print("\nEnter word to decrypt: "); String wordToDecrypt = input.next().toUpperCase(); CaesarCipher.decrypt(wordToDecrypt); } else System.exit(0); */ switch (choice){ case 1: System.out.print("Enter word to encrypt: "); String wordToEncrypt = input.next().toUpperCase(); CaesarCipher.encrypt(wordToEncrypt); break; case 2: System.out.print("\nEnter word to decrypt: "); String wordToDecrypt = input.next().toUpperCase(); CaesarCipher.decrypt(wordToDecrypt); break; case 3: System.exit(0); } } } }
package mm; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Getter @Setter public class ShoppingBasket { Map<Book, Integer> basket = new HashMap<>(); /** * @param book - book to be added * Method that adds a book to the shopping basked with default quantity=1 and if the book * already exists it just adds a quantity to it */ public void addToBasket(Book book) { basket.put(book, basket.getOrDefault(book, 0) + 1); } /** * @param book - selected book * @param quantity - new quantity value * Method that changes the quantity of given book */ public void changeQuantity(Book book, int quantity) { basket.replace(book, quantity); } /** * @return list of all books in the basket */ public List<Book> returnAllBooksInBasket() { List<Book> booksInBasket = new ArrayList<>(); booksInBasket.addAll(basket.keySet()); return booksInBasket; } /*** * * @return total amount of all books in the basket */ public double returnTotalAmount() { double totalAmount = 0; for (Book book : basket.keySet()) { //calculating the total amount based on book price * quantity totalAmount = totalAmount + (book.getBookPrice() * basket.get(book)); } return totalAmount; } /** * Method prints books and quantity in the basket */ public void printBooksAndQuantityInBasket() { System.out.println("Books in basket:"); for (Book book : basket.keySet()) { String bookName = book.getName(); String quantity = basket.get(book).toString(); System.out.println("Book Name:" + bookName + " " + "|" + " " + "Quantity:" + quantity); } } }
package com.solomon.domain; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; /** * Created by xuehaipeng on 2017/8/2. */ public class QuestionForPost { private Long id; private String title; // 标题 private String keyword; // 关键词 private Long menuId; // 最低一级栏目的id private Long authorId; // 作者id private Integer weight; // 权重 private Integer status; // 状态 private Integer score; // 问答分值 private Date createdTime; private Date updatedTime; private Date publishedTime; // 发布日期 private String question; // 问题 private String answer; // 答案 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public Long getMenuId() { return menuId; } public void setMenuId(Long menuId) { this.menuId = menuId; } public Long getAuthorId() { return authorId; } public void setAuthorId(Long authorId) { this.authorId = authorId; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public Date getUpdatedTime() { return updatedTime; } public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } public Date getPublishedTime() { return publishedTime; } public void setPublishedTime(Date publishedTime) { this.publishedTime = publishedTime; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @Override public String toString() { return "QuestionForPost{" + "id=" + id + ", title='" + title + '\'' + ", keyword='" + keyword + '\'' + ", menuId=" + menuId + ", authorId=" + authorId + ", weight=" + weight + ", status=" + status + ", score=" + score + ", createdTime=" + createdTime + ", updatedTime=" + updatedTime + ", publishedTime=" + publishedTime + ", question='" + question + '\'' + ", answer='" + answer + '\'' + "} "; } }
package com.tencent.mm.plugin.ext.provider; import com.tencent.mm.sdk.platformtools.al.a; class ExtControlProviderSNS$1 implements a { ExtControlProviderSNS$1() { } public final boolean vD() { ExtControlProviderSNS.Ju(); return false; } }
package org.newdawn.slick.gui; import org.lwjgl.Sys; import org.newdawn.slick.Color; import org.newdawn.slick.Font; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Rectangle; public class TextField extends AbstractComponent { private static final int INITIAL_KEY_REPEAT_INTERVAL = 400; private static final int KEY_REPEAT_INTERVAL = 50; private int width; private int height; protected int x; protected int y; private int maxCharacter = 10000; private String value = ""; private Font font; private Color border = Color.white; private Color text = Color.white; private Color background = new Color(0.0F, 0.0F, 0.0F, 0.5F); private int cursorPos; private boolean visibleCursor = true; private int lastKey = -1; private char lastChar = Character.MIN_VALUE; private long repeatTimer; private String oldText; private int oldCursorPos; private boolean consume = true; public TextField(GUIContext container, Font font, int x, int y, int width, int height, ComponentListener listener) { this(container, font, x, y, width, height); addListener(listener); } public TextField(GUIContext container, Font font, int x, int y, int width, int height) { super(container); this.font = font; setLocation(x, y); this.width = width; this.height = height; } public void setConsumeEvents(boolean consume) { this.consume = consume; } public void deactivate() { setFocus(false); } public void setLocation(int x, int y) { this.x = x; this.y = y; } public int getX() { return this.x; } public int getY() { return this.y; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public void setBackgroundColor(Color color) { this.background = color; } public void setBorderColor(Color color) { this.border = color; } public void setTextColor(Color color) { this.text = color; } public void render(GUIContext container, Graphics g) { if (this.lastKey != -1) if (this.input.isKeyDown(this.lastKey)) { if (this.repeatTimer < System.currentTimeMillis()) { this.repeatTimer = System.currentTimeMillis() + 50L; keyPressed(this.lastKey, this.lastChar); } } else { this.lastKey = -1; } Rectangle oldClip = g.getClip(); g.setWorldClip(this.x, this.y, this.width, this.height); Color clr = g.getColor(); if (this.background != null) { g.setColor(this.background.multiply(clr)); g.fillRect(this.x, this.y, this.width, this.height); } g.setColor(this.text.multiply(clr)); Font temp = g.getFont(); int cpos = this.font.getWidth(this.value.substring(0, this.cursorPos)); int tx = 0; if (cpos > this.width) tx = this.width - cpos - this.font.getWidth("_"); g.translate((tx + 2), 0.0F); g.setFont(this.font); g.drawString(this.value, (this.x + 1), (this.y + 1)); if (hasFocus() && this.visibleCursor) g.drawString("_", (this.x + 1 + cpos + 2), (this.y + 1)); g.translate((-tx - 2), 0.0F); if (this.border != null) { g.setColor(this.border.multiply(clr)); g.drawRect(this.x, this.y, this.width, this.height); } g.setColor(clr); g.setFont(temp); g.clearWorldClip(); g.setClip(oldClip); } public String getText() { return this.value; } public void setText(String value) { this.value = value; if (this.cursorPos > value.length()) this.cursorPos = value.length(); } public void setCursorPos(int pos) { this.cursorPos = pos; if (this.cursorPos > this.value.length()) this.cursorPos = this.value.length(); } public void setCursorVisible(boolean visibleCursor) { this.visibleCursor = visibleCursor; } public void setMaxLength(int length) { this.maxCharacter = length; if (this.value.length() > this.maxCharacter) this.value = this.value.substring(0, this.maxCharacter); } protected void doPaste(String text) { recordOldPosition(); for (int i = 0; i < text.length(); i++) keyPressed(-1, text.charAt(i)); } protected void recordOldPosition() { this.oldText = getText(); this.oldCursorPos = this.cursorPos; } protected void doUndo(int oldCursorPos, String oldText) { if (oldText != null) { setText(oldText); setCursorPos(oldCursorPos); } } public void keyPressed(int key, char c) { if (hasFocus()) { if (key != -1) { if (key == 47 && ( this.input.isKeyDown(29) || this.input.isKeyDown(157))) { String text = Sys.getClipboard(); if (text != null) doPaste(text); return; } if (key == 44 && ( this.input.isKeyDown(29) || this.input.isKeyDown(157))) { if (this.oldText != null) doUndo(this.oldCursorPos, this.oldText); return; } if (this.input.isKeyDown(29) || this.input.isKeyDown(157)) return; if (this.input.isKeyDown(56) || this.input.isKeyDown(184)) return; } if (this.lastKey != key) { this.lastKey = key; this.repeatTimer = System.currentTimeMillis() + 400L; } else { this.repeatTimer = System.currentTimeMillis() + 50L; } this.lastChar = c; if (key == 203) { if (this.cursorPos > 0) this.cursorPos--; if (this.consume) this.container.getInput().consumeEvent(); } else if (key == 205) { if (this.cursorPos < this.value.length()) this.cursorPos++; if (this.consume) this.container.getInput().consumeEvent(); } else if (key == 14) { if (this.cursorPos > 0 && this.value.length() > 0) { if (this.cursorPos < this.value.length()) { this.value = String.valueOf(this.value.substring(0, this.cursorPos - 1)) + this.value.substring(this.cursorPos); } else { this.value = this.value.substring(0, this.cursorPos - 1); } this.cursorPos--; } if (this.consume) this.container.getInput().consumeEvent(); } else if (key == 211) { if (this.value.length() > this.cursorPos) this.value = String.valueOf(this.value.substring(0, this.cursorPos)) + this.value.substring(this.cursorPos + 1); if (this.consume) this.container.getInput().consumeEvent(); } else if (c < '' && c > '\037' && this.value.length() < this.maxCharacter) { if (this.cursorPos < this.value.length()) { this.value = String.valueOf(this.value.substring(0, this.cursorPos)) + c + this.value.substring(this.cursorPos); } else { this.value = String.valueOf(this.value.substring(0, this.cursorPos)) + c; } this.cursorPos++; if (this.consume) this.container.getInput().consumeEvent(); } else if (key == 28) { notifyListeners(); if (this.consume) this.container.getInput().consumeEvent(); } } } public void setFocus(boolean focus) { this.lastKey = -1; super.setFocus(focus); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\gui\TextField.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package A.p5; /** * @author Deep-Feeling-1999 * @create 2020/10/10 */ public interface IShape { int surfaceArea(); int volume(); String getName(); }
package com.example.deverajan.androidexcercise; import android.content.Context; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.json.JSONObject; import adapter.ListAdapter; import model.ListModel; import utils.Utils; public class ListActivity extends AppCompatActivity { RecyclerView list; Toolbar toolbar; ListAdapter listAdapter; Context context = ListActivity.this; SwipeRefreshLayout swipeRefreshLayout; private static final int PHONE_PORTRAIT_COLUMNS = 1; private static final int PHONE_LANDSCAPE_COLUMNS = 2; int mCardsColumns; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); init(); onclick(); getListdata(); } private void onclick() { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getListdata(); } }); } //get the data from server using volly library private void getListdata() { final Boolean online = Utils.isOnline((ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE)); if (online) { JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, getResources().getString(R.string.list_api), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { parseJSON(response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("Error: " + error.getMessage()); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, String.valueOf(jsonObjReq)); } else { Toast.makeText(getApplicationContext(),"No internet connection!",Toast.LENGTH_SHORT).show(); if (swipeRefreshLayout != null ) { swipeRefreshLayout.setRefreshing(false); } } } //parse the json object using GSON library private void parseJSON(String response) { if (swipeRefreshLayout != null ) { swipeRefreshLayout.setRefreshing(false); } Gson gson = new GsonBuilder().create(); ListModel listModel = gson.fromJson(response, ListModel.class); updateUI(listModel); } //update the list private void updateUI(ListModel listModel) { setSupportActionBar(toolbar); getSupportActionBar().setTitle(listModel.getTitle()); if (Utils.isPortrait(context)) { mCardsColumns = PHONE_PORTRAIT_COLUMNS; } else { mCardsColumns = PHONE_LANDSCAPE_COLUMNS; } if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } else { listAdapter = new ListAdapter(listModel.getListrows(), context); list.setLayoutManager(new StaggeredGridLayoutManager(mCardsColumns, StaggeredGridLayoutManager.VERTICAL)); list.setItemAnimator(new DefaultItemAnimator()); list.setAdapter(listAdapter); } } private void init() { list = (RecyclerView) findViewById(R.id.list); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipeRefreshLayout); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (Utils.isPortrait(context)) { mCardsColumns = PHONE_PORTRAIT_COLUMNS; } else { mCardsColumns = PHONE_LANDSCAPE_COLUMNS; } list.setLayoutManager(new StaggeredGridLayoutManager(mCardsColumns, StaggeredGridLayoutManager.VERTICAL)); list.scrollToPosition(0); } }
package br.org.funcate.glue.model.toolbar; /** * This Enumeration represents all tools of GLUE application. * * @author Moraes, Emerson Leite. * */ public enum ToolEnum { TERRALIB("TerraLib"), GOOGLE("Google"), WMS("WMS"), PAINT("Paint"), REBUILD("Rebuild"), ZOOMIN("ZoomIn"), ZOOMOUT("ZoomOut"), ZOOMAREA( "ZoomArea"), PAN("Pan"), DISTANCE("Distance"), UNDO("Undo"), REDO("Redo"), PHOTOLOCATION("PhotoLocation"), INFO("Info"), LINKS( "Links"), ATRIBS("Atributes"), CLEAN("Clean"), PDF("Pdf"), EXPORT("Export"), HELPONLINE("HelpOnline"); /** * Tool's name. */ private String name; /** * ToolEnum's constructor. * * @param name */ private ToolEnum(String name) { this.name = name; } /** * Override of Object's toString method. */ public String toString() { return name; } }
package zystudio.cases.javabase; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import zystudio.mylib.utils.LogUtil; /** * * Timer与TimerTask虽然刚会用,但是文档上已经推荐用ScheduledThreadPoolExecutor了 * */ public class CaseTimerAndTimerTask { private static CaseTimerAndTimerTask sCase; public static CaseTimerAndTimerTask intance() { if (sCase == null) { sCase = new CaseTimerAndTimerTask(); } return sCase; } private CaseTimerAndTimerTask() { } public void work() { try { TimerTask mTimerTask = new MyTimerTask(); Timer timer = new Timer(true); // timer.scheduleAtFixedRate(mTimerTask, 0, 10 * 1000); /** * 第三个参数的意思是两次TimerTask begin的间隔,但是比如底下的task,如果sleep超过了这个7000,那两次begin的间隔也会变长的 * 注意是两次timerTask begin的间隔,而不是上次timerTask end与上次timerTask begin的间隔, * 这个Timer不cancel的话,timerTask会一直反复下去的 */ timer.schedule(mTimerTask, 0, 7000); LogUtil.log("TimerTask launch:Thread:"+Thread.currentThread().getName()+"|"+new Date()); Thread.sleep(120000); timer.cancel(); LogUtil.log("TimerTask canceled"); Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } } private static class MyTimerTask extends TimerTask { @Override public void run() { try { LogUtil.log("TimerTask begin at:" + new Date()+"|Thread:"+Thread.currentThread().getName()+","+Thread.currentThread().getId()); //可以看到这个2w比上边的10*1000时间更长,于是上边的10*1000的rate就不行了,得按2w的这个rate走 //当然如果去掉这个2w的话,就是按10000的频率固定拉起这个线程的 Thread.sleep(2000); LogUtil.log("TimerTask last at:" + new Date()); } catch (Exception e) { e.printStackTrace(); } } } }
package com.ryx.bank.http.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import com.ryx.bank.http.others.HttpChannelInitializer; /** * @author Leo 2014年11月10日下午2:45:08 */ public class HttpsServer { private int PORT = 8080; HttpsServer() { } HttpsServer(int port) { this.PORT = port; } public void run() { EventLoopGroup workerGroup = new NioEventLoopGroup(20); EventLoopGroup bossGroup = new NioEventLoopGroup(20); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // use direct buffers bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new HttpChannelInitializer(false)) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ; ChannelFuture f; try { System.err.println("Open your web browser and navigate to " + "http" + "://127.0.0.1:" + PORT + '/'); // Bind and start to accept incoming connections. f = bootstrap.bind(PORT).sync(); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to // gracefully // shut down your server. f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } }
package lp2.testes; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import lp2.lerDados.Usuario; import org.junit.Before; import org.junit.Test; /** * * @author Flavia Gangorra<br> * Irvile Rodrigues Lavor<br> * Jordao Ezequiel Serafim de Araujo<br> * */ public class UsuarioTest { Usuario user1,user2; List<Integer> opinioesUser1 = new ArrayList<Integer>(); List<Integer> opinioesUser2 = new ArrayList<Integer>(); @Before public void criaUsuarios() throws Exception{ opinioesUser1.add(2); opinioesUser2.add(1); user1 = new Usuario("Reinaldo",opinioesUser1); user2 = new Usuario("Livia",opinioesUser2); } @Test public final void testUsuario() { List<Integer> auxUser1 = new ArrayList<Integer>(opinioesUser1); List<Integer> auxUser2 = new ArrayList<Integer>(opinioesUser2); Assert.assertEquals("Erro no construtor", "Reinaldo", user1.getNome()); Assert.assertEquals("Erro no construtor", "Livia", user2.getNome()); Assert.assertEquals("Erro no construtor",auxUser1 , user1.getOpinioes()); Assert.assertEquals("Erro no construtor",auxUser2 , user2.getOpinioes()); } @Test public void testaConstrutor(){ try { user1 = new Usuario(null, opinioesUser1); Assert.fail("Devia ter dado erro"); } catch (Exception e) { Assert.assertEquals("Erro no contrutor de usuario", "Nome nulo/vazio.", e.getMessage()); } try { user1 = new Usuario("nome", null); Assert.fail("Devia ter dado erro"); } catch (Exception e) { Assert.assertEquals("Erro no contrutor de usuario", "Lista de Opinioes nula/vazia.", e.getMessage()); } } @Test public final void testSetNome() throws Exception { try{ user1.setNome(null); Assert.fail("Esperava erro"); }catch(Exception ex){ Assert.assertEquals("Nome nulo/vazio.", ex.getMessage()); } try{ user1.setNome(""); Assert.fail("Esperava erro"); }catch(Exception ex){ Assert.assertEquals("Nome nulo/vazio.", ex.getMessage()); } user1.setNome("Nazareno"); user2.setNome("Raquel"); Assert.assertEquals("Erro no metodo serOpinioes","Nazareno", user1.getNome()); Assert.assertEquals("Erro no metodo serOpinioes","Raquel", user2.getNome()); } @Test public void testaSetOpinioes() throws Exception{ try{ user1.setOpinioes(null); Assert.fail("Esperava erro"); }catch(Exception ex){ Assert.assertEquals("Lista de Opinioes nula/vazia.", ex.getMessage()); } try{ opinioesUser1.clear(); user1.setOpinioes(opinioesUser1); Assert.fail("Esperava erro"); }catch(Exception ex){ Assert.assertEquals("Lista de Opinioes nula/vazia.", ex.getMessage()); } List<Integer> auxUser1 = new ArrayList<Integer>(); auxUser1.add(5); auxUser1.add(2); user1.setOpinioes(auxUser1); //testa se setou o user1 para nova lista. Assert.assertEquals("Erro no metodo setOpinioes", auxUser1, user1.getOpinioes()); } }
package Validaciones; import javax.swing.*; public class ValidacionesUsuarios { public static boolean validaUsuarios(String nom, JTextField text){ if (nom.equals("") || !nom.matches("^[A-Za-zñÑ0-9]{5,10}$")) { pintarRojo(text); return true; }else{ text.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 255, 0))); return false; } } public static boolean validaContrasena(String pass, JTextField text){ if (pass.equals("") || !pass.matches("^[A-Za-zñÑ0-9\\W]{5,10}$")) { pintarRojo(text); return true; } else if(pass.matches("^\\s+$")){ pintarRojo(text); return true; } else{ text.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 255, 0))); return false; } } private static void pintarRojo(JTextField txt) { txt.requestFocus(); txt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0))); txt.setSelectionStart(0); txt.setSelectionEnd(txt.getText().length()); } }
package com.example.sleeplearning; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.wifi.WifiManager; import android.os.PowerManager; import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.annotation.RequiresPermission; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Chronometer; import android.widget.TextView; import android.widget.Toast; import com.example.sleeplearning.model.UserData; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Source; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.TimeZone; public class Session extends AppCompatActivity { private TextView endSessionButton, restartSessionButton; private Chronometer timer; public boolean running; public long pauseOffset; private String timerLimit; private int counter_offset = 1; private MediaPlayer silen; private MediaPlayer oceanMediaPlayer = new MediaPlayer(); private int i = 0; private int counter = 0; private int x = 0; private String offset; private boolean minimize = true; private ArrayList<Date> timestamps; PowerManager.WakeLock pwakelock; private boolean paused = false; HashMap<String, Object> responses = new HashMap<>(); String url = "https://storage.googleapis.com/sleep-learning-app/audio-files/"; // your URL here MediaPlayer mediaPlayer = new MediaPlayer(); String userEmail,subjectId; FirebaseFirestore db ; private String logs = ""; ProgressDialog pd; // audio links String ocean = "https://storage.googleapis.com/sleep-learning-app/audio-files/ocean.mp3"; String silence = "https://storage.googleapis.com/sleep-learning-app/audio-files/20-minutes-of-silence.m4a"; String fullsilence = "https://storage.googleapis.com/sleep-learning-app/audio-files/40-minutes-of-silence.m4a"; String five_minutes_silence = "https://storage.googleapis.com/sleep-learning-app/audio-files/5-minutes-of-silence.m4a"; String madarinsAudios []={ "mandarin-1.m4a", "mandarin-2.m4a" }; String arabicAudio [] ={ "arabic-1.m4a", "arabic-2.m4a", "arabic-3.m4a" }; String selectedAudioStream []; String language; private FirebaseAuth mAuth; private FirebaseUser user; private FirebaseFirestore database; WifiManager.WifiLock wifiLock; PowerManager powerManager; PowerManager.WakeLock wakeLock; WifiManager wifi; WifiManager.MulticastLock lock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_session); language = ""; offset = ""; timestamps = new ArrayList<>(); //wakelock acquire wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock"); powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); wakeLock.acquire(); wifiLock.acquire(); //get current user mAuth = FirebaseAuth.getInstance(); user = mAuth.getCurrentUser(); subjectId = ""; db = FirebaseFirestore.getInstance(); pd = new ProgressDialog(this); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); acquireLock(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = new Date(); Intent intent = getIntent(); responses = (HashMap<String, Object>)intent.getSerializableExtra("response data"); language = (String) intent.getSerializableExtra("user language"); offset = (String) intent.getSerializableExtra("offset"); Log.v("lan",language); // responses.put("timeWhenAsleep",new Date()); // save the time when the user is going to sleep if(user!=null) { pd.show(); userEmail= user.getEmail(); DocumentReference docRef = db.collection("Subjects").document(userEmail); Source source = Source.SERVER; docRef.get(source).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserData data = documentSnapshot.toObject(UserData.class); subjectId =data.getID(); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); formatter = new SimpleDateFormat("MMM dd, yyyy"); String strDate = formatter.format(date); String userResponse = "null"; //userResponse = message.getText().toString(); responses.put("timeWhenAsleep",new Date()); HashMap<String, Object> responses_to_save = new HashMap<>(); for (String key : responses.keySet()) { if (!responses.get(key).equals("NaN")) { responses_to_save.put(key,responses.get(key)); } } db.collection(subjectId).document(strDate).set(responses_to_save).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } // endSessionButton = findViewById(R.id.endSessionTxtView); restartSessionButton = findViewById(R.id.restartSessionTxtView); /*timer = findViewById(R.id.chronometer); timerLimit = "40:00"; timer.setBase(SystemClock.elapsedRealtime() - pauseOffset); timer.start(); running = true;*/ restartSessionButton.setEnabled(true); i=0; selectedAudioStream = new String[2]; if (language.equals("Arabic") || language.equals("arabic")) { selectedAudioStream = arabicAudio; } else if (language.equals("Mandarin") || language.equals("mandarin")) { selectedAudioStream = madarinsAudios; } Log.v("songs",selectedAudioStream[0]); // Log.v("songs",selectedAudioStream[1]); oceanMediaPlayer = new MediaPlayer(); oceanMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); oceanMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); silen = new MediaPlayer(); silen.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); silen.setAudioStreamType(AudioManager.STREAM_MUSIC); counter_offset = 1; final int max_counter = Integer.parseInt(offset)/5; try { HashMap<String,Object> logs = new HashMap<>(); // send logs to firebase for debugging logs.put("a",max_counter); logs.put("time a", new Date()); db.collection("logs").document(userEmail).set(logs).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); Log.v("start",Integer.toString(counter_offset)); silen.setDataSource(five_minutes_silence); silen.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } silen.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // debugging logs Log.v("start","aaa"); HashMap<String,Object> logs = new HashMap<>(); logs.put("offset",counter_offset); logs.put("timeof", new Date()); db.collection("logs").document(userEmail).update(logs); // db.collection("logs").document(userId).set(counter_offset); silen.start(); } }); silen.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { counter_offset++; Log.v("start",Integer.toString(counter_offset)); if(counter_offset <= max_counter) { if (silen.isPlaying()) silen.stop(); silen.reset(); // debugging HashMap<String,Object> logs = new HashMap<>(); logs.put("aa",counter_offset); logs.put("time aa", new Date()); db.collection("logs").document(userEmail).update(logs); Log.v("offset_current",Integer.toString(counter_offset)); if (silen == null) silen = new MediaPlayer(); try { silen.setDataSource(five_minutes_silence); silen.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } else { Log.v("offset_current","aaaa"); if (silen.isPlaying()) silen.stop(); silen.reset(); silen.release(); silen = null; // debugging HashMap<String,Object> logs = new HashMap<>(); logs.put("aaa","silence finished"); logs.put("time aaa", new Date()); db.collection("logs").document(userEmail).update(logs); Log.v("silence", "silence audio finished"); //after the silence period ends play ocean audio playOceanAudio(); } } }); //LayoutInflater layoutInflater = LayoutInflater.from(this); //final View promptView = layoutInflater.inflate(R.layout.requestfeedback_layout, null); //final AlertDialog alertD = new AlertDialog.Builder(this).create(); // Check the language of the user and assign corresponding audio stream // check if the 40 min mark was reached /* timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { long time = SystemClock.elapsedRealtime() - chronometer.getBase(); int h = (int)(time /3600000); int m = (int)(time - h*3600000)/60000; int s= (int)(time - h*3600000- m*60000)/1000 ; String hh = h < 10 ? "0"+h: h+""; String mm = m < 10 ? "0"+m: m+""; String ss = s < 10 ? "0"+s: s+""; chronometer.setText(hh+":"+mm+":"+ss); if ("05:00:00".equals(timer.getText())) { stopmusic(); } } });*/ /* timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { if("00:40".equals(timer.getText())) { stopmusic(); } } });*/ // timer.setBase(SystemClock.elapsedRealtime()); //when the user clicks the end session button endSessionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final AlertDialog.Builder builder = new AlertDialog.Builder(Session.this); builder.setMessage("Are you sure you want to end the session?"); builder.setTitle("Confirm"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { wifiLock.release(); wakeLock.release(); //audio have been stopped so the user can minimize the app and not receive a user leaving message minimize = false; // clear all the resources we used releaseLock(); if (mediaPlayer!=null) { if (mediaPlayer.isPlaying()) mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } if (oceanMediaPlayer!=null) { if (oceanMediaPlayer.isPlaying()) oceanMediaPlayer.stop(); oceanMediaPlayer.release(); oceanMediaPlayer = null; } if (silen!=null) { if (silen.isPlaying()) silen.stop(); silen.release(); silen = null; } //alertD.setView(promptView); //alertD.setCancelable(false); //alertD.show(); DateFormat dateFormats = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormats.setTimeZone(TimeZone.getTimeZone("UTC")); //responses.put("timeWhenAwake",new Date()); // save when the user wake up if(user!=null) { pd.show(); userEmail= user.getEmail(); DocumentReference docRef = db.collection("Subjects").document(userEmail); Source source = Source.SERVER; docRef.get(source).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserData data = documentSnapshot.toObject(UserData.class); subjectId =data.getID(); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); formatter = new SimpleDateFormat("MMM dd, yyyy"); String strDate = formatter.format(date); String userResponse = "null"; //userResponse = message.getText().toString(); responses.put("timeWhenAwake",new Date()); HashMap<String, Object> responses_to_save = new HashMap<>(); for (String key : responses.keySet()) { if (!responses.get(key).equals("NaN")) { responses_to_save.put(key,responses.get(key)); } } db.collection(subjectId).document(strDate).set(responses_to_save).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); Intent intent = new Intent(Session.this, FirstQuestion.class); intent.putExtra("response data", responses); startActivity(intent); finish(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } // /*responses.put("numberOfRestarts",counter); if(timestamps.size()!=0) { responses.put("timesPressedRestart", timestamps); }*/ /*Intent intent = new Intent(Session.this, FirstQuestion.class); intent.putExtra("response data", responses); startActivity(intent); finish();*/ } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); //Intent intent = new Intent(Session.this, MainActivity.class); //startActivity(intent); //finish(); AlertDialog dialog = builder.create(); dialog.show(); } }); restartSessionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.v("songs", "restart pressed"); if (mediaPlayer != null) { if (mediaPlayer.isPlaying() || oceanMediaPlayer.isPlaying()) { Log.v("songs", "restart accepted"); Toast.makeText(getApplicationContext(),"Session restarted",Toast.LENGTH_LONG).show(); counter++; timestamps.add(new Date()); // save restart timestamps and the number of restarts if(user!=null) { pd.show(); userEmail= user.getEmail(); DocumentReference docRef = db.collection("Subjects").document(userEmail); Source source = Source.SERVER; docRef.get(source).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { UserData data = documentSnapshot.toObject(UserData.class); subjectId =data.getID(); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); formatter = new SimpleDateFormat("MMM dd, yyyy"); String strDate = formatter.format(date); String userResponse = "null"; //userResponse = message.getText().toString(); responses.put("numberOfRestarts",counter); if(timestamps.size()!=0) { responses.put("timesPressedRestart", timestamps); } HashMap<String, Object> responses_to_save = new HashMap<>(); for (String key : responses.keySet()) { if (!responses.get(key).equals("NaN")) { responses_to_save.put(key,responses.get(key)); } } db.collection(subjectId).document(strDate).set(responses_to_save).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getApplicationContext(),"Check your internet connection",Toast.LENGTH_LONG).show(); } }); } // //startTimer(v); if (mediaPlayer.isPlaying()) { x = mediaPlayer.getCurrentPosition(); mediaPlayer.pause(); paused = true; try { if (silen != null) { if (silen.isPlaying()) silen.stop(); silen.reset(); } if (silen == null) silen = new MediaPlayer(); silen.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); silen.setDataSource(silence); silen.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } silen.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { silen.start(); } }); silen.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { playOceanAudio(); } }); } else if (oceanMediaPlayer.isPlaying()) { i = 0; x = 0; paused = false; oceanMediaPlayer.stop(); oceanMediaPlayer.release(); oceanMediaPlayer = null; //playOceanAudio(); try { if (silen != null) { if (silen.isPlaying()) silen.stop(); silen.reset(); } if (silen == null) silen = new MediaPlayer(); silen.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); silen.setDataSource(silence); silen.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } silen.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { silen.start(); } }); silen.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { playOceanAudio(); } }); } //mediaPlayer.release(); //mediaPlayer = null; } else { Toast.makeText(getApplicationContext(),"The session can not be restarted because no audio sounds are playing currently",Toast.LENGTH_LONG).show(); } } } }); } /* public void startTimer(View v) { timer.setBase(SystemClock.elapsedRealtime() - pauseOffset); timer.start(); running = true; } public void stopTimer(View v) { timer.setBase(SystemClock.elapsedRealtime()); pauseOffset = 0; timer.stop(); running= false; } */ // make the app run in the background so that the timer can continue to run and @Override public void onBackPressed() { //this.moveTaskToBack(true); } public void playmusic () { HashMap<String,Object> logs = new HashMap<>(); logs.put("audio","audio started"); logs.put("time audio", new Date()); db.collection("logs").document(userEmail).update(logs); // if the user pressed restart seek where the audio was at the moment and play the music from there if(paused) { paused =false; mediaPlayer.seekTo(x); mediaPlayer.start(); } else { i = 0; if (mediaPlayer == null) mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(url + selectedAudioStream[i]); Log.v("log","preparing"); mediaPlayer.prepareAsync(); // might take long! (for buffering, etc) } catch (IOException e) { e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mediaPlayer.start(); HashMap<String,Object> logs = new HashMap<>(); logs.put("audioname"+i,selectedAudioStream[i]); logs.put("time audioplayed"+i, new Date()); db.collection("logs").document(userEmail).update(logs); Log.v("log","starting"); // mediaPlayer.setLooping(true); } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (i < (selectedAudioStream.length-1)) { try { Log.v("audio","manadarin 2"); i++; mediaPlayer.stop(); mediaPlayer.reset(); if (mediaPlayer == null) mediaPlayer = new MediaPlayer(); mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setDataSource(url + selectedAudioStream[i]); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } } }); } } public void stopmusic () { if (mediaPlayer.isPlaying()) mediaPlayer.stop(); mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; if (silen.isPlaying()) silen.stop(); silen.stop(); silen.release(); silen = null; if (oceanMediaPlayer.isPlaying()) oceanMediaPlayer.stop(); oceanMediaPlayer.stop(); oceanMediaPlayer.release(); oceanMediaPlayer = null; } public void acquireLock() { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); pwakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"myapp:mywakelocktag"); pwakelock.acquire(); } public void releaseLock() { pwakelock.release(); } /*int silencePosition=0,soundPosition=0; @Override protected void onPause() { super.onPause(); if (silen!=null) { if (silen.isPlaying()) { silencePosition = silen.getCurrentPosition(); silen.pause(); } } if (mediaPlayer!=null) { if (mediaPlayer.isPlaying()) { soundPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.pause(); } } } @Override protected void onResume() { super.onResume(); if (silen!=null) { if (!silen.isPlaying() && silen.getCurrentPosition() > 1) { silen.seekTo(silen.getCurrentPosition()); silen.start(); } } if (mediaPlayer!=null) { if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 1) { mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()); mediaPlayer.start(); } } }*/ public void playOceanAudio() { restartSessionButton.setEnabled(true); Log.v("audio","ocean"); HashMap<String,Object> logs = new HashMap<>(); logs.put("ocean","started"); logs.put("time ocean", new Date()); db.collection("logs").document(userEmail).update(logs); if (oceanMediaPlayer == null) oceanMediaPlayer = new MediaPlayer(); oceanMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); oceanMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { oceanMediaPlayer.setDataSource(ocean); oceanMediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } oceanMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { Log.v("log","preparing ocean start"); oceanMediaPlayer.start(); } }); oceanMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (oceanMediaPlayer!=null) { if (oceanMediaPlayer.isPlaying()) { oceanMediaPlayer.stop(); } oceanMediaPlayer.reset(); } HashMap<String,Object> logs = new HashMap<>(); logs.put("ocean end","end"); logs.put("time ocean end", new Date()); db.collection("logs").document(userEmail).update(logs); Log.v("log","next music"); playmusic(); } }); } @Override protected void onUserLeaveHint() { if (minimize) Toast.makeText(getApplicationContext(),"App going in the background, for an uninterrupted session it is recommended to run the application and keep it in the foreground",Toast.LENGTH_LONG).show(); super.onUserLeaveHint(); wakeLock.acquire(); wifiLock.acquire(); } @Override protected void onDestroy() { super.onDestroy(); wakeLock.release(); wifiLock.release(); // lock.release(); } @Override protected void onPause() { wifiLock.acquire(); wakeLock.acquire(); /*wakeLock.acquire(); wifiLock.acquire(); oceanMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);*/ Log.v("pause","pausing"); /* final WifiManager.WifiLock wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)) .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock"); PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); final PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag"); wakeLock.acquire(); wifiLock.acquire(); silen.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); // onResume();*/ super.onPause(); } @Override protected void onResume() { //super.onResume(); Log.v("paused","pausingd"); /*oceanMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); wakeLock.acquire(); wifiLock.acquire();*/ wifiLock.acquire(); super.onResume(); } }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.business.impl.scheduler; import javax.persistence.EntityManager; import seava.ad.business.api.scheduler.IQuartzBlobTriggerService; import seava.ad.domain.impl.scheduler.QuartzBlobTrigger; import seava.j4e.business.service.entity.AbstractEntityService; /** * Repository functionality for {@link QuartzBlobTrigger} domain entity. It contains * finder methods based on unique keys as well as reference fields. * */ public class QuartzBlobTrigger_Service extends AbstractEntityService<QuartzBlobTrigger> implements IQuartzBlobTriggerService { public QuartzBlobTrigger_Service() { super(); } public QuartzBlobTrigger_Service(EntityManager em) { super(); this.setEntityManager(em); } @Override public Class<QuartzBlobTrigger> getEntityClass() { return QuartzBlobTrigger.class; } }
/* * StreamedInput.java * * Created on July 10, 2003, 8:11 PM */ package com.espendwise.manta.loader; import java.util.List; /** * Implementing Classes for dealing with binary files (excel, pdf etc). * @author deping */ public interface IInputStreamParser { /** *Gets called once for each line of text in the file. */ public abstract void parseLine(List pParsedLine) throws Exception; }
package collection.bstAVL; import tree.TreeNode; import java.util.ArrayList; import java.util.Iterator; /** * leetcode 173.Binary Search Tree Iterator * https://leetcode.com/problems/binary-search-tree-iterator/description/ * @param <T> */ public class BSTIterator<T> { private Iterator<T> itr; public BSTIterator(TreeNode<T> root) { ArrayList<T> list=new ArrayList<>(); inOrder(root,list); itr=list.iterator(); } private void inOrder(TreeNode<T> p,ArrayList<T> list){ if (p!=null){ inOrder(p.getLeft(),list); list.add(p.getVal()); inOrder(p.getRight(),list); } } /** @return whether we have a next smallest number */ public boolean hasNext() { return itr.hasNext(); } /** @return the next smallest number */ public T next() { return itr.next(); } }
package com.hesoyam.pharmacy.integration.feedback; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.hesoyam.pharmacy.feedback.dto.EmployeeComplaintCreateDTO; import com.hesoyam.pharmacy.feedback.dto.PharmacyComplaintCreateDTO; import com.hesoyam.pharmacy.user.model.User; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc class ComplaintTests { @Autowired private WebApplicationContext context; @Autowired private MockMvc mvc; private static ObjectMapper objectMapper; private static ObjectWriter objectWriter; @BeforeAll public static void initAll(){ objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); objectWriter = objectMapper.writer().withDefaultPrettyPrinter(); } @BeforeEach public void init(){ mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test @WithUserDetails (value = "hesoyampharmacy+veselin@gmail.com") void placeInvalidEmployeeComplaintTest() throws Exception { //Invalid because he doesn't have any completed appointment with specified employee. mvc.perform(post("/complaint/create-employee-complaint").contentType(MediaType.APPLICATION_JSON_VALUE).content(getInvalidEmployeeComplaintRequestJSON()).with(user(getUserDetails()))).andExpect(status().is(400)); } @Test @WithUserDetails (value = "hesoyampharmacy+veselin@gmail.com") void placeInvalidPharmacyComplaintTest() throws Exception{ //Invalid, no reserved medicine/recipe and other constraints mvc.perform(post("/complaint/create-pharmacy-complaint").contentType(MediaType.APPLICATION_JSON_VALUE).content(getInvalidPharmacyComplaintRequestJSON()).with(user(getUserDetails()))).andExpect(status().is(400)); } private User getUserDetails(){ UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext (). getAuthentication (); return (User) authentication.getPrincipal (); } private String getInvalidPharmacyComplaintRequestJSON() throws JsonProcessingException{ PharmacyComplaintCreateDTO pharmacyComplaintCreateDTO = new PharmacyComplaintCreateDTO(); pharmacyComplaintCreateDTO.setBody("Test pharmacy complaint body"); pharmacyComplaintCreateDTO.setPharmacyId(1l); return objectWriter.writeValueAsString(pharmacyComplaintCreateDTO); } private String getInvalidEmployeeComplaintRequestJSON() throws JsonProcessingException { EmployeeComplaintCreateDTO employeeComplaint = new EmployeeComplaintCreateDTO(); employeeComplaint.setBody("Test complaint body"); employeeComplaint.setEmployeeId(1l); return objectWriter.writeValueAsString(employeeComplaint); } }
import tester.Tester; // to represent an ancestor tree interface IAT { // counts the amount of people in this ancestor's trees int count(); } // to represent an unknown member of an ancestor tree class Unknown implements IAT { Unknown() { } // counts the amount of people in this unknown trees public int count() { return 0; } } // to represent a person with the person's ancestor tree class Person implements IAT { String name; IAT mom; IAT dad; Person(String name, IAT mom, IAT dad) { this.name = name; this.mom = mom; this.dad = dad; } // counts this person and every known person in his family tree public int count() { return 1 + mom.count() + dad.count(); } } class ExamplesIAT { IAT unknown = new Unknown(); IAT one = new Person("1", this.unknown, this.unknown); IAT two = new Person("1", this.one, this.unknown); IAT three = new Person("1", this.two, this.one); boolean testCount(Tester t) { return t.checkExpect(this.three.count(), 4); } }
package com.penzias.entity; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SmModular { // 程序模块编码 @Expose private Integer id; // 上级模块编码 @Expose private Integer parentId; // 名称 @Expose @SerializedName("name") private String modularName; // 功能模块地址 private String modularUrl; // 描述 private String modularDesc; // 顺序 private Integer modularOrder; // 样式或图标 private String modularStyle; // 是否显示:0-不显示,1-显示 private String modularShow; // 标识,基于样式控制 private String modularFlag; // 增删改查 private String crud; // 以下不参与映射 @Expose private boolean open; // 是否选中 @Expose private boolean checked; public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public Integer getParentId(){ return parentId; } public void setParentId(Integer parentId){ this.parentId = parentId; } public String getModularName(){ return modularName; } public void setModularName(String modularName){ this.modularName = modularName; } public String getModularUrl(){ return modularUrl; } public void setModularUrl(String modularUrl){ this.modularUrl = modularUrl; } public String getModularDesc(){ return modularDesc; } public void setModularDesc(String modularDesc){ this.modularDesc = modularDesc; } public Integer getModularOrder(){ return modularOrder; } public void setModularOrder(Integer modularOrder){ this.modularOrder = modularOrder; } public String getModularStyle(){ return modularStyle; } public void setModularStyle(String modularStyle){ this.modularStyle = modularStyle; } public String getModularShow(){ return modularShow; } public void setModularShow(String modularShow){ this.modularShow = modularShow; } public String getModularFlag(){ return modularFlag; } public void setModularFlag(String modularFlag){ this.modularFlag = modularFlag; } public String getCrud(){ return crud; } public void setCrud(String crud){ this.crud = crud; } public boolean isOpen(){ return open; } public void setOpen(boolean open){ this.open = open; } public boolean isChecked(){ return checked; } public void setChecked(boolean checked){ this.checked = checked; } }
package com.niubimq.service; import java.util.List; import com.niubimq.pojo.Producer; /** * @Description: 生产者信息管理 * @author junjin4838 * @version 1.0 */ public interface PCManageService { /** * 查询生产者信息 * @param producerSign * @return List */ public List<Producer> showProducer(String producerSign); /** * 新增生产者信息 * @param producer */ public void addProducer(Producer producer); /** * 删除生产者信息 * @param producer */ public void deleteProducer(Producer producer); /** * 修改生产者信息 * @param producer */ public void updateProducer(Producer producer); }
package enthu_l; public class e_1074 { public static void main(String[] args){ new e_1074().sayHello(); } //1 public static void sayHello(){ System.out.println("Static Hello World"); } //2 public void sayHello() { System.out.println("Hello World "); } //3 }
package com.example.dev.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.util.Pair; import android.view.View; import android.widget.Button; import com.base.adev.activity.BaseActivity; import com.example.dev.R; public class GSYVideoActivity extends BaseActivity implements View.OnClickListener { private String title; private Button mBtnOpenVideo; private Button mBtnRvPlayer; private Button mBtnRvPlayerMini; @Override protected void initContentView(Bundle bundle) { setContentView(R.layout.activity_gsy_video); } @Override protected void initView() { mBtnOpenVideo = (Button) findViewById(R.id.btn_open_video); mBtnRvPlayer = (Button) findViewById(R.id.btn_rv_player); mBtnRvPlayerMini = (Button) findViewById(R.id.btn_rv_player_mini); } @Override protected void initLogic() { mToolbar.setTitle(title); mBtnOpenVideo.setOnClickListener(this); mBtnRvPlayer.setOnClickListener(this); mBtnRvPlayerMini.setOnClickListener(this); } @Override protected void getBundleExtras(Bundle extras) { title = extras.getString("title"); } @Override public void onClick(View v) { Intent intent; ActivityOptionsCompat activityOptions; switch (v.getId()) { case R.id.btn_open_video: //直接一个页面播放的 intent = new Intent(context, GSYPlayerActivity.class); intent.putExtra(GSYPlayerActivity.TRANSITION, true); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { Pair pair = new Pair<>(mBtnOpenVideo, GSYPlayerActivity.IMG_TRANSITION); activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation( context, pair); ActivityCompat.startActivity(context, intent, activityOptions.toBundle()); } else { context.startActivity(intent); context.overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out); } break; case R.id.btn_rv_player: //普通列表播放,只支持全屏,但是不支持屏幕重力旋转,滑出后不持有 intent = new Intent(context, GSYPlayerRVDisActivity.class); intent.putExtra("title", getString(R.string.text_rv_player)); activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(context); ActivityCompat.startActivity(context, intent, activityOptions.toBundle()); break; case R.id.btn_rv_player_mini: //支持全屏重力旋转的列表播放,滑动后不会被销毁 intent = new Intent(context, GSYPlayerRVMiniActivity.class); intent.putExtra("title", getString(R.string.text_rv_player_mini)); activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(context); ActivityCompat.startActivity(context, intent, activityOptions.toBundle()); break; default: break; } } }
package com.tbt.testapi.main; public class Options { public String type = null; public String name = null; public String configPath = "config/"; public boolean debug = true; }
package tiny1.asint; import java.util.Map; public class TinyASint { public static abstract class ASTNode { private int etqi; private int etqs; public int etqi() {return etqi;} public int etqs() {return etqs;} public void setEtqi(int etqi) {this.etqi = etqi;} public void setEtqs(int etqs) {this.etqs = etqs;} } public static class StringLocalizado { private String s; private int fila; private int col; public StringLocalizado(String s, int fila, int col) { this.s = s; this.fila = fila; this.col = col; } public int fila() {return fila;} public int col() {return col;} public String toString() { return s; } public boolean equals(Object o) { return (o == this) || ( (o instanceof StringLocalizado) && (((StringLocalizado)o).s.equals(s))); } public int hashCode() { return s.hashCode(); } } public enum Type{ INT, BOOL, REAL, STRING, NULL, ERROR, OK, ARRAY, RECORD, POINTER } public enum DecType{ VAR, TYPE, PROC } public static abstract class Exp extends ASTNode{ private Tipo tipo; public Exp() {} public boolean esDesignador(){ return false; } public Dec vinculo(){ throw new UnsupportedOperationException("Vinculo unsupported."); } public void setVinculo(Dec dec){ throw new UnsupportedOperationException("Set vinculo unsupported."); } public void setTipo(Tipo tipo){this.tipo = tipo;} public Tipo getTipo(){return tipo;} public Type getType(){return tipo.type();} public abstract int prioridad(); public abstract void procesa(Procesamiento procesamiento); public abstract StringLocalizado str(); } public static abstract class ExpBin extends Exp { private Exp arg0; private Exp arg1; public Exp arg0() {return arg0;} public Exp arg1() {return arg1;} public ExpBin(Exp arg0, Exp arg1) { super(); this.arg0 = arg0; this.arg1 = arg1; } public StringLocalizado str(){ return arg0().str(); } } public static abstract class ExpUni extends Exp { private Exp arg; public Exp arg() {return arg;} public ExpUni(Exp arg) { super(); this.arg = arg; } public StringLocalizado str(){ return arg().str(); } } private static abstract class ExpAditiva extends ExpBin { public ExpAditiva(Exp arg0, Exp arg1) { super(arg0,arg1); } public final int prioridad() { return 0; } } public static class Suma extends ExpAditiva { public Suma(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Resta extends ExpAditiva { public Resta(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } private static abstract class ExpLogico extends ExpBin { public ExpLogico(Exp arg0, Exp arg1) { super(arg0,arg1); } public final int prioridad() { return 1; } } public static class And extends ExpLogico { public And(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Or extends ExpLogico { public Or(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } private static abstract class ExpComparativa extends ExpBin { public ExpComparativa(Exp arg0, Exp arg1) { super(arg0,arg1); } public final int prioridad() { return 2; } } public static class LT extends ExpComparativa { public LT(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class GT extends ExpComparativa { public GT(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class LE extends ExpComparativa { public LE(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class GE extends ExpComparativa { public GE(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class EQ extends ExpComparativa { public EQ(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class NE extends ExpComparativa { public NE(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } private static abstract class ExpMultiplicativa extends ExpBin { public ExpMultiplicativa(Exp arg0, Exp arg1) { super(arg0,arg1); } public final int prioridad() { return 3; } } public static class Mul extends ExpMultiplicativa { public Mul(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Div extends ExpMultiplicativa { public Div(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Mod extends ExpMultiplicativa { public Mod(Exp arg0, Exp arg1) { super(arg0,arg1); } public void procesa(Procesamiento p) { p.procesa(this); } } private static abstract class ExpPre extends ExpUni { public ExpPre(Exp arg) { super(arg); } public final int prioridad() { return 4; } } public static class Not extends ExpPre { public Not(Exp arg) { super(arg); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Neg extends ExpPre { public Neg(Exp arg) { super(arg); } public void procesa(Procesamiento p) { p.procesa(this); } } private static abstract class ExpAcc extends Exp{ private StringLocalizado id; private Exp exp; public ExpAcc(Exp exp, StringLocalizado id) { super(); this.id = id; this.exp = exp; } public StringLocalizado id(){return id;} public Exp exp(){return exp;} public final int prioridad() { return 5; } public abstract void procesa(Procesamiento procesamiento); public StringLocalizado str(){ return exp.str(); } } public static class Index extends ExpBin { public Index(Exp exp0, Exp exp1) { super(exp0, exp1); } @Override public boolean esDesignador(){ return true; } public final int prioridad() { return 5; } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Atr extends ExpAcc { public Atr(Exp arg0, StringLocalizado arg1) { super(arg0,arg1); } @Override public boolean esDesignador(){ return true; } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Ptr extends ExpAcc { public Ptr(Exp arg0, StringLocalizado arg1) { super(arg0,arg1); } @Override public boolean esDesignador(){ return true; } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Indir extends ExpUni { public Indir(Exp arg) { super(arg); } @Override public boolean esDesignador(){ return true; } public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 6; } } public static class Parentesis extends ExpUni { public Parentesis(Exp arg) { super(arg); } public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class Ent extends Exp { private StringLocalizado entero; public Ent(StringLocalizado ent) { super(); this.entero = ent; } public StringLocalizado str() {return entero;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class IdenExp extends Exp{ private StringLocalizado id; private Dec vinculo; public IdenExp(StringLocalizado id) { super(); this.id = id; } @Override public boolean esDesignador(){ return true; } public StringLocalizado str() {return id;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } @Override public Dec vinculo(){ return vinculo; } @Override public void setVinculo(Dec dec){ this.vinculo = dec; } } public static class Lreal extends Exp { private StringLocalizado lr; public Lreal(StringLocalizado lreal) { super(); this.lr = lreal; } public StringLocalizado str() {return lr;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class True extends Exp { private StringLocalizado t; public True(StringLocalizado t) { super(); this.t = t; } public StringLocalizado str() {return t;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class False extends Exp { private StringLocalizado t; public False(StringLocalizado t) { super(); this.t = t; } public StringLocalizado str() {return t;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class Cadena extends Exp { private StringLocalizado cad; public Cadena(StringLocalizado cadena) { super(); this.cad = cadena; } public StringLocalizado str() {return cad;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static class Nnull extends Exp { private StringLocalizado n; public Nnull(StringLocalizado n) { super(); this.n = n; } public StringLocalizado str() {return n;} public void procesa(Procesamiento p) { p.procesa(this); } public final int prioridad() { return 7; } } public static abstract class Exps { public Exps(){ } public Exps exps(){return null;} public Exp exp(){return null;} public abstract void procesa(Procesamiento p); } public static class NoExps extends Exps{ public NoExps(){ super(); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class Exps1 extends Exps { private Exp exp; private Exps exps; public Exps1(Exps exps, Exp exp) { super(); this.exp = exp; this.exps = exps; } @Override public Exp exp() {return exp;} @Override public Exps exps() {return exps;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class Exps0 extends Exps { private Exp exp; public Exps0(Exp exp) { super(); this.exp = exp; } @Override public Exp exp() {return exp;} public void procesa(Procesamiento p) { p.procesa(this); } } public static abstract class Insts extends ASTNode{ private boolean ok; public Insts(){ ok = true; } public abstract void procesa(Procesamiento p); public boolean getOk(){return ok;} public void setOk(boolean ok){this.ok = ok;} } public static class NoInsts extends Insts{ public NoInsts(){ super(); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class InstsComp extends Insts { private Inst inst; private Insts insts; public InstsComp(Insts insts, Inst inst) { super(); this.inst = inst; this.insts = insts; } public Inst inst() {return inst;} public Insts insts() {return insts;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class InstsSimp extends Insts { private Inst inst; public InstsSimp(Inst inst) { super(); this.inst = inst; } public Inst inst() {return inst;} public void procesa(Procesamiento p) { p.procesa(this); } } public static abstract class Inst extends ASTNode{ private int etqi; private int etqs; private boolean ok; public Inst(){ ok = true; } public abstract void procesa(Procesamiento p); public int etqi() {return etqi;} public int etqs() {return etqs;} public void setEtqi(int etqi) {this.etqi = etqi;} public void setEtqs(int etqs) {this.etqs = etqs;} public boolean getOk(){return ok;} public void setOk(boolean ok){this.ok = ok;} } public static class IAsig extends Inst { private Exp exp0; private Exp exp1; public IAsig(Exp exp0, Exp exp1) { super(); this.exp0 = exp0; this.exp1 = exp1; } public Exp exp0() {return exp0;} public Exp exp1() {return exp1;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IIfThen extends Inst { private Exp exp; private Insts insts; public IIfThen(Exp exp, Insts insts) { super(); this.exp = exp; this.insts = insts; } public Exp exp() {return exp;} public Insts insts() {return insts;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IIfThenElse extends Inst { private Exp exp; private Insts insts0; private Insts insts1; public IIfThenElse(Exp exp, Insts insts0, Insts insts1) { super(); this.exp = exp; this.insts0 = insts0; this.insts1 = insts1; } public Exp exp() {return exp;} public Insts insts0() {return insts0;} public Insts insts1() {return insts1;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IWhile extends Inst { private Exp exp; private Insts insts; public IWhile(Exp exp, Insts insts) { super(); this.exp = exp; this.insts = insts; } public Exp exp() {return exp;} public Insts insts() {return insts;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IRead extends Inst { private Exp exp; public IRead(Exp exp) { super(); this.exp = exp; } public Exp exp() {return exp;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IWrite extends Inst { private Exp exp; public IWrite(Exp exp) { super(); this.exp = exp; } public Exp exp() {return exp;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class INew extends Inst { private Exp exp; public INew(Exp exp) { super(); this.exp = exp; } public Exp exp() {return exp;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class IDelete extends Inst { private Exp exp; public IDelete(Exp exp) { super(); this.exp = exp; } public Exp exp() {return exp;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class INl extends Inst { public INl(){ super(); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class ICall extends Inst { private StringLocalizado id; private Exps exps; private Dec vinculo; public ICall(StringLocalizado id, Exps exps) { super(); this.id = id; this.exps = exps; } public StringLocalizado id() {return id;} public Exps exps() { return exps;} public void procesa(Procesamiento p) { p.procesa(this); } public Dec vinculo(){return this.vinculo;} public void setVinculo(Dec dec){this.vinculo = dec;} public String toString(){return "ICall " + id.toString();} } public static class Bloque extends Inst { private Prog prog; private int tam; public Bloque(Prog prog) { super(); this.prog = prog; } public Prog prog() {return prog;} public void procesa(Procesamiento p) { p.procesa(this); } public int tam() {return tam;} public void setTam(int tam) {this.tam = tam;} } public static abstract class Tipo extends ASTNode{ int tam; public Tipo(){} public abstract Type type(); public Tipo tipoSimpl(){return this;} public abstract void procesa(Procesamiento p); public abstract String toString(); public int tam() {return tam;} public void setTam(int tam) {this.tam = tam;} } public static class INT extends Tipo { public INT(){ super(); } public void procesa(Procesamiento p){ p.procesa(this); } public Type type() { return Type.INT; } @Override public String toString(){return "INT";} } public static class REAL extends Tipo { public REAL(){ super(); } public void procesa(Procesamiento p){ p.procesa(this); } public Type type() { return Type.REAL; } @Override public String toString(){return "REAL";} } public static class BOOL extends Tipo { public BOOL(){ super(); } public void procesa(Procesamiento p){ p.procesa(this); } public Type type() { return Type.BOOL; } @Override public String toString(){return "BOOL";} } public static class STRING extends Tipo { public STRING(){ super(); } public void procesa(Procesamiento p){ p.procesa(this); } public Type type() { return Type.STRING; } @Override public String toString(){return "STRING";} } public static class IdenTipo extends Tipo { private StringLocalizado str; private Dec vinculo = null; public IdenTipo(StringLocalizado str){ super(); this.str = str; } public Dec vinculo(){return this.vinculo;} public void setVinculo(Dec dec){this.vinculo = dec;} @Override public Tipo tipoSimpl(){return vinculo.tipo();} public Type type(){ return vinculo.tipo().type(); } public StringLocalizado str(){return str;} public void procesa(Procesamiento p){ p.procesa(this); } @Override public String toString(){return str.toString();} } public static class ARRAY extends Tipo { private StringLocalizado num; private Tipo tipo; private int dim; public ARRAY(StringLocalizado num, Tipo tipo){ super(); this.tipo = tipo; this.num = num; } public StringLocalizado num(){return num;} public Tipo tipo(){return tipo;} public void setTipo(Tipo tipo) {this.tipo = tipo;} public void procesa(Procesamiento p){p.procesa(this);} @Override public Type type() {return Type.ARRAY;} public void setDim(int dim) {this.dim = dim;} public int getDim() {return dim;} @Override public Tipo tipoSimpl(){ //this.tipo = tipo.tipoSimpl(); return this; } @Override public String toString(){return "ARRAY";} } public static class REGISTRO extends Tipo { private Campos campos; private Map<String, Campo> listCampos; public REGISTRO(Campos campos){ super(); this.campos = campos; } public void setList(Map<String, Campo> listCampos){this.listCampos = listCampos;} public Map<String, Campo> getList(){return this.listCampos;} public Campos campos(){return campos;} public void procesa(Procesamiento p){ p.procesa(this); } @Override public Type type() { return Type.RECORD; } @Override public String toString(){return "REGISTRO";} } public static class POINTER extends Tipo { private Tipo tipo; public POINTER(Tipo tipo){ super(); this.tipo = tipo; } public Tipo tipo(){return tipo;} public void setTipo(Tipo tipo) {this.tipo = tipo;} @Override public Tipo tipoSimpl(){ //this.tipo = tipo.tipoSimpl(); return this; } public void procesa(Procesamiento p){ p.procesa(this); } @Override public Type type() { return Type.POINTER; } @Override public String toString(){return "POINTER";} } public static class ERROR extends Tipo { public ERROR(){ super(); } @Override public Type type() {return Type.ERROR;} @Override public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){return "ERROR";} } public static class OK extends Tipo { public OK(){ super(); } @Override public Type type() {return Type.OK;} @Override public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){return "OK";} } public static class NULL extends Tipo { public NULL(){ super(); } @Override public Type type() {return Type.NULL;} @Override public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){return "NULL";} } public static abstract class Campos{ public Campos(){ } public Campos campos(){return null;} public Campo campo(){return null;} public abstract void procesa(Procesamiento p); } public static class CamposComp extends Campos{ private Campos campos; private Campo campo; public CamposComp(Campos campos, Campo campo){ super(); this.campos = campos; this.campo = campo; } @Override public Campos campos(){return campos;} @Override public Campo campo(){return campo;} public void procesa(Procesamiento p){ p.procesa(this); } } public static class CamposSimp extends Campos{ private Campo campo; public CamposSimp(Campo campo){ super(); this.campo = campo; } @Override public Campo campo(){return campo;} public void procesa(Procesamiento p){ p.procesa(this); } } public static class Campo { int dir; int desp; private StringLocalizado id; private Tipo tipo; private Type type; public Campo(Tipo tipo, StringLocalizado id){ this.tipo = tipo; this.id = id; } public Tipo tipo() {return tipo;} public void setTipo(Tipo tipo){this.tipo = tipo;} public Type type(){return type;} public void setType(Type type){this.type = type;} public StringLocalizado id() {return id;} public void setDir(int dir){ this.dir = dir; } public int getDir(){ return dir;} public void procesa(Procesamiento p){ p.procesa(this); } public int desp() {return desp;} public void setDesp(int desp) {this.desp = desp;} @Override public String toString(){ return "Campo " + this.id().toString() + "; Dir: " + this.dir + "; Desp: " + this.desp; } } public static abstract class Decs extends ASTNode{ private int tam; public Decs() { } public abstract void procesa(Procesamiento p); public int tam() {return tam;} public void setTam(int tam) {this.tam = tam;} } public static class NoDecs extends Decs{ public NoDecs(){ super(); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class AuxDecs extends Decs{ private Decs decs; public AuxDecs(Decs decs) { super(); this.decs = decs; } public Decs decs() {return decs;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class LDecSimp extends Decs { private Dec dec; public LDecSimp(Dec dec) { super(); this.dec = dec; } public Dec dec() {return dec;} public void procesa(Procesamiento p) { p.procesa(this); } } public static class LDecComp extends Decs { private Dec dec; private Decs decs; public LDecComp(Decs decs, Dec dec) { super(); this.dec = dec; this.decs = decs; } public Dec dec() {return dec;} public Decs decs() {return decs;} public void procesa(Procesamiento p) { p.procesa(this); } } public static abstract class Dec extends ASTNode{ private int tam; int ambito; int dir; private StringLocalizado id; private Tipo tipo; private Type type; public Dec(Tipo tipo, StringLocalizado id) { this.tipo = tipo; this.id = id; } public Tipo tipo() {return tipo;} public void setTipo(Tipo tipo){this.tipo = tipo;} public Type type(){return type;} public void setType(Type type){this.type = type;} public StringLocalizado id() {return id;} public void setAmbito(int ambito){ this.ambito = ambito; } public void setDir(int dir){ this.dir = dir; } public int tam() {return tam;} public void setTam(int tam) {this.tam = tam;} public int getAmbito(){ return ambito;} public int getDir(){ return dir;} public String toString(){ return "; Ambito: " + this.ambito; } public abstract DecType decType(); public abstract void procesa(Procesamiento p); } public static class DVar extends Dec { public DVar(Tipo tipo, StringLocalizado id) { super(tipo, id); } public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){ return "Var " + this.id().toString() + super.toString(); } @Override public DecType decType() { return DecType.VAR; } } public static class DTipo extends Dec { public DTipo(Tipo tipo, StringLocalizado id) { super(tipo, id); } @Override public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){ return "Tipo " + this.id().toString() + super.toString(); } @Override public DecType decType() { return DecType.TYPE; } } public static class DProc extends Dec{ private Pars pars; private Inst bloque; public DProc(StringLocalizado id, Pars pars, Inst bloque) { super(TypeOk, id); setType(Type.OK); this.pars = pars; this.bloque = bloque; } public Pars pars() {return pars;} public Inst bloque(){return bloque;} public void procesa(Procesamiento p) { p.procesa(this); } @Override public String toString(){ return "Proc " + this.id().toString() + super.toString(); } @Override public DecType decType() { return DecType.PROC; } } public static abstract class Pars { int tam; public Pars() { } public Pars pars(){return null;} public Par par(){return null;} public abstract void procesa(Procesamiento p); public void setTam(int tam) {this.tam = tam;} public int tam() {return tam;} } public static class NoPars extends Pars{ public NoPars(){ super(); } public void procesa(Procesamiento p) { p.procesa(this); } } public static class ParsComp extends Pars{ private Pars pars; private Par par; public ParsComp(Pars pars, Par par) { super(); this.par = par; this.pars= pars; } @Override public Pars pars(){return pars;} @Override public Par par(){return par;} public void procesa(Procesamiento p){ p.procesa(this); } } public static class ParsSimp extends Pars{ private Par par; public ParsSimp(Par par) { super(); this.par = par; } @Override public Par par(){return par;} public void procesa(Procesamiento p){ p.procesa(this); } } public static abstract class Par extends Dec{ public boolean esReferencia(){ return false; } public Par(Tipo tipo, StringLocalizado id) { super(tipo, id); } public abstract void procesa(Procesamiento p); } public static class ParRef extends Par{ public ParRef(Tipo tipo, StringLocalizado id) { super(tipo, id); } public void procesa(Procesamiento p){ p.procesa(this); } @Override public boolean esReferencia(){ return true; } @Override public String toString(){ return "ParRef " + this.id().toString() + super.toString(); } @Override public DecType decType() { return DecType.VAR; } } public static class ParSinRef extends Par{ public ParSinRef(Tipo tipo, StringLocalizado id) { super(tipo, id); } public void procesa(Procesamiento p){ p.procesa(this); } @Override public String toString(){ return "ParSinRef " + this.id().toString() + super.toString(); } @Override public DecType decType() { return DecType.VAR; } } public static class Prog { private Insts insts; private Decs decs; public Prog(Decs decs, Insts insts) { this.insts = insts; this.decs = decs; } public Insts insts() {return insts;} public Decs decs() {return decs;} public void procesa(Procesamiento p) { p.procesa(this); } } // Constructoras public Prog prog(Decs decs, Insts insts) {return new Prog(decs, insts);} public static final Decs noDecs = new NoDecs(); public Decs auxDecs(Decs decs) {return new AuxDecs(decs);} public Decs decSimp(Dec dec) {return new LDecSimp(dec);} public Decs decComp(Decs decs, Dec dec) {return new LDecComp(decs, dec);} public Dec dVar(Tipo tipo, StringLocalizado id) {return new DVar(tipo,id);} public Dec dTipo(Tipo tipo, StringLocalizado id) {return new DTipo(tipo,id);} public Dec dProc(StringLocalizado id, Pars pars, Inst bloque) {return new DProc(id, pars, bloque);} public static final Pars noPars = new NoPars(); public Pars parsComp(Pars pars, Par par) {return new ParsComp(pars, par);} public Pars parsSimp(Par par) {return new ParsSimp(par);} public Par parRef(Tipo tipo, StringLocalizado id) {return new ParRef(tipo,id);} public Par parSinRef(Tipo tipo, StringLocalizado id) {return new ParSinRef(tipo,id);} public static final Tipo TypeInt = new INT(); public static final Tipo TypeReal = new REAL(); public static final Tipo TypeBool = new BOOL(); public static final Tipo TypeString = new STRING(); public Tipo idenTipo(StringLocalizado str) {return new IdenTipo(str);} public Tipo array(StringLocalizado num, Tipo tipo) {return new ARRAY(num, tipo);} public Tipo registro(Campos campos) {return new REGISTRO(campos);} public static final Tipo TypeError = new ERROR(); public static final Tipo TypeOk = new OK(); public static final Tipo TypeNull = new NULL(); public Campos camposComp(Campos campos, Campo campo) {return new CamposComp(campos, campo);} public Campos camposSimp(Campo campo) {return new CamposSimp(campo);} public Campo campo(Tipo tipo, StringLocalizado id) {return new Campo(tipo, id);} public Tipo pointer(Tipo tipo) {return new POINTER(tipo);} public static final Insts noInsts = new NoInsts(); public Insts instsComp(Insts insts, Inst inst) {return new InstsComp(insts, inst);} public Insts instsSimp(Inst inst) {return new InstsSimp(inst);} public Inst iAsig(Exp exp0, Exp exp1) {return new IAsig(exp0, exp1);} public Inst iIfThen(Exp exp, Insts insts) {return new IIfThen(exp, insts);} public Inst iIfThenElse(Exp exp, Insts insts0, Insts insts1) {return new IIfThenElse(exp, insts0, insts1);} public Inst iWhile(Exp exp, Insts insts) {return new IWhile(exp, insts);} public Inst iRead(Exp exp) {return new IRead(exp);} public Inst iWrite(Exp exp) {return new IWrite(exp);} public Inst iNew(Exp exp) {return new INew(exp);} public Inst iDelete(Exp exp) {return new IDelete(exp);} public Inst iNl(){ return new INl();} public Inst iCall(StringLocalizado id, Exps exps) {return new ICall(id, exps);} public Inst bloque(Prog prog) {return new Bloque(prog);} public static final Exps noExps = new NoExps(); public Exps exps1(Exps exps, Exp exp) {return new Exps1(exps, exp);} public Exps exps0(Exp exp) {return new Exps0(exp);} public Exp suma(Exp arg0, Exp arg1) {return new Suma(arg0,arg1);} public Exp resta(Exp arg0, Exp arg1) {return new Resta(arg0,arg1);} public Exp and(Exp arg0, Exp arg1) {return new And(arg0,arg1);} public Exp or(Exp arg0, Exp arg1) {return new Or(arg0,arg1);} public Exp lt(Exp arg0, Exp arg1) {return new LT(arg0,arg1);} public Exp gt(Exp arg0, Exp arg1) {return new GT(arg0,arg1);} public Exp ge(Exp arg0, Exp arg1) {return new GE(arg0,arg1);} public Exp le(Exp arg0, Exp arg1) {return new LE(arg0,arg1);} public Exp ne(Exp arg0, Exp arg1) {return new NE(arg0,arg1);} public Exp eq(Exp arg0, Exp arg1) {return new EQ(arg0,arg1);} public Exp cmp(String op, Exp arg0, Exp arg1){ switch(op){ case "<": return lt(arg0, arg1); case ">": return gt(arg0, arg1); case "<=": return le(arg0, arg1); case ">=": return ge(arg0, arg1); case "!=": return ne(arg0, arg1); case "==": return eq(arg0, arg1); default: throw new UnsupportedOperationException("cmp "+op); } } public Exp mul(Exp arg0, Exp arg1) {return new Mul(arg0,arg1);} public Exp div(Exp arg0, Exp arg1) {return new Div(arg0,arg1);} public Exp mod(Exp arg0, Exp arg1) {return new Mod(arg0,arg1);} public Exp op3na(String op, Exp arg0, Exp arg1){ switch(op){ case "*": return mul(arg0, arg1); case "/": return div(arg0, arg1); case "%": return mod(arg0, arg1); default: throw new UnsupportedOperationException("cmp "+op); } } public Exp not(Exp arg) {return new Not(arg);} public Exp neg(Exp arg) {return new Neg(arg);} public Exp index(Exp arg0, Exp arg1) {return new Index(arg0, arg1);} public Exp ptr(Exp arg0, StringLocalizado arg1) {return new Ptr(arg0, arg1);} public Exp atr(Exp arg0, StringLocalizado arg1) {return new Atr(arg0, arg1);} public Exp indir(Exp arg) {return new Indir(arg);} public Exp parentesis(Exp arg) {return new Parentesis(arg);} public Exp ent(StringLocalizado num) {return new Ent(num);} public Exp idenExp(StringLocalizado id) {return new IdenExp(id);} public Exp lreal(StringLocalizado num) {return new Lreal(num);} public Exp ttrue(StringLocalizado t) {return new True(t);} public Exp ffalse(StringLocalizado f) {return new False(f);} public Exp cadena(StringLocalizado id) {return new Cadena(id);} public Exp nnull(StringLocalizado n) {return new Nnull(n);} public StringLocalizado str(String s, int fila, int col) { return new StringLocalizado(s,fila,col); } }
package com.media2359.mediacorpspellinggame.data; /** * Created by xijunli on 13/2/17. */ public class Result { private int id; private int questionId; private String theAnswer; private int score; private int timeTaken; public Result(Builder builder) { this.id = builder.id; this.questionId = builder.questionId; this.theAnswer = builder.theAnswer; this.score = builder.score; this.timeTaken = builder.timeTaken; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getQuestionId() { return questionId; } public void setQuestionId(int questionId) { this.questionId = questionId; } public String getTheAnswer() { return theAnswer; } public void setTheAnswer(String theAnswer) { this.theAnswer = theAnswer; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getTimeTaken() { return timeTaken; } public void setTimeTaken(int timeTaken) { this.timeTaken = timeTaken; } public static class Builder { private int id; private int questionId; private String theAnswer; private int score; private int timeTaken; public Builder() { } public Builder id(int id) { this.id = id; return this; } public Builder questionId(int questionId) { this.questionId = questionId; return this; } public Builder theAnswer(String theAnswer) { this.theAnswer = theAnswer; return this; } public Builder score(int score) { this.score = score; return this; } public Builder timeTaken(int timeTaken) { this.timeTaken = timeTaken; return this; } public Result build() { return new Result(this); } } }
package com.tencent.mm.plugin.appbrand.jsapi; import com.tencent.mm.plugin.appbrand.page.p; class bc$1 implements Runnable { final /* synthetic */ p fGY; final /* synthetic */ long fGZ; final /* synthetic */ bc fHa; bc$1(bc bcVar, p pVar, long j) { this.fHa = bcVar; this.fGY = pVar; this.fGZ = j; } public final void run() { this.fGY.gnt.setPullDownBackgroundColor((int) this.fGZ); } }
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.netl3vpn.manager.impl; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.util.KryoNamespace; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.incubator.net.resource.label.LabelResourceAdminService; import org.onosproject.incubator.net.resource.label.LabelResourceService; import org.onosproject.mastership.MastershipService; import org.onosproject.ne.NeData; import org.onosproject.ne.VpnAc; import org.onosproject.ne.VpnInstance; import org.onosproject.ne.manager.L3vpnNeService; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.onosproject.netl3vpn.entity.NetL3VpnAllocateRes; import org.onosproject.netl3vpn.entity.WebNetL3vpnInstance; import org.onosproject.netl3vpn.manager.NetL3vpnService; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.EventuallyConsistentMap; import org.onosproject.store.service.LogicalClockService; import org.onosproject.store.service.StorageService; import org.onosproject.yang.gen.v1.net.l3vpn.rev20160701.netl3vpn.instances.Instance; import org.onosproject.yang.gen.v1.net.l3vpn.rev20160701.netl3vpn.instances.instance.nes.Ne; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides implementation of NetL3vpnService. */ @Component(immediate = true) @Service public class NetL3vpnManager implements NetL3vpnService { private static final String INSTANCE_NOT_NULL = "Instance can not be null"; private static final String APP_ID = "org.onosproject.app.l3vpn.net"; private static final String RT = "rt"; private static final String RD = "rd"; private static final String VRF = "vrf"; private static final String NETL3INSTANCESTORE = "netl3vpn-instance"; private static final String NEL3INSTANCESTORE = "nel3vpn-instance"; private static final String NEL3ACSTORE = "nel3vpn-ac"; private static final long GLOBAL_LABEL_SPACE_MIN = 1; private static final long GLOBAL_LABEL_SPACE_MAX = Long.MAX_VALUE; protected static final Logger log = LoggerFactory .getLogger(NetL3vpnManager.class); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected MastershipService mastershipService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService storageService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected LogicalClockService clockService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected LabelResourceAdminService labelRsrcAdminService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected LabelResourceService labelRsrcService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private L3vpnNeService l3vpnNeService; private ApplicationId appId; private WebNetL3vpnInstance webNetL3vpnInstance; private NetL3VpnAllocateRes l3VpnAllocateRes; private NetL3vpnParseHandler netL3vpnParseHandler; private NetL3vpnLabelHandler netL3vpnLabelHandler; private NetL3vpnDecompHandler netL3vpnDecompHandler; private EventuallyConsistentMap<String, WebNetL3vpnInstance> webNetL3vpnStore; private EventuallyConsistentMap<String, VpnInstance> vpnInstanceStore; private EventuallyConsistentMap<String, VpnAc> vpnAcStore; @Activate public void activate() { appId = coreService.registerApplication(APP_ID); netL3vpnParseHandler = NetL3vpnParseHandler.getInstance(); netL3vpnLabelHandler = NetL3vpnLabelHandler.getInstance(); netL3vpnLabelHandler.initialize(labelRsrcAdminService, labelRsrcService); netL3vpnDecompHandler = NetL3vpnDecompHandler.getInstance(); KryoNamespace.Builder serializer = KryoNamespace.newBuilder() .register(KryoNamespaces.API).register(VpnInstance.class) .register(WebNetL3vpnInstance.class).register(VpnAc.class); webNetL3vpnStore = storageService .<String, WebNetL3vpnInstance>eventuallyConsistentMapBuilder() .withName(NETL3INSTANCESTORE).withSerializer(serializer) .withTimestampProvider((k, v) -> clockService.getTimestamp()) .build(); vpnInstanceStore = storageService .<String, VpnInstance>eventuallyConsistentMapBuilder() .withName(NEL3INSTANCESTORE).withSerializer(serializer) .withTimestampProvider((k, v) -> clockService.getTimestamp()) .build(); vpnAcStore = storageService .<String, VpnAc>eventuallyConsistentMapBuilder() .withName(NEL3ACSTORE).withSerializer(serializer) .withTimestampProvider((k, v) -> clockService.getTimestamp()) .build(); if (!netL3vpnLabelHandler.reserveGlobalPool(GLOBAL_LABEL_SPACE_MIN, GLOBAL_LABEL_SPACE_MAX)) { log.debug("Global node pool was already reserved."); } log.info("Started"); } @Deactivate public void deactivate() { log.info("Stopped"); } @Override public boolean createL3vpn(Instance instance) { checkNotNull(instance, INSTANCE_NOT_NULL); if (!checkDeviceStatus(instance)) { return false; } netL3vpnParseHandler.initialize(instance); webNetL3vpnInstance = netL3vpnParseHandler.cfgParse(); if (webNetL3vpnInstance == null) { log.debug("Parsing the web vpn instance failed, whose identifier is {} ", instance.id()); return false; } if (!checkOccupiedResource()) { log.debug("The resource of l3vpn instance is occupied."); return false; } l3VpnAllocateRes = applyResource(); if (l3VpnAllocateRes == null) { log.debug("Apply resources of l3vpn instance failed."); return false; } netL3vpnDecompHandler.initialize(l3VpnAllocateRes, deviceService); NeData neData = netL3vpnDecompHandler.decompNeData(webNetL3vpnInstance); if (l3vpnNeService.createL3vpn(neData)) { webNetL3vpnStore.put(webNetL3vpnInstance.getId(), webNetL3vpnInstance); for (VpnInstance vpnInstance : neData.vpnInstanceList()) { vpnInstanceStore.put(vpnInstance.neId(), vpnInstance); } for (VpnAc vpnAc : neData.vpnAcList()) { vpnAcStore.put(vpnAc.acId(), vpnAc); } return true; } return false; } /** * Check the status of devices for the instance. * * @param instance the specific instance * @return success or failure */ public boolean checkDeviceStatus(Instance instance) { for (Ne ne : instance.nes().ne()) { DeviceId deviceId = DeviceId.deviceId(ne.id()); if (deviceService.getDevice(deviceId) == null) { log.debug("Cannot get the device, whose ne id is {}.", ne.id()); return false; } if (!deviceService.isAvailable(deviceId)) { log.debug("The device whose ne id is {} cannot be available.", ne.id()); return false; } if (!mastershipService.isLocalMaster(deviceId)) { log.debug("The device whose ne id is {} is not master role.", ne.id()); return false; } } return true; } /** * Check the resource is valid or not. * * @return valid or not */ public boolean checkOccupiedResource() { for (Entry<String, WebNetL3vpnInstance> entry : webNetL3vpnStore .entrySet()) { if ((entry.getKey() == webNetL3vpnInstance.getId()) || (entry .getValue().getName() == webNetL3vpnInstance.getName())) { return false; } } return true; } /** * Apply the node labels from global node label pool. * * @return the allocate resource entity */ public NetL3VpnAllocateRes applyResource() { String routeTarget = netL3vpnLabelHandler .allocateResource(RT, webNetL3vpnInstance); Map<String, String> routeDistinguisherMap = new HashMap<String, String>(); for (String neId : webNetL3vpnInstance.getNeIdList()) { String routeDistinguisher = netL3vpnLabelHandler .allocateResource(RD, webNetL3vpnInstance); routeDistinguisherMap.put(neId, routeDistinguisher); } String vrfName = netL3vpnLabelHandler .allocateResource(VRF, webNetL3vpnInstance); if (routeTarget == null || routeDistinguisherMap == null || vrfName == null) { return null; } List<String> routeTargets = new ArrayList<String>(); routeTargets.add(routeTarget); return new NetL3VpnAllocateRes(routeTargets, routeDistinguisherMap, vrfName); } }
package com.ace.easyteacher.Adapter; import android.content.Context; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ace.easyteacher.DataBase.StudentInfo; import com.ace.easyteacher.R; import com.ace.easyteacher.View.MaterialRippleLayout; import com.facebook.drawee.view.SimpleDraweeView; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /** * Created by lenovo on 2015-12-13. */ public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> { private List<String> mDataset; private static LayoutInflater layoutInflater; public OnItemClickListener mItemClickListener; private List<StudentInfo> mListStudent; private Context context; private int lastAnimatedPosition = -1; private int viewHeight = 0; public StudentAdapter(Context context, List<StudentInfo> mListStudent) { super(); // mDataset = dataset; // for (int i = 0; i < 30; i++) { // mDataset.add("item" + i); // } this.mListStudent = mListStudent; layoutInflater = LayoutInflater.from(context); this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = layoutInflater.inflate(R.layout.item_student, null); // 创建一个ViewHolder return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { // 绑定数据到ViewHolder上 // viewHolder.textView.setText(mDataset.get(position)); viewHolder.bindView(mListStudent.get(position), position); } @Override public int getItemCount() { return mListStudent.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private TextView mStudentName, mStudentId, mStudentAge, mStudentPosition; private SimpleDraweeView mHead; private MaterialRippleLayout mp; public ViewHolder(View itemView) { super(itemView); // textView = (TextView) itemView.findViewById(R.id.text); mHead = (SimpleDraweeView) itemView.findViewById(R.id.student_head); mStudentName = (TextView) itemView.findViewById(R.id.student_name); mStudentAge = (TextView) itemView.findViewById(R.id.student_age); mStudentId = (TextView) itemView.findViewById(R.id.student_number); mStudentPosition = (TextView) itemView.findViewById(R.id.student_position); mp = (MaterialRippleLayout) itemView.findViewById(R.id.mp); } void bindView(StudentInfo studentInfo, final int position) { mStudentId.setText(studentInfo.getSid() + ""); mStudentAge.setText(studentInfo.getBirthday()); mStudentPosition.setText(studentInfo.getPosition()); mStudentName.setText(studentInfo.getName()); Uri uri = Uri.parse("http://com-ace-teacher.oss-cn-shenzhen.aliyuncs.com/" + studentInfo.getSid() + ".jpg"); mHead.setImageURI(uri); mp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mItemClickListener.onItemClick(itemView, position); } }); } } public interface OnItemClickListener { public void onItemClick(View view, int position); } public void setOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } }