blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
9c5441f6c2dc2b501c7c36f02f6abf658c90cfcb
3579c367451e47c99530e83cc80e8e773cb7c300
/gzxant-shop/src/main/java/com/gzxant/service/shop/order/pay/ShopOrderPayService.java
31c4a8f4741ec985444530ac25f9541b157ed607
[ "Apache-2.0" ]
permissive
Parmet/gzxant
d3b5db257cc7b3dafb919836a7d9ad27ae467952
09e3e34407cde898284875217ca42adcc0504e64
refs/heads/master
2020-03-09T10:15:19.537897
2018-05-09T03:25:48
2018-05-09T03:25:48
128,732,887
0
2
Apache-2.0
2018-05-11T05:34:50
2018-04-09T07:36:22
JavaScript
UTF-8
Java
false
false
812
java
package com.gzxant.service.shop.order.pay; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gzxant.entity.shop.order.pay.ShopOrderPay; import com.gzxant.dao.shop.order.pay.ShopOrderPayDao; import com.gzxant.service.shop.order.pay.IShopOrderPayService; import com.gzxant.vo.shop.order.ShopOrderVo; import com.gzxant.base.service.impl.BaseService; /** * <p> * 商城-订单支付表 服务实现类 * </p> * * @author xiaoyc * @since 2018-04-21 */ @Service @Transactional(readOnly = true, rollbackFor = Exception.class) public class ShopOrderPayService extends BaseService<ShopOrderPayDao, ShopOrderPay> implements IShopOrderPayService { @Override public void insert(ShopOrderVo param) { } }
[ "158215350@qq.com" ]
158215350@qq.com
b116e0859779bf83c8ed3d754c86454902d33ac8
ce96a870a394c0ab47ca5464ebcbcc406d057f3c
/src/modelo/Equipo.java
227b9bcea9607a7405948dd1330175bf1de2e495
[]
no_license
geopelia/fundalara
454d8675afa0d71703cd549e0d11f205dab5f16b
ea03993f29dce55af96bca31d267fe211a82b4be
refs/heads/master
2021-01-15T18:50:12.653493
2012-01-16T13:04:11
2012-01-16T13:04:11
2,925,084
0
0
null
null
null
null
UTF-8
Java
false
false
5,585
java
package modelo; // Generated 09/01/2012 10:28:45 AM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Equipo generated by hbm2java */ @Entity @Table(name = "equipo", schema = "public") public class Equipo implements java.io.Serializable { private int codigoEquipo; private Categoria categoria; private Divisa divisa; private DatoBasico datoBasico; private String nombre; private char estatus; private Set<PersonalEquipo> personalEquipos = new HashSet<PersonalEquipo>(0); private Set<Roster> rosters = new HashSet<Roster>(0); private Set<EquipoCompetencia> equipoCompetencias = new HashSet<EquipoCompetencia>( 0); private Set<TestEvaluativo> testEvaluativos = new HashSet<TestEvaluativo>(0); private Set<SesionEjecutada> sesionEjecutadas = new HashSet<SesionEjecutada>( 0); private Set<Sesion> sesions = new HashSet<Sesion>(0); private Set<ComisionEquipo> comisionEquipos = new HashSet<ComisionEquipo>(0); public Equipo() { } public Equipo(int codigoEquipo, Categoria categoria, Divisa divisa, DatoBasico datoBasico, String nombre, char estatus) { this.codigoEquipo = codigoEquipo; this.categoria = categoria; this.divisa = divisa; this.datoBasico = datoBasico; this.nombre = nombre; this.estatus = estatus; } public Equipo(int codigoEquipo, Categoria categoria, Divisa divisa, DatoBasico datoBasico, String nombre, char estatus, Set<PersonalEquipo> personalEquipos, Set<Roster> rosters, Set<EquipoCompetencia> equipoCompetencias, Set<TestEvaluativo> testEvaluativos, Set<SesionEjecutada> sesionEjecutadas, Set<Sesion> sesions, Set<ComisionEquipo> comisionEquipos) { this.codigoEquipo = codigoEquipo; this.categoria = categoria; this.divisa = divisa; this.datoBasico = datoBasico; this.nombre = nombre; this.estatus = estatus; this.personalEquipos = personalEquipos; this.rosters = rosters; this.equipoCompetencias = equipoCompetencias; this.testEvaluativos = testEvaluativos; this.sesionEjecutadas = sesionEjecutadas; this.sesions = sesions; this.comisionEquipos = comisionEquipos; } @Id @Column(name = "codigo_equipo", unique = true, nullable = false) public int getCodigoEquipo() { return this.codigoEquipo; } public void setCodigoEquipo(int codigoEquipo) { this.codigoEquipo = codigoEquipo; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "codigo_categoria", nullable = false) public Categoria getCategoria() { return this.categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "codigo_divisa", nullable = false) public Divisa getDivisa() { return this.divisa; } public void setDivisa(Divisa divisa) { this.divisa = divisa; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "codigo_clasificacion", nullable = false) public DatoBasico getDatoBasico() { return this.datoBasico; } public void setDatoBasico(DatoBasico datoBasico) { this.datoBasico = datoBasico; } @Column(name = "nombre", nullable = false) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "estatus", nullable = false, length = 1) public char getEstatus() { return this.estatus; } public void setEstatus(char estatus) { this.estatus = estatus; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<PersonalEquipo> getPersonalEquipos() { return this.personalEquipos; } public void setPersonalEquipos(Set<PersonalEquipo> personalEquipos) { this.personalEquipos = personalEquipos; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<Roster> getRosters() { return this.rosters; } public void setRosters(Set<Roster> rosters) { this.rosters = rosters; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<EquipoCompetencia> getEquipoCompetencias() { return this.equipoCompetencias; } public void setEquipoCompetencias(Set<EquipoCompetencia> equipoCompetencias) { this.equipoCompetencias = equipoCompetencias; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<TestEvaluativo> getTestEvaluativos() { return this.testEvaluativos; } public void setTestEvaluativos(Set<TestEvaluativo> testEvaluativos) { this.testEvaluativos = testEvaluativos; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<SesionEjecutada> getSesionEjecutadas() { return this.sesionEjecutadas; } public void setSesionEjecutadas(Set<SesionEjecutada> sesionEjecutadas) { this.sesionEjecutadas = sesionEjecutadas; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<Sesion> getSesions() { return this.sesions; } public void setSesions(Set<Sesion> sesions) { this.sesions = sesions; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "equipo") public Set<ComisionEquipo> getComisionEquipos() { return this.comisionEquipos; } public void setComisionEquipos(Set<ComisionEquipo> comisionEquipos) { this.comisionEquipos = comisionEquipos; } }
[ "atilioquintero@gmail.com" ]
atilioquintero@gmail.com
decdf9c837393f8f190eb9cf5fb1adc65c482934
9956c8e5f32c18274ea884ed4a26f102f8615919
/chetaglio/src/main/java/com/chetaglio/service/service/ServizioService.java
d3b431b1084ed0e466e4248b9fb34c6e98720a8c
[]
no_license
frankid87/chetaglio
9475bddc8d35fbb4276e4ebf79b38965b208e158
efe8d2c08710cc1c4c4770ce1eadc3d1f72228eb
refs/heads/master
2020-12-24T20:51:51.349648
2016-04-18T14:20:27
2016-04-18T14:20:27
56,509,296
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.chetaglio.service.service; import java.util.List; import com.chetaglio.model.entity.Servizio; public interface ServizioService { public void create(Servizio servizio); public void update(Servizio servizio); public void delete(Servizio servizio); public Servizio findById(Long id); public List<Servizio> findAll(); }
[ "francesco.cinquepalmi@openstyle.it" ]
francesco.cinquepalmi@openstyle.it
b1d12bc3d427cf50445887d5ff72e2e41eb8df09
7b163a9bcef83e90ac9efaa88e3d5845e585a78f
/src/com/test/db/dao/impl/MenuDaoImpl.java
b32e232c9e8b355f8a9e2be47e555fd655302079
[]
no_license
wuwind/Springmvc_03
8f6c11f904c8a570c5a502b22f582825d5627758
39c0acc76a74ee4d14f3a18d55239c114a098a15
refs/heads/master
2020-09-01T11:49:21.108156
2019-11-11T08:06:18
2019-11-11T08:06:18
218,952,599
0
0
null
null
null
null
UTF-8
Java
false
false
335
java
package com.test.db.dao.impl; import com.test.db.dao.MenuDao; import com.test.model.Menu; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class MenuDaoImpl extends BaseDaoImpl<Menu> implements MenuDao { @Override public List<Menu> getAllMenu() { return getAll(); } }
[ "wuhf.com" ]
wuhf.com
f3a6f23e45d2c56d74c6d465c3a4ba0748f5eefc
320aad07ee712ac0162ebf4f17fb3f122129e827
/app/src/main/java/com/rawrstudio/lfa/model/Better_Featured_Image.java
ac092b19c58ea83efdacc2e3f76b11429d571d03
[]
no_license
nedfoor3/LFA_Android_V2.0
934ef982fd442b9cf7a892c49e52e6f6f88bc131
d32a7ea2c9cd11a00983ab7a0238d3c8cfb3932b
refs/heads/master
2021-01-21T06:38:29.127536
2017-03-06T17:02:25
2017-03-06T17:02:25
83,261,036
0
0
null
null
null
null
UTF-8
Java
false
false
1,974
java
package com.rawrstudio.lfa.model; /** * Created by Ricardo Rodriguez on 3/3/2017. */ public class Better_Featured_Image { private String description; private String media_type; private Media_Details media_details; private String source_url; /** * Gets description. * * @return the description */ public String getDescription() { return description; } /** * Sets description. * * @param description the description */ public void setDescription(String description) { this.description = description; } /** * Gets media type. * * @return the media type */ public String getMedia_type() { return media_type; } /** * Sets media type. * * @param media_type the media type */ public void setMedia_type(String media_type) { this.media_type = media_type; } /** * Gets media details. * * @return the media details */ public Media_Details getMedia_details() { return media_details; } /** * Sets media details. * * @param media_details the media details */ public void setMedia_details(Media_Details media_details) { this.media_details = media_details; } /** * Gets source url. * * @return the source url */ public String getSource_url() { return source_url; } /** * Sets source url. * * @param source_url the source url */ public void setSource_url(String source_url) { this.source_url = source_url; } @Override public String toString() { return "Better_Featured_Image{" + "description='" + description + '\'' + ", media_type='" + media_type + '\'' + ", media_details=" + media_details + ", source_url='" + source_url + '\'' + '}'; } }
[ "nedfoor@gmail.com" ]
nedfoor@gmail.com
4469fb16e443e7f22a88a39e8babe05bb3126613
ddc9502a239e6fb8f4b3e6b730e6c539c98031a4
/Employees/09-LambdaBuiltIns/practice2/EmployeeSearch09-02Prac/src/com/example/lambda/NoBonus.java
fae7c7bba00d101b4acf5772988bfcf3af639728
[]
no_license
NeilOberholzer/JavaAdv
67b0d93e039abd2c04560ac629a80e5d267055d7
d66b917e1d079b8adcb60fb1fcbb648596df32d8
refs/heads/master
2020-07-08T22:42:53.899167
2019-09-23T05:38:40
2019-09-23T05:38:40
203,799,588
0
0
null
null
null
null
UTF-8
Java
false
false
689
java
package com.example.lambda; /** * * @author oracle */ public enum NoBonus { STAFF(0.02), MANAGER(0.04), EXECUTIVE(0.06); private final double percent; NoBonus(double percent){ this.percent = percent; } public double percent(){ return percent; } public static double byRole(NoRole r){ double bonusPercent = 0.0d; switch(r){ case EXECUTIVE: bonusPercent = EXECUTIVE.percent; break; case MANAGER: bonusPercent = MANAGER.percent; break; case STAFF: bonusPercent = STAFF.percent; break; } return bonusPercent; } }
[ "neiloberholzer2016@gmail.com" ]
neiloberholzer2016@gmail.com
9e27c9a10414cbe23424fa33535704ec4509916e
3c5cfde83cc46a6a2de82ba321c381818a659ce8
/src/main/java/com/intuit/traveldiary/dao/TravelDAO.java
a6bb1ce544ece54890d720c13387b94614b0c2c5
[]
no_license
audupa/TravelDiary
f9791cb6c7b5b0fec7248efec166164ceab31aec
e66415378c1272cd2773927a90104de92842d39a
refs/heads/master
2016-09-05T11:48:39.421681
2015-04-21T17:14:12
2015-04-21T17:14:12
34,340,874
0
0
null
null
null
null
UTF-8
Java
false
false
408
java
package com.intuit.traveldiary.dao; import com.intuit.traveldiary.dao.GenericDAOImpl; import com.intuit.traveldiary.dto.TravelDO; import org.springframework.stereotype.Repository; /** * Created with IntelliJ IDEA. * User: AUDUPA * Date: 4/21/15 * Time: 3:16 PM * To change this template use File | Settings | File Templates. */ @Repository public class TravelDAO extends GenericDAOImpl<TravelDO> { }
[ "akshatha.udupa1@gmail.com" ]
akshatha.udupa1@gmail.com
b1f4ab64252b7e10ab3f9b3172cead9cfe973563
214838dc887c044c7b10f26a6fd85ee231ad8107
/vendor/github.com/google/protobuf/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
ec4879616479715704b006afe22a816c85ab970e
[ "LicenseRef-scancode-protobuf", "Apache-2.0" ]
permissive
coolbreeze000/ovs-gnxi
5c486e192bad4880bff6ea38f6969417986fd262
ad9c0bf3565a3cf8dfe5ca9929c2632a57fd279b
refs/heads/master
2021-04-18T21:31:53.828567
2019-04-22T21:01:02
2019-04-22T21:01:02
126,850,919
2
1
Apache-2.0
2019-04-22T21:01:03
2018-03-26T15:36:47
Go
UTF-8
Java
false
false
128,380
java
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.protobuf; import static com.google.protobuf.Internal.EMPTY_BYTE_ARRAY; import static com.google.protobuf.Internal.EMPTY_BYTE_BUFFER; import static com.google.protobuf.Internal.UTF_8; import static com.google.protobuf.Internal.checkNotNull; import static com.google.protobuf.WireFormat.FIXED32_SIZE; import static com.google.protobuf.WireFormat.FIXED64_SIZE; import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Reads and decodes protocol message fields. * * <p>This class contains two kinds of methods: methods that read specific protocol message * constructs and field types (e.g. {@link #readTag()} and {@link #readInt32()}) and methods that * read low-level values (e.g. {@link #readRawVarint32()} and {@link #readRawBytes}). If you are * reading encoded protocol messages, you should use the former methods, but if you are reading some * other format of your own design, use the latter. * * @author kenton@google.com Kenton Varda */ public abstract class CodedInputStream { private static final int DEFAULT_BUFFER_SIZE = 4096; private static final int DEFAULT_RECURSION_LIMIT = 100; // Integer.MAX_VALUE == 0x7FFFFFF == INT_MAX from limits.h private static final int DEFAULT_SIZE_LIMIT = Integer.MAX_VALUE; /** Visible for subclasses. See setRecursionLimit() */ int recursionDepth; int recursionLimit = DEFAULT_RECURSION_LIMIT; /** Visible for subclasses. See setSizeLimit() */ int sizeLimit = DEFAULT_SIZE_LIMIT; /** Create a new CodedInputStream wrapping the given InputStream. */ public static CodedInputStream newInstance(final InputStream input) { return newInstance(input, DEFAULT_BUFFER_SIZE); } /** Create a new CodedInputStream wrapping the given InputStream, with a specified buffer size. */ public static CodedInputStream newInstance(final InputStream input, int bufferSize) { if (bufferSize <= 0) { throw new IllegalArgumentException("bufferSize must be > 0"); } if (input == null) { // TODO(nathanmittler): Ideally we should throw here. This is done for backward compatibility. return newInstance(EMPTY_BYTE_ARRAY); } return new StreamDecoder(input, bufferSize); } /** Create a new CodedInputStream wrapping the given {@code Iterable <ByteBuffer>}. */ public static CodedInputStream newInstance(final Iterable<ByteBuffer> input) { if (!UnsafeDirectNioDecoder.isSupported()) { return newInstance(new IterableByteBufferInputStream(input)); } return newInstance(input, false); } /** Create a new CodedInputStream wrapping the given {@code Iterable <ByteBuffer>}. */ static CodedInputStream newInstance( final Iterable<ByteBuffer> bufs, final boolean bufferIsImmutable) { // flag is to check the type of input's ByteBuffers. // flag equals 1: all ByteBuffers have array. // flag equals 2: all ByteBuffers are direct ByteBuffers. // flag equals 3: some ByteBuffers are direct and some have array. // flag greater than 3: other cases. int flag = 0; // Total size of the input int totalSize = 0; for (ByteBuffer buf : bufs) { totalSize += buf.remaining(); if (buf.hasArray()) { flag |= 1; } else if (buf.isDirect()) { flag |= 2; } else { flag |= 4; } } if (flag == 2) { return new IterableDirectByteBufferDecoder(bufs, totalSize, bufferIsImmutable); } else { // TODO(yilunchong): add another decoders to deal case 1 and 3. return newInstance(new IterableByteBufferInputStream(bufs)); } } /** Create a new CodedInputStream wrapping the given byte array. */ public static CodedInputStream newInstance(final byte[] buf) { return newInstance(buf, 0, buf.length); } /** Create a new CodedInputStream wrapping the given byte array slice. */ public static CodedInputStream newInstance(final byte[] buf, final int off, final int len) { return newInstance(buf, off, len, /* bufferIsImmutable= */ false); } /** Create a new CodedInputStream wrapping the given byte array slice. */ static CodedInputStream newInstance( final byte[] buf, final int off, final int len, final boolean bufferIsImmutable) { ArrayDecoder result = new ArrayDecoder(buf, off, len, bufferIsImmutable); try { // Some uses of CodedInputStream can be more efficient if they know // exactly how many bytes are available. By pushing the end point of the // buffer as a limit, we allow them to get this information via // getBytesUntilLimit(). Pushing a limit that we know is at the end of // the stream can never hurt, since we can never past that point anyway. result.pushLimit(len); } catch (InvalidProtocolBufferException ex) { // The only reason pushLimit() might throw an exception here is if len // is negative. Normally pushLimit()'s parameter comes directly off the // wire, so it's important to catch exceptions in case of corrupt or // malicious data. However, in this case, we expect that len is not a // user-supplied value, so we can assume that it being negative indicates // a programming error. Therefore, throwing an unchecked exception is // appropriate. throw new IllegalArgumentException(ex); } return result; } /** * Create a new CodedInputStream wrapping the given ByteBuffer. The data starting from the * ByteBuffer's current position to its limit will be read. The returned CodedInputStream may or * may not share the underlying data in the ByteBuffer, therefore the ByteBuffer cannot be changed * while the CodedInputStream is in use. Note that the ByteBuffer's position won't be changed by * this function. Concurrent calls with the same ByteBuffer object are safe if no other thread is * trying to alter the ByteBuffer's status. */ public static CodedInputStream newInstance(ByteBuffer buf) { return newInstance(buf, /* bufferIsImmutable= */ false); } /** Create a new CodedInputStream wrapping the given buffer. */ static CodedInputStream newInstance(ByteBuffer buf, boolean bufferIsImmutable) { if (buf.hasArray()) { return newInstance( buf.array(), buf.arrayOffset() + buf.position(), buf.remaining(), bufferIsImmutable); } if (buf.isDirect() && UnsafeDirectNioDecoder.isSupported()) { return new UnsafeDirectNioDecoder(buf, bufferIsImmutable); } // The buffer is non-direct and does not expose the underlying array. Using the ByteBuffer API // to access individual bytes is very slow, so just copy the buffer to an array. // TODO(nathanmittler): Re-evaluate with Java 9 byte[] buffer = new byte[buf.remaining()]; buf.duplicate().get(buffer); return newInstance(buffer, 0, buffer.length, true); } /** Disable construction/inheritance outside of this class. */ private CodedInputStream() {} // ----------------------------------------------------------------- /** * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers * use this to read tags, since a protocol message may legally end wherever a tag occurs, and zero * is not a valid tag number. */ public abstract int readTag() throws IOException; /** * Verifies that the last call to readTag() returned the given tag value. This is used to verify * that a nested group ended with the correct end tag. * * @throws InvalidProtocolBufferException {@code value} does not match the last tag. */ public abstract void checkLastTagWas(final int value) throws InvalidProtocolBufferException; public abstract int getLastTag(); /** * Reads and discards a single field, given its tag value. * * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. * Otherwise, returns {@code true}. */ public abstract boolean skipField(final int tag) throws IOException; /** * Reads a single field and writes it to output in wire format, given its tag value. * * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. * Otherwise, returns {@code true}. * @deprecated use {@code UnknownFieldSet} or {@code UnknownFieldSetLite} to skip to an output * stream. */ @Deprecated public abstract boolean skipField(final int tag, final CodedOutputStream output) throws IOException; /** * Reads and discards an entire message. This will read either until EOF or until an endgroup tag, * whichever comes first. */ public abstract void skipMessage() throws IOException; /** * Reads an entire message and writes it to output in wire format. This will read either until EOF * or until an endgroup tag, whichever comes first. */ public abstract void skipMessage(CodedOutputStream output) throws IOException; // ----------------------------------------------------------------- /** Read a {@code double} field value from the stream. */ public abstract double readDouble() throws IOException; /** Read a {@code float} field value from the stream. */ public abstract float readFloat() throws IOException; /** Read a {@code uint64} field value from the stream. */ public abstract long readUInt64() throws IOException; /** Read an {@code int64} field value from the stream. */ public abstract long readInt64() throws IOException; /** Read an {@code int32} field value from the stream. */ public abstract int readInt32() throws IOException; /** Read a {@code fixed64} field value from the stream. */ public abstract long readFixed64() throws IOException; /** Read a {@code fixed32} field value from the stream. */ public abstract int readFixed32() throws IOException; /** Read a {@code bool} field value from the stream. */ public abstract boolean readBool() throws IOException; /** * Read a {@code string} field value from the stream. If the stream contains malformed UTF-8, * replace the offending bytes with the standard UTF-8 replacement character. */ public abstract String readString() throws IOException; /** * Read a {@code string} field value from the stream. If the stream contains malformed UTF-8, * throw exception {@link InvalidProtocolBufferException}. */ public abstract String readStringRequireUtf8() throws IOException; /** Read a {@code group} field value from the stream. */ public abstract void readGroup( final int fieldNumber, final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException; /** Read a {@code group} field value from the stream. */ public abstract <T extends MessageLite> T readGroup( final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException; /** * Reads a {@code group} field value from the stream and merges it into the given {@link * UnknownFieldSet}. * * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just call * {@link #readGroup}. */ @Deprecated public abstract void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws IOException; /** Read an embedded message field value from the stream. */ public abstract void readMessage( final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException; /** Read an embedded message field value from the stream. */ public abstract <T extends MessageLite> T readMessage( final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException; /** Read a {@code bytes} field value from the stream. */ public abstract ByteString readBytes() throws IOException; /** Read a {@code bytes} field value from the stream. */ public abstract byte[] readByteArray() throws IOException; /** Read a {@code bytes} field value from the stream. */ public abstract ByteBuffer readByteBuffer() throws IOException; /** Read a {@code uint32} field value from the stream. */ public abstract int readUInt32() throws IOException; /** * Read an enum field value from the stream. Caller is responsible for converting the numeric * value to an actual enum. */ public abstract int readEnum() throws IOException; /** Read an {@code sfixed32} field value from the stream. */ public abstract int readSFixed32() throws IOException; /** Read an {@code sfixed64} field value from the stream. */ public abstract long readSFixed64() throws IOException; /** Read an {@code sint32} field value from the stream. */ public abstract int readSInt32() throws IOException; /** Read an {@code sint64} field value from the stream. */ public abstract long readSInt64() throws IOException; // ================================================================= /** Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits. */ public abstract int readRawVarint32() throws IOException; /** Read a raw Varint from the stream. */ public abstract long readRawVarint64() throws IOException; /** Variant of readRawVarint64 for when uncomfortably close to the limit. */ /* Visible for testing */ abstract long readRawVarint64SlowPath() throws IOException; /** Read a 32-bit little-endian integer from the stream. */ public abstract int readRawLittleEndian32() throws IOException; /** Read a 64-bit little-endian integer from the stream. */ public abstract long readRawLittleEndian64() throws IOException; // ----------------------------------------------------------------- /** * Enables {@link ByteString} aliasing of the underlying buffer, trading off on buffer pinning for * data copies. Only valid for buffer-backed streams. */ public abstract void enableAliasing(boolean enabled); /** * Set the maximum message recursion depth. In order to prevent malicious messages from causing * stack overflows, {@code CodedInputStream} limits how deeply messages may be nested. The default * limit is 100. * * @return the old limit. */ public final int setRecursionLimit(final int limit) { if (limit < 0) { throw new IllegalArgumentException("Recursion limit cannot be negative: " + limit); } final int oldLimit = recursionLimit; recursionLimit = limit; return oldLimit; } /** * Only valid for {@link InputStream}-backed streams. * * <p>Set the maximum message size. In order to prevent malicious messages from exhausting memory * or causing integer overflows, {@code CodedInputStream} limits how large a message may be. The * default limit is {@code Integer.MAX_INT}. You should set this limit as small as you can without * harming your app's functionality. Note that size limits only apply when reading from an {@code * InputStream}, not when constructed around a raw byte array. * * <p>If you want to read several messages from a single CodedInputStream, you could call {@link * #resetSizeCounter()} after each one to avoid hitting the size limit. * * @return the old limit. */ public final int setSizeLimit(final int limit) { if (limit < 0) { throw new IllegalArgumentException("Size limit cannot be negative: " + limit); } final int oldLimit = sizeLimit; sizeLimit = limit; return oldLimit; } private boolean shouldDiscardUnknownFields = false; /** * Sets this {@code CodedInputStream} to discard unknown fields. Only applies to full runtime * messages; lite messages will always preserve unknowns. * * <p>Note calling this function alone will have NO immediate effect on the underlying input data. * The unknown fields will be discarded during parsing. This affects both Proto2 and Proto3 full * runtime. */ final void discardUnknownFields() { shouldDiscardUnknownFields = true; } /** * Reverts the unknown fields preservation behavior for Proto2 and Proto3 full runtime to their * default. */ final void unsetDiscardUnknownFields() { shouldDiscardUnknownFields = false; } /** * Whether unknown fields in this input stream should be discarded during parsing into full * runtime messages. */ final boolean shouldDiscardUnknownFields() { return shouldDiscardUnknownFields; } /** * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). Only valid for {@link * InputStream}-backed streams. */ public abstract void resetSizeCounter(); /** * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This is called when * descending into a length-delimited embedded message. * * <p>Note that {@code pushLimit()} does NOT affect how many bytes the {@code CodedInputStream} * reads from an underlying {@code InputStream} when refreshing its buffer. If you need to prevent * reading past a certain point in the underlying {@code InputStream} (e.g. because you expect it * to contain more data after the end of the message which you need to handle differently) then * you must place a wrapper around your {@code InputStream} which limits the amount of data that * can be read from it. * * @return the old limit. */ public abstract int pushLimit(int byteLimit) throws InvalidProtocolBufferException; /** * Discards the current limit, returning to the previous limit. * * @param oldLimit The old limit, as returned by {@code pushLimit}. */ public abstract void popLimit(final int oldLimit); /** * Returns the number of bytes to be read before the current limit. If no limit is set, returns * -1. */ public abstract int getBytesUntilLimit(); /** * Returns true if the stream has reached the end of the input. This is the case if either the end * of the underlying input source has been reached or if the stream has reached a limit created * using {@link #pushLimit(int)}. */ public abstract boolean isAtEnd() throws IOException; /** * The total bytes read up to the current position. Calling {@link #resetSizeCounter()} resets * this value to zero. */ public abstract int getTotalBytesRead(); /** * Read one byte from the input. * * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached. */ public abstract byte readRawByte() throws IOException; /** * Read a fixed size of bytes from the input. * * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached. */ public abstract byte[] readRawBytes(final int size) throws IOException; /** * Reads and discards {@code size} bytes. * * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached. */ public abstract void skipRawBytes(final int size) throws IOException; /** * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits * to be varint encoded, thus always taking 10 bytes on the wire.) * * @param n An unsigned 32-bit integer, stored in a signed int because Java has no explicit * unsigned support. * @return A signed 32-bit integer. */ public static int decodeZigZag32(final int n) { return (n >>> 1) ^ -(n & 1); } /** * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits * to be varint encoded, thus always taking 10 bytes on the wire.) * * @param n An unsigned 64-bit integer, stored in a signed int because Java has no explicit * unsigned support. * @return A signed 64-bit integer. */ public static long decodeZigZag64(final long n) { return (n >>> 1) ^ -(n & 1); } /** * Like {@link #readRawVarint32(InputStream)}, but expects that the caller has already read one * byte. This allows the caller to determine if EOF has been reached before attempting to read. */ public static int readRawVarint32(final int firstByte, final InputStream input) throws IOException { if ((firstByte & 0x80) == 0) { return firstByte; } int result = firstByte & 0x7f; int offset = 7; for (; offset < 32; offset += 7) { final int b = input.read(); if (b == -1) { throw InvalidProtocolBufferException.truncatedMessage(); } result |= (b & 0x7f) << offset; if ((b & 0x80) == 0) { return result; } } // Keep reading up to 64 bits. for (; offset < 64; offset += 7) { final int b = input.read(); if (b == -1) { throw InvalidProtocolBufferException.truncatedMessage(); } if ((b & 0x80) == 0) { return result; } } throw InvalidProtocolBufferException.malformedVarint(); } /** * Reads a varint from the input one byte at a time, so that it does not read any bytes after the * end of the varint. If you simply wrapped the stream in a CodedInputStream and used {@link * #readRawVarint32(InputStream)} then you would probably end up reading past the end of the * varint since CodedInputStream buffers its input. */ static int readRawVarint32(final InputStream input) throws IOException { final int firstByte = input.read(); if (firstByte == -1) { throw InvalidProtocolBufferException.truncatedMessage(); } return readRawVarint32(firstByte, input); } /** A {@link CodedInputStream} implementation that uses a backing array as the input. */ private static final class ArrayDecoder extends CodedInputStream { private final byte[] buffer; private final boolean immutable; private int limit; private int bufferSizeAfterLimit; private int pos; private int startPos; private int lastTag; private boolean enableAliasing; /** The absolute position of the end of the current message. */ private int currentLimit = Integer.MAX_VALUE; private ArrayDecoder(final byte[] buffer, final int offset, final int len, boolean immutable) { this.buffer = buffer; limit = offset + len; pos = offset; startPos = pos; this.immutable = immutable; } @Override public int readTag() throws IOException { if (isAtEnd()) { lastTag = 0; return 0; } lastTag = readRawVarint32(); if (WireFormat.getTagFieldNumber(lastTag) == 0) { // If we actually read zero (or any tag number corresponding to field // number zero), that's not a valid tag. throw InvalidProtocolBufferException.invalidTag(); } return lastTag; } @Override public void checkLastTagWas(final int value) throws InvalidProtocolBufferException { if (lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } @Override public int getLastTag() { return lastTag; } @Override public boolean skipField(final int tag) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: skipRawVarint(); return true; case WireFormat.WIRETYPE_FIXED64: skipRawBytes(FIXED64_SIZE); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: skipRawBytes(readRawVarint32()); return true; case WireFormat.WIRETYPE_START_GROUP: skipMessage(); checkLastTagWas( WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP)); return true; case WireFormat.WIRETYPE_END_GROUP: return false; case WireFormat.WIRETYPE_FIXED32: skipRawBytes(FIXED32_SIZE); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public boolean skipField(final int tag, final CodedOutputStream output) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: { long value = readInt64(); output.writeRawVarint32(tag); output.writeUInt64NoTag(value); return true; } case WireFormat.WIRETYPE_FIXED64: { long value = readRawLittleEndian64(); output.writeRawVarint32(tag); output.writeFixed64NoTag(value); return true; } case WireFormat.WIRETYPE_LENGTH_DELIMITED: { ByteString value = readBytes(); output.writeRawVarint32(tag); output.writeBytesNoTag(value); return true; } case WireFormat.WIRETYPE_START_GROUP: { output.writeRawVarint32(tag); skipMessage(output); int endtag = WireFormat.makeTag( WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP); checkLastTagWas(endtag); output.writeRawVarint32(endtag); return true; } case WireFormat.WIRETYPE_END_GROUP: { return false; } case WireFormat.WIRETYPE_FIXED32: { int value = readRawLittleEndian32(); output.writeRawVarint32(tag); output.writeFixed32NoTag(value); return true; } default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public void skipMessage() throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag)) { return; } } } @Override public void skipMessage(CodedOutputStream output) throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag, output)) { return; } } } // ----------------------------------------------------------------- @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readRawLittleEndian64()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readRawLittleEndian32()); } @Override public long readUInt64() throws IOException { return readRawVarint64(); } @Override public long readInt64() throws IOException { return readRawVarint64(); } @Override public int readInt32() throws IOException { return readRawVarint32(); } @Override public long readFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readFixed32() throws IOException { return readRawLittleEndian32(); } @Override public boolean readBool() throws IOException { return readRawVarint64() != 0; } @Override public String readString() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= (limit - pos)) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. final String result = new String(buffer, pos, size, UTF_8); pos += size; return result; } if (size == 0) { return ""; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public String readStringRequireUtf8() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= (limit - pos)) { String result = Utf8.decodeUtf8(buffer, pos, size); pos += size; return result; } if (size == 0) { return ""; } if (size <= 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void readGroup( final int fieldNumber, final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; } @Override public <T extends MessageLite> T readGroup( final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; return result; } @Deprecated @Override public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws IOException { readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry()); } @Override public void readMessage( final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { final int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); } @Override public <T extends MessageLite> T readMessage( final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); return result; } @Override public ByteString readBytes() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= (limit - pos)) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. final ByteString result = immutable && enableAliasing ? ByteString.wrap(buffer, pos, size) : ByteString.copyFrom(buffer, pos, size); pos += size; return result; } if (size == 0) { return ByteString.EMPTY; } // Slow path: Build a byte array first then copy it. return ByteString.wrap(readRawBytes(size)); } @Override public byte[] readByteArray() throws IOException { final int size = readRawVarint32(); return readRawBytes(size); } @Override public ByteBuffer readByteBuffer() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= (limit - pos)) { // Fast path: We already have the bytes in a contiguous buffer. // When aliasing is enabled, we can return a ByteBuffer pointing directly // into the underlying byte array without copy if the CodedInputStream is // constructed from a byte array. If aliasing is disabled or the input is // from an InputStream or ByteString, we have to make a copy of the bytes. ByteBuffer result = !immutable && enableAliasing ? ByteBuffer.wrap(buffer, pos, size).slice() : ByteBuffer.wrap(Arrays.copyOfRange(buffer, pos, pos + size)); pos += size; // TODO(nathanmittler): Investigate making the ByteBuffer be made read-only return result; } if (size == 0) { return EMPTY_BYTE_BUFFER; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public int readUInt32() throws IOException { return readRawVarint32(); } @Override public int readEnum() throws IOException { return readRawVarint32(); } @Override public int readSFixed32() throws IOException { return readRawLittleEndian32(); } @Override public long readSFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readSInt32() throws IOException { return decodeZigZag32(readRawVarint32()); } @Override public long readSInt64() throws IOException { return decodeZigZag64(readRawVarint64()); } // ================================================================= @Override public int readRawVarint32() throws IOException { // See implementation notes for readRawVarint64 fastpath: { int tempPos = pos; if (limit == tempPos) { break fastpath; } final byte[] buffer = this.buffer; int x; if ((x = buffer[tempPos++]) >= 0) { pos = tempPos; return x; } else if (limit - tempPos < 9) { break fastpath; } else if ((x ^= (buffer[tempPos++] << 7)) < 0) { x ^= (~0 << 7); } else if ((x ^= (buffer[tempPos++] << 14)) >= 0) { x ^= (~0 << 7) ^ (~0 << 14); } else if ((x ^= (buffer[tempPos++] << 21)) < 0) { x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); } else { int y = buffer[tempPos++]; x ^= y << 28; x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); if (y < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0) { break fastpath; // Will throw malformedVarint() } } pos = tempPos; return x; } return (int) readRawVarint64SlowPath(); } private void skipRawVarint() throws IOException { if (limit - pos >= MAX_VARINT_SIZE) { skipRawVarintFastPath(); } else { skipRawVarintSlowPath(); } } private void skipRawVarintFastPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (buffer[pos++] >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } private void skipRawVarintSlowPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (readRawByte() >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public long readRawVarint64() throws IOException { // Implementation notes: // // Optimized for one-byte values, expected to be common. // The particular code below was selected from various candidates // empirically, by winning VarintBenchmark. // // Sign extension of (signed) Java bytes is usually a nuisance, but // we exploit it here to more easily obtain the sign of bytes read. // Instead of cleaning up the sign extension bits by masking eagerly, // we delay until we find the final (positive) byte, when we clear all // accumulated bits with one xor. We depend on javac to constant fold. fastpath: { int tempPos = pos; if (limit == tempPos) { break fastpath; } final byte[] buffer = this.buffer; long x; int y; if ((y = buffer[tempPos++]) >= 0) { pos = tempPos; return y; } else if (limit - tempPos < 9) { break fastpath; } else if ((y ^= (buffer[tempPos++] << 7)) < 0) { x = y ^ (~0 << 7); } else if ((y ^= (buffer[tempPos++] << 14)) >= 0) { x = y ^ ((~0 << 7) ^ (~0 << 14)); } else if ((y ^= (buffer[tempPos++] << 21)) < 0) { x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); } else if ((x = y ^ ((long) buffer[tempPos++] << 28)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); } else if ((x ^= ((long) buffer[tempPos++] << 35)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); } else if ((x ^= ((long) buffer[tempPos++] << 42)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); } else if ((x ^= ((long) buffer[tempPos++] << 49)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49); } else { x ^= ((long) buffer[tempPos++] << 56); x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49) ^ (~0L << 56); if (x < 0L) { if (buffer[tempPos++] < 0L) { break fastpath; // Will throw malformedVarint() } } } pos = tempPos; return x; } return readRawVarint64SlowPath(); } @Override long readRawVarint64SlowPath() throws IOException { long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public int readRawLittleEndian32() throws IOException { int tempPos = pos; if (limit - tempPos < FIXED32_SIZE) { throw InvalidProtocolBufferException.truncatedMessage(); } final byte[] buffer = this.buffer; pos = tempPos + FIXED32_SIZE; return (((buffer[tempPos] & 0xff)) | ((buffer[tempPos + 1] & 0xff) << 8) | ((buffer[tempPos + 2] & 0xff) << 16) | ((buffer[tempPos + 3] & 0xff) << 24)); } @Override public long readRawLittleEndian64() throws IOException { int tempPos = pos; if (limit - tempPos < FIXED64_SIZE) { throw InvalidProtocolBufferException.truncatedMessage(); } final byte[] buffer = this.buffer; pos = tempPos + FIXED64_SIZE; return (((buffer[tempPos] & 0xffL)) | ((buffer[tempPos + 1] & 0xffL) << 8) | ((buffer[tempPos + 2] & 0xffL) << 16) | ((buffer[tempPos + 3] & 0xffL) << 24) | ((buffer[tempPos + 4] & 0xffL) << 32) | ((buffer[tempPos + 5] & 0xffL) << 40) | ((buffer[tempPos + 6] & 0xffL) << 48) | ((buffer[tempPos + 7] & 0xffL) << 56)); } @Override public void enableAliasing(boolean enabled) { this.enableAliasing = enabled; } @Override public void resetSizeCounter() { startPos = pos; } @Override public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { if (byteLimit < 0) { throw InvalidProtocolBufferException.negativeSize(); } byteLimit += getTotalBytesRead(); final int oldLimit = currentLimit; if (byteLimit > oldLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } currentLimit = byteLimit; recomputeBufferSizeAfterLimit(); return oldLimit; } private void recomputeBufferSizeAfterLimit() { limit += bufferSizeAfterLimit; final int bufferEnd = limit - startPos; if (bufferEnd > currentLimit) { // Limit is in current buffer. bufferSizeAfterLimit = bufferEnd - currentLimit; limit -= bufferSizeAfterLimit; } else { bufferSizeAfterLimit = 0; } } @Override public void popLimit(final int oldLimit) { currentLimit = oldLimit; recomputeBufferSizeAfterLimit(); } @Override public int getBytesUntilLimit() { if (currentLimit == Integer.MAX_VALUE) { return -1; } return currentLimit - getTotalBytesRead(); } @Override public boolean isAtEnd() throws IOException { return pos == limit; } @Override public int getTotalBytesRead() { return pos - startPos; } @Override public byte readRawByte() throws IOException { if (pos == limit) { throw InvalidProtocolBufferException.truncatedMessage(); } return buffer[pos++]; } @Override public byte[] readRawBytes(final int length) throws IOException { if (length > 0 && length <= (limit - pos)) { final int tempPos = pos; pos += length; return Arrays.copyOfRange(buffer, tempPos, pos); } if (length <= 0) { if (length == 0) { return Internal.EMPTY_BYTE_ARRAY; } else { throw InvalidProtocolBufferException.negativeSize(); } } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void skipRawBytes(final int length) throws IOException { if (length >= 0 && length <= (limit - pos)) { // We have all the bytes we need already. pos += length; return; } if (length < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } } /** * A {@link CodedInputStream} implementation that uses a backing direct ByteBuffer as the input. * Requires the use of {@code sun.misc.Unsafe} to perform fast reads on the buffer. */ private static final class UnsafeDirectNioDecoder extends CodedInputStream { /** The direct buffer that is backing this stream. */ private final ByteBuffer buffer; /** * If {@code true}, indicates that the buffer is backing a {@link ByteString} and is therefore * considered to be an immutable input source. */ private final boolean immutable; /** The unsafe address of the content of {@link #buffer}. */ private final long address; /** The unsafe address of the current read limit of the buffer. */ private long limit; /** The unsafe address of the current read position of the buffer. */ private long pos; /** The unsafe address of the starting read position. */ private long startPos; /** The amount of available data in the buffer beyond {@link #limit}. */ private int bufferSizeAfterLimit; /** The last tag that was read from this stream. */ private int lastTag; /** * If {@code true}, indicates that calls to read {@link ByteString} or {@code byte[]} * <strong>may</strong> return slices of the underlying buffer, rather than copies. */ private boolean enableAliasing; /** The absolute position of the end of the current message. */ private int currentLimit = Integer.MAX_VALUE; static boolean isSupported() { return UnsafeUtil.hasUnsafeByteBufferOperations(); } private UnsafeDirectNioDecoder(ByteBuffer buffer, boolean immutable) { this.buffer = buffer; address = UnsafeUtil.addressOffset(buffer); limit = address + buffer.limit(); pos = address + buffer.position(); startPos = pos; this.immutable = immutable; } @Override public int readTag() throws IOException { if (isAtEnd()) { lastTag = 0; return 0; } lastTag = readRawVarint32(); if (WireFormat.getTagFieldNumber(lastTag) == 0) { // If we actually read zero (or any tag number corresponding to field // number zero), that's not a valid tag. throw InvalidProtocolBufferException.invalidTag(); } return lastTag; } @Override public void checkLastTagWas(final int value) throws InvalidProtocolBufferException { if (lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } @Override public int getLastTag() { return lastTag; } @Override public boolean skipField(final int tag) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: skipRawVarint(); return true; case WireFormat.WIRETYPE_FIXED64: skipRawBytes(FIXED64_SIZE); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: skipRawBytes(readRawVarint32()); return true; case WireFormat.WIRETYPE_START_GROUP: skipMessage(); checkLastTagWas( WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP)); return true; case WireFormat.WIRETYPE_END_GROUP: return false; case WireFormat.WIRETYPE_FIXED32: skipRawBytes(FIXED32_SIZE); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public boolean skipField(final int tag, final CodedOutputStream output) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: { long value = readInt64(); output.writeRawVarint32(tag); output.writeUInt64NoTag(value); return true; } case WireFormat.WIRETYPE_FIXED64: { long value = readRawLittleEndian64(); output.writeRawVarint32(tag); output.writeFixed64NoTag(value); return true; } case WireFormat.WIRETYPE_LENGTH_DELIMITED: { ByteString value = readBytes(); output.writeRawVarint32(tag); output.writeBytesNoTag(value); return true; } case WireFormat.WIRETYPE_START_GROUP: { output.writeRawVarint32(tag); skipMessage(output); int endtag = WireFormat.makeTag( WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP); checkLastTagWas(endtag); output.writeRawVarint32(endtag); return true; } case WireFormat.WIRETYPE_END_GROUP: { return false; } case WireFormat.WIRETYPE_FIXED32: { int value = readRawLittleEndian32(); output.writeRawVarint32(tag); output.writeFixed32NoTag(value); return true; } default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public void skipMessage() throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag)) { return; } } } @Override public void skipMessage(CodedOutputStream output) throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag, output)) { return; } } } // ----------------------------------------------------------------- @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readRawLittleEndian64()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readRawLittleEndian32()); } @Override public long readUInt64() throws IOException { return readRawVarint64(); } @Override public long readInt64() throws IOException { return readRawVarint64(); } @Override public int readInt32() throws IOException { return readRawVarint32(); } @Override public long readFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readFixed32() throws IOException { return readRawLittleEndian32(); } @Override public boolean readBool() throws IOException { return readRawVarint64() != 0; } @Override public String readString() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= remaining()) { // TODO(nathanmittler): Is there a way to avoid this copy? // TODO(anuraaga): It might be possible to share the optimized loop with // readStringRequireUtf8 by implementing Java replacement logic there. // The same as readBytes' logic byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(pos, bytes, 0, size); String result = new String(bytes, UTF_8); pos += size; return result; } if (size == 0) { return ""; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public String readStringRequireUtf8() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= remaining()) { final int bufferPos = bufferPos(pos); String result = Utf8.decodeUtf8(buffer, bufferPos, size); pos += size; return result; } if (size == 0) { return ""; } if (size <= 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void readGroup( final int fieldNumber, final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; } @Override public <T extends MessageLite> T readGroup( final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; return result; } @Deprecated @Override public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws IOException { readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry()); } @Override public void readMessage( final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { final int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); } @Override public <T extends MessageLite> T readMessage( final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); return result; } @Override public ByteString readBytes() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= remaining()) { if (immutable && enableAliasing) { final ByteBuffer result = slice(pos, pos + size); pos += size; return ByteString.wrap(result); } else { // Use UnsafeUtil to copy the memory to bytes instead of using ByteBuffer ways. byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(pos, bytes, 0, size); pos += size; return ByteString.wrap(bytes); } } if (size == 0) { return ByteString.EMPTY; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public byte[] readByteArray() throws IOException { return readRawBytes(readRawVarint32()); } @Override public ByteBuffer readByteBuffer() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= remaining()) { // "Immutable" implies that buffer is backing a ByteString. // Disallow slicing in this case to prevent the caller from modifying the contents // of the ByteString. if (!immutable && enableAliasing) { final ByteBuffer result = slice(pos, pos + size); pos += size; return result; } else { // The same as readBytes' logic byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(pos, bytes, 0, size); pos += size; return ByteBuffer.wrap(bytes); } // TODO(nathanmittler): Investigate making the ByteBuffer be made read-only } if (size == 0) { return EMPTY_BYTE_BUFFER; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public int readUInt32() throws IOException { return readRawVarint32(); } @Override public int readEnum() throws IOException { return readRawVarint32(); } @Override public int readSFixed32() throws IOException { return readRawLittleEndian32(); } @Override public long readSFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readSInt32() throws IOException { return decodeZigZag32(readRawVarint32()); } @Override public long readSInt64() throws IOException { return decodeZigZag64(readRawVarint64()); } // ================================================================= @Override public int readRawVarint32() throws IOException { // See implementation notes for readRawVarint64 fastpath: { long tempPos = pos; if (limit == tempPos) { break fastpath; } int x; if ((x = UnsafeUtil.getByte(tempPos++)) >= 0) { pos = tempPos; return x; } else if (limit - tempPos < 9) { break fastpath; } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) { x ^= (~0 << 7); } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) { x ^= (~0 << 7) ^ (~0 << 14); } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) { x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); } else { int y = UnsafeUtil.getByte(tempPos++); x ^= y << 28; x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); if (y < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0) { break fastpath; // Will throw malformedVarint() } } pos = tempPos; return x; } return (int) readRawVarint64SlowPath(); } private void skipRawVarint() throws IOException { if (remaining() >= MAX_VARINT_SIZE) { skipRawVarintFastPath(); } else { skipRawVarintSlowPath(); } } private void skipRawVarintFastPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (UnsafeUtil.getByte(pos++) >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } private void skipRawVarintSlowPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (readRawByte() >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public long readRawVarint64() throws IOException { // Implementation notes: // // Optimized for one-byte values, expected to be common. // The particular code below was selected from various candidates // empirically, by winning VarintBenchmark. // // Sign extension of (signed) Java bytes is usually a nuisance, but // we exploit it here to more easily obtain the sign of bytes read. // Instead of cleaning up the sign extension bits by masking eagerly, // we delay until we find the final (positive) byte, when we clear all // accumulated bits with one xor. We depend on javac to constant fold. fastpath: { long tempPos = pos; if (limit == tempPos) { break fastpath; } long x; int y; if ((y = UnsafeUtil.getByte(tempPos++)) >= 0) { pos = tempPos; return y; } else if (limit - tempPos < 9) { break fastpath; } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) { x = y ^ (~0 << 7); } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) { x = y ^ ((~0 << 7) ^ (~0 << 14)); } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) { x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); } else if ((x = y ^ ((long) UnsafeUtil.getByte(tempPos++) << 28)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 35)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 42)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 49)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49); } else { x ^= ((long) UnsafeUtil.getByte(tempPos++) << 56); x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49) ^ (~0L << 56); if (x < 0L) { if (UnsafeUtil.getByte(tempPos++) < 0L) { break fastpath; // Will throw malformedVarint() } } } pos = tempPos; return x; } return readRawVarint64SlowPath(); } @Override long readRawVarint64SlowPath() throws IOException { long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public int readRawLittleEndian32() throws IOException { long tempPos = pos; if (limit - tempPos < FIXED32_SIZE) { throw InvalidProtocolBufferException.truncatedMessage(); } pos = tempPos + FIXED32_SIZE; return (((UnsafeUtil.getByte(tempPos) & 0xff)) | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24)); } @Override public long readRawLittleEndian64() throws IOException { long tempPos = pos; if (limit - tempPos < FIXED64_SIZE) { throw InvalidProtocolBufferException.truncatedMessage(); } pos = tempPos + FIXED64_SIZE; return (((UnsafeUtil.getByte(tempPos) & 0xffL)) | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24) | ((UnsafeUtil.getByte(tempPos + 4) & 0xffL) << 32) | ((UnsafeUtil.getByte(tempPos + 5) & 0xffL) << 40) | ((UnsafeUtil.getByte(tempPos + 6) & 0xffL) << 48) | ((UnsafeUtil.getByte(tempPos + 7) & 0xffL) << 56)); } @Override public void enableAliasing(boolean enabled) { this.enableAliasing = enabled; } @Override public void resetSizeCounter() { startPos = pos; } @Override public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { if (byteLimit < 0) { throw InvalidProtocolBufferException.negativeSize(); } byteLimit += getTotalBytesRead(); final int oldLimit = currentLimit; if (byteLimit > oldLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } currentLimit = byteLimit; recomputeBufferSizeAfterLimit(); return oldLimit; } @Override public void popLimit(final int oldLimit) { currentLimit = oldLimit; recomputeBufferSizeAfterLimit(); } @Override public int getBytesUntilLimit() { if (currentLimit == Integer.MAX_VALUE) { return -1; } return currentLimit - getTotalBytesRead(); } @Override public boolean isAtEnd() throws IOException { return pos == limit; } @Override public int getTotalBytesRead() { return (int) (pos - startPos); } @Override public byte readRawByte() throws IOException { if (pos == limit) { throw InvalidProtocolBufferException.truncatedMessage(); } return UnsafeUtil.getByte(pos++); } @Override public byte[] readRawBytes(final int length) throws IOException { if (length >= 0 && length <= remaining()) { byte[] bytes = new byte[length]; slice(pos, pos + length).get(bytes); pos += length; return bytes; } if (length <= 0) { if (length == 0) { return EMPTY_BYTE_ARRAY; } else { throw InvalidProtocolBufferException.negativeSize(); } } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void skipRawBytes(final int length) throws IOException { if (length >= 0 && length <= remaining()) { // We have all the bytes we need already. pos += length; return; } if (length < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } private void recomputeBufferSizeAfterLimit() { limit += bufferSizeAfterLimit; final int bufferEnd = (int) (limit - startPos); if (bufferEnd > currentLimit) { // Limit is in current buffer. bufferSizeAfterLimit = bufferEnd - currentLimit; limit -= bufferSizeAfterLimit; } else { bufferSizeAfterLimit = 0; } } private int remaining() { return (int) (limit - pos); } private int bufferPos(long pos) { return (int) (pos - address); } private ByteBuffer slice(long begin, long end) throws IOException { int prevPos = buffer.position(); int prevLimit = buffer.limit(); try { buffer.position(bufferPos(begin)); buffer.limit(bufferPos(end)); return buffer.slice(); } catch (IllegalArgumentException e) { throw InvalidProtocolBufferException.truncatedMessage(); } finally { buffer.position(prevPos); buffer.limit(prevLimit); } } } /** * Implementation of {@link CodedInputStream} that uses an {@link InputStream} as the data source. */ private static final class StreamDecoder extends CodedInputStream { private final InputStream input; private final byte[] buffer; /** bufferSize represents how many bytes are currently filled in the buffer */ private int bufferSize; private int bufferSizeAfterLimit; private int pos; private int lastTag; /** * The total number of bytes read before the current buffer. The total bytes read up to the * current position can be computed as {@code totalBytesRetired + pos}. This value may be * negative if reading started in the middle of the current buffer (e.g. if the constructor that * takes a byte array and an offset was used). */ private int totalBytesRetired; /** The absolute position of the end of the current message. */ private int currentLimit = Integer.MAX_VALUE; private StreamDecoder(final InputStream input, int bufferSize) { checkNotNull(input, "input"); this.input = input; this.buffer = new byte[bufferSize]; this.bufferSize = 0; pos = 0; totalBytesRetired = 0; } @Override public int readTag() throws IOException { if (isAtEnd()) { lastTag = 0; return 0; } lastTag = readRawVarint32(); if (WireFormat.getTagFieldNumber(lastTag) == 0) { // If we actually read zero (or any tag number corresponding to field // number zero), that's not a valid tag. throw InvalidProtocolBufferException.invalidTag(); } return lastTag; } @Override public void checkLastTagWas(final int value) throws InvalidProtocolBufferException { if (lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } @Override public int getLastTag() { return lastTag; } @Override public boolean skipField(final int tag) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: skipRawVarint(); return true; case WireFormat.WIRETYPE_FIXED64: skipRawBytes(FIXED64_SIZE); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: skipRawBytes(readRawVarint32()); return true; case WireFormat.WIRETYPE_START_GROUP: skipMessage(); checkLastTagWas( WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP)); return true; case WireFormat.WIRETYPE_END_GROUP: return false; case WireFormat.WIRETYPE_FIXED32: skipRawBytes(FIXED32_SIZE); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public boolean skipField(final int tag, final CodedOutputStream output) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: { long value = readInt64(); output.writeRawVarint32(tag); output.writeUInt64NoTag(value); return true; } case WireFormat.WIRETYPE_FIXED64: { long value = readRawLittleEndian64(); output.writeRawVarint32(tag); output.writeFixed64NoTag(value); return true; } case WireFormat.WIRETYPE_LENGTH_DELIMITED: { ByteString value = readBytes(); output.writeRawVarint32(tag); output.writeBytesNoTag(value); return true; } case WireFormat.WIRETYPE_START_GROUP: { output.writeRawVarint32(tag); skipMessage(output); int endtag = WireFormat.makeTag( WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP); checkLastTagWas(endtag); output.writeRawVarint32(endtag); return true; } case WireFormat.WIRETYPE_END_GROUP: { return false; } case WireFormat.WIRETYPE_FIXED32: { int value = readRawLittleEndian32(); output.writeRawVarint32(tag); output.writeFixed32NoTag(value); return true; } default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public void skipMessage() throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag)) { return; } } } @Override public void skipMessage(CodedOutputStream output) throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag, output)) { return; } } } /** Collects the bytes skipped and returns the data in a ByteBuffer. */ private class SkippedDataSink implements RefillCallback { private int lastPos = pos; private ByteArrayOutputStream byteArrayStream; @Override public void onRefill() { if (byteArrayStream == null) { byteArrayStream = new ByteArrayOutputStream(); } byteArrayStream.write(buffer, lastPos, pos - lastPos); lastPos = 0; } /** Gets skipped data in a ByteBuffer. This method should only be called once. */ ByteBuffer getSkippedData() { if (byteArrayStream == null) { return ByteBuffer.wrap(buffer, lastPos, pos - lastPos); } else { byteArrayStream.write(buffer, lastPos, pos); return ByteBuffer.wrap(byteArrayStream.toByteArray()); } } } // ----------------------------------------------------------------- @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readRawLittleEndian64()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readRawLittleEndian32()); } @Override public long readUInt64() throws IOException { return readRawVarint64(); } @Override public long readInt64() throws IOException { return readRawVarint64(); } @Override public int readInt32() throws IOException { return readRawVarint32(); } @Override public long readFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readFixed32() throws IOException { return readRawLittleEndian32(); } @Override public boolean readBool() throws IOException { return readRawVarint64() != 0; } @Override public String readString() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= (bufferSize - pos)) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. final String result = new String(buffer, pos, size, UTF_8); pos += size; return result; } if (size == 0) { return ""; } if (size <= bufferSize) { refillBuffer(size); String result = new String(buffer, pos, size, UTF_8); pos += size; return result; } // Slow path: Build a byte array first then copy it. return new String(readRawBytesSlowPath(size), UTF_8); } @Override public String readStringRequireUtf8() throws IOException { final int size = readRawVarint32(); final byte[] bytes; final int oldPos = pos; final int tempPos; if (size <= (bufferSize - oldPos) && size > 0) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. bytes = buffer; pos = oldPos + size; tempPos = oldPos; } else if (size == 0) { return ""; } else if (size <= bufferSize) { refillBuffer(size); bytes = buffer; tempPos = 0; pos = tempPos + size; } else { // Slow path: Build a byte array first then copy it. bytes = readRawBytesSlowPath(size); tempPos = 0; } return Utf8.decodeUtf8(bytes, tempPos, size); } @Override public void readGroup( final int fieldNumber, final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; } @Override public <T extends MessageLite> T readGroup( final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; return result; } @Deprecated @Override public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws IOException { readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry()); } @Override public void readMessage( final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { final int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); } @Override public <T extends MessageLite> T readMessage( final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); return result; } @Override public ByteString readBytes() throws IOException { final int size = readRawVarint32(); if (size <= (bufferSize - pos) && size > 0) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. final ByteString result = ByteString.copyFrom(buffer, pos, size); pos += size; return result; } if (size == 0) { return ByteString.EMPTY; } return readBytesSlowPath(size); } @Override public byte[] readByteArray() throws IOException { final int size = readRawVarint32(); if (size <= (bufferSize - pos) && size > 0) { // Fast path: We already have the bytes in a contiguous buffer, so // just copy directly from it. final byte[] result = Arrays.copyOfRange(buffer, pos, pos + size); pos += size; return result; } else { // Slow path: Build a byte array first then copy it. return readRawBytesSlowPath(size); } } @Override public ByteBuffer readByteBuffer() throws IOException { final int size = readRawVarint32(); if (size <= (bufferSize - pos) && size > 0) { // Fast path: We already have the bytes in a contiguous buffer. ByteBuffer result = ByteBuffer.wrap(Arrays.copyOfRange(buffer, pos, pos + size)); pos += size; return result; } if (size == 0) { return Internal.EMPTY_BYTE_BUFFER; } // Slow path: Build a byte array first then copy it. return ByteBuffer.wrap(readRawBytesSlowPath(size)); } @Override public int readUInt32() throws IOException { return readRawVarint32(); } @Override public int readEnum() throws IOException { return readRawVarint32(); } @Override public int readSFixed32() throws IOException { return readRawLittleEndian32(); } @Override public long readSFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readSInt32() throws IOException { return decodeZigZag32(readRawVarint32()); } @Override public long readSInt64() throws IOException { return decodeZigZag64(readRawVarint64()); } // ================================================================= @Override public int readRawVarint32() throws IOException { // See implementation notes for readRawVarint64 fastpath: { int tempPos = pos; if (bufferSize == tempPos) { break fastpath; } final byte[] buffer = this.buffer; int x; if ((x = buffer[tempPos++]) >= 0) { pos = tempPos; return x; } else if (bufferSize - tempPos < 9) { break fastpath; } else if ((x ^= (buffer[tempPos++] << 7)) < 0) { x ^= (~0 << 7); } else if ((x ^= (buffer[tempPos++] << 14)) >= 0) { x ^= (~0 << 7) ^ (~0 << 14); } else if ((x ^= (buffer[tempPos++] << 21)) < 0) { x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); } else { int y = buffer[tempPos++]; x ^= y << 28; x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); if (y < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0 && buffer[tempPos++] < 0) { break fastpath; // Will throw malformedVarint() } } pos = tempPos; return x; } return (int) readRawVarint64SlowPath(); } private void skipRawVarint() throws IOException { if (bufferSize - pos >= MAX_VARINT_SIZE) { skipRawVarintFastPath(); } else { skipRawVarintSlowPath(); } } private void skipRawVarintFastPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (buffer[pos++] >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } private void skipRawVarintSlowPath() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (readRawByte() >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public long readRawVarint64() throws IOException { // Implementation notes: // // Optimized for one-byte values, expected to be common. // The particular code below was selected from various candidates // empirically, by winning VarintBenchmark. // // Sign extension of (signed) Java bytes is usually a nuisance, but // we exploit it here to more easily obtain the sign of bytes read. // Instead of cleaning up the sign extension bits by masking eagerly, // we delay until we find the final (positive) byte, when we clear all // accumulated bits with one xor. We depend on javac to constant fold. fastpath: { int tempPos = pos; if (bufferSize == tempPos) { break fastpath; } final byte[] buffer = this.buffer; long x; int y; if ((y = buffer[tempPos++]) >= 0) { pos = tempPos; return y; } else if (bufferSize - tempPos < 9) { break fastpath; } else if ((y ^= (buffer[tempPos++] << 7)) < 0) { x = y ^ (~0 << 7); } else if ((y ^= (buffer[tempPos++] << 14)) >= 0) { x = y ^ ((~0 << 7) ^ (~0 << 14)); } else if ((y ^= (buffer[tempPos++] << 21)) < 0) { x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); } else if ((x = y ^ ((long) buffer[tempPos++] << 28)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); } else if ((x ^= ((long) buffer[tempPos++] << 35)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); } else if ((x ^= ((long) buffer[tempPos++] << 42)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); } else if ((x ^= ((long) buffer[tempPos++] << 49)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49); } else { x ^= ((long) buffer[tempPos++] << 56); x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49) ^ (~0L << 56); if (x < 0L) { if (buffer[tempPos++] < 0L) { break fastpath; // Will throw malformedVarint() } } } pos = tempPos; return x; } return readRawVarint64SlowPath(); } @Override long readRawVarint64SlowPath() throws IOException { long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public int readRawLittleEndian32() throws IOException { int tempPos = pos; if (bufferSize - tempPos < FIXED32_SIZE) { refillBuffer(FIXED32_SIZE); tempPos = pos; } final byte[] buffer = this.buffer; pos = tempPos + FIXED32_SIZE; return (((buffer[tempPos] & 0xff)) | ((buffer[tempPos + 1] & 0xff) << 8) | ((buffer[tempPos + 2] & 0xff) << 16) | ((buffer[tempPos + 3] & 0xff) << 24)); } @Override public long readRawLittleEndian64() throws IOException { int tempPos = pos; if (bufferSize - tempPos < FIXED64_SIZE) { refillBuffer(FIXED64_SIZE); tempPos = pos; } final byte[] buffer = this.buffer; pos = tempPos + FIXED64_SIZE; return (((buffer[tempPos] & 0xffL)) | ((buffer[tempPos + 1] & 0xffL) << 8) | ((buffer[tempPos + 2] & 0xffL) << 16) | ((buffer[tempPos + 3] & 0xffL) << 24) | ((buffer[tempPos + 4] & 0xffL) << 32) | ((buffer[tempPos + 5] & 0xffL) << 40) | ((buffer[tempPos + 6] & 0xffL) << 48) | ((buffer[tempPos + 7] & 0xffL) << 56)); } // ----------------------------------------------------------------- @Override public void enableAliasing(boolean enabled) { // TODO(nathanmittler): Ideally we should throw here. Do nothing for backward compatibility. } @Override public void resetSizeCounter() { totalBytesRetired = -pos; } @Override public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { if (byteLimit < 0) { throw InvalidProtocolBufferException.negativeSize(); } byteLimit += totalBytesRetired + pos; final int oldLimit = currentLimit; if (byteLimit > oldLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } currentLimit = byteLimit; recomputeBufferSizeAfterLimit(); return oldLimit; } private void recomputeBufferSizeAfterLimit() { bufferSize += bufferSizeAfterLimit; final int bufferEnd = totalBytesRetired + bufferSize; if (bufferEnd > currentLimit) { // Limit is in current buffer. bufferSizeAfterLimit = bufferEnd - currentLimit; bufferSize -= bufferSizeAfterLimit; } else { bufferSizeAfterLimit = 0; } } @Override public void popLimit(final int oldLimit) { currentLimit = oldLimit; recomputeBufferSizeAfterLimit(); } @Override public int getBytesUntilLimit() { if (currentLimit == Integer.MAX_VALUE) { return -1; } final int currentAbsolutePosition = totalBytesRetired + pos; return currentLimit - currentAbsolutePosition; } @Override public boolean isAtEnd() throws IOException { return pos == bufferSize && !tryRefillBuffer(1); } @Override public int getTotalBytesRead() { return totalBytesRetired + pos; } private interface RefillCallback { void onRefill(); } private RefillCallback refillCallback = null; /** * Reads more bytes from the input, making at least {@code n} bytes available in the buffer. * Caller must ensure that the requested space is not yet available, and that the requested * space is less than BUFFER_SIZE. * * @throws InvalidProtocolBufferException The end of the stream or the current limit was * reached. */ private void refillBuffer(int n) throws IOException { if (!tryRefillBuffer(n)) { // We have to distinguish the exception between sizeLimitExceeded and truncatedMessage. So // we just throw an sizeLimitExceeded exception here if it exceeds the sizeLimit if (n > sizeLimit - totalBytesRetired - pos) { throw InvalidProtocolBufferException.sizeLimitExceeded(); } else { throw InvalidProtocolBufferException.truncatedMessage(); } } } /** * Tries to read more bytes from the input, making at least {@code n} bytes available in the * buffer. Caller must ensure that the requested space is not yet available, and that the * requested space is less than BUFFER_SIZE. * * @return {@code true} If the bytes could be made available; {@code false} 1. Current at the * end of the stream 2. The current limit was reached 3. The total size limit was reached */ private boolean tryRefillBuffer(int n) throws IOException { if (pos + n <= bufferSize) { throw new IllegalStateException( "refillBuffer() called when " + n + " bytes were already available in buffer"); } // Check whether the size of total message needs to read is bigger than the size limit. // We shouldn't throw an exception here as isAtEnd() function needs to get this function's // return as the result. if (n > sizeLimit - totalBytesRetired - pos) { return false; } // Shouldn't throw the exception here either. if (totalBytesRetired + pos + n > currentLimit) { // Oops, we hit a limit. return false; } if (refillCallback != null) { refillCallback.onRefill(); } int tempPos = pos; if (tempPos > 0) { if (bufferSize > tempPos) { System.arraycopy(buffer, tempPos, buffer, 0, bufferSize - tempPos); } totalBytesRetired += tempPos; bufferSize -= tempPos; pos = 0; } // Here we should refill the buffer as many bytes as possible. int bytesRead = input.read( buffer, bufferSize, Math.min( // the size of allocated but unused bytes in the buffer buffer.length - bufferSize, // do not exceed the total bytes limit sizeLimit - totalBytesRetired - bufferSize)); if (bytesRead == 0 || bytesRead < -1 || bytesRead > buffer.length) { throw new IllegalStateException( input.getClass() + "#read(byte[]) returned invalid result: " + bytesRead + "\nThe InputStream implementation is buggy."); } if (bytesRead > 0) { bufferSize += bytesRead; recomputeBufferSizeAfterLimit(); return (bufferSize >= n) ? true : tryRefillBuffer(n); } return false; } @Override public byte readRawByte() throws IOException { if (pos == bufferSize) { refillBuffer(1); } return buffer[pos++]; } @Override public byte[] readRawBytes(final int size) throws IOException { final int tempPos = pos; if (size <= (bufferSize - tempPos) && size > 0) { pos = tempPos + size; return Arrays.copyOfRange(buffer, tempPos, tempPos + size); } else { return readRawBytesSlowPath(size); } } /** * Exactly like readRawBytes, but caller must have already checked the fast path: (size <= * (bufferSize - pos) && size > 0) */ private byte[] readRawBytesSlowPath(final int size) throws IOException { // Attempt to read the data in one byte array when it's safe to do. byte[] result = readRawBytesSlowPathOneChunk(size); if (result != null) { return result; } final int originalBufferPos = pos; final int bufferedBytes = bufferSize - pos; // Mark the current buffer consumed. totalBytesRetired += bufferSize; pos = 0; bufferSize = 0; // Determine the number of bytes we need to read from the input stream. int sizeLeft = size - bufferedBytes; // The size is very large. For security reasons we read them in small // chunks. List<byte[]> chunks = readRawBytesSlowPathRemainingChunks(sizeLeft); // OK, got everything. Now concatenate it all into one buffer. final byte[] bytes = new byte[size]; // Start by copying the leftover bytes from this.buffer. System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes); // And now all the chunks. int tempPos = bufferedBytes; for (final byte[] chunk : chunks) { System.arraycopy(chunk, 0, bytes, tempPos, chunk.length); tempPos += chunk.length; } // Done. return bytes; } /** * Attempts to read the data in one byte array when it's safe to do. Returns null if the size to * read is too large and needs to be allocated in smaller chunks for security reasons. */ private byte[] readRawBytesSlowPathOneChunk(final int size) throws IOException { if (size == 0) { return Internal.EMPTY_BYTE_ARRAY; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } // Integer-overflow-conscious check that the message size so far has not exceeded sizeLimit. int currentMessageSize = totalBytesRetired + pos + size; if (currentMessageSize - sizeLimit > 0) { throw InvalidProtocolBufferException.sizeLimitExceeded(); } // Verify that the message size so far has not exceeded currentLimit. if (currentMessageSize > currentLimit) { // Read to the end of the stream anyway. skipRawBytes(currentLimit - totalBytesRetired - pos); throw InvalidProtocolBufferException.truncatedMessage(); } final int bufferedBytes = bufferSize - pos; // Determine the number of bytes we need to read from the input stream. int sizeLeft = size - bufferedBytes; // TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE. if (sizeLeft < DEFAULT_BUFFER_SIZE || sizeLeft <= input.available()) { // Either the bytes we need are known to be available, or the required buffer is // within an allowed threshold - go ahead and allocate the buffer now. final byte[] bytes = new byte[size]; // Copy all of the buffered bytes to the result buffer. System.arraycopy(buffer, pos, bytes, 0, bufferedBytes); totalBytesRetired += bufferSize; pos = 0; bufferSize = 0; // Fill the remaining bytes from the input stream. int tempPos = bufferedBytes; while (tempPos < bytes.length) { int n = input.read(bytes, tempPos, size - tempPos); if (n == -1) { throw InvalidProtocolBufferException.truncatedMessage(); } totalBytesRetired += n; tempPos += n; } return bytes; } return null; } /** Reads the remaining data in small chunks from the input stream. */ private List<byte[]> readRawBytesSlowPathRemainingChunks(int sizeLeft) throws IOException { // The size is very large. For security reasons, we can't allocate the // entire byte array yet. The size comes directly from the input, so a // maliciously-crafted message could provide a bogus very large size in // order to trick the app into allocating a lot of memory. We avoid this // by allocating and reading only a small chunk at a time, so that the // malicious message must actually *be* extremely large to cause // problems. Meanwhile, we limit the allowed size of a message elsewhere. final List<byte[]> chunks = new ArrayList<byte[]>(); while (sizeLeft > 0) { // TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE. final byte[] chunk = new byte[Math.min(sizeLeft, DEFAULT_BUFFER_SIZE)]; int tempPos = 0; while (tempPos < chunk.length) { final int n = input.read(chunk, tempPos, chunk.length - tempPos); if (n == -1) { throw InvalidProtocolBufferException.truncatedMessage(); } totalBytesRetired += n; tempPos += n; } sizeLeft -= chunk.length; chunks.add(chunk); } return chunks; } /** * Like readBytes, but caller must have already checked the fast path: (size <= (bufferSize - * pos) && size > 0 || size == 0) */ private ByteString readBytesSlowPath(final int size) throws IOException { final byte[] result = readRawBytesSlowPathOneChunk(size); if (result != null) { return ByteString.wrap(result); } final int originalBufferPos = pos; final int bufferedBytes = bufferSize - pos; // Mark the current buffer consumed. totalBytesRetired += bufferSize; pos = 0; bufferSize = 0; // Determine the number of bytes we need to read from the input stream. int sizeLeft = size - bufferedBytes; // The size is very large. For security reasons we read them in small // chunks. List<byte[]> chunks = readRawBytesSlowPathRemainingChunks(sizeLeft); // Wrap the byte arrays into a single ByteString. List<ByteString> byteStrings = new ArrayList<ByteString>(1 + chunks.size()); byteStrings.add(ByteString.copyFrom(buffer, originalBufferPos, bufferedBytes)); for (byte[] chunk : chunks) { byteStrings.add(ByteString.wrap(chunk)); } return ByteString.copyFrom(byteStrings); } @Override public void skipRawBytes(final int size) throws IOException { if (size <= (bufferSize - pos) && size >= 0) { // We have all the bytes we need already. pos += size; } else { skipRawBytesSlowPath(size); } } /** * Exactly like skipRawBytes, but caller must have already checked the fast path: (size <= * (bufferSize - pos) && size >= 0) */ private void skipRawBytesSlowPath(final int size) throws IOException { if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } if (totalBytesRetired + pos + size > currentLimit) { // Read to the end of the stream anyway. skipRawBytes(currentLimit - totalBytesRetired - pos); // Then fail. throw InvalidProtocolBufferException.truncatedMessage(); } if (refillCallback != null) { // Skipping more bytes than are in the buffer. First skip what we have. int tempPos = bufferSize - pos; pos = bufferSize; // Keep refilling the buffer until we get to the point we wanted to skip to. // This has the side effect of ensuring the limits are updated correctly. refillBuffer(1); while (size - tempPos > bufferSize) { tempPos += bufferSize; pos = bufferSize; refillBuffer(1); } pos = size - tempPos; } else { // Skipping more bytes than are in the buffer. First skip what we have. totalBytesRetired += pos; int totalSkipped = bufferSize - pos; bufferSize = 0; pos = 0; try { while (totalSkipped < size) { int toSkip = size - totalSkipped; long skipped = input.skip(toSkip); if (skipped < 0 || skipped > toSkip) { throw new IllegalStateException( input.getClass() + "#skip returned invalid result: " + skipped + "\nThe InputStream implementation is buggy."); } totalSkipped += (int) skipped; } } finally { totalBytesRetired += totalSkipped; recomputeBufferSizeAfterLimit(); } } } } /** * Implementation of {@link CodedInputStream} that uses an {@link Iterable <ByteBuffer>} as the * data source. Requires the use of {@code sun.misc.Unsafe} to perform fast reads on the buffer. */ private static final class IterableDirectByteBufferDecoder extends CodedInputStream { /** The object that need to decode. */ private Iterable<ByteBuffer> input; /** The {@link Iterator} with type {@link ByteBuffer} of {@code input} */ private Iterator<ByteBuffer> iterator; /** The current ByteBuffer; */ private ByteBuffer currentByteBuffer; /** * If {@code true}, indicates that all the buffer are backing a {@link ByteString} and are * therefore considered to be an immutable input source. */ private boolean immutable; /** * If {@code true}, indicates that calls to read {@link ByteString} or {@code byte[]} * <strong>may</strong> return slices of the underlying buffer, rather than copies. */ private boolean enableAliasing; /** The global total message length limit */ private int totalBufferSize; /** The amount of available data in the input beyond {@link #currentLimit}. */ private int bufferSizeAfterCurrentLimit; /** The absolute position of the end of the current message. */ private int currentLimit = Integer.MAX_VALUE; /** The last tag that was read from this stream. */ private int lastTag; /** Total Bytes have been Read from the {@link Iterable} {@link ByteBuffer} */ private int totalBytesRead; /** The start position offset of the whole message, used as to reset the totalBytesRead */ private int startOffset; /** The current position for current ByteBuffer */ private long currentByteBufferPos; private long currentByteBufferStartPos; /** * If the current ByteBuffer is unsafe-direct based, currentAddress is the start address of this * ByteBuffer; otherwise should be zero. */ private long currentAddress; /** The limit position for current ByteBuffer */ private long currentByteBufferLimit; /** * The constructor of {@code Iterable<ByteBuffer>} decoder. * * @param inputBufs The input data. * @param size The total size of the input data. * @param immutableFlag whether the input data is immutable. */ private IterableDirectByteBufferDecoder( Iterable<ByteBuffer> inputBufs, int size, boolean immutableFlag) { totalBufferSize = size; input = inputBufs; iterator = input.iterator(); immutable = immutableFlag; startOffset = totalBytesRead = 0; if (size == 0) { currentByteBuffer = EMPTY_BYTE_BUFFER; currentByteBufferPos = 0; currentByteBufferStartPos = 0; currentByteBufferLimit = 0; currentAddress = 0; } else { tryGetNextByteBuffer(); } } /** To get the next ByteBuffer from {@code input}, and then update the parameters */ private void getNextByteBuffer() throws InvalidProtocolBufferException { if (!iterator.hasNext()) { throw InvalidProtocolBufferException.truncatedMessage(); } tryGetNextByteBuffer(); } private void tryGetNextByteBuffer() { currentByteBuffer = iterator.next(); totalBytesRead += (int) (currentByteBufferPos - currentByteBufferStartPos); currentByteBufferPos = currentByteBuffer.position(); currentByteBufferStartPos = currentByteBufferPos; currentByteBufferLimit = currentByteBuffer.limit(); currentAddress = UnsafeUtil.addressOffset(currentByteBuffer); currentByteBufferPos += currentAddress; currentByteBufferStartPos += currentAddress; currentByteBufferLimit += currentAddress; } @Override public int readTag() throws IOException { if (isAtEnd()) { lastTag = 0; return 0; } lastTag = readRawVarint32(); if (WireFormat.getTagFieldNumber(lastTag) == 0) { // If we actually read zero (or any tag number corresponding to field // number zero), that's not a valid tag. throw InvalidProtocolBufferException.invalidTag(); } return lastTag; } @Override public void checkLastTagWas(final int value) throws InvalidProtocolBufferException { if (lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } @Override public int getLastTag() { return lastTag; } @Override public boolean skipField(final int tag) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: skipRawVarint(); return true; case WireFormat.WIRETYPE_FIXED64: skipRawBytes(FIXED64_SIZE); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: skipRawBytes(readRawVarint32()); return true; case WireFormat.WIRETYPE_START_GROUP: skipMessage(); checkLastTagWas( WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP)); return true; case WireFormat.WIRETYPE_END_GROUP: return false; case WireFormat.WIRETYPE_FIXED32: skipRawBytes(FIXED32_SIZE); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public boolean skipField(final int tag, final CodedOutputStream output) throws IOException { switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: { long value = readInt64(); output.writeRawVarint32(tag); output.writeUInt64NoTag(value); return true; } case WireFormat.WIRETYPE_FIXED64: { long value = readRawLittleEndian64(); output.writeRawVarint32(tag); output.writeFixed64NoTag(value); return true; } case WireFormat.WIRETYPE_LENGTH_DELIMITED: { ByteString value = readBytes(); output.writeRawVarint32(tag); output.writeBytesNoTag(value); return true; } case WireFormat.WIRETYPE_START_GROUP: { output.writeRawVarint32(tag); skipMessage(output); int endtag = WireFormat.makeTag( WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP); checkLastTagWas(endtag); output.writeRawVarint32(endtag); return true; } case WireFormat.WIRETYPE_END_GROUP: { return false; } case WireFormat.WIRETYPE_FIXED32: { int value = readRawLittleEndian32(); output.writeRawVarint32(tag); output.writeFixed32NoTag(value); return true; } default: throw InvalidProtocolBufferException.invalidWireType(); } } @Override public void skipMessage() throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag)) { return; } } } @Override public void skipMessage(CodedOutputStream output) throws IOException { while (true) { final int tag = readTag(); if (tag == 0 || !skipField(tag, output)) { return; } } } // ----------------------------------------------------------------- @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readRawLittleEndian64()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readRawLittleEndian32()); } @Override public long readUInt64() throws IOException { return readRawVarint64(); } @Override public long readInt64() throws IOException { return readRawVarint64(); } @Override public int readInt32() throws IOException { return readRawVarint32(); } @Override public long readFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readFixed32() throws IOException { return readRawLittleEndian32(); } @Override public boolean readBool() throws IOException { return readRawVarint64() != 0; } @Override public String readString() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) { byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size); String result = new String(bytes, UTF_8); currentByteBufferPos += size; return result; } else if (size > 0 && size <= remaining()) { // TODO(yilunchong): To use an underlying bytes[] instead of allocating a new bytes[] byte[] bytes = new byte[size]; readRawBytesTo(bytes, 0, size); String result = new String(bytes, UTF_8); return result; } if (size == 0) { return ""; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public String readStringRequireUtf8() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) { final int bufferPos = (int) (currentByteBufferPos - currentByteBufferStartPos); String result = Utf8.decodeUtf8(currentByteBuffer, bufferPos, size); currentByteBufferPos += size; return result; } if (size >= 0 && size <= remaining()) { byte[] bytes = new byte[size]; readRawBytesTo(bytes, 0, size); return Utf8.decodeUtf8(bytes, 0, size); } if (size == 0) { return ""; } if (size <= 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void readGroup( final int fieldNumber, final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; } @Override public <T extends MessageLite> T readGroup( final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); --recursionDepth; return result; } @Deprecated @Override public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws IOException { readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry()); } @Override public void readMessage( final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry) throws IOException { final int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; builder.mergeFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); } @Override public <T extends MessageLite> T readMessage( final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException { int length = readRawVarint32(); if (recursionDepth >= recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } final int oldLimit = pushLimit(length); ++recursionDepth; T result = parser.parsePartialFrom(this, extensionRegistry); checkLastTagWas(0); --recursionDepth; popLimit(oldLimit); return result; } @Override public ByteString readBytes() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) { if (immutable && enableAliasing) { final int idx = (int) (currentByteBufferPos - currentAddress); final ByteString result = ByteString.wrap(slice(idx, idx + size)); currentByteBufferPos += size; return result; } else { byte[] bytes; bytes = new byte[size]; UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size); currentByteBufferPos += size; return ByteString.wrap(bytes); } } else if (size > 0 && size <= remaining()) { byte[] temp = new byte[size]; readRawBytesTo(temp, 0, size); return ByteString.wrap(temp); } if (size == 0) { return ByteString.EMPTY; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public byte[] readByteArray() throws IOException { return readRawBytes(readRawVarint32()); } @Override public ByteBuffer readByteBuffer() throws IOException { final int size = readRawVarint32(); if (size > 0 && size <= currentRemaining()) { if (!immutable && enableAliasing) { currentByteBufferPos += size; return slice( (int) (currentByteBufferPos - currentAddress - size), (int) (currentByteBufferPos - currentAddress)); } else { byte[] bytes = new byte[size]; UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, size); currentByteBufferPos += size; return ByteBuffer.wrap(bytes); } } else if (size > 0 && size <= remaining()) { byte[] temp = new byte[size]; readRawBytesTo(temp, 0, size); return ByteBuffer.wrap(temp); } if (size == 0) { return EMPTY_BYTE_BUFFER; } if (size < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public int readUInt32() throws IOException { return readRawVarint32(); } @Override public int readEnum() throws IOException { return readRawVarint32(); } @Override public int readSFixed32() throws IOException { return readRawLittleEndian32(); } @Override public long readSFixed64() throws IOException { return readRawLittleEndian64(); } @Override public int readSInt32() throws IOException { return decodeZigZag32(readRawVarint32()); } @Override public long readSInt64() throws IOException { return decodeZigZag64(readRawVarint64()); } @Override public int readRawVarint32() throws IOException { fastpath: { long tempPos = currentByteBufferPos; if (currentByteBufferLimit == currentByteBufferPos) { break fastpath; } int x; if ((x = UnsafeUtil.getByte(tempPos++)) >= 0) { currentByteBufferPos++; return x; } else if (currentByteBufferLimit - currentByteBufferPos < 10) { break fastpath; } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) { x ^= (~0 << 7); } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) { x ^= (~0 << 7) ^ (~0 << 14); } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) { x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); } else { int y = UnsafeUtil.getByte(tempPos++); x ^= y << 28; x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); if (y < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0 && UnsafeUtil.getByte(tempPos++) < 0) { break fastpath; // Will throw malformedVarint() } } currentByteBufferPos = tempPos; return x; } return (int) readRawVarint64SlowPath(); } @Override public long readRawVarint64() throws IOException { fastpath: { long tempPos = currentByteBufferPos; if (currentByteBufferLimit == currentByteBufferPos) { break fastpath; } long x; int y; if ((y = UnsafeUtil.getByte(tempPos++)) >= 0) { currentByteBufferPos++; return y; } else if (currentByteBufferLimit - currentByteBufferPos < 10) { break fastpath; } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) { x = y ^ (~0 << 7); } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) { x = y ^ ((~0 << 7) ^ (~0 << 14)); } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) { x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); } else if ((x = y ^ ((long) UnsafeUtil.getByte(tempPos++) << 28)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 35)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 42)) >= 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 49)) < 0L) { x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49); } else { x ^= ((long) UnsafeUtil.getByte(tempPos++) << 56); x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42) ^ (~0L << 49) ^ (~0L << 56); if (x < 0L) { if (UnsafeUtil.getByte(tempPos++) < 0L) { break fastpath; // Will throw malformedVarint() } } } currentByteBufferPos = tempPos; return x; } return readRawVarint64SlowPath(); } @Override long readRawVarint64SlowPath() throws IOException { long result = 0; for (int shift = 0; shift < 64; shift += 7) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } } throw InvalidProtocolBufferException.malformedVarint(); } @Override public int readRawLittleEndian32() throws IOException { if (currentRemaining() >= FIXED32_SIZE) { long tempPos = currentByteBufferPos; currentByteBufferPos += FIXED32_SIZE; return (((UnsafeUtil.getByte(tempPos) & 0xff)) | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24)); } return ((readRawByte() & 0xff) | ((readRawByte() & 0xff) << 8) | ((readRawByte() & 0xff) << 16) | ((readRawByte() & 0xff) << 24)); } @Override public long readRawLittleEndian64() throws IOException { if (currentRemaining() >= FIXED64_SIZE) { long tempPos = currentByteBufferPos; currentByteBufferPos += FIXED64_SIZE; return (((UnsafeUtil.getByte(tempPos) & 0xffL)) | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8) | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16) | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24) | ((UnsafeUtil.getByte(tempPos + 4) & 0xffL) << 32) | ((UnsafeUtil.getByte(tempPos + 5) & 0xffL) << 40) | ((UnsafeUtil.getByte(tempPos + 6) & 0xffL) << 48) | ((UnsafeUtil.getByte(tempPos + 7) & 0xffL) << 56)); } return ((readRawByte() & 0xffL) | ((readRawByte() & 0xffL) << 8) | ((readRawByte() & 0xffL) << 16) | ((readRawByte() & 0xffL) << 24) | ((readRawByte() & 0xffL) << 32) | ((readRawByte() & 0xffL) << 40) | ((readRawByte() & 0xffL) << 48) | ((readRawByte() & 0xffL) << 56)); } @Override public void enableAliasing(boolean enabled) { this.enableAliasing = enabled; } @Override public void resetSizeCounter() { startOffset = (int) (totalBytesRead + currentByteBufferPos - currentByteBufferStartPos); } @Override public int pushLimit(int byteLimit) throws InvalidProtocolBufferException { if (byteLimit < 0) { throw InvalidProtocolBufferException.negativeSize(); } byteLimit += getTotalBytesRead(); final int oldLimit = currentLimit; if (byteLimit > oldLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } currentLimit = byteLimit; recomputeBufferSizeAfterLimit(); return oldLimit; } private void recomputeBufferSizeAfterLimit() { totalBufferSize += bufferSizeAfterCurrentLimit; final int bufferEnd = totalBufferSize - startOffset; if (bufferEnd > currentLimit) { // Limit is in current buffer. bufferSizeAfterCurrentLimit = bufferEnd - currentLimit; totalBufferSize -= bufferSizeAfterCurrentLimit; } else { bufferSizeAfterCurrentLimit = 0; } } @Override public void popLimit(final int oldLimit) { currentLimit = oldLimit; recomputeBufferSizeAfterLimit(); } @Override public int getBytesUntilLimit() { if (currentLimit == Integer.MAX_VALUE) { return -1; } return currentLimit - getTotalBytesRead(); } @Override public boolean isAtEnd() throws IOException { return totalBytesRead + currentByteBufferPos - currentByteBufferStartPos == totalBufferSize; } @Override public int getTotalBytesRead() { return (int) (totalBytesRead - startOffset + currentByteBufferPos - currentByteBufferStartPos); } @Override public byte readRawByte() throws IOException { if (currentRemaining() == 0) { getNextByteBuffer(); } return UnsafeUtil.getByte(currentByteBufferPos++); } @Override public byte[] readRawBytes(final int length) throws IOException { if (length >= 0 && length <= currentRemaining()) { byte[] bytes = new byte[length]; UnsafeUtil.copyMemory(currentByteBufferPos, bytes, 0, length); currentByteBufferPos += length; return bytes; } if (length >= 0 && length <= remaining()) { byte[] bytes = new byte[length]; readRawBytesTo(bytes, 0, length); return bytes; } if (length <= 0) { if (length == 0) { return EMPTY_BYTE_ARRAY; } else { throw InvalidProtocolBufferException.negativeSize(); } } throw InvalidProtocolBufferException.truncatedMessage(); } /** * Try to get raw bytes from {@code input} with the size of {@code length} and copy to {@code * bytes} array. If the size is bigger than the number of remaining bytes in the input, then * throw {@code truncatedMessage} exception. * * @param bytes * @param offset * @param length * @throws IOException */ private void readRawBytesTo(byte[] bytes, int offset, final int length) throws IOException { if (length >= 0 && length <= remaining()) { int l = length; while (l > 0) { if (currentRemaining() == 0) { getNextByteBuffer(); } int bytesToCopy = Math.min(l, (int) currentRemaining()); UnsafeUtil.copyMemory(currentByteBufferPos, bytes, length - l + offset, bytesToCopy); l -= bytesToCopy; currentByteBufferPos += bytesToCopy; } return; } if (length <= 0) { if (length == 0) { return; } else { throw InvalidProtocolBufferException.negativeSize(); } } throw InvalidProtocolBufferException.truncatedMessage(); } @Override public void skipRawBytes(final int length) throws IOException { if (length >= 0 && length <= (totalBufferSize - totalBytesRead - currentByteBufferPos + currentByteBufferStartPos)) { // We have all the bytes we need already. int l = length; while (l > 0) { if (currentRemaining() == 0) { getNextByteBuffer(); } int rl = Math.min(l, (int) currentRemaining()); l -= rl; currentByteBufferPos += rl; } return; } if (length < 0) { throw InvalidProtocolBufferException.negativeSize(); } throw InvalidProtocolBufferException.truncatedMessage(); } // TODO: optimize to fastpath private void skipRawVarint() throws IOException { for (int i = 0; i < MAX_VARINT_SIZE; i++) { if (readRawByte() >= 0) { return; } } throw InvalidProtocolBufferException.malformedVarint(); } /** * Try to get the number of remaining bytes in {@code input}. * * @return the number of remaining bytes in {@code input}. */ private int remaining() { return (int) (totalBufferSize - totalBytesRead - currentByteBufferPos + currentByteBufferStartPos); } /** * Try to get the number of remaining bytes in {@code currentByteBuffer}. * * @return the number of remaining bytes in {@code currentByteBuffer} */ private long currentRemaining() { return (currentByteBufferLimit - currentByteBufferPos); } private ByteBuffer slice(int begin, int end) throws IOException { int prevPos = currentByteBuffer.position(); int prevLimit = currentByteBuffer.limit(); try { currentByteBuffer.position(begin); currentByteBuffer.limit(end); return currentByteBuffer.slice(); } catch (IllegalArgumentException e) { throw InvalidProtocolBufferException.truncatedMessage(); } finally { currentByteBuffer.position(prevPos); currentByteBuffer.limit(prevLimit); } } } }
[ "dherkel@google.com" ]
dherkel@google.com
5db43d1d3130f3d606dc5f14c480ecb9b614ab00
67f7a19e0ab650d4491ba304b2844aed8409f5e5
/src/Runner.java
251de60e8c2da333c69884d9a41116176c4a8224
[]
no_license
cgrad01/merchants-guide
e788c5b40435712943de4c9a96a96c9ab0335bab
b5b8a9510ea56216083fecb49b03eaff1f1d1753
refs/heads/master
2021-07-22T12:35:11.395968
2017-11-01T13:31:12
2017-11-01T13:31:12
107,890,811
0
0
null
null
null
null
UTF-8
Java
false
false
1,081
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class Runner { public static HashMap<String, Numeral> UNIT_VALUES = new HashMap<String, Numeral>() {}; public static HashMap<String, Integer> RESOURCE_VALUES = new HashMap<String, Integer>() {}; public static ArrayList<String> QUESTION_ANSWERS = new ArrayList<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("./input.txt")); Parsable[] parsers = {new NumeralParser(), new ResourceValueParser(), new UnitConverter()}; try { String line = br.readLine(); while (line != null) { for (Parsable parser : parsers) { parser.parse(line); } line = br.readLine(); } } finally { br.close(); } for (String answer: QUESTION_ANSWERS) { System.out.println(answer); } } }
[ "cgrad01@gmail.com" ]
cgrad01@gmail.com
3745f252674992909c1a51fa1f615ad34f72a6e8
08afea497a4e7ea7211abb17a3ce94c34b867845
/oxygen-aop/src/test/java/vip/justlive/oxygen/aop/Conf.java
4e04410cd4de94dd45706c2c5e5aea732d58866e
[ "Apache-2.0" ]
permissive
zihai367/oxygen
22443bb20a64d63280c2af1303789fcf0e5b6c44
a2dfb4810dc0e533ef63ab291a4e09345487fd24
refs/heads/master
2020-07-20T08:04:36.956444
2019-08-29T01:42:35
2019-08-29T01:42:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,860
java
/* * Copyright (C) 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package vip.justlive.oxygen.aop; import vip.justlive.oxygen.aop.annotation.Aspect; import vip.justlive.oxygen.aop.annotation.Aspect.TYPE; import vip.justlive.oxygen.ioc.annotation.Bean; import vip.justlive.oxygen.ioc.annotation.Inject; /** * @author wubo */ @Bean public class Conf { private final LogService logService; @Inject public Conf(LogService logService) { this.logService = logService; } @Aspect(annotation = Log.class, type = {TYPE.BEFORE, TYPE.AFTER, TYPE.CATCHING}, order = 1) public void log() { System.out.println("aop all log"); } @Aspect(annotation = Log.class, type = TYPE.BEFORE) public boolean log1(Invocation invocation) { System.out.println("aop before log1 " + invocation.getMethod()); logService.log(); return true; } @Aspect(annotation = Log.class, type = TYPE.AFTER) public void log2(Invocation invocation) { System.out.println("aop after log2 " + invocation.getMethod()); logService.log(); } @Aspect(annotation = Log.class, type = TYPE.CATCHING) public void log3(Invocation invocation) { System.out.println("aop catching log3 " + invocation.getMethod()); logService.log(); } @Log public void print() { System.out.println("print"); } }
[ "qq11419041@163.com" ]
qq11419041@163.com
90685116ec000683ef294cac967ec629e01cb743
20ba96cfe6032a8713a15e5a18a60bc540cbeea2
/e2e-component-biz-checkin-vertical/src/main/java/com/dayouzc/e2eapp/ebusiness/checkin/vertical/di/module/StatisticsModule.java
78841fda32d3a0fbbc3b4a08d7aa085a0cfe8e33
[]
no_license
chao121/chekin
fc02b8e42b31e6a67c1ad82587179c8642cdb2de
b7e5b4f4da9f5f3fbc209752594ddea201e819bb
refs/heads/master
2022-11-15T12:24:16.768746
2020-07-09T05:35:37
2020-07-09T05:35:37
278,271,324
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package com.dayouzc.e2eapp.ebusiness.checkin.vertical.di.module; import com.dayouzc.e2eapp.ebusiness.checkin.vertical.mvp.contract.StatisticsContract; import com.dayouzc.e2eapp.ebusiness.checkin.vertical.mvp.model.StatisticsModel; import dagger.Binds; import dagger.Module; /** * ================================================ * * @Description: 预约统计 * @Author qc * ================================================ */ @Module public abstract class StatisticsModule { @Binds abstract StatisticsContract.Model bindStatisticsModel(StatisticsModel model); }
[ "chaoqi@dayouzc.com" ]
chaoqi@dayouzc.com
e44a83d1f57dc8fec7a411078705824ac7e9f22b
310492655ac5490e1744b6b2de4f416a025a0186
/kaitou-office-excel/src/main/java/kaitou/office/excel/util/PropertyUtils.java
cd574c684dcd564ab1ecf2bad7b2105cbf4a7c23
[]
no_license
kaitouzhao/kaitou-office
28ed3dd8f69684f6c434392b11f2310be8598eb6
abb9c6393a2ba7b5c9812aeeb2193e3c02399777
refs/heads/master
2021-01-20T21:49:17.585773
2015-01-20T08:09:31
2015-01-20T08:09:31
29,518,948
1
0
null
null
null
null
UTF-8
Java
false
false
1,032
java
package kaitou.office.excel.util; import java.io.IOException; import java.util.Properties; /** * properties管理工具类. * User: 赵立伟 * Date: 2014/4/25 * Time: 10:31 */ public abstract class PropertyUtils { /** * 获取property值 * * @param name 名称 * @return 值 */ public static String getValue(String name) throws IOException { if (name == null || "".equals(name.trim())) { return ""; } java.io.InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"); Properties properties = new Properties(); properties.load(in); String value = properties.getProperty(name); return new String(value.getBytes("ISO-8859-1"), "gbk"); } /** * 获取项目文件 * * @param name 名称 * @return 路径 */ public static String getPath(String name) throws IOException { return System.getProperty("user.dir") + getValue(name); } }
[ "Kid.Zhao@gmail.com" ]
Kid.Zhao@gmail.com
539c3002316f35d440e970794e83794c33e35138
01345b6a4bd81ad836b95351e2fbcc7e30a48101
/spring-boot-tutorial/src/main/java/com/coverstar/dao/IOperations.java
b29c07ae339db265c4f6b813006555669b3279a6
[]
no_license
ShalithaJayamal/Onlineworld
388a654acd5e8aef46e67aef422c2a5641ddcaa8
6244d875f162d295a92f7a05f675e2b048455655
refs/heads/master
2022-12-01T05:35:42.095672
2020-08-15T18:22:32
2020-08-15T18:22:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package com.coverstar.dao; import java.io.Serializable; import java.util.List; import java.util.Optional; public interface IOperations<T extends Serializable> { Optional<T> findById(final long id); List<T> findAll(); T create(final T entity); T update(final T entity); void delete(final T entity); void deleteById(final long entityId); }
[ "shalithajayamal96@gmail.com" ]
shalithajayamal96@gmail.com
87a2b20cff18a11294d7ee9da0ce7ac732d77dce
b48a34155cd8e566039ded43e4e91a912e55bf45
/JXmall-product/src/main/java/com/lee/jxmall/product/vo/AttrGroupWithAttrsVo.java
c3949aaae15e68df2e58b9ed20c4b5fe09a9604e
[ "Apache-2.0" ]
permissive
Lee2580/JXmall
8ac713cc0f2fd715af2c13704368aeebe7b3c376
690a093ab6dd7394a32de400ac42bdb670446831
refs/heads/main
2023-08-24T09:33:44.652276
2021-09-22T08:25:41
2021-09-22T08:25:41
387,672,787
0
0
null
null
null
null
UTF-8
Java
false
false
337
java
package com.lee.jxmall.product.vo; import com.lee.jxmall.product.entity.AttrEntity; import com.lee.jxmall.product.entity.AttrGroupEntity; import lombok.Data; import java.util.List; @Data public class AttrGroupWithAttrsVo extends AttrGroupEntity { /** * 封装整个实体信息 */ private List<AttrEntity> attrs; }
[ "1114862851@qq.com" ]
1114862851@qq.com
2cca8dad8e8b07cd76e3a1e52dc363f3876c0b10
b7e1152f46a7871fa25ab11e0ed19e6046f4b414
/blog-api/src/main/java/com/zyz/blog/vo/PageResult.java
18c2f80a40be30f7903e1ac221c5a22efe18a4b3
[]
no_license
youki9527/blog
16bff754e47fd6de2d6be4ee9018b8af5c94f2d7
cbd1c02cb27e817217f11bb921c26fb193299184
refs/heads/master
2023-08-27T02:55:53.831491
2021-11-11T14:51:13
2021-11-11T14:51:13
410,240,992
0
0
null
null
null
null
UTF-8
Java
false
false
193
java
package com.zyz.blog.vo; import lombok.Data; import java.util.List; /** * @author zyz * @version 1.0 */ @Data public class PageResult<T> { private List<T> list; private Long total; }
[ "291821441@qq.com" ]
291821441@qq.com
09d164d59bea5b363524d1f44fdd9d66acb16443
cb57ab0a42e6a6b54a07fc6aa39edbfd2c88576d
/app/src/main/java/com/floatwindow/permission/rom/fw/Smartisan.java
2c8577a37e76e800064796e1b79c2a7bc6929628
[]
no_license
shionGitHub/FloatingWindow
a74759b0584439278487db122f72f80c35855f1c
306eae5c1f0c653ee420290e84b23a3231b20875
refs/heads/master
2020-05-03T20:22:45.613292
2019-06-25T06:45:43
2019-06-25T06:45:43
178,801,752
10
2
null
null
null
null
UTF-8
Java
false
false
662
java
package com.floatwindow.permission.rom.fw; import android.content.ComponentName; import android.content.Context; import android.content.Intent; public class Smartisan extends Rom { @Override public void openAutoStartSetting(Context context) { try { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.smartisanos.security", "com.smartisanos.security.MainActivity")); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } }
[ "346419807@qq.com" ]
346419807@qq.com
11803803718ea5d6ca953698e7aed8aa0d2722b3
0c40a63dfd91a6c7ea0b73937470f38677010778
/app/src/main/java/exception/OwnerIdMustBeLargerThanZeroException.java
fbc700e31207854b52a15f6cd275de18fc85bf94
[]
no_license
gyorgyice85/LoginRegister
6e3a75fcecf2dd58b9ac77b1af17a99d8c575d16
05264f6975fa36c70e688bf6bae33c45d187fbd8
refs/heads/master
2021-06-27T05:35:05.447170
2017-09-04T15:28:42
2017-09-04T15:28:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
225
java
package exception; /** * Created by Joshi on 11.08.2017. */ public class OwnerIdMustBeLargerThanZeroException extends Throwable { public OwnerIdMustBeLargerThanZeroException (String str) { super(str); } }
[ "schwegmaster@web.de" ]
schwegmaster@web.de
5750697a5c2137b6c765ef5a8da6614b02006351
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/21/21_06003215c5d001cd52273df3fadf569188022b0d/Game/21_06003215c5d001cd52273df3fadf569188022b0d_Game_t.java
9a049fe86ccd708de21421237d65e384f6a626aa
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
7,739
java
package graphic; import military.Shipyard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import state.Economy; import state.Fleet; import state.HQ; import state.Lane; import state.Star; import state.Universe; import ui.EconomyDialog; import ui.FleetWidget; import ui.HQWidget; import ui.IndexedDialog; import ui.StarWidget; import event.GameEventQueue; public class Game extends BasicGameState { private Image background; private StarWidget starWidget; private FleetWidget fleetWidget; private HQWidget hqWidget; private EconomyDialog econDialog; private Object selected; private GameEventQueue eventQueue; private IndexedDialog currentDialog; private int mouseDownTime; public void init(GameContainer gc, StateBasedGame game) throws SlickException { // Run module initialization. Be careful with dependencies. // This is for now very hard-coded and not very modular. Economy.init(); Fleet.init(); Shipyard.init(); // TODO figure out universe sizes, 500x500 for now. Size should be in the universe, not the camera! new Camera(new Vector2f(gc.getWidth(), gc.getHeight()), new Vector2f(600, 400)); starWidget = new StarWidget(); fleetWidget = new FleetWidget(); hqWidget = new HQWidget(); selected = null; econDialog = new EconomyDialog(); eventQueue = new GameEventQueue(); new Universe(); mouseDownTime = -1; currentDialog = null; // TODO load resources in a more intelligent way... Render.init(); background = new Image("resources/bck1.jpg"); Star.img = new Image("resources/star.png"); gc.setTargetFrameRate(120); // Pass two turns to reach a valid starting point (where last turn expenses are based on existing colonies). eventQueue.nextTurn(); eventQueue.nextTurn(); } public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException { // Draw backgrounds background.draw(0, 0); // FIXME Only a test to check coordinate direction, although it looks kind of cool... g.setColor(Color.white); g.drawLine(5, 5, 5, 10); g.drawLine(5, 5, 10, 5); g.setAntiAlias(true); Camera.instance().pushWorldTransformation(g); // Draw Lanes Lane.renderAll(gc, g); // Draw Stars for(Star s : Universe.instance().getStars()) { s.render(gc, g); } // Draw fleets for(Fleet tf : Universe.instance().getFleets()) { tf.render(gc, g, (tf == selected) ? Render.SELECTED : 0); } // Draw HQ for(HQ hq : HQ.all()) { hq.render(gc, g, (hq == selected) ? Render.SELECTED : 0); } // Draw in world widgets if(currentDialog != null) currentDialog.render(gc, g); // FIXME Temporary drawing world boundaries. Camera.instance().drawWorldLimits(g); // Draw HUD widgets g.popTransform(); econDialog.render(gc, g); // Draw events // eventQueue.render(gc, g); } public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException { // Process events and stop processing if modal. if(eventQueue.update(gc, delta)) return; // Check for input Input input = gc.getInput(); // Some interfaces if(mouseDownTime >= 0 && currentDialog != null) { currentDialog.mouseClick(Mouse.isButtonDown(0) ? 0 : 1, mouseDownTime); mouseDownTime += delta; } // Window displacement Vector2f displacement = new Vector2f(0.0f, 0.0f); if(input.isKeyDown(Input.KEY_RIGHT) || Mouse.getX() > Display.getWidth() - 5) { displacement.x = 1; } if(input.isKeyDown(Input.KEY_LEFT) || Mouse.getX() < 5) { displacement.x = -1; } if(input.isKeyDown(Input.KEY_UP) || Mouse.getY() > Display.getHeight() - 5) { displacement.y = -1; } if(input.isKeyDown(Input.KEY_DOWN) || Mouse.getY() < 5) { displacement.y = 1; } // Update x and y positions. Camera.instance().move(displacement.scale(delta/10.0f)); } /** * Advances the game to the next turn. */ public void turn() { // Move the universe forward. eventQueue.nextTurn(); } /** * Used for single clicks. */ @Override public void keyPressed(int key, char c) { if(key == Input.KEY_PRIOR) Camera.instance().zoom(true, Camera.instance().getScreenCenter()); else if(key == Input.KEY_NEXT) Camera.instance().zoom(false, Camera.instance().getScreenCenter()); else if(key == Input.KEY_T) this.turn(); else if(key == Input.KEY_E) econDialog.setVisible(!econDialog.isVisible()); else if(key == Input.KEY_SPACE) currentDialog = null; } @Override public void keyReleased(int key, char c) { if(key == Input.KEY_SPACE) showDialogForSelection(); } @Override public void mousePressed(int button, int x, int y) { mouseDownTime = 0; if(currentDialog != null && currentDialog.isCursorInside()) return; // Check if the click corresponds to a star. Star selectedStar = null; for(Star s : Universe.instance().getStars()) { if(s.screenCLick((float)x, (float)y, button)) { selectedStar = s; break; } } // If a star, check if we add routepoints. if(selectedStar != null) { if(selected instanceof Fleet) { Fleet fleet = (Fleet)selected; // If a fleet was selected and a star was clicked, we might be adding a route point. if(button == 0) { fleet = fleetWidget.getFleetFromSelection(); fleet.addToRoute(selectedStar); } else fleet.removeFromRoute(selectedStar); return; } else selected = selectedStar; // TODO HQ relocation } else selected = null; // Check which objects may have received the click signal. for(Fleet tf : Universe.instance().getFleets()) { if(tf.screenCLick((float)x, (float)y, button)) { selected = tf; break; } } for(HQ hq : HQ.all()) { if(hq.screenCLick((float)x, (float)y, button)) { selected = hq; break; } } showDialogForSelection(); } private void showDialogForSelection() { // Toggle modal interfaces according to the new selection. if(selected instanceof Fleet) { fleetWidget.showFleet((Fleet)selected); currentDialog = fleetWidget; } else if(selected instanceof Star) { starWidget.showStar((Star)selected); currentDialog = starWidget; } else if(selected instanceof HQ) { hqWidget.showHQ((HQ)selected); currentDialog = hqWidget; } else currentDialog = null; System.out.format("selected: %s, dialog: %s\n", (selected == null ? "null" : selected.toString()), (currentDialog == null ? "null" : currentDialog.toString())); } @Override public void mouseReleased(int button, int x, int y) { mouseDownTime = -1; } @Override public void mouseWheelMoved(int change) { Camera.instance().zoom(change >= 0, new Vector2f(Mouse.getX(), Display.getHeight() - Mouse.getY())); } @Override public void mouseMoved(int oldx, int oldy, int newx, int newy) { if(currentDialog != null && currentDialog.moveCursor(oldx, oldy, newx, newy)) mouseDownTime = -1; } @Override public int getID() { return Main.GameStates.MAINGAME.ordinal(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
61984c2c8a6e1dbd06d54eef863f3c14798ab8e1
15ae8d4bd9e1085e0ba7a54beae2f0c126a2dce4
/src/jiuzhang/dp/CountPlane.java
5ddd864d171c765eebdcf476b05da39d0e5fd0ed
[]
no_license
qdh0520/Algorithm
aae9cc61cc020ba371afe4e638bdb5bff11150cf
40f626d95eb877005149631d4ffc228b2829cc89
refs/heads/master
2020-07-06T12:23:23.300710
2019-09-19T14:50:29
2019-09-19T14:50:29
203,016,025
1
0
null
2019-08-18T14:32:46
2019-08-18T14:32:45
null
UTF-8
Java
false
false
1,686
java
package jiuzhang.dp; import java.util.*; /** * 数飞机 * Created by Dell on 2017-08-20. */ public class CountPlane { public class Interval { int start, end; Interval(int start, int end) { this.start = start; this.end = end; } } public int countOfAirplanes(List<Interval> airplanes) { // write your code here ArrayList<Event> list=new ArrayList<>(); for (Interval plane:airplanes){ list.add(new Event(plane.start,1)); list.add(new Event(plane.end,0)); } Collections.sort(list,Event.getComparator()); int cur=0;int max=0; Event curEvent; for(int i=0;i<list.size();i++){ curEvent=list.get(i); if(curEvent.flag==1){ cur++; }else{ cur--; } max=Math.max(max,cur); } return max; } public static class Event{ int time; int flag; public Event(int time, int flag) { this.time = time; this.flag = flag; } public static Comparator<Event> getComparator(){ return new Comparator<Event>() { @Override public int compare(Event o1, Event o2) { if(o1.time!=o2.time){ return o1.time-o2.time; } return o1.flag-o2.flag; } }; } } }
[ "18103412880@163.com" ]
18103412880@163.com
67047e03e254689b6705b09b8a1be1145cacfd3a
6f2a95effada827d4d13953931323a086a2656dc
/src/com/practica102/app/Factorial.java
f946d129775212567385f6daecdf3d1bd1e5d7ea
[]
no_license
AryNG/Exercise10.2
4ab127edf44e4600055928e66de929217e3cd5d9
93c0ea196606b84334451938fc92796b33599a78
refs/heads/master
2020-08-17T08:24:03.755292
2019-10-16T20:29:15
2019-10-16T20:29:15
215,638,544
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
1,402
java
package com.practica102.app;import java.util.Scanner; public class Factorial { public static void main(String[] args) { //Variable------------------------------------------------------------------------------------- long factorial=1; int number=-1; Scanner input= new Scanner(System.in); //Process-------------------------------------------------------------------------------------- do { System.out.println("Number to calculate:"); number=input.nextInt(); if (number<=0) { System.out.println("No negative numbers allowed"); } }while (number<=0); factorial = Factorial2(number); System.out.println("The Factorial of "+number+" is:"+factorial+"\n(Which is gotten by multiplying several times "+number+".)"); /*System.out.printLn(String.format("The factorial of %d is: %d, (which is gotten by multiplying several times %d .)", number, factorial, number));*/ //CLOSE---------------------------------------------------------------------------------------- input.close(); } //Method Factorial----------------------------------------------------------------------------- public static long Factorial2 (int n) { int factorial=1; for (int i=1;i<=n;i++) { factorial=factorial*i; } return factorial; } } //NOTES AND SUCH------------------------------------------------------------------------------- /*Para bajar de línea en el print, es alt+shift+y*/
[ "red.codes.lifes@gmail.com" ]
red.codes.lifes@gmail.com
9353eecff6c2ff2852959b119757a88d98ce493c
61c86ef495c474caa4fefc68ae549be7be619060
/day10-code/src/com/wendy/day10/demo02/Zi.java
3fe58fce762dcace92a517a376df3703a1299813
[]
no_license
Huihuihuiwan/-Java-idea-
619c53b7cff2af4137dcaa3b15973215ad3b6dac
b32ea8ec1fdabdb36544821c806660a2eb12a702
refs/heads/master
2022-07-17T09:57:31.397066
2020-04-16T12:18:47
2020-04-16T12:18:47
248,991,410
1
0
null
2022-06-21T03:02:04
2020-03-21T14:20:56
Java
UTF-8
Java
false
false
145
java
package com.wendy.day10.demo02; /** * Author : wendy_wan * Created : 2020/3/16 21:52 */ public class Zi extends Fu implements MyInterface{ }
[ "542996083@qq.com" ]
542996083@qq.com
a59fe7e3205bda0a9e0772a262f2701080d5f67d
a3de367b1284d35e1d33789e4374c112b41bd263
/numberone-auth/src/main/java/com/numberONe/task/SpringTaskController.java
bd954aec9d35d03ba9db1bf2c22b85604a5ed80b
[]
no_license
trudgeDreamer/numberone-auth
aae9a8219150e4f88642be44b2e7124183afa5ed
0b57dfbfa52eb5aa60286127b7ac0b9d50c120a7
refs/heads/master
2021-05-15T14:27:19.243827
2017-10-17T01:49:49
2017-10-17T01:49:49
107,202,745
0
0
null
null
null
null
UTF-8
Java
false
false
5,041
java
package com.numberONe.task; import java.util.Properties; import javax.inject.Inject; import org.hyperic.sigar.Sigar; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.numberONe.entity.ServerInfoFormMap; import com.numberONe.mapper.ServerInfoMapper; import com.numberONe.util.Common; import com.numberONe.util.EmailUtils; import com.numberONe.util.PropertiesUtils; import com.numberONe.util.SystemInfo; /** * Spring调度,指定时间执行 * 利用了spring中使用注解的方式来进行任务调度。 * @author numberONe * 2015-05-19 * @version 3.0v */ @Component @Lazy(false) public class SpringTaskController { @Inject private ServerInfoMapper serverInfoMapper; public static void main(String[] args) { SpringTaskController action = new SpringTaskController(); try { action.task(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 与用户设置的使用率比较 spirng 调度 * * @throws Exception */ @Scheduled(cron = "1 * * * * ? ") public void task() throws Exception { ServerInfoFormMap usage = SystemInfo.usage(new Sigar()); String cpuUsage = usage.get("cpuUsage")+"";// CPU使用率 String serverUsage = usage.get("ramUsage")+"";// 系统内存使用率 String JvmUsage = usage.get("jvmUsage")+"";// 计算JVM内存使用率 Properties prop = PropertiesUtils.getProperties(); String cpu = prop.getProperty("cpu"); String jvm = prop.getProperty("jvm"); String ram = prop.getProperty("ram"); String email = prop.getProperty("toEmail"); // 当系统消耗内存大于或等于用户设定的内存时,发送邮件 String cpubool = ""; String jvmbool = ""; String rambool = ""; String mark = "<font color='red'>"; if (Double.parseDouble(cpuUsage) > Double.parseDouble(cpu)) { cpubool = "style=\"color: red;font-weight: 600;\""; mark += "CPU当前:" + cpuUsage + "%,超出预设值 " + cpu + "%<br>"; } if (Double.parseDouble(JvmUsage) > Double.parseDouble(jvm)) { jvmbool = "style=\"color: red;font-weight: 600;\""; mark += "JVM当前:" + JvmUsage + "%,超出预设值 " + jvm + "%<br>"; } if (Double.parseDouble(serverUsage) > Double.parseDouble(ram)) { rambool = "style=\"color: red;font-weight: 600;\""; mark += "内存当前:" + serverUsage + "%,超出预设值 " + ram + "%"; } mark += "</font>"; // 邮件内容 String title = "服务器预警提示 - "+Common.fromDateH(); String centent = "当前时间是:" + Common.fromDateH() + "<br/><br/>" + "<style type=\"text/css\">" + ".common-table{" + "-moz-user-select: none;" + "width:100%;" + "border:0;" + "table-layout : fixed;" + "border-top:1px solid #dedfe1;" + "border-right:1px solid #dedfe1;" + "}" + "/*header*/" + ".common-table thead td,.common-table thead th{" + " height:23px;" + " background-color:#e4e8ea;" + " text-align:center;" + " border-left:1px solid #dedfe1;" + "}" + ".common-table thead th, .common-table tbody th{" + "padding-left:7px;" + "padding-right:7px;" + "width:15px;" + "text-align:center;" + "}" + ".common-table tbody td, .common-table tbody th{" + " height:25px!important;" + "border-bottom:1px solid #dedfe1;" + "border-left:1px solid #dedfe1;" + "cursor:default;" + "word-break: break-all;" + "-moz-outline-style: none;" + "_padding-right:7px;" + "text-align:center;" + "}</style>" + "<table class=\"common-table\">" + "<thead>" + "<tr>" + "<td width=\"100\">名称</td>" + "<td width=\"100\">参数</td>" + "<td width=\"275\">预警设置</td>" + "</tr>" + "</thead>" + "<tbody id=\"tbody\">" + "<tr " + cpubool + "><td>CPU</td><td style=\"text-align: left;\">当前使用率:" + cpuUsage + "%</td><td>使用率超出 " + cpu + "%,,发送邮箱提示 </td></tr>" + "<tr " + rambool + "><td>服务器内存</td><td style=\"text-align: left;\">当前使用率:" + serverUsage + "%</td><td>使用率超出 " + ram + "%,发送邮箱提示 </td></tr>" + "<tr " + jvmbool + "><td>JVM内存</td><td style=\"text-align: left;\">当前使用率:" + JvmUsage + "%</td><td>使用率超出 " + jvm + "%,,发送邮箱提示 </td></tr>" + "</tbody>" + "</table>"; mark = mark.replaceAll("'","\""); if (!Common.isEmpty(cpubool) || !Common.isEmpty(jvmbool) || !Common.isEmpty(rambool)) { try { EmailUtils.sendMail(prop.getProperty("fromEmail"), email, prop.getProperty("emailName"), prop.getProperty("emailPassword"), title, centent); // 保存预警信息 usage.put("setCpuUsage", cpu); usage.put("setJvmUsage", jvm); usage.put("setRamUsage", ram); usage.put("email", email); usage.put("mark", mark); serverInfoMapper.addEntity(usage); System.err.println("发送邮件!"); } catch (Exception e) { System.err.println("发送邮件失败!"); } } } }
[ "zengyunqing@froevercross.com" ]
zengyunqing@froevercross.com
492615b4275ac662fbe477738130d1dee964ea9a
f4876059e6fade07d6c746407995f12470a39670
/IS24-XML/src/main/java/org/openestate/io/is24_xml/xml/VermarktungGewerbeTyp.java
4d276174c77e42edd12ed3a9e98a59fc35fc562c
[ "Apache-2.0" ]
permissive
shkelqimbehluli/OpenEstate-IO
c77c63e80aa1ec5f8f5cc9ebdf31dcc260f05ff3
a414cd927108e83807833dd1e683d48e0d37136a
refs/heads/master
2020-05-20T15:09:29.857859
2016-03-11T17:52:55
2016-03-11T17:52:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
28,784
java
package org.openestate.io.is24_xml.xml; import java.math.BigDecimal; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.jvnet.jaxb2_commons.lang.CopyStrategy2; import org.jvnet.jaxb2_commons.lang.CopyTo2; import org.jvnet.jaxb2_commons.lang.Equals2; import org.jvnet.jaxb2_commons.lang.EqualsStrategy2; import org.jvnet.jaxb2_commons.lang.JAXBCopyStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy; import org.jvnet.jaxb2_commons.lang.ToString2; import org.jvnet.jaxb2_commons.lang.ToStringStrategy2; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; /** * <p>Java class for VermarktungGewerbeTyp complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="VermarktungGewerbeTyp"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;choice&gt; * &lt;element name="Miete"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="Pro" type="{http://www.immobilienscout24.de/immobilientransfer}MieteEinheitTyp" default="Monat" /&gt; * &lt;attribute name="Kaltmiete" use="required" type="{http://www.immobilienscout24.de/immobilientransfer}PreisAufAnfrage" /&gt; * &lt;attribute name="Kaution" type="{http://www.immobilienscout24.de/immobilientransfer}Text50Typ" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;element name="Kauf"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="Preis" use="required" type="{http://www.immobilienscout24.de/immobilientransfer}PreisAufAnfrage" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/choice&gt; * &lt;attribute name="PreisParkflaeche" type="{http://www.immobilienscout24.de/immobilientransfer}Zahl152Typ" /&gt; * &lt;attribute name="Nebenkosten" type="{http://www.immobilienscout24.de/immobilientransfer}Zahl152Typ" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "VermarktungGewerbeTyp", propOrder = { "miete", "kauf" }) public class VermarktungGewerbeTyp implements Cloneable, CopyTo2, Equals2, ToString2 { @XmlElementRef(name = "Miete", namespace = "http://www.immobilienscout24.de/immobilientransfer", type = JAXBElement.class) protected JAXBElement<VermarktungGewerbeTyp.Miete> miete; @XmlElementRef(name = "Kauf", namespace = "http://www.immobilienscout24.de/immobilientransfer", type = JAXBElement.class) protected JAXBElement<VermarktungGewerbeTyp.Kauf> kauf; @XmlAttribute(name = "PreisParkflaeche") @XmlJavaTypeAdapter(Adapter35 .class) protected BigDecimal preisParkflaeche; @XmlAttribute(name = "Nebenkosten") @XmlJavaTypeAdapter(Adapter35 .class) protected BigDecimal nebenkosten; /** * Gets the value of the miete property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link VermarktungGewerbeTyp.Miete }{@code >} * */ public JAXBElement<VermarktungGewerbeTyp.Miete> getMiete() { return miete; } /** * Sets the value of the miete property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link VermarktungGewerbeTyp.Miete }{@code >} * */ public void setMiete(JAXBElement<VermarktungGewerbeTyp.Miete> value) { this.miete = value; } /** * Gets the value of the kauf property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link VermarktungGewerbeTyp.Kauf }{@code >} * */ public JAXBElement<VermarktungGewerbeTyp.Kauf> getKauf() { return kauf; } /** * Sets the value of the kauf property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link VermarktungGewerbeTyp.Kauf }{@code >} * */ public void setKauf(JAXBElement<VermarktungGewerbeTyp.Kauf> value) { this.kauf = value; } /** * Gets the value of the preisParkflaeche property. * * @return * possible object is * {@link String } * */ public BigDecimal getPreisParkflaeche() { return preisParkflaeche; } /** * Sets the value of the preisParkflaeche property. * * @param value * allowed object is * {@link String } * */ public void setPreisParkflaeche(BigDecimal value) { this.preisParkflaeche = value; } /** * Gets the value of the nebenkosten property. * * @return * possible object is * {@link String } * */ public BigDecimal getNebenkosten() { return nebenkosten; } /** * Sets the value of the nebenkosten property. * * @param value * allowed object is * {@link String } * */ public void setNebenkosten(BigDecimal value) { this.nebenkosten = value; } public String toString() { final ToStringStrategy2 strategy = JAXBToStringStrategy.INSTANCE; final StringBuilder buffer = new StringBuilder(); append(null, buffer, strategy); return buffer.toString(); } public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { strategy.appendStart(locator, this, buffer); appendFields(locator, buffer, strategy); strategy.appendEnd(locator, this, buffer); return buffer; } public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { { JAXBElement<VermarktungGewerbeTyp.Miete> theMiete; theMiete = this.getMiete(); strategy.appendField(locator, this, "miete", buffer, theMiete, (this.miete!= null)); } { JAXBElement<VermarktungGewerbeTyp.Kauf> theKauf; theKauf = this.getKauf(); strategy.appendField(locator, this, "kauf", buffer, theKauf, (this.kauf!= null)); } { BigDecimal thePreisParkflaeche; thePreisParkflaeche = this.getPreisParkflaeche(); strategy.appendField(locator, this, "preisParkflaeche", buffer, thePreisParkflaeche, (this.preisParkflaeche!= null)); } { BigDecimal theNebenkosten; theNebenkosten = this.getNebenkosten(); strategy.appendField(locator, this, "nebenkosten", buffer, theNebenkosten, (this.nebenkosten!= null)); } return buffer; } public Object clone() { return copyTo(createNewInstance()); } public Object copyTo(Object target) { final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE; return copyTo(null, target, strategy); } public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) { final Object draftCopy = ((target == null)?createNewInstance():target); if (draftCopy instanceof VermarktungGewerbeTyp) { final VermarktungGewerbeTyp copy = ((VermarktungGewerbeTyp) draftCopy); { Boolean mieteShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.miete!= null)); if (mieteShouldBeCopiedAndSet == Boolean.TRUE) { JAXBElement<VermarktungGewerbeTyp.Miete> sourceMiete; sourceMiete = this.getMiete(); @SuppressWarnings("unchecked") JAXBElement<VermarktungGewerbeTyp.Miete> copyMiete = ((JAXBElement<VermarktungGewerbeTyp.Miete> ) strategy.copy(LocatorUtils.property(locator, "miete", sourceMiete), sourceMiete, (this.miete!= null))); copy.setMiete(copyMiete); } else { if (mieteShouldBeCopiedAndSet == Boolean.FALSE) { copy.miete = null; } } } { Boolean kaufShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.kauf!= null)); if (kaufShouldBeCopiedAndSet == Boolean.TRUE) { JAXBElement<VermarktungGewerbeTyp.Kauf> sourceKauf; sourceKauf = this.getKauf(); @SuppressWarnings("unchecked") JAXBElement<VermarktungGewerbeTyp.Kauf> copyKauf = ((JAXBElement<VermarktungGewerbeTyp.Kauf> ) strategy.copy(LocatorUtils.property(locator, "kauf", sourceKauf), sourceKauf, (this.kauf!= null))); copy.setKauf(copyKauf); } else { if (kaufShouldBeCopiedAndSet == Boolean.FALSE) { copy.kauf = null; } } } { Boolean preisParkflaecheShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.preisParkflaeche!= null)); if (preisParkflaecheShouldBeCopiedAndSet == Boolean.TRUE) { BigDecimal sourcePreisParkflaeche; sourcePreisParkflaeche = this.getPreisParkflaeche(); BigDecimal copyPreisParkflaeche = ((BigDecimal) strategy.copy(LocatorUtils.property(locator, "preisParkflaeche", sourcePreisParkflaeche), sourcePreisParkflaeche, (this.preisParkflaeche!= null))); copy.setPreisParkflaeche(copyPreisParkflaeche); } else { if (preisParkflaecheShouldBeCopiedAndSet == Boolean.FALSE) { copy.preisParkflaeche = null; } } } { Boolean nebenkostenShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.nebenkosten!= null)); if (nebenkostenShouldBeCopiedAndSet == Boolean.TRUE) { BigDecimal sourceNebenkosten; sourceNebenkosten = this.getNebenkosten(); BigDecimal copyNebenkosten = ((BigDecimal) strategy.copy(LocatorUtils.property(locator, "nebenkosten", sourceNebenkosten), sourceNebenkosten, (this.nebenkosten!= null))); copy.setNebenkosten(copyNebenkosten); } else { if (nebenkostenShouldBeCopiedAndSet == Boolean.FALSE) { copy.nebenkosten = null; } } } } return draftCopy; } public Object createNewInstance() { return new VermarktungGewerbeTyp(); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final VermarktungGewerbeTyp that = ((VermarktungGewerbeTyp) object); { JAXBElement<VermarktungGewerbeTyp.Miete> lhsMiete; lhsMiete = this.getMiete(); JAXBElement<VermarktungGewerbeTyp.Miete> rhsMiete; rhsMiete = that.getMiete(); if (!strategy.equals(LocatorUtils.property(thisLocator, "miete", lhsMiete), LocatorUtils.property(thatLocator, "miete", rhsMiete), lhsMiete, rhsMiete, (this.miete!= null), (that.miete!= null))) { return false; } } { JAXBElement<VermarktungGewerbeTyp.Kauf> lhsKauf; lhsKauf = this.getKauf(); JAXBElement<VermarktungGewerbeTyp.Kauf> rhsKauf; rhsKauf = that.getKauf(); if (!strategy.equals(LocatorUtils.property(thisLocator, "kauf", lhsKauf), LocatorUtils.property(thatLocator, "kauf", rhsKauf), lhsKauf, rhsKauf, (this.kauf!= null), (that.kauf!= null))) { return false; } } { BigDecimal lhsPreisParkflaeche; lhsPreisParkflaeche = this.getPreisParkflaeche(); BigDecimal rhsPreisParkflaeche; rhsPreisParkflaeche = that.getPreisParkflaeche(); if (!strategy.equals(LocatorUtils.property(thisLocator, "preisParkflaeche", lhsPreisParkflaeche), LocatorUtils.property(thatLocator, "preisParkflaeche", rhsPreisParkflaeche), lhsPreisParkflaeche, rhsPreisParkflaeche, (this.preisParkflaeche!= null), (that.preisParkflaeche!= null))) { return false; } } { BigDecimal lhsNebenkosten; lhsNebenkosten = this.getNebenkosten(); BigDecimal rhsNebenkosten; rhsNebenkosten = that.getNebenkosten(); if (!strategy.equals(LocatorUtils.property(thisLocator, "nebenkosten", lhsNebenkosten), LocatorUtils.property(thatLocator, "nebenkosten", rhsNebenkosten), lhsNebenkosten, rhsNebenkosten, (this.nebenkosten!= null), (that.nebenkosten!= null))) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="Preis" use="required" type="{http://www.immobilienscout24.de/immobilientransfer}PreisAufAnfrage" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Kauf implements Cloneable, CopyTo2, Equals2, ToString2 { @XmlAttribute(name = "Preis", required = true) @XmlJavaTypeAdapter(Adapter36 .class) protected BigDecimal preis; /** * Gets the value of the preis property. * * @return * possible object is * {@link String } * */ public BigDecimal getPreis() { return preis; } /** * Sets the value of the preis property. * * @param value * allowed object is * {@link String } * */ public void setPreis(BigDecimal value) { this.preis = value; } public String toString() { final ToStringStrategy2 strategy = JAXBToStringStrategy.INSTANCE; final StringBuilder buffer = new StringBuilder(); append(null, buffer, strategy); return buffer.toString(); } public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { strategy.appendStart(locator, this, buffer); appendFields(locator, buffer, strategy); strategy.appendEnd(locator, this, buffer); return buffer; } public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { { BigDecimal thePreis; thePreis = this.getPreis(); strategy.appendField(locator, this, "preis", buffer, thePreis, (this.preis!= null)); } return buffer; } public Object clone() { return copyTo(createNewInstance()); } public Object copyTo(Object target) { final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE; return copyTo(null, target, strategy); } public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) { final Object draftCopy = ((target == null)?createNewInstance():target); if (draftCopy instanceof VermarktungGewerbeTyp.Kauf) { final VermarktungGewerbeTyp.Kauf copy = ((VermarktungGewerbeTyp.Kauf) draftCopy); { Boolean preisShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.preis!= null)); if (preisShouldBeCopiedAndSet == Boolean.TRUE) { BigDecimal sourcePreis; sourcePreis = this.getPreis(); BigDecimal copyPreis = ((BigDecimal) strategy.copy(LocatorUtils.property(locator, "preis", sourcePreis), sourcePreis, (this.preis!= null))); copy.setPreis(copyPreis); } else { if (preisShouldBeCopiedAndSet == Boolean.FALSE) { copy.preis = null; } } } } return draftCopy; } public Object createNewInstance() { return new VermarktungGewerbeTyp.Kauf(); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final VermarktungGewerbeTyp.Kauf that = ((VermarktungGewerbeTyp.Kauf) object); { BigDecimal lhsPreis; lhsPreis = this.getPreis(); BigDecimal rhsPreis; rhsPreis = that.getPreis(); if (!strategy.equals(LocatorUtils.property(thisLocator, "preis", lhsPreis), LocatorUtils.property(thatLocator, "preis", rhsPreis), lhsPreis, rhsPreis, (this.preis!= null), (that.preis!= null))) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="Pro" type="{http://www.immobilienscout24.de/immobilientransfer}MieteEinheitTyp" default="Monat" /&gt; * &lt;attribute name="Kaltmiete" use="required" type="{http://www.immobilienscout24.de/immobilientransfer}PreisAufAnfrage" /&gt; * &lt;attribute name="Kaution" type="{http://www.immobilienscout24.de/immobilientransfer}Text50Typ" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Miete implements Cloneable, CopyTo2, Equals2, ToString2 { @XmlAttribute(name = "Pro") protected MieteEinheitTyp pro; @XmlAttribute(name = "Kaltmiete", required = true) @XmlJavaTypeAdapter(Adapter36 .class) protected BigDecimal kaltmiete; @XmlAttribute(name = "Kaution") @XmlJavaTypeAdapter(Adapter7 .class) protected String kaution; /** * Gets the value of the pro property. * * @return * possible object is * {@link MieteEinheitTyp } * */ public MieteEinheitTyp getPro() { if (pro == null) { return MieteEinheitTyp.MONAT; } else { return pro; } } /** * Sets the value of the pro property. * * @param value * allowed object is * {@link MieteEinheitTyp } * */ public void setPro(MieteEinheitTyp value) { this.pro = value; } /** * Gets the value of the kaltmiete property. * * @return * possible object is * {@link String } * */ public BigDecimal getKaltmiete() { return kaltmiete; } /** * Sets the value of the kaltmiete property. * * @param value * allowed object is * {@link String } * */ public void setKaltmiete(BigDecimal value) { this.kaltmiete = value; } /** * Gets the value of the kaution property. * * @return * possible object is * {@link String } * */ public String getKaution() { return kaution; } /** * Sets the value of the kaution property. * * @param value * allowed object is * {@link String } * */ public void setKaution(String value) { this.kaution = value; } public String toString() { final ToStringStrategy2 strategy = JAXBToStringStrategy.INSTANCE; final StringBuilder buffer = new StringBuilder(); append(null, buffer, strategy); return buffer.toString(); } public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { strategy.appendStart(locator, this, buffer); appendFields(locator, buffer, strategy); strategy.appendEnd(locator, this, buffer); return buffer; } public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) { { MieteEinheitTyp thePro; thePro = this.getPro(); strategy.appendField(locator, this, "pro", buffer, thePro, (this.pro!= null)); } { BigDecimal theKaltmiete; theKaltmiete = this.getKaltmiete(); strategy.appendField(locator, this, "kaltmiete", buffer, theKaltmiete, (this.kaltmiete!= null)); } { String theKaution; theKaution = this.getKaution(); strategy.appendField(locator, this, "kaution", buffer, theKaution, (this.kaution!= null)); } return buffer; } public Object clone() { return copyTo(createNewInstance()); } public Object copyTo(Object target) { final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE; return copyTo(null, target, strategy); } public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) { final Object draftCopy = ((target == null)?createNewInstance():target); if (draftCopy instanceof VermarktungGewerbeTyp.Miete) { final VermarktungGewerbeTyp.Miete copy = ((VermarktungGewerbeTyp.Miete) draftCopy); { Boolean proShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.pro!= null)); if (proShouldBeCopiedAndSet == Boolean.TRUE) { MieteEinheitTyp sourcePro; sourcePro = this.getPro(); MieteEinheitTyp copyPro = ((MieteEinheitTyp) strategy.copy(LocatorUtils.property(locator, "pro", sourcePro), sourcePro, (this.pro!= null))); copy.setPro(copyPro); } else { if (proShouldBeCopiedAndSet == Boolean.FALSE) { copy.pro = null; } } } { Boolean kaltmieteShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.kaltmiete!= null)); if (kaltmieteShouldBeCopiedAndSet == Boolean.TRUE) { BigDecimal sourceKaltmiete; sourceKaltmiete = this.getKaltmiete(); BigDecimal copyKaltmiete = ((BigDecimal) strategy.copy(LocatorUtils.property(locator, "kaltmiete", sourceKaltmiete), sourceKaltmiete, (this.kaltmiete!= null))); copy.setKaltmiete(copyKaltmiete); } else { if (kaltmieteShouldBeCopiedAndSet == Boolean.FALSE) { copy.kaltmiete = null; } } } { Boolean kautionShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.kaution!= null)); if (kautionShouldBeCopiedAndSet == Boolean.TRUE) { String sourceKaution; sourceKaution = this.getKaution(); String copyKaution = ((String) strategy.copy(LocatorUtils.property(locator, "kaution", sourceKaution), sourceKaution, (this.kaution!= null))); copy.setKaution(copyKaution); } else { if (kautionShouldBeCopiedAndSet == Boolean.FALSE) { copy.kaution = null; } } } } return draftCopy; } public Object createNewInstance() { return new VermarktungGewerbeTyp.Miete(); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) { if ((object == null)||(this.getClass()!= object.getClass())) { return false; } if (this == object) { return true; } final VermarktungGewerbeTyp.Miete that = ((VermarktungGewerbeTyp.Miete) object); { MieteEinheitTyp lhsPro; lhsPro = this.getPro(); MieteEinheitTyp rhsPro; rhsPro = that.getPro(); if (!strategy.equals(LocatorUtils.property(thisLocator, "pro", lhsPro), LocatorUtils.property(thatLocator, "pro", rhsPro), lhsPro, rhsPro, (this.pro!= null), (that.pro!= null))) { return false; } } { BigDecimal lhsKaltmiete; lhsKaltmiete = this.getKaltmiete(); BigDecimal rhsKaltmiete; rhsKaltmiete = that.getKaltmiete(); if (!strategy.equals(LocatorUtils.property(thisLocator, "kaltmiete", lhsKaltmiete), LocatorUtils.property(thatLocator, "kaltmiete", rhsKaltmiete), lhsKaltmiete, rhsKaltmiete, (this.kaltmiete!= null), (that.kaltmiete!= null))) { return false; } } { String lhsKaution; lhsKaution = this.getKaution(); String rhsKaution; rhsKaution = that.getKaution(); if (!strategy.equals(LocatorUtils.property(thisLocator, "kaution", lhsKaution), LocatorUtils.property(thatLocator, "kaution", rhsKaution), lhsKaution, rhsKaution, (this.kaution!= null), (that.kaution!= null))) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } } }
[ "andy@openindex.de" ]
andy@openindex.de
e2e1162c161627862e31fdfb42045250641543da
548a7a311324751de587d83ac3b8ae1886f70dfa
/src/main/java/com/xxx/common/utils/PrimaryKeyUtil.java
4db49bdc5431e0e885c5d254f665fe54fcc330a4
[]
no_license
oIdmonk/springbootGeneratorCode
0ff3a18368b191bf3b1df82512d5163d56bdf38d
9cab5764e724fbae61fc6d45f01c831fabfaf6ad
refs/heads/master
2020-04-09T11:25:51.578736
2018-12-20T09:14:31
2018-12-20T09:14:31
160,309,209
1
0
null
null
null
null
UTF-8
Java
false
false
2,689
java
package com.xxx.common.utils; import java.util.Random; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 主键生成表 * @author huangyufei * @Description * @date 2017-12-23 15:46 */ public class PrimaryKeyUtil { private static final long ONE_STEP = 10; private static final Lock LOCK = new ReentrantLock(); private static long lastTime = System.currentTimeMillis(); private static short lastCount = 0; private static int count = 0; @SuppressWarnings("finally") public static String nextId() { LOCK.lock(); try { if (lastCount == ONE_STEP) { boolean done = false; while (!done) { long now = System.currentTimeMillis(); if (now == lastTime) { try { Thread.currentThread(); Thread.sleep(1); } catch (InterruptedException e) { } continue; } else { lastTime = now; lastCount = 0; done = true; } } } count = lastCount++; } finally { LOCK.unlock(); return lastTime+""+String.format("%03d",count)+getStringRandom(8); } } //生成随机数字和字母, public static String getStringRandom(int length) { String val = ""; Random random = new Random(); //参数length,表示生成几位随机数 for(int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; //输出字母还是数字 if( "char".equalsIgnoreCase(charOrNum) ) { //输出是大写字母还是小写字母 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char)(random.nextInt(26) + temp); } else if( "num".equalsIgnoreCase(charOrNum) ) { val += String.valueOf(random.nextInt(10)); } } return val; } /** * uuid * @return */ public static String newUUId(){ return UUID.randomUUID().toString(); } public static void main(String[] args) { String a = ""; //测试 //System.out.println(getStringRandom(8)); //测试 for(int i=0;i<1000;i++) { a = UUID.randomUUID().toString(); System.out.println(a); } } }
[ "470612348@qq.com" ]
470612348@qq.com
3336892951c9dc1c1c2f96eb69e4a17c40e731ad
ab5d86024da303562208c1cdc842031f91ebc1cb
/moshi/src/test/java/moshi/tets.java
c22cdebf758386d39d5247530ae292403091e300
[]
no_license
ff445566/moshi
5cfa1ecac5be44bc2058609674139c024dd284df
88029ba8583a81e0f332615d7fdea011b947585c
refs/heads/master
2020-03-18T08:26:33.009081
2018-06-03T11:35:38
2018-06-03T11:35:38
134,509,658
0
0
null
null
null
null
GB18030
Java
false
false
2,213
java
package moshi; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class tets { public static void main(String[] args) { List list=new ArrayList<Object>(); list.add("b"); list.add("a");list.add("a"); list.add("a");list.add("d");list.add("c"); list.add("c"); System.out.println(list.toString()); System.out.println(E(list).toString()); Object[] arr = list.toArray(); System.out.println(arr[1]); } // 去除相同元素 public static List A(List list){ for(int i=0;i<list.size();i++){ for(int j=list.size()-1;j>i;j--){ if(list.get(i).equals(list.get(j))){ list.remove(j); } } } return list; } public static List B(List list){ Set set=new HashSet<Object>(); List list2=new ArrayList<Object>(); Iterator<String> iterator= list.iterator(); while(iterator.hasNext()){ String str = iterator.next(); if(set.add(str)){ list2.add(str); } } //set.addAll(set); list.clear(); list.addAll(list2); return list; } public static List C(List list){ List list2=new ArrayList<Object>(); for (int i = 0; i < list.size(); i++) { if(!list2.contains(list.get(i))){ list2.add(i); } } return list; } // 统计相同图元素 public static <E> List D(List list){ List list2=new ArrayList<Object>(); Map map=new HashMap<String, Integer>(); for (int i = 0; i < list.size(); i++) { if( map.containsKey(list.get(i))){ String key=(String) list.get(i); int value=(Integer) map.get(key); map.put(key, ++value); } else map.put(list.get(i), 1); } // 遍历hashmap // Iterator iter=map.entrySet().iterator(); // while(iter.hasNext()){ // Entry<String, Integer> entry = (Map.Entry<String, Integer>)iter.next(); // String key=entry.getKey(); // int value=entry.getValue(); // } list.clear(); list.add(map); return list; } public static List E(List list){ List list2=new ArrayList(); list2.add("11"); list2.add("22"); list2.add("33"); list.addAll(1,list2); return list; } }
[ "1015809436@qq.com" ]
1015809436@qq.com
9398870df65c42d79203f903db3b8389ecb69088
18fddc2226dcdfb61c5d307be2c9c5830952cb73
/src/main/java/process/EstimateLeftRightVariance_JFRC2013.java
c0719b961ee06469e770c6dd3e0423af15a2326b
[ "BSD-2-Clause" ]
permissive
saalfeldlab/template-building
a72b9b348edba648a9fc2eb3f8319f0403cd7bad
84ad3a4573358c4ca6fbb99509c8b29e97b0051c
refs/heads/master
2023-08-24T04:32:46.926463
2023-08-15T19:38:24
2023-08-15T19:38:24
78,023,958
8
3
BSD-2-Clause
2023-05-12T15:14:23
2017-01-04T14:43:58
Jupyter Notebook
UTF-8
Java
false
false
10,639
java
package process; import java.io.File; import java.io.IOException; import bdv.util.Bdv; import bdv.util.BdvFunctions; import ij.IJ; import ij.ImagePlus; import io.AffineImglib2IO; import io.nii.NiftiIo; import jitk.spline.XfmUtils; import loci.formats.FormatException; import net.imglib2.Cursor; import net.imglib2.FinalInterval; import net.imglib2.RandomAccess; import net.imglib2.converter.Converters; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.img.imageplus.FloatImagePlus; import net.imglib2.img.imageplus.ImagePlusImgs; import net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.InvertibleRealTransform; import net.imglib2.realtransform.InvertibleRealTransformSequence; import net.imglib2.realtransform.RealViews; import net.imglib2.realtransform.ants.ANTSDeformationField; import net.imglib2.realtransform.ants.ANTSLoadAffine; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.util.Intervals; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import transforms.AffineHelper; public class EstimateLeftRightVariance_JFRC2013 { // This factors 2 iso brings it to microns - but is my rough guess // based on the relative sizes of JFRC2013 and JFRC2010 // double[] factors = new double[]{ 1, 1, 1 }; // double[] rawRes = new double[]{ 0.4393, 0.4393, 0.4393 }; // double[] rawRes = new double[]{ 0.36, 0.36, 0.36 }; double[] factors = new double[]{ 1, 1, 1 }; double[] factors2Iso = new double[]{ 1.0, 1.0, 1.0 }; double[] rawRes = new double[]{ 0.1882689, 0.1882689, 0.38 }; double[] res; // AffineTransform3D toIso; AffineTransform3D up3d; AffineTransform3D down3d; AffineTransform3D up3dNoShift; public EstimateLeftRightVariance_JFRC2013() { init(); } public void init() { // toIso = new AffineTransform3D(); // toIso.set( factors2Iso[ 0 ], 0, 0 ); // toIso.set( factors2Iso[ 1 ], 1, 1 ); // toIso.set( factors2Iso[ 2 ], 2, 2 ); up3d = new AffineTransform3D(); up3d.set( factors[ 0 ], 0, 0 ); up3d.set( factors[ 1 ], 1, 1 ); up3d.set( factors[ 2 ], 2, 2 ); up3d.set( 4, 0, 3 ); up3d.set( 4, 1, 3 ); up3d.set( 2, 2, 3 ); down3d = up3d.inverse(); up3dNoShift = new AffineTransform3D(); up3dNoShift.set( factors[ 0 ], 0, 0 ); up3dNoShift.set( factors[ 1 ], 1, 1 ); up3dNoShift.set( factors[ 2 ], 2, 2 ); res = new double[ 3 ]; for( int i = 0; i < 3; i++ ) { res[ i ] = rawRes[ i ] * factors[ i ]; } } public InvertibleRealTransformSequence buildTransform( String flipPreXfmF, String affineF, String deformationF ) throws IOException, FormatException { System.out.println("affine: " + affineF ); System.out.println("deformation: " + deformationF ); AffineTransform3D affine = ANTSLoadAffine.loadAffine( affineF ); // ANTSDeformationField df = null; ImagePlus ip = NiftiIo.readNifti( new File( deformationF ) ); Img< FloatType > defLowImg = ImageJFunctions.convertFloat( ip ); ANTSDeformationField df = new ANTSDeformationField( defLowImg, new double[]{ 1, 1, 1 }, ip.getCalibration().getUnit() ); AffineTransform3D flipAffine = null; if( flipPreXfmF != null && !flipPreXfmF.isEmpty() ) { System.out.println("have flip: " + flipPreXfmF ); flipAffine = AffineHelper.to3D( AffineImglib2IO.readXfm( 3, new File( flipPreXfmF ) )); } return buildTransform( flipAffine, affine, df ); } public InvertibleRealTransformSequence buildTransform( AffineTransform3D flipPreXfm, AffineTransform3D affine, ANTSDeformationField df ) { AffineTransform3D totalAffine = null; if ( flipPreXfm != null ) { totalAffine = flipPreXfm.inverse().copy(); } else { totalAffine = down3d.copy(); } totalAffine.preConcatenate( affine.inverse() ); InvertibleRealTransformSequence totalXfm = new InvertibleRealTransformSequence(); totalXfm.add( totalAffine ); if ( df != null ) { totalXfm.add( df ); } // if ( toNormal != null ) // { // totalXfm.add( toNormal ); // } // totalXfm.add( up3dNoShift ); // totalXfm.add( toIso ); return totalXfm; } public <T extends RealType<T>> void buildDistanceImage( Img<FloatType> destinationImg, Img<T> mask, InvertibleRealTransform totalXfm, InvertibleRealTransform totalXfmFlip, InvertibleRealTransform templateFlip ) { double[] x = new double[ 3 ]; double[] xFlip = new double[ 3 ]; double[] xSrc = new double[ 3 ]; double[] xSrcFlip = new double[ 3 ]; Cursor< FloatType > cursor = destinationImg.cursor(); RandomAccess< T > mra = mask.randomAccess(); while( cursor.hasNext() ) { cursor.fwd(); mra.setPosition( cursor ); if( mra.get().getRealDouble() <= 0 ) { continue; } cursor.localize( x ); templateFlip.applyInverse( xFlip, x ); totalXfm.applyInverse( xSrc, x); totalXfmFlip.applyInverse( xSrcFlip, xFlip ); cursor.get().setReal( distance( xSrc, xSrcFlip, res ) ); } } public static double distance( double[] x, double[] y, double[] res ) { double squaredDist = 0.0; for( int i = 0; i < x.length; i++ ) { squaredDist += res[ i ] * ( x[ i ] - y[ i ] ) * ( x[ i ] - y[ i ] ); } return Math.sqrt( squaredDist ); } public static void main( String[] args ) throws IOException, FormatException, ImgLibException { String outDistImg = args[ 0 ]; String templateF = args[ 1 ]; String templateFlipF = args[ 2 ]; String templateFlipAdjustF = args[ 3 ]; String affineF = args[ 4 ]; String warpF = args[ 5 ]; String unflipToCanF = args[ 6 ]; String affineFlipF = args[ 7 ]; String warpFlipF = args[ 8 ]; String fliptoCanF = args[ 9 ]; String templateSymDefF = "/nrs/saalfeld/john/projects/flyChemStainAtlas/flipComparisons/JFRC2013/symmetry/JFRC2013_222-flip-toOrigWarp.nii"; //FinalInterval destInterval = new FinalInterval( 765, 766, 303 ); // DO THE WORK EstimateLeftRightVariance_JFRC2013 alg = new EstimateLeftRightVariance_JFRC2013(); System.out.println("build unflipped"); System.out.println("preXfm : unflipToCanF: " + unflipToCanF); InvertibleRealTransformSequence totalXfm = alg.buildTransform( unflipToCanF, affineF, warpF ); System.out.println("build flipped"); InvertibleRealTransformSequence totalXfmFlip = alg.buildTransform( fliptoCanF, affineFlipF, warpFlipF ); System.out.println( "totalXfm : " + totalXfm ); System.out.println( "totalXfmFlip: " + totalXfmFlip ); AffineTransform3D templateFlip = AffineHelper.to3D( AffineImglib2IO.readXfm( 3, new File( templateFlipF ) )); AffineTransform3D templateAdjust = ANTSLoadAffine.loadAffine( templateFlipAdjustF ); templateFlip.preConcatenate( templateAdjust.inverse() ); ImagePlus ip = NiftiIo.readNifti( new File( templateSymDefF ) ); Img< FloatType > defLowImg = ImageJFunctions.convertFloat( ip ); ANTSDeformationField templateDf = new ANTSDeformationField( defLowImg, new double[]{ 1, 1, 1 }, ip.getCalibration().getUnit() ); InvertibleRealTransformSequence symmetrizingTransform = new InvertibleRealTransformSequence(); symmetrizingTransform.add( templateFlip ); symmetrizingTransform.add( templateDf ); // String testF = "/groups/saalfeld/saalfeldlab/FROM_TIER2/fly-light/20160107_31_63X_female/data_1/C1/C1_TileConfiguration_lens.registered.tif"; // String testF = "/groups/saalfeld/saalfeldlab/FROM_TIER2/fly-light/20160107_31_63X_female/data_1/B5/B5_TileConfiguration_lens.registered.tif"; // Img< ShortType > testImg = ImageJFunctions.wrap( IJ.openImage( testF )); Img< FloatType > baseImg = ImageJFunctions.convertFloat( IJ.openImage( templateF )); // /** // * Check the image // */ // IntervalView< ShortType > xfmImg = // Views.interval( // Views.raster( // RealViews.transform( // Views.interpolate( Views.extendZero( testImg ), new NLinearInterpolatorFactory< ShortType >() ), // totalXfm )), // baseImg ); // // IntervalView< ShortType > xfmFlipImg = // Views.interval( // Views.raster( // RealViews.transform( // Views.interpolate( Views.extendZero( testImg ), new NLinearInterpolatorFactory< ShortType >() ), // totalXfmFlip )), // baseImg ); // // IntervalView< ShortType > xfmFlipBackImg = // Views.interval( // Views.raster( // RealViews.transform( // Views.interpolate( Views.extendZero( xfmFlipImg ), new NLinearInterpolatorFactory< ShortType >() ), // symmetrizingTransform )), // baseImg ); // // // Bdv bdv = BdvFunctions.show( Views.stack( xfmImg, xfmFlipBackImg ), "xfm img" ); //// Bdv bdv = BdvFunctions.show( Views.stack( xfmImg, xfmFlipImg ), "xfm img" ); // bdv.getBdvHandle().getSetupAssignments().getConverterSetups().get( 0 ).setDisplayRange( 0, 1000 ); /** * Check the template flip */ // IntervalView< FloatType > templateFlipImg = // Views.interval( // Views.raster( // RealViews.transform( // Views.interpolate( Views.extendZero( baseImg ), new NLinearInterpolatorFactory< FloatType >() ), // symmetrizingTransform )), // baseImg ); // // Bdv bdv = BdvFunctions.show( Views.stack( baseImg, templateFlipImg ), "xfm img" ); // bdv.getBdvHandle().getSetupAssignments().getConverterSetups().get( 0 ).setDisplayRange( 0, 150 ); // double[] x = new double[]{ 158.0, 326.0, 159.0 }; // double[] xFlip = new double[ 3 ]; // // templateFlip.applyInverse( xFlip, x ); // // double[] xSrc = new double[ 3 ]; // double[] xSrcFlip = new double[ 3 ]; // totalXfm.applyInverse( xSrc, x); // totalXfmFlip.applyInverse( xSrcFlip, xFlip ); // // System.out.println( "x : " + XfmUtils.printArray( x )); // System.out.println( "x flip : " + XfmUtils.printArray( xFlip )); // System.out.println( "xSrc : " + XfmUtils.printArray( xSrc )); // System.out.println( "xSrcFlip: " + XfmUtils.printArray( xSrcFlip )); System.out.println( "allocating" ); FloatImagePlus< FloatType > distanceImage = ImagePlusImgs.floats( Intervals.dimensionsAsLongArray( baseImg ) ); System.out.println( "computing" ); alg.buildDistanceImage( distanceImage, baseImg, totalXfm, totalXfmFlip, symmetrizingTransform ); System.out.println( "writing" ); IJ.save( distanceImage.getImagePlus(), outDistImg ); System.out.println( "done" ); } }
[ "bogovicj@janelia.hhmi.org" ]
bogovicj@janelia.hhmi.org
8247faf7a60bb8a50a68771ca062de973ea7ff61
8f44efbc229262b5b278015cc3d4288c1fb7e535
/src/main/resources/com/prestafacturaService/mongo/dto/MetodoPago.java
adea0058547c7fecc7207ae105ba254b00a83349
[]
no_license
JorgeP86/prestafactura
6939a766981a40f1d462baa8efd45f259fc1f0b8
b0d36637874377bd7cbfc97af20c8b1701c5d9a6
refs/heads/master
2021-01-22T06:54:51.022735
2014-06-01T20:05:51
2014-06-01T20:05:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
package com.prestafacturaService.mongo.dto; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="metodoPago") public class MetodoPago extends BaseEntity{ /** * */ private static final long serialVersionUID = -4605147685084909199L; private String nombre; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
[ "jorge.pareja86@gmail.com" ]
jorge.pareja86@gmail.com
5c0016085c7e52db8a81e399a28b0de68162b286
a5ee89c7bdb1d6f65873222d24aadcfa6635cebc
/src/main/java/com/family/algorithem2012/thread2/Station.java
2bcb61903476cdb2f1d07ed0832fa54a8cb3c4fd
[]
no_license
galen17/example1200
02d3de46398e6c8b440cccf99aface090bc10292
3789164e2706533b8c678192144d17a332adef02
refs/heads/master
2022-12-21T06:02:43.670598
2021-11-23T15:01:44
2021-11-23T15:01:44
156,043,135
2
0
null
2022-12-10T04:11:00
2018-11-04T02:43:49
Java
UTF-8
Java
false
false
592
java
package com.family.algorithem2012.thread2; public class Station extends Thread { public Station(String name) { super(name); } static int tick = 20; @Override public void run() { while (tick > 0) { if (tick >0) { System.out.println(getName() + "卖出了第" + tick + "张票"); tick --; } else { System.out.println("票卖完了!"); } } try { sleep(1000); } catch (Exception e) { e.printStackTrace(); } } }
[ "daguozb@163.com" ]
daguozb@163.com
db2a9aed464973934e2f4420f7b58ff0e3d1ae6b
c70b282e06e173935608b9bed4fb0d202b1e0865
/src/Interfaces/GestionarCompras.java
2b50609f32a297f5487f36b80306b8c8da3c6f8b
[]
no_license
ariellugo92/ProyectoProgramacionPrincipal
8ccac4ac20a89b3594c6a4e6059170a5f7a13fdc
49e8d79c67d42c3757081da0c638eb17c8771d8b
refs/heads/master
2021-03-12T23:59:35.227076
2015-04-18T23:47:15
2015-04-18T23:47:15
31,480,860
0
0
null
null
null
null
UTF-8
Java
false
false
27,850
java
package Interfaces; import Archivos.ArchivoCategoriaProd; import Archivos.ArchivoCompras; import Archivos.ArchivoEmpleados; import Archivos.ArchivoProductos; import Archivos.ArchivoProveedores; import Pojos.CategoriaProd; import Pojos.Compras; import Pojos.Empleados; import Pojos.Productos; import Pojos.Proveedores; import java.awt.event.ItemEvent; import java.io.IOException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author IaraDenisse */ public class GestionarCompras extends javax.swing.JDialog { DefaultTableModel modelo; public void tabla() { String encabezados[] = {"id", "Factura", "Producto", "Proveedor", "Empleado", "Fecha", "Cantidad", "Precio", "Total", "Tipo"}; String datos[][] = {}; modelo = new DefaultTableModel(datos, encabezados); TablaCompras.setModel(modelo); } private void limpiarTabla() { for (int i = 0; i < TablaCompras.getRowCount(); i++) { modelo.removeRow(i); i -= 1; } } public void cargarCategorias(JComboBox jcombo) { try { ArchivoCategoriaProd cpdao = new ArchivoCategoriaProd(); List<CategoriaProd> catgProd = cpdao.encontrar(); for (CategoriaProd cp : catgProd) { jcombo.addItem(cp.getNombre().trim()); } } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } } public String[] getCategorias(String categoria) { String[] pro = null; try { ArchivoProductos pdao = new ArchivoProductos(); List<Productos> prod = pdao.encontrar(); pro = new String[prod.size()]; int j = 0; for (Productos p : prod) { String catg = p.getCategoriaProd().getNombre().trim(); if (categoria.equals(catg)) { String products = p.getNombre().trim(); pro[j] = products; j++; } } } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } return pro; } public void cargarEmp(JComboBox jcombo) { try { ArchivoEmpleados edao = new ArchivoEmpleados(); List<Empleados> emp = edao.encontrar(); for (Empleados e : emp) { if (e.getDepartamentos().getNombre().trim().equals("compras")) { jcombo.addItem(e.getNombre().trim()); } } } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } } public GestionarCompras(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.comboProductos.setEnabled(false); cargarCategorias(comboCategoriasProd); cargarEmp(comboEmpleados); tabla(); try { ArchivoCompras cdao = new ArchivoCompras(); List<Compras> comp = cdao.encontrar(); agregarTabla(comp); } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } } public void agregarCompras() { try { ArchivoCompras cdao = new ArchivoCompras(); ArchivoProductos pdao = new ArchivoProductos(); ArchivoEmpleados edao = new ArchivoEmpleados(); List<Compras> compras = cdao.encontrar(); Compras c = new Compras(); c.setId(compras.size() + 1); Productos p = pdao.buscarNombre(this.comboProductos.getSelectedItem().toString().trim()); if (comboCategoriasProd.getSelectedIndex() == 0) { JOptionPane.showMessageDialog(this, "Por favor seleccione un producto", "Aviso", JOptionPane.INFORMATION_MESSAGE); return; } c.setProductos(p); List<Productos> prod = pdao.encontrar(); for (Productos pp : prod) { String produts = pp.getNombre().trim(); if (this.comboProductos.getSelectedItem().toString().trim().equals(produts)) { c.setProveedores(pp.getProveedores().getRazon_social().trim()); } } Empleados e = edao.buscarNombre(this.comboEmpleados.getSelectedItem().toString()); if (this.comboEmpleados.getSelectedIndex() == 0) { JOptionPane.showMessageDialog(this, "Elija un empleado"); return; } c.setEmpleados(e); //---------------------------------------------------------- if (this.calendarFecha.getDate() == null) { JOptionPane.showMessageDialog(this, "Seleccione una fecha", "Error", JOptionPane.ERROR_MESSAGE); return; } Date fecha = this.calendarFecha.getDate(); DateFormat df = DateFormat.getDateInstance(); String fechaCompra = df.format(fecha); //----------------------------------------------------------- c.setFechaCompra(fechaCompra); txtCantidad.getValue(); c.setCantidadCompra((double) txtCantidad.getValue()); c.setPrecioCompra(Double.parseDouble(txtPrecio.getText())); if (radioCredito.isSelected()) { c.setTipoCompra(radioCredito.getLabel()); }else if (radioContado.isSelected()) { c.setTipoCompra(radioContado.getLabel()); } c.setFactura(txtFactura.getText()); double total = c.getCantidadCompra() * c.getPrecioCompra(); c.setTotalCompra(total); cdao.guardar(c); cdao.cerrar(); JOptionPane.showMessageDialog(this, "La compra se registro correctamente", "Aviso", JOptionPane.INFORMATION_MESSAGE); List<Compras> cargar = new ArrayList<>(); cargar.add(c); agregarTabla(cargar); List<Productos> prods = pdao.encontrar(); for (Productos pr : prods) { String products = pr.getNombre().trim(); if (c.getProductos().getNombre().trim().equals(products)) { pr.setId(pr.getId()); pr.setNombre(pr.getNombre()); pr.setCategoriaProd(pr.getCategoriaProd()); pr.setProveedores(pr.getProveedores()); pr.setMarca(pr.getMarca()); pr.setPrecio(c.getPrecioCompra()); double cantidad = pr.getCantidad() + c.getCantidadCompra(); pr.setCantidad(cantidad); pr.setUnidadMedida(pr.getUnidadMedida()); pdao.modificar(pr); } } pdao.cerrar(); } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } } public void agregarTabla(List<Compras> comp){ for (Compras c : comp) { int id = c.getId(); String prod = c.getProductos().getNombre().trim(); String prov = c.getProveedores().trim(); String emp = c.getEmpleados().getNombre().trim(); String fecha = c.getFechaCompra(); double cant = c.getCantidadCompra(); double precio = c.getPrecioCompra(); String tipo = c.getTipoCompra(); String fact = c.getFactura(); double total = c.getTotalCompra(); Object datos [] = {id, fact, prod, prov, emp, fecha, cant, precio, total, tipo}; modelo.addRow(datos); } } public void limpiarAgrega(){ comboCategoriasProd.setSelectedIndex(0); comboProductos.setEnabled(false); txtCantidad.setValue(1); txtPrecio.setText(""); RadioTIpoDeCompra.clearSelection(); txtProveedor.setText(""); txtRuc.setText(""); txtFactura.setText(""); comboEmpleados.setSelectedIndex(0); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { RadioTIpoDeCompra = new javax.swing.ButtonGroup(); jcMousePanel1 = new jcMousePanel.jcMousePanel(); jPanel1 = new javax.swing.JPanel(); btnLimprar = new org.edisoncor.gui.button.ButtonTask(); jPanel5 = new javax.swing.JPanel(); comboCategoriasProd = new javax.swing.JComboBox(); comboProductos = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); labelUnidad = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); txtPrecio = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); radioCredito = new javax.swing.JRadioButton(); radioContado = new javax.swing.JRadioButton(); calendarFecha = new com.toedter.calendar.JDateChooser(); jLabel7 = new javax.swing.JLabel(); txtCantidad = new javax.swing.JSpinner(); btnAgregar = new org.edisoncor.gui.button.ButtonTask(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtFactura = new javax.swing.JTextField(); txtRuc = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); comboEmpleados = new javax.swing.JComboBox(); btnNuevoProveedor = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); txtProveedor = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); TablaCompras = new org.jdesktop.swingx.JXTable(); botonRegresarProducto = new org.edisoncor.gui.button.ButtonTask(); botonExportar_a_ExcelProduct = new org.edisoncor.gui.button.ButtonTask(); botonReporteProductos = new org.edisoncor.gui.button.ButtonTask(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Gestionar compras"); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jcMousePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Fondos/fondoPrincipal.jpeg"))); // NOI18N jcMousePanel1.setVisibleLogo(false); jcMousePanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnLimprar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Iconos/limpiarBoton.png"))); // NOI18N btnLimprar.setText("Limpiar"); btnLimprar.setDescription("Ventana"); btnLimprar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimprarActionPerformed(evt); } }); jPanel1.add(btnLimprar, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 260, 176, -1)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Agregue los datos de la compra")); jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); comboCategoriasProd.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--- Categoria del producto ---" })); comboCategoriasProd.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { comboCategoriasProdItemStateChanged(evt); } }); jPanel5.add(comboCategoriasProd, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 180, 25)); comboProductos.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione el producto" })); comboProductos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { comboProductosMouseClicked(evt); } }); jPanel5.add(comboProductos, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 30, 180, 25)); jLabel6.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel6.setText("Fecha de compra"); jPanel5.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, 100, 25)); jPanel5.add(labelUnidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 120, 65, 25)); jLabel8.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel8.setText("Precio C$"); jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 150, 100, 25)); jPanel5.add(txtPrecio, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 150, 75, 25)); jLabel10.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel10.setText("Tipo de compra"); jPanel5.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 200, 100, 25)); RadioTIpoDeCompra.add(radioCredito); radioCredito.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N radioCredito.setText("Credito"); jPanel5.add(radioCredito, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 200, 75, 25)); RadioTIpoDeCompra.add(radioContado); radioContado.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N radioContado.setText("Contado"); jPanel5.add(radioContado, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 200, 75, 25)); jPanel5.add(calendarFecha, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 90, 140, 25)); jLabel7.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel7.setText("Cantidad"); jPanel5.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 120, 100, 25)); txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(1.0d), Double.valueOf(1.0d), null, Double.valueOf(1.0d))); jPanel5.add(txtCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 120, 90, 25)); jPanel1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 420, 240)); btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Iconos/agregar compra.png"))); // NOI18N btnAgregar.setText("Agregar"); btnAgregar.setDescription("a la factura"); btnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAgregarActionPerformed(evt); } }); jPanel1.add(btnAgregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 260, 176, -1)); jcMousePanel1.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 12, 450, 330)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del proveedor")); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel1.setText("Factura"); jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 120, 100, 25)); jLabel2.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel2.setText("Numero Ruc"); jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, 100, 25)); jPanel2.add(txtFactura, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, 150, 25)); txtRuc.setEditable(false); jPanel2.add(txtRuc, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 80, 150, 25)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Empleado que realizo la compra")); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); comboEmpleados.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione al empleado" })); jPanel4.add(comboEmpleados, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 30, 220, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 310, 80)); btnNuevoProveedor.setText("Si el producto es nuevo, presione aqui"); btnNuevoProveedor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNuevoProveedorActionPerformed(evt); } }); jPanel2.add(btnNuevoProveedor, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, 290, -1)); jLabel3.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel3.setText("Proveedor"); jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 40, 100, 25)); txtProveedor.setEditable(false); jPanel2.add(txtProveedor, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 40, 150, 25)); jcMousePanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(473, 12, 330, 330)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de la compra")); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jScrollPane1.setViewportView(TablaCompras); jPanel3.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 770, 190)); jcMousePanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 348, 791, 230)); botonRegresarProducto.setForeground(new java.awt.Color(255, 255, 255)); botonRegresarProducto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Iconos/regresar.png"))); // NOI18N botonRegresarProducto.setText("Regresar"); botonRegresarProducto.setDescription(" "); botonRegresarProducto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonRegresarProductoActionPerformed(evt); } }); jcMousePanel1.add(botonRegresarProducto, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 590, 200, -1)); botonExportar_a_ExcelProduct.setForeground(new java.awt.Color(255, 255, 255)); botonExportar_a_ExcelProduct.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Iconos/excel.png"))); // NOI18N botonExportar_a_ExcelProduct.setText("Exportar"); botonExportar_a_ExcelProduct.setDescription("a Miscrosoft Excel"); jcMousePanel1.add(botonExportar_a_ExcelProduct, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 590, 200, -1)); botonReporteProductos.setForeground(new java.awt.Color(255, 255, 255)); botonReporteProductos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Iconos/reportes.png"))); // NOI18N botonReporteProductos.setText("Reporte"); botonReporteProductos.setDescription("de productos"); jcMousePanel1.add(botonReporteProductos, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 590, 200, -1)); getContentPane().add(jcMousePanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 820, 690)); setSize(new java.awt.Dimension(835, 697)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void comboCategoriasProdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboCategoriasProdItemStateChanged if (evt.getStateChange() == ItemEvent.SELECTED) { this.comboProductos.setEnabled(true); if (this.comboCategoriasProd.getSelectedIndex() > 0) { this.comboProductos.setModel(new DefaultComboBoxModel(getCategorias(this.comboCategoriasProd.getSelectedItem().toString()))); } } }//GEN-LAST:event_comboCategoriasProdItemStateChanged private void comboProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_comboProductosMouseClicked try { ArchivoProductos pdao = new ArchivoProductos(); List<Productos> prod = pdao.encontrar(); String product = this.comboProductos.getSelectedItem().toString(); for (Productos p : prod) { String prodt = p.getNombre().trim(); if (product.equals(prodt)) { if (p.getUnidadMedida().equals("unidad")) { this.labelUnidad.setText(p.getUnidadMedida().trim() + "es"); } else if (p.getUnidadMedida().equals("libras")) { this.labelUnidad.setText(p.getUnidadMedida().trim()); } txtProveedor.setText(p.getProveedores().getRazon_social().trim()); txtRuc.setText(p.getProveedores().getRuc().trim()); } } } catch (IOException ex) { Logger.getLogger(GestionarCompras.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_comboProductosMouseClicked private void botonRegresarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonRegresarProductoActionPerformed this.dispose(); }//GEN-LAST:event_botonRegresarProductoActionPerformed private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed if (txtPrecio.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Por favor ingrese el precio del producto", "Aviso", JOptionPane.INFORMATION_MESSAGE); return; } if (!radioCredito.isSelected() && !radioContado.isSelected()) { JOptionPane.showMessageDialog(this, "Por favor seleccione el tipo de la compra", "Aviso", JOptionPane.INFORMATION_MESSAGE); return; } if (txtFactura.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Por favor ingrese el numero de factura que le proporciono su proveedor", "Aviso", JOptionPane.INFORMATION_MESSAGE); return; } agregarCompras(); }//GEN-LAST:event_btnAgregarActionPerformed private void btnLimprarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimprarActionPerformed limpiarAgrega(); }//GEN-LAST:event_btnLimprarActionPerformed private void btnNuevoProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoProveedorActionPerformed OpcionesDeProductos dialog = new OpcionesDeProductos(new javax.swing.JFrame(), true); dialog.setVisible(true); }//GEN-LAST:event_btnNuevoProveedorActionPerformed /** * @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(GestionarCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GestionarCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GestionarCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GestionarCompras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { GestionarCompras dialog = new GestionarCompras(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup RadioTIpoDeCompra; private org.jdesktop.swingx.JXTable TablaCompras; private org.edisoncor.gui.button.ButtonTask botonExportar_a_ExcelProduct; private org.edisoncor.gui.button.ButtonTask botonRegresarProducto; private org.edisoncor.gui.button.ButtonTask botonReporteProductos; private org.edisoncor.gui.button.ButtonTask btnAgregar; private org.edisoncor.gui.button.ButtonTask btnLimprar; private javax.swing.JButton btnNuevoProveedor; private com.toedter.calendar.JDateChooser calendarFecha; private javax.swing.JComboBox comboCategoriasProd; private javax.swing.JComboBox comboEmpleados; private javax.swing.JComboBox comboProductos; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private jcMousePanel.jcMousePanel jcMousePanel1; private javax.swing.JLabel labelUnidad; private javax.swing.JRadioButton radioContado; private javax.swing.JRadioButton radioCredito; private javax.swing.JSpinner txtCantidad; private javax.swing.JTextField txtFactura; private javax.swing.JTextField txtPrecio; private javax.swing.JTextField txtProveedor; private javax.swing.JTextField txtRuc; // End of variables declaration//GEN-END:variables }
[ "ariellugo92@gmail.com" ]
ariellugo92@gmail.com
6e85701dbbbadf8c1bfca22481dea8af6521f620
52af9468ca367aa65b5f7fb74d6dd61df021ad0d
/src/marsrover/enums/DirectionEnum.java
472a47621aa0707d8fdd528c2586c5b6d9254234
[]
no_license
zeynepcoskun/marsrover
28ee075b36fbdb0ec93ebe6bea24f7357654e856
223d8d643f835326709b27ee5a58a1cfacf22883
refs/heads/master
2023-06-04T21:29:21.955862
2021-06-20T21:13:46
2021-06-20T21:13:46
378,732,502
0
0
null
null
null
null
UTF-8
Java
false
false
1,000
java
package marsrover.enums; public enum DirectionEnum { NORTH("North", "N", true), EAST("East", "E", true), WEST("West", "W", true), SOUTH("South", "S", true); private final String direction; private final String directionLetter; private final boolean active; private DirectionEnum(String direction, String directionLetter, boolean active) { this.direction = direction; this.directionLetter = directionLetter; this.active = active; } public static DirectionEnum getNORTH() { return NORTH; } public static DirectionEnum getEAST() { return EAST; } public static DirectionEnum getWEST() { return WEST; } public static DirectionEnum getSOUTH() { return SOUTH; } public String getDirection() { return direction; } public String getDirectionLetter() { return directionLetter; } public boolean isActive() { return active; } }
[ "apple@apples-MacBook-Pro.local" ]
apple@apples-MacBook-Pro.local
255b6778e65e11434e5be8ff4f145cad564ba29d
6771110f7b5cde97812a4e1a856c2a4052d82669
/src/main/java/jp/co/cos_mos/mdm/v1/dao/mapper/OwnerMapper.java
f0f6932c47e7e9252bc6c42005c0abff6d641290
[]
no_license
C-MDM/c-mdm-v1
82bc814ecd25b6570ed8ba1b2b2244ce12d7c6da
8d99b878c9b96c2903e3e46ff060ff1630f83c2c
refs/heads/master
2020-04-29T03:08:02.352928
2015-02-01T12:53:21
2015-02-01T12:53:21
27,480,256
0
0
null
null
null
null
UTF-8
Java
false
false
363
java
package jp.co.cos_mos.mdm.v1.dao.mapper; import java.util.List; import jp.co.cos_mos.mdm.v1.dao.entity.Owner; public interface OwnerMapper { public Owner select(Long id); public int insert(Owner owner); public int update(Owner owner); public int delete(Owner owner); public List<Owner> selectAll(); public int inactive(Owner owner); }
[ "HisashiYoshida@IP-C0A860DE.corp.amazonworkspaces.com" ]
HisashiYoshida@IP-C0A860DE.corp.amazonworkspaces.com
47589b34153b3c75ae7313aa6c82c9dcc93ccdf5
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/97/501.java
06631370e53fb9fad9be1908a93d60524c3adaa4
[ "MIT" ]
permissive
qiuchili/ggnn_graph_classification
c2090fefe11f8bf650e734442eb96996a54dc112
291ff02404555511b94a4f477c6974ebd62dcf44
refs/heads/master
2021-10-18T14:54:26.154367
2018-10-21T23:34:14
2018-10-21T23:34:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
604
java
package <missing>; public class GlobalMembers { public static int Main() { int n; int m; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { n = Integer.parseInt(tempVar); } m = n / 100; System.out.printf("%d\n",m); m = (n % 100) / 50; System.out.printf("%d\n",m); m = ((n % 100) % 50) / 20; System.out.printf("%d\n",m); m = (((n % 100) % 50) % 20) / 10; System.out.printf("%d\n",m); m = ((((n % 100) % 50) % 20) % 10) / 5; System.out.printf("%d\n",m); m = (((((n % 100) % 50) % 20) % 10) % 5) / 1; System.out.printf("%d\n",m); return 0; } }
[ "y.yu@open.ac.uk" ]
y.yu@open.ac.uk
540647e7b7e97c524b7b09ed8a2f6c3747e5f3cf
8a8a4e240f0a89af3b84161a2c8a0d15f20b3449
/src/main/java/com/mashup/ootd/domain/post/dto/PostCreateRequest.java
1602e2ea8603fff974e54ef41ede843070d9ab65
[]
no_license
mash-up-kr/FCS-backend
99d1996965793574ca6e6a9a5942f4c2c8fc29b8
763af8752013430e2f367e243552105aa0c9b23a
refs/heads/master
2022-12-29T16:28:09.434362
2020-10-12T14:20:11
2020-10-12T14:20:11
280,346,792
0
3
null
null
null
null
UTF-8
Java
false
false
936
java
package com.mashup.ootd.domain.post.dto; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.multipart.MultipartFile; import com.mashup.ootd.domain.post.entity.Post; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class PostCreateRequest { private MultipartFile uploadFile; private String message; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate date; private String address; private String weather; private Integer temperature; // TODO 추후 임시 디폴트 값 제거 private List<Long> styleIds = Arrays.asList(1L, 5L); public Post toEntity(String url) { return Post.builder() .photoUrl(url) .message(message) .date(date) .address(address) .weather(weather) .temperature(temperature) .build(); } }
[ "ehdgus2398@gmail.com" ]
ehdgus2398@gmail.com
47b74bbfd40a7813ee8357a3f86e03bbb564e76a
2ecfca74b3757ee574a29896ae4242d005b50dd3
/scarabei-red/src/com/jfixby/scarabei/red/db/simple/SimpleDBConfig.java
8390dbb12249dc880d1e52ea80ab21604877238b
[]
no_license
ekoi/Scarabei
edc6bceeba9612be8b19d951efcd17900f0901f1
300be6a937fc81e5c0496f33d9a6c2259ce13f04
refs/heads/master
2021-06-24T07:44:26.728005
2017-09-10T09:42:39
2017-09-10T09:42:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package com.jfixby.scarabei.red.db.simple; import com.jfixby.scarabei.api.file.File; import com.jfixby.scarabei.api.names.ID; public class SimpleDBConfig { public ID dbName; public File storageFolder; public boolean readFromStorage; }
[ "github@jfixby.com" ]
github@jfixby.com
939348230bd399d1bbd570c8cff581fd104a1b81
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/neo4j--neo4j/033f6326bddfef6431b1bf4dad0770aea24f5325/before/BatchOperationService.java
040f64fa8567b3f0bceb3ddcf4925997cf16ff95
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
7,419
java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server.rest.web; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URI; import java.util.Map; import javax.servlet.ServletException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.codehaus.jackson.map.ObjectMapper; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.AbstractGraphDatabase; import org.neo4j.server.database.Database; import org.neo4j.server.rest.domain.BatchOperationFailedException; import org.neo4j.server.rest.repr.BadInputException; import org.neo4j.server.rest.repr.BatchOperationResults; import org.neo4j.server.rest.repr.InputFormat; import org.neo4j.server.rest.repr.OutputFormat; import org.neo4j.server.web.WebServer; @Path( "/batch" ) public class BatchOperationService { private static final String ID_KEY = "id"; private static final String METHOD_KEY = "method"; private static final String BODY_KEY = "body"; private static final String TO_KEY = "to"; private static final JsonFactory jsonFactory = new JsonFactory(); private final OutputFormat output; private final WebServer webServer; private final Database database; public BatchOperationService( @Context Database database, @Context WebServer webServer, @Context InputFormat input, @Context OutputFormat output ) { this.output = output; this.webServer = webServer; this.database = database; } @POST public Response performBatchOperations( @Context UriInfo uriInfo, InputStream body ) throws BadInputException { AbstractGraphDatabase db = database.graph; Transaction tx = db.beginTx(); try { JsonParser jp = jsonFactory.createJsonParser(body); ObjectMapper mapper = new ObjectMapper(); BatchOperationResults results = new BatchOperationResults(); JsonToken token; String field; String jobMethod, jobPath, jobBody; Integer jobId; // TODO: Perhaps introduce a simple DSL for // deserializing streamed JSON? while( (token = jp.nextToken()) != null) { if(token == JsonToken.START_OBJECT) { jobMethod = jobPath = jobBody = ""; jobId = null; while( (token = jp.nextToken()) != JsonToken.END_OBJECT && token != null) { field = jp.getText(); token = jp.nextToken(); if(field.equals(METHOD_KEY)) { jobMethod = jp.getText().toUpperCase(); } else if(field.equals(TO_KEY)) { jobPath = jp.getText(); } else if(field.equals(ID_KEY)) { jobId = jp.getIntValue(); } else if(field.equals(BODY_KEY)) { JsonNode node = mapper.readTree(jp); StringWriter out = new StringWriter(); JsonGenerator gen = jsonFactory.createJsonGenerator(out); mapper.writeTree(gen, node); gen.flush(); gen.close(); jobBody = out.toString(); } } // Read one job description. Execute it. performJob(results, uriInfo, jobMethod, jobPath, jobBody, jobId); } } Response res = Response.ok() .entity( results.toJSON() ) .header( HttpHeaders.CONTENT_ENCODING, "UTF-8" ) .type( MediaType.APPLICATION_JSON ) .build(); tx.success(); return res; } catch ( Exception e ) { tx.failure(); return output.serverError( e ); } finally { tx.finish(); } } private void performJob( BatchOperationResults results, UriInfo uriInfo, String method, String path, String body, Integer id ) throws IOException, ServletException { InternalJettyServletRequest req = new InternalJettyServletRequest(); InternalJettyServletResponse res = new InternalJettyServletResponse(); // Replace {[ID]} placeholders with location values Map<Integer, String> locations = results.getLocations(); path = replaceLocationPlaceholders( path, locations ); body = replaceLocationPlaceholders( body, locations ); URI targetUri = calculateTargetUri( uriInfo, path ); req.setup( method, targetUri.toString(), body ); res.setup(); webServer.invokeDirectly( targetUri.getPath(), req, res ); if ( is2XXStatusCode( res.getStatus() ) ) { results.addOperationResult( path, id, res.getOutputStream() .toString(), res.getHeader( "Location" ) ); } else { throw new BatchOperationFailedException( res.getStatus(), res.getOutputStream() .toString() ); } } private URI calculateTargetUri( UriInfo serverUriInfo, String requestedPath ) { URI baseUri = serverUriInfo.getBaseUri(); if ( requestedPath.startsWith( baseUri.toString() ) ) { requestedPath = requestedPath.substring( baseUri.toString() .length() ); } if ( !requestedPath.startsWith( "/" ) ) { requestedPath = "/" + requestedPath; } return baseUri.resolve( "." + requestedPath ); } private String replaceLocationPlaceholders( String str, Map<Integer, String> locations ) { // TODO: Potential memory-hog on big requests, write smarter // implementation. for ( Integer jobId : locations.keySet() ) { str = str.replace( "{" + jobId + "}", locations.get( jobId ) ); } return str; } private boolean is2XXStatusCode( int statusCode ) { return statusCode >= 200 && statusCode < 300; } }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
edfd39bd38434641e7552f3ca3a5c914e698acee
63d74e2c7ec887ec000347b2d93b84f3fec49dca
/KmerPosition.java
4cb866efdb7c30fdf292db2c4546a2647f5c6120
[]
no_license
jtfield/java_projects
d13bd6be4a5fb10f888c49d6f13f750ec57d776a
e39902cd02dfe677e6d219ed16704f1258030dc8
refs/heads/master
2022-11-24T05:16:41.320123
2020-07-29T22:29:14
2020-07-29T22:29:14
260,313,577
0
0
null
null
null
null
UTF-8
Java
false
false
7,533
java
package template; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import fileIO.ByteStreamWriter; import fileIO.FileFormat; import fileIO.ReadWrite; import shared.Parser; import shared.PreParser; import shared.Shared; import shared.Timer; import shared.Tools; import stream.ConcurrentReadInputStream; import stream.ConcurrentReadOutputStream; import stream.Read; import structures.ListNum; import structures.LongList; /** * Read in file of high-throughput reads and report the positions at which kmers from reference start * @author Jasper Toscani Field * @date Jun 4, 2020 * */ public class KmerPosition { public static void main(String[] args){ //Start a timer immediately upon code entrance. Timer t=new Timer(); //Create an instance of this class KmerPosition x=new KmerPosition(args); //Run the object x.process(t); //Close the print stream if it was redirected Shared.closeStream(x.outstream); } public KmerPosition(String[] args){ {//Preparse block for help, config files, and outstream PreParser pp=new PreParser(args, getClass(), false); args=pp.args; outstream=pp.outstream; } Parser parser=new Parser(); for(int i=0; i<args.length; i++){ String arg=args[i]; String[] split=arg.split("="); String a=split[0].toLowerCase(); String b=split.length>1 ? split[1] : null; if(b!=null && b.equalsIgnoreCase("null")){b=null;} if(a.equals("parse_flag_goes_here")){ //Set a variable here }else if(a.equals("ref")){ ref=b; }else if(a.equals("k")){ k=Integer.parseInt(b); }else if(parser.parse(arg, a, b)){ //do nothing }else{ // throw new RuntimeException("Unknown parameter "+args[i]); assert(false) : "Unknown parameter "+args[i]; outstream.println("Unknown parameter "+args[i]); } } {//Process parser fields Parser.processQuality(); maxReads=parser.maxReads; in1=parser.in1; in2=parser.in2; out1=parser.out1; } ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, true, false, false); ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true); ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, null, true, true); ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true); } void process(Timer t){ HashSet<String> kr=kmerReturn(); final ConcurrentReadInputStream cris; { cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2); cris.start(); } boolean paired=cris.paired(); //System.out.println(paired); long readsProcessed=0, basesProcessed=0; { ListNum<Read> ln=cris.nextList(); ArrayList<Read> reads=(ln!=null ? ln.list : null); if(reads!=null && !reads.isEmpty()){ Read r=reads.get(0); assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired()); } while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} for(int idx=0; idx<reads.size(); idx++){ final Read r1=reads.get(idx); final Read r2=r1.mate; readsProcessed+=r1.pairCount(); basesProcessed+=r1.pairLength(); // ********* Process reads here ********* //System.out.println(r1); processRead(r1, kr, counts1, totalEncounter1); if(r1.mate!=null) { processRead(r2, kr, counts2, totalEncounter2); } } cris.returnList(ln); if(verbose){outstream.println("Returned a list.");} ln=cris.nextList(); reads=(ln!=null ? ln.list : null); } if(ln!=null){ cris.returnList(ln.id, ln.list==null || ln.list.isEmpty()); } } errorState=ReadWrite.closeStreams(cris) | errorState; if(verbose){outstream.println("Finished reading data.");} //System.out.println(counts); outputResults(counts1, totalEncounter1, counts2, totalEncounter2); t.stop(); outstream.println("Time: \t"+t); outstream.println("Reads Processed: "+readsProcessed+" \t"+String.format(Locale.ROOT, "%.2fk reads/sec", (readsProcessed/(double)(t.elapsed))*1000000)); assert(!errorState) : "An error was encountered."; } private void outputResults(LongList posCounts1, LongList readCounts1, LongList posCounts2, LongList readCounts2){ if(ffout1==null) {return;} ByteStreamWriter bsw=new ByteStreamWriter(ffout1); bsw.start(); long[] readArray1 = readCounts1.toArray(); long[] countArray1 = posCounts1.toArray(); long[] readArray2 = readCounts2.toArray(); long[] countArray2 = posCounts2.toArray(); bsw.println("#pos" + "\t" + "read1_count" + "\t" + "read1_perc" + "\t" + "read2_count" + "\t" + "read2_perc"); int maxLen = Tools.max(readArray1.length, readArray2.length); for(int i=0; i<maxLen; i++) { bsw.print(i); bsw.print('\t'); bsw.print(countArray1.length>i ? countArray1[i] : 0); bsw.print('\t'); bsw.print(countArray1.length>i ? (countArray1[i] / (float) readArray1[i]) * 100 : 0, 3); bsw.print('\t'); bsw.print(countArray2.length>i ? countArray2[i] : 0); bsw.print('\t'); bsw.print(countArray2.length>i ? (countArray2[i] / (float) readArray2[i]) * 100 : 0, 3); bsw.println(); } //Write stuff to the bsw //bsw.println("Stuff"); errorState=bsw.poisonAndWait() | errorState; } private HashSet<String> kmerReturn(){ HashSet<String> hs=new HashSet<String>(); ArrayList<Read> readArray=ConcurrentReadInputStream.getReads(maxReads, false, ffref, null, null, null); for(Read r : readArray) { addToSet(hs, r); } //System.out.println(hs); return hs; } private int addToSet(HashSet<String> hs, Read r) { int countRead=0; for(int i=0, j=k; j<=r.length(); i++, j++) { //String(byte[] bytes, int offset, int length) String s=new String(r.bases, i, k); hs.add(s); countRead++; } return countRead; } private LongList processRead(Read r, HashSet<String> hs, LongList count, LongList readCount) { for(int i=0, j=k; j<=r.length(); i++, j++) { //String(byte[] bytes, int offset, int length) String s=new String(r.bases, i, k); readCount.increment(i); if(hs.contains(s)) { count.increment(i); } //System.out.println(totalEncounter); //System.out.println(counts); } return count; } /*--------------------------------------------------------------*/ /*--------------------------------------------------------------*/ private String in1=null; private String in2=null; private String out1=null; private String ref=null; private final FileFormat ffin1; private final FileFormat ffin2; private final FileFormat ffout1; private final FileFormat ffref; /*--------------------------------------------------------------*/ private long maxReads=-1; private boolean errorState=false; private int k=6; private LongList counts1=new LongList(); private LongList totalEncounter1=new LongList(); private LongList counts2=new LongList(); private LongList totalEncounter2=new LongList(); /*--------------------------------------------------------------*/ private java.io.PrintStream outstream=System.err; public static boolean verbose=false; }
[ "jtoscanifield@ucmerced.edu" ]
jtoscanifield@ucmerced.edu
a7b1f043fac85df2477a32df43fc241a26bd5ae9
5dd224a7655f59cc8a1d033636225ad614026ac7
/backendJaxRSProject/src/main/java/com/andersen/backendjaxrsproject/Employee.java
b4b41a459fffa2b96e2accce1daa0f06caff5165
[]
no_license
elandersen/JavaProjects
ce73b6d4532a2deae386c3552dde4266a338c674
f7f7181dbf87608e2f01147386d2c5d84d674834
refs/heads/master
2021-04-29T11:09:36.574920
2017-01-02T18:56:54
2017-01-02T18:56:54
77,855,022
0
0
null
null
null
null
UTF-8
Java
false
false
3,005
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.andersen.backendjaxrsproject; import javax.xml.bind.annotation.XmlRootElement; import org.bson.types.ObjectId; /** * * @author Esther */ @XmlRootElement public class Employee { private long _id; private String firstName; private String lastName; private String middleName; private String emailAddress; private String phoneNumber; private String positionCategory; private String dateHired; private String address1; private String address2; private String city; private String state; private String zipcode; private Boolean activeFlag; public long getId() { return _id; } public void setId(long _id) { this._id = _id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPositionCategory() { return positionCategory; } public void setPositionCategory(String positionCategory) { this.positionCategory = positionCategory; } public String getDateHired() { return dateHired; } public void setDateHired(String dateHired) { this.dateHired = dateHired; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public Boolean getActiveFlag() { return activeFlag; } public void setActiveFlag(Boolean activeFlag) { this.activeFlag = activeFlag; } }
[ "edeem55@gmail.com" ]
edeem55@gmail.com
007b293635e2b81ec75e7f472c78a9710ae86f50
3f814bf738ced638d15cba063de724b4988c777d
/homework_ch5/src/P50.java
ab491bdf2bddd73906cc9105b4874415af1c4bb8
[]
no_license
QuasarsZ/HW_CH5
fdc5c05f5c1bb68b7d0b291d43ddf621fef466f3
35d1da3f68398673ff1fa9498b646eccd75fd29d
refs/heads/master
2020-04-08T15:56:59.117656
2018-11-28T12:27:44
2018-11-28T12:27:44
null
0
0
null
null
null
null
BIG5
Java
false
false
474
java
public class P50 { public static void main (String[] args) { Car50 car1 = new Car50("1號車"); Thread th1 = new Thread(car1); th1.start(); for(int i=0;i<5;i++) { System.out.println("正在進行main()的處理工作"); } } } class Car50 implements Runnable { private String name; public Car50(String nm) { name =nm; } public void run() { for(int i=0;i<5;i++) { System.out.println("正在進行"+name+"的處理工作"); } } }
[ "zxc70921@gmail.com" ]
zxc70921@gmail.com
5684efc6c6944276c158788a0b516f026d6e8fc8
25a4bbaaf918757910fe86f97c332385c7dfe6d1
/IntelliJ_IDEA_workspace/day02/src/com/zrj/java/VariableTest4.java
b4811fc44b3e7b84991b623157f8aceabec2ad70
[]
no_license
ahanabi/java
cc779d2774457385f41b93603e39d39948b0c267
ac80b25f598c49ddf236754f45ca6c24a6232a1d
refs/heads/master
2023-04-06T05:15:57.464689
2021-04-25T03:11:46
2021-04-25T03:11:46
263,314,661
0
0
null
null
null
null
UTF-8
Java
false
false
554
java
package com.zrj.java; class VariableTest4 { public static void main(String[] args) { //1.编码情况1: long l = 123213; System.out.println(l); //编译失败:过大的整数 //long l1 = 21332423235234123; long l1 = 21332423235234123L; //**************** //编译失败 // float f1 = 12.3f; float f1 = (float)12.3; //2.编码情况2: //整型常量,默认类型为int型 //浮点型常量,默认类型为double型 byte b = 12; //byte b1 = b + 1;//编译失败 //float f1 = b + 12.3;//编译失败 } }
[ "15151853077@163.com" ]
15151853077@163.com
71848fa8e2c114ef435063083510f575c5689c43
8cd79231511b86a37f26f9418f0c468fe5eb488f
/src/main/java/com/github/kodomo/mallysmith/government/database/repository/publicservant/PublicServantRepository.java
bb96dab63ec51142044ad40066f252638a72b8d3
[]
no_license
kodomomo/MALLYSmith-Government
2100a4d8e60e99c321fab2b6923da4bd4614f698
c91eff0810e12a15378b970b3a017dccd31afa42
refs/heads/master
2023-04-03T02:18:18.201512
2021-04-10T18:03:37
2021-04-10T18:03:37
356,574,948
0
1
null
null
null
null
UTF-8
Java
false
false
672
java
package com.github.kodomo.mallysmith.government.database.repository.publicservant; import com.github.kodomo.mallysmith.government.database.orm.MysqlConnector; import com.github.kodomo.mallysmith.government.database.orm.Repository; public class PublicServantRepository { private final Repository repository = MysqlConnector.getInstance().getRepository(); public PublicServant findById(int id) { try { return repository.findOne( String.format("select * from tbl_public_servant where id = %d", id), PublicServant.class ); } catch (Exception ignored) {} return null; } }
[ "leaguelugas@gmail.com" ]
leaguelugas@gmail.com
383b7e8606a0c269499ebec10abadd956c93e331
e1a4acf1d41b152a0f811e82c27ad261315399cc
/examples/java/com/intel/daal/examples/neural_networks/ELULayerDenseBatch.java
58f303e0661e6a5997926588afebdd8a50dd5547
[ "Apache-2.0", "Intel" ]
permissive
ValeryiE/daal
e7572f16e692785db1e17bed23b6ab709db4e705
d326bdc5291612bc9e090d95da65aa579588b81e
refs/heads/master
2020-08-29T11:37:16.157315
2019-10-25T13:11:01
2019-10-25T13:11:01
218,020,419
0
0
Apache-2.0
2019-10-28T10:22:19
2019-10-28T10:22:19
null
UTF-8
Java
false
false
4,103
java
/* file: ELULayerDenseBatch.java */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * 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. *******************************************************************************/ /* // Content: // Java example of ELU layer in the batch processing mode //////////////////////////////////////////////////////////////////////////////// */ package com.intel.daal.examples.neural_networks; import com.intel.daal.algorithms.neural_networks.layers.elu.*; import com.intel.daal.algorithms.neural_networks.layers.ForwardResultId; import com.intel.daal.algorithms.neural_networks.layers.ForwardResultLayerDataId; import com.intel.daal.algorithms.neural_networks.layers.ForwardInputId; import com.intel.daal.algorithms.neural_networks.layers.BackwardResultId; import com.intel.daal.algorithms.neural_networks.layers.BackwardInputId; import com.intel.daal.algorithms.neural_networks.layers.BackwardInputLayerDataId; import com.intel.daal.data_management.data.Tensor; import com.intel.daal.data_management.data.HomogenTensor; import com.intel.daal.examples.utils.Service; import com.intel.daal.services.DaalContext; /** * <a name="DAAL-EXAMPLE-JAVA-ELULAYERBATCH"> * @example ELULayerDenseBatch.java */ class ELULayerDenseBatch { private static final String datasetFileName = "../data/batch/layer.csv"; private static DaalContext context = new DaalContext(); public static void main(String[] args) throws java.io.FileNotFoundException, java.io.IOException { /* Read datasetFileName from a file and create a tensor to store forward input data */ Tensor tensorData = Service.readTensorFromCSV(context, datasetFileName); /* Create an algorithm to compute forward elu layer results using default method */ EluForwardBatch eluLayerForward = new EluForwardBatch(context, Float.class, EluMethod.defaultDense); /* Set input objects for the forward elu layer */ eluLayerForward.input.set(ForwardInputId.data, tensorData); /* Compute forward elu layer results */ EluForwardResult forwardResult = eluLayerForward.compute(); /* Print the results of the forward elu layer */ Service.printTensor("Forward ELU layer result (first 5 rows):", forwardResult.get(ForwardResultId.value), 5, 0); /* Get the size of forward elu layer output */ int nSize = (int)forwardResult.get(ForwardResultId.value).getSize(); long[] dims = forwardResult.get(ForwardResultId.value).getDimensions(); /* Create a tensor with backward input data */ double[] data = new double[nSize]; Tensor tensorDataBack = new HomogenTensor(context, dims, data, 1.0); /* Create an algorithm to compute backward elu layer results using default method */ EluBackwardBatch eluLayerBackward = new EluBackwardBatch(context, Float.class, EluMethod.defaultDense); /* Set input objects for the backward elu layer */ eluLayerBackward.input.set(BackwardInputId.inputGradient, tensorDataBack); eluLayerBackward.input.set(BackwardInputLayerDataId.inputFromForward, forwardResult.get(ForwardResultLayerDataId.resultForBackward)); /* Compute backward elu layer results */ EluBackwardResult backwardResult = eluLayerBackward.compute(); /* Print the results of the backward elu layer */ Service.printTensor("Backward ELU layer result (first 5 rows):", backwardResult.get(BackwardResultId.gradient), 5, 0); context.dispose(); } }
[ "nikolay.a.petrov@intel.com" ]
nikolay.a.petrov@intel.com
0cc76d345625f912ccae30089c653bfcd170f986
0ad89ba96ce7203cd90d54c65f926425b1b661b8
/src/main/java/com/vinylstore/vinyl/service/AccountServiceImpl.java
169b79543a16fc6d79396763e36d8183f16e2a50
[]
no_license
xayde/vinyl
4d6de314f588736f3f2f0308c21e75565acb68fb
a1a5d95f7d431b6feac6e411bca9586573f81410
refs/heads/master
2022-01-30T13:42:03.547512
2019-06-01T14:31:46
2019-06-01T14:31:46
184,765,902
0
0
null
null
null
null
UTF-8
Java
false
false
974
java
package com.vinylstore.vinyl.service; import com.vinylstore.vinyl.dao.AccountDao; import com.vinylstore.vinyl.exception.UniqueEmailException; import com.vinylstore.vinyl.model.Account; import lombok.RequiredArgsConstructor; import org.glassfish.jersey.internal.guava.Lists; import org.springframework.stereotype.Service; import java.util.List; @RequiredArgsConstructor @Service public class AccountServiceImpl implements AccountService { private final AccountDao accountDao; @Override public void createAccount(Account account) { if (findByEmail(account.getEmail().trim()) != null) { throw new UniqueEmailException("Email address already exists."); } accountDao.save(account); } @Override public Account findByEmail(String email) { return accountDao.findByEmail(email); } @Override public List<Account> getAllAccounts() { return Lists.newArrayList(accountDao.findAll()); } }
[ "ldmadalina@gmail.com" ]
ldmadalina@gmail.com
a7ff4209a3aafdec6c3135fee7d145fadbb59b78
fb3fff16f3201379ec6a1f1c00c71770ace669eb
/src/main/java/com/course/practicaljava/service/RandomCarService.java
6917a1021cb6a91bb66c555675be3efa7fc8acdb
[]
no_license
praneethamurthy2012/testgradle
3775a1384e28a31b15984dda329e4a1d427828b4
a240029a6333d8f844ee0bccbc16e053d7aaee55
refs/heads/main
2023-03-19T00:52:23.562997
2021-02-24T09:15:44
2021-02-24T09:15:44
331,517,884
0
0
null
null
null
null
UTF-8
Java
false
false
2,174
java
package com.course.practicaljava.service; import java.util.ArrayList; import java.util.concurrent.ThreadLocalRandom; import org.springframework.stereotype.Service; import com.course.practicaljava.entity.Car; import com.course.practicaljava.entity.Engine; import com.course.practicaljava.entity.Tire; import com.course.practicaljava.util.RandomDateUtil; @Service public class RandomCarService implements CarService { @Override public Car generateCar() { var brand = BRANDS.get(ThreadLocalRandom.current().nextInt(0, BRANDS.size())); var color = COLORS.get(ThreadLocalRandom.current().nextInt(0, COLORS.size())); var type = TYPES.get(ThreadLocalRandom.current().nextInt(0, TYPES.size())); var available = ThreadLocalRandom.current().nextBoolean(); var price = ThreadLocalRandom.current().nextInt(5000, 12001); var firstReleaseDate = RandomDateUtil.generateRandomLocalDate(); int randomCount = ThreadLocalRandom.current().nextInt(ADDITIONAL_FEATURES.size()); var additionalFeatures = new ArrayList<String>(); for (int i = 0; i < randomCount; i++) { additionalFeatures.add(ADDITIONAL_FEATURES.get(i)); } var fuel = FUELS.get(ThreadLocalRandom.current().nextInt(FUELS.size())); var horsePower = ThreadLocalRandom.current().nextInt(100, 221); var engine = new Engine(); engine.setFuelType(fuel); engine.setHorsePower(horsePower); var tires = new ArrayList<Tire>(); for (int i = 0; i < 3; i++) { var tire = new Tire(); var manufacturer = TIRE_MANUFACTURERS.get(ThreadLocalRandom.current().nextInt(TIRE_MANUFACTURERS.size())); var size = ThreadLocalRandom.current().nextInt(15, 18); var tirePrice = ThreadLocalRandom.current().nextInt(200, 401); tire.setManufacturer(manufacturer); tire.setPrice(tirePrice); tire.setSize(size); tires.add(tire); } var secretFeature = ThreadLocalRandom.current().nextBoolean() ? "Can fly" : null; var result = new Car(brand, color, type, available, price, firstReleaseDate); result.setAdditionalFeatures(additionalFeatures); result.setEngine(engine); result.setTires(tires); result.setSecretFeature(secretFeature); return result; } }
[ "sreedharamurthy.n@WIB-LAP-003752.wibmodc.com" ]
sreedharamurthy.n@WIB-LAP-003752.wibmodc.com
a7c38da30fd7e08e239e2fa2ac98834d84717dbb
6e45dd703a2172a643368c171edd3342feca5b81
/ProjetoWeb/src/command/ManterUsuarioEditar.java
116478856cd3525db1fb21d9aa0765a678200184
[]
no_license
cavaleiros/Grupo6
02142ba9036f2a43af685342278ea328a4e746fd
f168d079e2f160a028269cfb3240af9e502cf6fe
refs/heads/master
2021-01-21T14:12:00.550055
2016-05-26T04:45:05
2016-05-26T04:45:05
55,647,091
0
0
null
null
null
null
UTF-8
Java
false
false
834
java
package command; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.UsuarioService; public class ManterUsuarioEditar implements Command { @Override public void executa(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String usuario = request.getParameter("usuario"); String senha = request.getParameter("senha"); UsuarioService usuarioService = new UsuarioService(usuario, senha); RequestDispatcher view = null; usuarioService.carregar(); request.setAttribute("usuario", usuarioService.getData()); view = request.getRequestDispatcher("AlterarUsuario.jsp"); view.forward(request, response); } }
[ "moral@192.168.0.4" ]
moral@192.168.0.4
2765ac256c033ff2f7f56c01fc730d6d2c6d1602
0a25c69b7f42a86aae0d2c0498d77a54c1d7d7e0
/java2c/HelloWorld.java
65355d7830c7756a89223e436dbf2ecfe752ca1a
[]
no_license
tomasz0ca/jni_exercise
ae751e5bbda85b27682f24af670b80cb2e996440
6ff6866c7741dc1a61e50e262196c7aa757a04b3
refs/heads/master
2021-09-27T19:50:06.483152
2016-09-05T20:14:17
2016-09-05T20:14:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
203
java
class HelloWorld { private native void print(); public static void main(String[] args) { new HelloWorld().print(); } static { System.loadLibrary("HelloWorld"); } }
[ "tomasz gta" ]
tomasz gta
edaf41171d9ce8f8a76a09f1aff1fe6a1be9cf08
9e687714b601295d85d0304ed0234dfa8fded05a
/app/src/androidTest/java/com/example/texttospech/ExampleInstrumentedTest.java
6e24283f74f331706fb632579438bbf5649a5a75
[]
no_license
abdulkarim212/TexttoSpech
038054339a757e48ff8b9832ec6996b5bc31adb3
f09908bbb4cf417c4831d549d60cc75792d8b785
refs/heads/master
2020-06-16T16:32:16.814703
2019-07-07T10:15:35
2019-07-07T10:15:35
195,637,081
0
0
null
null
null
null
UTF-8
Java
false
false
717
java
package com.example.texttospech; import android.content.Context; import androidx.test.InstrumentationRegistry; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.texttospech", appContext.getPackageName()); } }
[ "abdulkar212@gmail.com" ]
abdulkar212@gmail.com
29f7612853d389fd47c583f3a63305f9ca543e72
f7e585e2a4ea26848bb6873168284cac57806c78
/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/v4/R.java
b6f9162769e763df97107294b229b05e471a5743
[]
no_license
rbeat/cashy
edcf05b70eec61f25464d4002375625015b3ef19
b5a8aca50bbda3bcfd147262a667f82dde4f1dbc
refs/heads/master
2023-01-19T07:23:31.485334
2020-11-02T14:19:28
2020-11-02T14:19:28
316,294,062
0
0
null
null
null
null
UTF-8
Java
false
false
10,338
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.v4; public final class R { private R() {} public static final class attr { private attr() {} public static final int font = 0x7f0300da; public static final int fontProviderAuthority = 0x7f0300dc; public static final int fontProviderCerts = 0x7f0300dd; public static final int fontProviderFetchStrategy = 0x7f0300de; public static final int fontProviderFetchTimeout = 0x7f0300df; public static final int fontProviderPackage = 0x7f0300e0; public static final int fontProviderQuery = 0x7f0300e1; public static final int fontStyle = 0x7f0300e2; public static final int fontWeight = 0x7f0300e4; } public static final class bool { private bool() {} public static final int abc_action_bar_embed_tabs = 0x7f040000; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050075; public static final int notification_icon_bg_color = 0x7f050076; public static final int notification_material_background_media_default_color = 0x7f050077; public static final int primary_text_default_material_dark = 0x7f05007c; public static final int ripple_material_light = 0x7f050081; public static final int secondary_text_default_material_dark = 0x7f050082; public static final int secondary_text_default_material_light = 0x7f050083; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06004e; public static final int compat_button_inset_vertical_material = 0x7f06004f; public static final int compat_button_padding_horizontal_material = 0x7f060050; public static final int compat_button_padding_vertical_material = 0x7f060051; public static final int compat_control_corner_material = 0x7f060052; public static final int notification_action_icon_size = 0x7f0600c1; public static final int notification_action_text_size = 0x7f0600c2; public static final int notification_big_circle_margin = 0x7f0600c3; public static final int notification_content_margin_start = 0x7f0600c4; public static final int notification_large_icon_height = 0x7f0600c5; public static final int notification_large_icon_width = 0x7f0600c6; public static final int notification_main_column_padding_top = 0x7f0600c7; public static final int notification_media_narrow_margin = 0x7f0600c8; public static final int notification_right_icon_size = 0x7f0600c9; public static final int notification_right_side_padding_top = 0x7f0600ca; public static final int notification_small_icon_background_padding = 0x7f0600cb; public static final int notification_small_icon_size_as_large = 0x7f0600cc; public static final int notification_subtext_size = 0x7f0600cd; public static final int notification_top_pad = 0x7f0600ce; public static final int notification_top_pad_large_text = 0x7f0600cf; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070088; public static final int notification_bg = 0x7f070089; public static final int notification_bg_low = 0x7f07008a; public static final int notification_bg_low_normal = 0x7f07008b; public static final int notification_bg_low_pressed = 0x7f07008c; public static final int notification_bg_normal = 0x7f07008d; public static final int notification_bg_normal_pressed = 0x7f07008e; public static final int notification_icon_background = 0x7f07008f; public static final int notification_template_icon_bg = 0x7f070090; public static final int notification_template_icon_low_bg = 0x7f070091; public static final int notification_tile_bg = 0x7f070092; public static final int notify_panel_notification_icon_bg = 0x7f070093; } public static final class id { private id() {} public static final int action0 = 0x7f080008; public static final int action_container = 0x7f080010; public static final int action_divider = 0x7f080012; public static final int action_image = 0x7f080013; public static final int action_text = 0x7f080019; public static final int actions = 0x7f08001a; public static final int async = 0x7f080024; public static final int blocking = 0x7f08002c; public static final int cancel_action = 0x7f08002f; public static final int chronometer = 0x7f080035; public static final int end_padder = 0x7f080050; public static final int forever = 0x7f08005c; public static final int icon = 0x7f080063; public static final int icon_group = 0x7f080064; public static final int info = 0x7f08006a; public static final int italic = 0x7f08006c; public static final int line1 = 0x7f080072; public static final int line3 = 0x7f080073; public static final int media_actions = 0x7f08007a; public static final int normal = 0x7f080088; public static final int notification_background = 0x7f080089; public static final int notification_main_column = 0x7f08008a; public static final int notification_main_column_container = 0x7f08008b; public static final int right_icon = 0x7f08009b; public static final int right_side = 0x7f08009c; public static final int status_bar_latest_event_content = 0x7f0800cc; public static final int text = 0x7f0800d7; public static final int text2 = 0x7f0800d8; public static final int time = 0x7f0800e2; public static final int title = 0x7f0800e3; } public static final class integer { private integer() {} public static final int cancel_button_image_alpha = 0x7f090004; public static final int status_bar_notification_info_maxnum = 0x7f09000f; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b0035; public static final int notification_action_tombstone = 0x7f0b0036; public static final int notification_media_action = 0x7f0b0037; public static final int notification_media_cancel_action = 0x7f0b0038; public static final int notification_template_big_media = 0x7f0b0039; public static final int notification_template_big_media_custom = 0x7f0b003a; public static final int notification_template_big_media_narrow = 0x7f0b003b; public static final int notification_template_big_media_narrow_custom = 0x7f0b003c; public static final int notification_template_custom_big = 0x7f0b003d; public static final int notification_template_icon_group = 0x7f0b003e; public static final int notification_template_lines_media = 0x7f0b003f; public static final int notification_template_media = 0x7f0b0040; public static final int notification_template_media_custom = 0x7f0b0041; public static final int notification_template_part_chronometer = 0x7f0b0042; public static final int notification_template_part_time = 0x7f0b0043; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0f00a0; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f10011a; public static final int TextAppearance_Compat_Notification_Info = 0x7f10011b; public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f10011c; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f10011d; public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f10011e; public static final int TextAppearance_Compat_Notification_Media = 0x7f10011f; public static final int TextAppearance_Compat_Notification_Time = 0x7f100120; public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f100121; public static final int TextAppearance_Compat_Notification_Title = 0x7f100122; public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f100123; public static final int Widget_Compat_NotificationActionContainer = 0x7f1001c9; public static final int Widget_Compat_NotificationActionText = 0x7f1001ca; } public static final class styleable { private styleable() {} public static final int[] FontFamily = { 0x7f0300dc, 0x7f0300dd, 0x7f0300de, 0x7f0300df, 0x7f0300e0, 0x7f0300e1 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300da, 0x7f0300e2, 0x7f0300e3, 0x7f0300e4, 0x7f03020e }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; } }
[ "admin@rbeat.gq" ]
admin@rbeat.gq
5dc455408865cd3dcd8777be8c001c0ba2318548
73786aaa7f23557fb3126cf3eeb60a6724d5af21
/src/main/java/com/chapter04/model/Dish.java
314ea94a83fbfd9d8515cf45ca7e60d7d1a9e28e
[]
no_license
vvshinevv/modern-java-in-action
c101224bcb2fbb96eb9fbd3120a7ddc3f2f28632
07b3d517c1867b2569ab8ac429893a76b95d9881
refs/heads/main
2023-03-18T18:54:29.290125
2021-03-06T14:59:08
2021-03-06T14:59:08
342,131,447
0
0
null
2021-03-06T14:59:08
2021-02-25T05:18:06
null
UTF-8
Java
false
false
389
java
package com.chapter04.model; public class Dish { private final String name; private final boolean vegetarian; private final int calories; private final Type type; public Dish(String name, boolean vegetarian, int calories, Type type) { this.name = name; this.vegetarian = vegetarian; this.calories = calories; this.type = type; } }
[ "vvshinevv@gmail.com" ]
vvshinevv@gmail.com
900521198a2a449ee3b777dc5793e3ca2273ccb6
cd454e3f22bc482836af190bf0f83e920d089bbc
/src/asteroids/game/Level.java
ba82a28c49cb5c02230fdcb6c1f2674f61c609c9
[]
no_license
Axquaris/AsteroidDodger
26f17c868aa86fb87bc251406d0043d98cbcce72
09848d1d62f44d3802b6f2383d378b2111bf2154
refs/heads/master
2021-01-16T21:46:21.644281
2016-06-16T22:31:49
2016-06-16T22:31:49
61,329,943
1
0
null
null
null
null
UTF-8
Java
false
false
2,996
java
package asteroids.game; import java.util.ArrayList; import asteroids.particles.Particle; import asteroids.particles.ParticleSpawner; import asteroids.util.XY; public class Level { //===============// //Game Properties// These change based //===============// on difficulty. //Asteroid protected XY ASTEROID_SIZE = new XY(50,50); //Asteroid Spawning protected int STARTING_RATE = 20; protected double RATE_MULTIPLIER = .99; protected int MAX_RATE = 9; protected double ASTEROID_Y_SPEED_MIN = 3; protected double ASTEROID_Y_SPEED_MAX = 6; protected double ASTEROID_X_SPEED_MIN = -2; protected double ASTEROID_X_SPEED_MAX = 2; //Asteroid Spawning protected double spawnRate; protected int spawnCounter; //Ship protected XY SHIP_POSITION = new XY(250,400); //Starting position protected XY SHIP_DIMENSIONS = new XY(50,50); protected double THRUST_POWER = .3; protected int MAX_HP = 100; protected double HP_REGEN = .02; protected double SHIP_MASS_MULTIPLIER = 4.0/5; //Objects protected ParticleSpawner particleSpawner; protected AsteroidField asteroidField; protected Ship ship; protected int score; public Level() { initObjects(); } public void initObjects() { //Setup Asteroid Spawning spawnRate = STARTING_RATE; spawnCounter = 0; //Objects particleSpawner = new ParticleSpawner(); asteroidField = new AsteroidField(this); ship = new Ship(this); score = 0; } public Level(int a) { //Setup Asteroid Spawning MAX_RATE = a; spawnCounter = 0; //Objects particleSpawner = new ParticleSpawner(); asteroidField = new AsteroidField(this); } public boolean update() { particleSpawner.updateTasks(); particleSpawner.updateParticles(); asteroidField.moveField(); if (spawnCounter >= spawnRate) { asteroidField.addAsteroid(); spawnCounter = 0; if (spawnRate > MAX_RATE) spawnRate *= RATE_MULTIPLIER; score += 5; } spawnCounter++; if (ship.update()<=0) { return true; // gameover } score++; return false; } public void menuUpdate() { particleSpawner.updateTasks(); particleSpawner.updateParticles(); asteroidField.moveField(); if (spawnCounter >= MAX_RATE) { asteroidField.addAsteroid(); spawnCounter = 0; } spawnCounter++; } public ArrayList<Asteroid> getField() { return asteroidField.getField(); } public ArrayList<Particle> getParticles() { return particleSpawner.getParticles(); } }
[ "domceb@gmail.com" ]
domceb@gmail.com
b5382c20a7b0cebcfaf80503e06d287bc15d5f60
b94cf72334e53a2235d298c3ae8adf11946ec5bc
/app/src/main/java/com/mahmoudsallam/task/ui/details/DetailsFragment.java
ee5266265cbd252e6d3ad6eedd30ba83a3da9634
[]
no_license
mahmodsallam/sharing_group
235d9d386cc7d7eab7003406c6e663f8d453ba73
0d68ccf6bf116c427219f0c31fd2bb88813a8c1b
refs/heads/master
2021-05-24T18:33:14.573832
2020-06-21T13:15:18
2020-06-21T13:15:18
253,700,352
0
0
null
null
null
null
UTF-8
Java
false
false
2,521
java
package com.mahmoudsallam.task.ui.details; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.NavOptions; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.QuickContactBadge; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.navigation.NavigationView; import com.mahmoudsallam.task.R; import com.mahmoudsallam.task.data.model.api.UsersResponse; import com.mahmoudsallam.task.ui.main.MainFragment; public class DetailsFragment extends Fragment { private TextView nameText, userNameText, emailText, addressText, phoneText, website, company; private ImageView backImg; public static DetailsFragment newInstance() { Bundle args = new Bundle(); DetailsFragment fragment = new DetailsFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_details, container, false); nameText = view.findViewById(R.id.name_text); userNameText = view.findViewById(R.id.username_text); emailText = view.findViewById(R.id.email_text); addressText = view.findViewById(R.id.address_text); phoneText = view.findViewById(R.id.phone_text); website = view.findViewById(R.id.website_text); company = view.findViewById(R.id.company_text); UsersResponse user = this.getArguments().getParcelable("USER_DETAILS"); nameText.setText(user.getName()); userNameText.setText(user.getUsername()); emailText.setText(user.getEmail()); addressText.setText(user.getAddress().toString()); phoneText.setText(user.getPhone()); website.setText(user.getWebsite()); company.setText(user.getCompany().getName()); backImg = view.findViewById(R.id.back_img); backImg.setOnClickListener(v -> { Navigation.findNavController(v) .popBackStack(R.id.mainFragment, false); }); return view; } }
[ "mahmoug2020@gmail.com" ]
mahmoug2020@gmail.com
675f12faa0be32eb34aad9378539c4f0232b8b10
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.minihd.qq/assets/exlibs.1.jar/classes.jar/khi.java
72b86c51841f202b839726c731488a903e37ef0d
[]
no_license
tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651957
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
2022-01-31T09:46:26
2022-01-31T02:43:22
Java
UTF-8
Java
false
false
637
java
import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mobileqq.troop.activity.TroopCreateAvatarActivity; public class khi implements View.OnClickListener { public khi(TroopCreateAvatarActivity paramTroopCreateAvatarActivity) {} public void onClick(View paramView) { this.a.a.putExtra("isBack", 1); this.a.setResult(-1, this.a.a); this.a.finish(); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.minihd.qq\assets\exlibs.1.jar\classes.jar * Qualified Name: khi * JD-Core Version: 0.7.0.1 */
[ "98632993+tsuzcx@users.noreply.github.com" ]
98632993+tsuzcx@users.noreply.github.com
5124ef2fb379c26cd06c1dee6dcddf58e75e8689
a91f0b711ec5dbcdbea3a258d9e166f164cbd646
/core/src/me/extain/game/map/dungeonGen/StartRoom.java
e1e74134860027614fb4365e0a926bbf8c1c4a5c
[]
no_license
Extain/RogueGame2
76845595e23e5f94b4ab0e405dc3c200e6843a0e
4027c3a26d568341f268eafc0cd16a731be13316
refs/heads/master
2023-08-23T19:09:09.230270
2021-09-29T02:31:08
2021-09-29T02:31:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,263
java
package me.extain.game.map.dungeonGen; import com.github.czyzby.noise4j.map.Grid; import com.github.czyzby.noise4j.map.generator.room.AbstractRoomGenerator; import com.github.czyzby.noise4j.map.generator.room.RoomType; public class StartRoom implements RoomType { private Grid gridObj; public StartRoom(Grid grid) { this.gridObj = grid; } private AbstractRoomGenerator.Room room; @Override public void carve(AbstractRoomGenerator.Room room, Grid grid, float value) { //DefaultRoomType.CASTLE.carve(room, grid, 1f); int topX = room.getX(); int topY = room.getY(); int tRightX = topX + room.getWidth(); int RightY = topY; for (int x = room.getX(); x < room.getX() + room.getWidth(); x++) { for (int y = room.getY(); y < room.getY() + room.getHeight(); y++) { grid.set(x, y, 0.5f); } } for (int x1 = 0; x1 < grid.getWidth(); x1++) { for (int y1 = 0; y1 < grid.getHeight(); y1++) { for (int x = topX; x < tRightX; x++) { // Top if (grid.get(x, topY + room.getHeight()) != 0.9f) gridObj.set(x, topY + room.getHeight(), 0.6f); } for (int y = room.getY(); y < room.getY() + room.getHeight(); y++) { // Left if (grid.get(room.getX() - 1, y) != 0.9f || grid.get(room.getX() - 1, y) != 0.6f) gridObj.set(room.getX() - 1, y, 0.3f); } for (int x = room.getX(); x < room.getX() + room.getWidth(); x++) { // Bottom if (grid.get(x, room.getY() - 1) != 0.9f || grid.get(x, room.getY() - 1) != 0.6f) gridObj.set(x, room.getY() - 1, 0.4f); } for (int y = room.getY(); y < room.getY() + room.getHeight(); y++) { // Right if (grid.get(room.getX() + room.getWidth(), y) != 0.9f || grid.get(room.getX() + room.getWidth(), y) != 0.6f) gridObj.set((room.getX()) + room.getWidth(), y, 0.1f); if (grid.get(room.getX() - 1, room.getY() - 1) != 0.9f) { gridObj.set(room.getX() - 1, room.getY() - 1, 1f); // Bottom Left Corner } if (grid.get(room.getX() - 1, room.getY() + room.getHeight()) != 0.9f) { gridObj.set(room.getX() - 1, room.getY() + room.getHeight(), 0.3f); // Top Left Corner } if (grid.get(room.getX() + room.getWidth() - 1, room.getY() - 1) != 0.9f) { gridObj.set(room.getX() + room.getWidth(), room.getY() - 1, 1f); // Bottom Right corner } if (grid.get(room.getX() + room.getWidth(), room.getY() + room.getHeight()) != 0.9f) { gridObj.set(room.getX() + room.getWidth(), room.getY() + room.getHeight(), 0.1f); // Top Right corner } } } } } @Override public boolean isValid(AbstractRoomGenerator.Room room) { return true; } public AbstractRoomGenerator.Room getRoom() { return room; } }
[ "trikmaniac@gmail.com" ]
trikmaniac@gmail.com
54c5533cf59125c1a8944b8497b74e17393d4a20
15ef3a490a5fd0960b6050d12997e17e4529cc5f
/src/step16/ex6/MyClass2.java
046798aefad60d015defc322eb9e186092a948fe
[]
no_license
joelweon/java01
e51b98641e550dd1a6111c2cbea615edf056c9e8
d0af6666b9888573900f6811ba458ff51eee1e64
refs/heads/master
2020-06-29T13:44:46.453281
2017-02-06T06:16:29
2017-02-06T06:16:29
74,125,124
0
0
null
null
null
null
UTF-8
Java
false
false
238
java
/* final 사용 */ package step16.ex6; public class MyClass2 { // 메서드 앞에 final을 붙이면 오버라이딩 불가! // => 임의의 기능 변경을 막기 위해 public final void m1() {} public void m2() {} }
[ "joel.weon@gmail.com" ]
joel.weon@gmail.com
356211c3f7898d2477e473cf6ad635a1f6dfc37c
2e103182475666ed0a96804f5030efa74469a276
/ymate-platform-core/src/main/java/net/ymate/platform/core/module/impl/DefaultModuleConfigurer.java
9f2fdee9e3b6ace3a81bd515080d9fd2cf91824c
[ "Apache-2.0" ]
permissive
suninformation/ymate-platform-v2
057832ec37f527d136bcef70971e03460d969f98
a0c8549fa448c07610906b799a4e44ad3b7f0236
refs/heads/master
2023-07-22T17:26:57.261618
2023-07-08T06:11:10
2023-07-08T06:11:10
45,100,886
136
45
Apache-2.0
2023-03-14T23:54:25
2015-10-28T09:09:12
Java
UTF-8
Java
false
false
2,126
java
/* * Copyright 2007-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.core.module.impl; import net.ymate.platform.core.configuration.IConfigReader; import net.ymate.platform.core.configuration.impl.MapSafeConfigReader; import net.ymate.platform.core.module.IModuleConfigurer; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang3.StringUtils; import java.util.Collections; import java.util.Map; /** * @author 刘镇 (suninformation@163.com) on 2019-08-07 18:52 * @since 2.1.0 */ public class DefaultModuleConfigurer implements IModuleConfigurer { public static DefaultModuleConfigurer createEmpty(String moduleName) { return new DefaultModuleConfigurer(moduleName, Collections.emptyMap()); } private final String moduleName; private final IConfigReader configReader; public DefaultModuleConfigurer(String moduleName, Map<?, ?> cfgMap) { this(moduleName, MapSafeConfigReader.bind(cfgMap)); } public DefaultModuleConfigurer(String moduleName, IConfigReader configReader) { if (StringUtils.isBlank(moduleName)) { throw new NullArgumentException("moduleName"); } if (configReader == null) { throw new NullArgumentException("configReader"); } this.moduleName = moduleName; this.configReader = configReader; } @Override public String getModuleName() { return moduleName; } @Override public IConfigReader getConfigReader() { return configReader; } }
[ "suninformation@163.com" ]
suninformation@163.com
a3a4c69fa3336bcdb481c495d818cc21a91a6929
2d9cdfbde93a45e0b34d84f56e9da7182c3b5721
/ServisBroadcast/src/com/example/servisbroadcast/MyService.java
da58b0f5b34a4adad1bf6bbfca3c8b56225254c6
[]
no_license
Amashilda/O_o
3393bb1e8a2189f6d08e5e5e236222b1354a4bdc
e7e95fd5a567cb4b1727fb51d6ebd9392826ba6e
refs/heads/master
2021-01-19T07:39:36.402797
2014-05-15T13:50:57
2014-05-15T13:50:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,309
java
package com.example.servisbroadcast; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService extends Service { final String LOG_TAG = "myLogs"; ExecutorService es; public void onCreate() { super.onCreate(); Log.d(LOG_TAG, "MyService onCreate"); es = Executors.newFixedThreadPool(2); } public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, "MyService onDestroy"); } public int onStartCommand(Intent intent, int flags, int startId) { Log.d(LOG_TAG, "MyService onStartCommand"); int time = intent.getIntExtra(MainActivity.PARAM_TIME, 1); int task = intent.getIntExtra(MainActivity.PARAM_TASK, 0); MyRun mr = new MyRun(startId, time, task); es.execute(mr); return super.onStartCommand(intent, flags, startId); } public IBinder onBind(Intent arg0) { return null; } class MyRun implements Runnable { int time; int startId; int task; public MyRun(int startId, int time, int task) { this.time = time; this.startId = startId; this.task = task; Log.d(LOG_TAG, "MyRun#" + startId + " create"); } public void run() { Intent intent = new Intent(MainActivity.BROADCAST_ACTION); Log.d(LOG_TAG, "MyRun#" + startId + " start, time = " + time); try { // сообщаем об старте задачи intent.putExtra(MainActivity.PARAM_TASK, task); intent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_START); sendBroadcast(intent); // начинаем выполнение задачи TimeUnit.SECONDS.sleep(time); // сообщаем об окончании задачи intent.putExtra(MainActivity.PARAM_STATUS, MainActivity.STATUS_FINISH); intent.putExtra(MainActivity.PARAM_RESULT, time * 100); sendBroadcast(intent); } catch (InterruptedException e) { e.printStackTrace(); } stop(); } void stop() { Log.d(LOG_TAG, "MyRun#" + startId + " end, stopSelfResult(" + startId + ") = " + stopSelfResult(startId)); } } }
[ "Amashilda@gmail.com" ]
Amashilda@gmail.com
8eb67e8dc9426059391ccca97e2249e4a0b93458
74f7a6973a3ef5824ad760e1fa3d6b472539f7d5
/src/com/example/managementsystem/Login.java
83fa5f8a8a4bf147edc1b8c9103ac8fd55d61667
[]
no_license
sujiyuva/Attendance
e6c0c3be7a7bf4fd77de78de3196c80d5b6f3be4
85822531bede1a7075ca568848b1b3f44393c8ce
refs/heads/master
2021-01-10T03:30:09.762497
2016-03-08T10:02:17
2016-03-08T10:02:17
51,506,752
0
0
null
null
null
null
UTF-8
Java
false
false
1,285
java
package com.example.managementsystem; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Login extends Activity { Button admin, staff, stu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); admin = (Button) findViewById(R.id.button1); staff = (Button) findViewById(R.id.button2); stu = (Button) findViewById(R.id.button3); admin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(Login.this, Signin.class); startActivity(intent); } }); staff.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(Login.this, Signinstaff.class); startActivity(intent); } }); stu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(Login.this, Signinstudent.class); startActivity(intent); } }); } }
[ "sujiyuva90@gmail.com" ]
sujiyuva90@gmail.com
1b21b3aea28123504fef122401c7cec06ca6f701
ddeb708a197abfd9c31335088a7fee19ec7600d8
/service-provider/src/test/java/serviceImpl/UserServiceImplTest.java
7d578bc800a5fb03b116412c5f308902c94b6355
[]
no_license
butalso/wechat-resource-recovery
3ff225b206fa41cf2767ec67752a535d9d501fa4
718008d6f2ff340a811c4e468fcd6358c91595d2
refs/heads/master
2021-09-14T09:40:41.673055
2018-05-11T13:03:40
2018-05-11T13:03:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,225
java
package serviceImpl; import dto.Address; import entity.Collector; import entity.Company; import entity.Customer; import entity.Manager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import service.UserService; import java.util.Date; @RunWith(SpringJUnit4ClassRunner.class) // spring配置文件 @ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"}) public class UserServiceImplTest { @Autowired UserService userService; Customer customer; Collector collector; Company company; Manager manager; Address address = new Address("江苏省", "南京市", "鼓楼区", "江南骏园"); @Before public void setUp() { customer = new Customer("熊大", "123", "M", "12345678900", address); collector = new Collector("熊二", "123", "M", "12345678900", "回收哥", "440882199823140905", address); company = new Company("熊三", "123", "12345678900", address); manager = new Manager("熊四","123", "M", "12345678900", address); } @Test public void addUser() { // customer.setName("熊大"); // userService.addUser(customer); // userService.addUser(collector); // userService.addUser(company); userService.addUser(manager); } @Test public void delUser() { userService.delUser("胡昌明", 0); // userService.delUser("熊二", 1); // userService.delUser("废品大叔", 2); // userService.delUser("周先生", 3); } @Test public void updateUser() { customer = (Customer) userService.getUserDetails("熊大", 0); collector = (Collector) userService.getUserDetails("熊二", 1); company = (Company) userService.getUserDetails("熊三", 2); manager = (Manager) userService.getUserDetails("熊四", 3); customer.setPhone("222"); userService.updateUser(customer); collector.setPhone("222"); userService.updateUser(collector); company.setPhone("222"); userService.updateUser(company); manager.setPhone("222"); userService.updateUser(manager); } @Test public void getUser() { // System.out.println(userService.getUserDetails("熊大", 0)); System.out.println(userService.getUserDetails("慢羊羊", 1)); // System.out.println(userService.getUserDetails("废品大叔", 2)); // System.out.println(userService.getUserDetails("熊四", 3)); } @Test public void updatePassword() { userService.updatePassword("狙击手", 0, "123456", "123"); } @Test public void getAllUsers() throws InterruptedException { // System.out.println(userService.getAllUsers(0)); Date date = new Date(); Thread.sleep(1000); Date date1 = new Date(); System.out.println(date); System.out.println(date1); System.out.println(date.before(date1)); } }
[ "ouwenyue@hhu.edu.cn" ]
ouwenyue@hhu.edu.cn
9e18fad8706954c1741ee217a4da1be1a4bdd55c
de8e7ac0742d0fc1d51932e4c2755a2032ba7a1b
/app/src/main/java/com/ksggroup/altanet/altasocial/Model/GetReactionRequest.java
8541f0adb1e9779c618a3ab7d88a1c2fb1c97776
[]
no_license
ksggroup/AltaSocial
905452695019a97d93fdd62e8f43ae0fc7a3f779
19bebdd128c38ec6aa87d329e7b60bc9003c382b
refs/heads/master
2020-05-21T07:35:14.950816
2017-03-12T17:30:42
2017-03-12T17:30:42
84,596,437
0
0
null
null
null
null
UTF-8
Java
false
false
861
java
package com.ksggroup.altanet.altasocial.Model; import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.PropertyInfo; import java.util.Hashtable; public class GetReactionRequest implements KvmSerializable { private Long post_id; public Long getPost_id() { return post_id; } public void setPost_id(Long post_id) { this.post_id = post_id; } public GetReactionRequest(Long post_id) { this.post_id = post_id; } @Override public Object getProperty(int i) { return post_id; } @Override public int getPropertyCount() { return 1; } @Override public void setProperty(int i, Object o) { this.post_id = Long.valueOf(o.toString()); } @Override public void getPropertyInfo(int i, Hashtable hashtable, PropertyInfo propertyInfo) { propertyInfo.setName("post_id"); propertyInfo.setType(Long.class); } }
[ "vfiguracion@tiaxa.asia" ]
vfiguracion@tiaxa.asia
0b5388f3c93c07f2e0e41ec799f53556c27164e2
3dab3b92367c0a92c802f181319e731dca572a70
/src/main/java/discord/bot/command/bot/managing/ForcePropertiesSaveCommand.java
947979daf04db3ef75a369d3b253200342cd05d0
[]
no_license
Minipasglop/S-perNat-ralBot
c794407d2e98ce59df1ff9cb9b3a3b52a1437167
58ec4c0c8dc39d1468f289319e37b062d460e986
refs/heads/master
2022-06-14T20:53:48.568461
2019-11-03T20:49:32
2019-11-03T20:49:32
199,709,468
0
0
null
2022-06-10T00:41:19
2019-07-30T18:50:49
Java
UTF-8
Java
false
false
1,956
java
package discord.bot.command.bot.managing; import discord.bot.BotGlobalManager; import discord.bot.command.ICommand; import discord.bot.utils.misc.MessageSenderFactory; import discord.bot.utils.misc.SharedStringEnum; import discord.bot.utils.save.ServerPropertiesJSONUpdate; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import java.util.List; public class ForcePropertiesSaveCommand extends ICommand { private final String HELP = "Cette commande permet à Vigo de forcer la sauvegarde des propriétés avant un eventuel reboot. \nUsage: `!" + this.commandName + "`"; private final String COMMAND_SUCCESS = "Successfully saved properties files"; public ForcePropertiesSaveCommand(String commandName) { super(commandName); } @Override public boolean called(String[] args, MessageReceivedEvent event) { if (args.length != 0 && args[0].equals("help") || args.length != 0 ) { return false; } else return true; } @Override public void action(String[] args, MessageReceivedEvent event) { if(event.getAuthor().getId().equals(BotGlobalManager.getConfig().getBotOwnerUserId())) { List<Guild> guildList = BotGlobalManager.getServers(); for (int i = 0; i < guildList.size(); i++) { new ServerPropertiesJSONUpdate().init(event.getGuild().getId()); } MessageSenderFactory.getInstance().sendSafePrivateMessage(event.getAuthor(), COMMAND_SUCCESS, event.getTextChannel(), COMMAND_SUCCESS); }else { event.getMessage().delete().queue(); MessageSenderFactory.getInstance().sendSafePrivateMessage(event.getAuthor(), SharedStringEnum.BOT_OWNER_ONLY.getSharedString(), event.getTextChannel(), SharedStringEnum.BOT_OWNER_ONLY.getSharedString()); } } @Override public String help() { return HELP; } }
[ "dertest58@yahoo.fdr" ]
dertest58@yahoo.fdr
a0eb451060dc163f47f4a58d01e08ce04c8ea71d
2586f3b8626c14aa53e9f87ac0844689b22a8b48
/src/sun/util/resources/cldr/ext/CurrencyNames_fil.java
28dc11bcf45060fcf9aded0107b21c9d44302dd3
[]
no_license
shaoxiongdu/LearningJDK
46fd841471f5d0e2737ebcd3570ef6f018a90ddb
406e4de55d107648ed6497d625239c637227aa66
refs/heads/master
2022-11-12T14:30:01.400708
2022-11-08T13:00:17
2022-11-08T13:00:17
350,005,058
18
11
null
null
null
null
UTF-8
Java
false
false
15,234
java
/* * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2016 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in * http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of the Unicode data files and any associated documentation * (the "Data Files") or Unicode software and any associated documentation * (the "Software") to deal in the Data Files or Software * without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, and/or sell copies of * the Data Files or Software, and to permit persons to whom the Data Files * or Software are furnished to do so, provided that * (a) this copyright and permission notice appear with all copies * of the Data Files or Software, * (b) this copyright and permission notice appear in associated * documentation, and * (c) there is clear notice in each modified Data File or in the Software * as well as in the documentation associated with the Data File(s) or * Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder * shall not be used in advertising or otherwise to promote the sale, * use or other dealings in these Data Files or Software without prior * written authorization of the copyright holder. */ package sun.util.resources.cldr.ext; import sun.util.resources.OpenListResourceBundle; public class CurrencyNames_fil extends OpenListResourceBundle { @Override protected final Object[][] getContents() { final String metaValue_CNH = "CNH"; final Object[][] data = new Object[][] { { "mwk", "Malawian Kwacha" }, { "FJD", "FJD" }, { "STD", "STD" }, { "LVL", "LVL" }, { "SCR", "SCR" }, { "CDF", "CDF" }, { "BBD", "BBD" }, { "mga", "Malagasy Ariary" }, { "HNL", "HNL" }, { "UGX", "UGX" }, { "ZAR", "ZAR" }, { "dem", "Deutsche Marks" }, { "bam", "Bosnia-Herzegovina Convertible Mark" }, { "egp", "Egyptian Pound" }, { "CUC", "CUC" }, { "ssp", "Pound ng Timog Sudan" }, { "BSD", "BSD" }, { "nio", "C\u00f3rdoba ng Nicaragua" }, { "SDG", "SDG" }, { "nzd", "Dolyar ng New Zealand" }, { "IQD", "IQD" }, { "brl", "Real ng Barzil" }, { "CUP", "CUP" }, { "GMD", "GMD" }, { "fjd", "Dolyar ng Fiji" }, { "RSD", "RSD" }, { "mxn", "Piso ng Mexico" }, { "std", "S\u00e3o Tom\u00e9 & Pr\u00edncipe Dobra (1977\u20132017)" }, { "lvl", "Latvian Lats" }, { "scr", "Seychellois Rupee" }, { "cdf", "Congolese Franc" }, { "bbd", "Dolyar ng Barbados" }, { "MYR", "MYR" }, { "hnl", "Lempira ng Honduras" }, { "ugx", "Ugandan Shilling" }, { "FKP", "FKP" }, { "zar", "Rand ng Timog Africa" }, { "stn", "S\u00e3o Tom\u00e9 & Pr\u00edncipe Dobra" }, { "UYU", "UYU" }, { "cuc", "Convertible na Piso ng Cuba" }, { "bsd", "Dolyar ng Bahamas" }, { "CVE", "CVE" }, { "OMR", "OMR" }, { "sdg", "Pound ng Sudan" }, { "KES", "KES" }, { "SEK", "SEK" }, { "BTN", "BTN" }, { "iqd", "Iraqi Dinar" }, { "GNF", "GNF" }, { "cup", "Piso ng Cuba" }, { "gmd", "Gambian Dalasi" }, { "MZN", "MZN" }, { "twd", "Dolyar ng New Taiwan" }, { "ARS", "ARS" }, { "rsd", "Serbian Dinar" }, { "QAR", "QAR" }, { "myr", "Malaysian Ringgit" }, { "IRR", "IRR" }, { "fkp", "Pound ng Falkland Islands" }, { "xof", "CFA Franc ng Kanlurang Africa" }, { "THB", "\u0e3f" }, { "UZS", "UZS" }, { "uyu", "Piso ng Uruguay" }, { "BDT", "BDT" }, { "cve", "Cape Verdean Escudo" }, { "omr", "Omani Rial" }, { "LYD", "LYD" }, { "kes", "Kenyan Shilling" }, { "sek", "Swedish Krona" }, { "KWD", "KWD" }, { "btn", "Bhutanese Ngultrum" }, { "RUB", "RUB" }, { "gnf", "Guinean Franc" }, { "ISK", "ISK" }, { "mzn", "Mozambican Metical" }, { "ars", "Piso ng Argentina" }, { "qar", "Qatari Rial" }, { "MKD", "MKD" }, { "irr", "Iranian Rial" }, { "DZD", "DZD" }, { "thb", "Thai Baht" }, { "uzs", "Uzbekistan Som" }, { "xpf", "CFP Franc" }, { "PAB", "PAB" }, { "SGD", "SGD" }, { "bdt", "Bangladeshi Taka" }, { "KGS", "KGS" }, { "lyd", "Libyan Dinar" }, { "kwd", "Kuwaiti Dinar" }, { "rub", "Russian Ruble" }, { "CHF", "CHF" }, { "HRK", "HRK" }, { "isk", "Icelandic Kr\u00f3na" }, { "DJF", "DJF" }, { "mkd", "Macedonian Denar" }, { "TZS", "TZS" }, { "dzd", "Algerian Dinar" }, { "pab", "Balboa ng Panama" }, { "sgd", "Dolyar ng Singapore" }, { "KHR", "KHR" }, { "IDR", "IDR" }, { "kgs", "Kyrgystani Som" }, { "KYD", "KYD" }, { "BWP", "BWP" }, { "SHP", "SHP" }, { "TJS", "TJS" }, { "xaf", "CFA Franc BEAC" }, { "AED", "AED" }, { "RWF", "RWF" }, { "chf", "Swiss Franc" }, { "hrk", "Croatian Kuna" }, { "djf", "Djiboutian Franc" }, { "DKK", "DKK" }, { "BGN", "BGN" }, { "MMK", "MMK" }, { "NOK", "NOK" }, { "SYP", "SYP" }, { "tzs", "Tanzanian Shilling" }, { "vnd", "Vietnamese Dong" }, { "aud", "Dolyar ng Australya" }, { "LKR", "LKR" }, { "khr", "Cambodian Riel" }, { "CZK", "CZK" }, { "idr", "Indonesian Rupiah" }, { "kyd", "Dolyar ng Cayman Islands" }, { "HTG", "HTG" }, { "bwp", "Botswanan Pula" }, { "shp", "Saint Helena Pound" }, { "tjs", "Tajikistani Somoni" }, { "BHD", "BHD" }, { "rwf", "Rwandan Franc" }, { "aed", "United Arab Emirates Dirham" }, { "KZT", "KZT" }, { "SZL", "SZL" }, { "dkk", "Danish Krone" }, { "YER", "YER" }, { "bgn", "Bulgarian Lev" }, { "AFN", "AFN" }, { "mmk", "Myanmar Kyat" }, { "nok", "Norwegian Krone" }, { "syp", "Syrian Pound" }, { "AWG", "AWG" }, { "NPR", "NPR" }, { "MNT", "MNT" }, { "lkr", "Sri Lankan Rupee" }, { "czk", "Czech Republic Koruna" }, { "BYN", "BYN" }, { "HUF", "HUF" }, { "xcd", "Dolyar ng Silangang Caribbean" }, { "BYR", "BYR" }, { "htg", "Gourde ng Haiti" }, { "BIF", "BIF" }, { "bhd", "Bahraini Dinar" }, { "sit", "Slovenian Tolar" }, { "kzt", "Kazakhstani Tenge" }, { "szl", "Swazi Lilangeni" }, { "yer", "Yemeni Rial" }, { "afn", "Afghan Afghani" }, { "BZD", "BZD" }, { "MOP", "MOP" }, { "NAD", "NAD" }, { "awg", "Florin ng Aruba" }, { "npr", "Nepalese Rupee" }, { "mnt", "Mongolian Tugrik" }, { "gbp", "British Pound" }, { "byn", "Belarusian Ruble" }, { "PEN", "PEN" }, { "huf", "Hungarian Forint" }, { "WST", "WST" }, { "TMT", "TMT" }, { "byr", "Belarusian Ruble (2000\u20132016)" }, { "bif", "Burundian Franc" }, { "GTQ", "GTQ" }, { "CLP", "CLP" }, { "TND", "TND" }, { "bzd", "Dolyar ng Belize" }, { "mop", "Macanese Pataca" }, { "nad", "Dolyar ng Namibia" }, { "SLL", "SLL" }, { "skk", "Slovak Koruna" }, { "pen", "Peruvian Sol" }, { "wst", "Samoan Tala" }, { "tmt", "Turkmenistani Manat" }, { "frf", "French Franc" }, { "DOP", "DOP" }, { "KMF", "KMF" }, { "gtq", "Quetzal ng Guatemala" }, { "clp", "Piso ng Chile" }, { "tnd", "Tunisian Dinar" }, { "GEL", "GEL" }, { "MAD", "MAD" }, { "sll", "Sierra Leonean Leone" }, { "TOP", "TOP" }, { "AZN", "AZN" }, { "PGK", "PGK" }, { "CNH", metaValue_CNH }, { "UAH", "UAH" }, { "ERN", "ERN" }, { "dop", "Piso ng Dominican" }, { "kmf", "Comorian Franc" }, { "MRO", "MRO" }, { "gel", "Georgian Lari" }, { "mad", "Moroccan Dirham" }, { "azn", "Azerbaijani Manat" }, { "top", "Tongan Pa\u02bbanga" }, { "pgk", "Papua New Guinean Kina" }, { "BMD", "BMD" }, { "PHP", "\u20b1" }, { "cnh", metaValue_CNH }, { "uah", "Ukrainian Hryvnia" }, { "PYG", "PYG" }, { "JMD", "JMD" }, { "ern", "Eritrean Nakfa" }, { "COP", "COP" }, { "USD", "$" }, { "mro", "Mauritanian Ouguiya (1973\u20132017)" }, { "cny", "Chinese Yuan" }, { "mru", "Mauritanian Ouguiya" }, { "ETB", "ETB" }, { "SOS", "SOS" }, { "VEF", "VEF" }, { "VUV", "VUV" }, { "LAK", "LAK" }, { "bmd", "Dolyar ng Bermuda" }, { "BND", "BND" }, { "php", "Piso ng Pilipinas" }, { "xxx", "Hindi Kilalang Pera" }, { "LRD", "LRD" }, { "pyg", "Paraguayan Guarani" }, { "jmd", "Dolyar ng Jamaica" }, { "ALL", "ALL" }, { "ZMW", "ZMW" }, { "cop", "Piso ng Colombia" }, { "usd", "Dolyar ng US" }, { "etb", "Ethiopian Birr" }, { "veb", "Venezuelan Bol\u00edvar (1871\u20132008)" }, { "GHS", "GHS" }, { "GYD", "GYD" }, { "KPW", "KPW" }, { "BOB", "BOB" }, { "MDL", "MDL" }, { "sos", "Somali Shilling" }, { "vef", "Bol\u00edvar ng Venezuela" }, { "vuv", "Vanuatu Vatu" }, { "lak", "Laotian Kip" }, { "AMD", "AMD" }, { "bnd", "Dolyar ng Brunei" }, { "zmk", "Zambian Kwacha (1968\u20132012)" }, { "TRY", "TRY" }, { "LBP", "LBP" }, { "JOD", "JOD" }, { "lrd", "Dolyar ng Liberia" }, { "all", "Albanian Lek" }, { "zmw", "Zambian Kwacha" }, { "MUR", "MUR" }, { "GIP", "GIP" }, { "RON", "RON" }, { "ils", "Israeli New Sheqel" }, { "ghs", "Ghanaian Cedi" }, { "gyd", "Dolyar ng Guyanese" }, { "kpw", "Won ng Hilagang Korea" }, { "NGN", "NGN" }, { "bob", "Boliviano ng Bolivia" }, { "mdl", "Moldovan Leu" }, { "CRC", "CRC" }, { "PKR", "PKR" }, { "amd", "Armenian Dram" }, { "ANG", "ANG" }, { "try", "Turkish Lira" }, { "lbp", "Pound ng Lebanon" }, { "jod", "Jordanian Dinar" }, { "hkd", "Dolyar ng Hong Kong" }, { "eur", "Euro" }, { "SRD", "SRD" }, { "lsl", "Lesotho Loti" }, { "LTL", "LTL" }, { "SAR", "SAR" }, { "TTD", "TTD" }, { "cad", "Dolyar ng Canada" }, { "MVR", "MVR" }, { "eek", "Estonian Kroon" }, { "mur", "Mauritian Rupee" }, { "gip", "Gibraltar Pound" }, { "ron", "Romanian Leu" }, { "JPY", "\u00a5" }, { "AOA", "AOA" }, { "PLN", "PLN" }, { "SBD", "SBD" }, { "ngn", "Nigerian Naira" }, { "crc", "Col\u00f3n ng Costa Rica" }, { "pkr", "Pakistani Rupee" }, { "ang", "Antillean Guilder ng Netherlands" }, { "MWK", "MWK" }, { "srd", "Dolyar ng Suriname" }, { "ltl", "Lithuanian Litas" }, { "sar", "Saudi Riyal" }, { "ttd", "Dolyar ng Trinidad and Tobago" }, { "MGA", "MGA" }, { "mvr", "Maldivian Rufiyaa" }, { "inr", "Indian Rupee" }, { "BAM", "BAM" }, { "EGP", "EGP" }, { "SSP", "SSP" }, { "krw", "Won ng Timog Korea" }, { "aoa", "Angolan Kwanza" }, { "jpy", "Japanese Yen" }, { "pln", "Polish Zloty" }, { "sbd", "Dolyar ng Solomon Islands" }, { "NIO", "NIO" }, }; return data; } }
[ "kangjianwei1990@qq.com" ]
kangjianwei1990@qq.com
f0600bfbb5f9dfdaa9845a45e3b338b464dfb272
66848c4e6efe821af2ae7e41435092f272725d61
/src/com/agloco/action/UpdateTermsOfUseAction.java
e2e82cddd52d852f1a49b24c0243d83ad85977ba
[]
no_license
harrysun2006/ag_Guest
59168e01d23ed27bc50ce20e0ed57b1f66eff68a
331ada157fe7487901e11bae2e6f859fb80e398b
refs/heads/master
2021-01-01T06:33:07.027227
2014-09-03T10:58:39
2014-09-03T10:58:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,927
java
/** * Copyright (c) 2000-2006 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.agloco.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.agloco.exception.CannotCatchedException; import com.agloco.exception.UserPasswordAuthenticateException; import com.agloco.exception.UserPasswordConfirmException; import com.agloco.model.AGMember; import com.agloco.service.util.MailServiceUtil; import com.agloco.service.util.MemberServiceUtil; import com.agloco.util.ValidateUtil; import com.liferay.util.servlet.SessionErrors; /** * <a href="UpdateTermsOfUseAction.java.html"><b><i>View Source</i></b></a> * * @author Erick Kong * */ public class UpdateTermsOfUseAction extends Action { private static Log _log = LogFactory.getLog(UpdateTermsOfUseAction.class); public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res){ try{ String password = req.getParameter("newPassword").trim(); String cfmPassword = req.getParameter("newPasswordCfm").trim(); if(ValidateUtil.isPassword(password) && ValidateUtil.isPassword(cfmPassword)) { if(!password.equals(cfmPassword)) throw new UserPasswordConfirmException(); } else throw new UserPasswordAuthenticateException(); AGMember member = MemberServiceUtil.updateAgreedToTermsOfUse(req.getRemoteUser(), true ,password); MailServiceUtil.sendFirstSigninMail(member); req.setAttribute("memberCode", member.getMemberCode()); //top.jsp use for referralcenter req.getSession().setAttribute(com.agloco.Constants.MEMBERCODE,member.getMemberCode()); return mapping.findForward("agloco.sign_up.sign-up-email-link.jsp"); } catch(Exception e){ if(e instanceof UserPasswordAuthenticateException || e instanceof UserPasswordConfirmException) SessionErrors.add(req, e.getClass().getName() , e); else { _log.error(e.getMessage()); SessionErrors.add(req, CannotCatchedException.class.getName() , new CannotCatchedException()); } return mapping.findForward("portal.terms_of_use"); } //remove this to MemberServiceImpl at 12/09/06 // AGMemberCount agmc = new AGMemberCount(); // agmc.setMemberId(member.getMemberId()); // MemberServiceUtil.addAGMemberCount(agmc); // AGMemberTemp member = MemberServiceUtil.getAGMemberTempByUserId(req.getRemoteUser()); // return mapping.findForward(Constants.COMMON_REFERER); } }
[ "harrysun2006@gmail.com" ]
harrysun2006@gmail.com
0f634fae8597e80f39a02fad9e61e291a8bb2705
0bc2d579792c8a9b2426de8ea834a3c80d329bcd
/q_5_7_2.java
0a61d353594ba7530067df904815b8b849ba75b0
[]
no_license
jalhago-shipda/javastudy
63a80eacb8d93175bca43c5f2f6de559ac12815b
d5943a66daffc5c2cdab2ba6fbdeb623e0f2f382
refs/heads/master
2021-01-10T10:30:56.080268
2015-11-30T11:56:24
2015-11-30T11:56:24
46,752,870
0
0
null
null
null
null
UTF-8
Java
false
false
881
java
class q_5_7_2 { public static void main(String[] args) { for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(i+j==9) { System.out.println("a = " + i + ", b = " + j); break; // 이 브레이크ㅜ는 쓸 필요가 없음. 어차피 이프문 끝나면 안의포문 벗어나서 바깥포문 조건검사해서 참이면 다시 진행되는 형식이라 굳이 쓸필요가 없다 } } } } } /* answer 답은 똑같이 나옴. class q_5_7_2 { public static void main(String[] args) { for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if((i*10+j)+(j*10+i)==99) System.out.println(i + ", " + j); } } } }
[ "Hackintosh@g2eks-iMac.local" ]
Hackintosh@g2eks-iMac.local
378538a4fcf2e1f737f1f2570d56fa8e25a6c7e1
38bdd1f0893ffffef09ce100240fdfb50a91a792
/src/com/song/Section1/part3/Stack.java
228569ea57cacf82b3dd47d70b851f00a94014c7
[]
no_license
songxiang666/ArithmeticNote
81c6a5863d837e1d9d718859004a72e27f8e26a7
21d48921eb197d70908d5e25d370cc4b98260f4d
refs/heads/master
2021-07-09T16:08:53.888844
2017-10-08T01:20:31
2017-10-08T01:20:31
106,141,603
0
0
null
null
null
null
UTF-8
Java
false
false
891
java
package com.song.Section1.part3; import java.util.Iterator; public class Stack<Item> implements Iterable<Item> { private Node first; private int N; private class Node{ Item item; Node next; } public boolean isEmpty(){ return N==0; } public int size(){ return N; } public void push(Item item){ Node oldFirst=first; first=new Node(); first.item=item; first.next=oldFirst; N++; } public Item pop(){ Item item=first.item; first=first.next; N--; return item; } @Override public Iterator<Item> iterator() { return new StackIterator(); } class StackIterator implements Iterator<Item>{ private Node current=first; @Override public boolean hasNext() { return current!=null; } @Override public Item next(){ Item item=current.item; current=current.next; return item; } @Override public void remove() { } } }
[ "2298389762@qq.com" ]
2298389762@qq.com
ab049a48231381197134e3d8268bc19dff7a6790
424bf7c7da4bd511b590579d4813726ae138dc8a
/JDBC/LowestSalariedEmpDemo.java
e246dfb47a6c9af2ae561c7fe519adce91b759b9
[]
no_license
PhoeniX-d/Java
1b37e682bad84f5ce8b8b85899033e0b4154c70d
ec5a002437207b57ec72ee7c63905011eb9ef2a5
refs/heads/master
2021-11-23T10:54:18.443505
2021-11-06T05:08:32
2021-11-06T05:08:32
238,947,856
1
0
null
null
null
null
UTF-8
Java
false
false
1,124
java
import java.util.Scanner; import java.sql.*; public class LowestSalariedEmpDemo { public static void main(String[] args) throws SQLException { java.util.Properties p = new java.util.Properties(); try { java.io.FileInputStream fis = new java.io.FileInputStream(".\\..\\..\\db.properties"); p.load(fis); } catch (Exception e) { e.printStackTrace(); } String jdbc_url = p.getProperty("OracleURL"); String user = p.getProperty("OracleUser"); String pwd = p.getProperty("OraclePwd"); String sql_query = "select * from employee where sal = (select min(sal) from employee)"; try (Connection con = DriverManager.getConnection(jdbc_url, user, pwd)) { Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql_query); if (rs.next()) { System.out.println("\nLowest Salaried Employee Information"); System.out.println("EID\tENAME\tCITY\tSAL"); System.out.println("----------------------------------------------------------------------"); System.out.println( rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getFloat(4)); } } } }
[ "prnv24choudhary@gmail.com" ]
prnv24choudhary@gmail.com
41bc8f8515c256ca50c7e58259351b95b1053aee
b58aa8ead65032e1187cc1b37fc25c3f119b5158
/Aviata/app/src/main/java/com/example/aslan/aviata/DetailActivity.java
5e3198bb601c9608c923c537a2a88f8363dd5c79
[]
no_license
TheStrangeOne/Aviata
8e382306b540d394d2e922847800089f98843535
9ceacab574659c3c6ef30b94a722415ecad8916b
refs/heads/master
2021-01-21T20:01:32.983984
2017-05-23T14:57:21
2017-05-23T14:57:21
92,184,401
0
0
null
null
null
null
UTF-8
Java
false
false
2,659
java
package com.example.aslan.aviata; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; public class DetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); getSupportActionBar().hide(); TextView id = (TextView) findViewById(R.id.ID); TextView flNum = (TextView) findViewById(R.id.flNum); TextView deptAir = (TextView) findViewById(R.id.deptAirport); TextView arrAir = (TextView) findViewById(R.id.arrAirport); TextView deptDate = (TextView) findViewById(R.id.deptDate); TextView arrDate = (TextView) findViewById(R.id.arrDate); TextView status = (TextView) findViewById(R.id.status); TextView duration = (TextView) findViewById(R.id.duration); // TextView s2 = (TextView) findViewById(R.id.student2); // TextView title = (TextView) findViewById(R.id.description); // TextView appr = (TextView) findViewById(R.id.approved); int index = getIntent().getIntExtra( "position", 0 ); Sheets sl = Sheets.getInstance(); ArrayList<SheetObject> al = sl.getData(); SheetObject so = al.get( index ); if ( so != null ) { id.setText(so.id+" "); flNum.setText(so.airlCode+so.flightNum); deptAir.setText(so.depAirport.getName()+"("+so.depAir+")"); arrAir.setText(so.arrAirport.getName()+"("+so.arrAir+")"); deptDate.setText(""+so.depDate); arrDate.setText(""+so.arrDate); if(so.status.equals("A")) status.setText("Active "); else if(so.status.equals("C")) status.setText("Canceled "); else if(so.status.equals("L")) status.setText("Landed "); else if(so.status.equals("S")) status.setText("Scheduled "); else status.setText(so.status+" "); duration.setText(so.duration+"minutes"); /* s1.setText(so.s1First + " " + so.s1Last); s2.setText("School and major: " + so.school+", "+so.major); title.setText("Year of study: " + so.year); appr.setText("E-mail address: " + so.approved);*/ } else { Toast toast = Toast.makeText( this, "No data", Toast.LENGTH_SHORT ); toast.show(); } } }
[ "aslan.assylkhanov@nu.edu.kz" ]
aslan.assylkhanov@nu.edu.kz
0f29cb78783ac99e3b53456c1f24d2629972a389
75427f06a741ea066f690d3e35e292de4eba8c61
/src/main/java/com/ly/lucky/entity/Customer.java
75352f52a6cb17622abcf180b307459408b7d9ff
[]
no_license
18702701497/lucky
52dc49bd48d28a89f6675825f95c66d12941987b
365464a3b38682d9d581727b7ec79060115d5363
refs/heads/master
2023-04-28T12:34:32.697352
2021-05-10T09:05:36
2021-05-10T09:05:36
365,982,219
0
0
null
null
null
null
UTF-8
Java
false
false
887
java
package com.ly.lucky.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import com.ly.lucky.entity.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import java.time.LocalDateTime; /** * <p> * * </p> * * @author liuyang * @since 2021-03-21 */ @Data @EqualsAndHashCode(callSuper = true) public class Customer extends BaseEntity { private static final long serialVersionUID = 1L; @TableId(value = "customer_id", type = IdType.AUTO) private Integer customerId; private String realName; private String sex; private Integer age; private String email; private String phone; private String address; }
[ "18702701497@163.com" ]
18702701497@163.com
d17bea067ff98551a43387053af928c145b12f35
67a06dc0bac8015605f1dec4a05bff44f0fa58c7
/train-data-boot/src/main/java/com/ibm/train/rest/TrainController.java
be200f706b2c7c81b689e99fca6feaf8800a35f0
[]
no_license
sahithi-95/New_Git
d410ff103f4cd7878921d7faccb775013b5c8f8f
23dcf90cfac9f5def019b525cea7804ad6ecd649
refs/heads/master
2023-04-09T02:23:47.305732
2021-04-20T06:12:51
2021-04-20T06:12:51
359,698,779
0
0
null
null
null
null
UTF-8
Java
false
false
1,445
java
package com.ibm.train.rest; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import com.ibm.train.entity.Train; import com.ibm.train.exception.InvalidTrainException; import com.ibm.train.service.TrainService; @RestController public class TrainController { @Autowired private TrainService service; @PostMapping(value = "/train", consumes = "application/json") public String addTrain(@RequestBody Train t) { int code = service.addTrain(t); return "Train added with code: " + code; } @GetMapping(value = "/train/{code}", produces = "application/json") public Train getTrain(@PathVariable("code") int code) { Train t = null; try { t = service.getTrain(code); } catch (InvalidTrainException e) { e.printStackTrace(); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, String.format(e.getMessage())); } return t; } @GetMapping(value = "/trains", produces = "application/json") public Collection<Train> getAll() { return service.getAll(); } }
[ "sahithi2gmail.com" ]
sahithi2gmail.com
ac1aaf6931c8804feecfdf3dd459b8f37b3899a0
5652cd332c46db632f6f4f21a3fbebbaef86ff06
/app/src/test/java/com/example/petagram/ExampleUnitTest.java
ed0b68ac5291114ae996d9af595b9dd58c75f447
[]
no_license
Code-JMJ/PetagramC4S1
a0f08ee8276441e658903f9c7866b905ddd2946d
d50f11ae9356da638d0a276e2e65eff2aceeef34
refs/heads/master
2023-02-11T07:34:21.474229
2021-01-10T18:08:24
2021-01-10T18:08:24
328,446,002
1
0
null
null
null
null
UTF-8
Java
false
false
381
java
package com.example.petagram; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "jheimi1216@gmail.com" ]
jheimi1216@gmail.com
d9e7c71bb84c9f21a2c93e6fd9344ee3d1a48050
281a442401b1e50cf34404cd1be8211ebdd32190
/coffe-os/src/test/java/com/coffe/CoffeOsApplicationTests.java
ce672d8fd332a55a3348b02678d40be734344b5d
[]
no_license
Bruno-H-Moraes/santander-crud-test
8cbec7e03dff06206f93c308cfa8d8fbfc874f54
7ac80974315592afdd5a7f341c51c6c1c4f21d0c
refs/heads/master
2023-03-20T21:02:05.181401
2021-03-14T23:49:24
2021-03-14T23:49:24
345,833,497
0
0
null
null
null
null
UTF-8
Java
false
false
202
java
package com.coffe; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CoffeOsApplicationTests { @Test void contextLoads() { } }
[ "brunohmoraes93@gmail.com" ]
brunohmoraes93@gmail.com
3cbc2c682a4de59665ae3870176d88538579cd09
5c5172b07a333e745bd2f73b694d2929f271c39f
/com.example.demo.dao/src/main/java/com/example/demo/dao/base/BaseDao.java
a4941c8e636e12445dddef4589b5e81d7ea45325
[]
no_license
Fsn40/example
58eb85f274bbc2b01cb661a06371e7830c1bb127
b6b9432fe6e5668b2ec0fca330aa9cbfa245a58c
refs/heads/master
2020-12-02T17:43:05.420596
2017-07-06T09:27:16
2017-07-06T09:27:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
152
java
package com.example.demo.dao.base; public interface BaseDao<T> extends DeleteBaseDao<T>, InsertBaseDao<T>, UpdateBaseDao<T>, SelectBaseDao<T>{ }
[ "fusining40@163.com" ]
fusining40@163.com
f662f888f0d8611ccded10e44ec5bcad69e0ea0e
939bc9b579671de84fb6b5bd047db57b3d186aca
/jdk.javadoc/jdk/javadoc/internal/doclets/toolkit/taglets/BaseTaglet.java
2292c090c6d853c7fa5429ec04d2943313f21a29
[]
no_license
lc274534565/jdk11-rm
509702ceacfe54deca4f688b389d836eb5021a17
1658e7d9e173f34313d2e5766f4f7feef67736e8
refs/heads/main
2023-01-24T07:11:16.084577
2020-11-16T14:21:37
2020-11-16T14:21:37
313,315,578
1
1
null
null
null
null
UTF-8
Java
false
false
4,409
java
/* * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package jdk.javadoc.internal.doclets.toolkit.taglets; import java.util.Set; import javax.lang.model.element.Element; import com.sun.source.doctree.DocTree; import jdk.javadoc.internal.doclets.toolkit.Content; /** * A base class that implements the {@link Taglet} interface. * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> * * @author Jamie Ho */ public class BaseTaglet implements Taglet { /** * The different kinds of place where any given tag may be used. */ enum Site { OVERVIEW, MODULE, PACKAGE, TYPE, CONSTRUCTOR, METHOD, FIELD } protected final String name; private final boolean inline; private final Set<Site> sites; BaseTaglet(String name, boolean inline, Set<Site> sites) { this.name = name; this.inline = inline; this.sites = sites; } /** * Returns true if this {@code Taglet} can be used in constructor documentation. * @return true if this {@code Taglet} can be used in constructor documentation and false * otherwise. */ public final boolean inConstructor() { return sites.contains(Site.CONSTRUCTOR); } /** * Returns true if this {@code Taglet} can be used in field documentation. * @return true if this {@code Taglet} can be used in field documentation and false * otherwise. */ public final boolean inField() { return sites.contains(Site.FIELD); } /** * Returns true if this {@code Taglet} can be used in method documentation. * @return true if this {@code Taglet} can be used in method documentation and false * otherwise. */ public final boolean inMethod() { return sites.contains(Site.METHOD); } /** * Returns true if this {@code Taglet} can be used in overview documentation. * @return true if this {@code Taglet} can be used in method documentation and false * otherwise. */ public final boolean inOverview() { return sites.contains(Site.OVERVIEW); } /** * Returns true if this {@code Taglet} can be used in module documentation. * @return true if this {@code Taglet} can be used in module documentation and false * otherwise. */ public final boolean inModule() { return sites.contains(Site.MODULE); } /** * Returns true if this {@code Taglet} can be used in package documentation. * @return true if this {@code Taglet} can be used in package documentation and false * otherwise. */ public final boolean inPackage() { return sites.contains(Site.PACKAGE); } /** * Returns true if this {@code Taglet} can be used in type documentation (classes or interfaces). * @return true if this {@code Taglet} can be used in type documentation and false * otherwise. */ public final boolean inType() { return sites.contains(Site.TYPE); } /** * Returns true if this {@code Taglet} is an inline tag. * @return true if this {@code Taglet} represents an inline tag and false otherwise. */ public final boolean isInlineTag() { return inline; } /** * Returns the name of this tag. * @return the name of this tag. */ public String getName() { return name; } /** * {@inheritDoc} * @throws UnsupportedTagletOperationException thrown when the method is * not supported by the taglet. */ public Content getTagletOutput(Element element, DocTree tag, TagletWriter writer) { throw new UnsupportedTagletOperationException("Method not supported in taglet " + getName() + "."); } /** * {@inheritDoc} * @throws UnsupportedTagletOperationException thrown when the method is not * supported by the taglet. */ public Content getTagletOutput(Element holder, TagletWriter writer) { throw new UnsupportedTagletOperationException("Method not supported in taglet " + getName() + "."); } }
[ "274534565@qq.com" ]
274534565@qq.com
019a53f29c773dd5cc6d5aeda59b4abee77de8d0
bf873c4f11131f84f6809f2cfb02f7bbad3c3790
/bluemp/com/blue/wxmp/sdk/api/ReturnCode.java
f5a844a4ed7b9e13ad15dcd75271d681599db771
[]
no_license
nagyistge/VMall
924023ddb34c555f56c1ba331d9743f3adcc0b91
0ae98ba3d75c9b6be884be474d47760ffc18cbbe
refs/heads/master
2020-07-03T23:42:50.255046
2015-08-21T07:37:09
2015-08-21T07:37:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,274
java
package com.blue.wxmp.sdk.api; import java.util.HashMap; import java.util.Map; /** * 微信接口全局返回码 */ public class ReturnCode { @SuppressWarnings("serial") private static final Map<Integer, String> errCodeToErrMsg = new HashMap<Integer, String>(){{ put(-1, "系统繁忙"); put(0, "请求成功"); put(40001, "获取access_token时AppSecret错误,或者access_token无效"); put(40002, "不合法的凭证类型"); put(40003, "不合法的OpenID"); put(40004, "不合法的媒体文件类型"); put(40005, "不合法的文件类型"); put(40006, "不合法的文件大小"); put(40007, "不合法的媒体文件id"); put(40008, "不合法的消息类型"); put(40009, "不合法的图片文件大小"); put(40010, "不合法的语音文件大小"); put(40011, "不合法的视频文件大小"); put(40012, "不合法的缩略图文件大小"); put(40013, "不合法的APPID"); put(40014, "不合法的access_token"); put(40015, "不合法的菜单类型"); put(40016, "不合法的按钮个数"); put(40017, "不合法的按钮个数"); put(40018, "不合法的按钮名字长度"); put(40019, "不合法的按钮KEY长度"); put(40020, "不合法的按钮URL长度"); put(40021, "不合法的菜单版本号"); put(40022, "不合法的子菜单级数"); put(40023, "不合法的子菜单按钮个数"); put(40024, "不合法的子菜单按钮类型"); put(40025, "不合法的子菜单按钮名字长度"); put(40026, "不合法的子菜单按钮KEY长度"); put(40027, "不合法的子菜单按钮URL长度"); put(40028, "不合法的自定义菜单使用用户"); put(40029, "不合法的oauth_code"); put(40030, "不合法的refresh_token"); put(40031, "不合法的openid列表"); put(40032, "不合法的openid列表长度"); put(40033, "不合法的请求字符,不能包含\\uxxxx格式的字符"); put(40035, "不合法的参数"); put(40038, "不合法的请求格式"); put(40039, "不合法的URL长度"); put(40050, "不合法的分组id"); put(40051, "分组名字不合法"); put(41001, "缺少access_token参数"); put(41002, "缺少appid参数"); put(41003, "缺少refresh_token参数"); put(41004, "缺少secret参数"); put(41005, "缺少多媒体文件数据"); put(41006, "缺少media_id参数"); put(41007, "缺少子菜单数据"); put(41008, "缺少oauth code"); put(41009, "缺少openid"); put(42001, "access_token超时"); put(42002, "refresh_token超时"); put(42003, "oauth_code超时"); put(43001, "需要GET请求"); put(43002, "需要POST请求"); put(43003, "需要HTTPS请求"); put(43004, "需要接收者关注"); put(43005, "需要好友关系"); put(44001, "多媒体文件为空"); put(44002, "POST的数据包为空"); put(44003, "图文消息内容为空"); put(44004, "文本消息内容为空"); put(45001, "多媒体文件大小超过限制"); put(45002, "消息内容超过限制"); put(45003, "标题字段超过限制"); put(45004, "描述字段超过限制"); put(45005, "链接字段超过限制"); put(45006, "图片链接字段超过限制"); put(45007, "语音播放时间超过限制"); put(45008, "图文消息超过限制"); put(45009, "接口调用超过限制"); put(45010, "创建菜单个数超过限制"); put(45015, "回复时间超过限制"); put(45016, "系统分组,不允许修改"); put(45017, "分组名字过长"); put(45018, "分组数量超过上限"); put(46001, "不存在媒体数据"); put(46002, "不存在的菜单版本"); put(46003, "不存在的菜单数据"); put(46004, "不存在的用户"); put(47001, "解析JSON/XML内容错误"); put(48001, "api功能未授权"); put(50001, "用户未授权该api"); }}; /** * 通过返回码获取返回信息 */ public static String get(int errCode){ String result = errCodeToErrMsg.get(errCode); return result !=null? result : "未知返回码:" + errCode; } }
[ "Administrator@skynethp" ]
Administrator@skynethp
959de161b3f24325266482fc0367b6afd824d8df
a1061e6311865888d329921e9cc07cdb3c5c4da5
/Fibonacci.java
82e520ca326ba864a3852de71c9b3fbf41ab2555
[]
no_license
SNAYi/JavaCode
9a6b5264c76a6e9cf128d1143632dbd9415a203c
38db5649148cbb2b8bd316234329fb0da79c0b51
refs/heads/master
2022-07-10T04:23:21.118191
2019-08-23T15:18:44
2019-08-23T15:18:44
173,422,212
0
0
null
null
null
null
UTF-8
Java
false
false
799
java
/** * */ /** * @auther SNAYi *@describe * @date 2019/5/15 下午 08:23 */ public class Fibonacci { public static void main(String[] args) { int n = Fibonacci(6); System.out.println(n); } //递归实现,下标从1开始 public static int Fibonacci(int n) { int result = 0; if(n <= 0) { return -1; }else if(n == 1||n == 2) { return 1; } else { result = Fibonacci(n - 1) + Fibonacci(n - 2); } return result; } public static int Fibonacci1(int n) { int[] array = new int[100]; array[0] = 1; array[1] = 1; for (int i = 2; i <= n; i++) { array[i] = array[i - 1] + array[i - 2]; } return array[n]; } }
[ "1141176009@qq.com" ]
1141176009@qq.com
dfcd5cbd8b07bbf82a3699d7e4fb4b59e1cec35d
a3b72fe0d8a74cd11e960a846023ba46248a24af
/eclipse-workspace11/HelloWord/src/main/java/com/tansection/programmatic/StudentJDBCTemplate.java
575a35158331d47bcf6af049a47eaa53e4e738c4
[]
no_license
inglepr/WebApp
437d8c655702c767c3f09875beab92def96d3393
d5b243f8294e26781c0452bc92a4b7150eb64025
refs/heads/master
2023-01-12T12:58:21.712637
2019-08-21T04:00:12
2019-08-21T04:00:12
192,723,580
0
0
null
2023-01-07T08:54:11
2019-06-19T11:59:27
TypeScript
UTF-8
Java
false
false
2,237
java
package com.tansection.programmatic; import java.util.List; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; public class StudentJDBCTemplate implements StudentDAO { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; private PlatformTransactionManager transactionManager; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public void create(String name, Integer age, Integer marks, Integer year){ TransactionDefinition def = new DefaultTransactionDefinition(); TransactionStatus status = transactionManager.getTransaction(def); try { String SQL1 = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL1, name, age); // Get the latest student id to be used in Marks table String SQL2 = "select max(id) from Student"; int sid = jdbcTemplateObject.queryForInt( SQL2 ); String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)"; jdbcTemplateObject.update( SQL3, sid, marks, year); System.out.println("Created Name = " + name + ", Age = " + age); transactionManager.commit(status); } catch (DataAccessException e) { System.out.println("Error in creating record, rolling back"); transactionManager.rollback(status); throw e; } return; } public List<StudentMarks> listStudents() { String SQL = "select * from Student, Marks where Student.id=Marks.sid"; List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, new StudentMarksMapper()); return studentMarks; } }
[ "inglepriya95@gmail.com" ]
inglepriya95@gmail.com
69aa49945b735181254f34b45d04661e45387261
f941f90e2835338173af9c229c87a52eef6f9d4e
/src/main/java/de/synyx/tutorials/spring/reactjs/demo/utils/Fetch.java
051932d67afa6cb0df1e30a9fe9095be513979fe
[]
no_license
ufukomer/temp-showcase
3b0081330c3ee3ab0443a500fa45b3c2b08c4c76
8ed1ea511b8a128394e8da4d7f59073f42d3047e
refs/heads/master
2021-01-22T09:12:51.413809
2017-02-14T12:21:01
2017-02-14T12:21:01
81,941,464
2
0
null
null
null
null
UTF-8
Java
false
false
701
java
package de.synyx.tutorials.spring.reactjs.demo.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class Fetch { public String fetch(String uri) throws IOException { URL url = new URL(uri); URLConnection uc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String response; StringBuffer buffer = new StringBuffer(""); while ((response = in.readLine()) != null) { buffer.append(response + "\n"); } in.close(); return buffer.toString(); } }
[ "ufukomer@gmail.com" ]
ufukomer@gmail.com
9f1b881a96c9a5e2fcf46243be17c319d7d4c903
d40c84afc557191eac6e14a37cc5d714620b8ce9
/src/main/java/twilightforest/world/layer/GenLayerTFBiomeBorders.java
02cdcb47d70bcc2b4f0707a41e8bdaadacbe55e0
[]
no_license
Kerzachek/TwilightForest
a1b642aa40792658667ef2cdeb95556c4a3283c6
c782e6a14e6bf01977318884fa7efebf4631d299
refs/heads/master
2021-12-09T06:56:21.550342
2016-05-02T20:37:23
2016-05-02T20:37:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,232
java
package twilightforest.world.layer; import net.minecraft.world.gen.layer.GenLayer; import net.minecraft.world.gen.layer.IntCache; import twilightforest.biomes.TFBiomeBase; public class GenLayerTFBiomeBorders extends GenLayer { public GenLayerTFBiomeBorders(long l, GenLayer genlayer) { super(l); this.field_75909_a = genlayer; } public int[] func_75904_a(int x, int z, int width, int depth) { int nx = x - 1; int nz = z - 1; int nwidth = width + 2; int ndepth = depth + 2; int[] input = this.field_75909_a.func_75904_a(nx, nz, nwidth, ndepth); int[] output = IntCache.func_76445_a(width * depth); for (int dz = 0; dz < depth; ++dz) { for (int dx = 0; dx < width; ++dx) { int right = input[dx + 0 + (dz + 1) * nwidth]; int left = input[dx + 2 + (dz + 1) * nwidth]; int up = input[dx + 1 + (dz + 0) * nwidth]; int down = input[dx + 1 + (dz + 2) * nwidth]; int center = input[dx + 1 + (dz + 1) * nwidth]; if (this.onBorder(TFBiomeBase.tfLake.field_76756_M, center, right, left, up, down)) { output[dx + dz * width] = TFBiomeBase.fireflyForest.field_76756_M; } else if (this.onBorder(TFBiomeBase.clearing.field_76756_M, center, right, left, up, down)) { output[dx + dz * width] = TFBiomeBase.oakSavanna.field_76756_M; } else if (this.onBorder(TFBiomeBase.deepMushrooms.field_76756_M, center, right, left, up, down)) { output[dx + dz * width] = TFBiomeBase.mushrooms.field_76756_M; } else if (this.onBorder(TFBiomeBase.glacier.field_76756_M, center, right, left, up, down)) { output[dx + dz * width] = TFBiomeBase.tfSnow.field_76756_M; } else { output[dx + dz * width] = center; } } } return output; } boolean onBorder(int biome, int center, int right, int left, int up, int down) { return center != biome ? false : (right != biome ? true : (left != biome ? true : (up != biome ? true : down != biome))); } }
[ "pturchan@yahoo.com" ]
pturchan@yahoo.com
f5ef1247bf19de5d5e2fa27cf938c103d281f419
b22b0b492065611e8915aad23b18f68c9aeabd97
/app/src/main/java/com/eburg/sudokusolver/database/DBAdapter.java
24d57eecff4aad76009951e4661504efa64c8232
[]
no_license
evanBurg/AndroidSudokuSolver
dd1e1f9ab23dc34e0c9df5829d725f4e062897af
c0d5470cc2f336325ac1856e123919699e1bba35
refs/heads/master
2020-09-12T19:25:40.001868
2019-12-03T22:53:06
2019-12-03T22:53:06
222,526,084
0
0
null
2019-12-03T20:06:13
2019-11-18T19:20:45
Java
UTF-8
Java
false
false
6,207
java
package com.eburg.sudokusolver.database; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.content.Context; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.eburg.sudokusolver.models.Solution; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import static com.eburg.sudokusolver.database.Utilities.flattenArray; import static com.eburg.sudokusolver.database.Utilities.inflateArray; public class DBAdapter { public interface Listener { void update(); } static final String KEY_ROWID = "_id"; static final String KEY_PROBLEM = "problem"; static final String KEY_SOLUTION = "solution"; static final String KEY_IMAGE = "image"; static final String KEY_DATE = "date"; static final String TAG = "SudokuSolverDatabase"; static final String DATABASE_NAME = "SudokuSolver"; static final String DATABASE_TABLE = "previouspuzzles"; static final int DATABASE_VERSION = 6; ArrayList<Listener> listeners; static final String DATABASE_CREATE = String.format( "create table if not exists %s (" + "%s integer primary key autoincrement," + "%s TEXT not null," + "%s TEXT not null," + "%s TEXT not null," + "%s TEXT not null" + ")", DATABASE_TABLE, KEY_ROWID, KEY_PROBLEM, KEY_SOLUTION, KEY_IMAGE, KEY_DATE ); final Context context; DatabaseHelper DBHelper; SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; listeners = new ArrayList<>(); DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(String.format("DROP TABLE IF EXISTS %s", DATABASE_TABLE)); onCreate(db); } } public DBAdapter open(Listener listener) throws SQLException { db = DBHelper.getWritableDatabase(); DBHelper.onCreate(db); listeners.add(listener); return this; } public void close() { DBHelper.close(); } public long insertSolution(Solution solution) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_PROBLEM, flattenArray(solution.getProblem())); initialValues.put(KEY_SOLUTION, flattenArray(solution.getSolution())); initialValues.put(KEY_IMAGE, solution.getImage().toString()); Calendar cal = Calendar.getInstance(); TimeZone tz = cal.getTimeZone(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset df.setTimeZone(tz); String nowAsISO = df.format(new Date()); initialValues.put(KEY_DATE, nowAsISO); long id = db.insert(DATABASE_TABLE, null, initialValues); updateListeners(); return id; } public boolean deleteSolution(long rowId) { boolean success = db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; updateListeners(); return success; } public boolean deleteAllSolutions() { boolean success = db.delete(DATABASE_TABLE, KEY_ROWID + "> -1", null) > 0; updateListeners(); return success; } public ArrayList<Solution> getAllSolutions() { ArrayList<Solution> solutions = new ArrayList<>(); Cursor mCursor = db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_PROBLEM, KEY_SOLUTION, KEY_IMAGE, KEY_DATE}, null, null, null, null, null); while(mCursor.moveToNext()){ solutions.add(new Solution( mCursor.getInt(0), inflateArray(mCursor.getString(1)), inflateArray(mCursor.getString(2)), mCursor.getString(3), mCursor.getString(4) )); } mCursor.close(); return solutions; } public Solution getSolution(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_PROBLEM, KEY_SOLUTION, KEY_IMAGE, KEY_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); }else{ return null; } return new Solution( mCursor.getInt(0), inflateArray(mCursor.getString(1)), inflateArray(mCursor.getString(2)), mCursor.getString(3), mCursor.getString(4) ); } public boolean updateSolution(Solution solution) { ContentValues args = new ContentValues(); args.put(KEY_PROBLEM, flattenArray(solution.getProblem())); args.put(KEY_SOLUTION, flattenArray(solution.getSolution())); args.put(KEY_IMAGE, solution.getImage().toString()); boolean success = db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + solution.getId(), null) > 0; updateListeners(); return success; } private void updateListeners(){ for(Listener listener : listeners){ listener.update(); } } }
[ "burgenator@hotmail.com" ]
burgenator@hotmail.com
3cacfd541797c6f1e22121d091a5b7a5738fa639
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/8/8_bbdf3702f3ef65d1b31fc32cc613f71262e4e259/MultipleException/8_bbdf3702f3ef65d1b31fc32cc613f71262e4e259_MultipleException_t.java
a46f91cb13954da64d2b0855ddc2a5d605050530
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
3,800
java
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package com.metamatrix.api.exception; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; /** * Exception that represents the occurrence of multiple exceptions. */ public class MultipleException extends Exception implements Externalizable { /** *The set of Throwable instances that make up this exception * @link aggregation * @associates <b>java.lang.Throwable</b> * @supplierCardinality 1..* */ private List throwablesList = null; /** An error code. */ private String code; /** * No-arg Constructor */ public MultipleException() { super(); } /** * Construct an instance with the set of exceptions and error message * specified. * * @param throwables the set of exceptions that is to comprise * this exception * @param message The error message */ public MultipleException( Collection throwables, String message ) { this( throwables, null, message ); } /** * Construct an instance with the set of exceptions, and an error code and * message specified. * * @param throwables the set of exceptions that is to comprise * this exception * @param message The error message * @param code The error code */ public MultipleException( Collection<Throwable> throwables, String code, String message ) { super( message ); this.throwablesList = Collections.unmodifiableList(new ArrayList<Throwable>(throwables)); setCode( code ); } /** * Get the code for this exception. * @return the code value */ public String getCode(){ return code; } /** * Set the code for this exception. * @param code the new code value */ public void setCode(String code){ this.code = code; } /** * Obtain the set of exceptions that comprise this exception. * @return the set of Throwable instances that comprise this exception. */ public List getExceptions() { return this.throwablesList; } //## JDBC4.0-begin ## @Override //## JDBC4.0-end ## public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { this.code = (String)in.readObject(); this.throwablesList = ExceptionHolder.toThrowables((List<ExceptionHolder>)in.readObject()); } //## JDBC4.0-begin ## @Override //## JDBC4.0-end ## public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(code); out.writeObject(ExceptionHolder.toExceptionHolders(throwablesList)); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
923533c1de93a76394eddd11df178ad24f37d015
aae77f355cd8cf78fb3b219f94fafff2254cdc13
/FoodOrderingApp-service/src/main/java/com/upgrad/FoodOrderingApp/service/entity/StateEntity.java
e28742665e127b42f49b8b63d36cbcf7efd466fe
[]
no_license
shivamfet/FoodOrderingApp
646ccf1ba3db02fe812d283433a7b952ec6030b5
2815a734dba2756e5846f8628a2eb37c86da50f8
refs/heads/main
2023-03-02T08:15:26.146087
2021-02-17T06:05:33
2021-02-17T06:05:33
335,822,818
0
0
null
null
null
null
UTF-8
Java
false
false
1,665
java
package com.upgrad.FoodOrderingApp.service.entity; import javax.persistence.*; import javax.validation.constraints.Size; import java.util.List; @Entity @Table(name = "state" , schema = "public") @NamedQueries ( { @NamedQuery(name = "getAllStates" , query = "select s from StateEntity s"), @NamedQuery(name = "getStateByUuid" , query = "select s from StateEntity s where s.uuid = :uuid") } ) public class StateEntity { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) Integer id; @Column(name = "uuid") @Size(max = 200) String uuid; @Column(name = "state_name") @Size(max = 30) String stateName; @OneToMany(mappedBy = "stateEntity" , cascade = CascadeType.REMOVE , fetch = FetchType.LAZY) List<AddressEntity> addressEntityList; public StateEntity() { } public StateEntity(String uuid , String stateName) { this.uuid = uuid; this.stateName = stateName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } public List<AddressEntity> getAddressEntityList() { return addressEntityList; } public void setAddressEntityList(List<AddressEntity> addressEntityList) { this.addressEntityList = addressEntityList; } }
[ "shivamfet@gmail.com" ]
shivamfet@gmail.com
f28c0899e6d526c846f4042bd843f507c30f24c0
82535c063725342546eafb8b80ab34eddd66ba75
/app/src/main/java/com/example/colliensepodder/parentscare/MyService.java
9252db43d43839551a20af26a12bf6c2e034d7a1
[]
no_license
Colliense1/ParentsCare
af6ba22603dc7358ebb869eeba94e287ab6c520a
1cd1fd1769171483ee6d923379dd97b699193d73
refs/heads/master
2020-04-04T10:04:54.309527
2019-01-20T10:18:19
2019-01-20T10:18:19
155,837,280
0
0
null
null
null
null
UTF-8
Java
false
false
899
java
package com.example.colliensepodder.parentscare; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { YourTask(intent, flags); return Service.START_STICKY; } @Override public void onDestroy() { super.onDestroy(); // Intent iuu = new Intent(this, MainActivity.class); // startActivity(iuu); Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor"); sendBroadcast(broadcastIntent); } private void YourTask(final Intent intent, final int ff) { //showNotification(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
[ "colliensepodder25@gmail.com" ]
colliensepodder25@gmail.com
8bf2c61abbe09acb945de82829691879e257297a
549569fa0ee30168425418166282b0608ecda3f1
/src/jonablock/TransactionOutput.java
b8303128c17bffb13491f54456255ff6551eb1a6
[]
no_license
CSELINGUA/jonablock
6329a93dce11c40b996c9273e33b1c0bf4ef73df
12bcb6bc7bf674c6233193b9ce9be15be3cffbef
refs/heads/master
2023-08-01T02:00:23.311621
2021-09-26T19:14:05
2021-09-26T19:14:05
410,640,221
0
0
null
null
null
null
UTF-8
Java
false
false
901
java
package jonablock; import java.security.PublicKey; public class TransactionOutput { public String id; public PublicKey recipient; //also known as the owner of these data public float value; // the amount of coin / values they own public String parentTransactionId; // the id of the transaction this output was created in public TransactionOutput(PublicKey recipient, float value, String parentTransactionId) { this.recipient = recipient; this.value = value; this.parentTransactionId = parentTransactionId; this.id = StringUtil.applylSha256(StringUtil.getStringFromKey(recipient) + Float.toString(value) + parentTransactionId); } //Check if coin belongs to you public boolean isMine (PublicKey publicKey){ return (publicKey == recipient); } //Returns true if new transaction could be created }
[ "42624373+CSELINGUA@users.noreply.github.com" ]
42624373+CSELINGUA@users.noreply.github.com
4ab2429b879ed8a597e85fb00dd0fff6919d2cd6
8310ef2307ba08390628faf3c8191eeb5621a863
/com/sun/speech/freetts/diphone/DiphonePitchmarkGenerator.java
d23771efe9000b83a99b9a05c0c93a2d0c260a6f
[]
no_license
jsimon963/JeffsTest
b7a2d106637684738a1ca5feda01a08e11b74f3a
68e02fe99603ef8a0ef1a99d32debf372780fbd5
refs/heads/master
2021-04-28T16:01:43.751505
2018-03-07T01:55:56
2018-03-07T01:55:56
122,005,468
0
0
null
null
null
null
UTF-8
Java
false
false
6,036
java
/** * Portions Copyright 2001 Sun Microsystems, Inc. * Portions Copyright 1999-2001 Language Technologies Institute, * Carnegie Mellon University. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. */ package com.sun.speech.freetts.diphone; import com.sun.speech.freetts.FeatureSet; import com.sun.speech.freetts.Item; import com.sun.speech.freetts.relp.LPCResult; import com.sun.speech.freetts.UtteranceProcessor; import com.sun.speech.freetts.Utterance; import com.sun.speech.freetts.Relation; import com.sun.speech.freetts.ProcessException; import com.sun.speech.freetts.relp.SampleInfo; /** * Calculates pitchmarks. This is an utterance processor that expects * the utterance to have a target relation. It will create an * LPCResult and add it to the utterance based upon features of the * target relation. * * @see LPCResult * @see Relation * @see SampleInfo */ public class DiphonePitchmarkGenerator implements UtteranceProcessor { /** * Generates the LPCResult for this utterance. * * @param utterance the utterance to process * * @throws ProcessException if an error occurs while processing * the utterance * @throws IllegalStateException if the given utterance has no * relation named Relation.TARGET or a feature named * SampleInfo.UTT_NAME */ public void processUtterance(Utterance utterance) throws ProcessException { // precondition that must be satisfied Relation targetRelation = utterance.getRelation(Relation.TARGET); if (targetRelation == null) { throw new IllegalStateException ("DiphonePitchmarkGenerator: Target relation does not exist"); } SampleInfo sampleInfo; sampleInfo = (SampleInfo) utterance.getObject(SampleInfo.UTT_NAME); if (sampleInfo == null) { throw new IllegalStateException ("DiphonePitchmarkGenerator: SampleInfo does not exist"); } float pos, lpos = 0, f0, m = 0; final float lf0 = 120; double time = 0; int pitchMarks = 0; // how many pitch marks LPCResult lpcResult; IntLinkedList timesList = new IntLinkedList(); // first pass to count how many pitch marks will be required for (Item targetItem = targetRelation.getHead(); targetItem != null; targetItem = targetItem.getNext()) { FeatureSet featureSet = targetItem.getFeatures(); pos = featureSet.getFloat("pos"); f0 = featureSet.getFloat("f0"); if (time == pos) { continue; } m = (f0-lf0)/pos; for (; time < pos; pitchMarks++) { time += 1/(lf0 + (time * m)); // save the time value in a list timesList.add((int) (time * sampleInfo.getSampleRate())); } } lpcResult = new LPCResult(); // resize the number of frames to the number of pitchmarks lpcResult.resizeFrames(pitchMarks); pitchMarks = 0; int[] targetTimes = lpcResult.getTimes(); // second pass puts the values in timesList.resetIterator(); for (; pitchMarks < targetTimes.length; pitchMarks++) { targetTimes[pitchMarks] = timesList.nextInt(); } utterance.setObject("target_lpcres", lpcResult); } /** * Returns a string representation of this object. * * @return a string representation of this object */ public String toString() { return "DiphonePitchmarkGenerator"; } } /** * Represents a linked list with each node of the list storing * a primitive int data type. Unlike the java.util.LinkedList, it avoids * the need to wrap the float number in a Float object. This avoids * unnecessary object creation, and is therefore faster and saves memory. * However, it does not implement the java.util.List interface. * * This linked list is used as a replacement for a simple array of * ints. Certain performance critical loops have had performance * issues due to the overhead associated with array index bounds * checking performed by the VM. Using this type of data structure * allowed the checking to be bypassed. Note however that we've seen * great improvement in compiler performance in this area such that we * may be able to revert to using an array without any performance * impact. * * [[[ TODO look at replacing this with a simple int array ]]] */ class IntLinkedList { private IntListNode head = null; private IntListNode tail = null; private IntListNode iterator = null; /** * Constructs an empty IntLinkedList. */ public IntLinkedList() { head = null; tail = null; iterator = null; } /** * Adds the given float to the end of the list. * * @param val the float to add */ public void add(int val) { IntListNode node = new IntListNode(val); if (head == null) { head = node; tail = node; } else { tail.next = node; tail = node; } } /** * Moves the iterator to point to the front of the list. */ public void resetIterator() { iterator = head; } /** * Returns the next float in the list, advances the iterator. * The <code>hasNext()</code> method MUST be called before calling * this method to check if the iterator is point to null, * otherwise NullPointerException will be thrown. * * @return the next value */ public int nextInt() { int val = iterator.val; if (iterator != null) { iterator = iterator.next; } return val; } /** * Checks if there are more elements for the iterator. * * @return <code>true</code> if there are more elements; * otherwise <code>false</code> */ public boolean hasNext() { return (iterator != null); } } /** * Represents a node for the IntList */ class IntListNode { int val; IntListNode next; /** * Creates a node that wraps the given value. * * @param val the value to be contained in the list */ public IntListNode(int val) { this.val = val; next = null; } }
[ "jeffery.simon@va.gov" ]
jeffery.simon@va.gov
5217c7732856fc0abb7d24787cbb570e974c27f1
cb54af5d404bfbd9481f11151e344900be0f7520
/wires-support/src/main/java/fr/cla/wires/support/functional/Indexed.java
c2adee24ce85f5dd6fb0a157cd1b34bdfc821ae2
[ "Apache-2.0" ]
permissive
vandekeiser/wires
cc76afd398a227e42cc287ef73dae78359a78cc6
b388f3436f4a062f19907289085fd99e112d171a
refs/heads/master
2021-10-08T13:28:10.560267
2018-12-12T20:16:27
2018-12-12T20:16:27
110,474,565
1
1
null
null
null
null
UTF-8
Java
false
false
2,170
java
package fr.cla.wires.support.functional; import fr.cla.wires.support.oo.AbstractValueObject; import java.util.Arrays; import java.util.List; //@formatter:off /** * A value combined with an index, indicating its position in an ordered sequence. * * @param <T> The type of the indexed value. */ public final class Indexed<T> extends AbstractValueObject<Indexed<T>> { /** * Combine an index and a value into an indexed value. * @param index The index of the value. * @param value The value indexed. * @param <T> The type of the value. * @return The indexed value. */ public static <T> Indexed<T> index(int index, T value) { return new Indexed<>(index, value); } private final int index; private final T value; private Indexed(int index, T value) { super(indexedOfT()); this.index = index; this.value = value; } /** * @return The indexed value. */ public int getIndex() { return index; } /** * @return The value indexed. */ public T getValue() { return value; } @Override public String toString() { return String.format("{ index: %d, value: %s }", index, value); } @Override protected List<Object> equalityCriteria() { return Arrays.asList(this.index, this.value); } private static <T> Class<Indexed<T>> indexedOfT() { Class<?> unbounded = Indexed.class; //Doesn't matter, as this is only used in AbstractValueObject::equals, for the isInstance check. //This unchecked cast means that Indexed of all types are compared together without ClassCastException, // but this doesn't matter because Indexed with equal values and indices should be equal. //This is proved by IndexedTest::should_not_get_classcast_when_calling_equals_on_indexeds_of_different_types // and IndexedTest::equals_should_be_true_for_indexeds_of_different_types_but_same_value_and_index @SuppressWarnings("unchecked") Class<Indexed<T>> indexedOfT = (Class<Indexed<T>>) unbounded; return indexedOfT; } } //@formatter:on
[ "laurent_claisse@hotmail.fr" ]
laurent_claisse@hotmail.fr
0e3736e163bb2ad908573540eba9d6818a1fca02
27b052c54bcf922e1a85cad89c4a43adfca831ba
/src/AP.java
b35544d01bdf9aefc5c88aa38a0779122fdc4cc8
[]
no_license
dreadiscool/YikYak-Decompiled
7169fd91f589f917b994487045916c56a261a3e8
ebd9e9dd8dba0e657613c2c3b7036f7ecc3fc95d
refs/heads/master
2020-04-01T10:30:36.903680
2015-04-14T15:40:09
2015-04-14T15:40:09
33,902,809
3
0
null
null
null
null
UTF-8
Java
false
false
1,992
java
public enum AP { public final int s; public final int t; public final int u; static { AP[] arrayOfAP = new AP[18]; arrayOfAP[0] = a; arrayOfAP[1] = b; arrayOfAP[2] = c; arrayOfAP[3] = d; arrayOfAP[4] = e; arrayOfAP[5] = f; arrayOfAP[6] = g; arrayOfAP[7] = h; arrayOfAP[8] = i; arrayOfAP[9] = j; arrayOfAP[10] = k; arrayOfAP[11] = l; arrayOfAP[12] = m; arrayOfAP[13] = n; arrayOfAP[14] = o; arrayOfAP[15] = p; arrayOfAP[16] = q; arrayOfAP[17] = r; v = arrayOfAP; } private AP(int paramInt1, int paramInt2, int paramInt3) { this.s = paramInt1; this.t = paramInt2; this.u = paramInt3; } public static AP a(int paramInt) { AP[] arrayOfAP = a(); int i1 = arrayOfAP.length; int i2 = 0; AP localAP; if (i2 < i1) { localAP = arrayOfAP[i2]; if (localAP.t != paramInt) {} } for (;;) { return localAP; i2++; break; localAP = null; } } public static AP[] a() { return (AP[])v.clone(); } public static AP b(int paramInt) { AP[] arrayOfAP = a(); int i1 = arrayOfAP.length; int i2 = 0; AP localAP; if (i2 < i1) { localAP = arrayOfAP[i2]; if (localAP.s != paramInt) {} } for (;;) { return localAP; i2++; break; localAP = null; } } public static AP c(int paramInt) { AP[] arrayOfAP = a(); int i1 = arrayOfAP.length; int i2 = 0; AP localAP; if (i2 < i1) { localAP = arrayOfAP[i2]; if (localAP.u != paramInt) {} } for (;;) { return localAP; i2++; break; localAP = null; } } } /* Location: C:\Users\dreadiscool\Desktop\tools\classes-dex2jar.jar * Qualified Name: AP * JD-Core Version: 0.7.0.1 */
[ "paras@protrafsolutions.com" ]
paras@protrafsolutions.com
d645e7467a19c51e247c211976420458bf3ae93c
f6a5b6d133d251a8b374cfe5c8c5249f856f8f28
/src/tsk/KraininStat.java
b92f2d7a7a39673c6110517a7396756d61be6489
[]
no_license
umass-forensics/DEX-forensics
0f2f4a86ed77c20e4829d0727611b8b6178dabd8
9994e2e479e38d718560a2b3c4a226df32a71058
refs/heads/master
2021-01-01T15:44:10.554485
2014-09-14T15:52:37
2014-09-14T15:52:37
24,026,012
1
0
null
null
null
null
UTF-8
Java
false
false
7,030
java
package tsk; import jargs.gnu.CmdLineParser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import org.jdom.Element; import org.jdom.xpath.XPath; import dex.Dex; import dex.Out; import disk.DiskImageEntry; import ntfs.MasterFileTable; public class KraininStat { private final static String COMMAND = "java ntfs.NTFSParser"; private static void usage (String err) { if (err!=null) Out.err("\nERROR: "+err); Out.err("\nUsage:\njava tsk.KraininStat [istat options] [OPTIONS] disk_image mftentry"); Out.err("Output the DEX format of a particular MFT entry; write dex to stdout."); Out.err("\t[istat options]:"); Out.err("\t\t-o offset (in sectors)"); Out.err("\t\tno other istat options are currently supported."); Out.err(""); Out.err("\tOPTIONS:"); Out.err("\t\t-h, --help: display this help file"); Out.err("\t\t--input-dex INFILE: read from input dex INFILE; output dex"); Out.err("\t\t will include all data from INFILE"); Out.err("\t\t--output-dex OUTFILE: write DEX to OUTFILE"); Out.err("\nDex wrapper for istat\nauthors: Brian Levine, Marc Liberatore (c) 2009"); System.exit(1); } public static void main(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option outputXml = parser.addStringOption("output-dex"); CmdLineParser.Option inputXml = parser.addStringOption("input-dex"); CmdLineParser.Option offset = parser.addIntegerOption('o',"offset"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { usage(e.getMessage()); } Boolean helpRequested = (Boolean)parser.getOptionValue(help, Boolean.FALSE); if (helpRequested) { usage(null); } int offsetSector = (Integer)parser.getOptionValue(offset, new Integer(0)); String[] otherArgs = parser.getRemainingArgs(); if (otherArgs.length != 2) { usage("Exactly two command line arguments required."); } String imageFilename = otherArgs[0]; String mftEntry =otherArgs[1]; String commandLine = COMMAND + " -o " + offsetSector+ " -n " + mftEntry + " " +imageFilename ; Out.err(commandLine+"\n"); if ( !(new File(imageFilename).exists())) { usage("File " + imageFilename + " not found."); } Dex evidence = null; MasterFileTable masterFileTable = null; String xpathToDiskImage = null; String xpathToPartitionTable = null; String inputXmlFilename = (String)parser.getOptionValue(inputXml); if (inputXmlFilename == null) { evidence = new Dex(); String md5sum = Dex.computeMD5(imageFilename); DiskImageEntry d = new DiskImageEntry(evidence.getRoot(), imageFilename, md5sum); xpathToDiskImage = d.getXPath(); } else { evidence = new Dex(inputXmlFilename); //TODO look for either a DiskImage or a VolumeFile String md5sum = Dex.computeMD5(imageFilename); xpathToDiskImage = "/DEXroot/DiskImage[@MD5Sum=\"" + md5sum + "\"]"; XPath xpath = XPath.newInstance(xpathToDiskImage); Element e = (Element)xpath.selectSingleNode(evidence.getRoot()); if (e == null) { usage("Specified disk image not found in dex INFILE."); } if (offsetSector > 0) { xpathToPartitionTable = "/DEXroot/PartitionTable/Volume[StartSector=\"" + offsetSector + "\"]"; XPath x = XPath.newInstance(xpathToPartitionTable); Element f = (Element)x.selectSingleNode(evidence.getRoot()); if (f == null) { usage("No partition at specified offset."); } } } masterFileTable = new MasterFileTable(evidence.getRoot()); if (xpathToPartitionTable == null) { masterFileTable.setParentPointer(xpathToDiskImage); } else { masterFileTable.setParentPointer(xpathToPartitionTable); } //Perhaps this info should go inside the entry start tag, not the MFT start tag. //But we are assuming that istat is creating all entry xml in this MFT masterFileTable.addInformationSource("Mike Krainin's MFT Parser", commandLine); exec_command(commandLine); process_exec_output(masterFileTable, mftEntry); String outputXmlFilename = (String)parser.getOptionValue(outputXml); if (outputXmlFilename == null) { evidence.dump(System.out); } else { System.err.println("dumping to "+outputXmlFilename); evidence.dump(new BufferedWriter(new FileWriter(outputXmlFilename))); } } static Scanner exec_output; private static void exec_command(String command) { Process p = null; try { p = Runtime.getRuntime().exec(command); } catch (IOException ex) { ex.printStackTrace(); } exec_output = new Scanner(p.getInputStream()); //exec_output.useDelimiter("\n"); } private static void process_exec_output(MasterFileTable mftElement,String entryAddress) { Element entry = mftElement.addMftEntry(entryAddress, "SKIPPING-"+entryAddress); Element enclosing = null; String pattern= ""; String attName = ""; Element runListAtt = new Element("Att"); String runListResident = ""; entry.addContent(runListAtt); exec_output.useDelimiter("\\n"); while (exec_output.hasNext(".*")){ pattern="Type: (\\$.*) \\(.+Resident Size: (\\d+)"; if (exec_output.hasNext(pattern)) { exec_output.next(pattern); attName = exec_output.match().group(1).replaceAll("\\s", "").replaceAll("\\$", ""); System.err.println("value: "+attName+"Attribute"); enclosing = new Element(attName); entry.addContent(enclosing); Element innerElement = new Element(attName); innerElement.setAttribute("Resident","Resident"); runListAtt.addContent(innerElement); } else { pattern="Type: (\\$.*) \\(.+Non-Resident"; if (exec_output.hasNext(pattern)) { exec_output.next(pattern); attName = exec_output.match().group(1).replaceAll("\\s", "").replaceAll("\\$", ""); System.err.println("value: "+attName+"Attribute"); enclosing = new Element(attName); entry.addContent(enclosing); runListResident = "Non-Resident"; } else { pattern="\\tRun List: (.+)"; if (exec_output.hasNext(pattern)) { exec_output.next(pattern); Element innerElement = new Element(attName); innerElement.addContent(exec_output.match().group(1)); innerElement.setAttribute("Resident",runListResident); runListAtt.addContent(innerElement); } else { pattern="([^:]+):(.*)"; if (exec_output.hasNext(pattern)) { exec_output.next(pattern); String tmp = exec_output.match().group(1).replaceAll("\\s", ""); System.err.println("entry found: "+tmp); //System.err.println("time: "+exec_output.match().group(1)+":: "+exec_output.match().group(2)); Element innerElement = new Element(tmp); innerElement.addContent(exec_output.match().group(2)); enclosing.addContent(innerElement); } } } } System.err.println(entry.getChildren()); } } }
[ "brian@cs.umass.edu" ]
brian@cs.umass.edu
7fcde3bcc7bea4935d8c863f29ef028734513cba
9e680e51b562bc9da204e02a82637869ad8bd407
/src/main/java/com/codegym/model/MailBox.java
2c2d5e566be9ca90404a014c62c5a6a201a1c42a
[]
no_license
ngocqui196/mailbox
9cb4cd2c051ba143d4d5e3654717b4fd8dd6a496
6dd77a90bceacee8e088507e7df270b56244b70e
refs/heads/master
2023-03-01T17:00:20.287901
2021-02-05T05:20:35
2021-02-05T05:20:35
336,171,964
0
0
null
null
null
null
UTF-8
Java
false
false
1,028
java
package com.codegym.model; public class MailBox { private String language; private int size; private boolean spamfilter; private String signature; public MailBox() { } public MailBox(String language, int size, boolean spamfilter, String signature) { this.language = language; this.size = size; this.spamfilter = spamfilter; this.signature = signature; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public boolean isSpamfilter() { return spamfilter; } public void setSpamfilter(boolean spamfilter) { this.spamfilter = spamfilter; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } }
[ "ngocqui196" ]
ngocqui196
4f696d1814f4dda3e450c9acdc6dc65c3500d9cd
04466e52222819a5d6be7bae288cc8452693f3ad
/week-07/day-02_Streams/Exercise7.java
6ee4d1d0e6fa3d388e126044e2d2451c9b4a4965
[]
no_license
lorinczkinga/lorinczkinga
e9cc7f912f15a60fd895b659312c0e0dec01dd4f
a96ea9d80f76ac592d9b8b1d775f2d1134cfdd17
refs/heads/master
2020-06-07T23:18:18.528714
2018-08-23T18:40:14
2018-08-23T18:40:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
public class Exercise7 { public static void main(String[] args) { String somethingString = "sssFGjtSjN"; somethingString.chars() .map(x -> ((int)somethingString.chars().filter(c -> (char) c == (char) x).count())) .forEach(System.out::println); } }
[ "lorincz.kinga1991@gmail.com" ]
lorincz.kinga1991@gmail.com
b59ae6da8c9bc7db444121a76cd363055958cb8c
08a71117ddc2791b6f64140cd9642e3067523d9e
/admin/src/main/java/oneEco/web/AccountController.java
319358ab852a9da2c6fc1d4587b8f4d328433e0f
[]
no_license
kjy1111/1eco.metaverse.admin
6e5d845545a1c6f5e7d134e23c59496e2d6bea91
32b38505ef2b28226b5b9ed71ad3156eb03d4a9c
refs/heads/main
2023-08-26T17:49:06.537385
2021-10-25T06:08:50
2021-10-25T06:08:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,394
java
package oneEco.web; import com.google.common.base.Strings; import grinbi.common.model.JsonObject; import grinbi.configurations.SessionListener; import grinbi.message.MessageSourceWrapper; import grinbi.utility.SessionCookieUtil; import oneEco.model.logical.OprtrLoginModel; import oneEco.model.physical.BbscttModel; import oneEco.model.physical.OprtrModel; import oneEco.service.OprtrService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; @Controller @RequestMapping(value = "/admin/account") public class AccountController { @Autowired private OprtrService oprtrService; @Autowired private MessageSourceWrapper messageSourceWrapper; @ResponseBody @RequestMapping(value = "/login.do", method = RequestMethod.POST) public JsonObject login(@Valid OprtrLoginModel loginModel, Errors errors, HttpServletRequest request, HttpSession session) throws Exception { JsonObject jo = new JsonObject(); SessionCookieUtil.removeSessionAttribute(request, this.messageSourceWrapper.getMessage("session.name")); SessionCookieUtil.removeSessionAttribute(request, "roleList"); OprtrModel oprtrModel = this.oprtrService.login(loginModel); if (oprtrModel != null) { SessionListener.login(loginModel.getUserid()); oprtrModel.setUserid(loginModel.getUserid()); session.setAttribute(this.messageSourceWrapper.getMessage("session.name"), oprtrModel); jo.IsSucceed = true; if (Strings.isNullOrEmpty(request.getParameter("returnUrl"))){ jo.RedirectUrl = "/page.do?pageid=N-01"; }else { jo.RedirectUrl = request.getParameter("returnUrl"); } // 로그인 후에 반드시 한번 호출해 주어야 한다. this.oprtrService.getRoles(); } else { jo.IsSucceed = false; jo.Message = "로그인에 실패 하였습니다."; } return jo; } }
[ "toskf072@gmail.com" ]
toskf072@gmail.com
ecc266e463b03f5b50f65a1367bffd26d94cdb9c
090bc22affd14b69ed0fe6f5b0fa4a06db53d7dd
/src/dialog/JSaveAsDialog.java
2d8584557101e905102a49682646122f10be2e8b
[]
no_license
VincentBonnemains/OOTP3
7b4a382af245f957b7359ed2e9f4cb927e604867
f855d15f04fbafb015723bee0d6c663a0b509273
refs/heads/master
2021-01-10T14:34:40.810945
2015-11-22T19:19:08
2015-11-22T19:19:08
44,189,503
0
1
null
2015-10-16T09:59:34
2015-10-13T16:23:50
Java
UTF-8
Java
false
false
196
java
package dialog; import javax.swing.JFileChooser; public class JSaveAsDialog extends JFileChooser { public JSaveAsDialog() { setDialogTitle("Save as..."); } }
[ "arthur.gustin@gmail.com" ]
arthur.gustin@gmail.com
b70696baabec55cc7248063c51b360978f7a9f76
35208b330adf4f6698a63bc7798d1f4df942b923
/src/main/java/net/floodlightcontroller/connmonitor/MyLogger.java
0909c0695037a6777aecab9f7cf3a056f2e2ea45
[ "Apache-2.0" ]
permissive
xph906/SDN
f151d6a1f67403f9ef3609f6a3301197fae6408f
d50641cf6b3df12ba7dbaded695dc106f8bbda78
refs/heads/master
2020-05-17T03:03:05.953714
2015-03-12T04:38:44
2015-03-12T04:38:44
29,147,851
0
0
null
null
null
null
UTF-8
Java
false
false
1,447
java
package net.floodlightcontroller.connmonitor; public class MyLogger { /* * Level: * 0: contoled by enable_xx * 1: one highest level gets dumped LogError * 2: top two channels get dumped LogError, LogInfo * 3: all three get dumped LogError, LogInfo, LogDebug */ private int level; private boolean enable_error; private boolean enable_debug; private boolean enable_info; public MyLogger(){ setLevel(0); setEnableError(true); setEnableInfo(true); setEnableDebug(false); } public void LogError(String str){ if(level!=0 || enable_error) System.err.println(str); } public void LogDebug(String str){ if((level==3) || ((level==0) && enable_debug)) System.out.println(str); } public void LogInfo(String str){ if((level==2) || (level==3) || ((level==0) && enable_info)) System.out.println(str); } public MyLogger(int l){ setLevel(l); } public boolean isEnableError() { return enable_error; } public void setEnableError(boolean enable_error) { this.enable_error = enable_error; } public boolean isEnableDebug() { return enable_debug; } public void setEnableDebug(boolean enable_debug) { this.enable_debug = enable_debug; } public boolean isEnableInfo() { return enable_info; } public void setEnableInfo(boolean enable_info) { this.enable_info = enable_info; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
[ "xiangpan2011@u.northwestern.edu" ]
xiangpan2011@u.northwestern.edu
41fc541a4ef1b97b92cdeddd8502a67af6f03b56
66407c05f55d4851d06196b5f25d68a225346972
/src/main/java/com/nagarro/repository/ShipwreckRepository.java
8d3c11e4b8b1180f079725b30ebc8d1fe8f2f929
[]
no_license
vineet7838/springboot_crud_app
c1c47fa2b79f047ec6a1f83294ae87f21aa1aa92
4f2be7022f90fce481fd9f67e85b64fbc49cb183
refs/heads/master
2020-05-19T05:47:56.711599
2019-05-14T10:59:55
2019-05-14T10:59:55
184,857,802
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package com.nagarro.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.nagarro.model.Shipwreck; public interface ShipwreckRepository extends JpaRepository<Shipwreck, Long> { }
[ "vineetagarwal267@gmail.com" ]
vineetagarwal267@gmail.com
33882d5bf1a9a51bb1f3b3ef94c5f208e58a60e0
31e1d1fa6037d2a18717e805a631a36929a7a3d3
/app/src/main/java/com/superpowered/voicejam/Player.java
9694e7439d7e4f8f97985692169b15027c7c179d
[]
no_license
dkorobov2/voice_jam
8821b5e7a1ceaa1e1280fc40c558bfd82e186ac5
387da4269ea5c5e8af9d2e1d696a5e4eea66e2ea
refs/heads/master
2021-07-03T09:00:53.237663
2017-09-24T03:31:31
2017-09-24T03:31:31
104,615,694
1
0
null
null
null
null
UTF-8
Java
false
false
2,799
java
package com.superpowered.voicejam; import android.annotation.TargetApi; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Build; import android.util.Log; import java.util.ArrayList; /** * Created by korobov2 on 9/10/2017. */ public class Player { AssetFileDescriptor afd; MediaPlayer mPlayer = new MediaPlayer(); private SoundPool pianoSounds; Context mainActivityContext; boolean ready; ArrayList<Integer> soundIds; // from C2 to B5 String[] notes = {"C2", "Db2", "D2", "Eb2", "E2", "F2", "Gb2", "G2", "Ab2", "A2", "Bb2", "B2", "C3", "Db3", "D3", "Eb3", "E3", "F3", "Gb3", "G3", "Ab3", "A3", "Bb3", "B3", "C4", "Db4", "D4", "Eb4", "E4", "F4", "Gb4", "G4", "Ab4", "A4", "Bb4", "B4", "C5", "Db5", "D5", "Eb5", "E5", "F5", "Gb5", "G5", "Ab5", "A5", "Bb5", "B5",}; public Player(Context c) { mainActivityContext = c; soundIds = new ArrayList<Integer>(); pianoSounds = buildSoundPool(); ready = false; for (int i = 0; i < notes.length; i++) { try { afd = mainActivityContext.getAssets().openFd("piano_ff_" + notes[i] + ".mp3"); soundIds.add(pianoSounds.load(afd, i)); } catch (Exception e) { } } pianoSounds.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int mySoundId, int status) { ready = true; } }); } /** * Verify device's API before to load soundpool * * @return */ @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.LOLLIPOP) private SoundPool buildSoundPool() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_UNKNOWN) .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) .build(); pianoSounds = new SoundPool.Builder() .setMaxStreams(24) .setAudioAttributes(audioAttributes) .build(); } else { buildBeforeAPI21(); } return pianoSounds; } public void buildBeforeAPI21() { pianoSounds = new SoundPool(24, AudioManager.STREAM_MUSIC, 0); } public void playNote(int index) { if (ready) { Log.i("player", "playing note"); pianoSounds.play(soundIds.get(index), 1, 1, 0, 0, 1); } } }
[ "korobov2@illinois.edu" ]
korobov2@illinois.edu
978be60bb12c1137f7c82b986d0647017d83f089
6f05113d100ba0414413f9ce4493791fe258ce51
/src/Result.java
21cbe360075ae5e80984ce71e47e2e43596953c9
[]
no_license
brycesandlund/4x4TicTacToe
490cdc49f2b6bf79f21ae8f72d6ad6adf63d81f7
e1424fcb284ec2c03ee50d545fe45265ce18f13e
refs/heads/master
2016-09-08T00:45:27.941291
2014-02-08T02:30:41
2014-02-08T02:30:41
16,633,915
1
0
null
null
null
null
UTF-8
Java
false
false
53
java
public enum Result { PLAY1WIN, PLAY2WIN, CATS }
[ "bcsandlund@gmail.com" ]
bcsandlund@gmail.com
d0f0fdcf66174d5f274d8394639adccd5884dd7b
84f818927d7379ed049047aadb4faf3828c82cbf
/Application_programming_in_java/Homeworks/CP125Assignment7/src/test/java/app/Assignment7Test.java
6bff5717661cdf1144bcfc98f23cfe26e75f857e
[]
no_license
joettcrow/University_of_Washington
00c667c3bff1ebb871f5becf06d0325bea02a76b
59fcd9c0fb3ab61d432d023963c010bdb3e50238
refs/heads/master
2020-03-10T20:10:27.490849
2018-09-10T23:08:44
2018-09-10T23:08:44
129,564,659
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package app; import com.scg.persistent.initDb; import org.junit.Test; import static org.junit.Assert.*; /** * @author jcrowley */ public class Assignment7Test { @Test public void mainTest() { String[] args = {"one", "two", "three"}; initDb.main(args); Assignment7.main(args); } }
[ "jcrowley@indeed.com" ]
jcrowley@indeed.com
917998206a6241a3fbd2f905c8b1d8da61cf90ef
2406bc87938d916a1bee7eef74b9e6b44296180c
/yidao-common/src/main/java/com/ruoyi/common/json/CustomConfig.java
37d4625453e363374c3a803cdd07222ec08dbb90
[ "MIT" ]
permissive
zd938780519/YiDaoProject
d49c92b7b894cfc7984587845a9b9a456c69637f
0bcf381e39baa17377979f97b95d9b98b6ee57d6
refs/heads/master
2022-12-21T11:27:01.878226
2019-10-28T08:07:02
2019-10-28T08:07:02
217,984,198
0
1
MIT
2022-12-15T23:38:58
2019-10-28T06:56:24
JavaScript
UTF-8
Java
false
false
1,013
java
package com.ruoyi.common.json; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; @Configuration public class CustomConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider) throws IOException { //设置返回null转为 空字符串"" paramJsonGenerator.writeString(""); } }); return objectMapper; } }
[ "838780519@qq.com" ]
838780519@qq.com
009b4924b57bc721a56e49bae87c626ecf23479e
837c138c13cc1764dfd811424c3d7889c20216af
/MyBox/src/main/java/mara/mybox/tools/FileTools.java
93be8941b30caa382fa89cb1a105035c17f1ba39
[ "Apache-2.0" ]
permissive
CRY-D/MyBox
36ac5c88ec09c8f98af370afd5d1df7fa8a72330
a48a9f88963cb51a008a6bc8495c89751ec6c364
refs/heads/master
2023-02-21T18:15:54.375314
2021-01-27T14:04:57
2021-01-27T14:04:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
44,410
java
package mara.mybox.tools; import java.awt.Desktop; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import mara.mybox.data.FileInformation; import mara.mybox.data.FileSynchronizeAttributes; import mara.mybox.data.TextEditInformation; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.AppVariables.MyBoxTempPath; import static mara.mybox.value.AppVariables.message; import mara.mybox.value.CommonValues; import org.apache.commons.io.FileUtils; /** * @Author mara * @CreateDate 2018-6-2 11:01:45 * @Description */ public class FileTools { public static enum FileSortMode { ModifyTimeDesc, ModifyTimeAsc, CreateTimeDesc, CreateTimeAsc, SizeDesc, SizeAsc, NameDesc, NameAsc, FormatDesc, FormatAsc } public static FileSortMode sortMode(String mode) { for (FileSortMode v : FileSortMode.values()) { if (v.name().equals(mode) || message(v.name()).equals(mode)) { return v; } } return null; } public static String filenameFilter(String name) { if (name == null || name.isBlank()) { return name; } Pattern pattern = Pattern.compile(CommonValues.FileNameSpecialChars); return pattern.matcher(name).replaceAll("_"); } public static long createTime(final String filename) { try { FileTime t = Files.readAttributes(Paths.get(filename), BasicFileAttributes.class).creationTime(); return t.toMillis(); } catch (Exception e) { return -1; } } public static long createTime(File file) { if (file == null || !file.exists()) { return -1; } return createTime(file.getAbsolutePath()); } public static String getFilePrefix(File file) { try { return getFilePrefix(file.getName()); } catch (Exception e) { return ""; } } public static String getName(final String filename) { if (filename == null) { return null; } String fname = filename; int pos = fname.lastIndexOf(File.separator); if (pos >= 0) { fname = fname.substring(pos + 1); } return fname; } public static String namePrefix(final String file) { if (file == null) { return null; } String fname = getName(file); int pos = fname.lastIndexOf('.'); if (pos >= 0) { fname = fname.substring(0, pos); } return fname; } // filename may include path or not, it is decided by caller public static String getFilePrefix(String file) { if (file == null) { return null; } String path, name; int pos = file.lastIndexOf(File.separator); if (pos >= 0) { path = file.substring(0, pos + 1); name = file.substring(pos + 1); } else { path = ""; name = file; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos); } else { return path + name; } } public static String getFileSuffix(File file) { if (file == null) { return null; } return getFileSuffix(file.getName()); } // not include "." public static String getFileSuffix(String file) { if (file == null || file.endsWith(File.separator)) { return null; } if (file.endsWith(".")) { return ""; } String name = getName(file); int pos = name.lastIndexOf('.'); if (pos >= 0) { return name.substring(pos + 1); } else { return ""; } } public static String replaceFileSuffix(String file, String newSuffix) { if (file == null || newSuffix == null) { return null; } String path, name; int pos = file.lastIndexOf(File.separator); if (pos >= 0) { path = file.substring(0, pos + 1); name = file.substring(pos + 1); } else { path = ""; name = file; } pos = name.lastIndexOf('.'); if (pos >= 0) { name = path + name.substring(0, pos + 1) + newSuffix; } else { name = path + name + "." + newSuffix; } return name; } public static String appendName(String file, String append) { if (file == null) { return null; } if (append == null || append.isEmpty()) { return file; } String path, name; int pos = file.lastIndexOf(File.separator); if (pos >= 0) { path = file.substring(0, pos + 1); name = file.substring(pos + 1); } else { path = ""; name = file; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos) + append + name.substring(pos); } else { return path + name + append; } } public static String getTempFileName() { return getTempFileName(MyBoxTempPath.getAbsolutePath()); } public static File getTempFile() { return getPathTempFile(MyBoxTempPath.getAbsolutePath()); } public static File getTempFile(String suffix) { return getPathTempFile(MyBoxTempPath.getAbsolutePath(), suffix); } public static File getTempDirectory() { return getPathTempDirectory(MyBoxTempPath.getAbsolutePath()); } public static String getTempFileName(String path) { return path + File.separator + new Date().getTime() + IntTools.getRandomInt(100); } public static File getPathTempFile(String path) { File file = new File(getTempFileName(path)); while (file.exists()) { file = new File(getTempFileName(path)); } return file; } public static File getPathTempFile(String path, String suffix) { File file = new File(getTempFileName(path) + suffix); while (file.exists()) { file = new File(getTempFileName(path) + suffix); } return file; } public static File getPathTempDirectory(String path) { File file = new File(getTempFileName(path) + File.separator); while (file.exists()) { file = new File(getTempFileName(path) + File.separator); } file.mkdirs(); return file; } public static String showFileSize(long size) { double kb = size * 1.0d / 1024; if (kb < 1024) { return DoubleTools.scale3(kb) + " KB"; } else { double mb = kb / 1024; if (mb < 1024) { return DoubleTools.scale3(mb) + " MB"; } else { double gb = mb / 1024; return DoubleTools.scale3(gb) + " GB"; } } } public static int compareFilename(File f1, File f2) { if (f1 == null) { return f2 == null ? 0 : -1; } if (f2 == null) { return 1; } if (f1.isFile() && f2.isFile() && f1.getParent().equals(f2.getParent())) { return StringTools.compareWithNumber(f1.getName(), f2.getName()); } else { Comparator<Object> compare = Collator.getInstance(Locale.getDefault()); return compare.compare(f1.getAbsolutePath(), f2.getAbsolutePath()); } } public static void sortFiles(List<File> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } try { switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.lastModified() - f1.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.lastModified() - f2.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case NameDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return compareFilename(f2, f1); } }); break; case NameAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return compareFilename(f1, f2); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t2 - t1; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t1 - t2; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.length() - f1.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.length() - f2.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case FormatDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileTools.getFileSuffix(f2).compareTo(FileTools.getFileSuffix(f1)); } }); break; case FormatAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileTools.getFileSuffix(f1).compareTo(FileTools.getFileSuffix(f2)); } }); break; } } catch (Exception e) { MyBoxLog.debug(e.toString()); } } public static List<File> sortFiles(File path, FileSortMode sortMode) { if (path == null || !path.isDirectory()) { return null; } File[] pathFiles = path.listFiles(); if (pathFiles == null || pathFiles.length == 0) { return null; } List<File> files = new ArrayList<>(); for (File file : pathFiles) { if (file.isFile()) { files.add(file); } } if (files.isEmpty()) { return null; } sortFiles(files, sortMode); return files; } public static void sortFileInformations(List<FileInformation> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().lastModified() - f1.getFile().lastModified()); } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().lastModified() - f2.getFile().lastModified()); } }); break; case NameDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return compareFilename(f2.getFile(), f1.getFile()); } }); break; case NameAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return compareFilename(f1.getFile(), f2.getFile()); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t2 - t1); } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t1 - t2); } }); break; case SizeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().length() - f1.getFile().length()); } }); break; case SizeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().length() - f2.getFile().length()); } }); break; case FormatDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileTools.getFileSuffix(f2.getFile()).compareTo(FileTools.getFileSuffix(f1.getFile())); } }); break; case FormatAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileTools.getFileSuffix(f1.getFile()).compareTo(FileTools.getFileSuffix(f2.getFile())); } }); break; } } public static boolean isSupportedImage(File file) { if (file == null || !file.isFile()) { return false; } String suffix = getFileSuffix(file.getName()).toLowerCase(); return CommonValues.SupportedImages.contains(suffix); } public static boolean copyFile(String sourceFile, String targetFile) { return copyFile(new File(sourceFile), new File(targetFile)); } public static boolean copyFile(File sourceFile, File targetFile) { return copyFile(sourceFile, targetFile, false, true); } public static boolean copyFile(File sourceFile, File targetFile, boolean isCanReplace, boolean isCopyAttrinutes) { try { if (sourceFile == null || !sourceFile.exists() || !sourceFile.isFile()) { return false; } if (!targetFile.exists()) { if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath())); } } else if (!isCanReplace || targetFile.isDirectory()) { return false; } else if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static FileSynchronizeAttributes copyWholeDirectory(File sourcePath, File targetPath) { FileSynchronizeAttributes attr = new FileSynchronizeAttributes(); copyWholeDirectory(sourcePath, targetPath, attr); return attr; } public static boolean copyWholeDirectory(File sourcePath, File targetPath, FileSynchronizeAttributes attr) { return copyWholeDirectory(sourcePath, targetPath, attr, true); } public static boolean copyWholeDirectory(File sourcePath, File targetPath, FileSynchronizeAttributes attr, boolean clearTarget) { try { if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) { return false; } if (attr == null) { attr = new FileSynchronizeAttributes(); } if (targetPath.exists()) { if (clearTarget && !deleteDir(targetPath)) { return false; } } else { targetPath.mkdirs(); } File[] files = sourcePath.listFiles(); if (files == null) { return false; } for (File file : files) { File targetFile = new File(targetPath + File.separator + file.getName()); if (file.isFile()) { if (copyFile(file, targetFile, attr)) { attr.setCopiedFilesNumber(attr.getCopiedFilesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } else if (file.isDirectory()) { if (copyWholeDirectory(file, targetFile, attr, clearTarget)) { attr.setCopiedDirectoriesNumber(attr.getCopiedDirectoriesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean copyFile(File sourceFile, File targetFile, FileSynchronizeAttributes attr) { if (attr == null) { attr = new FileSynchronizeAttributes(); } return copyFile(sourceFile, targetFile, attr.isCanReplace(), attr.isCopyAttrinutes()); } public static boolean rename(File sourceFile, File targetFile) { try { if (sourceFile == null || !sourceFile.exists() || targetFile == null) { return false; } if (!delete(targetFile)) { return false; } System.gc(); FileUtils.moveFile(sourceFile, targetFile); // Files.move(sourceFile.toPath(), targetFile.toPath(), // StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean delete(String fileName) { if (fileName == null || fileName.isBlank()) { return false; } return delete(new File(fileName)); } public static boolean delete(File file) { try { if (file == null || !file.exists()) { return true; } System.gc(); if (file.isDirectory()) { FileUtils.deleteDirectory(file); return true; } else { return file.delete(); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean clearDir(File dir) { if (dir == null) { return false; } if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { file.delete(); } else if (file.isDirectory()) { deleteDir(file); } } } } return true; // try { // FileUtils.cleanDirectory(dir); // return true; // } catch (Exception e) { // MyBoxLog.error(e); // return false; // } } public static boolean deleteDir(File dir) { if (dir == null) { return false; } if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { boolean success = deleteDir(file); if (!success) { return false; } } } } return dir.delete(); // FileUtils.deleteQuietly(dir); // return true; } public static int deleteEmptyDir(File dir, boolean trash) { return deleteEmptyDir(dir, 0, trash); } public static int deleteEmptyDir(File dir, int count, boolean trash) { if (dir != null && dir.exists() && dir.isDirectory()) { File[] files = dir.listFiles(); if (files == null || files.length == 0) { if (trash) { Desktop.getDesktop().moveToTrash(dir); } else { deleteDir(dir); } return ++count; } for (File file : files) { if (file.isDirectory()) { count = deleteEmptyDir(file, count, trash); } } files = dir.listFiles(); if (files == null || files.length == 0) { if (trash) { Desktop.getDesktop().moveToTrash(dir); } else { deleteDir(dir); } return ++count; } } return count; } public static void deleteNestedDir(File sourceDir) { try { if (sourceDir == null || !sourceDir.exists() || !sourceDir.isDirectory()) { return; } System.gc(); File targetTmpDir = getTempDirectory(); deleteNestedDir(sourceDir, targetTmpDir); deleteDir(targetTmpDir); deleteDir(sourceDir); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void deleteNestedDir(File sourceDir, File tmpDir) { try { if (sourceDir.isDirectory()) { File[] files = sourceDir.listFiles(); if (files == null || files.length == 0) { return; } for (File file : files) { if (file.isDirectory()) { File[] subfiles = file.listFiles(); if (subfiles != null) { for (File subfile : subfiles) { if (subfile.isDirectory()) { String target = tmpDir.getAbsolutePath() + File.separator + subfile.getName(); Files.move(Paths.get(subfile.getAbsolutePath()), Paths.get(target)); } else { delete(subfile); } } } file.delete(); } else { delete(file); } } deleteNestedDir(tmpDir, sourceDir); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static boolean deleteDirExcept(File dir, File except) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.equals(except)) { continue; } boolean success = deleteDirExcept(file, except); if (!success) { return false; } } } } return delete(dir); } // Return files number and total length public static long[] countDirectorySize(File dir, boolean countSubdir) { long[] size = new long[2]; try { if (dir == null) { return size; } if (dir.isFile()) { size[0] = 1; size[1] = dir.length(); } else if (dir.isDirectory()) { File[] files = dir.listFiles(); size[0] = 0; size[1] = 0; if (files != null) { for (File file : files) { if (file.isFile()) { size[0]++; size[1] += file.length(); } else if (file.isDirectory()) { if (countSubdir) { long[] fsize = countDirectorySize(file, countSubdir); size[0] += fsize[0]; size[1] += fsize[1]; } } } } } } catch (Exception e) { MyBoxLog.debug(e.toString()); } return size; } public static List<File> allFiles(File file) { if (file == null) { return null; } List<File> files = new ArrayList<>(); if (file.isFile()) { files.add(file); } else if (file.isDirectory()) { File[] dirFiles = file.listFiles(); if (dirFiles != null) { for (File dirFile : dirFiles) { files.addAll(allFiles(dirFile)); } } } return files; } public static List<File> splitFileByFilesNumber(File file, String filename, long filesNumber) { try { if (file == null || filesNumber <= 0) { return null; } long bytesNumber = file.length() / filesNumber; List<File> splittedFiles = new ArrayList<>(); try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; int digit = (filesNumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen, fileIndex = 1, startIndex = 0, endIndex = 0; while ((fileIndex < filesNumber) && (bufLen = inputStream.read(buf)) > 0) { endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } buf = new byte[(int) (file.length() - endIndex)]; bufLen = inputStream.read(buf); if (bufLen > 0) { endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { outputStream.write(buf); } splittedFiles.add(new File(newFilename)); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } } public static List<File> splitFileByBytesNumber(File file, String filename, long bytesNumber) { try { if (file == null || bytesNumber <= 0) { return null; } List<File> splittedFiles = new ArrayList<>(); try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; long fnumber = file.length() / bytesNumber; if (file.length() % bytesNumber > 0) { fnumber++; } int digit = (fnumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen, fileIndex = 1, startIndex = 0, endIndex = 0; while ((bufLen = inputStream.read(buf)) > 0) { endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } } public static List<File> splitFileByStartEndList(File file, String filename, List<Long> startEndList) { try { if (file == null || startEndList == null || startEndList.isEmpty() || startEndList.size() % 2 > 0) { return null; } List<File> splittedFiles = new ArrayList<>(); for (int i = 0; i < startEndList.size(); i += 2) { File f = cutFile(file, filename, startEndList.get(i), startEndList.get(i + 1)); if (f != null) { splittedFiles.add(f); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } } // 1-based start, that is: from (start - 1) to ( end - 1) actually public static File cutFile(File file, String filename, long startIndex, long endIndex) { try { if (file == null || startIndex < 1 || startIndex > endIndex) { return null; } File tempFile = FileTools.getTempFile(); String newFilename = filename + "-cut-b" + startIndex + "-b" + endIndex; try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { if (startIndex > 1) { inputStream.skip(startIndex - 1); } int cutLength = (int) (endIndex - startIndex + 1); byte[] buf = new byte[cutLength]; int bufLen; bufLen = inputStream.read(buf); if (bufLen <= 0) { return null; } try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) { if (cutLength > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); newFilename = filename + "-cut-b" + startIndex + "-b" + bufLen; } outputStream.write(buf); } } File actualFile = new File(newFilename); if (FileTools.rename(tempFile, actualFile)) { return actualFile; } else { return null; } } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } } public static boolean mergeFiles(File file1, File file2, File targetFile) { try { List<File> files = new ArrayList(); files.add(file1); files.add(file2); return mergeFiles(files, targetFile); } catch (Exception e) { MyBoxLog.debug(e.toString()); return false; } } public static boolean mergeFiles(List<File> files, File targetFile) { if (files == null || files.isEmpty() || targetFile == null) { return false; } try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) { byte[] buf = new byte[CommonValues.IOBufferLength]; int bufLen; for (File file : files) { try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { while ((bufLen = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bufLen); } } } } catch (Exception e) { MyBoxLog.debug(e.toString()); return false; } return true; } public static byte[] readBytes(File file) { byte[] data = null; try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { int bufSize = (int) file.length(); data = new byte[bufSize]; int readLen = inputStream.read(data); if (readLen > 0 && readLen < bufSize) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e.toString()); } return data; } public static byte[] readBytes(File file, long offset, int length) { if (file == null || offset < 0 || length <= 0) { return null; } byte[] data; try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { data = new byte[length]; inputStream.skip(offset); int readLen = inputStream.read(data); if (readLen > 0 && readLen < length) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } return data; } public static Charset charset(File file) { try { TextEditInformation info = new TextEditInformation(file); if (TextTools.checkCharset(info)) { return info.getCharset(); } else { return Charset.forName("utf-8"); } } catch (Exception e) { return Charset.forName("utf-8"); } } public static boolean isUTF8(File file) { Charset charset = charset(file); return charset.equals(Charset.forName("utf-8")); } public static String readTexts(File file) { return readTexts(file, charset(file)); } public static String readTexts(File file, Charset charset) { StringBuilder s = new StringBuilder(); try ( BufferedReader reader = new BufferedReader(new FileReader(file, charset))) { String line; while ((line = reader.readLine()) != null) { s.append(line).append(System.lineSeparator()); } } catch (Exception e) { return null; } return s.toString(); } public static File writeFile(File file, String data) { return writeFile(file, data, Charset.forName("utf-8")); // if (file.exists()) { // return writeFile(file, data, charset(file)); // } else { // return writeFile(file, data, Charset.forName("utf-8")); // } } public static File writeFile(File file, String data, Charset charset) { if (file == null || data == null) { return null; } try ( FileWriter writer = new FileWriter(file, charset != null ? charset : Charset.forName("utf-8"))) { writer.write(data); writer.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } return file; } public static File writeFile(String data) { return writeFile(getTempFile(), data); } public static boolean writeFile(File file, byte[] data) { if (file == null || data == null) { return false; } try ( BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { outputStream.write(data); outputStream.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } public static boolean same(File file1, File file2) { return Arrays.equals(SystemTools.SHA1(file1), SystemTools.SHA1(file2)); } public static int bufSize(File file, int memPart) { Runtime r = Runtime.getRuntime(); long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); long min = Math.min(file.length(), availableMem / memPart); return min > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) min; } public static File removeBOM(File file) { try { String setName = null; try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { byte[] header = new byte[4]; int readLen; if ((readLen = inputStream.read(header, 0, 4)) > 0) { header = ByteTools.subBytes(header, 0, readLen); setName = TextTools.checkCharsetByBom(header); if (setName == null) { return file; } } } File tmpFile = getTempFile(); try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { int bomSize = TextTools.bomSize(setName); inputStream.skip(bomSize); int readLen; byte[] buf = new byte[bufSize(file, 16)]; while ((readLen = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, readLen); } } return tmpFile; } catch (Exception e) { MyBoxLog.debug(e.toString()); return null; } } }
[ "rshmara@sina.com" ]
rshmara@sina.com
3de6336657b4c73917f7d3184cc03db386908337
862c1d2c189cda01c60e08495bb38666ec13b624
/java.basic/basic-code/src/cn/siahk/day01/demo01/SimpleCollection.java
5b4d09aed10a52cb59ae0b50a16001005b3044b1
[]
no_license
Siahk/java.study
1038c6058266efc74d628a0cd816e5495c87b0f1
e089141aee1c562275e71fabc597c7b79bfa2f96
refs/heads/main
2023-04-21T13:58:07.737985
2021-05-05T10:40:33
2021-05-05T10:40:33
364,532,227
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
package cn.siahk.day01.demo01; import java.util.*; public class SimpleCollection { public static void main(String[] args) { Collection<Integer> c = new ArrayList<>(); for(int i = 0; i < 10; i++) c.add(i); // Autoboxing for(Integer i : c) System.out.print(i + ", "); } } /* Output: * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, * */
[ "59272201+Siahk@users.noreply.github.com" ]
59272201+Siahk@users.noreply.github.com
fce58dbb34c2d980addf83894d7221ff4cbb12bd
b5818ada5d2e336c865695c5313f3d4d3ea8539b
/src/CLASS/DB_INFO.java
27b6dfc4649690b7ab7a119a4520b7da45f5bf2d
[]
no_license
Greenhill12/Bookstore
93906cc6170b753a4d7808503fbca9e5fe091106
fa7054e5cfa1ebecbb3d7542a1b53de00e0667c4
refs/heads/master
2020-03-31T10:43:20.580435
2018-10-08T21:11:14
2018-10-08T21:11:14
152,146,706
0
0
null
null
null
null
UTF-8
Java
false
false
958
java
package CLASS; import java.sql.Connection; import java.sql.DriverManager; import java.sql.*; public class DB_INFO { private static final String CONN_STRING = "jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=UTF-8"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; static Connection conn = null; public static Connection getConnection() { if (conn != null) return conn; return getConnection(CONN_STRING, USERNAME, PASSWORD); } private static Connection getConnection(String db_name,String user_name,String password) { try { conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("Connected!"); } catch(SQLException e) { System.err.println("e");; } return conn; } }
[ "johnnydille@inbox.lv" ]
johnnydille@inbox.lv
1db3403c74e9df21f6f84fd4ae8817cf926410f5
90e9d4abc8897e0d11c35de16b234e0533ac9e2b
/src/main/java/com/chenjing/weixinpay/dto/VideoOrderDto.java
065b3fa3399c2b7df5cc1c0849c622e5ffc43ab5
[]
no_license
ChenJing940528/weixinpay
3c0c4b04dcccf9749a488b0039b1b9b38822bb7d
282e013d3e9ad01a4300d51c56f79aa97dca1242
refs/heads/master
2020-05-04T16:46:43.229982
2019-04-10T09:11:49
2019-04-10T09:11:49
179,077,289
0
0
null
null
null
null
UTF-8
Java
false
false
266
java
package com.chenjing.weixinpay.dto; import com.chenjing.weixinpay.domain.VideoOrder; /** * description:VideoOrderDto * * @author:chenjing * @version:1.0 * @time:16:30 */ /* * 订单数据传输对象 * */ public class VideoOrderDto extends VideoOrder{ }
[ "761160510@qq.com" ]
761160510@qq.com
988694e528f6e71a58f1d1fb90d2b30fa445f353
1a289ed6fbb12158b7b36d167aa0124b561b42d1
/BIBHRMS/src/java/entity/employeeEntity/.svn/text-base/EmployeeWillEntity.java.svn-base
19b8de90c0c01b913367b351e82919f0ec57d672
[]
no_license
BirukZ/MasterProject
e1dbb05c53c40a4ce368485a4f33f9e577a6f92b
ed08cf672ccb37ac4945b836113dc77023d29705
refs/heads/master
2021-01-19T10:25:49.061712
2017-02-17T05:09:24
2017-02-17T05:09:24
82,179,971
0
0
null
null
null
null
UTF-8
Java
false
false
18,918
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package entity.employeeEntity; import connectionProvider.ConnectionManager; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import manager.globalUseManager.ErrorLogWriter; /** * * @author Administrator */ @Entity @Table(name = "HR_EMPLOYEE_WILL") @NamedQueries({@NamedQuery(name = "EmployeeWillEntity.findAll", query = "SELECT e FROM EmployeeWillEntity e"), @NamedQuery(name = "EmployeeWillEntity.findByWillId", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willId = :willId"), @NamedQuery(name = "EmployeeWillEntity.findByWillFirstName", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willFirstName = :willFirstName"), @NamedQuery(name = "EmployeeWillEntity.findByWillMiddleName", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willMiddleName = :willMiddleName"), @NamedQuery(name = "EmployeeWillEntity.findByWillLastName", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willLastName = :willLastName"), @NamedQuery(name = "EmployeeWillEntity.findByWillsalry", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willsalry = :willsalry"), @NamedQuery(name = "EmployeeWillEntity.findByWillregionid", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willregionid = :willregionid"), @NamedQuery(name = "EmployeeWillEntity.findByWillzoneorcity", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willzoneorcity = :willzoneorcity"), @NamedQuery(name = "EmployeeWillEntity.findByWillworedaorsubcity", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willworedaorsubcity = :willworedaorsubcity"), @NamedQuery(name = "EmployeeWillEntity.findByWillkebelle", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willkebelle = :willkebelle"), @NamedQuery(name = "EmployeeWillEntity.findByWillhousenumber", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willhousenumber = :willhousenumber"), @NamedQuery(name = "EmployeeWillEntity.findByWillworkingin", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willworkingin = :willworkingin"), @NamedQuery(name = "EmployeeWillEntity.findByMobile", query = "SELECT e FROM EmployeeWillEntity e WHERE e.mobile = :mobile"), @NamedQuery(name = "EmployeeWillEntity.findByWillworkingphonenumber", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willworkingphonenumber = :willworkingphonenumber"), @NamedQuery(name = "EmployeeWillEntity.findByWillresidencephonenumber", query = "SELECT e FROM EmployeeWillEntity e WHERE e.willresidencephonenumber = :willresidencephonenumber")}) public class EmployeeWillEntity extends ConnectionManager implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "WILL_ID") private String willId; @Column(name = "EMP_ID") private String employeeId; @Column(name = "WILL_FIRST_NAME") private String willFirstName; @Column(name = "WILL_MIDDLE_NAME") private String willMiddleName; @Column(name = "WILL_LAST_NAME") private String willLastName; @Column(name = "WILLSALRY") private String willsalry; @Column(name = "WILLREGIONID") private String willregionid; @Column(name = "WILLZONEORCITY") private String willzoneorcity; @Column(name = "WILLWOREDAORSUBCITY") private String willworedaorsubcity; @Column(name = "WILLKEBELLE") private String willkebelle; @Column(name = "WILLHOUSENUMBER") private String willhousenumber; @Column(name = "WILLWORKINGIN") private String willworkingin; @Column(name = "MOBILE") private String mobile; @Column(name = "WILLWORKINGPHONENUMBER") private String willworkingphonenumber; @Column(name = "WILLRESIDENCEPHONENUMBER") private String willresidencephonenumber; @Column(name = "TITLE") private String title; public EmployeeWillEntity() { } public EmployeeWillEntity(String willId) { this.willId = willId; } public String getWillId() { return willId; } public void setWillId(String willId) { this.willId = willId; } public String getWillFirstName() { return willFirstName; } public void setWillFirstName(String willFirstName) { this.willFirstName = willFirstName; } public String getWillMiddleName() { return willMiddleName; } public void setWillMiddleName(String willMiddleName) { this.willMiddleName = willMiddleName; } public String getWillLastName() { return willLastName; } public void setWillLastName(String willLastName) { this.willLastName = willLastName; } public String getWillsalry() { return willsalry; } public void setWillsalry(String willsalry) { this.willsalry = willsalry; } public String getWillregionid() { return willregionid; } public void setWillregionid(String willregionid) { this.willregionid = willregionid; } public String getWillzoneorcity() { return willzoneorcity; } public void setWillzoneorcity(String willzoneorcity) { this.willzoneorcity = willzoneorcity; } public String getWillworedaorsubcity() { return willworedaorsubcity; } public void setWillworedaorsubcity(String willworedaorsubcity) { this.willworedaorsubcity = willworedaorsubcity; } public String getWillkebelle() { return willkebelle; } public void setWillkebelle(String willkebelle) { this.willkebelle = willkebelle; } public String getWillhousenumber() { return willhousenumber; } public void setWillhousenumber(String willhousenumber) { this.willhousenumber = willhousenumber; } public String getWillworkingin() { return willworkingin; } public void setWillworkingin(String willworkingin) { this.willworkingin = willworkingin; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getWillworkingphonenumber() { return willworkingphonenumber; } public void setWillworkingphonenumber(String willworkingphonenumber) { this.willworkingphonenumber = willworkingphonenumber; } public String getWillresidencephonenumber() { return willresidencephonenumber; } public void setWillresidencephonenumber(String willresidencephonenumber) { this.willresidencephonenumber = willresidencephonenumber; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int hashCode() { int hash = 0; hash += (willId != null ? willId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof EmployeeWillEntity)) { return false; } EmployeeWillEntity other = (EmployeeWillEntity) object; if ((this.willId == null && other.willId != null) || (this.willId != null && !this.willId.equals(other.willId))) { return false; } return true; } @Override public String toString() { return "entity.employeeEntity.EmployeeWillEntity[willId=" + willId + "]"; } public boolean saveEmployeeWill(EmployeeWillEntity employeeWillEntity) { Connection _con = null; PreparedStatement _ps = null; ResultSet _rs = null; int check; String _insert = "INSERT " + "INTO HR_EMPLOYEE_WILL " + " ( EMP_ID," + " WILL_FIRST_NAME, " + " WILL_MIDDLE_NAME, " + " WILL_LAST_NAME, " + " WILLSALRY, " + " WILLREGIONID, " + " WILLZONEORCITY, " + " WILLWOREDAORSUBCITY, " + " WILLKEBELLE, " + " WILLHOUSENUMBER, " + " WILLWORKINGIN, " + " MOBILE, " + " WILLWORKINGPHONENUMBER, " + " WILLRESIDENCEPHONENUMBER," + " TITLE " + " ) " + " VALUES " + " (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { _con = getConnection(); _ps = _con.prepareStatement(_insert); _ps.setString(1, employeeWillEntity.getEmployeeId()); _ps.setString(2, employeeWillEntity.getWillFirstName()); _ps.setString(3, employeeWillEntity.getWillMiddleName()); _ps.setString(4, employeeWillEntity.getWillLastName()); _ps.setString(5, employeeWillEntity.getWillsalry()); _ps.setString(6, employeeWillEntity.getWillregionid()); _ps.setString(7, employeeWillEntity.getWillzoneorcity()); _ps.setString(8, employeeWillEntity.getWillworedaorsubcity()); _ps.setString(9, employeeWillEntity.getWillkebelle()); _ps.setString(10, employeeWillEntity.getWillhousenumber()); _ps.setString(11, employeeWillEntity.getWillworkingin()); _ps.setString(12, employeeWillEntity.getMobile()); _ps.setString(13, employeeWillEntity.getWillworkingphonenumber()); _ps.setString(14, employeeWillEntity.getWillresidencephonenumber()); _ps.setString(15, employeeWillEntity.getTitle()); if (_ps.executeUpdate() > 0) { return true; } else { return false; } } catch (Exception ex) { ex.printStackTrace(); ErrorLogWriter.writeError(ex); } return false; } public boolean saveEmployeeWill(ArrayList<HashMap> employeeWillList) { Connection _con = null; PreparedStatement _ps = null; ResultSet _rs = null; boolean check = false; String _insert = "INSERT " + "INTO HR_EMPLOYEE_WILL " + " ( EMP_ID," + " WILL_FIRST_NAME, " + " WILL_MIDDLE_NAME, " + " WILL_LAST_NAME, " + " WILLSALRY, " + " WILLREGIONID, " + " WILLZONEORCITY, " + " WILLWOREDAORSUBCITY, " + " WILLKEBELLE, " + " WILLHOUSENUMBER, " + " EXTERNALDOUMENTNO, " + " INTERNALDOCUMENTNO, " + " WILLSTATUS, " + " TITLE " + " ) " + " VALUES " + " (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { _con = getConnection(); for (HashMap hm : employeeWillList) { _ps = _con.prepareStatement(_insert); _ps.setString(1, hm.get("employeeId").toString()); _ps.setString(2, hm.get("willFirstName").toString()); _ps.setString(3, hm.get("willMiddleName").toString()); _ps.setString(4, hm.get("willLastName").toString()); _ps.setString(5, hm.get("willSalary").toString()); _ps.setString(6, hm.get("willRegion").toString()); _ps.setString(7, hm.get("willZoneorCity").toString()); _ps.setString(8, hm.get("willWoredaorSubCity").toString()); _ps.setString(9, hm.get("willKebele").toString()); _ps.setString(10, hm.get("willHouseNumber").toString()); _ps.setString(11, hm.get("externalDoumentNo").toString()); _ps.setString(12, hm.get("internalDocumentNo").toString()); _ps.setString(13, hm.get("willStatus").toString()); _ps.setString(14, hm.get("willTitle").toString()); if (_ps.executeUpdate() > 0) { return true; } check = true; } if (check) { return true; } else { return false; } } catch (Exception ex) { ex.printStackTrace(); ErrorLogWriter.writeError(ex); } return false; } public boolean updateEmployeeWill(HashMap listOFEmployeeWill) { Connection _con = null; PreparedStatement _ps = null; String _insert = "UPDATE HR_EMPLOYEE_WILL " + "SET WILL_FIRST_NAME = ?, " + " WILL_MIDDLE_NAME = ?, " + " WILL_LAST_NAME = ?, " + " WILLSALRY = ?, " + " WILLREGIONID = ?, " + " WILLZONEORCITY = ?, " + " WILLWOREDAORSUBCITY = ?, " + " WILLKEBELLE = ?, " + " WILLHOUSENUMBER = ?, " + " EXTERNALDOUMENTNO = ?, " + " INTERNALDOCUMENTNO = ?, " + " WILLSTATUS = ?, " + " EMP_ID = ?, " + " TITLE = ?, " + " REGISTRATIONDATE = ? " + "WHERE WILL_ID = ?"; try { _con = getConnection(); _ps = _con.prepareStatement(_insert); _ps.setString(1, listOFEmployeeWill.get("willFirstName").toString()); _ps.setString(2, listOFEmployeeWill.get("willMiddleName").toString()); _ps.setString(3, listOFEmployeeWill.get("willLastName").toString()); _ps.setString(4, listOFEmployeeWill.get("willSalary").toString()); _ps.setString(5, listOFEmployeeWill.get("willRegion").toString()); _ps.setString(6, listOFEmployeeWill.get("willZoneorCity").toString()); _ps.setString(7, listOFEmployeeWill.get("willWoredaorSubCity").toString()); _ps.setString(8, listOFEmployeeWill.get("kebelle").toString()); _ps.setString(9, listOFEmployeeWill.get("willHouseNumber").toString()); _ps.setString(10, listOFEmployeeWill.get("externalDoumentNo").toString()); _ps.setString(11, listOFEmployeeWill.get("internalDocumentNo").toString()); _ps.setString(12, listOFEmployeeWill.get("willStatus").toString()); _ps.setString(13, listOFEmployeeWill.get("employeeId").toString()); _ps.setString(14, listOFEmployeeWill.get("willTitle").toString()); _ps.setString(15, listOFEmployeeWill.get("registrationDate").toString()); _ps.setString(16, listOFEmployeeWill.get("willId").toString()); if (_ps.executeUpdate() > 0) { return true; } else { return false; } } catch (Exception ex) { ex.printStackTrace(); ErrorLogWriter.writeError(ex); } return false; } public boolean deleteEmployeeWill(String willId) { Connection _con = null; PreparedStatement _ps = null; ResultSet _rs = null; int check; String _delete = "DELETE FROM HR_EMPLOYEE_WILL WHERE WILL_ID = ?"; try { _con = getConnection(); _ps = _con.prepareStatement(_delete); _ps.setString(1, willId); if (_ps.executeUpdate() > 0) { return true; } else { return false; } } catch (Exception ex) { ex.printStackTrace(); ErrorLogWriter.writeError(ex); } return false; } public ArrayList<HashMap> getEmployeeWill(String employeeId) { String _select = "SELECT WILL_ID, " + " WILL_FIRST_NAME, " + " WILL_MIDDLE_NAME, " + " WILL_LAST_NAME, " + " WILLSALRY, " + " WILLREGIONID, " + " WILLZONEORCITY, " + " WILLWOREDAORSUBCITY, " + " WILLKEBELLE, " + " WILLHOUSENUMBER, " + " TITLE, " + " WILLSTATUS , " + " EXTERNALDOUMENTNO, " + " INTERNALDOCUMENTNO, " + " nvl(REGISTRATIONDATE,'not register') as REGISTRATIONDATE" + " FROM HR_EMPLOYEE_WILL " + " WHERE EMP_ID=? "; Connection _con = null; PreparedStatement _ps = null; ResultSet _rs = null; ArrayList<HashMap> listOfEmployee = new ArrayList<HashMap>(); try { _con = getConnection(); _ps = _con.prepareStatement(_select); _ps.setString(1, employeeId); _rs = _ps.executeQuery(); while (_rs.next()) { HashMap hm = new HashMap(); hm.put("WILL_ID", _rs.getString("WILL_ID")); hm.put("WILL_FIRST_NAME", _rs.getString("WILL_FIRST_NAME")); hm.put("WILL_MIDDLE_NAME", _rs.getString("WILL_MIDDLE_NAME")); hm.put("WILL_LAST_NAME", _rs.getString("WILL_LAST_NAME")); hm.put("WILLSALRY", _rs.getString("WILLSALRY")); hm.put("WILLREGIONID", _rs.getString("WILLREGIONID")); hm.put("WILLZONEORCITY", _rs.getString("WILLZONEORCITY")); hm.put("WILLWOREDAORSUBCITY", _rs.getString("WILLWOREDAORSUBCITY")); hm.put("WILLKEBELLE", _rs.getString("WILLKEBELLE")); hm.put("WILLHOUSENUMBER", _rs.getString("WILLHOUSENUMBER")); hm.put("INTERNALDOCUMENTNO", _rs.getString("INTERNALDOCUMENTNO")); hm.put("EXTERNALDOUMENTNO", _rs.getString("EXTERNALDOUMENTNO")); hm.put("REGISTRATIONDATE", _rs.getString("REGISTRATIONDATE")); hm.put("TITLE", _rs.getString("TITLE")); hm.put("WILLSTATUS", _rs.getString("WILLSTATUS")); listOfEmployee.add(hm); } return listOfEmployee; } catch (Exception e) { e.printStackTrace(); ErrorLogWriter.writeError(e); return null; } } }
[ "birukz02@gmail.com" ]
birukz02@gmail.com