text
stringlengths 10
2.72M
|
|---|
package br.com.becommerce.core.exception;
public class NotFoundException extends BusinessException {
private static final long serialVersionUID = -8011743156158774600L;
public NotFoundException(String messagePattern, Object... objects) {
super(messagePattern, objects);
}
}
|
package com.fleet.alg;
/**
* 编写一个函数来查找字符串数组中的最长公共前缀。
* <p>
* 如果不存在公共前缀,返回空字符串 ""。
* <p>
* 示例 1:
* <p>
* 输入: ["flower","flow","flight"]
* 输出: "fl"
* 示例 2:
* <p>
* 输入: ["dog","racecar","car"]
* 输出: ""
* 解释: 输入不存在公共前缀。
* 说明:
* <p>
* 所有输入只包含小写字母 a-z 。
*/
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower","flow","flight"};
System.out.println(longestCommonPrefix1(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
int length = strs[0].length();
while (length > 0) {
boolean start = true;
String r = strs[0].substring(0, length);
for (int i = 1; i < strs.length; i++) {
if (!strs[i].startsWith(r)) {
start = false;
}
}
if (start) {
return r;
}
length--;
}
return "";
}
public static String longestCommonPrefix1(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String r = strs[0];
for (int i = 1; i < strs.length; i++) {
r = longestCommonPrefix(r, strs[i]);
if (r.length() == 0) {
break;
}
}
return r;
}
public static String longestCommonPrefix(String s1, String s2) {
int length = Math.min(s1.length(), s2.length());
int index = 0;
while (index < length) {
if (s1.charAt(index) != s2.charAt(index)) {
break;
}
index++;
}
return s1.substring(0, index);
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import android.content.Context;
import android.net.Proxy;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.util.Date;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
public class dq$a extends dq {
private Context a;
public dq$a(Context context) {
this.a = context;
}
public final byte[] a(String str, byte[] bArr, dn dnVar) {
if (str == null) {
ct.d("no destUrl!", new Object[0]);
return null;
}
long j;
do doVar = null;
int i = 0;
if (bArr == null) {
j = 0;
} else {
j = (long) bArr.length;
}
ct.h("start req: %s sz:%d", new Object[]{str, Long.valueOf(j)});
String str2 = "";
String str3 = "";
Object obj = null;
int i2 = 0;
String str4 = str;
while (true) {
int i3 = i + 1;
if (i < 3 && i2 < 2) {
if (obj != null) {
throw new Exception("net redirect");
}
Object obj2;
int i4;
if (i3 > 1) {
ct.h("try time:" + i3, new Object[0]);
if (i3 == 2 && dnVar.c() == 2) {
dnVar.b(false);
}
try {
Thread.sleep(5000);
} catch (Throwable e) {
ct.a(e);
}
}
String n = e.n(this.a);
new Date().getTime();
try {
doVar = a(str4, bArr, n, i3);
} catch (Exception e2) {
n = e2.toString();
if (str3.equals(n)) {
str2 = str2 + i3 + ":same ";
} else {
str2 = str2 + i3 + ":" + n + " ";
}
str3 = n;
}
new Date().getTime();
if (doVar != null) {
HttpResponse httpResponse = doVar.a;
HttpEntity entity = httpResponse.getEntity();
long j2 = 0;
if (entity != null) {
j2 = entity.getContentLength();
if (j2 < 0) {
j2 = 0;
}
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
ct.h("response code:%d ", new Object[]{Integer.valueOf(statusCode)});
ct.h("contentLength:%d ", new Object[]{Long.valueOf(j2)});
if (statusCode != 200) {
obj2 = (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) ? 1 : null;
if (obj2 != null) {
obj2 = 1;
Header firstHeader = httpResponse.getFirstHeader("Location");
if (firstHeader == null) {
ct.d("redirect code:" + statusCode + " Location is null! return", new Object[0]);
try {
if (doVar.b != null) {
doVar.b.abort();
}
} catch (Exception e3) {
}
return null;
}
i4 = i2 + 1;
i = 0;
String value = firstHeader.getValue();
ct.h("redirect code:%d , to:%s", new Object[]{Integer.valueOf(statusCode), value});
try {
if (doVar.b != null) {
doVar.b.abort();
}
obj = 1;
i2 = i4;
str4 = value;
} catch (Exception e4) {
str4 = value;
}
}
} else if (!httpResponse.containsHeader("encrypt-status")) {
return a(httpResponse, doVar.b);
} else {
ct.d("svr encry failed: " + httpResponse.getFirstHeader("encrypt-status").getValue(), new Object[0]);
return null;
}
}
obj2 = obj;
i4 = i2;
i = i3;
obj = obj2;
i2 = i4;
}
}
throw new Exception(str2);
}
private static do a(String str, byte[] bArr, String str2, int i) {
Throwable th;
HttpPost httpPost;
if (str == null) {
ct.d("no destUrl!", new Object[0]);
return null;
}
HttpEntity byteArrayEntity;
if (bArr != null) {
try {
byteArrayEntity = new ByteArrayEntity(bArr);
} catch (Throwable th2) {
th = th2;
httpPost = null;
ct.a(th);
ct.d("execute error:%s", new Object[]{th.toString()});
if (httpPost != null) {
httpPost.abort();
}
throw new Exception(th.toString());
}
}
byteArrayEntity = new ByteArrayEntity("".getBytes());
HttpClient a = a(str2, i);
if (a == null) {
ct.d("no httpClient!", new Object[0]);
return null;
}
httpPost = new HttpPost(str);
try {
httpPost.setHeader("wup_version", "3.0");
httpPost.setHeader("TYPE_COMPRESS", "2");
httpPost.setHeader("encr_type", "rsapost");
ch a2 = ch.a();
if (a2 != null) {
httpPost.setHeader("bea_key", a2.j());
}
httpPost.setEntity(byteArrayEntity);
HttpResponse execute = a.execute(httpPost, new BasicHttpContext());
ct.h("execute request:\n %s", new Object[]{((HttpRequest) r0.getAttribute("http.request")).getRequestLine().toString()});
return new do(execute, httpPost);
} catch (Throwable th3) {
th = th3;
ct.a(th);
ct.d("execute error:%s", new Object[]{th.toString()});
if (httpPost != null) {
httpPost.abort();
}
throw new Exception(th.toString());
}
}
private byte[] a(HttpResponse httpResponse, HttpPost httpPost) {
Throwable th;
byte[] bArr = null;
if (httpResponse != null) {
if (httpResponse.getStatusLine().getStatusCode() != 200) {
StatusLine statusLine = httpResponse.getStatusLine();
ct.c("request failure code:%d , line:%s ", new Object[]{Integer.valueOf(r1), statusLine});
} else {
if (httpResponse.containsHeader("session_id") && httpResponse.containsHeader("max_time")) {
ch.a().a(this.a, httpResponse.getFirstHeader("session_id").getValue(), httpResponse.getFirstHeader("max_time").getValue());
}
HttpEntity entity = httpResponse.getEntity();
if (entity == null) {
ct.d("no response datas!", new Object[0]);
} else {
BufferedInputStream bufferedInputStream;
try {
bufferedInputStream = new BufferedInputStream(new DataInputStream(entity.getContent()));
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(128);
while (true) {
int read = bufferedInputStream.read();
if (read == -1) {
break;
}
byteArrayOutputStream.write(read);
}
byteArrayOutputStream.flush();
bArr = byteArrayOutputStream.toByteArray();
try {
bufferedInputStream.close();
} catch (Throwable th2) {
ct.a(th2);
}
if (httpPost != null) {
httpPost.abort();
}
} catch (Throwable th3) {
th2 = th3;
}
} catch (Throwable th4) {
th2 = th4;
bufferedInputStream = bArr;
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (Throwable th5) {
ct.a(th5);
}
}
if (httpPost != null) {
httpPost.abort();
}
throw th2;
}
}
}
}
return bArr;
}
private static HttpClient a(String str, int i) {
try {
HttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(basicHttpParams, 30000);
HttpConnectionParams.setSoTimeout(basicHttpParams, 20000);
HttpConnectionParams.setSocketBufferSize(basicHttpParams, 2000);
basicHttpParams.setBooleanParameter("http.protocol.handle-redirects", false);
HttpClient defaultHttpClient = new DefaultHttpClient(basicHttpParams);
HttpProtocolParams.setUseExpectContinue(basicHttpParams, false);
defaultHttpClient.setHttpRequestRetryHandler(new 1());
if (str == null || !str.toLowerCase(Locale.US).contains("wap") || i == 2) {
if (str != null) {
ct.a("Don't use proxy: %s, try time: %s", new Object[]{str, Integer.valueOf(i)});
}
defaultHttpClient.getParams().removeParameter("http.route.default-proxy");
return defaultHttpClient;
}
ct.a("use proxy: %s, try time: %s", new Object[]{str, Integer.valueOf(i)});
defaultHttpClient.getParams().setParameter("http.route.default-proxy", new HttpHost(Proxy.getDefaultHost(), Proxy.getDefaultPort()));
return defaultHttpClient;
} catch (Throwable th) {
ct.a(th);
ct.d("httpclient error!", new Object[0]);
return null;
}
}
}
|
import java.util.*;
import java.util.stream.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
public class C {
public static final BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
public static final PrintWriter outWriter = new PrintWriter(System.out);
public static Object solve() {
int n = nextInt(), k = nextInt();
double u = nextDouble();
double[] probs = new double[n+1];
for (int i = 0; i < probs.length; i++) { probs[i] = i==n ? 1 : nextDouble(); }
Arrays.sort(probs);
for (int i = 0; i < n+1; i++) {
double diff = probs[i] - probs[0];
if (diff * i > u+0.00001) {
for (int j = 0; j < i; j++) {
probs[j] += u/i;
}
break;
}
u -= diff * i;
for (int j = 0; j < i; j++) {
probs[j] = probs[i];
}
}
double out = 1;
for (double d : probs) { out *= d; }
return out;
}
public static void main(String[] args) {
int T = nextInt();
for (int i = 0; i < T; i++) {
outWriter.print("Case #"+(i+1)+": ");
Object tmp = solve();
if (tmp != null) { outWriter.println(tmp); }
}
outWriter.flush();
}
public static StringTokenizer tokenizer = null;
public static String nextLine() {
try { return buffer.readLine(); } catch (IOException e) { throw new UncheckedIOException(e); }
}
public static String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) { tokenizer = new StringTokenizer(nextLine()); }
return tokenizer.nextToken();
}
public static int nextInt() { return Integer.parseInt(next()); }
public static long nextLong() { return Long.parseLong(next()); }
public static double nextDouble() { return Double.parseDouble(next()); }
}
|
package oop.ex6.component.variable;
/**
* unAppropriate usage of variable assignment
*/
public class VariableUsageException extends VariableDeclarationException {
/** prevents annoying warning */
private static final long serialVersionUID = 1L;
}
|
package net.minecraft.network.play.client;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayServer;
public class CPacketConfirmTeleport implements Packet<INetHandlerPlayServer> {
private int telportId;
public CPacketConfirmTeleport() {}
public CPacketConfirmTeleport(int teleportIdIn) {
this.telportId = teleportIdIn;
}
public void readPacketData(PacketBuffer buf) throws IOException {
this.telportId = buf.readVarIntFromBuffer();
}
public void writePacketData(PacketBuffer buf) throws IOException {
buf.writeVarIntToBuffer(this.telportId);
}
public void processPacket(INetHandlerPlayServer handler) {
handler.processConfirmTeleport(this);
}
public int getTeleportId() {
return this.telportId;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\client\CPacketConfirmTeleport.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
/*
* 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 jframework.ui;
import data.core.ui.PopupFrame;
import data.core.ui.UiCalendarPopup;
import jframework.ui.student.ListStudent;
import data.core.api.ApiDate;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import static data.Constants.*;
import static data.Constants.TIME;
import static data.PackageFunctions.*;
import data.core.api.ApiError;
import data.core.api.ApiFile;
import java.awt.Component;
import jframework.ui.classes.ListClass;
import jframework.ui.parent.ListParent;
import jframework.ui.assessment.AddAssessment;
import jframework.ui.assessment.EditAssessment;
import jframework.ui.report.SetupReport;
/**
*
* @author Ryno Laptop
*/
public final class MainPanel extends javax.swing.JFrame {
Timer timer;
/**
* Creates new form UsersList
*/
//--------------------------------------------------------------------------
public MainPanel() {
initComponents();
//start clock
setTimeLabel();
setDateLabel();
this.timer = new Timer(1000, clockUpdate);
timer.start();
setMainPanel("Student List", new ListStudent());
try{
this.setIconImage(ApiFile.getImageIcon(ICON_LOGO).getImage());
}catch(Exception ex){
new ApiError().generate(ex);
}
}
//--------------------------------------------------------------------------
public MainPanel(String title, Component comp) {
initComponents();
//start clock
setTimeLabel();
setDateLabel();
this.timer = new Timer(1000, clockUpdate);
timer.start();
setMainPanel(title, new ListStudent());
}
//--------------------------------------------------------------------------
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
contentPanel = new javax.swing.JPanel();
clockPanel = new javax.swing.JPanel();
clockLabel = new javax.swing.JLabel();
dateLabel = new javax.swing.JLabel();
panelViewTitle = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
jMenuItem4 = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
studentMenu = new javax.swing.JMenu();
studentListMenuItem = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
studentListMenuItem1 = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
exportMenuItem = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
contentPanel.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout contentPanelLayout = new javax.swing.GroupLayout(contentPanel);
contentPanel.setLayout(contentPanelLayout);
contentPanelLayout.setHorizontalGroup(
contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
contentPanelLayout.setVerticalGroup(
contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 376, Short.MAX_VALUE)
);
clockPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
clockLabel.setBackground(new java.awt.Color(255, 255, 255));
clockLabel.setText("2016-04-24 10:36:22");
clockLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
dateLabel.setBackground(new java.awt.Color(255, 255, 255));
dateLabel.setText("2016-04-24 10:36:22");
dateLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
panelViewTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout clockPanelLayout = new javax.swing.GroupLayout(clockPanel);
clockPanel.setLayout(clockPanelLayout);
clockPanelLayout.setHorizontalGroup(
clockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(clockPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(dateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelViewTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(clockLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
clockPanelLayout.setVerticalGroup(
clockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, clockPanelLayout.createSequentialGroup()
.addGroup(clockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clockLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(panelViewTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
fileMenu.setText("File");
jMenuItem4.setText("jMenuItem4");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
fileMenu.add(jMenuItem4);
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
studentMenu.setText("List");
studentListMenuItem.setText("Student List");
studentListMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
studentListMenuItemActionPerformed(evt);
}
});
studentMenu.add(studentListMenuItem);
jMenuItem1.setText("Parents List");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
studentMenu.add(jMenuItem1);
studentListMenuItem1.setText("Class List");
studentListMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
studentListMenuItem1ActionPerformed(evt);
}
});
studentMenu.add(studentListMenuItem1);
menuBar.add(studentMenu);
jMenu1.setText("Assessment");
jMenuItem5.setText("New Assessment");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem5);
jMenuItem6.setText("Assessment List");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem6);
menuBar.add(jMenu1);
jMenu2.setText("Reports");
exportMenuItem.setText("Export");
exportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportMenuItemActionPerformed(evt);
}
});
jMenu2.add(exportMenuItem);
jMenuItem2.setText("Report List");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem2);
menuBar.add(jMenu2);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(clockPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(contentPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(clockPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void studentListMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentListMenuItemActionPerformed
// TODO add your handling code here:
setMainPanel("Student List", new ListStudent());
}//GEN-LAST:event_studentListMenuItemActionPerformed
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void studentListMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentListMenuItem1ActionPerformed
// TODO add your handling code here:
setMainPanel("Class List", new ListClass());
}//GEN-LAST:event_studentListMenuItem1ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
// TODO add your handling code here:
setMainPanel("Parent List", new ListParent());
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
// JCalendar cal = new JCalendar();
// PopupFrame popup = new PopupFrame(cal.getDayChooser());
// popup.setSize(320, 230);
// popup.setVisible(true);
new PopupFrame(new UiCalendarPopup(), 320, 210).setVisible(true);
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void exportMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportMenuItemActionPerformed
// TODO add your handling code here:
new SetupReport().setVisible(true);
}//GEN-LAST:event_exportMenuItemActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
// TODO add your handling code here:
new AddAssessment().setVisible(true);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
// TODO add your handling code here:
new EditAssessment().setVisible(true);
}//GEN-LAST:event_jMenuItem6ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainPanel().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel clockLabel;
private javax.swing.JPanel clockPanel;
private javax.swing.JPanel contentPanel;
private javax.swing.JLabel dateLabel;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenuItem exportMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuBar menuBar;
private javax.swing.JLabel panelViewTitle;
private javax.swing.JMenuItem studentListMenuItem;
private javax.swing.JMenuItem studentListMenuItem1;
private javax.swing.JMenu studentMenu;
// End of variables declaration//GEN-END:variables
ActionListener clockUpdate = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTimeLabel();
setDateLabel();
}
};
public void setTimeLabel(){
clockLabel.setText(ApiDate.getDate(TIME));
}
public void setDateLabel(){
dateLabel.setText(ApiDate.getDate(DATE_CUSTOM_1));
}
public void setPanelTitle(String title){
panelViewTitle.setText(title);
}
public void setMainPanel(String title, Component comp){
contentPanel.removeAll();
contentPanel.setLayout(new BorderLayout());
contentPanel.add(comp);
contentPanel.revalidate();
contentPanel.repaint();
this.setPanelTitle(title);
this.setTitle(getSystemTitle(title));
}
}
|
package com.lucky.watisrain.map;
import java.util.List;
import com.lucky.watisrain.Global;
import com.lucky.watisrain.backend.data.Path;
import com.lucky.watisrain.backend.data.Waypoint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
/**
* This class handles drawing things to map-specific coordinates. This is necessary because
* by default, we can only draw to screen coordinates, which is not useful when we want
* an overlay over the map of the campus.
*/
public class MapDraw {
private Canvas canvas;
private RectF rct;
private float offset_x;
private float offset_y;
private float scale;
/**
* Constructs a MapDraw. This is specific to one rendering of the screen.
* @param canvas the canvas object to draw to
* @param displayRectangle the current field of view
*/
public MapDraw(Canvas canvas, RectF displayRectangle){
this.canvas = canvas;
rct = displayRectangle;
// Compute offsets given display rectangle
scale = (rct.right-rct.left) / Global.MAP_WIDTH * Global.MAP_ADJUST_SCALING;
offset_x = -rct.left + Global.MAP_ADJUST_X*scale;
offset_y = -rct.top + Global.MAP_ADJUST_Y*scale;
}
/**
* Draws a Path object, including all waypoints.
* @param linewidth the width of the path (in map relative pixels)
*/
public void drawPathOnMap(Path path, float linewidth, Paint paint){
List<Waypoint> wps = path.getWaypoints();
for(int i=0; i<wps.size()-1; i++){
drawLineOnMap(wps.get(i).getX(), wps.get(i).getY(), wps.get(i+1).getX(), wps.get(i+1).getY(), linewidth, paint);
}
}
/*
* More primitive routines here
*/
/**
* Draw a circle in map relative units
*/
public void drawCircleOnMap(float x, float y, float radius, Paint paint){
float adjust_x = x * scale - offset_x;
float adjust_y = y * scale - offset_y;
canvas.drawCircle(adjust_x, adjust_y, radius*scale, paint);
}
/**
* Draw a line in map relative units. The line goes from the point
* (x1,y1) to the point (x2,y2).
* @param linewidth how wide is the line (map relative pixels)
*/
public void drawLineOnMap(float x1, float y1, float x2, float y2, float linewidth, Paint paint){
// Don't draw a line from a point to itself. Doing so causes a
// problem on some devices.
if(x1 == x2 && y1 == y2)
return;
float adjust_x1 = x1 * scale - offset_x;
float adjust_y1 = y1 * scale - offset_y;
float adjust_x2 = x2 * scale - offset_x;
float adjust_y2 = y2 * scale - offset_y;
paint.setStrokeWidth(linewidth*scale);
canvas.drawLine(adjust_x1, adjust_y1, adjust_x2, adjust_y2, paint);
}
/**
* Draws a bitmap in map relative units. Assumes the image is square.
*/
public void drawImageOnMap(Bitmap bitmap, float x, float y, float width){
float adjust_x = x * scale - offset_x;
float adjust_y = y * scale - offset_y;
float scwidth = scale*width;
// Scale image down
int img_width = bitmap.getWidth();
int img_height = bitmap.getHeight();
Matrix scaleMatrix = new Matrix();
scaleMatrix.setRectToRect(
new RectF(0,0,img_width,img_height),
new RectF(adjust_x-scwidth/2,adjust_y-scwidth/2,adjust_x+scwidth/2,adjust_y+scwidth/2),
Matrix.ScaleToFit.CENTER);
canvas.drawBitmap(bitmap, scaleMatrix, null);
}
}
|
/**
* Project Name:WebScan
* File Name:DatabaseSourceDriver.java
* Package Name:databasesource
* Date:2014Äê1ÔÂ9ÈÕÏÂÎç9:20:13
* Copyright (c) 2014, hzycaicai@163.com All Rights Reserved.
*
*/
package databasesource;
import java.util.ArrayList;
/**
* ClassName:DatabaseSourceDriver
*
* @author hzycaicai
* @version
*/
public abstract class DatabaseSourceDriver {
public abstract DatabaseSource getNewDatabaseSource();
/*
* update the status of the items in the prefetch database
*/
public abstract void updateScanPlan(int fid, int status);
/*
* update the items in status 1 while not appear in checkresult database.
*/
public abstract void updateScanPlan(ArrayList<Integer> list);
}
|
package edunova;
public class Zadatak7 {
//Program učitava brojeve sve dok se ne pojavi broj -1
//program ispisuje zbroj svih primljenih brojeva
public static void main(String[] args) {
int ukupno=0;
int broj;
while(true) {
broj = Metode.ucitajBroj("Učitaj broj");
if(broj==-1) {
break;
}
ukupno+=broj;
}
System.out.println(ukupno);
}
}
|
package javasearch;
public class SearchException extends Exception {
private String msg;
public SearchException(final String msg) {
this.msg = msg;
}
public final String getMessage() {
return this.msg;
}
}
|
package HI;
import javax.swing.JFrame;
import javax.swing.JPanel;
import problemDomain.Sale;
import problemDomain.Session;
import problemDomain.Store;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PaymentEntry extends JPanel {
private JTextField textField;
private JTextField textField_1;
/**
* Create the panel.
*/
public PaymentEntry(JFrame frame, JPanel currentPanel, Sale sale, Session session) {
setLayout(null);
JLabel lblPayment = new JLabel("Payment");
lblPayment.setFont(new Font("Tahoma", Font.BOLD, 15));
lblPayment.setBounds(181, 0, 98, 19);
add(lblPayment);
JLabel lblPaymentDue = new JLabel("Payment Due:");
lblPaymentDue.setBounds(10, 37, 81, 14);
add(lblPaymentDue);
textField = new JTextField();
textField.setBounds(10, 62, 98, 20);
textField.setText(sale.calcTotal().toString());
add(textField);
textField.setColumns(10);
JLabel lblAmountTendered = new JLabel("Amount Tendered:");
lblAmountTendered.setBounds(10, 93, 109, 14);
add(lblAmountTendered);
textField_1 = new JTextField();
textField_1.setBounds(10, 118, 98, 20);
textField_1.setText(sale.calcAmtTendered().toString());
add(textField_1);
textField_1.setColumns(10);
JButton btnCash = new JButton("Cash");
btnCash.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.getContentPane().removeAll();
frame.getContentPane().add(new CashPaymentEntry(frame, currentPanel, sale, session));
frame.getContentPane().revalidate();
}
});
btnCash.setBounds(10, 169, 89, 23);
add(btnCash);
JButton btnCheck = new JButton("Check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
frame.getContentPane().add(new CheckPaymentEntry(frame, currentPanel, sale, session));
frame.getContentPane().revalidate();
}
});
btnCheck.setBounds(10, 203, 89, 23);
add(btnCheck);
JButton btnCredit = new JButton("Credit");
btnCredit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
frame.getContentPane().add(new CreditPaymentEntry(frame, currentPanel, sale, session));
frame.getContentPane().revalidate();
}
});
btnCredit.setBounds(10, 237, 89, 23);
add(btnCredit);
JButton btnPaymentComplete = new JButton("Payment Complete");
btnPaymentComplete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().removeAll();
frame.getContentPane().add(currentPanel);
frame.getContentPane().repaint();
}
});
if (sale.getTotalPayments().compareTo(sale.calcTotal()) < 0)
{
btnPaymentComplete.setEnabled(false);
}
else
{
btnPaymentComplete.setEnabled(true);
}
btnPaymentComplete.setBounds(149, 266, 151, 23);
add(btnPaymentComplete);
}
}
|
public class Main{
public static void main(String[] args) {
Volvo XC90 = new Volvo();
Volvo XC70 = new Volvo();
Volvo XC60 = new Volvo();
Volvo XC50 = new Volvo();
Volvo XC40 = new Volvo();
}
}
|
package com.cricmania.models;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.MongoException;
import net.vz.mongodb.jackson.JacksonDBCollection;
import play.modules.mongodb.jackson.MongoDB;
public class MetaDataDocument extends Base {
private Map<String,Long> table;
private static JacksonDBCollection<MetaDataDocument,String> coll = MongoDB.getCollection(MetaDataDocument.class.getSimpleName(), MetaDataDocument.class, String.class);
public Map<String, Long> getTable() {
return table;
}
public void setTable(Map<String, Long> table) {
this.table = table;
}
public static MetaDataDocument getMetaDataDocument() {
MetaDataDocument document = null;
try {
document = coll.findOneById("1");
} catch(MongoException e) {
document = new MetaDataDocument();
document.setId("1");
document.setTable(new HashMap<String,Long>());
coll.save(document);
}
if(document == null) {
document = new MetaDataDocument();
document.setId("1");
document.setTable(new HashMap<String,Long>());
coll.save(document);
}
return document;
}
public void update() {
coll.updateById(this.id,this);
}
public void save() {
coll.save(this);
}
public static String getGeneratedId(String className) {
MetaDataDocument document = MetaDataDocument.getMetaDataDocument();
Long id = document.getTable().get(className);
if(id == null) {
id = 1l;
} else {
id++;
}
document.getTable().put(className, id);
document.update();
return id.toString();
}
}
|
package com.brunocalou.guitarstudio;
import android.util.Log;
/**
* Created by bruno on 08/02/16.
*/
public class DistortionEffect extends Effect {
private final String LOG_TAG = "distortion_effect";
private int threshold;
DistortionEffect() {
nativePtr = _initNative();
}
public void setThreshold(int threshold) {
Log.d(LOG_TAG, "Set Threshold to " + threshold);
int max_16 = 32767;
if (threshold < 0) {
threshold = 0;
} else if (threshold > max_16) {
threshold = max_16;
}
this.threshold = threshold;
_setThreshold(getNativePtr(), threshold);
}
@Override
public void reload() {
super.reload();
if (getNativePtr() == 0) {
nativePtr = _initNative();
setThreshold(threshold);
}
}
public int getMaxThreshold() {
return 32767; //16 bits
}
public int getThreshold() {
Log.v(LOG_TAG, "Returning threshold = " + this.threshold);
return this.threshold;
}
public native void _setThreshold(long ptr, int threshold);
private native long _initNative();
}
|
package com.cyberdust.automation.utils;
import com.cyberdust.automation.application.AutomationUI;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DeviceReader {
private static boolean runningIOSSimulator;
private static boolean runningAndroidDevice;
private static boolean runningIOSDevice;
private static boolean IOSOverride;
private static boolean checkingDevice = true;
private static String connectedDevice;
private static String IOS_UDID;
public void checkDevice () throws Exception {
boolean connectedIOS = false;
boolean connectedAndroid = false;
String output;
runningIOSSimulator = false;
runningAndroidDevice = false;
runningIOSDevice = false;
ProcessBuilder processBuilder = new ProcessBuilder("system_profiler", "SPUSBDataType");
Process process = processBuilder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((output = stdInput.readLine()) != null) {
if (output.toLowerCase().contains("serial") && output.length() > 45) {
IOS_UDID = output.replace(" Serial Number: ", "");
}
if (output.toLowerCase().contains("iphone")) {
connectedIOS = true;
}
if (output.toLowerCase().contains("android")) {
connectedAndroid = true;
}
}
processBuilder = new ProcessBuilder(System.getenv("ANDROID_HOME")+"/platform-tools/adb", "devices");
process = processBuilder.start();
stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
if (!connectedIOS && !connectedAndroid) {
while ((output = stdInput.readLine()) != null) {
if (!output.contains("List of devices attached") && !output.isEmpty()) {
connectedAndroid = true;
connectedIOS = false;
}
}
}
if (System.getProperty("os.name").toLowerCase().contains("win")) {
runningAndroidDevice = true;
connectedDevice = "Android";
}
if ((IOSOverride && (connectedIOS || connectedAndroid)) || (!connectedIOS && !connectedAndroid)) {
runningIOSSimulator = true;
connectedDevice = "iOS Simulator";
}
if (!IOSOverride && connectedIOS && !connectedAndroid) {
runningIOSDevice = true;
connectedDevice = "iPhone";
}
if (!IOSOverride && connectedAndroid) {
runningAndroidDevice = true;
connectedDevice = "Android";
}
}
public static void runDeviceWorker() {
SwingWorker<Void, Void> deviceWorker = new SwingWorker<Void, Void>() {
DeviceReader reader = new DeviceReader();
public Void doInBackground() throws Exception {
while (checkingDevice) {
try {
Thread.sleep(1000);
reader.checkDevice();
AutomationUI.setCurrentDevice(connectedDevice);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
};
deviceWorker.execute();
}
public static boolean isRunningIOSSimulator() {
return runningIOSSimulator;
}
public static boolean isRunningAndroidDevice() {
return runningAndroidDevice;
}
public static boolean isRunningIOSDevice() {
return runningIOSDevice;
}
public static boolean isCheckingDevice() {
return checkingDevice;
}
public static String getConnectedDevice() {
return connectedDevice;
}
public static String getIOSUdid() {
return IOS_UDID;
}
public static void setIOSOverride(boolean IOSOverride) {
DeviceReader.IOSOverride = IOSOverride;
}
}
|
package animatronics.api.energy;
public interface ITETransfersEntropy extends ITEHasEntropy {
}
|
package com.ews;
import com.ews.creativetabs.EwsTab;
import com.ews.init.ModRecipes;
import com.ews.proxy.CommonProxy;
import com.ews.util.Reference;
import com.ews.world.ModWorldGen;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod(modid = Reference.MOD_ID, name = Reference.NAME, version = Reference.VERSION, dependencies = "redstoneflux" )
public class Main {
public static final EwsTab EWS_TAB = new EwsTab();
@Instance
public static Main instance;
@SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.COMMON_PROXY_CLASS)
public static CommonProxy proxy;
@EventHandler
public static void PreInit(FMLPreInitializationEvent event)
{
GameRegistry.registerWorldGenerator(new ModWorldGen(), 3);
}
@EventHandler
public static void init(FMLInitializationEvent event)
{
ModRecipes.init();
}
@EventHandler
public static void PostInit(FMLPostInitializationEvent event)
{
}
}
|
package org.zz.jni;
public class mxImageTool {
static {
System.loadLibrary("mxImageTool");
}
/****************************************************************************
功 能:获取算法信息
参 数:
返回:算法信息
*****************************************************************************/
static public native void ImageToolVersion(byte[] szVersion);
/*******************************************************************************************
功 能: 图像文件加载到内存
参 数: szLoadFilePath - 输入 图像路径
iChannels - 输入 图像通道数,1-加载为灰度图像,3-加载为RGB图像
pImgBuf - 输出 外部图像缓冲区,用于接收图像数据,如果为NULL,则不接收
oImgWidth - 输出 图像宽度
oImgHeight - 输出 图像高度
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int ImageLoad(String szLoadFilePath, int iChannels,
byte[] pImgBuf, int[] oImgWidth, int[] oImgHeight);
/*******************************************************************************************
功 能: 保存图像数据
参 数: szSaveFilePath - 输入 保存图像路径
pImgBuf - 输入 图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iChannels - 输入 图像通道
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int ImageSave(String szSaveFilePath,
byte[] pImgBuf, int iImgWidth, int iImgHeight, int iChannels);
/*******************************************************************************************
功 能: YUV数据转换为RGB数据(Android摄像头获取的数据为YUV格式)
参 数: pYUVImage - 输入 YUV图像数据
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
pRGBImage - 输出 RGB图像数据
返 回: 1-成功,其他-失败
备 注: https://www.cnblogs.com/snailgardening/p/opencv_yuv_rgb.html
*******************************************************************************************/
static public native void YUV2RGB(byte[] pYUVImage, int iImgWidth, int iImgHeight,
byte[] pRGBImage);
/*******************************************************************************************
功 能: RGB图像数据转换为灰度图像数据
参 数: pRGBImage - 输入 RGB图像数据
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
pGrayImage - 输出 灰度图像数据
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native void RGB2GRAY(byte[] pRGBImage, int iImgWidth, int iImgHeight, byte[] pGrayImage);
/*******************************************************************************************
功 能: 对输入图像根据输入的目标宽度进行按比例缩放。
参 数: pImgBuf - 输入 图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iChannels - 输入 图像通道
iDstImgWidth - 输入 目标图像宽度
iDstImgHeight - 输入 目标图像高度
pDstImgBuf - 输出 目标图像缓冲区
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int Zoom(byte[] pImgBuf, int iImgWidth, int iImgHeight, int iChannels,
int iDstImgWidth, int iDstImgHeight, byte[] pDstImgBuf);
/*******************************************************************************************
功 能: 在输入的RGB图像上根据输入的Rect绘制矩形框
参 数: pRgbImgBuf - 输入 RGB图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iRect - 输入 Rect[0] =x;
Rect[1] =y;
Rect[2] =width;
Rect[3] =height;
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int DrawRect(byte[] pRgbImgBuf, int iImgWidth, int iImgHeight, int[] iRect);
/*******************************************************************************************
功 能: 在输入的RGB图像上根据输入的点坐标绘制点
参 数: pRgbImgBuf - 输入 RGB图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iPointPos - 输入 点坐标序列(x1,y1,x2,y2,...)
iPointNum - 输入 点个数
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int DrawPoint(byte[] pRgbImgBuf, int iImgWidth, int iImgHeight,
int[] iPointPos, int iPointNum);
/*******************************************************************************************
功 能: 在输入的RGB图像上根据输入的点坐标绘制点序号
参 数: pRgbImgBuf - 输入 RGB图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iPointX - 输入 指定位置的X坐标
iPointY - 输入 指定位置的Y坐标
szText - 输入 显示文字
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int DrawText(byte[] pRgbImgBuf, int iImgWidth, int iImgHeight,
int iPointX, int iPointY, String szText);
/*******************************************************************************************
功 能: 图像文件数据转换为RGB24内存数据
参 数: pFileDataBuf - 输入 图像文件数据
iFileDataLen - 输入 图像文件数据长度
pRGB24Buf - 输出 RGB24内存数据
iWidth - 输出 图像宽度
iHeight - 输出 图像高度
返 回: >=0成功,其他-失败
*******************************************************************************************/
static public native int ImageDecode(byte[] pFileDataBuf, int iFileDataLen,
byte[] pRGB24Buf, int[] iWidth, int[] iHeight);
/*******************************************************************************************
功 能: RGB24内存数据转换为图像文件数据
参 数: pRGB24Buf - 输入 RGB24内存数据
iWidth - 输入 图像宽度
iHeight - 输入 图像高度
szTpye - 输入 文件后缀,比如.jpg;.bmp
pFileDataBuf - 输出 图像文件数据
iFileDataLen - 输出 图像文件数据长度
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int ImageEncode(byte[] pRGB24Buf, int iWidth, int iHeight,
String szTpye, byte[] pFileDataBuf, int[] iFileDataLen);
/*******************************************************************************************
功 能: 输入的RGB图像,进行顺时针90/180/270角度旋转
参 数: pRgbImgBuf - 输入 RGB图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iAngle - 输入,角度90/180/270
pDstImgBuf - 输出 RGB图像缓冲区
iDstWidth - 输出 图像宽度
iDstHeight - 输出 图像高度
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int ImageRotate(byte[] pRgbImgBuf, int iImgWidth, int iImgHeight, int iAngle,
byte[] pDstImgBuf, int[] iDstWidth, int[] iDstHeight);
/*******************************************************************************************
功 能: 输入的RGB图像,进行镜像
参 数: pRgbImgBuf - 输入 RGB图像缓冲区
iImgWidth - 输入 图像宽度
iImgHeight - 输入 图像高度
iIndex - 输入, >0: 沿y-轴翻转, 0: 沿x-轴翻转, <0: x、y轴同时翻转
pDstImgBuf - 输出 RGB图像缓冲区
返 回: 1-成功,其他-失败
*******************************************************************************************/
static public native int ImageFlip(byte[] pRgbImgBuf, int iImgWidth, int iImgHeight, int iIndex,
byte[] pDstImgBuf);
}
|
package com.gestion.villes;
public class Ville {
private String Nom_Ville;
private int Nombre_habitants;
private int[] Precipitation_Mensuel = new int[12];
private int[] Temperature_Mensuel = new int[12];
public Ville(){
}
public Ville(String Nom_Ville, int Nombre_habitants, int[] Precipitation_Mensuel, int[] Temperature_Mensuel){
this.Nom_Ville = Nom_Ville;
this.Nombre_habitants = Nombre_habitants;
this.Precipitation_Mensuel = Precipitation_Mensuel;
this.Temperature_Mensuel = Temperature_Mensuel;
}
public String getNom_Ville() {
return Nom_Ville;
}
public void setNom_Ville(String nom_Ville) {
Nom_Ville = nom_Ville;
}
public int getNombre_habitants() {
return Nombre_habitants;
}
public void setNombre_habitants(int nombre_habitants) {
Nombre_habitants = nombre_habitants;
}
public int[] getPrecipitation_Mensuel() {
return Precipitation_Mensuel;
}
public void setPrecipitation_Mensuel(int[] precipitation_Mensuel) {
this.Precipitation_Mensuel = precipitation_Mensuel;
}
public int[] getTemperature_Mensuel() {
return Temperature_Mensuel;
}
public void setTemperature_Mensuel(int[] temperature_Mensuel) {
Temperature_Mensuel = temperature_Mensuel;
}
private float moyenneP = 0;
private float moyenneT = 0;
private int maxiP = 0;
private int maxiT = 0;
public float moyennePrecipitation(){
for (int P: Precipitation_Mensuel){
moyenneP += P;
}
return moyenneP/12;
}
public float moyenneTemperature(){
for (int T: Temperature_Mensuel) {
moyenneT += T;
}
return moyenneT/12;
}
public int maxPrecipitation(){
for (int P: Precipitation_Mensuel) {
if (P > maxiP){
maxiP = P;
}
}
return maxiP;
}
public int maxTemperature(){
for (int T: Temperature_Mensuel){
if (T > maxiT){
maxiT = T;
}
}
return maxiT;
}
@Override
public String toString() {
return "Ville [ Nom ville : " + Nom_Ville + ", Nombre habitants : " + Nombre_habitants + ", Précipitation moyenne : " + moyennePrecipitation() +
", Température moyenne : " + moyenneTemperature() + ", Précipitation maximum : " + maxPrecipitation() + ", Température maximum : " +
maxTemperature() + "]";
}
}
|
package com.summer.web.basic.context;
/**
* 微服务名称
*
* @author luke
*/
public enum SummerServiceEnum {
S_1001(1001, "用户服务"),
S_1004(1004, "订单服务"),
;
private int code;
private String name;
SummerServiceEnum(int code, String name) {
this.code = code;
this.name = name;
}
public static SummerServiceEnum get(int code) {
for (SummerServiceEnum codeEnum : values()) {
if (codeEnum.code == code) {
return codeEnum;
}
}
return null;
}
public int getCode() {
return this.code;
}
public String getName() {
return this.name;
}
}
|
package com.tencent.mm.plugin.websearch;
import com.tencent.mm.a.e;
import com.tencent.mm.g.a.bc;
import com.tencent.mm.plugin.websearch.api.p;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
class PluginWebSearch$3 extends c<bc> {
final /* synthetic */ PluginWebSearch pKx;
PluginWebSearch$3(PluginWebSearch pluginWebSearch) {
this.pKx = pluginWebSearch;
this.sFo = bc.class.getName().hashCode();
}
private boolean a(bc bcVar) {
Throwable e;
int intValue;
if (bcVar != null && bcVar.bIB.bIC == 27) {
if (bcVar.bIB.bID == 2 && !PluginWebSearch.checkTopStoryTemplateFolderValid()) {
PluginWebSearch.access$200(bcVar.bIB.bID, 12);
}
String zU = p.zU(bcVar.bIB.bID);
String zV = p.zV(bcVar.bIB.bID);
int zW = p.zW(bcVar.bIB.bID);
if (!(bi.oW(zU) || bi.oW(zV))) {
File file = new File(bcVar.bIB.filePath);
if (file.exists()) {
x.i("MicroMsg.WebSearch.PluginWebSearch", "checkResUpdateListener callback to update %s", new Object[]{file.getAbsoluteFile()});
File file2 = new File(zU, "temp");
File file3 = new File(file2, zV);
file2.mkdirs();
e.y(file.getAbsolutePath(), file3.getAbsolutePath());
int fR = bi.fR(file3.getAbsolutePath(), file2.getAbsolutePath());
if (fR >= 0) {
Properties properties = new Properties();
InputStream fileInputStream;
try {
fileInputStream = new FileInputStream(new File(file2, "config.conf"));
try {
properties.load(fileInputStream);
e.f(fileInputStream);
} catch (Exception e2) {
e = e2;
try {
x.printErrStackTrace("MicroMsg.WebSearch.PluginWebSearch", e, e.getMessage(), new Object[0]);
e.f(fileInputStream);
intValue = Integer.valueOf(properties.getProperty("version", "1")).intValue();
e.k(file2);
if (zW < intValue) {
if (fR >= 0) {
PluginWebSearch.access$200(bcVar.bIB.bID, 13);
} else {
PluginWebSearch.access$200(bcVar.bIB.bID, 11);
}
x.i("MicroMsg.WebSearch.PluginWebSearch", "res no need update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
} else {
PluginWebSearch.access$200(bcVar.bIB.bID, 9);
x.i("MicroMsg.WebSearch.PluginWebSearch", "res update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
PluginWebSearch.access$300(this.pKx, file, bcVar.bIB.bID);
}
return false;
} catch (Throwable th) {
e = th;
e.f(fileInputStream);
throw e;
}
}
} catch (Exception e3) {
e = e3;
fileInputStream = null;
x.printErrStackTrace("MicroMsg.WebSearch.PluginWebSearch", e, e.getMessage(), new Object[0]);
e.f(fileInputStream);
intValue = Integer.valueOf(properties.getProperty("version", "1")).intValue();
e.k(file2);
if (zW < intValue) {
PluginWebSearch.access$200(bcVar.bIB.bID, 9);
x.i("MicroMsg.WebSearch.PluginWebSearch", "res update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
PluginWebSearch.access$300(this.pKx, file, bcVar.bIB.bID);
} else {
if (fR >= 0) {
PluginWebSearch.access$200(bcVar.bIB.bID, 13);
} else {
PluginWebSearch.access$200(bcVar.bIB.bID, 11);
}
x.i("MicroMsg.WebSearch.PluginWebSearch", "res no need update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
}
return false;
} catch (Throwable th2) {
e = th2;
fileInputStream = null;
e.f(fileInputStream);
throw e;
}
intValue = Integer.valueOf(properties.getProperty("version", "1")).intValue();
} else {
intValue = 1;
}
e.k(file2);
if (zW < intValue) {
PluginWebSearch.access$200(bcVar.bIB.bID, 9);
x.i("MicroMsg.WebSearch.PluginWebSearch", "res update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
PluginWebSearch.access$300(this.pKx, file, bcVar.bIB.bID);
} else {
if (fR >= 0) {
PluginWebSearch.access$200(bcVar.bIB.bID, 13);
} else {
PluginWebSearch.access$200(bcVar.bIB.bID, 11);
}
x.i("MicroMsg.WebSearch.PluginWebSearch", "res no need update template subtype:%d currentVersion:%d resVersion:%d", new Object[]{Integer.valueOf(bcVar.bIB.bID), Integer.valueOf(zW), Integer.valueOf(intValue)});
}
} else {
x.e("MicroMsg.WebSearch.PluginWebSearch", "checkResUpdateListener file not exist");
}
}
}
return false;
}
}
|
/*
* 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 Format;
/**
*
* @author Michi
*/
public class TextFormat {
public static String GetIntWithLeadingZeros(int number, int length){
int i = 1;
int tmpNumber = number;
while(tmpNumber / 10 > 0){
i++;
tmpNumber = tmpNumber / 10;
}
if(i >= length)
return number + "";
else
{
StringBuilder b = new StringBuilder(length);
for(int k = 0; k < length-i; k++)
b.append("0");
b.append(number);
return b.toString();
}
}
}
|
package com.general;
import com.general.eventSystem.Event;
import com.general.eventSystem.EventDispatcher;
import com.general.eventSystem.EventListener;
import java.util.Queue;
public abstract class AbstractElevator<E extends Event, P> implements EventListener<E> {
private Queue<E> eventQueue;
private P property;
private ElevatorStatus currentStatus;
private int currentFloor = 0;
private EventDispatcher dispatcher;
public AbstractElevator(EventDispatcher dispatcher, Queue<E> eventQueue, P property) {
this.dispatcher = dispatcher;
this.eventQueue = eventQueue;
this.property = property;
this.currentStatus = ElevatorStatus.Hold;
}
// process queue
public void process() {
}
protected final P getProperty() {
return property;
}
protected final ElevatorStatus getCurrentStatus() {
return currentStatus;
}
protected final void setCurrentStatus(ElevatorStatus currentStatus) {
this.dispatcher.emitMessageAsync(String.format("Status %s", currentStatus.toString()));
this.currentStatus = currentStatus;
}
protected final int getCurrentFloor() {
return currentFloor;
}
protected final void setCurrentFloor(int currentFloor) {
this.dispatcher.emitMessageAsync(String.format("Floor %d", currentFloor));
this.currentFloor = currentFloor;
}
protected final Queue<E> getEventQueue() {
return eventQueue;
}
public final EventDispatcher getDispatcher() {
return dispatcher;
}
public static void sleep(int value) {
try {
Thread.sleep(value);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Override
public synchronized void onEvent(E event) {
dispatcher.emitMessageAsync(String.format("Dispatched event %s%n", event));
if (!eventQueue.contains(event)) {
eventQueue.add(event);
process();
}
}
}
|
package org.firstinspires.ftc.teamcode;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.DogeCV;
import com.disnodeteam.dogecv.detectors.roverrukus.GoldAlignDetector;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
//this is a test for github - please ignore
@Autonomous(name = "NO TOUCHY! BS", group = "Autonomous")
//@Disabled
public class BlueSilver13475 extends LinearOpMode {
private GoldAlignDetector detector;
private DcMotor leftDrive = null;
private DcMotor rightDrive = null;
private DcMotor landerRiser1 = null;
private DcMotor landerRiser2 = null;
private Servo flippy = null;
private ElapsedTime runtime = new ElapsedTime();
static final double COUNTS_PER_MOTOR_REV = 1220; // eg: TETRIX Motor Encoder
static final double DRIVE_GEAR_REDUCTION = 1.0; // This is < 1.0 if geared UP
static final double WHEEL_DIAMETER_INCHES = 4.0; // For figuring circumference
static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
(WHEEL_DIAMETER_INCHES * 3.1415);
static final double DRIVE_SPEED = 0.6;
static final double TURN_SPEED = 0.5;
static final double RISER_SPEED = 0.5;
@Override
public void runOpMode() {
setUp();
waitForStart();
//the following code isn't ready for qualifiers :(
//instead, we will drive to crater, drop derky derk, and run for sweet life
if(detector.getXPosition()>=0 && (detector.getXPosition()<229)){
//left
detector.disable();
encoderDrive(1,0,0,3,5.5);
encoderDrive(.3, -2.5, -2.5, -30, 5.0);
encoderDrive(.3, 3, -3, 0, 5.0);
encoderDrive(.3, 3.5, 3.5, 0, 5.0);
encoderDrive(.3, -3, 3, 0, 5.0);
/*
encoderDrive(DRIVE_SPEED, -13.5, 13.5, 0, 5.0);//turn to face balls
encoderDrive(DRIVE_SPEED, 3, 3, 0, 5.0);//not totlly sure why this is here tbh
encoderDrive(DRIVE_SPEED, 7.5, -7.5, 0, 5.0);//turn 60
encoderDrive(DRIVE_SPEED, 18, 18, 0, 5.0); //move to ball 1
encoderDrive(DRIVE_SPEED, 10, -10, 0, 5.0);//turn 60 (was 7.5)
//encoderDrive(DRIVE_SPEED, 15, 15, 0, 5.0);//onward
*/
//code that should work faster and more effective maybe
encoderDrive(DRIVE_SPEED, 11, -11, 0, 5.0);//turn to face balls
encoderDrive(.3, -9, -9, 0, 5.0);//move into intersection
encoderDrive(DRIVE_SPEED, -11.5, 11.5, 0, 5.0);//turn
encoderDrive(DRIVE_SPEED, 11, 11, 0, 5.0);//move to ball
encoderDrive(DRIVE_SPEED, 11.5, -11.5, 0, 5.0);//turn to face ball
encoderDrive(.3, -7, -7, 0, 5.0);//hit ball
encoderDrive(DRIVE_SPEED, 4, 4, 0, 5.0);//return
encoderDrive(DRIVE_SPEED, -11.5, 11.5, 0, 5.0);//turn to backup
encoderDrive(DRIVE_SPEED, -60, -60, 0, 5.0);//backup
encoderDrive(DRIVE_SPEED, -6, 6, 0, 5.0);//turn 60
encoderDrive(DRIVE_SPEED, -30, -30, 0, 5.0);//backup
/*
//encoderDrive(DRIVE_SPEED, 5, -5, 0, 5.0);//turn to hit ball
encoderDrive(.2, -5.25, -5.25, 0, 5.0);//hit ball
encoderDrive(DRIVE_SPEED, 6, 6, 0, 5.0);//reverse
encoderDrive(DRIVE_SPEED, -6, 6, 0, 5.0);//turn (was 6)
encoderDrive(DRIVE_SPEED, -60, -60, 0, 5.0);//backup
encoderDrive(DRIVE_SPEED, -6, 6, 0, 5.0);//turn 60
encoderDrive(DRIVE_SPEED, -30, -30, 0, 5.0);//backup
encoderDrive(DRIVE_SPEED, -24, 24, 0, 5.0);
flippy.setPosition(0);
sleep(1000);
flippy.setPosition(1);
encoderDrive(DRIVE_SPEED, 44, 44, 0, 5.0);//backup
*/
}
else if((detector.getXPosition()>=230) && (detector.getXPosition()<449)){
//middle
detector.disable();
//code to disembark:
encoderDrive(1,0,0,3,5.5);
encoderDrive(.3, -2.5, -2.5, 0, 5.0);
encoderDrive(.3, 3, -3, -3, 5.0);
encoderDrive(.3, 3.5, 3.5, 0, 5.0);
encoderDrive(.3, -3, 3, 0, 5.0);
encoderDrive(DRIVE_SPEED, 11, -11, 0, 5.0);//turn to face balls
encoderDrive(.3, -17, -17, 0, 5.0);//hit mid ball
encoderDrive(DRIVE_SPEED, 5, 5, 0, 5.0);//return
encoderDrive(DRIVE_SPEED, -11.5, 11.5, 0, 5.0);//turn to backup
encoderDrive(DRIVE_SPEED, -46, -46, 0, 5.0);//backup
encoderDrive(DRIVE_SPEED, -6, 6, 0, 5.0);//turn 60
encoderDrive(DRIVE_SPEED, -25, -25, 0, 5.0);//backup
flippy.setPosition(0);
sleep(1000);
flippy.setPosition(1);
encoderDrive(DRIVE_SPEED, 48, 48, 0, 5.0);//backup
}
else if(detector.getXPosition()>=450){
//right
detector.disable();
encoderDrive(1,0,0,3,5.5);
encoderDrive(.3, -2.5, -2.5, 0, 5.0);
encoderDrive(.3, 3, -3, -3, 5.0);
encoderDrive(.3, 3.5, 3.5, 0, 5.0);
encoderDrive(.3, -3, 3, 0, 5.0);
encoderDrive(DRIVE_SPEED, 11, -11, 0, 5.0);//turn to face balls
encoderDrive(.3, -9, -9, 0, 5.0);//move into intersection
encoderDrive(DRIVE_SPEED, -11.5, 11.5, 0, 5.0);//turn
encoderDrive(DRIVE_SPEED, -11, -11, 0, 5.0);//move to ball
encoderDrive(DRIVE_SPEED, 11.5, -11.5, 0, 5.0);//turn to face ball
encoderDrive(.3, -7, -7, 0, 5.0);//hit ball
encoderDrive(DRIVE_SPEED, 4, 4, 0, 5.0);//return
encoderDrive(DRIVE_SPEED, -11.5, 11.5, 0, 5.0);//turn to backup
encoderDrive(DRIVE_SPEED, -35, -35, 0, 5.0);//backup
encoderDrive(DRIVE_SPEED, -6, 6, 0, 5.0);//turn 60
encoderDrive(DRIVE_SPEED, -27, -27, 0, 5.0);//backup
flippy.setPosition(0);
sleep(1000);
flippy.setPosition(1);
encoderDrive(DRIVE_SPEED, 48, 48, 0, 5.0);//backup
}
}
/*
* Method to perfmorm a relative move, based on encoder counts.
* Encoders are not reset as the move is based on the current position.
* Move will stop if any of three conditions occur:
* 1) Move gets to the desired position
* 2) Move runs out of time
* 3) Driver stops the opmode running.
*/
public void encoderDrive(double speed,
double leftInches, double rightInches, double riser,
double timeoutS) {
int newLeftTarget;
int newRightTarget;
int newRiserTarget;
// Ensure that the opmode is still active
if (opModeIsActive()) {
// Determine new target position, and pass to motor controller
newLeftTarget = leftDrive.getCurrentPosition() + (int) (leftInches * COUNTS_PER_INCH);
newRightTarget = rightDrive.getCurrentPosition() + (int) (rightInches * COUNTS_PER_INCH);
newRiserTarget = landerRiser1.getCurrentPosition() + (int) (riser * COUNTS_PER_INCH);
//newRiserTarget = landerRiser2.getCurrentPosition() + (int) (riser * COUNTS_PER_INCH);
leftDrive.setTargetPosition(newLeftTarget);
rightDrive.setTargetPosition(newRightTarget);
landerRiser1.setTargetPosition(newRiserTarget);
landerRiser2.setTargetPosition(newRiserTarget);
// Turn On RUN_TO_POSITION
leftDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
rightDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
landerRiser1.setMode(DcMotor.RunMode.RUN_TO_POSITION);
landerRiser2.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
leftDrive.setPower(Math.abs(speed));
rightDrive.setPower(Math.abs(speed));
landerRiser1.setPower(Math.abs(speed));
landerRiser2.setPower(Math.abs(speed));
// keep looping while we are still active, and there is time left, and both motors are running.
// Note: We use (isBusy() && isBusy()) in the loop test, which means that when EITHER motor hits
// its target position, the motion will stop. This is "safer" in the event that the robot will
// always end the motion as soon as possible.
// However, if you require that BOTH motors have finished their moves before the robot continues
// onto the next step, use (isBusy() || isBusy()) in the loop test.
while (opModeIsActive() &&
(runtime.seconds() < timeoutS) &&
(leftDrive.isBusy() && rightDrive.isBusy() || landerRiser1.isBusy())) {
// Display it for the driver.
telemetry.addData("Path1", "Running to %7d :%7d :%7d", newLeftTarget, newRightTarget, newRiserTarget);
telemetry.addData("Path2", "Running at %7d :%7d :%7d",
leftDrive.getCurrentPosition(),
rightDrive.getCurrentPosition(),
landerRiser1.getCurrentPosition());
telemetry.update();
}
// Stop all motion;
leftDrive.setPower(0);
rightDrive.setPower(0);
landerRiser1.setPower(0);
landerRiser2.setPower(0);
// Turn off RUN_TO_POSITION
leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
landerRiser1.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
landerRiser2.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// sleep(250); // optional pause after each move
}
}
private void setUp() {
/*
* Initialize the drive system variables.
* The init() method of the hardware class does all the work here
*/
leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
landerRiser1 = hardwareMap.get(DcMotor.class, "lander_riser1");
landerRiser2 = hardwareMap.get(DcMotor.class, "lander_riser2");
flippy= hardwareMap.servo.get("flippy_flipper");
leftDrive.setDirection(DcMotor.Direction.FORWARD);
rightDrive.setDirection(DcMotor.Direction.REVERSE);
// Send telemetry message to signify robot waiting;
telemetry.addData("Status", "Resetting Encoders");
telemetry.update();
leftDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
landerRiser1.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
landerRiser2.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
landerRiser1.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
landerRiser2.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// Send telemetry message to indicate successful Encoder reset
telemetry.addData("Path0", "Starting at %7d :%7d :%7d",
leftDrive.getCurrentPosition(),
rightDrive.getCurrentPosition(),
landerRiser1.getCurrentPosition());
telemetry.update();
//DodeCV stuff
// Set up detector
telemetry.addData("Status", "DogeCV 2018.0 - Gold Align Example");
// Set up detector
detector = new GoldAlignDetector(); // Create detector
detector.init(hardwareMap.appContext, CameraViewDisplay.getInstance()); // Initialize it with the app context and camera
detector.useDefaults(); // Set detector to use default settings
// Optional tuning
detector.alignSize = 100; // How wide (in pixels) is the range in which the gold object will be aligned. (Represented by green bars in the preview)
detector.alignPosOffset = 0; // How far from center frame to offset this alignment zone.
detector.downscale = 0.4; // How much to downscale the input frames
detector.areaScoringMethod = DogeCV.AreaScoringMethod.MAX_AREA; // Can also be PERFECT_AREA
//detector.perfectAreaScorer.perfectArea = 10000; // if using PERFECT_AREA scoring
detector.maxAreaScorer.weight = 0.005; //
detector.ratioScorer.weight = 5; //
detector.ratioScorer.perfectRatio = 1.0; // Ratio adjustment
detector.enable(); // Start the detector!
}
}
|
package banyuan.day05.practice.p01;
/*
1.interface Inter{void show();}
class Outer{ 你的代码; }
class OuterDemo{
public static void main(String[] args){
Outer.method().show();
}
}
*/
/**
* @author newpc
*/
public interface Inter {
void show();
}
|
package com.teaman.data;
/**
* <h1> User </h1>
* <p>
* Interface containing methods to return user data
* </p>
*
* @author Aaron Weaver
* Team Andronerds
* waaronl@okstate.edu
* @version 1.0
* @since 1/30/16
*/
public interface User {
// String constants for columns within the user db.
static final String FIRST_NAME = "firstName";
static final String LAST_NAME = "lastName";
static final String PROFILE_PICTURE = "profilePicture";
static final String AUDITORY_DISABILITY = "auditoryDisability";
static final String PHYSICAL_DISABILITY = "physicalDisability";
static final String VISUAL_DISABILITY = "visualDisability";
/**
* Retrieve username from User.
*
* @return User's username
*/
String getUsername();
/**
* Retrieve email from User.
*
* @return User's email
*/
String getEmail();
/**
* Retrieve display name of User.
*
* @return User's display name
*/
String getDisplayName(boolean lastNameOnlyInitial);
/**
* Retrieve the first name of a given User.
*
* @return User's first name
*/
String getFirstName();
/**
* Retrieve the last name of a given User.
*
* @return User's last name
*/
String getLastName();
String getUserAvatar();
boolean hasAuditoryDisability();
boolean hasVisualDisability();
boolean hasPhysicalDisability();
}
|
package twosumII;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public List<List<Integer>> allPairs(int[] array, int target) {
// Write your solution here.
List<List<Integer>> result = new ArrayList<List<Integer>>();
//Map<number,count>
Map<Integer, Integer> map = new HashMap<>();
for(int num : array){
Integer count = map.get(num);
if(num * 2 == target && count != null && count == 1){
result.add(Arrays.asList(num,num));
}
//prevent from dup, so count == null condition
if(map.containsKey(target - num) && count == null){
result.add(Arrays.asList(target - num, num));
}
if(count == null){
map.put(num, 1);
}else{
map.put(num, 1 + count);
}
}
return result;
}
}
|
package ua.kpi.tef;
import java.util.Scanner;
/**
* Created by User on 17.03.2016.
*/
public class Controller {
// The Constants
public static final double PI = 3.14;
public static final int FOUR = 4;
// The Regex
// ?nick@mail.com?
public static final String REGEX_MAIL = "^([a-z0-9_-]+\\.)*[a-z0-9_-]+@[a-z0-9_-]+(\\.[a-z0-9_-]+)*\\.[a-z]{2,6}$";
// ?http://www.my-site.com?
public static final String REGEX_URL = "^((https?|ftp)\\:\\/\\/)?([a-z0-9]{1})((\\.[a-z0-9-])|([a-z0-9-]))*\\.([a-z]{2,6})(\\/?)$";
// ?+38(044)555-55-55?
public static final String REGEX_PHONE = "^\\+\\d{2}\\(\\d{3}\\)\\d{3}-\\d{2}-\\d{2}$";
public static final String HELLO = "Hello";
public static final String WORLD = "world!";
// Constructor
private Model model;
private View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
}
// The Work method
public void processUser() {
Scanner sc = new Scanner(System.in);
view.printMessage(View.INPUT_DATA);
model.setWord(0, inputValueWithScanner(sc, HELLO));
model.setWord(1, inputValueWithScanner(sc, WORLD));
model.makeSentence();
view.printMessageAndValue(View.OUR_SENTENCE, model.getSentence());
}
// The Utility methods
public String inputValueWithScanner(Scanner sc, String correctValue) {
String value = sc.next();
if (!value.equals(correctValue)) {
view.printMessage(View.WRONG_INPUT_DATA + View.INPUT_DATA);
return "";
}
return value;
}
}
|
package ru.netology.web.data;
import com.github.javafaker.Faker;
import lombok.NoArgsConstructor;
import lombok.Value;
@NoArgsConstructor
public class DataHelper {
@Value
public static class AuthInfo {
String login;
String password;
}
public static AuthInfo getAuthInfo() {
return new AuthInfo("vasya", "qwerty123");
}
public static AuthInfo getInvalidLoginForAuth() {
Faker faker = new Faker();
return new AuthInfo(faker.name().firstName(), "qwerty123");
}
public static AuthInfo getInvalidPasswordForAuth() {
Faker faker = new Faker();
return new AuthInfo("vasya", faker.internet().password());
}
@Value
public static class VerificationCode {
String code;
}
public static String getInvalidVerificationCode() {
return "765756756756756";
}
}
|
package javaPractice2;
public class CountEvenAndCountOdd {
public static void main(String[] args) {
int num=12345;
int ecount=0;
int ocount=0;
int check;
while(num>0){
check=num%10;
num=num/10;
if(check%2==0) {
ecount++;
}else{
ocount++;
}}
System.out.println("ecount ="+ecount+","+"ocount ="+ocount);
}
}
|
package com.rk.dp.structural.flyweight;
public class FlyweightMain {
// Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint.
// Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object
// when no matching object is found.
public static void main(String[] args) {
// TODO Auto-generated method stub
ShapeFactory sf = new ShapeFactory();
Circle circle1 = sf.getCircle("Red");
circle1.draw();
Circle circle2 = sf.getCircle("Red");
circle2.draw();
Circle circle3 = sf.getCircle("Green");
circle3.draw();
Circle circle4 = sf.getCircle("Blue");
circle4.draw();
Circle circle5 = sf.getCircle("Brown");
circle5.draw();
}
}
|
package chatroom.model.message;
public abstract class UserMessage extends Message implements Displayable {
protected String sender;
public String getSender(){
return sender;
}
}
|
package jonceski.kliment.googlecertprepare.ui;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import jonceski.kliment.googlecertprepare.R;
import jonceski.kliment.googlecertprepare.data.WeatherDayTable;
import jonceski.kliment.googlecertprepare.data.WeatherDbHelper;
import jonceski.kliment.googlecertprepare.models.WeatherDay;
import jonceski.kliment.googlecertprepare.util.NetworkUtils;
import jonceski.kliment.googlecertprepare.util.WeatherJSONParser;
/**
* Activity that shows the weather data.
*/
public class WeatherActivity extends AppCompatActivity implements ListItemclickListener, LoaderManager.LoaderCallbacks<ArrayList<WeatherDay>> {
private RecyclerView mRecyclerView;
private ForecastDataAdapter mfForecastDataAdapter;
private ProgressBar progressBar;
private TextView tvError;
private WeatherDbHelper db;
private static final int WEATHER_DATA_LOADER = 22;
private static final String WEATHER_DATA_URL = "weather_data_url";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new WeatherDbHelper(this);
initViews();
getData();
readAllDataFromDb();
}
private void initViews() {
this.tvError = (TextView) findViewById(R.id.tv_error);
this.mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast);
this.progressBar = (ProgressBar) findViewById(R.id.pb_loading_indicator);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mfForecastDataAdapter = new ForecastDataAdapter(this);
mRecyclerView.setAdapter(mfForecastDataAdapter);
}
private void readAllDataFromDb() {
Cursor cursor = db.getWeatherData();
while (cursor.moveToNext()) {
String id = cursor.getLong(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry._ID)) + "";
String weather = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_WEATHER));
String humidity = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_HUMIDITY));
String pressure = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_PRESSURE));
String clouds = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_CLOUDS));
String min = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_MIN));
String max = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_MAX));
String timestamp = cursor.getString(cursor.getColumnIndex(WeatherDayTable.WeatherDayEntry.COLUMN_TIMESTAMP));
StringBuilder data = new StringBuilder();
data.append(id).append(" , ").append(weather).append(" , ").append(humidity).append(" , ")
.append(pressure).append(" , ").append(clouds).append(" , ").append(min).append(" ," +
" ").append(max).append(" , ").append(timestamp).append(" , ").append("\n");
Log.d(WeatherActivity.class.getSimpleName(), data.toString());
}
}
private void getData() {
//new FetchWeatherdata().execute("94043,USA");
Bundle bundle = new Bundle();
bundle.putString(WEATHER_DATA_URL, "94043,USA");
LoaderManager loaderManager = getSupportLoaderManager();
Loader<ArrayList<WeatherDay>> weatherLoader = loaderManager.getLoader(WEATHER_DATA_LOADER);
loaderManager.initLoader(WEATHER_DATA_LOADER, bundle, this);
}
@Override
public void onItemClicked(int itemIndex) {
Intent intent = new Intent(WeatherActivity.this, DetailedWeatherActivity.class);
intent.putExtra(DetailedWeatherActivity.DETAILS_KEY, mfForecastDataAdapter.getItemAt(itemIndex));
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int selectedMenuItem = item.getItemId();
switch (selectedMenuItem) {
case R.id.action_search :
startActivity(new Intent(WeatherActivity.this, SettingsActivity.class));
break;
case R.id.action_refresh :
getData();
break;
case R.id.action_content_provider:
startActivity(new Intent(WeatherActivity.this, UseContentProviderExample.class));
break;
}
return super.onOptionsItemSelected(item);
}
private boolean refreshEnabled() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPreferences.getBoolean(getString(R.string.key_refresh_prefs), false);
}
@Override
public void onLoadFinished(android.support.v4.content.Loader<ArrayList<WeatherDay>> loader,
ArrayList<WeatherDay> data) {
Log.d(WeatherActivity.class.getSimpleName(), "on Loader finish" + WeatherActivity.this);
progressBar.setVisibility(View.GONE);
if (data != null) {
mfForecastDataAdapter.setForecastData(data);
} else {
tvError.setVisibility(View.VISIBLE);
tvError.setText("Error occured during fetching weather data.");
}
}
@Override
public void onLoaderReset(android.support.v4.content.Loader<ArrayList<WeatherDay>> loader) {
}
@Override
public android.support.v4.content.Loader<ArrayList<WeatherDay>> onCreateLoader(int id, final Bundle args) {
return new android.support.v4.content.AsyncTaskLoader<ArrayList<WeatherDay>>(this) {
private ArrayList<WeatherDay> cacheData;
@Override
protected void onStartLoading() {
super.onStartLoading();
if (args == null) {
return;
}
tvError.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
if (cacheData == null) {
forceLoad();
} else {
deliverResult(cacheData);
}
}
@Override
public ArrayList<WeatherDay> loadInBackground() {
String passedData = args.getString(WEATHER_DATA_URL);
if (TextUtils.isEmpty(passedData)) {
return null;
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
URL weatherUrl = NetworkUtils.buildUrl("");
try {
String weatherResult = NetworkUtils.getResponseFromHttpUrl(weatherUrl);
cacheData = WeatherJSONParser.parseWeatherData(weatherResult);
//db.bulkInsert(cacheData);
return cacheData;
} catch (IOException ex) {
ex.printStackTrace();
return null;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Sends the result of the load to the registered listener.
*
* @param data The result of the load
*/
public void deliverResult(ArrayList<WeatherDay> data) {
progressBar.setVisibility(View.GONE);
cacheData = data;
super.deliverResult(data);
}
};
}
@Override
protected void onPause() {
super.onPause();
Log.d(WeatherActivity.class.getSimpleName(), "onPause : " + WeatherActivity.this);
}
@Override
protected void onStop() {
super.onStop();
Log.d(WeatherActivity.class.getSimpleName(), "onStop : " + WeatherActivity.this);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(WeatherActivity.class.getSimpleName(), "onDestroy : " + WeatherActivity.this + " - isfinishing : " + isFinishing());
}
}
|
package br.com.higornucci.contracheque.dominio;
import org.junit.Ignore;
import org.junit.Test;
import java.math.BigDecimal;
import br.com.higornucci.contracheque.dominio.desconto.CalculadorDeDesconto;
import br.com.higornucci.contracheque.dominio.desconto.irrf.CalculadorDeIRRF;
import br.com.higornucci.contracheque.dominio.real.Real;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class IRRFTest {
@Test
public void deve_calcular_o_valor_do_irrf_sem_desconto_do_salario() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(1500));
Real valorDescontadoEsperado = new Real(BigDecimal.ZERO);
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_sem_desconto_para_teto_do_salario() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(1903.98));
Real valorDescontadoEsperado = new Real(BigDecimal.ZERO);
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_piso_da_aliquota_minima_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(1903.99));
Real valorDescontadoEsperado = new Real(BigDecimal.ZERO);
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_teto_da_aliquota_minima_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(2826.65));
Real valorDescontadoEsperado = new Real(new BigDecimal(69.2));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_piso_da_aliquota_intermediaria_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(2826.66));
Real valorDescontadoEsperado = new Real(new BigDecimal(69.2));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_teto_da_aliquota_intermediaria_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(3751.05));
Real valorDescontadoEsperado = new Real(new BigDecimal(207.86));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_piso_da_aliquota_maxima_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(3751.06));
Real valorDescontadoEsperado = new Real(new BigDecimal(207.86));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_teto_da_aliquota_maxima_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(4664.68));
Real valorDescontadoEsperado = new Real(new BigDecimal(413.42));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_valor_piso_acima_do_teto_e_com_maior_aliquota_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(4664.69));
Real valorDescontadoEsperado = new Real(new BigDecimal(413.43));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
@Test
public void deve_calcular_o_valor_do_irrf_para_valor_acima_do_teto_e_com_maior_aliquota_a_partir_do_salario_bruto() throws Exception {
Real valorDoSalarioBruto = new Real(new BigDecimal(5619.12));
Real valorDescontadoEsperado = new Real(new BigDecimal(675.90));
CalculadorDeDesconto calculadorDeDesconto = new CalculadorDeIRRF(valorDoSalarioBruto);
Real valorDescontado = calculadorDeDesconto.calcular();
assertThat(valorDescontado, is(equalTo(valorDescontadoEsperado)));
}
}
|
package com.example.ahmed.octopusmart.RecyclerAdapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ahmed.octopusmart.Interfaces.GenericItemClickCallback;
import com.example.ahmed.octopusmart.Model.ServiceModels.SubFilterModel;
import com.example.ahmed.octopusmart.R;
import com.example.ahmed.octopusmart.holders.ProductInfoItemViewHolder;
import java.util.ArrayList;
/**
* Created by ahmed on 20/12/2017.
*/
public class ProductSpecsAdapter extends GenericAdapter<SubFilterModel>
{
public ProductSpecsAdapter(ArrayList<SubFilterModel> items,
Context context,
GenericItemClickCallback<SubFilterModel> adapterItemClickCallbacks)
{
super(items, context, adapterItemClickCallbacks);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(getContext())
.inflate(R.layout.product_info_item, parent, false);
return new ProductInfoItemViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
SubFilterModel subFilterModel = getItem(position);
if(subFilterModel != null)
{
ProductInfoItemViewHolder viewHolder =
(ProductInfoItemViewHolder) holder;
viewHolder.field.setText(subFilterModel.getName());
viewHolder.info.setText(subFilterModel.getBody());
}
}
}
|
package com.bw.movie.mvp.view.apdater;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bw.movie.R;
import com.bw.movie.mvp.model.bean.ComingMovie;
import com.bw.movie.mvp.model.utils.GlideRoundTransform;
import com.bw.movie.mvp.view.activity.ShowActivity;
import java.util.List;
public class ComingApdater extends RecyclerView.Adapter<MyComingViewHoder> {
Context context;
List<ComingMovie.ResultBean> list;
public ComingApdater(Context context, List<ComingMovie.ResultBean> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyComingViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
MyComingViewHoder hoder = new MyComingViewHoder(LayoutInflater.from(context).inflate(R.layout.coming_item,parent,false));
return hoder;
}
@Override
public void onBindViewHolder(@NonNull MyComingViewHoder holder, final int position) {
Glide.with(context)
.load(list.get(position).getImageUrl())
.bitmapTransform(new GlideRoundTransform(context,35))
.into(holder.ivMovieImageThree);
//holder.ivMovieImageThree.setImageURI(Uri.parse(list.get(position).getImageUrl()));
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,ShowActivity.class);
intent.putExtra("id",list.get(position %list.size()).getId());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
}
|
package com.game.snakesAndLadder;
import java.util.List;
import java.util.Random;
public interface Dice {
int roll();
class CrookedDice implements Dice {
@Override
public int roll() {
Random random = new Random();
return List.of(2, 4, 6).get(random.nextInt(3));
}
}
class NormalDice implements Dice {
@Override
public int roll() {
return (int)(Math.random() * 6 + 1);
}
}
}
|
package net.sareweb.onddo.portlet.generic;
import java.util.Enumeration;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class SarewebPortlet extends MVCPortlet {
protected Log _log;
protected ThemeDisplay themeDisplay;
public SarewebPortlet() {
_log = LogFactoryUtil.getLog(this.getClass());
}
public void savePreferences(ActionRequest request, ActionResponse response) throws Exception {
_log.debug("Saving preferences");
prefs = request.getPreferences();
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()){
String prefName = (String)params.nextElement();
if(prefName.startsWith("PREF_")){
_log.debug("updating " + prefName);
String prefValue= request.getParameter(prefName);
if(prefValue!=null)prefs.setValue(prefName, prefValue);
}
}
prefs.store();
}
public static final String PARAM_RES_TYPE="PARAM_RES_TYPE";
public static final String PARAM_RES_ID="PARAM_RES_ID";
public static final String RES_TYPE_HTML="RES_TYPE_HTML";
public static final String RES_TYPE_JSON="RES_TYPE_JSON";
public static final String RES_TYPE_FILE="RES_TYPE_FILE";
protected PortletPreferences prefs;
}
|
package cz.educanet;
public class MathUtils {
/**
* Calculates the greatest common divisor.
* https://www.bbc.co.uk/bitesize/guides/z9hb97h/revision/5
* ie. for 8 and 12 => 4.
* ie. for 10 and 5 => 5.
* ect.
*
* @param a first number
* @param b second number
* @return GCD
*/
public static int findGreatestCommonDenominator(int a, int b) {
int mensi = a;
if (b < a) {// najde mensi cislo
mensi = b;
}
for (int i = mensi; i > 1; i--) {
if ((a % i == 0) && (b % i == 0)) {// zjistuje co je delitelne
return i;
}
}
return 1;
//throw new UnsupportedOperationException();
}
/**
* Calculates the lowest common multiple.
* https://www.bbc.co.uk/bitesize/guides/z9hb97h/revision/5
* ie. for 5 and 6 => 30.
* multiples for 5: 5, 10, 15, 20, 25, *30*, 35...
* multiples for 6: 6, 12, 18, 24, *30*...
*
* @param a first number
* @param b second number
* @return GCD
*/
public static int findLowestCommonMultiple(int a, int b) {
//throw new UnsupportedOperationException();
int vetsi = a;
if (b > a) {
vetsi = b;
}
int i = vetsi;
while (true) {
if ((i % a == 0) && (i % b == 0)){// nachazi delitele
return i;
}
i++;// aby se v dalsim kole hledalo dalsi cislo
}
}
}
|
package test.nz.org.take.compiler.scenario13.generated;
/**
* Class generated by the take compiler.
* This class represents the predicate ranking
* @version Mon Feb 18 10:34:07 CET 2008
*/
public class ranking {
public test.nz.org.take.compiler.scenario13.Bean slot1;
public long slot2;
public ranking(test.nz.org.take.compiler.scenario13.Bean slot1, long slot2) {
super();
this.slot1 = slot1;
this.slot2 = slot2;
}
public ranking() {
super();
}
}
|
package br.com.andreguedes.xti;
/**
* Compare operators
* @author Andre
*
*/
public class Aula15 {
// Aula 15 - Operadores de comparacao
public static void main(String[] args) {
int x = 6;
System.out.println(x == 7);
System.out.println(x != 6);
System.out.println(x < 3);
//System.out.println(x instanceof int); Not compile, because int isn`t a object, it`s a primitive type
Integer y = x;
System.out.println(y instanceof Integer); // It`ll compile, because it`s a compatible type with the Wrapper Integer
//System.out.println(x == "6"); Not compile, because the types that we`re compare are different
}
}
|
package com.zen.spark.etl.conf.bill;
/**
* 聊天账单
* Created Tom
* 2017-03-07.
*/
public class BI10029 {
public static int billId = 0;// 账单ID
public static int gameId = 1;// 游戏ID
public static int ts = 2;// 时间戳
public static int userId = 3;// 用户ID
public static int gameSceneId = 4;// 游戏场次ID
public static int roomId = 5;// 房间ID
public static int tableId = 6;// 桌子ID
public static int coin = 7;// 聊天话费游戏币
public static int content = 8;// 聊天内容
public static int phiz = 9;// 动态表情
public static int TOTAL = 10;
}
|
package com.kakaopay.moneyspread.network;
import com.kakaopay.moneyspread.domain.SpreadResponse;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class HeaderTest {
@Test
@DisplayName("Header_Test")
public void findByRoomTokenAndSpreadYN_Test() {
//give
SpreadResponse sr = SpreadResponse.builder()
.createUserId("Donghak")
.people(5)
.totalMoney(2000)
.roomId("kakaoPayRoom")
.id(1)
.build();
//when
Header<SpreadResponse> header = Header.OK(sr);
Header<String> headerError = Header.ERROR("카카오페이 안녕하세요!");
//Then
//1. OK
Assertions.assertThat(header.getData().getCreateUserId()).isEqualTo("Donghak");
Assertions.assertThat(header.getData().getPeople()).isEqualTo(5);
Assertions.assertThat(header.getData().getTotalMoney()).isEqualTo(2000);
Assertions.assertThat(header.getData().getRoomId()).isEqualTo("kakaoPayRoom");
Assertions.assertThat(header.getData().getId()).isEqualTo(1);
//2. ERROR
Assertions.assertThat(headerError.getDescription()).isEqualTo("카카오페이 안녕하세요!");
}
}
|
package edu.buet.cse.spring.ch03.v4.impl;
import org.springframework.stereotype.Component;
import edu.buet.cse.spring.ch03.v4.model.Instrument;
@Component("piano")
public class Piano implements Instrument {
private static final String PIANO_NAME = "Piano";
@Override
public String getName() {
return PIANO_NAME;
}
@Override
public void play() {
System.out.println("PING PING PINNNNNG");
}
}
|
package io.github.amitg87.semaphore.problems.childCare;
import io.github.amitg87.semaphore.lib.Mutex;
import io.github.amitg87.semaphore.lib.Semaphore;
import io.github.amitg87.semaphore.util.Runner;
/**
* At a child care center, state regulations require that there is always one adult present for every three children.
*
*/
public class Demo {
private static int children = 0;
private static int adults = 0;
private static int childrenWaitingToEnter = 0;
private static int adultsWaitingToLeave = 0;
private static Mutex mutex = new Mutex();
private static Semaphore childQueueEnter = new Semaphore(0, true);
private static Semaphore adultQueueLeave = new Semaphore(0, true);
public static void main(String args[]){
int caretakerCount = 3;
int childrenCount = 9;
for(int i=1; i<=caretakerCount; i++){
new Children("Child-" + i);
}
for(int i=1; i<=childrenCount; i++){
new CareTaker("Caretaker-" + i);
}
}
/**
* Caretaker:
* Incoming caretaker will result in waiting children to enter care center.
* Outgoing caretaker will have to wait for children to leave.
*/
static class CareTaker extends Runner{
public CareTaker(String name) {
super(name);
}
@Override
public void loop() {
mutex.enter();
adults++;
if(childrenWaitingToEnter>0){
int count = Math.min(childrenWaitingToEnter, 3);
childQueueEnter.release(count);
childrenWaitingToEnter = childrenWaitingToEnter - count;
children = children + 3;
}
mutex.leave();
//critical section
mutex.enter();
if(children < 3*(adults-1)){
adults--;
mutex.leave();
} else {
adultsWaitingToLeave++;
mutex.leave();
adultQueueLeave.acquire();
}
}
}
/**
* Incoming children will wait if there are not enough caretakers.
* Outgoing children will signal any waiting caretaker.
*/
static class Children extends Runner{
public Children(String name) {
super(name);
}
@Override
public void loop() {
mutex.enter();
if(children < 3*adults){
children++;
mutex.leave();
} else {
childrenWaitingToEnter++;
mutex.leave();
childQueueEnter.acquire();
}
//critical section
mutex.enter();
children--;
if(adultsWaitingToLeave>0 && children <= 3*(adults-1)){
adultsWaitingToLeave--;
adults--;
adultQueueLeave.release();
}
mutex.leave();
}
}
}
|
package com.facebook.react.views.scroll;
import com.a;
import com.facebook.i.a.a;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.PixelUtil;
import java.util.Map;
public class ReactScrollViewCommandHelper {
public static Map<String, Integer> getCommandsMap() {
return MapBuilder.of("scrollTo", Integer.valueOf(1), "scrollToEnd", Integer.valueOf(2), "flashScrollIndicators", Integer.valueOf(3));
}
public static <T> void receiveCommand(ScrollCommandHandler<T> paramScrollCommandHandler, T paramT, int paramInt, ReadableArray paramReadableArray) {
a.b(paramScrollCommandHandler);
a.b(paramT);
a.b(paramReadableArray);
if (paramInt != 1) {
if (paramInt != 2) {
if (paramInt == 3) {
paramScrollCommandHandler.flashScrollIndicators(paramT);
return;
}
throw new IllegalArgumentException(a.a("Unsupported command %d received by %s.", new Object[] { Integer.valueOf(paramInt), paramScrollCommandHandler.getClass().getSimpleName() }));
}
paramScrollCommandHandler.scrollToEnd(paramT, new ScrollToEndCommandData(paramReadableArray.getBoolean(0)));
return;
}
paramScrollCommandHandler.scrollTo(paramT, new ScrollToCommandData(Math.round(PixelUtil.toPixelFromDIP(paramReadableArray.getDouble(0))), Math.round(PixelUtil.toPixelFromDIP(paramReadableArray.getDouble(1))), paramReadableArray.getBoolean(2)));
}
public static interface ScrollCommandHandler<T> {
void flashScrollIndicators(T param1T);
void scrollTo(T param1T, ReactScrollViewCommandHelper.ScrollToCommandData param1ScrollToCommandData);
void scrollToEnd(T param1T, ReactScrollViewCommandHelper.ScrollToEndCommandData param1ScrollToEndCommandData);
}
public static class ScrollToCommandData {
public final boolean mAnimated;
public final int mDestX;
public final int mDestY;
ScrollToCommandData(int param1Int1, int param1Int2, boolean param1Boolean) {
this.mDestX = param1Int1;
this.mDestY = param1Int2;
this.mAnimated = param1Boolean;
}
}
public static class ScrollToEndCommandData {
public final boolean mAnimated;
ScrollToEndCommandData(boolean param1Boolean) {
this.mAnimated = param1Boolean;
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\scroll\ReactScrollViewCommandHelper.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package test3.suiteEx;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Test5 {
// test case 1
@Test
public void t5() {
System.out.println("Test5:in test case 1");
}
@BeforeClass
public void beforeClass51() {
System.out.println("Test5:in beforeClass");
}
@AfterClass
public void afterClass51() {
System.out.println("Test5:in afterClass");
}
@BeforeTest
public void beforeTest51() {
System.out.println("Test5:in beforeTest");
}
@AfterTest
public void afterTest51() {
System.out.println("Test5:in afterTest");
}
@BeforeSuite
public void beforeSuite51() {
System.out.println("Test5:in beforeSuite");
}
@AfterSuite
public void afterSuite51() {
System.out.println("Test5:in afterSuite");
}
}
|
package com.eres.waiter.waiter.model.events;
public class EventIAmTableChange {
private boolean type;
public boolean isType() {
return type;
}
public EventIAmTableChange(boolean type) {
this.type = type;
}
}
|
package corgi.hub.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
@ComponentScan("corgi.hub.core")
public class Application {
public static ConfigurableApplicationContext context;
public static String nodeId;
public void init(String []args) throws Exception {
String configName = System.getProperty("hub.config.name");
configName = configName == null ? "corgi" : configName;
System.setProperty("spring.config.name", configName);
Application.context = SpringApplication.run(Application.class, args);
}
public static ConfigurableApplicationContext getContenxt() {
return context;
}
public static void main(String []args) throws Exception {
new Application().init(args);
}
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean(name = "queueThreadPoolExecutor")
public ThreadPoolTaskExecutor createThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(100);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(1);
executor.setKeepAliveSeconds(300);
executor.initialize();
return executor;
}
}
|
package com.lins.myzoom.result;
/**
* @ClassName Result
* @Description TODO
* @Author lin
* @Date 2021/1/30 13:38
* @Version 1.0
**/
public class Result {
private int code;
public Result(int code){
this.code=code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
|
package arenaworker.abilityobjects;
import arenaworker.abilities.Ability;
public class Mine extends Grenade {
public Mine(Ability ability, double rotation, double radius, double amountOfForce, double damage, String color) {
super(ability, rotation, radius, amountOfForce, damage, false, color, 120);
initialUpdateName = "mineInitial";
updateName = "mineUpdate";
destroyUpdateName = "mineDestroy";
SendInitialToAll();
}
}
|
package com.tencent.mm.ac;
import com.tencent.mm.ac.a.g;
import com.tencent.mm.bt.h.d;
class z$7 implements d {
z$7() {
}
public final String[] xb() {
return g.diD;
}
}
|
/*
* 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 dao;
/**
*
* @author Leo
*/
public class Problema {
private int idproblema;
private int idproblemaatual;
private String latitude;
private String longitude;
private int idprimeiraconsulta;
public int getIdprimeiraconsulta() {
return idprimeiraconsulta;
}
public void setIdprimeiraconsulta(int idprimeiraconsulta) {
this.idprimeiraconsulta = idprimeiraconsulta;
}
public int getIdproblema() {
return idproblema;
}
public void setIdproblema(int idproblema) {
this.idproblema = idproblema;
}
public int getIdproblemaatual() {
return idproblemaatual;
}
public void setIdproblemaatual(int idproblemaatual) {
this.idproblemaatual = idproblemaatual;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
|
package com.milos.server;
import com.milos.domain.Answer;
import com.milos.domain.Message;
import com.milos.domain.logger.PrimitiveLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Receiver implements Runnable {
public interface MessageReceived {
Answer messageReceived(Message message);
}
private Socket socket;
private MessageReceived callback;
private PrimitiveLogger logger;
public Receiver(final Socket socket, final MessageReceived callback, PrimitiveLogger logger) {
if (socket == null) {
throw new IllegalArgumentException("socket must not be null");
}
if (callback == null) {
throw new IllegalArgumentException("callback must not be null");
}
if (logger == null) {
throw new IllegalArgumentException("logger must not be null");
}
this.socket = socket;
this.callback = callback;
this.logger = logger;
}
@Override
public void run() {
try {
logger.info("Connected: " + socket);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (in.hasNextLine()) {
String line = in.nextLine();
Message message = Message.fromJson(line);
Answer answer = callback.messageReceived(message);
out.println(answer.toJson());
}
} catch (Exception e) {
logger.error("Error:" + socket + ";" + e.getMessage());
} finally {
try {
socket.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
logger.error("Closed: " + socket);
}
}
}
|
package ec.com.yacare.y4all.activities.principal;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaActionSound;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import ec.com.yacare.y4all.activities.DatosAplicacion;
import ec.com.yacare.y4all.activities.R;
import ec.com.yacare.y4all.lib.dto.Evento;
import ec.com.yacare.y4all.lib.enumer.EstadoEventoEnum;
import ec.com.yacare.y4all.lib.enumer.TipoEquipoEnum;
import ec.com.yacare.y4all.lib.enumer.TipoEventoEnum;
import ec.com.yacare.y4all.lib.sqllite.EventoDataSource;
class FotosPagerAdapter extends PagerAdapter {
Activity mContext;
LayoutInflater mLayoutInflater;
ArrayList<Evento> eventos;
public FotosPagerAdapter(Activity context, ArrayList<Evento> eventos) {
mContext = context;
this.eventos = eventos;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return eventos.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = mLayoutInflater.inflate(R.layout.fragment_screen_slide_page, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView1);
ImageButton btnGuardarFotoActual = (ImageButton) itemView.findViewById(R.id.btnGuardarFotoActual);
if(!eventos.get(position).getId().equals("1")) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Y4Home/" + eventos.get(position).getId() + ".jpg");
imageView.setImageBitmap(bitmap);
btnGuardarFotoActual.setVisibility(View.GONE);
}else{
Bitmap bitmap = BitmapFactory.decodeByteArray(eventos.get(position).getFotoActual(), 0, eventos.get(position).getFotoActual().length);
imageView.setImageBitmap(bitmap);
btnGuardarFotoActual.setVisibility(View.VISIBLE);
}
Typeface font = Typeface.createFromAsset(mContext.getAssets(), "Lato-Regular.ttf");
TextView fecha = (TextView) itemView.findViewById(R.id.textoFecha);
fecha.setTypeface(font);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
if(eventos.get(position).getFecha().startsWith(dateFormat.format(date))){
fecha.setText("Hoy a las " + eventos.get(position).getFecha().substring(11, 19));
}else{
fecha.setText(eventos.get(position).getFecha());
}
btnGuardarFotoActual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaActionSound sound = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
sound = new MediaActionSound();
sound.play(MediaActionSound.SHUTTER_CLICK);
}
DatosAplicacion datosAplicacion = (DatosAplicacion) mContext.getApplicationContext();
EventoDataSource datasource = new EventoDataSource(mContext);
datasource.open();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Evento evento = new Evento();
evento.setOrigen(TipoEquipoEnum.PORTERO.getDescripcion() + ": " + datosAplicacion.getEquipoSeleccionado().getNombreEquipo());
evento.setId(UUID.randomUUID().toString());
evento.setFecha(dateFormat.format(date));
evento.setEstado(EstadoEventoEnum.RECIBIDO.getCodigo());
evento.setComando("FOTO");
evento.setTipoEvento(TipoEventoEnum.FOTO.getCodigo());
evento.setIdEquipo(datosAplicacion.getEquipoSeleccionado().getId());
FileOutputStream fileOuputStream = null;
try {
fileOuputStream = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/"+ evento.getId() +".jpg");
fileOuputStream.write(eventos.get(position).getFotoActual());
fileOuputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
evento.setMensaje("S");
datasource.createEvento(evento);
datasource.close();
}
});
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
|
package com.conn.port;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* TCP Port
* @author leesk
*
*/
public class TCPPort implements DevicePort
{
private final int defaultPort = 9100;
private final int timeout = 3000;
private static TCPPort tcpPort;
private TCPPort(){}
public static TCPPort getInstance()
{
if(tcpPort == null)
tcpPort = new TCPPort();
return tcpPort;
}
public TCPConnection openPort(String address) throws IOException
{
return openPort(address, defaultPort);
}
/**
* Connect the interface to the destination address.
* @param address IP address.
* @param port Port Number.
* @throws IOException
*/
public TCPConnection openPort(String address, int port) throws IOException
{
InetSocketAddress socketAdress = new InetSocketAddress(InetAddress.getByName(address), port);
Socket socket = new Socket();
socket.connect(socketAdress, timeout);
return new TCPConnection(socket);
}
}
|
package org.inftel.socialwind.client.web.mvp.ui;
import org.inftel.socialwind.client.web.mvp.ClientFactory;
import org.inftel.socialwind.client.web.mvp.places.HotspotListPlace;
import org.inftel.socialwind.client.web.mvp.places.IntroduccionPlace;
import org.inftel.socialwind.client.web.mvp.places.PerfilPlace;
import org.inftel.socialwind.client.web.mvp.places.PlayasListPlace;
import org.inftel.socialwind.client.web.mvp.places.SesionListPlace;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Esta clase contiene la parte central de la pagina, compuesta por un menu lateral derecho y la
* parte principal para la informacion en el lado izquierdo. Ademas controla los eventos que ocurren
* en el.
*
* @author aljiru
*
*/
public class PanelCentral extends Composite {
private static PanelCentralUiBinder uiBinder = GWT.create(PanelCentralUiBinder.class);
interface PanelCentralUiBinder extends UiBinder<Widget, PanelCentral> {
}
@UiField
SimplePanel exampleArea;
/** Instancia de la clase para obtener los objetos mas pesados */
ClientFactory clientFactory = GWT.create(ClientFactory.class);
/**
* Metodo constructor. Inicializa el widget y establece el panel de Introduccion como panel
* inicial
*/
public PanelCentral() {
initWidget(uiBinder.createAndBindUi(this));
setWidgetToMaxWidthAndHeight();
Window.addResizeHandler(resizeHandler);
}
/**
* Maneja los eventos del boton marcado como opIntro
*
* @param event
* Evento que refleja la pulsacion del boton de introduccion
*/
@UiHandler("opIntro")
void showPanelIntroduccion(ClickEvent event) {
clientFactory.getPlaceController().goTo(new IntroduccionPlace());
}
/**
* Maneja los eventos del boton Playas
*
* @param event
* Evento que refleja la pulsacion del boton de playas
*/
@UiHandler("opPlayas")
void showPanelPlayas(ClickEvent event) {
clientFactory.getPlaceController().goTo(new PlayasListPlace());
}
@UiHandler("opHotspots")
void showPanelHotspots(ClickEvent event) {
clientFactory.getPlaceController().goTo(new HotspotListPlace());
}
@UiHandler("opHistorico")
void showPanelHistorico(ClickEvent event) {
clientFactory.getPlaceController().goTo(new SesionListPlace());
}
/**
* Maneja los eventos del boton Perfil
*
* @param event
* Evento que refleja la pulsacion del boton de perfil
*/
@UiHandler("opPerfil")
void showPanelPerfil(ClickEvent event) {
clientFactory.getPlaceController().goTo(new PerfilPlace());
}
/* ************* WIDGET CENTERING CODE *************** */
private ResizeHandler resizeHandler = new ResizeHandler() {
public void onResize(ResizeEvent event) {
setWidgetToMaxWidthAndHeight();
}
};
/**
* Metodo que establece el 100% del ancho y el 70% del alto de la pantalla
*/
private void setWidgetToMaxWidthAndHeight() {
setWidth("100%");
setHeight((Window.getClientHeight() * 0.8) + "px");
}
public SimplePanel getPanelContainer() {
return exampleArea;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
public final class bcx extends a {
public String rDt;
public int rKb;
public String rwt;
public int rxJ;
public int sfd;
protected final int a(int i, Object... objArr) {
int fQ;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.fT(1, this.rKb);
if (this.rDt != null) {
aVar.g(2, this.rDt);
}
if (this.rwt != null) {
aVar.g(3, this.rwt);
}
aVar.fT(4, this.rxJ);
aVar.fT(5, this.sfd);
return 0;
} else if (i == 1) {
fQ = f.a.a.a.fQ(1, this.rKb) + 0;
if (this.rDt != null) {
fQ += f.a.a.b.b.a.h(2, this.rDt);
}
if (this.rwt != null) {
fQ += f.a.a.b.b.a.h(3, this.rwt);
}
return (fQ + f.a.a.a.fQ(4, this.rxJ)) + f.a.a.a.fQ(5, this.sfd);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) {
if (!super.a(aVar2, this, fQ)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bcx bcx = (bcx) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
bcx.rKb = aVar3.vHC.rY();
return 0;
case 2:
bcx.rDt = aVar3.vHC.readString();
return 0;
case 3:
bcx.rwt = aVar3.vHC.readString();
return 0;
case 4:
bcx.rxJ = aVar3.vHC.rY();
return 0;
case 5:
bcx.sfd = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package tez.levent.feyyaz.kedi.activities.details;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.MySSLSocketFactory;
import com.loopj.android.http.RequestParams;
import com.varunest.sparkbutton.SparkButton;
import com.varunest.sparkbutton.SparkEventListener;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
import tez.levent.feyyaz.kedi.R;
import tez.levent.feyyaz.kedi.fragments.KulupFragment;
import static tez.levent.feyyaz.kedi.activities.SplashScreen.URL;
public class DuyuruActivity extends AppCompatActivity {
TextView baslik,aciklama,tarih,kulup_adi;
int id;
Boolean isInProcess=false;
SparkButton favori;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duyuru);
baslik=(TextView)findViewById(R.id.duyuru_baslik);
aciklama=(TextView)findViewById(R.id.aciklama);
tarih=(TextView)findViewById(R.id.tarih);
kulup_adi=(TextView)findViewById(R.id.kulup_adi);
favori = (SparkButton) findViewById(R.id.favori_spark);
favori.setVisibility(View.INVISIBLE);
id = getIntent().getIntExtra("id",0);
kulup_adi.setText(getIntent().getStringExtra("kulup_adi"));
baslik.setText(getIntent().getStringExtra("baslik"));
aciklama.setText(getIntent().getStringExtra("aciklama"));
tarih.setText(getIntent().getStringExtra("tarih"));
getFavoriDurumu();
favori.setEventListener(new SparkEventListener() {
@Override
public void onEvent(ImageView button, boolean buttonState) {
if (!isInProcess){
if (buttonState) {
favoriEkle();
} else {
favoriCikar();
}
}
}
});
}
private void getFavoriDurumu(){
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
String k_adi = sharedPref.getString("k_adi",null);
AsyncHttpClient client = new AsyncHttpClient();
client.setSSLSocketFactory(MySSLSocketFactory.getFixedSocketFactory());
RequestParams params = new RequestParams();
params.put("duyuru_id", id);
params.put("ogr_no", k_adi);
client.post(URL + "android/get_favori_info.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, @NonNull byte[] responseBody) {
Animation myFadeInAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_in);
favori.setVisibility(View.VISIBLE);
favori.startAnimation(myFadeInAnimation);
try {
JSONObject json = new JSONObject(new String(responseBody));
if (json.getBoolean("durum")){
favori.setChecked(true);
}else {
favori.setChecked(false);
}
} catch (JSONException e) {
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, @NonNull Throwable error) {
Animation myFadeInAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_in);
favori.setVisibility(View.VISIBLE);
favori.startAnimation(myFadeInAnimation);
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void favoriEkle(){
isInProcess = true;
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
String k_adi = sharedPref.getString("k_adi",null);
AsyncHttpClient client = new AsyncHttpClient();
client.setSSLSocketFactory(MySSLSocketFactory.getFixedSocketFactory());
RequestParams params = new RequestParams();
params.put("duyuru_id", id);
params.put("ogr_no", k_adi);
client.post(URL + "android/insert_favori.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, @NonNull byte[] responseBody) {
isInProcess=false;
try {
JSONObject json = new JSONObject(new String(responseBody));
if (json.getBoolean("durum")){
favori.setChecked(true);
}else {
favori.setChecked(false);
Toast.makeText(getBaseContext(),json.getString("mesaj"),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
favori.setChecked(false);
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, @NonNull Throwable error) {
isInProcess=false;
favori.setChecked(false);
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void favoriCikar(){
isInProcess = true;
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
String k_adi = sharedPref.getString("k_adi",null);
AsyncHttpClient client = new AsyncHttpClient();
client.setSSLSocketFactory(MySSLSocketFactory.getFixedSocketFactory());
RequestParams params = new RequestParams();
params.put("duyuru_id", id);
params.put("ogr_no", k_adi);
client.post(URL + "android/delete_favori.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, @NonNull byte[] responseBody) {
isInProcess=false;
try {
JSONObject json = new JSONObject(new String(responseBody));
if (json.getBoolean("durum")){
favori.setChecked(false);
}else {
favori.setChecked(true);
Toast.makeText(getBaseContext(),json.getString("mesaj"),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
favori.setChecked(true);
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, @NonNull Throwable error) {
isInProcess=false;
favori.setChecked(true);
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
kulup_adi.setText(intent.getStringExtra("kulup_adi"));
baslik.setText(intent.getStringExtra("baslik"));
aciklama.setText(intent.getStringExtra("aciklama"));
tarih.setText(intent.getStringExtra("tarih"));
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return false;
}
}
|
package org.springframework.fom;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.fom.annotation.FomSchedule;
import java.util.Set;
/**
*
* @author shanhm1991@163.com
*
*/
public class ScheduleInfo {
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private final String scheduleName;
private final String scheduleBeanName;
private final String state;
private final String stateTitile;
private final String stateImage;
private final long scheduleTimes;
private final String loadTime;
private final String lastTime;
private final String nextTime;
private final long success;
private final long failed;
private final int waiting;
private final long active;
private final List<Conf> config = new ArrayList<>();
private final String loggerName;
private String loggerLevel;
public ScheduleInfo(ScheduleContext<?> scheduleContext){
this.scheduleName = scheduleContext.getScheduleName();
this.scheduleBeanName = scheduleContext.getScheduleBeanName();
this.scheduleTimes = scheduleContext.getSchedulTimes();
this.loadTime = dateFormat.format(scheduleContext.getLoadTime());
if(0 == scheduleContext.getLastTime()){
this.lastTime = "";
}else{
this.lastTime = dateFormat.format(scheduleContext.getLastTime());
}
if(0 == scheduleContext.getNextTime()){
this.nextTime = "";
}else{
this.nextTime = dateFormat.format(scheduleContext.getNextTime());
}
this.loggerName = scheduleContext.getLogger().getName();
State state = scheduleContext.getState();
this.state = state.name();
this.stateTitile = state.title();
this.stateImage = state.src();
ScheduleStatistics scheduleStatistics = scheduleContext.getScheduleStatistics();
this.success = scheduleStatistics.getSuccess();
this.failed = scheduleStatistics.getFailed();
ScheduleConfig scheduleConfig = scheduleContext.getScheduleConfig();
this.waiting = scheduleConfig.getWaitings();
this.active = scheduleConfig.getActives();
Map<String, Object> configMap = new HashMap<>();
configMap.putAll(scheduleConfig.getConfMap());
Map<String, Object> internalConf = ScheduleConfig.getInternalConf();
Set<String> readOnlyKey = ScheduleConfig.getReadOnlyConf();
// 内部配置
for(String key : internalConf.keySet()){
Object defaultVal = internalConf.get(key);
Object val = configMap.remove(key);
if(val == null){
if(readOnlyKey.contains(key)){
config.add(new Conf(key, defaultVal, true, true, true, false));
}else{
config.add(new Conf(key, defaultVal, true, false, true, false));
}
}else{
if(FomSchedule.CRON.equals(key)){
config.add(new Conf(key, scheduleConfig.getCronExpression(), true, false, false, false));
}else{
if(readOnlyKey.contains(key)){
config.add(new Conf(key, val, true, true, false, false));
}else{
config.add(new Conf(key, val, true, false, false, false));
}
}
}
}
// 自定义配置 已经环境变量
for(Entry<String, Object> entry : configMap.entrySet()){
config.add(new Conf(entry.getKey(), entry.getValue(), false, false, false, false));
}
}
public static class Conf{
private boolean internal = false;
private boolean onlyRead = false;
private boolean envirment = false;
private boolean defaultValue = false;
private final String key;
private final Object value;
public Conf(String key, Object value, boolean internal, boolean onlyRead, boolean defaultValue, boolean envirment){
this.key = key;
this.value = value;
this.internal = internal;
this.onlyRead = onlyRead;
this.envirment = envirment;
this.defaultValue = defaultValue;
}
public boolean isInternal() {
return internal;
}
public boolean isOnlyRead() {
return onlyRead;
}
public boolean isEnvirment() {
return envirment;
}
public boolean isDefaultValue() {
return defaultValue;
}
public String getKey() {
return key;
}
public Object getValue() {
return value;
}
}
public String getScheduleName() {
return scheduleName;
}
public String getScheduleBeanName() {
return scheduleBeanName;
}
public String getState() {
return state;
}
public String getLoadTime() {
return loadTime;
}
public String getLoggerLevel() {
return loggerLevel;
}
public void setLoggerLevel(String loggerLevel) {
this.loggerLevel = loggerLevel;
}
public long getScheduleTimes() {
return scheduleTimes;
}
public String getLastTime() {
return lastTime;
}
public String getNextTime() {
return nextTime;
}
public String getLoggerName() {
return loggerName;
}
public long getSuccess() {
return success;
}
public long getFailed() {
return failed;
}
public long getWaiting() {
return waiting;
}
public long getActive() {
return active;
}
public String getStateTitile() {
return stateTitile;
}
public String getStateImage() {
return stateImage;
}
public List<Conf> getConfig() {
return config;
}
@Override
public String toString() {
return "{scheduleName=" + scheduleName + ", scheduleBeanName=" + scheduleBeanName + ", state="
+ state + ", scheduleTimes=" + scheduleTimes + ", loadTime=" + loadTime + ", lastTime=" + lastTime
+ ", nextTime=" + nextTime + ", success=" + success + ", failed=" + failed + ", waiting=" + waiting
+ ", active=" + active + ", loggerName=" + loggerName + ", loggerLevel=" + loggerLevel + "}";
}
}
|
package com.marcuschiu.jpahibernateandh2database;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpaHibernateAndH2DatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(JpaHibernateAndH2DatabaseApplication.class, args);
}
}
|
package com.dzz.policy.service.service.policy;
import com.alibaba.fastjson.JSON;
import com.dzz.policy.api.domain.dto.PolicyCommonHolderSaveParam;
import com.dzz.policy.api.domain.dto.PolicyCommonSaveParam;
import com.dzz.policy.api.domain.dto.PolicyCommonSubjectSaveParam;
import com.dzz.policy.service.domain.model.Policy;
import com.google.common.collect.Lists;
import junit.framework.TestCase;
import org.junit.Test;
/**
* @author dzz
* @version 1.0.0
* @since 2019年08月20 10:32
*/
public class BeanTransformerTest extends TestCase {
@Test
public void testTransform() {
PolicyCommonSaveParam policyCommonSaveParam = new PolicyCommonSaveParam();
PolicyCommonHolderSaveParam policyCommonHolderSaveParam = new PolicyCommonHolderSaveParam();
PolicyCommonSubjectSaveParam policyCommonSubjectSaveParam = new PolicyCommonSubjectSaveParam();
policyCommonSaveParam.setHolder(policyCommonHolderSaveParam);
policyCommonSaveParam.setSubjects(Lists.newArrayList(policyCommonSubjectSaveParam));
policyCommonSaveParam.setPolicyNo("123123123123");
TestFunction testFunction = new TestFunction();
Policy policy = testFunction.function.apply(policyCommonSaveParam);
System.out.println(JSON.toJSONString(policy));
}
// private Function<PolicyCommonSaveParam, Policy> function = (param) -> {
// Policy policy = new Policy();
// policy.setPolicyNo(param.getPolicyNo());
// return policy;
// };
}
|
package me.yamas.tools.utils;
public class StringUtil {
public static boolean containsIgnoreCase(String[] board, String string){
String[] arrayOfString;
int j = (arrayOfString = board).length;
for(int i = 0; i < j; i++){
String otherstring = arrayOfString[i];
if(otherstring.equalsIgnoreCase(string)){
return true;
}
}
return false;
}
public static String replace(String text, String searchString, String replacement){
if(text == null || text.isEmpty() || searchString.isEmpty()) return text;
if(replacement == null) replacement = "";
int start = 0;
int max = -1;
int end = text.indexOf(searchString, start);
if(end == -1) return text;
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = (increase < 0 ? 0 : increase);
increase += (max < 0 ? 16 : (max > 64 ? 64 : max));
StringBuilder sb = new StringBuilder(text.length() + increase);
while(end != -1){
sb.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if(--max == 0) break;
end = text.indexOf(searchString, start);
}
sb.append(text.substring(start));
return sb.toString();
}
}
|
package at.xirado.bean.log;
import at.xirado.bean.Bean;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.LayoutBase;
import club.minnced.discord.webhook.WebhookClient;
import org.jline.utils.AttributedStringBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.locks.ReentrantLock;
public class FileLoggerLayout extends LayoutBase<ILoggingEvent> {
private final List<String> pendingMessages = new ArrayList<>();
private final ReentrantLock webhookLock = new ReentrantLock();
private final int emptyLength = getWebhookMessageLength(Collections.emptyList());
public FileLoggerLayout() {
Thread webhookThread = new Thread(() ->
{
int state = 0;
long waitingTime = 0;
while (true) {
webhookLock.lock();
int size = pendingMessages.size();
webhookLock.unlock();
if (size > 0 && state != 1) {
state = 1; //Waiting
waitingTime = System.currentTimeMillis();
}
if (state == 1 && (System.currentTimeMillis() > waitingTime + 3000)) {
webhookLock.lock();
List<List<String>> pack = splitUp(pendingMessages);
pack.forEach(this::sendWebhook);
pendingMessages.clear();
webhookLock.unlock();
state = 0;
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
});
webhookThread.setDaemon(true);
webhookThread.start();
}
public String doLayout(ILoggingEvent event) {
StringBuilder sbuf = new StringBuilder();
LocalDateTime myDateObj = LocalDateTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
AttributedStringBuilder asb = new AttributedStringBuilder();
asb.append("[").append(formattedDate).append("] [")
.append(event.getThreadName())
.append("] [")
.append(event.getLevel().levelStr.toUpperCase())
.append("]: ")
.append(event.getFormattedMessage());
if (event.getThrowableProxy() != null) {
IThrowableProxy iThrowableProxy = event.getThrowableProxy();
asb.append("\n").append(ThrowableProxyUtil.asString(iThrowableProxy));
}
asb.append(CoreConstants.LINE_SEPARATOR);
sbuf.append(asb.toAnsi());
if (Bean.getInstance().getWebhookClient() != null && event.getLevel() != Level.DEBUG) {
webhookLock.lock();
pendingMessages.add(getFormatted(event));
webhookLock.unlock();
}
return sbuf.toString();
}
private static final String GREY = "\u001B[30m";
private static final String RED = "\u001B[31m";
private static final String YELLOW = "\u001B[33m";
private static final String BLUE = "\u001B[34m";
private static final String WHITE = "\u001B[37m";
private static final String RESET = "\u001B[0m";
private static String getFormatted(ILoggingEvent event) {
String formattedMessage = event.getFormattedMessage();
if (formattedMessage.length() > 1500)
formattedMessage = "[!] Message too long";
Level level = event.getLevel();
String priColor = "";
if (level.equals(Level.WARN))
priColor = YELLOW;
else if (level.equals(Level.ERROR))
priColor = RED;
else if (level.equals(Level.INFO))
priColor = BLUE;
else
priColor = WHITE;
StringBuilder builder = new StringBuilder()
.append(GREY)
.append("[")
.append(priColor)
.append(event.getLevel().levelStr.toUpperCase(Locale.ROOT))
.append(GREY)
.append("] ")
.append(priColor)
.append(formattedMessage)
.append("\n");
if (event.getThrowableProxy() != null) {
IThrowableProxy iThrowableProxy = event.getThrowableProxy();
String result = ThrowableProxyUtil.asString(iThrowableProxy).length() > 1500 ? " [!] Stacktrace too long!\n" : ThrowableProxyUtil.asString(iThrowableProxy) + "\n";
builder.append(result).append(RESET);
}
return builder.toString();
}
private void sendWebhook(List<String> logs) {
WebhookClient client = Bean.getInstance().getWebhookClient();
StringBuilder result = new StringBuilder("```ansi\n");
logs.forEach(result::append);
result.append("```");
client.send(result.toString().trim());
logs.clear();
}
private int getWebhookMessageLength(List<String> logs) {
StringBuilder result = new StringBuilder("```ansi\n");
logs.forEach(result::append);
result.append("```");
return result.length();
}
/**
* Splits up a List of Strings into smaller Lists that are smaller than 2000 characters in length
*
* @param input The input list
* @return a List of Lists with a resulting length smaller than 2000 characters
*/
private List<List<String>> splitUp(List<String> input) {
List<List<String>> output = new ArrayList<>();
List<String> current = new ArrayList<>();
int currentSize = emptyLength; // Including the char count of the code block (should be 11)
int index = 0;
for (int i = 0; i < input.size(); i++) {
if (currentSize + input.get(i).length() <= 2000) {
currentSize += input.get(i).length();
current.add(input.get(i));
continue;
}
output.add(new ArrayList<>(current));
current.clear();
current.add(input.get(i));
currentSize = input.get(i).length();
index = i;
}
List<String> lastIter = new ArrayList<>();
for (int i = index; i < input.size(); i++)
lastIter.add(input.get(i));
output.add(lastIter);
return output;
}
}
|
/*
* Copyright (C) 2016. ly(emiya.angra@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ly.commonutils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Author: ly(emiya.angra@gmail.com)
* <p/>
* Date: 2015-01-29
* <p/>
* Time: 10:27
*/
public class DataUtils {
private static final String TAG = "DataUtils";
private DataUtils() {
}
/**
* Transcode the gbk string to utf8 string
*
* @return return utf8 string,if an exception occurred or param is null,return null
*/
public static String fromGBKToUTF8(String gbk) {
String utf;
try {
String iso = new String(gbk.getBytes("UTF-8"), "ISO-8859-1");
utf = new String(iso.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
utf = null;
} catch (NullPointerException e) {
e.printStackTrace();
utf = null;
}
return utf;
}
/**
* Get String from InputStream with gbk code
*/
public static String getStringFromInputStream(InputStream is) {
return getStringFromInputStream(is, "GBK");
}
public static String getStringFromInputStream(InputStream is, String encode) {
BufferedReader reader;
StringBuilder builder = new StringBuilder();
String line;
try {
reader = new BufferedReader(new InputStreamReader(is, encode));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
|
package fr.epita.quiz.tests;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import fr.epita.quiz.datamodel.Choice;
import fr.epita.quiz.datamodel.Question;
import fr.epita.quiz.datamodel.Quiz;
import fr.epita.quiz.datamodel.User;
import fr.epita.quiz.services.dataaccess.ChoiceJPADAO;
import fr.epita.quiz.services.dataaccess.QuizDataService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class TestDataServiceWithTransaction {
@Inject
QuizDataService quizDS;
@Inject
ChoiceJPADAO choiceDAO;
@Test
public void testQuestionWithChoicesInsertion() {
/*
//given
Question question = new Question();
question.setContent("What is maven ?");
Choice choice1 = new Choice();
String firstChoiceText = "it is a dependency injection framework";
choice1.setText(firstChoiceText);
choice1.setValid(false);
Choice choice2 = new Choice();
choice2.setText("it is including a dependency management tool");
choice2.setValid(true);
//when
quizDS.createQuestionAndChoices(question, choice1, choice2);
//then
Choice criteria = new Choice();
criteria.setQuestion(question);
List<Choice> searchResults = choiceDAO.search(criteria);
Assert.assertTrue(!searchResults.isEmpty());
List<Choice> subList = searchResults.stream()
.filter(c -> c.getText().equals(firstChoiceText))
.collect(Collectors.toList());
Assert.assertEquals(1, subList.size());
*/
/*
User user = new User();
user.setNick("layso");
int questionCount = 3;
List<Question> qList = new ArrayList<Question>();
List<Choice> cList = new ArrayList<Choice>();
for (int i=0; i<questionCount; ++i) {
Question newQuestion = new Question();
newQuestion.setContent("Question " + i + "for second test");
qList.add(newQuestion);
for (int j=0; j<Question.CHOICE_COUNT; ++j) {
Choice newChoice = new Choice();
newChoice.setText("Choice for question " + i);
newChoice.setValid(j == questionCount%4);
cList.add(newChoice);
}
}
quizDS.CreateQuiz(user, "Bu da ikinci", qList, cList);*/
/*
Quiz squiz = new Quiz();
//squiz.setName("e");
List<Quiz> quizs = quizDS.GetAllQuizLike(squiz);
System.out.println(quizs.size());
for (Quiz quiz : quizs) {
System.out.println(quiz.getName());
}
*/
/*
User user = new User();
user.setId(1);
user.setNick("layso");
Quiz quiz = new Quiz();
quiz.setId(3);
quiz.setName("Bu da ikinci");
quiz.setUser(user);
List<Question> questions = quizDS.GetAllQuestionsOfQuiz(quiz);
for (Question q : questions) {
System.out.println(q.getContent());
for (Choice choice : quizDS.GetAllChoicesOfQuestion(q)) {
System.out.println(choice.getText() + " / " + choice.getValid());
}
}
*/
Quiz criteria = new Quiz();
criteria.setName("");
for (Quiz q: quizDS.GetAllQuizLike(criteria)) {
System.out.println(q.getName());
}
}
}
|
package com.shangcai.action.customer;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.irille.core.repository.orm.Entity;
import com.irille.core.web.exception.ReturnCode;
import com.irille.core.web.exception.WebMessageException;
import com.shangcai.action.BaseAction;
import com.shangcai.common.OssUtil;
import com.shangcai.entity.common.Member;
import com.shangcai.interceptor.ItpWxLogin;
import com.shangcai.view.ImageView;
import irille.util.MD5Util;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CustomerAction<T extends Entity, R extends Serializable> extends BaseAction<T, R> {
private final Logger logger = LoggerFactory.getLogger(CustomerAction.class);
private File file;
public Member curMember() {
return ItpWxLogin.getMember();
}
public void setMember(Member member) {
ItpWxLogin.setMember(member);
}
public void uploadImage() throws IOException {
try {
write(new ImageView() {{
setUrl("http://"+(OssUtil.cname==null?(OssUtil.bucketName+"."+OssUtil.endpoint):OssUtil.cname)+OssUtil.upload(entityClazz(), MD5Util.getMD5(file)+".jpg", file));
}});
} catch (IOException e) {
throw new WebMessageException(ReturnCode.service_unknow, "上传失败请稍后再试");
}
}
}
|
package com.nmoumoulidis.opensensor.model.processing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.nmoumoulidis.opensensor.model.SensorDictionary;
/**
* Utility class. Provides transformations between JSON strings and Java data structures,
* as well as performs JSON/data validation by removing the invalid values...
* @author Nikos Moumoulidis
*
*/
public class JSONParser
{
private String stringJSON = null;
private JSONArray readings = null;
private HashMap<String, String> dataMap = null;
private ArrayList<HashMap<String, String>> dataList = null;
private DataValidator dataValidator;
private JSONObject topLevelServerJSONObject = null;
private JSONArray mainDataJSONArray = null;
public static final String NODE_DATETIME = "datetime";
public static final String NODE_LOCATION = "location";
private ArrayList<String> keyList = null;
public JSONParser(String json, DataValidator validator) {
this.stringJSON = json;
this.dataValidator = validator;
this.keyList = new ArrayList<String>();
}
public JSONParser(String json) {
this.stringJSON = json;
}
public ArrayList<HashMap<String, String>> validateDataFromSensorStation() throws JSONException {
try {
dataList = new ArrayList<HashMap<String, String>>();
readings = new JSONArray(this.stringJSON);
for(int i=0 ; i<readings.length() ; i++) {
JSONObject obj = readings.getJSONObject(i);
// In order to track data loss...
this.dataValidator.incrementAllData();
// Run through the object's keys and validate them.
Iterator<String> iter = (Iterator<String>)obj.keys();
boolean areKeysValid = true;
while(iter.hasNext()) {
String key = iter.next();
if(!key.equals("datetime") && !key.equals("location")) {
if(!SensorDictionary.isValidSensor(key)) {
areKeysValid = false;
}
}
}
// If the keys of the object are valid...
if(areKeysValid) {
// If its the first object: add all the keys in the keyList.
if(i == 0) {
iter = (Iterator<String>)obj.keys();
while(iter.hasNext()) {
String key = iter.next();
if(!key.equals("datetime") && !key.equals("location")) {
keyList.add(key);
}
}
}
// Parse through them
try {
String datetime = obj.getString(NODE_DATETIME);
String location = obj.getString(NODE_LOCATION);
for(int j=0 ; j<keyList.size() ; j++) {
if(obj.getString(keyList.get(j)).equals(null)
|| obj.getString(keyList.get(j)).equals("")) {
throw new JSONException("empty or null data value");
}
// Validate that sensor values are numbers.
// Exception thrown here would be due to invalid (trash) data
//(i.e. a temperature value which is not a number).
double tempVariable = obj.getDouble(keyList.get(j));
}
// If data are valid, create a hashmap and add them to it.
dataMap = new HashMap<String, String>();
dataMap.put(NODE_DATETIME, datetime);
dataMap.put(NODE_LOCATION, location);
for(int j=0 ; j<keyList.size() ; j++) {
dataMap.put(keyList.get(j), obj.getString(keyList.get(j)));
}
}
catch (JSONException invalidNodeExc) {
System.out.println(invalidNodeExc.getMessage());
// In order to track data loss...
this.dataValidator.incrementDatalost();
// Exception due to reading validation is thrown, we skip this reading.
continue;
}
dataList.add(dataMap); // Add the map object to the list.
}
else {
// In order to track data loss...
this.dataValidator.incrementDatalost();
// keys are not valid, we skip this reading.
continue;
}
}
} catch (JSONException e) {
throw e;
}
return dataList;
}
public String transformSensorStationDataBackToJSON(ArrayList<HashMap<String, String>> dataList) {
ArrayList<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
JSONObject newObj;
for(int i=0 ; i<dataList.size() ; i++) {
newObj = new JSONObject(dataList.get(i));
jsonObjectList.add(newObj);
}
JSONArray jsArray = new JSONArray(jsonObjectList);
return jsArray.toString();
}
public ArrayList<String> parseSensorList() {
ArrayList<String> sensorList = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(this.stringJSON);
for(int i=0 ; i<jsonArray.length() ; i++) {
sensorList.add(jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return sensorList;
}
public ArrayList<HashMap<String, String>> parseServerDataFromJSONToListOfMaps() throws JSONException {
dataList = new ArrayList<HashMap<String, String>>();
JSONObject tempObject;
HashMap<String,String> map;
topLevelServerJSONObject = new JSONObject(this.stringJSON);
if(topLevelServerJSONObject.get("resultsEmpty").equals("false")) {
mainDataJSONArray = topLevelServerJSONObject.getJSONArray("data");
for(int i=0 ; i<mainDataJSONArray.length() ; i++) {
try {
tempObject = mainDataJSONArray.getJSONObject(i);
map = new HashMap<String,String>();
map.put("date", tempObject.get("date").toString());
map.put("location", tempObject.get("location").toString());
String userFriendlyName = SensorDictionary.validSensorNames.get(tempObject.get("sensor_name").toString());
map.put("sensor_name", userFriendlyName);
map.put("avg_value", tempObject.get("avg_value").toString());
map.put("min_value", tempObject.get("min_value").toString());
map.put("max_value", tempObject.get("max_value").toString());
dataList.add(map);
} catch (JSONException e) {
// We skip this data object...
continue;
}
}
return dataList;
}
else {
System.out.println("JSONException Captured...");
return null;
}
}
}
|
package br.edu.imed;
/**
*
* Classe de negócio (representa um conceito do mundo real para resolver um problema)
*
*/
public class Produto {
/*
* Atributos: o que sabemos sobre a classe (objeto)
*
* */
String descricao;
Double preco = 0d;
String fabricante;
// Integer: Wrapper para int
Integer quantidadeEstoque = 0;
/*
* Métodos: o que a classe (objeto) faz
*
* */
public void adicionarItem(Integer quantidade) {
quantidadeEstoque += quantidade;
}
public void removerItem(Integer quantidade) {
quantidadeEstoque -= quantidade;
}
public Integer obterSaldoEstoque() {
return quantidadeEstoque;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package unalcol.types.real.array.sparse;
import unalcol.types.collection.vector.sparse.SparseElement;
import java.util.Iterator;
/**
* @author jgomez
*/
public class SparseRealVectorDotProduct {
protected SparseElement<Double> element(Iterator<SparseElement<Double>> iter) {
if (iter.hasNext()) {
return iter.next();
}
return null;
}
public double apply(SparseRealVector x, SparseRealVector y) {
double prod = 0.0;
Iterator<SparseElement<Double>> iter_x = x.elements();
Iterator<SparseElement<Double>> iter_y = y.elements();
SparseElement<Double> elem_x = element(iter_x);
SparseElement<Double> elem_y = element(iter_y);
while (elem_x != null && elem_y != null) {
if (elem_x.index() < elem_y.index()) {
elem_x = element(iter_x);
} else {
if (elem_x.index() > elem_y.index()) {
elem_y = element(iter_y);
} else {
prod += elem_y.value() * elem_x.value();
elem_y = element(iter_y);
elem_x = element(iter_x);
}
}
}
return prod;
}
public double sqr_norm(SparseRealVector x) {
double prod = 0.0;
Iterator<SparseElement<Double>> iter = x.elements();
SparseElement<Double> elem;
while (iter.hasNext()) {
elem = iter.next();
prod += elem.value() * elem.value();
}
return prod;
}
public double norm(SparseRealVector x) {
return Math.sqrt(sqr_norm(x));
}
}
|
/*
* 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 Vistas;
import Clases.Cl_Compra;
import Clases.Cl_Conectar;
import Clases.Cl_Varios;
import Forms.frm_reg_compra;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author CONTABILIDAD 02
*/
public class frm_ver_compras extends javax.swing.JInternalFrame {
Cl_Conectar con = new Cl_Conectar();
Cl_Compra com = new Cl_Compra();
Cl_Varios ven = new Cl_Varios();
DefaultTableModel mostrar;
int i;
String periodo;
/**
* Creates new form frm_ver_compras
*/
public frm_ver_compras() {
initComponents();
java.util.Date fecha = new Date();
int mes = fecha.getMonth() + 1;
int anio = fecha.getYear() + 1900;
periodo = String.format("%02d", mes) + "-" + anio;
System.out.println(String.format("%02d", mes) + " - " + anio);
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idtipo_documento inner join moneda as m on c.idmoneda=m.idmoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.periodo = '" + periodo + "' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
private void ver_compras(String ver_com) {
mostrar = new DefaultTableModel() {
@Override
public boolean isCellEditable(int fila, int columna) {
return false;
}
};
mostrar.addColumn("Id");
mostrar.addColumn("Periodo");
mostrar.addColumn("Fec. Com.");
mostrar.addColumn("Fec. Pago");
mostrar.addColumn("Tipo Doc.");
mostrar.addColumn("Ser.");
mostrar.addColumn("Nro.");
mostrar.addColumn("RUC");
mostrar.addColumn("Razon Social");
mostrar.addColumn("Moneda");
mostrar.addColumn("Base");
mostrar.addColumn("Base M.N");
mostrar.addColumn("IGV");
mostrar.addColumn("Total");
mostrar.addColumn("Estado");
try {
Statement st = con.conexion();
ResultSet rs = con.consulta(st, ver_com);
Object fila[] = new Object[15];
while (rs.next()) {
fila[0] = rs.getString("idcompra");
fila[1] = rs.getString("periodo");
fila[2] = ven.fechaformateada(rs.getString("fec_com"));
fila[3] = "-";
fila[4] = rs.getString("nom_doc");
fila[5] = rs.getString("serie");
fila[6] = rs.getInt("numero");
fila[7] = rs.getString("ruc_pro");
fila[8] = rs.getString("raz_soc_pro");
fila[9] = rs.getString("corto");
fila[10] = ven.formato_numero(rs.getDouble("base"));
Double base = 0.0;
if (rs.getString("corto").equals("US$")) {
base = rs.getDouble("base") * rs.getDouble("tc");
} else {
base = rs.getDouble("base");
}
fila[11] = ven.formato_numero(base);
fila[12] = ven.formato_numero(base * 0.18);
fila[13] = ven.formato_numero(base * 1.18);
fila[14] = "PENDIENTE";
mostrar.addRow(fila);
}
t_compras.setModel(mostrar);
con.cerrar(rs);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
t_compras.getColumnModel().getColumn(0).setPreferredWidth(30);
t_compras.getColumnModel().getColumn(1).setPreferredWidth(70);
t_compras.getColumnModel().getColumn(2).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(3).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(4).setPreferredWidth(100);
t_compras.getColumnModel().getColumn(5).setPreferredWidth(70);
t_compras.getColumnModel().getColumn(6).setPreferredWidth(90);
t_compras.getColumnModel().getColumn(7).setPreferredWidth(90);
t_compras.getColumnModel().getColumn(8).setPreferredWidth(300);
t_compras.getColumnModel().getColumn(9).setPreferredWidth(40);
t_compras.getColumnModel().getColumn(10).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(11).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(12).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(13).setPreferredWidth(80);
t_compras.getColumnModel().getColumn(14).setPreferredWidth(80);
ven.centrar_celda(t_compras, 1);
ven.centrar_celda(t_compras, 2);
ven.centrar_celda(t_compras, 3);
ven.centrar_celda(t_compras, 4);
ven.centrar_celda(t_compras, 5);
ven.centrar_celda(t_compras, 6);
ven.centrar_celda(t_compras, 7);
ven.derecha_celda(t_compras, 10);
ven.derecha_celda(t_compras, 11);
ven.derecha_celda(t_compras, 12);
ven.derecha_celda(t_compras, 13);
txt_sub.setText(ven.formato_totales(subtotal()));
txt_igv.setText(ven.formato_totales(subtotal()*0.18));
txt_tot.setText(ven.formato_totales(subtotal()*1.18));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txt_bus = new javax.swing.JTextField();
cbx_bus = new javax.swing.JComboBox();
btn_cer = new javax.swing.JButton();
btn_reg = new javax.swing.JButton();
cbx_est = new javax.swing.JComboBox();
btn_det = new javax.swing.JButton();
btn_anu = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
t_compras = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txt_tot = new javax.swing.JTextField();
txt_igv = new javax.swing.JTextField();
txt_sub = new javax.swing.JTextField();
setClosable(true);
setTitle("Registro de Compras");
jLabel1.setText("Buscar:");
txt_bus.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_busKeyPressed(evt);
}
});
cbx_bus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PROVEEDOR", "NRO DOCUMENTO", "FECHA", "PERIODO" }));
cbx_bus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbx_busActionPerformed(evt);
}
});
btn_cer.setText("Cerrar");
btn_cer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_cerActionPerformed(evt);
}
});
btn_reg.setText("Registrar");
btn_reg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_regActionPerformed(evt);
}
});
cbx_est.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PENDIENTE", "PAGADO", "TODOS" }));
btn_det.setText("Ver Asiento");
btn_det.setEnabled(false);
btn_det.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_detActionPerformed(evt);
}
});
btn_anu.setText("Anular");
btn_anu.setEnabled(false);
btn_anu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_anuActionPerformed(evt);
}
});
t_compras.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
t_compras.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
t_comprasMouseClicked(evt);
}
});
jScrollPane1.setViewportView(t_compras);
jLabel2.setText("Sub Total");
jLabel3.setText("IGV");
jLabel4.setText("Total");
txt_tot.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_tot.setEnabled(false);
txt_igv.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_igv.setEnabled(false);
txt_sub.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_sub.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1164, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_bus, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbx_bus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbx_est, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_reg)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_cer))
.addGroup(layout.createSequentialGroup()
.addComponent(btn_det)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_anu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_sub, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_igv, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_tot, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_bus, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbx_bus, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_cer, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_reg, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbx_est, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_det, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_anu, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_tot, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_igv, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_sub, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private Double subtotal() {
Double sub = 0.0;
int nro_filas = t_compras.getRowCount();
for (int j = 0; j < nro_filas; j++) {
sub += Double.parseDouble(t_compras.getValueAt(j, 11).toString());
}
return sub;
}
private void btn_cerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cerActionPerformed
this.dispose();
}//GEN-LAST:event_btn_cerActionPerformed
private void btn_regActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_regActionPerformed
frm_reg_compra reg = new frm_reg_compra();
ven.llamar_ventana(reg);
this.dispose();
}//GEN-LAST:event_btn_regActionPerformed
private void btn_anuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_anuActionPerformed
int ax = JOptionPane.showConfirmDialog(null, "Desea Anular el Documento?");
if (ax == JOptionPane.YES_OPTION) {
try {
Statement st = con.conexion();
String ver_asiento = "select idasiento from asiento_compra where idcompra = '" + com.getId() + "' and periodo = '" + periodo + "'";
ResultSet rs = con.consulta(st, ver_asiento);
while (rs.next()) {
try {
Statement st1 = con.conexion();
String del_asiento = "delete from asiento_contable where periodo = '" + periodo + "' and id_asiento = '" + rs.getString("idasiento") + "' "
+ "and identificacion = 'M' and registro = 'C'";
System.out.println(del_asiento);
con.actualiza(st1, del_asiento);
con.cerrar(st1);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
con.cerrar(rs);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
try {
Statement st = con.conexion();
String del_asi = "delete from asiento_compra where idcompra = '" + com.getId() + "' and periodo = '" + periodo + "'";
System.out.println(del_asi);
con.actualiza(st, del_asi);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
try {
Statement st = con.conexion();
String del_com = "delete from compra where idcompra = '" + com.getId() + "' and periodo = '" + periodo + "'";
System.out.println(del_com);
con.actualiza(st, del_com);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
btn_anu.setEnabled(false);
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idTipo_Documento inner join moneda as m on c.idmoneda=m.idMoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.periodo = '" + periodo + "' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
}//GEN-LAST:event_btn_anuActionPerformed
private void t_comprasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t_comprasMouseClicked
i = t_compras.getSelectedRow();
com.setId(Integer.parseInt(t_compras.getValueAt(i, 0).toString()));
periodo = t_compras.getValueAt(i, 1).toString();
btn_anu.setEnabled(true);
btn_det.setEnabled(true);
}//GEN-LAST:event_t_comprasMouseClicked
private void txt_busKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_busKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
String bus = txt_bus.getText();
if (cbx_bus.getSelectedIndex() == 0) {
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idTipo_Documento inner join moneda as m on c.idmoneda=m.idMoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.ruc_pro = '" + bus + "' or p.raz_soc_pro like '%" + bus + "%' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
if (cbx_bus.getSelectedIndex() == 1) {
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idTipo_Documento inner join moneda as m on c.idmoneda=m.idMoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.numero = '" + bus + "' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
if (cbx_bus.getSelectedIndex() == 2) {
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idTipo_Documento inner join moneda as m on c.idmoneda=m.idMoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.fec_com = '" + bus + "' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
if (cbx_bus.getSelectedIndex() == 3) {
String ver_com = "select c.idcompra, c.periodo, c.fec_com, c.ruc_pro, p.raz_soc_pro, td.nom_doc, c.serie, c.numero, c.tc, m.corto, c.base, c.estado from "
+ "compra as c inner join tipo_documento as td on c.idtido = td.idTipo_Documento inner join moneda as m on c.idmoneda=m.idMoneda "
+ "inner join proveedor as p on c.ruc_pro = p.ruc_pro where c.periodo = '" + bus + "' order by c.periodo desc, c.idcompra desc";
ver_compras(ver_com);
}
}
}//GEN-LAST:event_txt_busKeyPressed
private void btn_detActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_detActionPerformed
Map<String, Object> parametros = new HashMap<>();
parametros.put("idcompra", com.getId());
parametros.put("periodo", periodo);
String filename = "rpt_asiento_compra";
ven.ver_reporte(filename, parametros);
btn_det.setEnabled(false);
}//GEN-LAST:event_btn_detActionPerformed
private void cbx_busActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbx_busActionPerformed
txt_bus.setText("");
txt_bus.requestFocus();
}//GEN-LAST:event_cbx_busActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_anu;
private javax.swing.JButton btn_cer;
private javax.swing.JButton btn_det;
private javax.swing.JButton btn_reg;
private javax.swing.JComboBox cbx_bus;
private javax.swing.JComboBox cbx_est;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable t_compras;
private javax.swing.JTextField txt_bus;
private javax.swing.JTextField txt_igv;
private javax.swing.JTextField txt_sub;
private javax.swing.JTextField txt_tot;
// End of variables declaration//GEN-END:variables
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.activity.model;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.persistence.Embeddable;
/**
* This class represents a reference to an ActivityType contained within an
* ActivityUnit.
*
*/
@Embeddable
public class ActivityTypeId implements java.io.Externalizable {
private static final int VERSION = 1;
private String _unitId=null;
private int _unitIndex=0;
/**
* The default constructor.
*/
public ActivityTypeId() {
}
/**
* The copy constructor.
*
* @param act The activity to copy.
*/
public ActivityTypeId(ActivityTypeId act) {
_unitId = act._unitId;
_unitIndex = act._unitIndex;
}
/**
* This constructor initializes the id and index
* for the reference.
*
* @param id The activity unit id
* @param index The activity type index within the unit
*/
public ActivityTypeId(String id, int index) {
_unitId = id;
_unitIndex = index;
}
/**
* This method sets the activity unit id.
*
* @param id The activity unit id
*/
public void setUnitId(String id) {
_unitId = id;
}
/**
* This method gets the activity unit id.
*
* @return The activity unit id
*/
public String getUnitId() {
return (_unitId);
}
/**
* This method sets the index of the activity
* type within the activity unit.
*
* @param index The index
*/
public void setUnitIndex(int index) {
_unitIndex = index;
}
/**
* This method sets the index of the activity
* type within the activity unit.
*
* @return The index
*/
public int getUnitIndex() {
return (_unitIndex);
}
/**
* This method creates an id associated with the
* supplied activity type.
*
* @param at The activity type
* @return The id for the activity type
*/
public static ActivityTypeId createId(ActivityType at) {
return (new ActivityTypeId(at.getUnitId(), at.getUnitIndex()));
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
if (obj instanceof ActivityTypeId) {
return (((ActivityTypeId)obj)._unitId.equals(_unitId)
&& ((ActivityTypeId)obj)._unitIndex == _unitIndex);
}
return (false);
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return (_unitId.hashCode());
}
/**
* {@inheritDoc}
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(VERSION);
out.writeObject(_unitId);
out.writeInt(_unitIndex);
}
/**
* {@inheritDoc}
*/
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
in.readInt(); // Consume version, as not required for now
_unitId = (String)in.readObject();
_unitIndex = in.readInt();
}
}
|
package unocerounocero;
import java.awt.event.*;
public class Controlador extends MouseAdapter {
private Modelo modelo; // ******** Modelo Vista Controlador
private int xPressed=0,yPressed=0;
private int numFigura=0;
private int numFiguras=0;
public Controlador(Modelo modelo) {
this.modelo = modelo; // ******** Modelo Vista Controlador
}
public void mousePressed(MouseEvent e) {
int tt = Tablero.TAMANIO;
int tt2 = tt/2;
xPressed = (e.getX()-Vista.COMIENZO_X);
if (xPressed>=0)
xPressed = xPressed/Vista.LADO;
else
xPressed=-1;
yPressed = (e.getY()-Vista.COMIENZO_Y)/Vista.LADO;
if (xPressed>=0&&yPressed>tt&&xPressed<tt/2&&yPressed<=tt+tt2) { // Figura exterior superior izquierda
yPressed = yPressed-(tt+1);
numFigura=0;
} else
if (xPressed>=tt/2&&yPressed>tt&&xPressed<tt&&yPressed<tt+tt2) { // Figura exterior superior derecha
xPressed = xPressed-tt2;yPressed = yPressed-(tt+1);
numFigura=1;
} else
if (xPressed>=0&&yPressed>16&&xPressed<5&&yPressed<tt*2+2) { // Figura exterior inferior izquierda
yPressed = yPressed-(tt+tt2+2);
numFigura=2;
} else
if (xPressed>=tt/2&&yPressed>16&&xPressed<tt&&yPressed<tt*2+2) { // Figura exterior inferior derecha
xPressed = xPressed-tt2;yPressed = yPressed-(tt+tt2+2);
numFigura=3;
}
}
public void mouseReleased(MouseEvent e) {
int xReleased = (e.getX()-Vista.COMIENZO_X)/Vista.LADO;
int yReleased = (e.getY()-Vista.COMIENZO_Y)/Vista.LADO;
int x=xReleased-xPressed;
int y=yReleased-yPressed;
if (x>=0&&y>=0&&x<Tablero.TAMANIO&&y<Tablero.TAMANIO) {
boolean dibujada = modelo.colocaEnPosTablero(modelo.getFigurasMesa().get()[numFigura].getForma(),
x, y, Colores.indice(modelo.getFigurasMesa().get()[numFigura].getColor()));
if (dibujada) {
modelo.getFigurasMesa().borrar(numFigura);
numFiguras=(numFiguras+1)%4;
if (numFiguras==0)
modelo.getFigurasMesa().set(modelo.getFigurasMesa().nuevasFiguras(new Figuras1010()));
}
modelo.borrarProgresosTablero(modelo.getPuntuacion());
//modelo.estadoTablero();
}
}
}
|
package com.example.university.commands;
import com.example.university.utils.RequestType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SetSessionLanguage extends Command {
private static final long serialVersionUID = -8779243740825414648L;
private static final Logger LOG = LogManager.getLogger(SetSessionLanguage.class);
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response,
RequestType requestType) throws IOException, ServletException {
LOG.debug("Executing Command");
if (requestType == RequestType.GET) {
doGet(request);
}
return null;
}
private void doGet(HttpServletRequest request) {
HttpSession session = request.getSession();
String lang = "en".equals(request.getParameter("lang")) ? "en" : "ru";
session.setAttribute("lang", lang);
LOG.trace("Set session attribute 'lang' = {}", lang);
}
}
|
package com.bierocratie.ui;
import com.bierocratie.db.accounting.InvoiceDAO;
import com.bierocratie.db.persistence.PersistenceManager;
import com.bierocratie.model.accounting.Category;
import com.bierocratie.model.accounting.Tva;
import com.bierocratie.model.catalog.Capacity;
import com.bierocratie.model.catalog.SupplierType;
import com.bierocratie.model.diffusion.Medium;
import com.bierocratie.ui.view.ErrorView;
import com.bierocratie.ui.view.accounting.*;
import com.bierocratie.ui.view.catalog.*;
import com.bierocratie.ui.view.chat.ChatView;
import com.bierocratie.ui.view.dashboard.DashboardView;
import com.bierocratie.ui.view.diffusion.DiffusionView;
import com.bierocratie.ui.view.diffusion.MediumView;
import com.porotype.tinycon.Tinycon;
import com.porotype.webnotifications.WebNotification;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Push;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import javax.servlet.annotation.WebServlet;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
/**
* Created with IntelliJ IDEA.
* User: pir
* Date: 28/04/14
* Time: 14:06
* To change this template use File | Settings | File Templates.
*/
// FIXME
//@CDIUI("dashboard")
@Push
@PreserveOnRefresh
@Widgetset("com.bierocratie.ui.view.chat.ChatWidgetSet")
public class NavigatorUI extends UI {
/**
*
*/
private static final long serialVersionUID = 5250690888792419255L;
public static final String DASHBOARD_VIEW = "";
public static final String BEER_VIEW = "biere";
public static final String CASK_VIEW = "fut";
public static final String SUPPLIER_VIEW = "fournisseurs";
public static final String SUPPLIER_TYPE_VIEW = "typefournisseur";
public static final String COUNTRY_VIEW = "pays";
public static final String CAPACITY_VIEW = "capacite";
public static final String DIFFUSION_VIEW = "diffusion";
public static final String MEDIUM_VIEW = "media";
//public static final String ORDER_VIEW = "commandes";
//public static final String HOPPY_HOURS_VIEW = "hoppyhours";
public static final String INVOICE_VIEW = "factures";
public static final String INCOME_VIEW = "ca";
public static final String CATEGORY_VIEW = "categories";
public static final String CASH_PLAN_VIEW = "tresorerie";
public static final String OPERATING_STATEMENT_VIEW = "exploitation";
public static final String BUDGET_YEAR_VIEW = "exercice";
public static final String TVA_VIEW = "tva";
public static final String STOCK_VALUE_VIEW = "stock";
public static final String CHAT_VIEW = "chat";
private static final Logger LOG = LoggerFactory.getLogger(NavigatorUI.class);
static {
final JPAContainer<Medium> mediumEntities = JPAContainerFactory.make(Medium.class, "dashboard");
if (mediumEntities.getItemIds().isEmpty()) {
mediumEntities.addEntity(new Medium("Facebook"));
mediumEntities.addEntity(new Medium("Twitter"));
mediumEntities.addEntity(new Medium("Mailing List"));
mediumEntities.addEntity(new Medium("Brassam"));
mediumEntities.addEntity(new Medium("Bière/Fromages"));
mediumEntities.addEntity(new Medium("Vitrine"));
}
final JPAContainer<SupplierType> supplierTypeEntities = JPAContainerFactory.make(SupplierType.class, "dashboard");
if (supplierTypeEntities.getItemIds().isEmpty()) {
supplierTypeEntities.addEntity(new SupplierType("Brasserie"));
supplierTypeEntities.addEntity(new SupplierType("Grossiste"));
}
final JPAContainer<Capacity> capacityEntities = JPAContainerFactory.make(Capacity.class, "dashboard");
if (capacityEntities.getItemIds().isEmpty()) {
capacityEntities.addEntity(new Capacity("33cl", 0.33, 0.5));
capacityEntities.addEntity(new Capacity("50cl", 0.50, 0.6));
capacityEntities.addEntity(new Capacity("75cl", 0.75, 0.8));
capacityEntities.addEntity(new Capacity("Fût 20L", 20, 25));
capacityEntities.addEntity(new Capacity("Fût 30L", 30, 35));
}
final JPAContainer<Tva> tvaEntities = JPAContainerFactory.make(Tva.class, "dashboard");
if (tvaEntities.getItemIds().isEmpty()) {
tvaEntities.addEntity(new Tva(new BigDecimal("0.2")));
tvaEntities.addEntity(new Tva(new BigDecimal("0.1")));
tvaEntities.addEntity(new Tva(new BigDecimal("0.055")));
tvaEntities.addEntity(new Tva(new BigDecimal("0.196")));
tvaEntities.addEntity(new Tva(new BigDecimal("0.07")));
tvaEntities.addEntity(new Tva(new BigDecimal("0")));
}
final JPAContainer<Category> categoryEntities = JPAContainerFactory.make(Category.class, "dashboard");
if (categoryEntities.getItemIds().isEmpty()) {
tvaEntities.addContainerFilter(new Compare.Equal("rate", 0.2));
Tva defaultTva = tvaEntities.getItem(tvaEntities.firstItemId()).getEntity();
categoryEntities.addEntity(new Category("Achat marchandises", defaultTva));
categoryEntities.addEntity(new Category("Internet/téléphone", defaultTva));
categoryEntities.addEntity(new Category("Electricité", defaultTva));
categoryEntities.addEntity(new Category("Déplacements", defaultTva));
categoryEntities.addEntity(new Category("Navigo", defaultTva));
categoryEntities.addEntity(new Category("Dégustations", defaultTva));
categoryEntities.addEntity(new Category("Travaux", defaultTva));
categoryEntities.addEntity(new Category("Fournitures", defaultTva));
categoryEntities.addEntity(new Category("Impôts & Taxes", defaultTva));
categoryEntities.addEntity(new Category("Loyer", defaultTva));
categoryEntities.addEntity(new Category("Associations", defaultTva));
categoryEntities.addEntity(new Category("Honoraires", defaultTva));
categoryEntities.addEntity(new Category("RSI", defaultTva));
categoryEntities.addEntity(new Category("Publicité", defaultTva));
categoryEntities.addEntity(new Category("Frais bancaires", defaultTva));
categoryEntities.addEntity(new Category("Assurances", defaultTva));
tvaEntities.removeAllContainerFilters();
}
}
private WebNotification webNotification = new WebNotification(this);
public WebNotification getWebNotification() {
return webNotification;
}
private Tinycon t = new Tinycon();
public Tinycon getTinycon() {
return t;
}
@Override
protected void init(VaadinRequest request) {
webNotification.requestPermission();
// TODO Créer les CSS
Responsive.makeResponsive();
Navigator navigator = new Navigator(this, this);
navigator.setErrorView(ErrorView.class);
navigator.addView(DASHBOARD_VIEW, DashboardView.class);
navigator.addView(BEER_VIEW, BeerView.class);
navigator.addView(CASK_VIEW, CaskView.class);
navigator.addView(SUPPLIER_VIEW, SupplierView.class);
navigator.addView(SUPPLIER_TYPE_VIEW, SupplierTypeView.class);
navigator.addView(COUNTRY_VIEW, CountryView.class);
navigator.addView(CAPACITY_VIEW, CapacityView.class);
navigator.addView(DIFFUSION_VIEW, DiffusionView.class);
navigator.addView(MEDIUM_VIEW, MediumView.class);
//navigator.addView(ORDER_VIEW, OrderView.class);
//navigator.addView(HOPPY_HOURS_VIEW, HoppyHoursView.class);
navigator.addView(INCOME_VIEW, IncomeView.class);
navigator.addView(INVOICE_VIEW, InvoiceByCategoryView.class);
navigator.addView(CATEGORY_VIEW, CategoryView.class);
navigator.addView(CASH_PLAN_VIEW, CashPlanView.class);
navigator.addView(OPERATING_STATEMENT_VIEW, OperatingStatementView.class);
navigator.addView(BUDGET_YEAR_VIEW, BudgetYearView.class);
navigator.addView(TVA_VIEW, TvaView.class);
navigator.addView(STOCK_VALUE_VIEW, StockValueView.class);
navigator.addView(CHAT_VIEW, ChatView.class);
getUI().getPage().setTitle("Tableau de bord");
navigator.navigateTo(DASHBOARD_VIEW);
t.extend(this);
UI.getCurrent().setErrorHandler(new DefaultErrorHandler() {
/**
*
*/
private static final long serialVersionUID = -615894631556635756L;
@Override
public void error(com.vaadin.server.ErrorEvent event) {
Throwable throwableCause = null;
for (Throwable t = event.getThrowable(); t != null; t = t.getCause()) {
if (t.getCause() == null) {
throwableCause = t;
}
}
if (throwableCause instanceof SQLException) {
LOG.error("", throwableCause);
} else {
doDefault(event);
}
// FIXME ne pas perdre la session
}
});
try {
InvoiceDAO invoiceDAO = new InvoiceDAO();
final JPAContainer<Tva> tvaEntities = JPAContainerFactory.make(Tva.class, "dashboard");
tvaEntities.addContainerFilter(new Compare.Equal("rate", 0.196));
Tva tva196 = tvaEntities.getItem(tvaEntities.getItemIds().toArray()[0]).getEntity();
tvaEntities.removeAllContainerFilters();
tvaEntities.addContainerFilter(new Compare.Equal("rate", 0.2));
Tva tva200 = tvaEntities.getItem(tvaEntities.getItemIds().toArray()[0]).getEntity();
tvaEntities.removeAllContainerFilters();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(0);
calendar.set(2013, Calendar.JANUARY, 1);
invoiceDAO.updateTVAByDefault(tva196, tva200, calendar.getTime());
} catch (SQLException e) {
Notification.show("Erreur de conversion de données", e.getMessage(), Notification.Type.ERROR_MESSAGE);
LOG.error(e.getMessage(), e);
}
}
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = NavigatorUI.class)
public static class Servlet extends VaadinServlet {
/**
*
*/
private static final long serialVersionUID = 5609038808232411088L;
@Override
public void destroy() {
PersistenceManager.getInstance().closeEntityManagerFactory();
}
}
}
|
package com.tencent.mm.plugin.nearby.a;
import com.tencent.mm.ab.l;
import com.tencent.mm.g.a.ka;
import com.tencent.mm.model.au;
import com.tencent.mm.pluginsdk.c.c;
import com.tencent.mm.protocal.c.aqv;
import com.tencent.mm.protocal.c.aqx;
import com.tencent.mm.sdk.b.b;
import java.util.Iterator;
import java.util.LinkedList;
class f$4 extends c<ka> {
final /* synthetic */ f lBu;
f$4(f fVar) {
this.lBu = fVar;
}
public final /* synthetic */ b a(int i, l lVar, b bVar) {
ka kaVar = (ka) bVar;
e eVar = (e) lVar;
kaVar.bUp.bSU = ((aqx) eVar.diG.dIE.dIL).hLg;
ka.b bVar2 = kaVar.bUp;
LinkedList linkedList = ((aqx) eVar.diG.dIE.dIL).rbQ;
if (linkedList != null) {
Iterator it = linkedList.iterator();
while (it.hasNext()) {
aqv aqv = (aqv) it.next();
au.HU();
com.tencent.mm.model.c.Gw().fX(aqv.hbL, aqv.rEJ);
}
}
bVar2.bUb = linkedList;
return kaVar;
}
public final /* synthetic */ boolean a(b bVar) {
ka kaVar = (ka) bVar;
if (kaVar.bUo.bTN) {
c.k(kaVar);
} else {
l(kaVar);
}
return false;
}
public final /* synthetic */ l b(b bVar) {
return new e(((ka) bVar).bUo.bSr);
}
public final int aAu() {
return 377;
}
}
|
public interface Buf {
void buf(Character character);
}
|
package cn.edu.zucc.web.service;
import cn.edu.zucc.web.model.User;
import cn.edu.zucc.web.model.ViewRun;
import cn.edu.zucc.web.model.ViewTotal;
import java.util.List;
/**
* Created by zxy on 11/20/2016.
*/
public interface SearchService {
List<User> selectByKeyword(String keyword, int start, int size);
List<ViewRun> selectRunsByUserno(String keyword, int start, int size);
ViewTotal selectRunByUserno(String keyword);
Integer getPageAll(String keyword);
Integer getPageDetails(String keyword);
}
|
package com.example.medicalprocess;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import classes.Utilisateur;
import android.os.AsyncTask;
import android.widget.Toast;
public class SignUpAsyncTask extends AsyncTask<Object, Void, Void> {
SignUpActivity activity;
String nom;
String prenom;
String email;
String password;
int entite;
int fonction;
@Override
protected Void doInBackground(Object... params) {
activity = (SignUpActivity) params[0];
nom = (String) params[1];
prenom = (String) params[2];
email = (String) params[3];
password = (String) params[4];
entite = (Integer) params[5];
fonction = (Integer) params[6];
return null;
}
protected void onPostExecute(Void result)
{
try {
Utilisateur.add(nom, prenom, password, email, entite, fonction);
activity.finish();
} catch (NoSuchAlgorithmException e) {
Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
activity.init();
} catch (SQLException e) {
Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
activity.init();
}
}
}
|
package pe.gob.trabajo.service;
import pe.gob.trabajo.domain.Calperiodo;
import pe.gob.trabajo.domain.Datlab;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
public class PeriodosCtsGeneratorServiveImp implements PeriodosCtsGeneratorService{
/* Fechas para CTS*/
private static final LocalDate FEC_FIN_PT1 = LocalDate.of(1990,12,31);
private static final LocalDate FEC_FIN_OSPT1 = LocalDate.of(1962,1,11);
private static final LocalDate FEC_INI_EC2 = LocalDate.of(1962,7,12);
private static final LocalDate FEC_FIN_EC2T1 = LocalDate.of(1979,9,30);
private static final LocalDate FEC_FIN_EC2T2 = LocalDate.of(1989,12,31);
private static final LocalDate FEC_FIN_PT2 = LocalDate.of(2000,10,31);
private static final LocalDate FEC_FIN_PT3 = LocalDate.of(2004,10,31);
private static final LocalDate FEC_INI_PT4 = LocalDate.of(2004,11,1);
@Override
public ArrayList<Calperiodo> getListPerCtsAnualObreroT1(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_OSPT1);
}
@Override
public ArrayList<Calperiodo> getListPerCtsAnualObreroT2(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_PT1);
}
@Override
public ArrayList<Calperiodo> getListPerCtsAnualEmpleadoT1(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_PT1);
}
@Override
public ArrayList<Calperiodo> getListPerCtsAnualEmpleadoT2ST1(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_EC2T1);
}
@Override
public ArrayList<Calperiodo> getListPerCtsAnualEmpleadoT2ST2(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_EC2T2);
}
@Override
public ArrayList<Calperiodo> getListPerCtsAnualEmpleadoT2ST3(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
return getListPerCtsReserva(listaPeriodos,datosLaborales,FEC_FIN_PT1);
}
@Override
public ArrayList<Calperiodo> getListPerCtsSemestral1(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
LocalDate fecFinRan = FEC_FIN_PT2;
LocalDate fecIniPer;
LocalDate fecFinPer;
Period tmpToFin;
Calperiodo per;
int b = 0;
int np = 1;
ArrayList<Calperiodo> listPeriodos = new ArrayList<>();
if(listaPeriodos.size()==0){
fecIniPer = datosLaborales.getdFecvincul();
} else {
listPeriodos = listaPeriodos;
fecIniPer = listaPeriodos.get(listaPeriodos.size() - 1).gettFecfin().plusDays(1);
np = listaPeriodos.get(listaPeriodos.size() - 1).getnNumper() + 1;
}
if(datosLaborales.getdFeccese().isBefore(fecFinRan)){
fecFinPer = datosLaborales.getdFeccese();
} else{
fecFinPer = fecFinRan;
}
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer);
if((per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),1,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear(),5,1)))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear(),4,30));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}else if((per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),11,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear()+1,1,1)))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear() +1,4,30));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}else if (per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),5,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear(),11,1))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear(),10,31));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}
np++;
tmpToFin = fecIniPer.until(fecFinPer);
for(int a=0;a<=tmpToFin.toTotalMonths();a=a+6){
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer.plusMonths(a));
if(per.gettFecini().plusMonths(6).isAfter(fecFinPer.minusDays(b+1))){
per.settFecfin(fecFinPer);
listPeriodos.add(per);
break;
} else{
per.settFecfin(per.gettFecini().plusMonths(6).minusDays(1));
listPeriodos.add(per);
}
b++;
np++;
}
return listPeriodos;
}
@Override
public ArrayList<Calperiodo> getListPerCtsMensual(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
LocalDate fecFinRan = FEC_FIN_PT3;
LocalDate fecIniPer;
LocalDate fecFinPer;
Period tmpToFin;
Calperiodo per;
int b = 0;
int np = 1;
ArrayList<Calperiodo> listPeriodos = new ArrayList<>();
if(listaPeriodos.size()==0){
fecIniPer = datosLaborales.getdFecvincul();
} else {
listPeriodos = listaPeriodos;
fecIniPer = listaPeriodos.get(listaPeriodos.size() - 1).gettFecfin().plusDays(1);
np = listaPeriodos.get(listaPeriodos.size() - 1).getnNumper() + 1;
}
if(datosLaborales.getdFeccese().isBefore(fecFinRan)){
fecFinPer = datosLaborales.getdFeccese();
} else{
fecFinPer = fecFinRan;
}
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer);
per.settFecfin(per.gettFecini().withDayOfMonth(1).plusMonths(1).minusDays(1));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
np++;
tmpToFin = fecIniPer.until(fecFinPer);
for(int a=0;a<=tmpToFin.toTotalMonths() + b ;a++){
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer.plusMonths(a));
if(per.gettFecini().plusMonths(1).isAfter(fecFinPer.minusDays(1))){ // Ojo aquí con las demas funciones minusdays(1)
per.settFecfin(fecFinPer);
listPeriodos.add(per);
System.out.println("ROMPIO CON F0: " + per.gettFecini() + " FF: " + per.gettFecfin());
break;
} else{
per.settFecfin(per.gettFecini().plusMonths(1).minusDays(1));
listPeriodos.add(per);
}
np++;
}
return listPeriodos;
}
@Override
public ArrayList<Calperiodo> getListPerCtsSemestral2(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales) {
LocalDate fecIniPer;
LocalDate fecFinPer;
Period tmpToFin;
Calperiodo per;
int b = 0;
int np = 1;
ArrayList<Calperiodo> listPeriodos = new ArrayList<>();
if(listaPeriodos.size()==0){
fecIniPer = datosLaborales.getdFecvincul();
} else {
listPeriodos = listaPeriodos;
fecIniPer = listaPeriodos.get(listaPeriodos.size() - 1).gettFecfin().plusDays(1);
np = listaPeriodos.get(listaPeriodos.size() - 1).getnNumper() + 1;
}
fecFinPer = datosLaborales.getdFecvincul();
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer);
if((per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),1,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear(),5,1)))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear(),4,30));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}else if((per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),11,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear()+1,1,1)))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear() +1,4,30));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}else if (per.gettFecini().isAfter(LocalDate.of(fecIniPer.getYear(),5,1).minusDays(1))&&
per.gettFecini().isBefore(LocalDate.of(per.gettFecini().getYear(),11,1))){
per.settFecfin(LocalDate.of(per.gettFecini().getYear(),10,31));
listPeriodos.add(per);
fecIniPer = per.gettFecfin().plusDays(1);
}
np++;
tmpToFin = fecIniPer.until(fecFinPer);
for(int a=0;a<=tmpToFin.toTotalMonths();a=a+6){
per = new Calperiodo();
per.setnNumper(np);
per.settFecini(fecIniPer.plusMonths(a));
if(per.gettFecini().plusMonths(6).isAfter(fecFinPer.minusDays(b+1))){
per.settFecfin(fecFinPer);
listPeriodos.add(per);
break;
} else{
per.settFecfin(per.gettFecini().plusMonths(6).minusDays(1));
listPeriodos.add(per);
}
b++;
np++;
}
return listPeriodos;
}
/* Funcion para pediodos Cts de la Reserva */
@Override
public ArrayList<Calperiodo> getListPerCtsReserva(ArrayList<Calperiodo> listaPeriodos, Datlab datosLaborales, LocalDate fecFinRan ) {
ArrayList<Calperiodo> listPeriodos = new ArrayList<>();
Calperiodo per;
LocalDate fecFinPer;
LocalDate fecIniPer;
int np = 0;
if(listaPeriodos.size()==0){
fecIniPer = datosLaborales.getdFecvincul();
} else {
listPeriodos = listaPeriodos;
fecIniPer = listaPeriodos.get(listaPeriodos.size() - 1).gettFecfin().plusDays(1);
np = listaPeriodos.get(listaPeriodos.size() - 1).getnNumper();
}
if(datosLaborales.getdFeccese().isBefore(fecFinRan)){
fecFinPer = datosLaborales.getdFeccese();
} else{
fecFinPer = fecFinRan;
}
per = new Calperiodo();
np++;
per.setnNumper(np);
per.settFecini(fecIniPer);
LocalDate as;
for(as = datosLaborales.getdFecvincul();as.isBefore(fecFinPer.plusDays(1));as = as.plusYears(1)){
if(as.isAfter(fecIniPer.minusDays(1))){
// System.out.println(fecIniPer + " Fecha: "+ as + " " + fecFinPer);
//
if(per.gettFecini().plusYears(1).minusDays(1).isAfter(fecFinPer.minusDays(1))){
per.settFecfin(fecFinPer);
listPeriodos.add(per);
break;
} else {
per.settFecfin(as.minusDays(1).plusYears(1));//plus
listPeriodos.add(per);
break;
}
}
}
return null;
}
}
|
package string;
public class Exercise11 {
public String subBigInteger(String a, String b) {
StringBuilder res = new StringBuilder();
int count = 1;
int miss = 0;
int sub = 0;
if (a.length() < b.length() || (a.length() == b.length() && a.compareTo(b) < 0)) {
return "-" + subBigInteger(b,a);
}
while (count <= a.length()) {
sub = digitFromRight(a, count) - digitFromRight(b, count) + miss;
miss = sub < 0 ? -1 : 0;
res.append(10 * -miss + sub);
count++;
}
return standardizeNumber(res.reverse().toString());
}
private static int digitFromRight(String str, int right){
if (str.length() - right < 0) return 0;
return str.charAt(str.length() - right) - '0';
}
public String standardizeNumber(String str) {
int i = 0;
while(i < str.length() && str.charAt(i) == '0') i ++;
return str.substring(i);
}
}
|
package Exception.FileException;
public class FileWriteFailException extends FileException {
public FileWriteFailException(String message) {
super(message);
}
}
|
package com.tencent.mm.plugin.fav.a.a;
import com.tencent.mm.protocal.c.vv;
import com.tencent.mm.protocal.c.vx;
import com.tencent.mm.protocal.c.vy;
import com.tencent.mm.protocal.c.vz;
import com.tencent.mm.protocal.c.wa;
import com.tencent.mm.protocal.c.we;
import com.tencent.mm.protocal.c.wk;
import com.tencent.mm.protocal.c.wu;
import com.tencent.mm.protocal.c.xa;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.List;
public final class a {
public static String bc(List<vx> list) {
if (list == null || list.size() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml data list empty");
return "";
}
int size = list.size();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("<datalist count='").append(size).append("'>");
for (int i = 0; i < size; i++) {
vx vxVar = (vx) list.get(i);
stringBuffer.append("<dataitem ");
if (vxVar.rzC) {
stringBuffer.append("datatype='").append(vxVar.bjS).append("'");
}
if (vxVar.rAf) {
stringBuffer.append(" datastatus='").append(vxVar.rAe).append("'");
}
if (vxVar.rzL) {
stringBuffer.append(" dataid='").append(vxVar.jdM).append("'");
}
if (vxVar.rAr) {
stringBuffer.append(" htmlid='").append(bi.WS(vxVar.rAq)).append("'");
}
if (vxVar.rAx) {
stringBuffer.append(" dataillegaltype='").append(vxVar.rAw).append("'");
}
if (vxVar.rzX) {
stringBuffer.append(" datasourceid='").append(vxVar.rzW).append("'");
}
stringBuffer.append(">");
if (vxVar.rzE) {
stringBuffer.append("<datafmt>").append(vxVar.rzD).append("</datafmt>");
}
if (vxVar.rzh) {
stringBuffer.append("<datatitle>").append(bi.WS(vxVar.title)).append("</datatitle>");
}
if (vxVar.rzi) {
stringBuffer.append("<datadesc>").append(bi.WS(vxVar.desc)).append("</datadesc>");
}
if (vxVar.rzj) {
stringBuffer.append("<cdn_thumburl>").append(bi.WS(vxVar.dwE)).append("</cdn_thumburl>");
}
if (vxVar.rzm) {
stringBuffer.append("<thumb_width>").append(vxVar.dwJ).append("</thumb_width>");
}
if (vxVar.rzn) {
stringBuffer.append("<thumb_height>").append(vxVar.dwI).append("</thumb_height>");
}
if (vxVar.rzp) {
stringBuffer.append("<cdn_dataurl>").append(bi.WS(vxVar.rzo)).append("</cdn_dataurl>");
}
if (vxVar.rzl) {
stringBuffer.append("<cdn_thumbkey>").append(bi.WS(vxVar.rzk)).append("</cdn_thumbkey>");
}
if (vxVar.rzr) {
stringBuffer.append("<cdn_datakey>").append(bi.WS(vxVar.rzq)).append("</cdn_datakey>");
}
if (vxVar.rzt) {
stringBuffer.append("<cdn_encryver>").append(vxVar.rzs).append("</cdn_encryver>");
}
if (vxVar.rzu) {
stringBuffer.append("<duration>").append(vxVar.duration).append("</duration>");
}
if (vxVar.rzw) {
stringBuffer.append("<stream_weburl>").append(bi.WS(vxVar.rzv)).append("</stream_weburl>");
}
if (vxVar.rzy) {
stringBuffer.append("<stream_dataurl>").append(bi.WS(vxVar.rzx)).append("</stream_dataurl>");
}
if (vxVar.rzA) {
stringBuffer.append("<stream_lowbandurl>").append(bi.WS(vxVar.rzz)).append("</stream_lowbandurl>");
}
if (vxVar.rzB) {
stringBuffer.append("<dataext>").append(bi.WS(vxVar.bJv)).append("</dataext>");
}
if (vxVar.rzG) {
stringBuffer.append("<fullmd5>").append(vxVar.rzF).append("</fullmd5>");
}
if (vxVar.rzI) {
stringBuffer.append("<head256md5>").append(vxVar.rzH).append("</head256md5>");
}
if (vxVar.rzK) {
stringBuffer.append("<fullsize>").append(vxVar.rzJ).append("</fullsize>");
}
if (vxVar.rzR) {
stringBuffer.append("<thumbfullmd5>").append(vxVar.rzQ).append("</thumbfullmd5>");
}
if (vxVar.rzT) {
stringBuffer.append("<thumbhead256md5>").append(vxVar.rzS).append("</thumbhead256md5>");
}
if (vxVar.rzV) {
stringBuffer.append("<thumbfullsize>").append(vxVar.rzU).append("</thumbfullsize>");
}
if (vxVar.rzZ) {
stringBuffer.append("<stream_videoid>").append(bi.WS(vxVar.rzY)).append("</stream_videoid>");
}
if (vxVar.rAh) {
stringBuffer.append("<datasrctitle>").append(bi.WS(vxVar.rAg)).append("</datasrctitle>");
}
if (vxVar.rAl) {
stringBuffer.append("<datasrcname>").append(bi.WS(vxVar.rAk)).append("</datasrcname>");
}
if (vxVar.rAn) {
stringBuffer.append("<datasrctime>").append(bi.WS(vxVar.rAm)).append("</datasrctime>");
}
if (vxVar.rAt && (vxVar.rAi == null || vxVar.rAi.rAN == null || vxVar.rAi.rAN.boi() == 0)) {
stringBuffer.append("<canvasPageXml>").append(bi.WS(vxVar.canvasPageXml)).append("</canvasPageXml>");
}
if (vxVar.rAs) {
stringBuffer.append("<statextstr>").append(bi.WS(vxVar.bZN)).append("</statextstr>");
}
if (vxVar.rAz) {
stringBuffer.append("<recordxml>").append(vxVar.rAy).append("</recordxml>");
}
wa waVar = vxVar.rAo;
if (waVar != null) {
stringBuffer.append("<streamvideo>");
stringBuffer.append("<streamvideourl>").append(bi.WS(waVar.dyJ)).append("</streamvideourl>");
stringBuffer.append("<streamvideototaltime>").append(waVar.rBq).append("</streamvideototaltime>");
stringBuffer.append("<streamvideotitle>").append(bi.WS(waVar.dyL)).append("</streamvideotitle>");
stringBuffer.append("<streamvideowording>").append(bi.WS(waVar.dyM)).append("</streamvideowording>");
stringBuffer.append("<streamvideoweburl>").append(bi.WS(waVar.dyN)).append("</streamvideoweburl>");
stringBuffer.append("<streamvideoaduxinfo>").append(bi.WS(waVar.dyP)).append("</streamvideoaduxinfo>");
stringBuffer.append("<streamvideopublishid>").append(bi.WS(waVar.dyQ)).append("</streamvideopublishid>");
stringBuffer.append("</streamvideo>");
}
vy vyVar = vxVar.rAi;
if (vyVar == null || vyVar.rAJ == null || vyVar.rAJ.boi() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml, data source item empty");
} else {
vz vzVar = vyVar.rAJ;
stringBuffer.append("<dataitemsource");
if (vzVar.rBc) {
stringBuffer.append(" sourcetype='").append(vzVar.bJt).append("'");
}
if (vzVar.rBg) {
stringBuffer.append(" sourceid='").append(vzVar.rBf).append("'");
}
stringBuffer.append(">");
if (vzVar.rBd) {
stringBuffer.append("<fromusr>").append(bi.WS(vzVar.bSS)).append("</fromusr>");
}
if (vzVar.rBe) {
stringBuffer.append("<tousr>").append(bi.WS(vzVar.toUser)).append("</tousr>");
}
if (vzVar.rBi) {
stringBuffer.append("<realchatname>").append(bi.WS(vzVar.rBh)).append("</realchatname>");
}
if (vzVar.rBj) {
stringBuffer.append("<msgid>").append(vzVar.bWQ).append("</msgid>");
}
if (vzVar.rBk) {
stringBuffer.append("<eventid>").append(vzVar.cca).append("</eventid>");
}
if (vzVar.rBl) {
stringBuffer.append("<appid>").append(vzVar.appId).append("</appid>");
}
if (vzVar.rBm) {
stringBuffer.append("<link>").append(bi.WS(vzVar.egr)).append("</link>");
}
if (vzVar.rBp) {
stringBuffer.append("<brandid>").append(bi.WS(vzVar.bGy)).append("</brandid>");
}
stringBuffer.append("</dataitemsource>");
}
vyVar = vxVar.rAi;
if (vyVar == null || vyVar.rAL == null || vyVar.rAL.boi() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml, loc item empty");
} else {
we weVar = vyVar.rAL;
stringBuffer.append("<locitem>");
if (weVar.rBx) {
stringBuffer.append("<label>").append(bi.WS(weVar.label)).append("</label>");
}
if (weVar.rBv) {
stringBuffer.append("<lat>").append(weVar.lat).append("</lat>");
}
if (weVar.rBu) {
stringBuffer.append("<lng>").append(weVar.lng).append("</lng>");
}
if (weVar.rBw) {
stringBuffer.append("<scale>").append(weVar.bSz).append("</scale>");
}
if (weVar.rBy) {
stringBuffer.append("<poiname>").append(weVar.bWB).append("</poiname>");
}
stringBuffer.append("</locitem>");
}
vyVar = vxVar.rAi;
if (vyVar == null || vyVar.rAN == null || vyVar.rAN.boi() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml, url item empty");
} else {
xa xaVar = vyVar.rAN;
stringBuffer.append("<weburlitem>");
if (xaVar.rCo) {
stringBuffer.append("<clean_url>").append(bi.WS(xaVar.rCn)).append("</clean_url>");
}
if (xaVar.rzi) {
stringBuffer.append("<pagedesc>").append(bi.WS(xaVar.desc)).append("</pagedesc>");
}
if (xaVar.rBD) {
stringBuffer.append("<pagethumb_url>").append(bi.WS(xaVar.thumbUrl)).append("</pagethumb_url>");
}
if (xaVar.rzh) {
stringBuffer.append("<pagetitle>").append(bi.WS(xaVar.title)).append("</pagetitle>");
}
if (xaVar.rCq) {
stringBuffer.append("<opencache>").append(xaVar.rCp).append("</opencache>");
}
if (xaVar.rCr) {
stringBuffer.append("<contentattr>").append(xaVar.dwt).append("</contentattr>");
}
if (xaVar.rAt) {
stringBuffer.append("<canvasPageXml>").append(bi.WS(xaVar.canvasPageXml)).append("</canvasPageXml>");
}
stringBuffer.append("</weburlitem>");
}
vyVar = vxVar.rAi;
if (vyVar == null || vyVar.rAP == null || vyVar.rAP.boi() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml, product item empty");
} else {
wk wkVar = vyVar.rAP;
stringBuffer.append("<productitem");
if (wkVar.rBF) {
stringBuffer.append(" type='").append(wkVar.type).append("'");
}
stringBuffer.append(">");
if (wkVar.rzh) {
stringBuffer.append("<producttitle>").append(bi.WS(wkVar.title)).append("</producttitle>");
}
if (wkVar.rzi) {
stringBuffer.append("<productdesc>").append(bi.WS(wkVar.desc)).append("</productdesc>");
}
if (wkVar.rBD) {
stringBuffer.append("<productthumb_url>").append(bi.WS(wkVar.thumbUrl)).append("</productthumb_url>");
}
if (wkVar.rBE) {
stringBuffer.append("<productinfo>").append(bi.WS(wkVar.info)).append("</productinfo>");
}
stringBuffer.append("</productitem>");
}
vyVar = vxVar.rAi;
if (vyVar == null || vyVar.rAR == null || vyVar.rAR.boi() == 0) {
x.v("MicroMsg.FavDataItemParser", "klem toXml, product item empty");
} else {
wu wuVar = vyVar.rAR;
stringBuffer.append("<tvitem>");
if (wuVar.rzh) {
stringBuffer.append("<tvtitle>").append(bi.WS(wuVar.title)).append("</tvtitle>");
}
if (wuVar.rzi) {
stringBuffer.append("<tvdesc>").append(bi.WS(wuVar.desc)).append("</tvdesc>");
}
if (wuVar.rBD) {
stringBuffer.append("<tvthumb_url>").append(bi.WS(wuVar.thumbUrl)).append("</tvthumb_url>");
}
if (wuVar.rBE) {
stringBuffer.append("<tvinfo>").append(bi.WS(wuVar.info)).append("</tvinfo>");
}
stringBuffer.append("</tvitem>");
}
vy vyVar2 = vxVar.rAi;
if (vyVar2 == null || vyVar2.rBa == null) {
x.e("MicroMsg.FavDataItemParser", "setAppBrandXml toXml, item empty");
} else {
vv vvVar = vyVar2.rBa;
if (vvVar != null) {
stringBuffer.append("<appbranditem>");
stringBuffer.append("<username>").append(bi.WS(vvVar.username)).append("</username>");
stringBuffer.append("<appid>").append(bi.WS(vvVar.appId)).append("</appid>");
stringBuffer.append("<pkgtype>").append(vvVar.bPh).append("</pkgtype>");
stringBuffer.append("<iconurl>").append(bi.WS(vvVar.iconUrl)).append("</iconurl>");
stringBuffer.append("<type>").append(vvVar.type).append("</type>");
stringBuffer.append("<pagepath>").append(bi.WS(vvVar.bGH)).append("</pagepath>");
stringBuffer.append("<sourcedisplayname>").append(bi.WS(vvVar.rzd)).append("</sourcedisplayname>");
stringBuffer.append("</appbranditem>");
}
}
stringBuffer.append("</dataitem>");
}
stringBuffer.append("</datalist>");
return stringBuffer.toString();
}
}
|
package com.chat.zipchat.Activity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.chat.zipchat.Fragment.ContactsFragment;
import com.chat.zipchat.Fragment.HomeFragment;
import com.chat.zipchat.Fragment.PaymentFragment;
import com.chat.zipchat.Fragment.ProfileFragment;
import com.chat.zipchat.Fragment.SettingsFragment;
import com.chat.zipchat.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import static com.chat.zipchat.Common.BaseClass.ConvertedDateTime;
import static com.chat.zipchat.Common.BaseClass.Invitefriend;
import static com.chat.zipchat.Common.BaseClass.UserId;
import static com.chat.zipchat.Common.BaseClass.isOnline;
import static com.chat.zipchat.Common.SessionManager.KEY_PROFILE_PIC;
import static com.chat.zipchat.Common.SessionManager.KEY_USERNAME;
import static com.chat.zipchat.Common.SessionManager.PREF_NAME;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
FrameLayout frame;
FragmentManager fragmentManager;
public static ImageView mImgUser;
TextView mTxtUserName, mToolbarTitle;
public static Toolbar toolbar;
DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbarTitle = findViewById(R.id.mToolbarTitle);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fragmentManager = getSupportFragmentManager();
frame = (FrameLayout) findViewById(R.id.frame);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.setDrawerIndicatorEnabled(false);
Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.menu_icon, getTheme());
toggle.setHomeAsUpIndicator(drawable);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (drawer.isDrawerVisible(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
onNavigationItemSelected(navigationView.getMenu().getItem(0));
View hView = navigationView.getHeaderView(0);
mImgUser = hView.findViewById(R.id.mImgUser);
mTxtUserName = hView.findViewById(R.id.mTxtUserName);
mImgUser.setOnClickListener(this);
SharedPreferences sharedpreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Glide.with(this).load(sharedpreferences.getString(KEY_PROFILE_PIC, null)).error(R.drawable.defult_user).into(mImgUser);
mTxtUserName.setText(sharedpreferences.getString(KEY_USERNAME, null));
HomeFragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.frame, homeFragment).commit();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
setResult(Activity.RESULT_CANCELED);
finishAffinity();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
item.setChecked(true);
if (id == R.id.nav_chats) {
HomeFragment homeFragment = new HomeFragment();
mToolbarTitle.setText(getResources().getText(R.string.chats));
fragmentManager.beginTransaction().replace(R.id.frame, homeFragment).commit();
} else if (id == R.id.nav_contacts) {
mToolbarTitle.setText(getResources().getText(R.string.contacts));
ContactsFragment contactsFragment = new ContactsFragment(this);
fragmentManager.beginTransaction().replace(R.id.frame, contactsFragment).commit();
} else if (id == R.id.nav_profile) {
mToolbarTitle.setText(getResources().getText(R.string.profile));
ProfileFragment profileFragment = new ProfileFragment(this);
fragmentManager.beginTransaction().replace(R.id.frame, profileFragment).commit();
} else if (id == R.id.nav_settings) {
mToolbarTitle.setText(getResources().getText(R.string.settings));
SettingsFragment settingsFragment = new SettingsFragment();
fragmentManager.beginTransaction().replace(R.id.frame, settingsFragment).commit();
} else if (id == R.id.nav_payments) {
mToolbarTitle.setText(getResources().getText(R.string.payments));
PaymentFragment paymentFragment = new PaymentFragment(this);
fragmentManager.beginTransaction().replace(R.id.frame, paymentFragment).commit();
} else if (id == R.id.nav_invite_friend) {
Invitefriend(this);
} else if (id == R.id.nav_help) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onResume() {
super.onResume();
DatabaseReference userLastOnlineRef = FirebaseDatabase.getInstance().getReference("user-details").child(UserId(this)).child("profile-details");
if (isOnline(this)) {
HashMap<String, Object> map = new HashMap<>();
map.put("isOnline", "1");
map.put("offline-time", ConvertedDateTime());
userLastOnlineRef.updateChildren(map);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
DatabaseReference userLastOnlineRef = FirebaseDatabase.getInstance().getReference("user-details").child(UserId(this)).child("profile-details");
HashMap<String, Object> map = new HashMap<>();
map.put("isOnline", "0");
map.put("offline-time", ConvertedDateTime());
userLastOnlineRef.onDisconnect().updateChildren(map);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mImgUser:
mToolbarTitle.setText(getResources().getText(R.string.profile));
ProfileFragment profileFragment = new ProfileFragment(this);
fragmentManager.beginTransaction().replace(R.id.frame, profileFragment).commit();
drawer.closeDrawer(GravityCompat.START);
break;
}
}
}
|
package uk.gov.hmcts.befta.dse.ccd;
import uk.gov.hmcts.befta.dse.ccd.definition.converter.ExcelTransformer;
import uk.gov.hmcts.befta.dse.ccd.definition.converter.JsonTransformer;
import java.io.File;
public class CcdBeftaUtils {
public static File convertJsonDefinitionToExcel(String jsonFolderPath) {
String path = new JsonTransformer(jsonFolderPath).transformToExcel();
return new File(path);
}
public static File convertJsonDefinitionToExcel(File jsonFolder) {
String path = new JsonTransformer(jsonFolder.getPath()).transformToExcel();
return new File(path);
}
public static File convertExcelFileToJson(String excelFilePath) {
String path = new ExcelTransformer(excelFilePath).transformToJson();
return new File(path);
}
public static File convertExcelFileToJson(File excelFile) {
String path = new ExcelTransformer(excelFile.getPath()).transformToJson();
return new File(path);
}
}
|
package org.ecsoya.yamail.utils;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
public class IOUtils {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final int EOF = -1;
public static void copy(InputStream input, Writer output)
throws IOException {
copy(input, output, Charset.defaultCharset());
}
public static void copy(InputStream input, Writer output, Charset encoding)
throws IOException {
InputStreamReader in = new InputStreamReader(input, toCharset(encoding));
copy(in, output);
}
public static Charset toCharset(Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
}
public static Charset toCharset(String charset) {
return charset == null ? Charset.defaultCharset() : Charset
.forName(charset);
}
public static int copy(Reader input, Writer output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
public static long copyLarge(Reader input, Writer output)
throws IOException {
return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]);
}
public static long copyLarge(Reader input, Writer output, char[] buffer)
throws IOException {
long count = 0;
int n = 0;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}
private IOUtils() {
}
}
|
package JavaSessions;
import java.util.ArrayList;
public class ArrayListConcept {
public static void main(String[] args) {
//default class in java
ArrayList ar=new ArrayList();
System.out.println(ar.size());
//ar.add method
ar.add(100);//0
ar.add(200);//1
System.out.println(ar.size());
ar.add(300);//2
ar.add(400);//3
System.out.println(ar.size());
ar.add(500);//4
ar.add(600);//5
ar.add(700);//6
System.out.println(ar.size());
ar.add(800);//7
ar.add(900);//8
ar.add(1000);//9
System.out.println(ar.size());
ar.add(1100);//10
//get method to print the elements of an ArrayList
System.out.println(ar.get(1));
System.out.println(ar.get(8));
System.out.println("li is " + 0);
System.out.println("hi is + " + (ar.size()-1));
ArrayList arr=new ArrayList();//dynamic
arr.add("Uttam");
arr.add('M');
arr.add(38);
for(int i=0;i<arr.size(); i++) {
System.out.println(arr.get(i));
}
System.out.println("------ **** -------");
//generics
ArrayList<Integer> marksList =new ArrayList<Integer>();
marksList.add(20);
marksList.add(30);
marksList.add(40);
marksList.add(50);
//marksList.add("tom");
// for each
for(Integer ele : marksList) {
System.out.println(ele);
}
System.out.println("------ **** -------");
ArrayList<String> countryList =new ArrayList<String>();
countryList.add("USA");
countryList.add("India");
//for each loop
for(String data : countryList) {
System.out.println(data);
}
ArrayList<Object> empData=new ArrayList<Object>();
empData.add("Tom");
empData.add(25);
empData.add('m');
empData.add(true);
empData.add(34.55);
System.out.println("------------");
for(int j=0; j<empData.size(); j++) {
System.out.println(empData.get(j));
}
//for each
//syso+cnt+space
for(Object elements : empData) {
System.out.println(elements);
}
}
}
|
package pro.eddiecache.kits.disk.indexed;
import pro.eddiecache.kits.disk.AbstractDiskCacheAttributes;
public class IndexedDiskCacheAttributes extends AbstractDiskCacheAttributes
{
private static final long serialVersionUID = 1L;
private static final int DEFAULT_MAX_KEY_SIZE = 5000;
private int maxKeySize = DEFAULT_MAX_KEY_SIZE;
private int optimizeAtRemoveCount = -1;
public static final boolean DEFAULT_OPTIMIZE_ON_SHUTDOWN = true;
private boolean optimizeOnShutdown = DEFAULT_OPTIMIZE_ON_SHUTDOWN;
public static final boolean DEFAULT_CLEAR_DISK_ON_STARTUP = false;
private boolean clearDiskOnStartup = DEFAULT_CLEAR_DISK_ON_STARTUP;
public IndexedDiskCacheAttributes()
{
super();
}
public int getMaxKeySize()
{
return this.maxKeySize;
}
public void setMaxKeySize(int maxKeySize)
{
this.maxKeySize = maxKeySize;
}
public int getOptimizeAtRemoveCount()
{
return this.optimizeAtRemoveCount;
}
public void setOptimizeAtRemoveCount(int cnt)
{
this.optimizeAtRemoveCount = cnt;
}
public void setOptimizeOnShutdown(boolean optimizeOnShutdown)
{
this.optimizeOnShutdown = optimizeOnShutdown;
}
public boolean isOptimizeOnShutdown()
{
return optimizeOnShutdown;
}
public void setClearDiskOnStartup(boolean clearDiskOnStartup)
{
this.clearDiskOnStartup = clearDiskOnStartup;
}
public boolean isClearDiskOnStartup()
{
return clearDiskOnStartup;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("IndexedDiskCacheAttributes ");
sb.append("\n diskPath = " + super.getDiskPath());
sb.append("\n maxPurgatorySize = " + super.getMaxPurgatorySize());
sb.append("\n maxKeySize = " + maxKeySize);
sb.append("\n optimizeAtRemoveCount = " + optimizeAtRemoveCount);
sb.append("\n shutdownSpoolTimeLimit = " + super.getShutdownSpoolTimeLimit());
sb.append("\n optimizeOnShutdown = " + optimizeOnShutdown);
sb.append("\n clearDiskOnStartup = " + clearDiskOnStartup);
return sb.toString();
}
}
|
package fr.demos;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.demos.formation.today.Climatisation;
/**
* Servlet implementation class MaDate
*/
@WebServlet("/MaDateController")
public class MaDateController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public MaDateController() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// d represente le model
Date d = new Date();
SimpleDateFormat sdf=new SimpleDateFormat ("EEE, MMM d, ''yyy' et il est' k 'heure' m 'minute'");
String laDate=sdf.format(d);
Climatisation clim1= new Climatisation ("t3", 12, 10, 1100);
// transfert du model
request.setAttribute("dateduJour", laDate);
request.setAttribute("clim1", clim1);
//appeler la vue
RequestDispatcher rd=request.getRequestDispatcher("/madateView.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
/**
* Created at 2008-01-23.
*/
package com.allinpay.generator.ibatis.generator;
import java.io.File;
/**
* @author pony
* 如果有任何对代码的修改,请按下面的格式注明修改的内容.
* 序号 时间 作者 修改内容
* 1. 2008-1-23 pony created this class.
*/
public class ServiceContextXmlGenerator extends AbstractConfigFileGenerator {
public ServiceContextXmlGenerator() {
setTemplateFile("context-service.html");
setModuleFilePath("resource/context");
}
/* (non-Javadoc)
* @see com.allinpay.generator.ibatis.generator.AbstractCodeGenerator#createEmptyGeneratedFile(java.lang.String)
*/
@Override
public File createEmptyGeneratedFile(String fileName) {
String moduleName = (String) getModel().get("lastPackageName");
String dir = getGeneratedFilePath() + File.separator + getModuleFilePath() + File.separator ;
new File(dir).mkdirs();
String filepath = dir + File.separator + moduleName + "-service.xml";
File file = new File(filepath);
return file;
}
protected String getGeneratedFilename(String fileName) {
String moduleName = (String) getModel().get("lastPackageName");
String filepath = getGeneratedFilePath() + File.separator + getModuleFilePath() + File.separator+ moduleName + "-service.xml";
return filepath;
}
/* (non-Javadoc)
* @see com.allinpay.generator.ibatis.generator.AbstractCodeGenerator#getPackageIdentifier()
*/
@Override
public String getPackageIdentifier() {
return "";
}
/* (non-Javadoc)
* @see com.allinpay.generator.ibatis.ICodeGenerator#getName()
*/
public String getName() {
return "ServiceContentXmlGenerator";
}
}
|
package studio.baka.originiumcraft.entity;
import net.minecraft.entity.Entity;
import net.minecraft.util.Tuple;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class OCEntities {
public static final List<Tuple<Class<? extends Entity>,EntityRegistryProperties>> ENTITIYCLASSES = new ArrayList<>(
Arrays.asList(
new Tuple<>(EntityOriginiumInsect.class,EntityOriginiumInsect.REGISTRY_PROPERTIES),
new Tuple<>(EntityCastle3.class,EntityCastle3.REGISTRY_PROPERTIES)
)
);
}
|
package com.igitras.codegen.common.next;
/**
* Created by mason on 1/4/15.
*/
public interface CgMethod
extends CgMember, CgNameIdentifierOwner, CgModifierListOwner, CgTypeParameterListOwner, CgDocCommentOwner {
/**
* Returns the return type of the method.
*
* @return the method return type, or null if the method is a constructor.
*/
CgType getReturnType();
/**
* Returns the type element for the return type of the method.
*
* @return the type element for the return type, or null if the method is a constructor.
*/
CgTypeElement getReturnTypeElement();
/**
* Returns the parameter list for the method.
*
* @return the parameter list instance.
*/
CgParameterList getParameterList();
/**
* Returns the list of thrown exceptions for the method.
*
* @return the list of thrown exceptions instance.
*/
CgReferenceList getThrowsList();
/**
* Returns the body of the method.
*
* @return the method body, or null if the method belongs to a compiled class.
*/
CgCodeBlock getBody();
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* TvTasktime generated by hbm2java
*/
public class TvTasktime implements java.io.Serializable {
private TvTasktimeId id;
public TvTasktime() {
}
public TvTasktime(TvTasktimeId id) {
this.id = id;
}
public TvTasktimeId getId() {
return this.id;
}
public void setId(TvTasktimeId id) {
this.id = id;
}
}
|
package com.victor.stockpesistentdata.ui.adapter;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.victor.stockpesistentdata.R;
import com.victor.stockpesistentdata.model.Item;
import com.victor.stockpesistentdata.util.PriceUtil;
import java.util.ArrayList;
import java.util.List;
public class StockListAdapter extends RecyclerView.Adapter<StockListAdapter.StockListViewHolder> {
private final Context context;
private final List<Item> items = new ArrayList<>();
private ItemClickListener itemClickListener;
private ItemRemoveListener itemRemoveListener = (item, position) -> {
};
public StockListAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public StockListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardview_item, parent, false);
return new StockListViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull StockListViewHolder holder, int position) {
Item item = items.get(position);
holder.bindInformation(item);
}
@Override
public int getItemCount() {
return items.size();
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public void setItemRemoveListener(ItemRemoveListener itemRemoveListener) {
this.itemRemoveListener = itemRemoveListener;
}
public void add(Item item) {
items.add(item);
notifyDataSetChanged();
}
public void updateList(List<Item> result) {
items.clear();
items.addAll(result);
notifyDataSetChanged();
}
public void update(int position, Item result) {
items.set(position, result);
notifyDataSetChanged();
}
public void delete(Item item) {
items.remove(item);
notifyDataSetChanged();
}
class StockListViewHolder extends RecyclerView.ViewHolder {
private final TextView itemId;
private final TextView itemName;
private final TextView itemPrice;
private final TextView itemQnt;
private Item item;
public StockListViewHolder(@NonNull View itemView) {
super(itemView);
itemId = itemView.findViewById(R.id.cardview_item_id);
itemName = itemView.findViewById(R.id.cardview_item_name);
itemPrice = itemView.findViewById(R.id.cardview_item_price);
itemQnt = itemView.findViewById(R.id.cardview_item_qnt);
editListener(itemView);
deleteListener(itemView);
}
private void editListener(@NonNull View itemView) {
itemView.setOnClickListener(view -> itemClickListener.onItemClick(item, getAdapterPosition()));
}
private void deleteListener(@NonNull View itemView) {
itemView.setOnCreateContextMenuListener((contextMenu, view, contextMenuInfo) -> {
new MenuInflater(context).inflate(R.menu.menu_remove_item, contextMenu);
contextMenu.findItem(R.id.menu_remove_item)
.setOnMenuItemClickListener(menuItem -> {
itemRemoveListener.onItemClick(item, getAdapterPosition());
return true;
});
});
}
public void bindInformation(Item item) {
this.item = item;
String id = String.valueOf(item.getId());
itemId.setText(id);
itemName.setText(item.getName());
itemPrice.setText(PriceUtil.priceCurrency(item.getPrice()));
itemQnt.setText(item.getQuantityString());
}
}
public interface ItemClickListener {
void onItemClick(Item item, int position);
}
public interface ItemRemoveListener {
void onItemClick(Item item, int position);
}
}
|
package fiscal;
public enum FiscalAcaoCuidadoEspecialEnum {
LIVRE(1L), ALERTA(2L);
FiscalAcaoCuidadoEspecialEnum(Long value) {
this.value = value;
}
private Long value;
public void setValue(Long value) {
this.value = value;
}
public Long getValue() {
return value;
}
public boolean compareTo(FiscalAcaoTicket acaoTicket) {
return acaoTicket.getId().equals(this.getValue()) ? true : false;
}
}
|
package com.tencent.mm.plugin.subapp.b;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.afw;
import com.tencent.mm.protocal.c.afx;
import com.tencent.mm.sdk.platformtools.x;
import java.io.IOException;
import java.io.RandomAccessFile;
public final class a extends l implements k {
private RandomAccessFile aBA = null;
private int dHI = 0;
private e diJ;
private String filePath = null;
private int hjW = 0;
String url;
public a(String str) {
this.url = str;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a();
aVar.dIG = new afw();
aVar.dIH = new afx();
aVar.uri = "/cgi-bin/micromsg-bin/getpsmimg";
aVar.dIF = 141;
aVar.dII = 29;
aVar.dIJ = 1000000029;
b KT = aVar.KT();
afw afw = (afw) KT.dID.dIL;
afw.URL = this.url;
afw.rjC = this.hjW;
x.v("MicroMsg.NetSceneGetPSMImg", "doscene url:[" + this.url + "] + offset:" + this.hjW + " totallen:" + this.dHI);
return a(eVar, KT, this);
}
protected final int a(q qVar) {
String str = ((afw) ((b) qVar).dID.dIL).URL;
Object obj = str == null ? null : str.indexOf("weixin://") != 0 ? null : 1;
if (obj == null) {
x.e("MicroMsg.NetSceneGetPSMImg", "security checked failed : url invalid:" + this.url);
return l.b.dJn;
} else if (this.hjW < 0 || this.dHI < 0) {
x.e("MicroMsg.NetSceneGetPSMImg", "security checked failed : offset:" + this.hjW + " total:" + this.dHI);
return l.b.dJn;
} else {
if (this.hjW == 0) {
if (this.dHI != 0) {
x.e("MicroMsg.NetSceneGetPSMImg", "security checked failed : offset:" + this.hjW + " total:" + this.dHI);
return l.b.dJn;
}
} else if (this.hjW >= this.dHI) {
x.e("MicroMsg.NetSceneGetPSMImg", "security checked failed : offset:" + this.hjW + " total:" + this.dHI);
return l.b.dJn;
}
return l.b.dJm;
}
}
protected final int Cc() {
return 10;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
if (i2 == 0 && i3 == 0) {
afx afx = (afx) ((b) qVar).dIE.dIL;
x.d("MicroMsg.NetSceneGetPSMImg", "onGYNetEnd url:[" + this.url + "] + offset:" + this.hjW + " Resp[ totallen:" + afx.rjB + " bufSize:" + afx.rtW.siI + " ]");
if (afx.rjB > 0) {
this.dHI = afx.rjB;
}
if (d(this.url, afx.rtW.siK.lR, this.hjW)) {
this.hjW = afx.rtW.siI + this.hjW;
if (this.dHI <= this.hjW) {
x.d("MicroMsg.NetSceneGetPSMImg", "down url:[" + this.url + "] final size: " + this.dHI);
this.diJ.a(i2, i3, str, this);
return;
} else if (a(this.dIX, this.diJ) < 0) {
this.diJ.a(i2, i3, str, this);
return;
} else {
return;
}
}
this.diJ.a(3, -1, str, this);
return;
}
x.e("MicroMsg.NetSceneGetPSMImg", "onGYNetEnd errType:" + i2 + " errCode:" + i3);
this.diJ.a(i2, i3, str, this);
}
private boolean d(String str, byte[] bArr, int i) {
if (i == 0) {
if (this.aBA == null && this.filePath == null) {
this.filePath = com.tencent.mm.pluginsdk.h.a.a.Ts(str);
if (this.filePath == null) {
x.e("MicroMsg.NetSceneGetPSMImg", "writeFile getPath From url failed:[" + str + "]");
return false;
}
try {
this.aBA = new RandomAccessFile(this.filePath, "rw");
} catch (Exception e) {
x.e("MicroMsg.NetSceneGetPSMImg", "writeFile open file error [" + this.filePath + "] e:" + e.getMessage());
return false;
}
}
x.e("MicroMsg.NetSceneGetPSMImg", "writeFile param error");
return false;
}
try {
this.aBA.seek((long) i);
this.aBA.write(bArr, 0, bArr.length);
return true;
} catch (IOException e2) {
x.e("MicroMsg.NetSceneGetPSMImg", "writeFile write file error [" + this.filePath + "] e:" + e2.getMessage());
return false;
}
}
public final int getType() {
return 141;
}
}
|
//package Genericity;
//
//import java.util.Collection;
//
///**
// * @ClassName FruitTray
// * @Description TODO
// * @Author WDH
// * @Date 2019/8/15 19:04
// * @Version 1.0
// **/
//public class FruitTray<T> {
//
// private T t;
//
// public T function(T t){
// return t;
// }
//
// public <T extends Fruits> void printTArray(Collection<? extends Fruits> inputArray ) {
// for ( element : inputArray ){
// System.out.println(element);
// }
// }
//
//
//}
|
/*
* Davis Odom
* 8/26/15
* Removes the junk from a string, parses it into two ints and an operator,
* does the math and then spits out the result
*/
public class Calculator {
public static void main(String[] args) {
//The String
String string = "";
int num1=0,num2=0;
char operator = '+';
for(String s : args){
string = string.concat(s);
}
//Remove the junk
string.replaceAll("\\s","");
// The result of the operation
int result = 0;
// Determine the operator and do the math
if(string.contains("+")){
operator = '+';
num1 = Integer.parseInt(string.substring(0, string.indexOf('+')));
num2 = Integer.parseInt(string.substring(string.indexOf('+')+1));
result = num1 + num2;
}
if(string.contains("-")){
operator = '-';
num1 = Integer.parseInt(string.substring(0, string.indexOf('-')));
num2 = Integer.parseInt(string.substring(string.indexOf('-')+1));
result = num1 - num2;
}
if(string.contains("*")){
operator = '*';
num1 = Integer.parseInt(string.substring(0, string.indexOf('*')));
num2 = Integer.parseInt(string.substring(string.indexOf('*')+1));
result = num1 * num2;
}
if(string.contains("/")){
operator = '/';
num1 = Integer.parseInt(string.substring(0, string.indexOf('/')));
num2 = Integer.parseInt(string.substring(string.indexOf('/')+1));
result = num1 / num2;
}
// Display result
System.out.println(num1 + " " + operator + " " + num2
+ " = " + result);
}
}
|
package br.ita.sem4dia2.ModfAcessoCadeiaContrutores;
public abstract class TesteAbstrato {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.