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
e15dad530309ea9b0c1fcb3e783c988138f0c321
2cd346a770d2a60d673f9eff6a559af9f8ba8718
/app/build/tmp/kapt3/stubs/debug/com/example/contacts/Contract.java
ef16b434d08f58678ffaf2cfddd16a4943c10994
[]
no_license
iamarjun/Contacts
47b6c1c3b06ef972f442c3db21d18937d17c6bc0
41d1933a593e7b7eca3abbc5d85746f2519175bf
refs/heads/master
2020-04-17T12:31:52.133352
2019-02-03T14:29:07
2019-02-03T14:29:07
166,583,057
0
0
null
null
null
null
UTF-8
Java
false
false
3,525
java
package com.example.contacts; import java.lang.System; @kotlin.Metadata(mv = {1, 1, 13}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0003\bf\u0018\u00002\u00020\u0001:\u0002\u0002\u0003\u00a8\u0006\u0004"}, d2 = {"Lcom/example/contacts/Contract;", "", "ContactsPresenter", "ContactsView", "app_debug"}) public abstract interface Contract { @kotlin.Metadata(mv = {1, 1, 13}, bv = {1, 0, 3}, k = 1, d1 = {"\u00002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0000\bf\u0018\u00002\b\u0012\u0004\u0012\u00020\u00020\u0001J\u0010\u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u0006H&J\u0010\u0010\u0007\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u0006H&J\u0010\u0010\b\u001a\u00020\u00042\u0006\u0010\t\u001a\u00020\nH&J\u0010\u0010\u000b\u001a\u00020\u00042\u0006\u0010\f\u001a\u00020\rH&J\u0010\u0010\u000e\u001a\u00020\u00042\u0006\u0010\u000f\u001a\u00020\u0010H&\u00a8\u0006\u0011"}, d2 = {"Lcom/example/contacts/Contract$ContactsView;", "Lcom/example/contacts/BaseView;", "Lcom/example/contacts/Contract$ContactsPresenter;", "onErrorGettingContacts", "", "message", "", "onErrorSendingSMS", "onSuccessGettingAllContacts", "response", "Lcom/example/contacts/model/Contacts;", "onSuccessSendingSMS", "t", "Lcom/example/contacts/model/SmsResponse;", "setProgressBarVisibility", "visibility", "", "app_debug"}) public static abstract interface ContactsView extends com.example.contacts.BaseView<com.example.contacts.Contract.ContactsPresenter> { public abstract void onSuccessGettingAllContacts(@org.jetbrains.annotations.NotNull() com.example.contacts.model.Contacts response); public abstract void onErrorGettingContacts(@org.jetbrains.annotations.NotNull() java.lang.String message); public abstract void setProgressBarVisibility(boolean visibility); public abstract void onSuccessSendingSMS(@org.jetbrains.annotations.NotNull() com.example.contacts.model.SmsResponse t); public abstract void onErrorSendingSMS(@org.jetbrains.annotations.NotNull() java.lang.String message); } @kotlin.Metadata(mv = {1, 1, 13}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u001a\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0002\b\u0004\bf\u0018\u00002\u00020\u0001J\b\u0010\u0002\u001a\u00020\u0003H&J(\u0010\u0004\u001a\u00020\u00032\u0006\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u0007\u001a\u00020\u00062\u0006\u0010\b\u001a\u00020\u00062\u0006\u0010\t\u001a\u00020\u0006H&\u00a8\u0006\n"}, d2 = {"Lcom/example/contacts/Contract$ContactsPresenter;", "Lcom/example/contacts/BasePresenter;", "getAllContacts", "", "sendSMS", "firstName", "", "lastName", "number", "message", "app_debug"}) public static abstract interface ContactsPresenter extends com.example.contacts.BasePresenter { public abstract void getAllContacts(); public abstract void sendSMS(@org.jetbrains.annotations.NotNull() java.lang.String firstName, @org.jetbrains.annotations.NotNull() java.lang.String lastName, @org.jetbrains.annotations.NotNull() java.lang.String number, @org.jetbrains.annotations.NotNull() java.lang.String message); } }
[ "arjunmanoj1995@gmail.com" ]
arjunmanoj1995@gmail.com
7b349615e4e7b807dd098854f05c0773a318e0d8
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-customerprofiles/src/main/java/com/amazonaws/services/customerprofiles/model/transform/DeleteProfileObjectTypeRequestMarshaller.java
d45dd5201512f34f049ea7d313de3d385c1a3ad4
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
2,450
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.customerprofiles.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.customerprofiles.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteProfileObjectTypeRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteProfileObjectTypeRequestMarshaller { private static final MarshallingInfo<String> DOMAINNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("DomainName").build(); private static final MarshallingInfo<String> OBJECTTYPENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PATH).marshallLocationName("ObjectTypeName").build(); private static final DeleteProfileObjectTypeRequestMarshaller instance = new DeleteProfileObjectTypeRequestMarshaller(); public static DeleteProfileObjectTypeRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteProfileObjectTypeRequest deleteProfileObjectTypeRequest, ProtocolMarshaller protocolMarshaller) { if (deleteProfileObjectTypeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteProfileObjectTypeRequest.getDomainName(), DOMAINNAME_BINDING); protocolMarshaller.marshall(deleteProfileObjectTypeRequest.getObjectTypeName(), OBJECTTYPENAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
2209d9c108a634dddd7924d1fcbffc092982664e
dbd76cf6fe6ab6d4871ddb3983409345b3f915b5
/src/main/java/com/web/sangsang/cmm/entity/SsUserPlace.java
852dfe6d07a59410abd7b9c3f11ef6e22b34a05c
[]
no_license
oneYong/sangsang_web
3f2546bfe58fceb1939c5764f84359a464f4415d
2d6f1628b0b73473d59697a26675db0b11bad7b8
refs/heads/master
2021-01-13T11:31:26.077302
2017-03-23T08:33:37
2017-03-23T08:33:37
77,814,670
1
1
null
null
null
null
UTF-8
Java
false
false
528
java
package com.web.sangsang.cmm.entity; import com.web.sangsang.cmm.entity.annotation.Column; import com.web.sangsang.cmm.entity.annotation.Table; import lombok.Data; /** * 사용자-장소 */ @Table(name="SS_USER_PLACE") @Data public class SsUserPlace extends BaseEntity{ @Column(name="USER_UID",primarykey = true) private String userUid; @Column(name="PLACE_ID",primarykey = true) private Long placeId; @Column(name="VISIT_CONFIRM") private Boolean visitConfirm; @Column(name="INTEREST") private Boolean interest; }
[ "pig@neuttiui-Mac-mini.local" ]
pig@neuttiui-Mac-mini.local
309538cbd9df69b49ab2d7341ef1dd9f49546732
f0548f3357920d9baedd5190a2c4e82d8bbd7b1c
/src/main/java/factory/products/group/CreateGroup.java
c62e480ea65d43c4505b86e91ec2f41a93430a78
[]
no_license
enet71/Schedule
f8ea38122de9de167d73a6603c73771d92481abd
feaccd1fe5ffd8da493f9addc00a507e567875de
refs/heads/master
2020-07-02T08:10:26.658189
2016-10-29T13:05:05
2016-10-29T13:05:05
66,884,876
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
769
java
package factory.products.group; import db.Connect; import factory.abstractProducts.Create; import java.sql.SQLException; import java.sql.Statement; public class CreateGroup extends Create{ /** * Добавляет новую группу * * @param args Список параметров для создания. */ @Override public void insert(String... args) { Connect connect = new Connect(); Statement statement = connect.getStatement(); try { statement.executeUpdate("INSERT INTO GRP VALUES (null,'" + args[0] + "'," + args[1] + "," + args[2] + ")"); } catch (SQLException e) { e.printStackTrace(); }finally { connect.closeConnect(); } } }
[ "enet71@gmail.com" ]
enet71@gmail.com
05c081a0ff2c0fa83fdd6f317fed8e9adf0d70f1
1029b8af87e1a4fa3c83078304cdb88195616c41
/app/src/main/java/com/example/locationattendance/PasswordActivity.java
cbd8a69598f9cfdd0450fc4ea1b25a3487567d8c
[]
no_license
sonder233/LocationAttendance
83aa4dd43914fa3f1f556c9935160f2ca548ef59
b6a37a7a8259605cd627cdabc04dae41ebf35e3c
refs/heads/master
2023-02-04T01:34:02.816047
2020-12-13T17:58:37
2020-12-13T17:58:37
299,596,975
0
0
null
null
null
null
UTF-8
Java
false
false
1,800
java
package com.example.locationattendance; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class PasswordActivity extends AppCompatActivity { @BindView(R.id.ivBack) ImageView IV_back; @BindView(R.id.etPhone) EditText ET_phone; @BindView(R.id.etPassword) EditText ET_password; private String phoneNumber; private String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_password); //绑定butterKnife ButterKnife.bind(this); Intent intent = getIntent(); phoneNumber = intent.getStringExtra("phone_number"); ET_phone.setText(phoneNumber); ET_phone.setEnabled(false); //调试用 ET_password.setText("123456"); } @OnClick(R.id.tvConfirm) public void OnClickRegister(){ if (ET_password.getText().equals("")){ Toast.makeText(this, "请输入密码!", Toast.LENGTH_SHORT).show(); }else{ Dao dao = new Dao(PasswordActivity.this); password = ET_password.getText().toString().trim(); //dao.insert(); if(dao.queryUsername(phoneNumber)){ Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show(); } } } /*返回*/ @OnClick(R.id.ivBack) public void OnClickBack(){ finish(); } }
[ "2332447236@qq.com" ]
2332447236@qq.com
29d09f7842f3e8a52d013f06616def1bb5fee503
2e5409e1b5e19b75ca988cd76cc3c0748c4f0fdd
/sector-manager/src/test/java/pl/kijko/sectormanager/DefaultSectorManagerTest.java
a915a785c96673f5c808ae7a2329761f2579e6b0
[]
no_license
kijko/signalling
c6b25a5c4d182ba21b397be8988ef5e8bab1e91a
56f921988fb31dcc47732082b1b612535fffcc1c
refs/heads/master
2023-05-02T13:45:41.913385
2021-05-29T12:27:14
2021-05-29T12:27:14
320,863,934
0
0
null
null
null
null
UTF-8
Java
false
false
6,430
java
package pl.kijko.sectormanager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @SuppressWarnings("ALL") public class DefaultSectorManagerTest { private String managerName = "A"; private int numOfSectors = 3; private SectorMessageSender sender = mock(SectorMessageSender.class); private SectorMessageReceiver receiver = mock(SectorMessageReceiver.class); private SectorManager manager; @BeforeEach void setUp() { manager = new DefaultSectorManager(managerName, numOfSectors, sender, receiver); } @Test @DisplayName("should initialize sectors correctly") void getSectorsCorrectly() { // GIVEN-WHEN List<Sector> sectors = manager.getSectors(); // THEN assertEquals(3, sectors.size()); assertEquals("1", sectors.get(0).id); assertEquals("2", sectors.get(1).id); assertEquals("3", sectors.get(2).id); sectors.forEach(sector -> assertFalse(sector.isInNeed())); } @Test @DisplayName("should behave correctly on incoming help message") void behaveCorrectlyOnHelpMessage() { // GIVEN AtomicReference<Consumer<SectorMessage>> incomingMessageEvent = new AtomicReference<>(); SectorMessageReceiver customReceiver = newValue -> { incomingMessageEvent.set(newValue); return CommunicationResult.SUCCESS; }; manager = new DefaultSectorManager(managerName, numOfSectors, sender, customReceiver); SectorMessage incomingMessage = SectorMessage.toSector(managerName, "1", SectorMessage.SectorCommand.HELP); var onSectorChange = mock(Consumer.class); manager.addSectorChangeListener(onSectorChange); // WHEN incomingMessageEvent.get().accept(incomingMessage); // message received // THEN Sector sector = manager.getSectors().stream().filter(it -> it.id.equals("1")).findFirst().get(); assertEquals("1", sector.id); assertTrue(sector.isInNeed()); verify(receiver, times(1)).addMessageHandler(any()); verify(onSectorChange, times(1)).accept(sector); } @Test @DisplayName("should behave correctly on incoming cancel message") void behaveCorrectlyOnCancelMessage() { // GIVEN AtomicReference<Consumer<SectorMessage>> incomingMessageEvent = new AtomicReference<>(); SectorMessageReceiver customReceiver = newValue -> { incomingMessageEvent.set(newValue); return CommunicationResult.SUCCESS; }; manager = new DefaultSectorManager(managerName, numOfSectors, sender, customReceiver); SectorMessage incomingMessage = SectorMessage.toSector(managerName, "3", SectorMessage.SectorCommand.CANCEL); var onSectorChange = mock(Consumer.class); manager.addSectorChangeListener(onSectorChange); Sector sectorNeedsHelp = manager.getSectors().stream().filter(sector -> sector.id.equals("3")).findFirst().get(); sectorNeedsHelp.needsHelp(); assertTrue(manager.getSectors().stream().filter(sector -> sector.id.equals("3")).findFirst().get().isInNeed()); // WHEN incomingMessageEvent.get().accept(incomingMessage); // message received // THEN Sector sector = manager.getSectors().stream().filter(it -> it.id.equals("3")).findFirst().get(); assertEquals("3", sector.id); assertFalse(sector.isInNeed()); verify(receiver, times(1)).addMessageHandler(any()); verify(onSectorChange, times(1)).accept(sector); } @Test @DisplayName("should send got-it message and set sector as resolved") void resolveSector() { // GIVEN Sector sectorInNeed = manager.getSectors().stream().filter(it -> it.id.equals("3")).findFirst().get(); sectorInNeed.needsHelp(); assertTrue(sectorInNeed.isInNeed()); var onSectorChange = mock(Consumer.class); manager.addSectorChangeListener(onSectorChange); when(sender.send(any())).thenReturn(CommunicationResult.SUCCESS); // WHEN Sector modifiedSector = manager.resolve(sectorInNeed); // THEN assertSame(modifiedSector, sectorInNeed); assertFalse(sectorInNeed.isInNeed()); verify(sender, times(1)) .send(eq(SectorMessage.toSector(managerName, "3", SectorMessage.SectorCommand.GOT_IT))); verify(onSectorChange, times(1)).accept(sectorInNeed); } @Test @DisplayName("should not resolve sector because of sending error") void doNotResolve1() { // GIVEN Sector sectorInNeed = manager.getSectors().stream().filter(it -> it.id.equals("3")).findFirst().get(); sectorInNeed.needsHelp(); assertTrue(sectorInNeed.isInNeed()); var onSectorChange = mock(Consumer.class); manager.addSectorChangeListener(onSectorChange); when(sender.send(any())).thenReturn(CommunicationResult.ERROR); // WHEN Sector modifiedSector = manager.resolve(sectorInNeed); // THEN assertSame(modifiedSector, sectorInNeed); assertTrue(sectorInNeed.isInNeed()); verify(sender, times(1)) .send(eq(SectorMessage.toSector(managerName, "3", SectorMessage.SectorCommand.GOT_IT))); verify(onSectorChange, times(0)).accept(sectorInNeed); } @Test @DisplayName("should not send got-it message - change nothing") void doNotResolve2() { // GIVEN Sector sectorInNeed = manager.getSectors().stream().filter(it -> it.id.equals("3")).findFirst().get(); assertFalse(sectorInNeed.isInNeed()); var onSectorChange = mock(Consumer.class); manager.addSectorChangeListener(onSectorChange); // WHEN Sector modifiedSector = manager.resolve(sectorInNeed); // THEN assertSame(modifiedSector, sectorInNeed); assertFalse(sectorInNeed.isInNeed()); verify(sender, times(0)) .send(eq(SectorMessage.toSector(managerName, "3", SectorMessage.SectorCommand.GOT_IT))); verify(onSectorChange, times(0)).accept(sectorInNeed); } }
[ "kijkomaciej@gmail.com" ]
kijkomaciej@gmail.com
ebdf6d26fb6caa475e38ae7b70a38b26e851fedb
6cfcc977fff2a4be248ccafb2420b62af72ef29f
/src/mac/himanshu/sort/SortIntegers.java
7da3217b2f7b463aa1cea9305b9c458587d3a93f
[]
no_license
HimanshuChhabra/PracticeProblems
7a5dec3ad86f9a48f6c2cce247aa727890f33f90
1dc505bc42c2b2326173c06f13ad0d56e1a41d0c
refs/heads/master
2020-03-31T18:40:43.545971
2019-02-04T16:27:52
2019-02-04T16:27:52
152,467,993
0
0
null
null
null
null
UTF-8
Java
false
false
94
java
package mac.himanshu.sort; public interface SortIntegers { public void sort(int input[]); }
[ "himanshu.chhabra9304@gmail.com" ]
himanshu.chhabra9304@gmail.com
2c518bb4959f853604f44152127b080c9a170c57
61669cab28a9e33968b2ceca06806ab4e31bb417
/src/item/Item.java
51c92d7003bebf663188722381895c4c4a48d510
[]
no_license
kOchirasu/GridGame
b4acfa2cb8db6943486b030d9b38757a08a32720
7e97ea054311b26b50fa73eede5cfab8a16ea88d
refs/heads/master
2021-05-29T05:23:10.663105
2015-01-28T03:03:50
2015-01-28T03:03:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,171
java
package item; import graphics.SpriteLoader; import gridGame.Game; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.RadialGradientPaint; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.sql.ResultSet; import java.sql.SQLException; public class Item { int iD, type, minRange, maxRange, ability, atk, mAtk, acc, crit, value; String name; BufferedImage image; public Item(ItemLoader lookup, int iD) { try { ResultSet rs = lookup.search(iD); this.iD = iD; this.type = iD / 10000; //Gets first two digits of iD this.name = rs.getString("NAME"); this.minRange = rs.getInt("MINRANGE"); this.maxRange = rs.getInt("MAXRANGE"); this.ability = rs.getInt("ABILITY"); this.atk = rs.getInt("ATTACK"); this.mAtk = rs.getInt("MAGIC_ATTACK"); this.acc = rs.getInt("ACCURACY"); this.crit = rs.getInt("CRITICAL"); this.value = rs.getInt("VALUE"); } catch (SQLException ex) { System.out.println(ex.getMessage()); } SpriteLoader loader = new SpriteLoader(); this.image = loader.load("/Item/" + iD + ".png"); } //Normal item rendering function public void render(int x, int y, int r, Graphics g) { g.drawImage(image, x, y, Game.TILESIZE / r, Game.TILESIZE / r, null); } //used to render semi-transparent item when dragging public void render(int x, int y, Graphics g) { Graphics2D g2 = (Graphics2D) g; Point2D center = new Point2D.Float(x + Game.TILESIZE / 2, y + Game.TILESIZE /2); float radius = 15; float[] dist = {0.1f, 1f}; Color[] colors = {Color.DARK_GRAY, new Color(255, 255, 255, 0)}; RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors, CycleMethod.NO_CYCLE); g2.setPaint(p); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 0.5)); g2.fillOval(x, y, Game.TILESIZE, Game.TILESIZE); g2.drawImage(image, x, y, Game.TILESIZE, Game.TILESIZE, null); } @Override public String toString() { return "Item ID: \t" + iD + "\nName: \t\t" + name + "\nRange: \t\t" + minRange + "~" + maxRange + "\nAtt/M.Att: \t" + atk + "/" + mAtk + "\nAccuracy: \t" + acc + "\nCritical: \t" + crit + "\nSale Price: \t" + value; } public int getID() { return iD; } public String getNAME() { return name; } public int getATK() { return atk; } public int getMATK() { return mAtk; } public int getACC() { return acc; } public int getCRIT() { return crit; } public int getMinRANGE() { return minRange; } public int getMaxRANGE() { return maxRange; } public int getValue() { return value; } }
[ "2yangk23@gmail.com" ]
2yangk23@gmail.com
9c59ce0376624a07603f22a041aa18bdee2bc2ad
430aff6937808d11d310e65effaeb813234aa7a9
/app/src/main/java/com/alvindizon/launcher/features/main/MainViewModel.java
40834fc070e0f4b4af66a1aecfff098795aae93c
[]
no_license
alvindizon/launcher
9dfc9a646dbfc2ede3ddc179c33870a149cf1c04
29c84f921d95ef0b15a4a3e069fdd67b449b8ba6
refs/heads/master
2021-07-21T21:29:39.205270
2020-07-06T04:57:33
2020-07-06T04:57:33
193,343,126
0
1
null
null
null
null
UTF-8
Java
false
false
7,023
java
package com.alvindizon.launcher.features.main; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.alvindizon.launcher.core.Const; import com.alvindizon.launcher.core.applist.AppModel; import com.alvindizon.launcher.data.FaveAppDao; import com.alvindizon.launcher.data.FaveAppRecord; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; public class MainViewModel extends ViewModel { private final FaveAppDao faveAppDao; private final PackageManager packageManager; private CompositeDisposable compositeDisposable; private MutableLiveData<List<AppModel>> listData = new MutableLiveData<>(); @Inject public MainViewModel(FaveAppDao faveAppDao, PackageManager packageManager) { this.faveAppDao = faveAppDao; this.packageManager = packageManager; this.compositeDisposable = new CompositeDisposable(); } public LiveData<List<AppModel>> getListData() { return listData; } public LiveData<List<AppModel>> getLaunchableApps() { MutableLiveData<List<AppModel>> appListData = new MutableLiveData<>(); compositeDisposable.add(getLaunchableList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(appListData::setValue, Throwable::printStackTrace)); return appListData; } public void loadFaveAppList() { compositeDisposable.add(Single.fromCallable(faveAppDao::getAllRecords) .flatMap(this::loadSavedFavoriteApps) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listData::setValue, Throwable::printStackTrace)); } /** * Takes an AppModel object, converts it to FaveAppRecord, and inserts it * to the DB. If the app already exists in the faveapps DB, it is ignored and not added. * @param app An AppModel object that is */ public void addFaveApp(AppModel app) { compositeDisposable.add(Completable.fromAction(() -> faveAppDao.insert(new FaveAppRecord(app.getPackageName(), app.getAppLabel())) ) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> {}, Throwable::printStackTrace) ); } /** * Removes an app from the faveapps DB via its package name. * @param app An app to be removed from the db */ public void deleteFaveApp(AppModel app) { compositeDisposable.add(Completable.fromAction(() -> faveAppDao.deleteRecordByPackageName(app.getPackageName())) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> {}, Throwable::printStackTrace) ); } private Single<List<AppModel>> getLaunchableList() { List<AppModel> data = new ArrayList<>(); return Single.create(emitter -> { try { for(ResolveInfo resolveInfo : getLaunchableActivities()) { String appLabel =(String) resolveInfo.loadLabel(packageManager); if(appLabel.equals(Const.APP_NAME)) { continue; } data.add(new AppModel(resolveInfo.activityInfo.packageName, appLabel, packageManager.getApplicationIcon(resolveInfo.activityInfo.applicationInfo))); } } catch (Exception e) { e.printStackTrace(); emitter.tryOnError(e); } emitter.onSuccess(data); }); } private Single<List<AppModel>> loadSavedFavoriteApps(List<FaveAppRecord> faveAppRecords) { return Single.fromCallable(() -> { List<AppModel> faveList = new ArrayList<>(); // transform favorites retrieved from DB to appmodels that will be used in the UI for (FaveAppRecord faveAppRecord : faveAppRecords) { ApplicationInfo appInfo; try { appInfo = packageManager.getApplicationInfo(faveAppRecord.getPackageName(), 0); faveList.add(new AppModel( appInfo.packageName, packageManager.getApplicationLabel(appInfo).toString(), packageManager.getApplicationIcon(appInfo))); } catch (PackageManager.NameNotFoundException e) { // app was deleted/uninstalled, so delete record from DB faveAppDao.deleteRecordByPackageName(faveAppRecord.getPackageName()); e.printStackTrace(); } } return faveList; }); } private List<ResolveInfo> getLaunchableActivities() { Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> resInfos = packageManager.queryIntentActivities(intent, 0); Collections.sort(resInfos, new ResolveInfo.DisplayNameComparator(packageManager)); return resInfos; } /** * If fave apps are rearranged, overwrite existing fave apps list via this method. * This method basically calls an @Insert-annotated method with a REPLACE conflict strategy, which means * that if a similar record of a favorite app already exists in the DB, it will be replaced. * @param updatedList The list with rearranged favorite apps */ public void updateList(List<AppModel> updatedList) { compositeDisposable.add( Single.fromCallable(() -> { List<FaveAppRecord> dbList = new ArrayList<>(); for(AppModel appModel : updatedList) { dbList.add(new FaveAppRecord(appModel.getPackageName(), appModel.getAppLabel())); } return dbList; }) .flatMapCompletable(records -> Completable.fromAction(() -> faveAppDao.insert(records))) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> {}, Throwable::printStackTrace) ); } public void clearFaveApps() { compositeDisposable.add(faveAppDao.clearFaveAppDb() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> {}, Throwable::printStackTrace) ); } }
[ "alvin.dizon91@gmail.com" ]
alvin.dizon91@gmail.com
5c745094022a72a5b49249fe00c6dca0aef47726
cb2e6417ccc2b663f4196d1cb97a6b3decef7cd5
/Camera221/app/src/main/java/jp/ohwada/android/camera221/util/Camera2Base.java
b167d18dfd057641532a103513660eebc837376c
[]
no_license
tiendung690/Android_Samples
194c02668a812dcf25d2580fb968d7722c6afb2a
282b11ec28193c0308ae6039068d6d8903dc02e8
refs/heads/master
2021-02-27T12:05:18.406016
2020-03-07T10:11:49
2020-03-07T10:11:49
245,604,927
1
0
null
null
null
null
UTF-8
Java
false
false
42,678
java
/** * Camera2 Sample * Camera2Base * 2019-08-01 K.OHWADA */ package jp.ohwada.android.camera221.util; import android.content.Context; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.os.Handler; import android.os.HandlerThread; import android.util.DisplayMetrics; import android.util.Log; import android.util.Size; import android.util.SparseIntArray; import android.view.Display; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureFailure; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.MeteringRectangle; import android.hardware.camera2.params.StreamConfigurationMap; import android.hardware.camera2.CameraCharacteristics.Key; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Semaphore; import jp.ohwada.android.camera221.ui.AutoFitTextureView; /** * class Camera2Base * similar to CameraSource of Vision API * original : https://github.com/EzequielAdrianM/Camera2Vision */ public class Camera2Base { // debug protected final static boolean D = true; protected final static String TAG = "Camera2"; protected final static String TAG_BASE = "Camera2Base"; // image size、value for Nexus5 public final static int DEFAULT_WIDTH = 1280; public final static int DEFAULT_HEIGHT = 768; protected final static String LF = "\n"; /** * Camera state: Device is closed. */ public static final int STATE_CLOSED = 0; /** * Camera state: Device is opened, but is not capturing. */ public static final int STATE_OPENED = 1; /** * Camera state: Showing camera preview. */ public static final int STATE_PREVIEW = 2; /** * Camera state: Waiting for the focus to be locked. */ public static final int STATE_WAITING_LOCK = 3; /** * Camera state: Waiting for the exposure to be precapture state. */ public static final int STATE_WAITING_PRECAPTURE = 4; /** * Camera state: Waiting for the exposure state to be something other than precapture. */ public static final int STATE_WAITING_NON_PRECAPTURE = 5; /** * Camera state: Picture was taken. */ public static final int STATE_PICTURE_TAKEN = 6; // camera face public static final int CAMERA_FACING_BACK = CameraCharacteristics.LENS_FACING_BACK; public static final int CAMERA_FACING_FRONT = CameraCharacteristics.LENS_FACING_FRONT; protected int mFacing = CAMERA_FACING_BACK; // CaptureRequest // AE : auto exposure mode public static final int CAMERA_AE_OFF = CaptureRequest.CONTROL_AE_MODE_OFF; public static final int CAMERA_AE_ON = CaptureRequest.CONTROL_AE_MODE_ON; public static final int CAMERA_AE_AUTO_FLASH = CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH; public static final int CAMERA_AE_ON_ALWAYS_FLASH = CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH; public static final int CAMERA_AE_AUTO_FLASH_REDEYE = CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE; protected int mFlashMode = CAMERA_AE_AUTO_FLASH; // AF : auto focas mode public static final int CAMERA_AF_AUTO = CaptureRequest.CONTROL_AF_MODE_AUTO; public static final int CAMERA_AF_EDOF = CaptureRequest.CONTROL_AF_MODE_EDOF; public static final int CAMERA_AF_MACRO = CaptureRequest.CONTROL_AF_MODE_MACRO; public static final int CAMERA_AF_OFF = CaptureRequest.CONTROL_AF_MODE_OFF; public static final int CAMERA_AF_CONTINUOUS_PICTURE = CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE; public static final int CAMERA_AF_CONTINUOUS_VIDEO = CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO; protected int mFocusMode = CAMERA_AF_AUTO; // AWB : Auto white Baance mode //Value: 0: public final static int CAMERA_AWB_OFF = CaptureRequest.CONTROL_AWB_MODE_OFF; // Value: 1: public final static int CAMERA_AWB_AUTO = CaptureRequest.CONTROL_AWB_MODE_AUTO; // hardware level // 0 public static final int LEVEL_LIMITED = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL; // 1 public static final int LEVEL_FULL = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED; // 2 public static final int LEVEL_LEGACY = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; // 3 public static final int LEVEL_3 = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3; // Added in API level 28 // 4 //public static final int LEVEL_EXTERNAL = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL; public static final int LEVEL_NOT_SUPPORT = -1; public static final int LEVEL_NOT_FOUND = -2; public static final int LEVEL_NONE = -3; // CameraDevice StateCallback Error // value 1 private static final int ERROR_CAMERA_IN_USE = CameraDevice.StateCallback.ERROR_CAMERA_IN_USE; // value 2 private static final int ERROR_MAX_CAMERAS_IN_USE = CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE; // value 3 private static final int ERROR_CAMERA_DISABLED = CameraDevice.StateCallback.ERROR_CAMERA_DISABLED; // value 4 private static final int ERROR_CAMERA_DEVICE = CameraDevice.StateCallback.ERROR_CAMERA_DEVICE; // value 5 private static final int ERROR_CAMERA_SERVICE = CameraDevice.StateCallback.ERROR_CAMERA_SERVICE; // choiceBestAspectPictureSize protected static final double RATIO_TOLERANCE = 0.1; protected static final double MAX_RATIO_TOLERANCE = 0.18; protected static final SparseIntArray ORIENTATIONS = new SparseIntArray(); protected static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray(); /** * Clockwise angle through which the output image needs to be rotated to be upright on the device screen in its native orientation */ protected int mSensorOrientation; /** * the rotation of the screen from its "natural" orientation. */ protected int mDisplayRotation; /** * isSwappedDimensions that can be used by the record video routine. */ protected boolean isSwappedDimensions = false; protected Context mContext; // view protected AutoFitTextureView mTextureView; protected SurfaceView mViewSurfaceView; protected Surface mViewSurface; /** * A lock protecting camera state. */ protected final Object mCameraStateLock = new Object(); /** * A reference to the opened {@link CameraDevice}. */ protected CameraDevice mCameraDevice; /** * An additional thread for running tasks that shouldn't block the UI. */ protected HandlerThread mBackgroundThread; /** * A {@link Handler} for running tasks in the background. */ protected Handler mBackgroundHandler; /** * {@link CaptureRequest.Builder} for the camera preview */ protected CaptureRequest.Builder mPreviewRequestBuilder; /** * {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder} */ protected CaptureRequest mPreviewRequest; /** * The current state of camera state for taking pictures. * * @see #mCaptureCallback */ protected int mState = STATE_CLOSED; /** * A {@link CameraCaptureSession } for camera preview. */ protected CameraCaptureSession mCaptureSession; /** * The {@link Size} of camera preview. */ protected Size mPreviewSize; /** * The size of the largest JPEG format image of the camera supports */ protected Size mLargestSize; /** * ID of the current {@link CameraDevice}. */ protected String mCameraId; /** * Max preview width that is guaranteed by Camera2 API */ protected static final int MAX_PREVIEW_WIDTH = 1920; /** * Max preview height that is guaranteed by Camera2 API */ protected static final int MAX_PREVIEW_HEIGHT = 1080; static { ORIENTATIONS.append(Surface.ROTATION_0, 90); ORIENTATIONS.append(Surface.ROTATION_90, 0); ORIENTATIONS.append(Surface.ROTATION_180, 270); ORIENTATIONS.append(Surface.ROTATION_270, 180); } static { INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270); INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180); INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90); INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0); } /** * A {@link Semaphore} to prevent the app from exiting before closing the camera. */ protected Semaphore mCameraOpenCloseLock = new Semaphore(1); /** * The area of the image sensor which corresponds to active pixels after any geometric distortion correction has been applied * The area that can be used by the auto-focus (AF) routine. */ protected Rect mSensorArraySize; /** * Whether the current camera device supports Flash or not. */ protected boolean isFlashSupported; /** * metering regions that can be used by the auto-focus (AF) routine. */ protected boolean isMeteringAreaAFSupported = false; /** * Flag whether to support AutoFocusContinuousPicture * CONTROL_AF_MODE_AUTO */ protected boolean isAutoFocusSupported = false; /** * Flag whether to support AutoFocusContinuousPicture * CONTROL_AF_MODE_CONTINUOUS_PICTURE */ protected boolean isAutoFocusContinuousPictureSupported = false; /** * Flag whether to support AutoExposureOn * CONTROL_AE_MODE_ON */ protected boolean isAutoExposureOnSupported = false; /** * Flag whether to support AutoFlash * CONTROL_AE_MODE_ON_AUTO_FLASH */ protected boolean isAutoFlashSupported = false; /** * Flag whether to support AutoWhiteBalnce * CONTROL_AWB_MODE_AUTO */ protected boolean isAutoWhiteBalnceSupported = false; /** * Callback interface used to indicate when an error occurs */ public interface ErrorCallback{ public void onError(String msg); } protected ErrorCallback mErrorCallback; /** * constractor */ public Camera2Base() { // nop } /** * constractor */ public Camera2Base(Context context) { mContext = context; } /** * setFocusMode */ public void setFocusMode(int mode) { mFocusMode = mode; } /** * setFlashMode */ public void setFlashMode(int mode) { mFlashMode = mode; } /** * setFacing */ public void setFacing(int facing) { mFacing = facing; } /** * setErrorCallback */ public void setErrorCallback(ErrorCallback cb) { mErrorCallback = cb; } /** * getCameraFacing */ public int getCameraFacing() { return mFacing; } /** * isCameraFacingFront */ public boolean isCameraFacingFront() { boolean isFront = false; if (mFacing == CAMERA_FACING_FRONT) { isFront = true; } return isFront; } /** * getPreviewSize */ public Size getPreviewSize() { return mPreviewSize; } /** * getSensorArraySize */ public Rect getSensorArraySize() { return mSensorArraySize; } /** * isSwappedDimensions */ public boolean isSwappedDimensions() { return isSwappedDimensions; } /** * startBackgroundThread */ protected void startBackgroundThread() { log_base("startBackgroundThread"); mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } /** * stopBackgroundThread */ protected void stopBackgroundThread() { log_base("stopBackgroundThread"); try { if(mBackgroundThread != null) { mBackgroundThread.quitSafely(); mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } } catch (InterruptedException e) { e.printStackTrace(); } } /** * release */ public void release() { log_base("release"); stop(); } /** * stop */ public void stop() { log_base("stop"); synchronized (mCameraStateLock) { mState = STATE_CLOSED; } try { mCameraOpenCloseLock.acquire(); if (null != mCaptureSession) { mCaptureSession.close(); mCaptureSession = null; } if (null != mCameraDevice) { mCameraDevice.close(); mCameraDevice = null; } } catch (Exception e) { e.printStackTrace(); } finally { mCameraOpenCloseLock.release(); stopBackgroundThread(); } stopExtend(); } // stop /** * stopExtend */ protected void stopExtend() { } /** * getState */ public int getState() { return mState; } // getState /** * getDeviceLevel */ public int getDeviceLevel() { log_base("getDeviceLevel"); CameraManager manager = null; String cameraId = null; int deviceLevel = LEVEL_NONE; try { manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); if (manager != null) { cameraId = getCameraId(manager, mFacing); CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); } } catch (Exception ex) { ex.printStackTrace(); } if (manager == null) return LEVEL_NOT_SUPPORT; if( cameraId == null ) return LEVEL_NOT_FOUND; return deviceLevel; } // getDeviceLevel /** * isCamera2Native */ public boolean isCamera2Native() { log_base("isCamera2Native"); int deviceLevel = getDeviceLevel(); // This camera device is running in backward compatibility mode. boolean ret = (deviceLevel == LEVEL_LEGACY)? true: false; return ret; } // isCamera2Native /** * start with AutoFitTextureView */ public void start(AutoFitTextureView textureView) { log_base(" start AutoFitTextureView"); mTextureView = textureView; setUpCameraOutputs(textureView.getWidth(), textureView.getHeight() ); SurfaceTexture texture = textureView.getSurfaceTexture(); if(mPreviewSize != null) { texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } mViewSurface = new Surface(texture); startBackgroundThread(); prepareCamera(); openCamera(); } // start /** * start with SurfaceView */ public void start(SurfaceView surfaceView) { log_base(" start SurfaceView"); mViewSurfaceView = surfaceView; SurfaceHolder holder = mViewSurfaceView.getHolder(); mViewSurface = holder.getSurface(); setUpCameraOutputs(surfaceView.getWidth(), surfaceView.getHeight()); startBackgroundThread(); prepareCamera(); openCamera(); } // start /** * setUpCameraOutputs */ protected void setUpCameraOutputs(int width, int height) { log_base("setUpCameraOutputs"); // check permission if (!CameraPerm.isCameraGranted(mContext)) { notifyError("NOT Permission to access Camera"); return; } CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); if(manager == null) { notifyError("This device doesn't support Camera2 API"); return; } mCameraId = getCameraId(manager, mFacing); log_base("cameraId= " + mCameraId); if(mCameraId == null) { notifyError("NOT found " + getCameraFaceString()); return; } CameraCharacteristics characteristics = null; StreamConfigurationMap map = null; try { characteristics = manager.getCameraCharacteristics(mCameraId); map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); } catch (CameraAccessException e) { e.printStackTrace(); } if (characteristics == null) { log_base("characteristics null"); return; } if (map == null) { log_base("map null"); return; } // For still image captures, we use the largest available size. mLargestSize = getJpegLargestSize(map); log_base( "LargestSize: " +mLargestSize.toString() ); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); log_base("SensorOrientation: " + mSensorOrientation); mDisplayRotation = DisplayUtil.getDisplayRotation(mContext); log_base("DisplayRotation: " + mDisplayRotation); // Find out if we need to swap dimension to get the preview size relative to sensor coordinate. isSwappedDimensions = getSwappedDimensions(); mPreviewSize = calcPreviewSize(map, width, height, mLargestSize, isSwappedDimensions); // The area of the image sensor which corresponds to active pixels after any geometric distortion correction has been applied. mSensorArraySize = getSensorArraySize(characteristics); //The maximum number of metering regions that can be used by the auto-focus (AF) routine. isMeteringAreaAFSupported = hasMeteringAreaAFSupported(characteristics); // Check if the flash is supported. isFlashSupported = hasFlashSupport(characteristics); configureTransform(width, height, mPreviewSize, mDisplayRotation); setUpExtend( characteristics); } // setUpCameraOutputs /** * setUpExtend * for override */ protected void setUpExtend(CameraCharacteristics characteristics) { // nop } /** * setUp3ACotrol */ protected void setUp3ACotrol(CameraCharacteristics characteristics) { isAutoFocusSupported = containsCharacteristics(characteristics, CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES, CameraMetadata.CONTROL_AF_MODE_AUTO ); log_base("AutoFocusAuto: " + isAutoFocusSupported); isAutoFocusContinuousPictureSupported = containsCharacteristics(characteristics, CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE ); log_base("AutoFocusContinuousPicture: " + isAutoFocusContinuousPictureSupported); isAutoExposureOnSupported = containsCharacteristics(characteristics, CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES, CaptureRequest.CONTROL_AE_MODE_ON ); log_base("AutoExposureOn: " + isAutoExposureOnSupported); isAutoFlashSupported = containsCharacteristics(characteristics, CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH ); log_base("isAutoFlashSupported: " + isAutoFlashSupported); isAutoWhiteBalnceSupported = containsCharacteristics(characteristics, CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES, CameraCharacteristics.CONTROL_AWB_MODE_AUTO ); log_base("AutoWhiteBalnce: " + isAutoWhiteBalnceSupported); } /** * getAutoFocusPictureMode */ protected int getAutoFocusPictureMode() { int mode = CAMERA_AF_OFF; if(isAutoFocusContinuousPictureSupported) { mode = CAMERA_AF_CONTINUOUS_PICTURE ; } else if(isAutoFocusSupported) { mode = CAMERA_AF_AUTO; } log_base("getAutoFocusPictureMode: " + mode); return mode; } /** * getAutoExposureFlashMode */ protected int getAutoExposureFlashMode() { int mode = CAMERA_AE_OFF; if (isAutoFlashSupported) { mode = CAMERA_AE_AUTO_FLASH; } else if (isAutoExposureOnSupported) { mode = CAMERA_AE_ON; } log_base("getAutoExposureFlashMode: " + mode); return mode; } /** * getAutoWhiteBalanceMode */ protected int getAutoWhiteBalanceMode() { int mode = CAMERA_AWB_OFF; if (isAutoWhiteBalnceSupported) { mode = CAMERA_AWB_AUTO; } log_base("getAutoWhiteBalanceMode: " + mode); return mode; } /** * checkAvailableCapabilities */ protected boolean checkAvailableCapabilities(CameraCharacteristics characteristics, int key) { return containsCharacteristics(characteristics, CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES, key ); } /** * containsCharacteristics */ protected boolean containsCharacteristics(CameraCharacteristics characteristics, Key<int[]> key1, int key2 ) { int[] modes = characteristics.get(key1); return contains(modes, key2); } // containsCharacteristics /** * contains * Return true if the given array contains the given integer. */ protected boolean contains(int[] modes, int key_mode) { if (modes == null) { return false; } for (int i=0; i<modes.length; i++ ) { int mode = modes[i]; if (mode == key_mode) { return true; } } // for return false; } // contains /** * getCameraId */ protected String getCameraId(CameraManager manager, int cameraFacing) { String cameraId = null; try { String[] ids = manager.getCameraIdList(); for (int i=0; i<ids.length; i++ ) { String id = ids[i]; CameraCharacteristics c = manager.getCameraCharacteristics(id); int facing = c.get(CameraCharacteristics.LENS_FACING); if (facing == cameraFacing) { cameraId = id; break; } } // for } catch (CameraAccessException e) { e.printStackTrace(); } return cameraId; } // getCameraId /** * getCameraFace */ protected String getCameraFaceString() { String msg = ""; switch(mFacing) { case CAMERA_FACING_FRONT: msg = "Front Camera"; break; case CAMERA_FACING_BACK: msg = "Back Camera"; break; } return msg; } // getCameraFace /** * getJpegLargestSize */ protected Size getJpegLargestSize(StreamConfigurationMap map) { Size size = chooseLargestSize(map, ImageFormat.JPEG); log_base("JPEG LargestSize: " + size.toString()); return size; } // getJpegLargestSize /** * chooseLargestSize */ protected Size chooseLargestSize(StreamConfigurationMap map, int format) { Size[] supportedSizes = map.getOutputSizes(format); Size largest = Collections.max(Arrays.asList(supportedSizes), new CompareSizesByArea()); return largest; } // chooseLargestSize /** * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`. * This method should be called after the camera preview size is * determined in setUpCameraOutputs */ protected void configureTransform(int viewWidth, int viewHeight, Size previewSize, int displayRotation) { if (null == mTextureView || null == previewSize ) { return; } int previewWidth = previewSize.getWidth(); int previewHeight = previewSize.getHeight(); Matrix matrix = new Matrix(); RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); RectF bufferRect = new RectF(0, 0, previewHeight, previewWidth); float centerX = viewRect.centerX(); float centerY = viewRect.centerY(); if (Surface.ROTATION_90 == displayRotation || Surface.ROTATION_270 == displayRotation) { bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY()); matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL); float scale = Math.max( (float) viewHeight / previewHeight, (float) viewWidth / previewWidth); matrix.postScale(scale, scale, centerX, centerY); matrix.postRotate(90 * (displayRotation - 2), centerX, centerY); } else if (Surface.ROTATION_180 == displayRotation) { matrix.postRotate(180, centerX, centerY); } if( mTextureView != null ) { mTextureView.setTransform(matrix); } } // configureTransform /** * calcPreviewSize */ protected Size calcPreviewSize(StreamConfigurationMap map, int width, int height, Size largest, boolean isSwapped) { Point displaySize = DisplayUtil.getDisplaySize(mContext); int rotatedPreviewWidth = width; int rotatedPreviewHeight = height; int maxPreviewWidth = displaySize.x; int maxPreviewHeight = displaySize.y; if (isSwapped) { rotatedPreviewWidth = height; rotatedPreviewHeight = width; maxPreviewWidth = displaySize.y; maxPreviewHeight = displaySize.x; } if (maxPreviewWidth > MAX_PREVIEW_WIDTH) { maxPreviewWidth = MAX_PREVIEW_WIDTH; } if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) { maxPreviewHeight = MAX_PREVIEW_HEIGHT; } // Danger // Attempting to use too large a preview size could exceed the camera bus' bandwidth limitation Size[] choices = map.getOutputSizes(SurfaceTexture.class); Size previewSize = chooseOptimalSize(choices, rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest); log_base("PreviewSize: " + previewSize.toString()); return previewSize; } // calcPreviewSize /** * choose the smallest one that * is at least as large as the respective texture view size, and that is at most as large as the * respective max size, and whose aspect ratio matches with the specified value. If such size * doesn't exist, choose the largest one that is at most as large as the respective max size, * and whose aspect ratio matches with the specified value. */ protected Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) { log_base("chooseOptimalSize"); // Collect the supported resolutions that are at least as big as the preview Surface List<Size> bigEnough = new ArrayList<>(); // Collect the supported resolutions that are smaller than the preview Surface List<Size> notBigEnough = new ArrayList<>(); int w = aspectRatio.getWidth(); int h = aspectRatio.getHeight(); for (Size option : choices) { if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight && option.getHeight() == option.getWidth() * h / w) { if (option.getWidth() >= textureViewWidth && option.getHeight() >= textureViewHeight) { bigEnough.add(option); } else { notBigEnough.add(option); } } } // Pick the smallest of those big enough. If there is no one big enough, pick the // largest of those not big enough. if (bigEnough.size() > 0) { return Collections.min(bigEnough, new CompareSizesByArea()); } else if (notBigEnough.size() > 0) { return Collections.max(notBigEnough, new CompareSizesByArea()); } else { log_base("Couldn't find any suitable preview size"); return choices[0]; } } // chooseOptimalSize /** * getSensorArraySize */ protected Rect getSensorArraySize(CameraCharacteristics characteristics) { Rect rect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); log_base( "SensorArraySize=" + rect.toString() ); return rect; } /** * getDisplayOrientation */ protected int getDisplayOrientation() { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); return display.getRotation(); } // getDisplayOrientation /** * getDisplaySize */ protected Point getDisplaySize() { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); return size; } // getDisplaySize /** * hasMeteringAreaAFSupported * The maximum number of metering regions that can be used by the auto-focus (AF) routine. */ protected boolean hasMeteringAreaAFSupported(CameraCharacteristics characteristics) { Integer maxAFRegions = characteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF); boolean isSupported = (maxAFRegions >= 1)? true: false; log_base( "maxAFRegions= " + maxAFRegions + " isMeteringAreaAFSupported= " + isSupported); return isSupported; } /** * hasFlashSupport */ protected boolean hasFlashSupport(CameraCharacteristics characteristics) { log_base("hasFlashSupport"); Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); boolean hasSupport = available == null ? false : available; return hasSupport; } // hasFlashSupport /** * Find out if we need to swap dimension to get the preview size relative to sensor coordinate. */ protected boolean getSwappedDimensions() { boolean swappedDimensions = false; switch (mDisplayRotation) { case Surface.ROTATION_0: case Surface.ROTATION_180: if (mSensorOrientation == 90 || mSensorOrientation == 270) { swappedDimensions = true; } break; case Surface.ROTATION_90: case Surface.ROTATION_270: if (mSensorOrientation == 0 || mSensorOrientation == 180) { swappedDimensions = true; } break; default: log_base( "Display rotation is invalid: " + mDisplayRotation); } log_base("SwappedDimensions= " + swappedDimensions); return swappedDimensions; } // getSwappedDimensions /** * choiceBestAspectPictureSize * For still image captures, we use the largest available size. */ protected Size choiceBestAspectPictureSize(StreamConfigurationMap map) { Size[] supportedPictureSizes = map.getOutputSizes(ImageFormat.JPEG); //float targetRatio = Utils.getScreenRatio(mContext); float targetRatio = getScreenRatio(); Size bestSize = null; TreeMap<Double, List<Size>> diffs = new TreeMap<>(); //Select supported sizes which ratio is less than RATIO_TOLERANCE for (Size size : supportedPictureSizes) { float ratio = (float) size.getWidth() / size.getHeight(); double diff = Math.abs(ratio - targetRatio); if (diff < RATIO_TOLERANCE){ if (diffs.keySet().contains(diff)){ //add the value to the list diffs.get(diff).add(size); } else { List<android.util.Size> newList = new ArrayList<>(); newList.add(size); diffs.put(diff, newList); } } } //If no sizes were supported, (strange situation) establish a higher RATIO_TOLERANCE if(diffs.isEmpty()) { for (Size size : supportedPictureSizes) { float ratio = (float)size.getWidth() / size.getHeight(); double diff = Math.abs(ratio - targetRatio); if (diff < MAX_RATIO_TOLERANCE){ if (diffs.keySet().contains(diff)){ //add the value to the list diffs.get(diff).add(size); } else { List<android.util.Size> newList = new ArrayList<>(); newList.add(size); diffs.put(diff, newList); } } } } //Select the highest resolution from the ratio filtered ones. for (Map.Entry entry: diffs.entrySet()){ List<?> entries = (List) entry.getValue(); for (int i=0; i<entries.size(); i++) { android.util.Size s = (android.util.Size) entries.get(i); if(bestSize == null) { bestSize = new Size(s.getWidth(), s.getHeight()); } else if(bestSize.getWidth() < s.getWidth() || bestSize.getHeight() < s.getHeight()) { bestSize = new Size(s.getWidth(), s.getHeight()); } } } return bestSize; } // choiceBestAspectPictureSize /** * getScreenRatio */ protected float getScreenRatio() { DisplayMetrics metrics = mContext.getResources().getDisplayMetrics(); float ratio = ((float)metrics.heightPixels / (float)metrics.widthPixels); return ratio; } // getScreenRatio /** * notifyError * callback error, or throw RuntimeException */ protected void notifyError(String msg) { log_base("notifyError: " + msg); if (mErrorCallback != null) { mErrorCallback.onError(msg); } else { throw new RuntimeException(msg); } } // notifyError /** * prepareCamera * for override */ protected void prepareCamera() { // nop } /** * openCamera */ protected void openCamera() { log_base("openCamera"); // check permission if (!CameraPerm.isCameraGranted(mContext)) { log_base("not granted camera permission"); return; } if (mCameraId == null) { log_base("CameraId null"); return; } try { CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } // openCamera /** * closePreviewSession */ protected void closePreviewSession() { log_base("closePreviewSession"); if(mCaptureSession != null) { mCaptureSession.close(); mCaptureSession = null; } } // closePreviewSession /** * createCameraPreviewSession */ protected void createCameraPreviewSession() { log_base("createCameraPreviewSession"); // skip, if not open camera if(mCameraDevice == null) return; try { mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mPreviewRequestBuilder.addTarget(mViewSurface); List outputs = Arrays.asList(mViewSurface); mCameraDevice.createCaptureSession(outputs, mPreviewSession, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } // createCameraPreviewSession /** * CameraCaptureSession.StateCallback */ protected CameraCaptureSession.StateCallback mPreviewSession = new CameraCaptureSession.StateCallback() { @Override public void onConfigured( CameraCaptureSession cameraCaptureSession) { log_base("onConfigured"); procCaptureSessionConfigured(cameraCaptureSession); } @Override public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { log_base("CameraCaptureSession Configuration Failed!"); } }; // CameraCaptureSession.StateCallback /** * procCaptureSessionConfigured */ protected void procCaptureSessionConfigured( CameraCaptureSession cameraCaptureSession) { log_base("procCaptureSessionConfigured"); // The camera is already closed if (null == mCameraDevice) { return; } // When the session is ready, we start displaying the preview. mCaptureSession = cameraCaptureSession; try { // Auto focus should be continuous for camera preview. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, mFocusMode); if(isFlashSupported) { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, mFlashMode); } // Finally, we start displaying the camera preview. mPreviewRequest = mPreviewRequestBuilder.build(); mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } // procCaptureSessionConfigured /** * write into logcat */ protected void log_base( String msg ) { if (D) Log.d( TAG, TAG_BASE + " " + msg ); } // log_base /** * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state. */ protected CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened( CameraDevice cameraDevice) { log_base("onOpened"); procStateOpened( cameraDevice); } @Override public void onDisconnected( CameraDevice cameraDevice) { log_base("onDisconnected"); procStateDisconnected( cameraDevice); } @Override public void onError( CameraDevice cameraDevice, int error) { log_base("onError: "); procStateError( cameraDevice, error); } }; // CameraDevice.StateCallback /** * procStateOpened */ protected void procStateOpened( CameraDevice cameraDevice) { log_base("procStateOpened"); // This method is called when the camera is opened. We start camera preview here. synchronized (mCameraStateLock) { mState = STATE_OPENED; mCameraOpenCloseLock.release(); mCameraDevice = cameraDevice; createCameraPreviewSession(); } } // procStateOpened /** * rocStateDisconnected */ protected void procStateDisconnected( CameraDevice cameraDevice) { log_base("procStateDisconnected"); synchronized (mCameraStateLock) { mState = STATE_CLOSED; mCameraOpenCloseLock.release(); cameraDevice.close(); mCameraDevice = null; } } // procStateDisconnected /** * procStateError */ protected void procStateError( CameraDevice cameraDevice, int error) { synchronized (mCameraStateLock) { mState = STATE_CLOSED; mCameraOpenCloseLock.release(); cameraDevice.close(); } mCameraDevice = null; String msg = "State Error: " + LF + getCameraDeviceStateErrorMsg(error); log_base(msg); notifyError(msg); } // procStateError /** * getCameraDeviceStateErrorMsg */ protected String getCameraDeviceStateErrorMsg(int error) { String msg = ""; switch(error) { case ERROR_CAMERA_IN_USE: msg = "Camera inuse"; break; case ERROR_MAX_CAMERAS_IN_USE: msg = "max Cameras in use"; break; case ERROR_CAMERA_DISABLED: msg = "Camera Disabled"; break; case ERROR_CAMERA_DEVICE: msg = "Camera Device Error"; break; case ERROR_CAMERA_SERVICE: msg = "Camera Service Error"; break; } return msg; } // getCameraDeviceStateErrorMsg /** * A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture. */ protected CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureProgressed( CameraCaptureSession session, CaptureRequest request, CaptureResult result) { //log_base("onCaptureProgressed"); procCaptureResult(result); } @Override public void onCaptureCompleted( CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { //log_base("onCaptureCompleted"); procCaptureResult( result); } }; // CameraCaptureSession.CaptureCallback /** * procCaptureResult * for override */ protected void procCaptureResult(CaptureResult result) { } } // class Camera2Base
[ "vantiendung690@gmail.com" ]
vantiendung690@gmail.com
edaf1e67a0a46c313e9ffe0e2414e927203027f9
d0a87b74643e8ab0d7393185a815dfd378733bae
/carrental-ejb/src/main/java/ch/xxx/carrental/ui/model/Member.java
e83a17549b47eb19a45e6d980c738b7a725198b9
[ "Apache-2.0" ]
permissive
Angular2Guy/Angular2AndJavaEE
bbb9aeb488a700d922472b4b1c30edc13c2df7a9
de1f208cfef36649688da83f00216f1f1109f3ed
refs/heads/master
2023-08-16T10:14:41.388159
2023-08-10T18:10:25
2023-08-10T18:10:25
74,204,252
110
45
Apache-2.0
2023-08-10T18:10:28
2016-11-19T11:25:06
Java
UTF-8
Java
false
false
2,326
java
/** * Copyright 2016 Sven Loesekann 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 ch.xxx.carrental.ui.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; @Entity @XmlRootElement @Table(name = "Registrant", uniqueConstraints = @UniqueConstraint(columnNames = "email")) public class Member implements Serializable { /** Default value included to remove warning. Remove or modify at will. **/ private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @NotNull @Size(min = 1, max = 25) @Pattern(regexp = "[^0-9]*", message = "Must not contain numbers") private String name; @NotNull private String email; @NotNull @Size(min = 10, max = 12) @Digits(fraction = 0, integer = 12) @Column(name = "phone_number") private String phoneNumber; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
[ "you@example.com" ]
you@example.com
019dc7f8ad118b4453d6f1018f3e38e5c742ffda
2766b46e674fc0b4df60bd46d5874f72d6c33f41
/app/src/main/java/com/libra/app/activities/HomeActivity.java
e1aabfa57c729423b2364027f4fb2bd01aa3e50e
[]
no_license
maxxy212/RealmTest
96e4605f299754281d33cdb12822abf76a780f64
419d6fdcf54b708416dded22caf6f493a0838449
refs/heads/master
2020-04-15T11:25:53.117407
2019-01-08T11:13:15
2019-01-08T11:13:15
164,629,672
0
0
null
null
null
null
UTF-8
Java
false
false
5,130
java
package com.libra.app.activities; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.RadioButton; import com.libra.app.R; import com.libra.app.databinding.ActivityHomeBinding; import com.libra.app.model.Manifest; import com.libra.app.utilities.ToastUtil; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import io.realm.Realm; public class HomeActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { ActivityHomeBinding binding; private Context context; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_home); context = HomeActivity.this; realm = Realm.getDefaultInstance(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Lagos --> Asaba(Onitsha)"); toolbar.setNavigationOnClickListener(v -> onBackPressed()); binding.signedUpOpt.setOnCheckedChangeListener((group, checkedId) -> { RadioButton rbut = binding.getRoot().findViewById(checkedId); if (rbut.getText().toString().equalsIgnoreCase("true")){ binding.setShow("yes"); }else if (rbut.getText().toString().equalsIgnoreCase("false")){ binding.setShow("no"); } }); } public void onClick(View v){ String passengers = binding.passengers.getText().toString(); String payment = binding.payment.getText().toString(); String date = binding.date.getText().toString(); String dispatch = binding.dispatch.getText().toString(); String transload = binding.transload.getText().toString(); String miscell = binding.miscellaneous.getText().toString(); String loading = binding.loading.getText().toString(); String load_amt = binding.loadedAmt.getText().toString(); String comment = binding.comment.getText().toString(); if (passengers.isEmpty() || payment.isEmpty() || date.isEmpty() || dispatch.isEmpty()){ ToastUtil.makeLongToast(context, "Please fill above fields"); }else { realm.executeTransaction(realm -> { Manifest manifest = realm.createObject(Manifest.class); manifest.passengers = Integer.parseInt(passengers); manifest.amt = Double.parseDouble(payment); manifest.date = date; manifest.dispatch = Double.parseDouble(dispatch); if (!transload.isEmpty()){ manifest.transload = Integer.parseInt(transload); } if (!miscell.isEmpty()){ manifest.miscellaneous = Double.parseDouble(miscell); } if (!loading.isEmpty()){ manifest.loading = Integer.parseInt(loading); } if (!load_amt.isEmpty()){ manifest.amt_loading = Double.parseDouble(load_amt); } if (!comment.isEmpty()){ manifest.comment = comment; } ToastUtil.makeLongToast(context, "Added Successfully"); HistoryActivity.start(context, manifest); }); } } public void onDateClick(View v){ Calendar calendar = Calendar.getInstance(); DatePickerDialog dpd = DatePickerDialog.newInstance( this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ); dpd.setThemeDark(true); dpd.vibrate(true); dpd.setScrollOrientation(DatePickerDialog.ScrollOrientation.HORIZONTAL); dpd.show(getFragmentManager(), "Tag"); } @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, monthOfYear); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); Date selected = c.getTime(); binding.date.setText(formatDate(selected, sqlformat)); } public static SimpleDateFormat dateform = new SimpleDateFormat("dd MMMM yyyy"); public static SimpleDateFormat sqlformat = new SimpleDateFormat("dd-MM-yyyy"); public static String formatDate(Date date , SimpleDateFormat dateformat){ if(dateformat == null){ dateformat = dateform; } if(date != null){ return dateformat.format(date); } return ""; } }
[ "maxsteelobinna@gmail.com" ]
maxsteelobinna@gmail.com
77582c8187a9d7902b0e7718c608a6cd4c6755d4
c7978ad2df29b1d7bed1e23cd4494aee75782486
/src/main/java/me/wonwoo/web/PersonController.java
f2743f2521a46de0c458c8a4689276682e2962e0
[]
no_license
wonwoo/spring-reactor
edfe3567d04b206fbad78938a5934b07e655c105
8014b649eae124381ecf7845f179a82bc7912460
refs/heads/master
2021-01-22T04:27:56.667861
2017-09-03T13:50:18
2017-09-03T13:50:18
102,267,834
0
0
null
null
null
null
UTF-8
Java
false
false
759
java
package me.wonwoo.web; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Created by wonwoolee on 2017. 9. 3.. */ @RestController public class PersonController { private final PersonGenerator personGenerator; public PersonController(PersonGenerator personGenerator) { this.personGenerator = personGenerator; } @GetMapping("/{name}") Mono<Person> getPerson(@PathVariable String name) { return personGenerator.findByName(name); } @GetMapping("/") Flux<Person> getPersons() { return personGenerator.findAll(); } }
[ "aoruqjfu@gmail.com" ]
aoruqjfu@gmail.com
780315b942ac4d892738478e77c3dacd2dab659d
f4090d3c6e37e05f0d0955d93c01c82f3ba7956a
/test/src/main/java/cn/netkiller/controller/TestMongoController.java
e64dd72acf2e1a3caa9e21de94ccfe25e73f5589
[ "CC0-1.0" ]
permissive
jianhong123/Microservice
81687a5a4aa736f03acefdaf67fe6637acd82c35
2ef2a897c749061f31c6b4651b5885df1ec46b35
refs/heads/master
2023-08-24T09:21:44.407796
2021-10-14T11:37:04
2021-10-14T11:37:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,448
java
package cn.netkiller.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import cn.netkiller.domain.User; import cn.netkiller.service.UserService; @RestController public class TestMongoController { @Autowired private UserService userService; public TestMongoController() { // TODO Auto-generated constructor stub } @GetMapping("/mongo/save") public String save() { User user = new User(); user.setUseruame("netkiller"); user.setPassword("123456"); userService.save(user); return "Success"; } @Autowired @Qualifier(value = "primaryMongoTemplate") private MongoTemplate primaryMongoTemplate; @Autowired @Qualifier(value = "secondaryMongoTemplate") private MongoTemplate secondaryMongoTemplate; @GetMapping("/mongo/primary/save") public String primarysave() { User user = new User(); user.setUseruame("netkiller"); user.setPassword("123456"); primaryMongoTemplate.save(user); return "Success\r\n"; } @GetMapping("/mongo/secondary/save") public String secondaryMongoTemplate() { User user = new User(); user.setUseruame("netkiller"); user.setPassword("123456"); secondaryMongoTemplate.save(user); return "Success\r\n"; } }
[ "netkiller@msn.com" ]
netkiller@msn.com
b05b9a68d04b2fc7cbd61ea51cc2a1edd73882b4
7d8cdcdb4e2429b492896c230dac34858cfbf2b1
/src/main/java/cn/zl/zxrpc/ZxrpcApplication.java
f4fe32155ecd677e639f43ae5cfdd4ed3716880c
[]
no_license
swiftzL/zxrpc
db9ae5aa1dba76c3b17a33c31f21f97b4403db66
22ced6ce425e839c80c944c2a0851f08c1334dd7
refs/heads/master
2023-05-03T01:04:38.176212
2021-05-19T05:57:39
2021-05-19T05:57:39
363,809,461
1
0
null
null
null
null
UTF-8
Java
false
false
248
java
package cn.zl.zxrpc; public class ZxrpcApplication { // public static void main(String[] args) { // Logger logger = LoggerFactory.getLogger(ZxrpcApplication.class); // logger.debug("fsaf"); // String s =""; // } }
[ "swiftzl@outlook.com" ]
swiftzl@outlook.com
4649072390543d08e846112b68219c767b6ebe7d
dce0d08ab3d525e290d30efb8a1fd4bf175c2644
/converter-jacoco/generator/src/test/java/fr/pinguet62/codacy/TestTest.java
46e723ae5d3de8db3ef54c8d8a302e983f8c2c5d
[]
no_license
pinguet62/codacy-reporter
e3abef79f6544751c39dd020ef6903ca20e20a33
d2e908846135f41938dafd4aa9feac37d7916455
refs/heads/master
2021-09-01T11:01:30.396614
2017-12-26T16:59:43
2017-12-26T16:59:43
115,187,284
0
0
null
null
null
null
UTF-8
Java
false
false
237
java
package fr.pinguet62.codacy; import org.junit.Test; public class TestTest { @Test public void first() { First.checkPositive(42); } @Test public void second() { Second.doNothing("direct"); } }
[ "pinguet62@gmail.com" ]
pinguet62@gmail.com
9b608a3a0079f8fd7b4eb9ad745beda5df04da38
7c474f6bb31da170d054ab660f38aaaed1007627
/server/reporting/reporting-webapp/src/main/java/com/github/rmannibucau/sirona/reporting/web/plugin/thread/ThreadPlugin.java
f767fe2309b83994bffbe2a06b073ea27b11db18
[ "Apache-2.0", "CC-BY-3.0", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause" ]
permissive
olamy/sirona
b1a36fa7dc9561bb50fd1e1516422fe087587f88
c8c0fbab3c99cba5dfc32cb805faf79b462d6524
refs/heads/master
2021-12-03T09:09:48.379272
2019-01-06T15:51:14
2019-01-06T15:51:14
80,877,112
0
0
Apache-2.0
2021-08-20T09:45:52
2017-02-03T23:06:54
JavaScript
UTF-8
Java
false
false
1,310
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rmannibucau.sirona.reporting.web.plugin.thread; import com.github.rmannibucau.sirona.reporting.web.plugin.api.Local; import com.github.rmannibucau.sirona.reporting.web.plugin.api.Plugin; @Local public class ThreadPlugin implements Plugin { @Override public String name() { return "Threads"; } @Override public Class<?> endpoints() { return ThreadEndpoints.class; } @Override public String mapping() { return "/threads"; } }
[ "rmannibucau@apache.org" ]
rmannibucau@apache.org
2af47b23e32cd6c559f653310d6b64efc80bbc13
2313deb3ad34d8cfbe15ffd17dba91e2b420df61
/src/mailing/ReadSulekha.java
34f7c4f6df330284007e6c2769605a2520de184d
[]
no_license
arunimmanuelpro/tims
2fdbf562d387969f8911b5a609decf5c6b2fd28d
2c8c4c00f371b3b49445e4278186f5aafb7ee07d
refs/heads/master
2021-01-16T21:23:32.630096
2015-08-05T04:00:26
2015-09-18T13:17:48
38,527,719
0
0
null
null
null
null
UTF-8
Java
false
false
9,692
java
package mailing; import general.GetInfoAbout; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Flags.Flag; import javax.mail.internet.InternetAddress; import javax.mail.search.FlagTerm; import access.DbConnection; public class ReadSulekha { Properties properties = null; private Session session = null; private Store store = null; private Folder inbox = null; boolean gotdata = false; private String userName;// provide user name private String password;// provide password public ReadSulekha() { } public void readMails() throws IOException, Exception { Connection con = DbConnection.getConnection(); PreparedStatement ps0 = con.prepareStatement("select * from emailaccounts where id = 1"); ResultSet rs0 = ps0.executeQuery(); if(rs0.next()){ userName = rs0.getString("email"); password = rs0.getString("password"); } properties = new Properties(); properties.setProperty("mail.host", "bh-17.webhostbox.net"); properties.setProperty("mail.port", "143"); properties.setProperty("mail.transport.protocol", "imaps"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); try { store = session.getStore("imaps"); store.connect(); //System.out.println(store); inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false)); System.out.println("Sulekha Mail Count : "+messages.length); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; Address[] from = message.getFrom(); System.out.println("-------------------------------"); System.out.println("Date : " + message.getSentDate()); System.out.println("From : " + from[0]); System.out.println("Subject: " + message.getSubject()); int msgno = message.getMessageNumber(); boolean ignore = false; boolean already_read = false; Statement sd = con.createStatement(); String checksql = "SELECT * FROM `enquiry` WHERE `source`='SULEKHA' AND `mailid`='" + msgno + "'"; ResultSet rs2 = sd.executeQuery(checksql); if (rs2.next()) { already_read = true; } if (!already_read) { String email = from == null ? null : ((InternetAddress) from[0]).getAddress(); if (email.equalsIgnoreCase("enq@ypleads.sulekha.com")) { System.out.println("Sulekha Mail :" + email); } else { System.out.println("Mail Ignored :" + email); ignore = true; } } else { System.out.println("Mail Already Read. Ignored"); message.setFlag(Flags.Flag.SEEN, true); ignore = true; } ArrayList<String> details4 = new ArrayList<String>(); if (!ignore) { String html = message.getContent().toString(); int startindex = html.indexOf("<"); // To get Name String ref = "Customer's name: "; int endindex = html.indexOf(ref); StringBuilder str = new StringBuilder(html); str.replace(startindex, endindex, ""); str = new StringBuilder(str); startindex = str.indexOf(ref); endindex = str.indexOf("</td>"); str = new StringBuilder(str.substring(startindex, endindex)); str.replace(0, ref.indexOf(":"), ""); str.replace(0, 1, ""); //System.out.println("Name" + str); details4.add(str.toString()); // To get Looking For ref = "Looking for: "; endindex = html.indexOf(ref); str = new StringBuilder(html); str.replace(startindex, endindex, ""); str = new StringBuilder(str); startindex = str.indexOf(ref); endindex = str.indexOf("</td>"); str = new StringBuilder(str.substring(startindex, endindex)); str.replace(0, ref.indexOf(":"), ""); str.replace(0, 1, ""); //System.out.println("Looking For" + str); details4.add(str.toString()); // To get Service preference ref = "Service preference: "; endindex = html.indexOf(ref); str = new StringBuilder(html); str.replace(startindex, endindex, ""); str = new StringBuilder(str); startindex = str.indexOf(ref); endindex = str.indexOf("</td>"); str = new StringBuilder(str.substring(startindex, endindex)); str.replace(0, ref.indexOf(":"), ""); str.replace(0, 1, ""); //System.out.println("Service preference" + str); details4.add(str.toString()); // To get Email ID: ref = "Email ID: "; endindex = html.indexOf(ref); str = new StringBuilder(html); str.replace(startindex, endindex, ""); str = new StringBuilder(str); startindex = str.indexOf(ref); endindex = str.indexOf("</td>"); str = new StringBuilder(str.substring(startindex, endindex)); str.replace(0, ref.indexOf(":"), ""); str.replace(0, 1, ""); startindex = str.indexOf("<a"); endindex = str.indexOf(">"); str.replace(startindex, endindex, ""); startindex = 0; endindex = 1; str.replace(startindex, endindex, ""); ref = str.toString(); ref = ref.replace(">", ""); ref = ref.replace("</a", ""); //System.out.println("Email ID:" + ref); details4.add(ref); // To get Mobile number: ref = "Mobile number: "; endindex = html.indexOf(ref); str = new StringBuilder(html); str.replace(startindex, endindex, ""); str = new StringBuilder(str); startindex = str.indexOf(ref); endindex = str.indexOf("</td>"); str = new StringBuilder(str.substring(startindex, endindex)); str.replace(0, ref.indexOf(":"), ""); str.replace(0, 1, ""); //System.out.println("Mobile number:" + str); details4.add(str.toString()); gotdata = false; } boolean gotsulekha = false; if ((details4.size() > 0)) { try { SimpleDateFormat ddmm = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat yyyy = new SimpleDateFormat("yyyy"); Calendar calender = Calendar.getInstance(); Date currentdate = new Date(); calender.setTime(currentdate); int month = calender.get(Calendar.MONTH) + 1; String cDate = ddmm.format(currentdate); String year = yyyy.format(currentdate); Statement s = con.createStatement(); String mobilen = details4.get(4); String sql = "INSERT INTO `enquiry`(`source`, `name`, `email`, `mobile`, `qualification`, `stream`, `currentlyin`, `homephone`, `courseinterested`, `address`,`donebyid`,`date`,`month`,`year`,`status`,`mailid`) VALUES ('SULEKHA','" + details4.get(0) + "','" + details4.get(3) + "','" + mobilen + "','','','','','" + details4.get(1).replace("'","\\'") + "," + details4.get(2).replace("'", "\\'") + "','','0','" + cDate + "','" + month + "','" + year + "','NEW','" + msgno + "')"; //System.out.println(sql); s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = s.getGeneratedKeys(); if (rs.next()) { // Retrieve the auto generated key(s). int key = rs.getInt(1); sql = "INSERT INTO `enquiry_data`(`enquiry_id`, `followon`) VALUES ('" + key + "','" + cDate + "')"; s.executeUpdate(sql); ArrayList<String> users = GetInfoAbout.getuserswithrole("3"); SimpleDateFormat ddm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date cdd = new Date(); String cDatet = ddm.format(cdd); for (String tuser : users) { int userid = Integer.parseInt(tuser); sql = "INSERT INTO `notifications`(`msg`, `read` , `userid`,`ReceivedAt`) VALUES ('NEW ENQUIRY from SULEKHA :" + details4.get(0) + "',0,'" + userid + "','" + cDatet + "')"; s.executeUpdate(sql); } gotsulekha = true; } else { // Actual End } if (gotsulekha) { System.out.println("1 SULEKHA Mail Details Read Successfully"); try { message.setFlag(Flags.Flag.SEEN, true); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("SULEKHA Mail Details Read Failed"); message.setFlag(Flag.SEEN, false); } }catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Sorry No Data Found"); } } store.close(); } catch (MessagingException e) { e.printStackTrace(); }finally{ if(con!=null){ con.close(); } } } public static void main(String[] args) throws IOException { /*ReadSulekha sample = new ReadSulekha(); try { sample.readMails(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } }
[ "immanuel2305@gmail.com" ]
immanuel2305@gmail.com
d73c62eab71f53c063c517c68d2e7057b6cf8c95
1f800156e0d3d6cf1e257a32df33ef856fa88b7f
/entdiy-module/entdiy-module-common/src/main/java/com/entdiy/auth/service/DepartmentService.java
612f913abc32ef084f50b7848ad813b09fd3b99f
[ "Apache-2.0" ]
permissive
xautlx/s2jh4net
2b7fb7caa6a8363a081bfebf5c2ad9c420ffb736
5605de57f27413a333e665c84a55212d5c22c8c4
refs/heads/master
2021-08-28T17:38:38.833161
2021-08-13T07:16:00
2021-08-13T07:16:00
31,649,341
193
188
NOASSERTION
2021-08-13T06:46:40
2015-03-04T09:41:33
Java
UTF-8
Java
false
false
1,337
java
/** * Copyright © 2015 - 2017 EntDIY JavaEE Development Framework * * Site: https://www.entdiy.com, E-Mail: xautlx@hotmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.entdiy.auth.service; import com.entdiy.auth.dao.DepartmentDao; import com.entdiy.auth.entity.Department; import com.entdiy.core.service.BaseNestedSetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class DepartmentService extends BaseNestedSetService<Department, Long> { @Autowired private DepartmentDao departmentDao; @Transactional(readOnly = true) public Department findByCode(String code) { return departmentDao.findByCode(code); } }
[ "xautlx@hotmail.com" ]
xautlx@hotmail.com
c876949e183b3aed771b558176112815638cc731
fb8b320878b01d7684625570538d2551cbbea176
/springmyproject/src/springmyproject/controller/MemberController.java
4c9f1a00c523699cdd7e5afc96c38d9f6ed57835
[]
no_license
kermit96/myproject
34cf258a6d602ce9119605edc179997f769c4b3b
5ef28623a81e93d0d67cddaaa0cfb7affb1dbebc
refs/heads/master
2021-01-21T13:52:49.812832
2016-05-16T00:02:49
2016-05-16T00:02:49
48,746,444
0
0
null
null
null
null
UTF-8
Java
false
false
8,233
java
package springmyproject.controller; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import springmyproject.dao.MemberDAO; import springmyproject.dao.MemberMDAO; import springmyproject.dao.MemberService; @Controller public class MemberController { @Autowired MemberMDAO memberImpl; /* * 회원 가입 폼 요청 모델 함수 */ @RequestMapping("/Member/joinForm") public ModelAndView joinForm() { // 할일 없고 ModelAndView mv = new ModelAndView(); mv.setViewName("Member/JoinForm"); return mv; } /* * 우편번호 검색 폼 요청 함수 */ @RequestMapping("/Member/ZipSearchForm") public ModelAndView zipSeaechForm() { ModelAndView mv = new ModelAndView(); // 할일 // 데이터베이스에서 시도를 구해서 뷰에게 알려준다. MemberDAO dao = new MemberDAO(); System.out.println("start do==>"); ArrayList list = dao.getSIDO(); dao.close(); System.out.println("do==>"+list.size()); mv.addObject("SIDO", list); // mv.setViewName("Member/ZipSearchForm"); mv.setViewName("Member/ZipSearchForm"); return mv; } /* * 구군 검색 요청 처리 함수 */ @RequestMapping(value ="/Member/ZipSearchGugun") public ResponseEntity<String> zipSeaechGugun(HttpServletRequest req,HttpServletResponse resp) { // 할일 // 넘어온 시도를 알아낸다. String sido = req.getParameter("sido"); // 데이터베이스에서 그 시도의 구군을 검색한다. MemberDAO dao = new MemberDAO(); ArrayList list = dao.getGugun(sido); dao.close(); // 뷰에게 알려준다. // mv.addObject("GUGUN", list); // mv.setViewName("Member/ZipSearchGugun"); // System.out.println(sido); JSONArray array = new JSONArray(); for(Object tempobj:list) { array.add(tempobj.toString() ); } JSONObject obj = new JSONObject(); obj.put("gugun", array); // return mv; // resp.setContentType("text/html"); // resp.setCharacterEncoding("utf-8"); // System.out.println(obj.toJSONString()); // return obj.toJSONString(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("Content-Type", "application/json; charset=utf-8"); return new ResponseEntity<String>(obj.toJSONString(), responseHeaders, HttpStatus.CREATED); } /* * 읍면동 검색 요청 */ @RequestMapping("/Member/ZipSearchDong") public ModelAndView zipSeaechDong(HttpServletRequest req) { ModelAndView mv = new ModelAndView(); String sido = req.getParameter("sido"); String gugun = req.getParameter("gugun"); MemberDAO dao = new MemberDAO(); ArrayList list = dao.getDong(sido, gugun); dao.close(); mv.addObject("DONG", list); mv.setViewName("Member/ZipSearchDong"); return mv; } /* * 거리 정보 */ @RequestMapping("/Member/ZipSearchRoad") public ModelAndView zipSeaechRoad(HttpServletRequest req) { ModelAndView mv = new ModelAndView(); String sido = req.getParameter("sido"); String gugun = req.getParameter("gugun"); String dong = req.getParameter("dong"); MemberDAO dao = new MemberDAO(); ArrayList list = dao.getRoad(sido, gugun,dong); dao.close(); mv.addObject("ROAD", list); mv.setViewName("Member/ZipSearchRoad"); return mv; } /* * 우편번호 검색 요청 */ @RequestMapping("/Member/ZipSearch") // 도메인을 제외한 요청 부분을 쓴다. // 요청 내용 http://localhost:8080/SunWeb/Member/ZipSearch.sun // 도메인 http://localhost:8080/SunWeb public void zipSeaech(HttpServletRequest req,HttpServletResponse resp) { ModelAndView mv = new ModelAndView(); // 할일 // 넘어온 파라메터 받는다. String sido = req.getParameter("sido"); String gugun = req.getParameter("gugun"); String dong = req.getParameter("dong"); String road = req.getParameter("road"); // 이제 이 데이터를 이용해서 우편번호를 검색한다. // 우편번호 서울시 종로구 신영동 세검정로6나길 빌딩이름 MemberDAO dao = new MemberDAO(); ArrayList list = dao.getZipSearch(sido, gugun, dong, road); dao.close(); Document doc = new Document(); Element codes= new Element("codes"); JsonArray jsonarray = new JsonArray(); for(Object temp :list) { // JsonObject obj = new JsonObject(); Element code = new Element("code"); HashMap map = (HashMap)temp; Element zip = new Element("zip"); Element addr = new Element("addr"); zip.setText((String)map.get("ZIPCODE")) ; String addrstr = map.get("SIDO")+" "+ map.get("GUGUN")+" "+ map.get("DONG")+" "+ map.get("ROAD")+" "+ map.get("BLG")+" "+ map.get("JIBUN"); addr.setText(addrstr) ; code.addContent(zip); code.addContent(addr); codes.addContent(code); obj.addProperty("zip", map.get("ZIPCODE").toString()); obj.addProperty("addr", addrstr); // <zip>${temp.ZIPCODE}</zip> // <addr>${temp.SIDO} ${temp.GUGUN} ${temp.DONG} ${temp.ROAD} ${temp.BLG} ${temp.JIBUN}</addr> jsonarray.add(obj); } doc.addContent(codes); //doc.get resp.reset(); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("UTF-8")) ; String str = outputter.outputString(doc); System.out.println(str); Gson gson = new Gson(); String jsonstr = gson.toJson(list); try { // resp.getWriter().print(str); resp.getWriter().print(jsonarray.toString()); resp.getWriter().flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(jsonarray.toString()); // mv.addObject("ZIP", list); // prefix에서 지정한 부분을 제외한다. // 원래 뷰 이름 /WEB-INF/Member/ZipSearch.jsp // prefix /WEB-INF/ // mv.setViewName("Member/ZipSearch"); // return mv; } @RequestMapping("/Member2/*") public void getCount(HttpServletResponse resp ) { int count = memberImpl.getCount(); System.out.println(count); // resp.reset(); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); try { resp.getWriter().print("현재 count="+count); resp.getWriter().flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[ "태섭@tslim-pc" ]
태섭@tslim-pc
0b5b43470609e1fd233956f66caf05b8cc249564
af9d875a636b47667c8c5d883794945614bab437
/Games/games/board/ChutesAndLadders.java
2c655b3a1d2706aa4a0836730523378e56e6361c
[]
no_license
CarterLankford/MentorExercises
3d2f7f98dfc57c1f3c6cf97b0ccc2fac6cb1f85c
7f31bdaf033a24ff9481cbf102938a3e6d0bea1a
refs/heads/master
2021-08-24T13:54:09.708043
2020-04-17T01:53:28
2020-04-17T01:53:28
162,463,014
1
0
null
2020-04-17T01:53:30
2018-12-19T16:24:36
Java
UTF-8
Java
false
false
391
java
package games.board; import games.lib.Game; import games.lib.Movement; class ChutesAndLadders implements Game{ ChutesAndLadders(){ } @Override public String instructions(){ return "Unique instructions"; } @Override public boolean move(Movement movement){ System.out.println(movement.getClass().getName()); return true; } }
[ "calankford@outlook.com" ]
calankford@outlook.com
cc0bf0a2c55852ef782828c3178fb8bb7c9bca27
2a09bf694ff51530af3ca4687bbb9145ba6fc96f
/java programs/Set.java
3e31dc1245a93a7b7e0a600f72270d6dbec582d4
[]
no_license
premsri/notes
847c0324db1e5a1f873a5c5fb190996094b5d9e0
b37d2d3e85dec36ff0b9648bc8717222c5b6afb4
refs/heads/master
2021-04-27T06:28:23.855780
2018-03-03T14:06:29
2018-03-03T14:06:29
122,615,399
0
0
null
null
null
null
UTF-8
Java
false
false
441
java
package in.oops; import java.util.HashSet; public class Set { public static void main(String[] args) { HashSet ex =new HashSet(); ex.add(12); ex.add("test"); ex.add(122); System.out.println(ex); int i = ex.size(); System.out.println(i); ex.remove("test"); ex.add("ww"); System.out.println(ex); for (Object obj : ex) { System.out.println(obj); } String ey =ex.toString(); System.out.println(ey); } }
[ "premsri2504@gmail.com" ]
premsri2504@gmail.com
6ac7185cb3ad23cab66f8583a88cb8aada666292
7956e8fbb29f563f4f6bbc5c13474022349dedd3
/src/test/java/com/zhazhapan/util/RandomUtilsTest.java
2e72bce010aac8f1d60ac517654d3ade9e04197f
[ "MIT" ]
permissive
YRREALLYCUTE/util
051b8e615c7a066935d0ff8a17b3e463e6cd201a
1fc9f0ead1108f4d7208ba7c000df4244f708418
refs/heads/master
2021-10-09T04:43:05.289577
2018-12-20T12:55:12
2018-12-20T12:55:12
256,656,087
1
0
null
2020-04-18T02:48:29
2020-04-18T02:48:28
null
UTF-8
Java
false
false
1,473
java
package com.zhazhapan.util; import com.zhazhapan.modules.constant.ValueConsts; import org.junit.Test; public class RandomUtilsTest { @Test public void getRandomInteger() { System.out.println(RandomUtils.getRandomInteger(ValueConsts.NINE_INT)); } @Test public void getRandomUid() throws InterruptedException { for (int i = 0; i < 100; i++) { System.out.println(RandomUtils.getRandomUid()); Thread.sleep(1000); } } @Test public void getRandomEmail() { } @Test public void getRandomString() { } @Test public void getRandomStringWithoutSymbol() { } @Test public void getRandomStringOnlyLetter() { } @Test public void getRandomStringOnlyLowerCase() { } @Test public void getRandomStringOnlyUpperCase() { } @Test public void getRandomTextIgnoreRange() { } @Test public void getRandomText() { } @Test public void getRandomDouble() { } @Test public void getRandomDouble1() { } @Test public void getRandomDouble2() { } @Test public void getRandomIntegerIgnoreRange() { } @Test public void getRandomColor() { } @Test public void getRandomColor1() { } @Test public void getRandomNumber() { for (int i = 0; i < 100; i++) { assert Checker.isNumber(RandomUtils.getRandomNumber(11)); } } }
[ "tao@zhazhapan.com" ]
tao@zhazhapan.com
0190098494efb11df61ee44ee9664f7eb8843789
9786e79a538b69e7809f3fa19eee415440d71c44
/src/main/java/com/rent/dao/PrhRmoooMapper.java
55d03afdd0ff16915299ca639a76f88d725f6f7f
[]
no_license
stevenbluesky/rent
326095de1ea35783c229276b64024a30cf72d6cd
a12d7c49f163ae8296cb78a53bd7fd3f8278d3d7
refs/heads/master
2020-04-30T14:04:45.093732
2019-03-26T01:18:12
2019-03-26T01:18:12
176,878,556
0
0
null
null
null
null
UTF-8
Java
false
false
1,570
java
package com.rent.dao; import com.rent.common.persistence.annotation.MyBatisDao; import com.rent.entity.PrhRmooo; @MyBatisDao public interface PrhRmoooMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ int deleteByPrimaryKey(String no); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ int insert(PrhRmooo record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ int insertSelective(PrhRmooo record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ PrhRmooo selectByPrimaryKey(String no); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ int updateByPrimaryKeySelective(PrhRmooo record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PRH_RMOOO * * @mbggenerated Mon Apr 24 14:56:49 CST 2017 */ int updateByPrimaryKey(PrhRmooo record); }
[ "stevenbluesky@163.com" ]
stevenbluesky@163.com
25774eea7b9eb13ba4fc340a90f2c98414cf1c44
f00593a9f5e8c52d945c7dd35fcca4cd33c3e68b
/script/src/main/java/script/model/WBGUser.java
455ae37b118d7684b5af7cd47ea03aa4c5b65993
[]
no_license
weirod/weirod_person_project
866bf818e12a71154c76080bc3a5a6c52aba824d
16bea51cb5f8f86081b56029342e8b154f23d9d6
refs/heads/master
2020-03-28T00:50:09.625105
2018-09-05T09:25:14
2018-09-05T09:25:14
147,453,770
0
0
null
null
null
null
UTF-8
Java
false
false
1,591
java
package script.model; import java.math.BigDecimal; public class WBGUser { private long userid; /** *推荐人id */ private long parentid; private String username; private String password; /** * wt资产 */ private BigDecimal wt; /** * 推荐人 */ private String referral; public long getUserid() { return userid; } public void setUserid(long userid) { this.userid = userid; } public long getParentid() { return parentid; } public void setParentid(long parentid) { this.parentid = parentid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public BigDecimal getWt() { return wt; } public void setWt(BigDecimal wt) { this.wt = wt; } public String getReferral() { return referral; } public void setReferral(String referral) { this.referral = referral; } @Override public String toString() { return "WBGUser{" + "userid=" + userid + ", parentid=" + parentid + ", username='" + username + '\'' + ", password='" + password + '\'' + ", wt=" + wt + ", referral='" + referral + '\'' + '}'; } }
[ "247608022@qq.com" ]
247608022@qq.com
d246f422d002e705c40b1a347516f1bbee9aae91
61602d4b976db2084059453edeafe63865f96ec5
/com/tencent/mm/opensdk/modelbiz/CreateChatroom.java
e764de3ed7481478679a57f1624b4cb73db2ca32
[]
no_license
ZoranLi/thunder
9d18fd0a0ec0a5bb3b3f920f9413c1ace2beb4d0
0778679ef03ba1103b1d9d9a626c8449b19be14b
refs/heads/master
2020-03-20T23:29:27.131636
2018-06-19T06:43:26
2018-06-19T06:43:26
137,848,886
12
1
null
null
null
null
UTF-8
Java
false
false
1,771
java
package com.tencent.mm.opensdk.modelbiz; import android.os.Bundle; import com.tencent.mm.opensdk.a.d; import com.tencent.mm.opensdk.modelbase.BaseReq; import com.tencent.mm.opensdk.modelbase.BaseResp; public class CreateChatroom { public static class Req extends BaseReq { public String chatroomName; public String chatroomNickName; public String extMsg; public String groupId = ""; public boolean checkArgs() { return !d.h(this.groupId); } public int getType() { return 14; } public void toBundle(Bundle bundle) { super.toBundle(bundle); bundle.putString("_wxapi_create_chatroom_group_id", this.groupId); bundle.putString("_wxapi_create_chatroom_chatroom_name", this.chatroomName); bundle.putString("_wxapi_create_chatroom_chatroom_nickname", this.chatroomNickName); bundle.putString("_wxapi_create_chatroom_ext_msg", this.extMsg); bundle.putString("_wxapi_basereq_openid", this.openId); } } public static class Resp extends BaseResp { public String extMsg; public Resp(Bundle bundle) { fromBundle(bundle); } public boolean checkArgs() { return true; } public void fromBundle(Bundle bundle) { super.fromBundle(bundle); this.extMsg = bundle.getString("_wxapi_create_chatroom_ext_msg"); } public int getType() { return 14; } public void toBundle(Bundle bundle) { super.toBundle(bundle); bundle.putString("_wxapi_create_chatroom_ext_msg", this.extMsg); } } private CreateChatroom() { } }
[ "lizhangliao@xiaohongchun.com" ]
lizhangliao@xiaohongchun.com
a19e038b90aab89aa7cc901ac578445087533c15
116cb64dea6c937fc373bd6e1671697f1654d784
/src/gpcoder/bytestream/bytearray/ByteArrayInputStreamExample.java
26bed33db296be503feba2fe461c5c66b5a32769
[]
no_license
huy8895/2.16.-IO-Text-File
f4e6e293580b79af81930137693d9d899484713d
d0c81bf673d878b5c13569987e2f925eb1d3c92c
refs/heads/master
2022-11-21T21:31:55.431726
2020-07-27T13:41:51
2020-07-27T13:41:51
282,108,864
0
0
null
null
null
null
UTF-8
Java
false
false
402
java
package gpcoder.bytestream.bytearray; import java.io.ByteArrayInputStream; public class ByteArrayInputStreamExample { public static void main(String[] args) { byte[] bytes = {'h','e','l','l','o'}; ByteArrayInputStream bais = new ByteArrayInputStream(bytes); int k = 0; while ((k = bais.read()) != -1){ System.out.println((char) k); } } }
[ "huy8895@gmail.com" ]
huy8895@gmail.com
7be7fa63d67975b4a82569f7f25fffb8d2ef5bcd
8d210db735191c5a14cf2db57b0b02877daf8784
/src/ch15/LimitsOfInference.java
2b9093ab5e1e149ecf7db99f68a6cd8684969f12
[]
no_license
1326670425/TIJ
0cc127642ca13b26729fae267512d9df3f03f53f
a8f58dde62d2fd8955d130f81feed5de3d7833b1
refs/heads/master
2020-04-13T23:23:49.016618
2019-08-08T09:57:42
2019-08-08T09:57:42
163,505,084
0
0
null
null
null
null
GB18030
Java
false
false
704
java
/** * @Title LimitsOfInference.java * @Package ch15 * @Description TODO * @author 吴扬颉 * @date 2019年3月25日 * @version 1.0 */ package ch15; import java.util.*; import ch14.pets.*; /** * @ClassName LimitsOfInference * @Description Thinking in Java:类型推断只对赋值操作有效,其他时候不起作用,比如不能用于参数传递,编译错误 * <p>Java 8下可以编译通过 * @author 吴扬颉 * @date 2019年3月25日 * */ public class LimitsOfInference { static void f(Map<Person, List<? extends Pet>> petPeople) { System.out.println(petPeople.getClass().getName()); } public static void main(String[] args) { f(New.map()); } }
[ "1326670425@qq.com" ]
1326670425@qq.com
0772e8aee9d07033499987f20d3e3b936dfaf21e
698bd272a8a9f432c8f06e581194fba9cb006996
/taotao-sso/.svn/pristine/6d/6df3c49d350755e6c5cab26cf90f98ddcffbbf7f.svn-base
88b29fe0b9e59bcd9f1fa23094d69576192d8a3f
[]
no_license
dengjunpeng/taotao
ee169a104c26b5ff373c5442babb4635049cab15
3f9ade576ccdf566bdcf30a6fac0c6d572943b25
refs/heads/master
2021-01-18T22:23:50.012340
2017-05-27T08:31:43
2017-05-27T08:31:43
87,052,384
0
0
null
null
null
null
UTF-8
Java
false
false
5,141
package com.taotao.sso.service.impl; import java.util.Date; import java.util.List; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import com.my10000h.common.pojo.TaotaoResult; import com.taotao.jedis.JedisClient; import com.taotao.mapper.TbUserMapper; import com.taotao.pojo.TbUser; import com.taotao.pojo.TbUserExample; import com.taotao.pojo.TbUserExample.Criteria; import com.taotao.sso.service.UserService; import com.taotao.utils.JsonUtils; /** * 用户处理Service * * @author Administrator * */ @Service public class UserServiceImpl implements UserService { @Autowired private TbUserMapper userMapper; @Autowired private JedisClient jedisClient; @Value("${USER_SESSION}") private String USER_SESSION; @Value("${SESSION_EXPIRE}") private Integer SESSION_EXPIRE; /** * 判断数据是否可用 */ @Override public TaotaoResult checkData(String data, int type) { TbUserExample example = new TbUserExample(); Criteria criteria = example.createCriteria(); // 设置查询条件 // 1-判断用户名是否可用 if (type == 1) { criteria.andUsernameEqualTo(data); } else if (type == 2) { // 2-判断手机号是否可用 criteria.andPhoneEqualTo(data); } else if (type == 3) { // 3-判断邮箱是否可用 criteria.andEmailEqualTo(data); } else { return TaotaoResult.build(400, "非法数据,type不正确"); } List<TbUser> users = userMapper.selectByExample(example); if (users != null && users.size() > 0) { // 数据不可用 return TaotaoResult.ok(false); } // 数据可用 return TaotaoResult.ok(true); } /** * 用户注册 */ @Override public TaotaoResult register(TbUser user) { // 检查数据是否可用 if (StringUtils.isBlank(user.getUsername())) { return TaotaoResult.build(400, "用户名不能为空"); } // 判断用户名是否重复 TaotaoResult taotaoResult = checkData(user.getUsername(), 1); if (!(boolean) taotaoResult.getData()) { return TaotaoResult.build(400, "用户名重复"); } // 检查密码是否可用 if (StringUtils.isBlank(user.getPassword())) { return TaotaoResult.build(400, "密码不能为空"); } // 验证电话号码 if (StringUtils.isNotBlank(user.getPhone())) { TaotaoResult result = checkData(user.getPhone(), 2); if (!(boolean) result.getData()) { return TaotaoResult.build(400, "电话号码重复"); } } // 验证邮箱 if (StringUtils.isNotBlank(user.getEmail())) { TaotaoResult result = checkData(user.getEmail(), 3); if (!(boolean) result.getData()) { return TaotaoResult.build(400, "邮箱重复"); } } // 补全user属性 user.setCreated(new Date()); user.setUpdated(new Date()); // 密码md5加密,spring的工具类 String md5pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()); user.setPassword(md5pwd); // 插入数据 userMapper.insert(user); return TaotaoResult.ok(); } @Override public TaotaoResult login(String username, String password) { // 判断用户名,密码是否正确 TbUserExample example = new TbUserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo(username); List<TbUser> list = userMapper.selectByExample(example); if (list == null || list.size() == 0) { return TaotaoResult.build(400, "用户名或密码不正确"); } TbUser user = list.get(0); // 判断密码 // 密码md5加密 if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) { return TaotaoResult.build(400, "用户名或密码不正确"); } // 校验成功生成token,uuid String token = UUID.randomUUID().toString(); // 用户信息保存到redis,key-token,value-用户信息 // 清空密码提高安全性 user.setPassword(null); jedisClient.set(USER_SESSION + ":" + token, JsonUtils.objectToJson(user)); // 设置key的过期时间 jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE); // 返回登录成功,返回token return TaotaoResult.ok(token); } /** * 根据token查询用户 */ @Override public TaotaoResult getUserByToken(String token) { String json = jedisClient.get(USER_SESSION + ":" + token); if (StringUtils.isBlank(json)) { return TaotaoResult.build(400, "用户登录已过期"); } // 更新过期时间 jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE); // json转换成对象,如果不转,因为"在json中有意义,所以默认会进行字符串转义 TbUser user = JsonUtils.jsonToPojo(json, TbUser.class); return TaotaoResult.ok(user); } /** * 安全退出 */ @Override public TaotaoResult logout(String token) { String json = jedisClient.get(USER_SESSION + ":" + token); if(StringUtils.isBlank(json)){ return TaotaoResult.build(400, "用户已经退出"); } jedisClient.expire(USER_SESSION + ":" + token, 0); return TaotaoResult.ok(""); } }
[ "670124965@qq.com" ]
670124965@qq.com
c72f7bdb20a902266fcbafe1118f0eb20a757f66
230d5b6e0237f7c0c63b76bf08a4d234f5accda1
/dubbo/dubboprovider/src/main/java/com/dlh/dubbo/test/GenericTest.java
fff860902c595e29fccd8404b24b953fd632a696
[]
no_license
wutao123456/common
df0f672af28eb93510754f15ae0458e918bace35
fd72f4a1e59210368252a9475643109fc17c133c
refs/heads/master
2022-12-25T22:52:14.319452
2020-09-26T15:02:26
2020-09-26T15:02:26
155,397,238
0
0
null
2022-12-16T08:57:43
2018-10-30T14:15:10
Java
UTF-8
Java
false
false
649
java
package com.dlh.dubbo.test; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; /** * @author wutao * @email wutao56789@gmail.com * @date 2019/1/12 17:36 */ public class GenericTest { public static void main(String[] args) throws IOException { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("generic.xml"); System.out.println(classPathXmlApplicationContext.getDisplayName()+"here"); classPathXmlApplicationContext.start(); System.out.println("服务已经启动..."); System.in.read(); } }
[ "wutao56789@gmail.com" ]
wutao56789@gmail.com
625d64e643de16bce684a7a7d8b8919f298376a8
abe91103633f4664ffdadd95b8098ec0c2b575de
/src/controller/apps/iptopology-api/src/main/java/org/onosproject/iptopology/api/DomainId.java
4fb10701be8d795c9d4814190e3b564db636d1fc
[ "Apache-2.0", "MIT" ]
permissive
securedataplane/preacher
f1838f31c86834c07e89273f851dd62067f309cf
2f76581de47036e79cd6e1183948c88b35ce4950
refs/heads/master
2020-07-30T05:40:53.693036
2019-09-23T13:54:15
2019-09-23T13:54:15
210,105,650
1
0
null
null
null
null
UTF-8
Java
false
false
1,897
java
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.iptopology.api; import static com.google.common.base.MoreObjects.toStringHelper; import java.util.Objects; /** * Domain Identifier(32 Bit). */ public class DomainId { private final int domainIdentifier; /** * Constructor to initialize domain identifier. * * @param domainIdentifier domain identifier */ public DomainId(int domainIdentifier) { this.domainIdentifier = domainIdentifier; } /** * Obtain domain identifier. * * @return domain identifier */ public int domainIdentifier() { return domainIdentifier; } @Override public int hashCode() { return Objects.hash(domainIdentifier); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DomainId) { DomainId other = (DomainId) obj; return Objects.equals(domainIdentifier, other.domainIdentifier); } return false; } @Override public String toString() { return toStringHelper(this) .add("domainIdentifier", domainIdentifier) .toString(); } }
[ "Kashyap.Thimmaraju@sec.t-labs.tu-berlin.de" ]
Kashyap.Thimmaraju@sec.t-labs.tu-berlin.de
004af2975fc709d9194058095cd9aa969a6fcdb1
d460113df150c8d67d580c6aef90bcca0f84a8bf
/src/main/java/Nunc/Reports/package-info.java
944363e1d45fdad3341e002acef0fd3ae42c123f
[]
no_license
sandhyathumma2/new_project
80f9b7bb3acbd3b34f436438d38f296e47426d6b
dd19346bc49314c3861584f2bca6f23c8c0d908c
refs/heads/master
2023-06-20T19:22:43.084959
2021-07-16T07:49:07
2021-07-16T07:49:07
386,555,244
0
0
null
null
null
null
UTF-8
Java
false
false
21
java
package Nunc.Reports;
[ "sandhyathumma2@gmail.com" ]
sandhyathumma2@gmail.com
08ce5f423c4e3c9b824145ffb4b48b53cb7844d5
1ba5297c8fb885a6a85c6aa7e7c9f1c14c0a4f94
/src/main/java/top/nextnet/DelayService.java
c031f3e9a0ce31c16862f6d2532c5a0f9a31f4e3
[]
no_license
nherbaut/trains-delay-example
3a15c49af02913821fa6e2bcaf4dfdf539cf04f9
9a797042c3e4e4d796f91bbd9d6fd6968754c76a
refs/heads/master
2023-02-06T13:30:17.056215
2020-12-20T03:07:10
2020-12-20T03:07:10
322,982,640
0
0
null
null
null
null
UTF-8
Java
false
false
4,922
java
package top.nextnet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; /** * THis class computes the delays applicable for trains * * @author nherbaut * */ public class DelayService { Set<Train> trains; /** * * @param trains some trains to handle */ public DelayService(Train... trains) { this.trains = new HashSet<Train>(Arrays.asList(trains)); } /** * for a give stop, return a list of trains in correspondance according to their * initial schedule * * @param stop * @param schedule * @return */ private Collection<Train> getConnectionTrains(Train train, Stop stop, Long schedule) { Collection<Train> res = new HashSet<>(); for (Train correspondingTrain : this.trains) { if (correspondingTrain.equals(train)) { // we are not corresponding with ourself continue; } if (correspondingTrain.departFrom(stop)) { if (correspondingTrain.getInitialDepartureSchedule(stop) > schedule) { res.add(correspondingTrain); } else { // this trains leaves before the other one arrives, so don't add it } } } return res; } /** * modify the trains schedule to support the delay * * @param delay */ public void handleDelay(Delay delay) { Queue<Delay> delays = new LinkedList<>(); delays.add(delay); while (!delays.isEmpty()) { Delay nextDelay = delays.poll(); delays.addAll(this.handleSingleDelay(nextDelay)); condenseRegisteredDelays(delays); } } /** * if there are 2 or more delays for the same stop for the same train, keep only * the largest * * @param delays a collection of delays */ private static void condenseRegisteredDelays(Collection<Delay> delays) { Map<Train, Delay> trainDelayMap = new HashMap<>(); for (Delay d : delays) { if (trainDelayMap.containsKey(d.getTrain())) { if (trainDelayMap.get(d.getTrain()).getDelta() < d.getDelta()) { trainDelayMap.put(d.getTrain(), d); } } else { trainDelayMap.put(d.getTrain(), d); } } delays.clear(); delays.addAll(trainDelayMap.values()); } /** * handle a single delay on a single train * * @param delay * @return the list of delays needed to support connecting trains */ public Collection<Delay> handleSingleDelay(Delay delay) { Collection<Delay> resultingDelays = new HashSet<>(); Collection<DelayNotice> notices = Collections.emptySet(); // loop on all the trains to know which one the delay impacts for (Train train : this.trains) { // that's the one if (train.equals(delay.getTrain())) { try { // delay happens during the trip (affects arrival) or due to a delay required // for train connection. switch (delay.type) { case ARRIVAL: // from this arrival delay every schedule notices = train.delayAllStopsBeforeArrivalAt(delay.getStop(), delay.getDelta()); break; case DEPARTURE: // from this departure, delay every schedule notices = train.delayAllStopsFromDeparture(delay.getStop(), delay.getDelta()); break; } } catch (DelayException de) { // we reached a point where we can't delay the train anymore, no notice is // generated } break; } } // compute the real delays from the notices generated by the delay passed in // parameter for (DelayNotice notice : notices) { // for all co for (Train connectionTrain : getConnectionTrains(notice.getTrain(), notice.getStop(), notice.getInitialSchedule())) { // there may be a delay due to this reschedule Optional<Delay> optionalDelay = getRequiredDelay(connectionTrain, notice.getStop(), notice.getRealSchedule()); if (optionalDelay.isPresent()) { // a new delay is required resultingDelays.add(optionalDelay.get()); } else { // no delay is required, passengers can still make it on time. } } } return resultingDelays; } /** * THis method computes the delays required by a new departure schedule for a * train * * @param train the delayed train * @param stop the departure stop where the delay occured * @param newSchedule the new schedule needded by the train to accomodate the * delay * @return a list of delay that should be applied to other trains. */ private Optional<Delay> getRequiredDelay(Train train, Stop stop, Long newSchedule) { // if passengers can't make it if (train.getDepartureSchedule(stop) < newSchedule) { // delay the departure of the connection train. Delay newDelay = new Delay(train, stop, newSchedule - train.getDepartureSchedule(stop) + 5, DelayType.DEPARTURE); return Optional.of(newDelay); } // no delay required return Optional.empty(); } }
[ "nicolas.herbaut@univ-paris1.fr" ]
nicolas.herbaut@univ-paris1.fr
fdc94f70de7b5c980700cb44cc8da35a55834cf5
e9a65e2d24c2702de571a67e3d9333b1047c81f7
/app/src/main/java/tv/fengmang/xeniadialog/utils/RecorderHelper.java
585d297180b4c0ae8f3cf79e083697d1f3b731cf
[]
no_license
kisdy502/XeniaDialog
9834514f2716bdfb94b6cf478f486fcf7d6a3603
1d73d0ff3a643d7b277f758df6a01683c1b78fd5
refs/heads/master
2022-12-05T03:52:27.087791
2020-08-25T07:59:31
2020-08-25T07:59:31
290,757,844
0
0
null
null
null
null
UTF-8
Java
false
false
1,651
java
package tv.fengmang.xeniadialog.utils; import android.media.MediaRecorder; import android.os.Environment; import android.os.Handler; import android.text.format.DateFormat; import android.util.Log; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Locale; public class RecorderHelper { public static void record(MediaRecorder mMediaRecorder) { String fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a"; Log.d("RecorderHelper", "fileName:" + fileName); File destDir = new File(Environment.getExternalStorageDirectory() + "/test/"); if (!destDir.exists()) { destDir.mkdirs(); } String filePath = Environment.getExternalStorageDirectory() + "/test/" + fileName; Log.d("RecorderHelper", "filePath:" + filePath); try { mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.REMOTE_SUBMIX); //会报错 mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); mMediaRecorder.setOutputFile(filePath); mMediaRecorder.prepare(); } catch (IOException e) { e.printStackTrace(); } mMediaRecorder.start(); } public static void stopRecord(MediaRecorder mMediaRecorder) { if (mMediaRecorder != null) { mMediaRecorder.stop(); mMediaRecorder.release(); mMediaRecorder = null; } } }
[ "bwply2009@163.com" ]
bwply2009@163.com
9759ac72120eeca0bf2ed056857c68a5b3279534
195a71191ac4ce5e68d6af02579fc5fcacf3666f
/src/com/designPatern/builder/Director.java
d47d91558cf9110fe2690e31a2e5e1c5fb78a1c2
[]
no_license
praveenkumarbadiger/java-concepts
9763453217a07a1b160a16f7ce8b8f8ba53a097c
2e689db0ffa42ea599e245efc62b6eb2b2163d02
refs/heads/master
2022-02-24T07:05:32.987281
2022-02-08T03:19:38
2022-02-08T03:19:38
186,563,638
1
0
null
null
null
null
UTF-8
Java
false
false
392
java
package com.designPatern.builder; public class Director { private Builder builder; public Director(Builder builder) { super(); this.builder = builder; } public Home getComplexObjectHome() { return builder.getComplexHomeObject(); } public void manageRequiredHomeConstruction() { this.builder.buildFloors(); this.builder.buildWalls(); this.builder.buildTerrace(); } }
[ "praveenkumarkambar@gmail.com" ]
praveenkumarkambar@gmail.com
87601e24f73f8d8d3bd9e4d34f12274566f8cb6f
02b6afdd5793b6110c45e82b3f4854e8a38e9f48
/src/main/java/br/com/jmeterapp/repository/PersistentTokenRepository.java
4f73ab5a11ff0ba94d7859a8d2788a0573a3b581
[]
no_license
EdlaineZamora/jhipster
b090b4fc09eac0b42f3a8617b26337a606657bc8
184be69c7c8287b5dfcaf1195aa8917d337aad79
refs/heads/master
2021-01-04T14:06:52.291504
2017-01-11T00:32:37
2017-01-11T00:32:37
78,585,527
0
0
null
null
null
null
UTF-8
Java
false
false
524
java
package br.com.jmeterapp.repository; import br.com.jmeterapp.domain.PersistentToken; import br.com.jmeterapp.domain.User; import java.time.LocalDate; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Spring Data JPA repository for the PersistentToken entity. */ public interface PersistentTokenRepository extends JpaRepository<PersistentToken, String> { List<PersistentToken> findByUser(User user); List<PersistentToken> findByTokenDateBefore(LocalDate localDate); }
[ "edlainetsz1@hotmail.com" ]
edlainetsz1@hotmail.com
378fdf755124c30856e0004d4ebe57b2c6559384
dcad055580bb027010a3502394eb0823ed960db1
/Dynamic_SRS/src/id/ac/its/depandi/dynamic_srs/gui/srs/FormAddStep.java
880089bb032acf843ef252f522868b6961b116a8
[]
no_license
epiii/dynamicSrsApp
bcff0f8974e1b1c8caed52aaa31fd3ceee9ce3fc
ce5d001db0faf94d466dfb33f5d1b0389a81a994
refs/heads/master
2021-01-12T05:41:48.015711
2016-12-23T00:02:59
2016-12-23T00:02:59
77,170,675
0
0
null
null
null
null
UTF-8
Java
false
false
2,823
java
package id.ac.its.depandi.dynamic_srs.gui.srs; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import id.ac.its.depandi.dynamic_srs.core.Step; import id.ac.its.depandi.dynamic_srs.dao.StepDAO; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FormAddStep extends JDialog { private final JPanel contentPanel = new JPanel(); private JTextField txtStep; private StepDAO stepDAO; private Step theStep; private FormSRS fSRS; public FormAddStep(FormSRS fSRS){ this(); this.fSRS = fSRS; } /** * Create the dialog. */ public FormAddStep() { setResizable(false); setBounds(100, 100, 402, 120); getContentPane().setLayout(new BorderLayout()); contentPanel.setLayout(new FlowLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); { JLabel lblStepName = new JLabel("Step Name"); lblStepName.setFont(new Font("Gill Sans MT", Font.PLAIN, 12)); contentPanel.add(lblStepName); } { txtStep = new JTextField(); txtStep.setFont(new Font("Gill Sans MT", Font.PLAIN, 12)); contentPanel.add(txtStep); txtStep.setColumns(40); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton insertButton = new JButton("Insert"); insertButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addNewStep(); } }); insertButton.setFont(new Font("Gill Sans MT", Font.PLAIN, 12)); insertButton.setActionCommand("OK"); buttonPane.add(insertButton); getRootPane().setDefaultButton(insertButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancelButton.setFont(new Font("Gill Sans MT", Font.PLAIN, 12)); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } } private void addNewStep(){ stepDAO = new StepDAO(); String stepName = txtStep.getText(); if(stepName.equals("")) JOptionPane.showMessageDialog(this, "Please Input New Step.!"); else{ theStep = new Step(stepName); boolean result = stepDAO.addStep(theStep); if(result){ JOptionPane.showMessageDialog(this, "New Step Success Added.!"); dispose(); fSRS.refreshStepView(); }else JOptionPane.showMessageDialog(this, "Please Input Other New Step.!"); } } }
[ "gue.elfrianto@gmail.com" ]
gue.elfrianto@gmail.com
363e5564a505adf9918762d20b3a15ca252b2c63
57a7d45f155e7b80b8f7d8a79a1f0006fa1ac158
/app/src/main/java/com/bugevil/mhelmi/carshowroom/utils/Const.java
5eeb96ca31caec884c7743f292dfccfcff14edcd
[]
no_license
mhelmi/CarShowroom
9bedd4f7ef299756163c939002ce246b45ddf5f1
73de075732d33adfd92f4ecb0c99f394997f007b
refs/heads/master
2022-11-05T00:29:43.193915
2020-06-16T19:00:33
2020-06-16T19:00:33
272,788,516
2
0
null
null
null
null
UTF-8
Java
false
false
146
java
package com.bugevil.mhelmi.carshowroom.utils; public class Const { public static final int SUCCESS = 1; public static final int ERROR = 0; }
[ "mohamedhelmy137@gmail.com" ]
mohamedhelmy137@gmail.com
aa83ef24dcf5d8ef31146e34f7e97816ab8494f1
68ee068f2a8f44f6c469a70d8ba47eb667591e8a
/datasets/styler/milo/repair-attempt/batch_3/124/CubeItemNode.java
eb160cfaf6773d5e3f01f116ec91f71876e0758d
[]
no_license
aqhvhghtbtb/styler
261032390ef39224ab1fdfd51a70ba556e5f81d4
e2881daa6bbc7763ad4a9ba704c4d834316ed9c1
refs/heads/master
2021-03-07T16:50:11.364844
2020-02-28T10:00:47
2020-02-28T10:00:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,973
java
/* * Copyright (c) 2017 Kevin Herron * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.html. */ package org.eclipse.milo.opcua.sdk.server.model.nodes.variables; import java.util.Optional; import org.eclipse.milo.opcua.sdk.server.api.ServerNodeMap; import org.eclipse.milo.opcua.sdk.server.api.nodes.VariableNode; import org.eclipse.milo.opcua.sdk.server.model.types.variables.CubeItemType; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText; import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName; import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte; import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger; import org.eclipse.milo.opcua.stack.core.types.structured.AxisInformation; public class CubeItemNode extends ArrayItemNode implements CubeItemType { public CubeItemNode(ServerNodeMap nodeMap, NodeId nodeId, QualifiedName browseName, LocalizedText displayName, LocalizedText description, UInteger writeMask, UInteger userWriteMask) { super(nodeMap, nodeId, browseName, displayName, description, writeMask, userWriteMask); } public CubeItemNode(ServerNodeMap nodeMap, NodeId nodeId, QualifiedName browseName, LocalizedText displayName, LocalizedText description, UInteger writeMask, UInteger userWriteMask, DataValue value, NodeId dataType, Integer valueRank, UInteger[] arrayDimensions, UByte accessLevel, UByte userAccessLevel, double minimumSamplingInterval, boolean historizing) {super(nodeMap ,nodeId ,browseName ,displayName ,description ,writeMask ,userWriteMask ,value, dataType , valueRank ,arrayDimensions, accessLevel,userAccessLevel ,minimumSamplingInterval ,historizing ); } public PropertyNode getXAxisDefinitionNode() { Optional<VariableNode> propertyNode = getPropertyNode(CubeItemType.X_AXIS_DEFINITION); return (PropertyNode) propertyNode.orElse(null); } public AxisInformation getXAxisDefinition() { Optional<AxisInformation> propertyValue = getProperty(CubeItemType.X_AXIS_DEFINITION); return propertyValue.orElse(null); } public void setXAxisDefinition(AxisInformation value) { setProperty(CubeItemType.X_AXIS_DEFINITION, value); } public PropertyNode getYAxisDefinitionNode() { Optional<VariableNode> propertyNode = getPropertyNode(CubeItemType.Y_AXIS_DEFINITION); return (PropertyNode) propertyNode.orElse(null); } public AxisInformation getYAxisDefinition() { Optional<AxisInformation> propertyValue = getProperty(CubeItemType.Y_AXIS_DEFINITION); return propertyValue.orElse(null); } public void setYAxisDefinition(AxisInformation value) { setProperty(CubeItemType.Y_AXIS_DEFINITION, value); } public PropertyNode getZAxisDefinitionNode() { Optional<VariableNode> propertyNode = getPropertyNode(CubeItemType.Z_AXIS_DEFINITION); return (PropertyNode) propertyNode.orElse(null); } public AxisInformation getZAxisDefinition() { Optional<AxisInformation> propertyValue = getProperty(CubeItemType.Z_AXIS_DEFINITION); return propertyValue.orElse(null); } public void setZAxisDefinition(AxisInformation value) { setProperty(CubeItemType.Z_AXIS_DEFINITION, value); } }
[ "bloriot97@gmail.com" ]
bloriot97@gmail.com
bc88152433f8bc1bc501c8867b848b7b1cbfc96d
dfdf59bbae6ff96ec1a7c1cbc5aedcfd744e5107
/ams/src/ams/UserInterface.java
d5c62423c640ca149ca93d95d2bef7f0fe0dcd20
[]
no_license
Gaurav31200/ams2
be106fc0f0f137688ac7bd95e84635120908dcf2
ae04b856ca086966e68546e4691e9aeb090bd466
refs/heads/master
2022-01-09T13:38:07.738874
2019-05-14T06:07:29
2019-05-14T06:07:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,475
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 ams; import static ams.dbControl.rs; import static com.sun.javafx.scene.control.skin.Utils.getResource; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import net.proteanit.sql.DbUtils; /** The main UI. The homescreen basically * * @author Maan Alaulaqi (201610814@aau.ac.ae) */ public class UserInterface extends javax.swing.JFrame { protected static final ImageIcon ICON_ACTIVE = createImageIcon("images/Start_ACTIVE.png", "Card reader currently active.");// = new ImageIcon("/images/Start_ACTIVE.png"); protected static final ImageIcon ICON_INACTIVE = createImageIcon("images/Start_NOTACTIVE.png", "Card reader currently active.");//// = new ImageIcon("/images/Start_NOTACTIVE.png"); public static boolean x = false; protected static String uid_placeholder = ""; protected static String UID = uid_placeholder; /** * Creates new form UserInterface */ public UserInterface() { initComponents(); jPanel1.setVisible(true); jPanel4.setVisible(false); // jTable1.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLayeredPane1 = new javax.swing.JLayeredPane(); jPanel4 = new javax.swing.JPanel(); backToStart = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); studentListOnStart = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); ACTIVE_ICON = new javax.swing.JLabel(); INACTIVE_ICON = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); StudentCall = new java.awt.Label(); main_start = new javax.swing.JPanel(); currentClass = new java.awt.Label(); classCall = new java.awt.Label(); viewStudentsButton = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); mainBG_start = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setAutoRequestFocus(false); setBackground(new java.awt.Color(0, 0, 0)); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLayeredPane1.setMaximumSize(new java.awt.Dimension(798, 584)); jLayeredPane1.setPreferredSize(new java.awt.Dimension(798, 584)); jPanel4.setMinimumSize(new java.awt.Dimension(798, 584)); jPanel4.setOpaque(false); jPanel4.setPreferredSize(new java.awt.Dimension(798, 584)); backToStart.setText("Back"); backToStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { backToStartMouseReleased(evt); } }); studentListOnStart.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(studentListOnStart); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(370, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16)) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(backToStart, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE) .addComponent(backToStart, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) ); jLayeredPane1.add(jPanel4); jPanel4.setBounds(0, 0, 798, 584); jPanel2.setMaximumSize(new java.awt.Dimension(798, 584)); jPanel2.setMinimumSize(new java.awt.Dimension(798, 584)); jPanel2.setPreferredSize(new java.awt.Dimension(798, 584)); jPanel2.setLayout(null); ACTIVE_ICON.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Start_ACTIVE.png"))); // NOI18N jPanel2.add(ACTIVE_ICON); ACTIVE_ICON.setBounds(60, 230, 624, 155); INACTIVE_ICON.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Start_NOTACTIVE.png"))); // NOI18N jPanel2.add(INACTIVE_ICON); INACTIVE_ICON.setBounds(60, 230, 624, 155); INACTIVE_ICON.setVisible(false); jPanel1.setOpaque(false); StudentCall.setBackground(new java.awt.Color(255, 255, 255)); StudentCall.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N StudentCall.setText(((InterfaceCmds.getCurrentSwipe(UID) == null) ? " ": InterfaceCmds.getCurrentSwipe(UID)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 151, Short.MAX_VALUE) .addComponent(StudentCall, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(StudentCall, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 55, Short.MAX_VALUE)) ); System.out.println(CardConnection.cardUID+"< CardConnect.cardUID lol "); jPanel2.add(jPanel1); jPanel1.setBounds(90, 410, 541, 105); main_start.setMinimumSize(new java.awt.Dimension(798, 584)); main_start.setLayout(null); currentClass.setBackground(new java.awt.Color(255, 255, 255)); currentClass.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); currentClass.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N currentClass.setText("Current class: "); main_start.add(currentClass); currentClass.setBounds(90, 170, 160, 40); classCall.setBackground(new java.awt.Color(255, 255, 255)); classCall.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N classCall.setText(InterfaceCmds.getCurrentClass(1)); main_start.add(classCall); classCall.setBounds(250, 167, 390, 50); classCall.getAccessibleContext().setAccessibleName(""); viewStudentsButton.setText("View students"); viewStudentsButton.setVisible(false); viewStudentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewStudentsButtonActionPerformed(evt); } }); main_start.add(viewStudentsButton); viewStudentsButton.setBounds(620, 500, 140, 60); jButton1.setText("Attendance List"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { jButton1MouseReleased(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); main_start.add(jButton1); jButton1.setBounds(20, 490, 150, 70); mainBG_start.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/mainBG_start2.png"))); // NOI18N mainBG_start.setAlignmentY(0.0F); main_start.add(mainBG_start); mainBG_start.setBounds(0, 0, 798, 584); jPanel2.add(main_start); main_start.setBounds(0, 0, 800, 590); jLayeredPane1.add(jPanel2); jPanel2.setBounds(0, 0, 798, 584); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/mainBG_start2.png"))); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, 0)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING) ); jLayeredPane1.add(jPanel3); jPanel3.setBounds(0, 0, 800, 590); getContentPane().add(jLayeredPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void viewStudentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewStudentsButtonActionPerformed // TODO add your handling code here: java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ClassManager().setVisible(true); } }); //System.out.println(" Boop:"+ uid_placeholder+ "Coz why not lol "); }//GEN-LAST:event_viewStudentsButtonActionPerformed private void jButton1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseReleased // TODO add your handling code here: //dbControl.dbComd("select student.STUDENT_ID,student.first_name, student.last_name from student join student_class on student.id = STUDENT_CLASS.STUDENT_ID join class on class.id = student_class.class_id join instructor_class on instructor_class.CLASS_ID = student_class.CLASS_ID join instructor on instructor.ID = instructor_class.INSTRUCTOR_ID where class.id = "+stringy2[0][incrementMe-1]+" and student_class.class_section = '"+class_sec+"' and instructor_class.class_section = '"+class_sec+"'"); int active_class_id = ClassThread.classCheck(); System.out.println(active_class_id); //active_class_id = 2; if (active_class_id == 0){ //jPanel4.setVisible(true); //StudentListOnStart.setVisible(true); } else{ //good lord this sql query was a mess to figure out. //Basically it selects the students from the current class of the current //instructor. dbControl.dbComd("SELECT DISTINCT STUDENT.STUDENT_ID as \"Student ID\", FIRST_NAME as \"First Name\", LAST_NAME as \"Last Name\", PRESENT AS \"PRESENT?\" FROM STUDENT \n" + "JOIN STUDENT_CLASS ON STUDENT_CLASS.STUDENT_ID = STUDENT.ID\n" + "JOIN CLASS ON CLASS.ID = STUDENT_CLASS.CLASS_ID\n" + "JOIN ACTIVE_CLASSES ON ACTIVE_CLASSES.CLASS_ID = CLASS.ID\n" + "JOIN ATTEND ON ATTEND.STUDENT_ID = STUDENT.ID\n" + "JOIN CLASS_SCHEDULE ON CLASS_SCHEDULE.ID = ACTIVE_CLASSES.CLASS_SCHEDULE_ID\n" + "WHERE ACTIVE_CLASSES.ID = "+ active_class_id); //if (dbControl.rs.next()) StudentListOnStart.setModel(DbUtils.resultSetToTableModel(rs)); studentListOnStart.setModel(DbUtils.resultSetToTableModel(rs)); dbControl.doClose(); } //Use the following line to edit records. setValueAt(row,colum) System.out.println(studentListOnStart.getRowCount()+ " studentListOnStart size"); for (int i = 0; i < studentListOnStart.getRowCount(); i++){ boolean x = (boolean) studentListOnStart.getValueAt(i,3); if (!x) studentListOnStart.setValueAt("NOT PRESENT", i, 3); else studentListOnStart.setValueAt("PRESENT", i, 3); } System.out.println(studentListOnStart.getValueAt(1,3)); jPanel2.setVisible(false); jPanel4.setVisible(true); }//GEN-LAST:event_jButton1MouseReleased private void backToStartMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backToStartMouseReleased // TODO add your handling code here: jPanel2.setVisible(true); jPanel4.setVisible(false); }//GEN-LAST:event_backToStartMouseReleased private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed /** Returns an ImageIcon, or null if the path was invalid. * This is to allow images to brought in without a NullPointerException * Resourced from : * https://stackoverflow.com/questions/13151979/null-pointer-exception-when-an-imageicon-is-added-to-jbutton-in-netbeans */ public static ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = ClassLoader.getSystemResource(path); if (imgURL != null) { //System.out.println(path); return new ImageIcon(imgURL); } else { System.out.println("Couldn't find file: " + path); return null; } } /** * Need a way to access non-static methods from static context * Referenced from https://www.javacodegeeks.com/2017/10/can-non-static-method-access-static-variablemethod-java.html * * @param x Picture URL/File Path location * @return ImageIcon The image file will now be able to be used in java. */ public static ImageIcon getIcon(String x) { ImageIcon defaultIcon = new ImageIcon(ClassLoader.getSystemResource(x)); return defaultIcon; } /** * This is to update the name bar of the student/employee. I just stuck to student coz it's easier * @param UID Card UID. */ public static void updateStudent(String UID){ if (UID == ""){} else { //Update Student here uid_placeholder = UID; uid_placeholder = InterfaceCmds.getCurrentUID(UID); String y = InterfaceCmds.getCurrentSwipe(UID); StudentCall.setText(y); // System.out.println(uid_placeholder+ " " +y + " InterfaceCmds.getCurrentSwipe() reached"); //System.out.println("MAAN LOOK AT ME I'M THE UID WOO! " + UID); } } public static void updateActiveCheck(boolean success) { /* System.out.println(ACTIVE_ICON+" SYSTEM"); ImageIcon x,y; x = new ImageIcon(UserInterface.class.getResource("/images/Start_ACTIVE.png")); System.out.println(x + "LOLOLOLLOOLLOL"); y = new ImageIcon(UserInterface.class.getResource("/images/Start_NOTACTIVE.png"));*/ if(success) { /*System.out.println("YES" + x); ACTIVE_ICON.setIcon(ICON_ACTIVE);// = new ImageIcon("/images/Start_ACTIVE.png");); ACTIVE_ICON.setVisible(true); INACTIVE_ICON.setVisible(false);*/ updateChecker.updateActiveCheck(true); x = true; viewStudentsButton.setVisible(true); } else if(!success) { /* System.out.println("NO" + x); ACTIVE_ICON.setIcon(y); ACTIVE_ICON.setVisible(false); INACTIVE_ICON.setVisible(true);*/ x = false; updateChecker.updateActiveCheck(false); viewStudentsButton.setVisible(false); } } // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JLabel ACTIVE_ICON; public static javax.swing.JLabel INACTIVE_ICON; private static java.awt.Label StudentCall; private javax.swing.JButton backToStart; static java.awt.Label classCall; private java.awt.Label currentClass; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel mainBG_start; private javax.swing.JPanel main_start; private javax.swing.JTable studentListOnStart; public static javax.swing.JButton viewStudentsButton; // End of variables declaration//GEN-END:variables }
[ "thema3an@gmail.com" ]
thema3an@gmail.com
a74ab0944c43ec64325537ce89213f8665e2f971
dcdf71d13b4a9abc9542057eb86eb03fbebc2e97
/jsp/src/main/java/ru/job4j/config/MessageSecurityWebApplicationInitializer.java
3d9be1c691ac67f04e33d8dc9123968f91fe80e5
[ "Apache-2.0" ]
permissive
Rmelev/worktime
5e78bc1722b5cf6d8c4d668505e869abcf0cc4b0
d0778679a62e784fb7d2a01074c5554fb98cf680
refs/heads/master
2020-03-09T17:27:04.508381
2018-04-10T12:32:14
2018-04-10T12:32:14
128,908,785
0
0
null
null
null
null
UTF-8
Java
false
false
279
java
package ru.job4j.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * MessageSecurityWebApplicationInitializer. */ public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
[ "roman.shmelev@gmail.com" ]
roman.shmelev@gmail.com
971eb26157118ec1aaa72fcefc7196c4b7b6729a
7e65ec4751c07dc443c99b00652d67c6f5884e79
/src/main/java/com/jfinteck/dmq/service/IMongodbTableNameService.java
1ee854758bccb493e69315496b4b30c25c4c7de3
[]
no_license
tping-xiai/dmq-file-parsing
ef2dfddf3e5dacbf45e5e6ccf2326ab1b8f3f847
7fcf208ae61c72d8e635e1f961fb5d29417bc6d2
refs/heads/master
2020-04-19T15:18:32.746721
2019-03-12T12:10:25
2019-03-12T12:10:25
168,269,847
0
0
null
null
null
null
UTF-8
Java
false
false
485
java
package com.jfinteck.dmq.service; import java.util.List; import com.baomidou.mybatisplus.service.IService; import com.jfinteck.dmq.dto.BaseDTO; import com.jfinteck.dmq.dto.MongodbTableName; public interface IMongodbTableNameService extends IService<MongodbTableName>{ List<BaseDTO> findTableByServerIdAndDatabaseName(Long serverId, String databaseName); /** * 修改表解析状态值 * * @param tableName */ void updateTableIsAnalysis(MongodbTableName tableName); }
[ "zhuweijun735998@163.com" ]
zhuweijun735998@163.com
0d7bd13ea3406b62e2b6e4e36d04da57e5ed2bfb
5b15ad36e5082a859e3b6231facc0c13bf8e9576
/src/brness/pac22/SetAndMap/Test.java
4bc77ac9b78b17354f3d0e9ce26740178d537d5f
[]
no_license
brness/JavaAlgorithm
459ff332fd28aba7e73ba6b2cf8ca15557b2ffc8
b778d2041039dd8dbbcaa828f3219ab14ccc5308
refs/heads/master
2020-06-29T20:59:01.141480
2019-08-27T06:34:51
2019-08-27T06:37:37
200,621,557
2
0
null
null
null
null
UTF-8
Java
false
false
1,639
java
package brness.pac22.SetAndMap; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; public class Test { public static void main(String[] args) throws Exception{ // Set<String> set=new HashSet<>(); // set.add("fas"); // set.add("asd"); // set.add("das"); // set.add("dasasdf"); // set.add("wehew"); // // for (String s:set){ // System.out.println(s); // } // LinkedHashSet<String> set1=new LinkedHashSet<>(); // set1.add("New York"); // LinkedHashSet<String> set2=set1; // LinkedHashSet<String> set3=(LinkedHashSet<String>)(set1.clone()); // set1.add("Atlanta"); // System.out.println("set1 is "+set1); // System.out.println("set2 is "+set2); // System.out.println("set3 is "+set3); ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream("test.dat")); LinkedHashSet<String> set1=new LinkedHashSet<>(); set1.add("New York"); LinkedHashSet<String> set2=(LinkedHashSet<String>)(set1.clone()); set1.add("Atlanta"); outputStream.writeObject(set1); outputStream.writeObject(set2); outputStream.close(); ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream("test.dat")); set1=(LinkedHashSet<String>)inputStream.readObject(); set2=(LinkedHashSet<String>)inputStream.readObject(); System.out.println(set1); System.out.println(set2); inputStream.close(); } }
[ "529353354@qq.com" ]
529353354@qq.com
1e83541713b15693efec7924351efe5350a34a30
71c310da3ce930529411d30f17ddca2b9630c5c2
/Algo_Practice/SW_Expert/D2/SE_D2_1984_중간평균값구하기.java
bd1fae6115665afce34758a2b2a25536c0b65d98
[]
no_license
Tnx2U/Algo_Practice
21f136798b5f9ecbd0507fb1c704ae4d56dbdd0e
da0c14a0e7a189c013c22c6f4bcffbdad5931cfa
refs/heads/master
2022-04-07T22:02:50.601433
2020-03-04T06:11:17
2020-03-04T06:11:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
543
java
package D2; import java.util.Arrays; import java.util.Scanner; public class SE_D2_1984_중간평균값구하기 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { double ans = 0; int[] arr = new int[10]; for (int i = 0; i < 10; i++) { arr[i] = sc.nextInt(); } Arrays.sort(arr); for (int i = 1; i < arr.length-1; i++) { ans += arr[i]; } System.out.println("#"+t+" "+Math.round(ans/8)); } } }
[ "rndskadl@gmail.com" ]
rndskadl@gmail.com
77a02080550afef87ebc6dc337bdcf04175be743
00651d9fc0b20e514361f940f036a4b58e10f4da
/jblog/src/main/java/com/jblog/config/GatewayConfiguration.java
45cfad7f960888127c87ece4a58097ec93be8b0a
[]
no_license
arslanberk/JBlog
5ed745cd786dd6feb0fac6a81a32869d3a544ce3
86b193b7548bd1554dacfc6ff2e2444f5bc2a3cd
refs/heads/master
2021-09-04T02:28:11.833274
2018-01-14T17:33:59
2018-01-14T17:33:59
117,346,316
0
0
null
null
null
null
UTF-8
Java
false
false
1,876
java
package com.jblog.config; import io.github.jhipster.config.JHipsterProperties; import com.jblog.gateway.ratelimiting.RateLimitingFilter; import com.jblog.gateway.accesscontrol.AccessControlFilter; import com.jblog.gateway.responserewriting.SwaggerBasePathRewritingFilter; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.netflix.zuul.filters.RouteLocator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GatewayConfiguration { @Configuration public static class SwaggerBasePathRewritingConfiguration { @Bean public SwaggerBasePathRewritingFilter swaggerBasePathRewritingFilter(){ return new SwaggerBasePathRewritingFilter(); } } @Configuration public static class AccessControlFilterConfiguration { @Bean public AccessControlFilter accessControlFilter(RouteLocator routeLocator, JHipsterProperties jHipsterProperties){ return new AccessControlFilter(routeLocator, jHipsterProperties); } } /** * Configures the Zuul filter that limits the number of API calls per user. * <p> * This uses Bucket4J to limit the API calls, see {@link com.jblog.gateway.ratelimiting.RateLimitingFilter}. */ @Configuration @ConditionalOnProperty("jhipster.gateway.rate-limiting.enabled") public static class RateLimitingConfiguration { private final JHipsterProperties jHipsterProperties; public RateLimitingConfiguration(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Bean public RateLimitingFilter rateLimitingFilter() { return new RateLimitingFilter(jHipsterProperties); } } }
[ "berk.arslan93@gmail.com" ]
berk.arslan93@gmail.com
33472d895bb9ae8454bf739427fd38a28941bc4d
b2e8bfb7ffda9926bd5c3abc2269e214891a8b9b
/CompetitionPlatform/app/src/main/java/tecno/competitionplatform/entities/Country.java
ce644dffe9b9f75be5799e44b382a2fbbea7c7e2
[]
no_license
andres811/competition_android
ea6bb0ada1c8843271378b1fac72d72b58b71e4d
b53ec4054cda2c0803d9620b8f039a672e27231f
refs/heads/master
2016-08-12T05:23:05.657950
2015-12-20T22:09:17
2015-12-20T22:09:17
45,003,277
0
0
null
null
null
null
UTF-8
Java
false
false
648
java
package tecno.competitionplatform.entities; /** * Created by Andres on 31/10/2015. */ public class Country { private Integer countryId; private String sortname; private String name; public String getSortname() { return sortname; } public void setSortname(String sortname) { this.sortname = sortname; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[ "apena@cualit.com" ]
apena@cualit.com
873acd363c583a1cc8ac4be3f52947527b8a3a85
c7bbde6bd73928c19efd83f243cd7b37166d1b10
/spring-security/hello-service/src/main/java/com/frankmoley/landon/security/helloservice/Die.java
481e6c4697ba405a5d941138a52b1fbcafa30083
[]
no_license
dsuruagy/LiLSpring
2675de009e507370a5c64e05fc5b24d908cd621a
f381240f78570ebadb258189adac78620686c719
refs/heads/master
2023-08-17T05:45:12.512893
2021-10-03T20:35:58
2021-10-03T20:35:58
296,189,740
1
0
null
null
null
null
UTF-8
Java
false
false
289
java
package com.frankmoley.landon.security.helloservice; import java.util.Random; public class Die { private int value; public void roll(){ Random random = new Random(); value = random.nextInt(6) + 1; } public int getValue() { return value; } }
[ "dsuruagy@gmail.com" ]
dsuruagy@gmail.com
ef4489ce0a584b2849f07d9919c123fc0d308ae7
74b47b895b2f739612371f871c7f940502e7165b
/aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/transform/DvbSdtSettingsMarshaller.java
251d8dece503bb4aa4ef6717a32ffcdf82ae37ad
[ "Apache-2.0" ]
permissive
baganda07/aws-sdk-java
fe1958ed679cd95b4c48f971393bf03eb5512799
f19bdb30177106b5d6394223a40a382b87adf742
refs/heads/master
2022-11-09T21:55:43.857201
2022-10-24T21:08:19
2022-10-24T21:08:19
221,028,223
0
0
Apache-2.0
2019-11-11T16:57:12
2019-11-11T16:57:11
null
UTF-8
Java
false
false
2,936
java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediaconvert.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.mediaconvert.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DvbSdtSettingsMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DvbSdtSettingsMarshaller { private static final MarshallingInfo<String> OUTPUTSDT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("outputSdt").build(); private static final MarshallingInfo<Integer> SDTINTERVAL_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sdtInterval").build(); private static final MarshallingInfo<String> SERVICENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("serviceName").build(); private static final MarshallingInfo<String> SERVICEPROVIDERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("serviceProviderName").build(); private static final DvbSdtSettingsMarshaller instance = new DvbSdtSettingsMarshaller(); public static DvbSdtSettingsMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DvbSdtSettings dvbSdtSettings, ProtocolMarshaller protocolMarshaller) { if (dvbSdtSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dvbSdtSettings.getOutputSdt(), OUTPUTSDT_BINDING); protocolMarshaller.marshall(dvbSdtSettings.getSdtInterval(), SDTINTERVAL_BINDING); protocolMarshaller.marshall(dvbSdtSettings.getServiceName(), SERVICENAME_BINDING); protocolMarshaller.marshall(dvbSdtSettings.getServiceProviderName(), SERVICEPROVIDERNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
8788b6babaddcfa213a15967891a55fe330cfe0b
2f2672dbe495f3f348ac435183498c1c4de3975a
/app/src/main/java/com/example/it/myapplication/UploadVideo.java
de0b172300f71bedf9d33eef48e3f88096661daa
[]
no_license
srambtech/Accident-Status-Report
8fc928ebc3a2097b7aaf58d7d379241595ae1425
fa2ac42d637a9cf32305e121261a0837c26fbe4e
refs/heads/main
2023-03-11T07:06:00.336338
2021-02-12T02:09:10
2021-02-12T02:09:10
338,201,992
0
0
null
null
null
null
UTF-8
Java
false
false
2,681
java
package com.example.it.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class UploadVideo extends Activity implements OnClickListener { String realPath; TextView txtSDK; Button btnSelectImage; TextView txtUriPath,txtRealPath; ImageView imageView; String cno; String pstation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_video); Intent in=getIntent(); cno=in.getStringExtra("cno"); pstation=in.getStringExtra("pstation"); // get reference to views txtSDK = (TextView) findViewById(R.id.txtSDK); btnSelectImage = (Button) findViewById(R.id.btnSelectImage); txtUriPath = (TextView) findViewById(R.id.txtUriPath); txtRealPath = (TextView) findViewById(R.id.txtRealPath); imageView = (ImageView) findViewById(R.id.imgView); // add click listener to button btnSelectImage.setOnClickListener(this); } @Override public void onClick(View view) { // 1. on Upload click call ACTION_GET_CONTENT intent Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // 2. pick image only intent.setType("video/*"); // 3. start activity startActivityForResult(intent, 0); // define onActivityResult to do something with picked image } @Override protected void onActivityResult(int reqCode, int resCode, Intent data) { if(resCode == Activity.RESULT_OK && data != null){ // SDK < API11 if (Build.VERSION.SDK_INT < 11) realPath = RealPath.getRealPathFromURI_BelowAPI11(this, data.getData()); // SDK >= 11 && SDK < 19 else if (Build.VERSION.SDK_INT < 19) realPath = RealPath.getRealPathFromURI_API11to18(this, data.getData()); // SDK > 19 (Android 4.4) else realPath = RealPath.getRealPathFromURI_API19(this, data.getData()); launchUploadActivity(false); } }private void launchUploadActivity(boolean isImage){ Intent i = new Intent(UploadVideo.this, UploadActivity1.class); i.putExtra("filePath", realPath); i.putExtra("isImage", isImage); i.putExtra("cno",cno); i.putExtra("pstation",pstation); startActivity(i); } }
[ "sriram@sris-mbp.attlocal.net" ]
sriram@sris-mbp.attlocal.net
3503b58b397896d20af0bf124a8013cb161919b2
6a83218c92fbb26b9199b15454ce3dbca508a608
/common/src/main/java/dev/ftb/mods/ftbteams/client/gui/InviteScreen.java
1105ea5859ae917488f2e8ba44bd2912e7076789
[]
no_license
FTBTeam/FTB-Teams
17b037a6c983021169b7173942a65d8295eb563b
24f2e4551101477cda8268f6c1b715b168707cb1
refs/heads/main
2023-09-01T14:00:24.769673
2023-07-03T15:40:55
2023-07-03T15:40:55
219,998,659
10
23
null
2023-07-03T15:40:56
2019-11-06T13:05:33
Java
UTF-8
Java
false
false
1,161
java
package dev.ftb.mods.ftbteams.client.gui; import dev.ftb.mods.ftblibrary.icon.Icons; import dev.ftb.mods.ftbteams.api.FTBTeamsAPI; import dev.ftb.mods.ftbteams.api.client.KnownClientPlayer; import dev.ftb.mods.ftbteams.net.PlayerGUIOperationMessage; import net.minecraft.network.chat.Component; public class InviteScreen extends BaseInvitationScreen { public InviteScreen() { super(Component.translatable("ftbteams.gui.invite")); } @Override protected boolean shouldIncludePlayer(KnownClientPlayer player) { // any player who is online and not in a team return player.isOnlineAndNotInParty() && !player.equals(FTBTeamsAPI.api().getClientManager().self()); } @Override protected ExecuteButton makeExecuteButton() { return new ExecuteButton(Component.translatable("ftbteams.gui.send_invite"), Icons.ADD, () -> { new PlayerGUIOperationMessage(PlayerGUIOperationMessage.Operation.INVITE, invites).sendToServer(); closeGui(); }) { @Override public boolean isEnabled() { return !invites.isEmpty(); } }; } }
[ "des.herriott@gmail.com" ]
des.herriott@gmail.com
4dfd79e5582da09c6f64e01ae8587ebee92c8d93
824790e3aeacd3b83dd4e5a624aa102c47fc769b
/src/main/java/de/mkristian/ixtlan/gwt/caches/BrowserOrMemoryStore.java
1824df3ea0cb6351e38b8f092abb1452195e4744
[]
no_license
mkristian/ixtlan-gwt
79557dfc6085901b903f10baa6d7113e828d7c6c
7d3b3ce8df23c9547bfc11b80e6895141b119370
refs/heads/master
2020-07-26T15:01:15.622176
2014-01-12T21:08:54
2014-01-12T21:08:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,506
java
package de.mkristian.ixtlan.gwt.caches; import java.util.List; import org.fusesource.restygwt.client.JsonEncoderDecoder; import com.google.gwt.storage.client.Storage; import de.mkristian.ixtlan.gwt.models.Identifiable; public class BrowserOrMemoryStore<T extends Identifiable> implements Store<T> { private final Store<T> store; private boolean storeCollections; public BrowserOrMemoryStore(JsonEncoderDecoder<T> coder, String key){ this( coder, key, true ); } public BrowserOrMemoryStore(JsonEncoderDecoder<T> coder, String key, boolean storeCollections ){ this.storeCollections = storeCollections; if ( Storage.isLocalStorageSupported() ){ store = new BrowserStore<T>(coder, key); } else { store = new MemoryStore<T>(); } } public void update(T model, String json) { store.update(model, json); } public void replaceAll(List<T> models, String json) { if ( storeCollections ) { store.replaceAll(models, json); } } public T get(int id) { return store.get(id); } public List<T> getAll() { if (storeCollections) { return store.getAll(); } else { return null; } } public void remove(T model) { store.remove(model); } public void removeAll() { store.removeAll(); } public void purgeAll() { store.purgeAll(); } }
[ "m.kristian@web.de" ]
m.kristian@web.de
f72f4e44e890e5888d9566a252dfb1314e1d4ad9
b797d1ebe3986a063cdd074a6382a0209249b614
/src/main/java/FEM/Matrix/MatrixC.java
2a97ede35bde9955c9b0613914ac55327a0ad790
[]
no_license
AdamBrti/FemProblem
415418b63aaa4f6f54eeca1ea6f626e5ab114c74
8a2582fd089f8f7e38f5e97d54a8bed4f88f6b4a
refs/heads/master
2020-04-01T22:05:56.452949
2019-01-05T13:23:30
2019-01-05T13:23:30
153,691,574
0
0
null
null
null
null
UTF-8
Java
false
false
3,240
java
package FEM.Matrix; import FEM.FileOperation.DataFromFile; import FEM.model.UniversalElement; import java.util.ArrayList; import java.util.List; public class MatrixC { private DataFromFile dataFromFile; private double[][] jacobian; private double[][] jacobian2D; private double[] detJ; private double[][] fukcjaKsztaltu; public double[][] matrixC; private List<double[][]> listOfPointIntegrals; public MatrixC() { } public MatrixC(DataFromFile dataFromFile, UniversalElement universalElement, MatrixH matrixH) { this.dataFromFile = dataFromFile; this.jacobian = matrixH.getJacobian(); this.jacobian2D = matrixH.getJacobian2D(); this.detJ = matrixH.getDetJ(); } public void buildMatrixC(UniversalElement universalElement) { calculateFunkcjaKsztaltu(universalElement); calculateIntegralPoints(); calculateMatrixC(); //show2D(matrixC); } public void calculateFunkcjaKsztaltu(UniversalElement universalElement) { double[] ksiValues = universalElement.getKsiValueTable(); double[] etaValues = universalElement.getEtaValueTable(); double tmpFunkcjaKsztaltu[][] = new double[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == 0) { tmpFunkcjaKsztaltu[j][i] = 0.25 * (1 - ksiValues[j]) * (1 - etaValues[j]); } if (i == 1) { tmpFunkcjaKsztaltu[j][i] = 0.25 * (1 + ksiValues[j]) * (1 - etaValues[j]); } if (i == 2) { tmpFunkcjaKsztaltu[j][i] = 0.25 * (1 + ksiValues[j]) * (1 + etaValues[j]); } if (i == 3) { tmpFunkcjaKsztaltu[j][i] = 0.25 * (1 - ksiValues[j]) * (1 + etaValues[j]); } } } this.fukcjaKsztaltu = tmpFunkcjaKsztaltu; } public void calculateIntegralPoints() { listOfPointIntegrals = new ArrayList<>(); for (int p = 0; p < 4; p++) { double integralPoionts[][] = new double[4][4]; double[] tmpFunKsztaltu = fukcjaKsztaltu[p]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { integralPoionts[i][j] = dataFromFile.getSpecHeat() * dataFromFile.getDensity() * tmpFunKsztaltu[i] * tmpFunKsztaltu[j] * detJ[p]; } } listOfPointIntegrals.add(integralPoionts); } } public void calculateMatrixC() { matrixC = new double[4][4]; for (double[][] partMatrix : listOfPointIntegrals) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrixC[i][j] += partMatrix[i][j]; } } } } public void show2D(double[][] tab) { for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab.length; j++) { System.out.format("%.3f ", tab[i][j]); } System.out.println(); } System.out.println("\n----------------------------------------------------------------"); } }
[ "AdamBrti@users.noreply.github.com" ]
AdamBrti@users.noreply.github.com
63b43f8840edabf5ed8a4d651e9d84c8b5684ac0
0a06c25541f123c4791e3369011e5b87a9ce94b4
/HRSSM/src/main/java/com/show/service/StoTService.java
c57ee06c43c33e2bce518a78450ba1eaeaa94a21
[]
no_license
Jy03684315/HR-SSM
5d09853d293b1bc50eb0dc3ca0916a6dea9067e2
e7fbd0714d0581a77bb0a09761af3f4dc7acbc52
refs/heads/master
2020-03-23T23:28:29.374648
2018-08-06T18:59:30
2018-08-06T18:59:30
142,236,163
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
package com.show.service; import com.show.model.StoT; /** * Created by Show on 2018/8/2. */ public interface StoTService { void addStoT(StoT stoT); }
[ "304393698@qq.com" ]
304393698@qq.com
5ccf245462fc323d8c7566607f85077131a48643
50c485534336dc93375e03faede30c9ed016958e
/src/CustomComparator.java
ed002d2bf55d8909b6fcf03fd318a498648722a6
[]
no_license
min-chev/FunctionalProgramming
ed2caf81876cb0a8912f9d7149eea72d5862865a
96c025df361eba7bb04b3b7d7c2748a64fe175c6
refs/heads/master
2021-01-19T12:10:25.773886
2017-02-17T11:43:06
2017-02-17T11:43:06
82,291,953
0
0
null
null
null
null
UTF-8
Java
false
false
1,058
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; public class CustomComparator { public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Integer[] nums = Arrays.stream(reader.readLine().split(" ")) .map(Integer::parseInt).toArray(Integer[]::new); Comparator<Integer> custom = (o1, o2) -> { int o1Abs = Math.abs(o1); int o2Abs = Math.abs(o2); if (o1Abs % 2 == 0 && o2Abs % 2 == 1) { return -1; } else if (o1Abs % 2 == 1 && o2Abs % 2 == 0) { return 1; } else if (o1 < o2) { return -1; } else if (o2 < o1) { return 1; } return 0; }; Arrays.sort(nums, custom); for (Integer num : nums) { System.out.print(num + " "); } } }
[ "YOU@EXAMPLE.COM" ]
YOU@EXAMPLE.COM
1ddb09ca838d40ced5b1388a460b6c29bb485dc0
674c01ca7ac0e5e9cd4f9a9b7305d5950b68f8c7
/code/LIBREC/src/librec/intf/Recommender.java
344911d7a03ac030427b8d6ca411862ced2a5d7d
[]
no_license
mvijaikumar/TagEmbedSVD
6e5dea1afa640b0f993849bb406a83310ac29767
7a2fa8f6c987a92d38768f3308ea55e0460e5aae
refs/heads/master
2020-07-14T03:08:31.654206
2019-09-01T09:38:48
2019-09-01T09:38:48
205,221,801
1
0
null
null
null
null
UTF-8
Java
false
false
38,531
java
// Copyright (C) 2014 Guibing Guo // // This file is part of LibRec. // // LibRec 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. // // LibRec 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 LibRec. If not, see <http://www.gnu.org/licenses/>. // package librec.intf; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import librec.data.AddConfiguration; import librec.data.Configuration; import librec.data.DataDAO; import librec.data.DataSplitter; import librec.data.MatrixEntry; import librec.data.SparseMatrix; import librec.data.SparseVector; import librec.data.SymmMatrix; import librec.metric.ITimeMetric; import librec.metric.MetricCollection; import librec.metric.MetricMine; import librec.util.Debug; import librec.util.FileConfiger; import librec.util.FileIO; import librec.util.LineConfiger; import librec.util.Lists; import librec.util.Logs; import librec.util.Sims; import com.google.common.base.Stopwatch; import com.google.common.base.Strings; import com.google.common.cache.LoadingCache; /** * General recommenders * * @author Guibing Guo */ @Configuration public abstract class Recommender implements Runnable { /*************** MINE **************************/ protected static MetricMine minmet = new MetricMine(); protected BufferedWriter bw = null; protected static String resFile; protected static double testrmse; protected static double testmae ; protected static double coldu_testmae, coldu_testrmse, coldi_testmae, coldi_testrmse ; protected static String data_path; /************************************ Static parameters for all recommenders ***********************************/ // configer public static FileConfiger cf; // matrix of rating data public static SparseMatrix rateMatrix, timeMatrix; // default temporary file directory public static String tempDirPath; // params used for multiple runs public static Map<String, List<Float>> params = new HashMap<>(); // Guava cache configuration protected static String cacheSpec; // number of cpu cores used for parallelization protected static int numCPUs; // verbose protected static boolean verbose = true; // line configer for item ranking, evaluation protected static LineConfiger rankOptions, algoOptions; // is ranking/rating prediction public static boolean isRankingPred; // threshold to binarize ratings public static float binThold; // the ratio of validation data split from training data public static float validationRatio; // is diversity-based measures used protected static boolean isDiverseUsed; // early-stop criteria protected static String earlyStopMeasure = null; // is save model protected static boolean isSaveModel = false; // is split data by date protected static boolean isSplitByDate; // view of rating predictions public static String view; // rate DAO object public static DataDAO rateDao; // number of users, items, ratings protected static int numUsers, numItems, numRates; // number of recommended items protected static int numRecs, numIgnore; // a list of rating scales protected static List<Double> ratingScale; // number of rating levels protected static int numLevels; // Maximum, minimum values of rating scales protected static double maxRate, minRate; // ratings' timestamps public static SparseMatrix testTimeMatrix; // minimum, maximum timestamp protected static long minTimestamp, maxTimestamp; // init mean and standard deviation protected static double initMean, initStd; // small value for initialization protected static double smallValue = 0.01; // number of nearest neighbors protected static int knn; // similarity measure protected static String similarityMeasure; // number of shrinkage protected static int similarityShrinkage; /** * An indicator of initialization of static fields. This enables us to control when static fields are initialized, * while "static block" will be always initialized or executed. The latter could cause unexpected exceptions when * multiple runs (with different configuration files) are conducted sequentially, because some static settings will * not be override in such a "staic block". */ public static boolean resetStatics = true; /************************************ Recommender-specific parameters ****************************************/ // algorithm's name public String algoName; // current fold protected int fold; // fold information protected String foldInfo; // is output recommendation results protected boolean isResultsOut = true; // user-vector cache, item-vector cache protected LoadingCache<Integer, SparseVector> userCache, itemCache; // user-items cache, item-users cache protected LoadingCache<Integer, List<Integer>> userItemsCache, itemUsersCache; // rating matrix for training, validation and test protected SparseMatrix trainMatrix, validationMatrix, testMatrix; // upper symmetric matrix of item-item correlations protected SymmMatrix corrs; // performance measures //public Map<Measure, Double> measures; // RB Replace old Map with dedicated class for greater flexibility public MetricCollection measures, mesvalid, mesvalidtemp, mestesttemp; //Mine valid added // global average of training rates protected double globalMean; protected List<String> metricNames; /** * Recommendation measures * */ //public enum Measure { /* prediction-based measures */ // MAE, RMSE, NMAE, rMAE, rRMSE, MPE, Perplexity, /* ranking-based measures */ // D5, D10, Pre5, Pre10, Rec5, Rec10, MAP, MRR, NDCG, AUC, /* execution time */ // TrainTime, TestTime, /* loss value */ // Loss //} /** * Constructor for Recommender * * @param trainMatrix * train matrix * @param testMatrix * test matrix */ public Recommender(SparseMatrix trainMatrix, SparseMatrix testMatrix, int fold) { // config recommender if (cf == null || rateMatrix == null) { Logs.error("Recommender is not well configed"); System.exit(-1); } // static initialization (reset), only done once if (resetStatics) { // change the indicator resetStatics = false; ratingScale = rateDao.getRatingScale(); minRate = ratingScale.get(0); maxRate = ratingScale.get(ratingScale.size() - 1); numLevels = ratingScale.size(); numUsers = rateDao.numUsers(); numItems = rateDao.numItems(); // ratings' timestamps minTimestamp = rateDao.getMinTimestamp(); maxTimestamp = rateDao.getMaxTimestamp(); if (testTimeMatrix == null) testTimeMatrix = timeMatrix; initMean = 0.0; initStd = 0.1; cacheSpec = cf.getString("guava.cache.spec", "maximumSize=200,expireAfterAccess=2m"); rankOptions = cf.getParamOptions("item.ranking"); isRankingPred = rankOptions.isMainOn(); isDiverseUsed = rankOptions.contains("-diverse"); numRecs = rankOptions.getInt("-topN", -1); numIgnore = rankOptions.getInt("-ignore", -1); LineConfiger evalOptions = cf.getParamOptions("evaluation.setup"); view = evalOptions.getString("--test-view", "all"); validationRatio = evalOptions.getFloat("-v", 0.0f); isSplitByDate = evalOptions.contains("--by-date"); earlyStopMeasure = evalOptions.getString("--early-stop"); int numProcessors = Runtime.getRuntime().availableProcessors(); numCPUs = evalOptions.getInt("-cpu", numProcessors); // output options LineConfiger outputOptions = cf.getParamOptions("output.setup"); if (outputOptions != null) { verbose = outputOptions.isOn("-verbose", true); isSaveModel = outputOptions.contains("--save-model"); } knn = cf.getInt("num.neighbors", 20); similarityMeasure = cf.getString("similarity", "PCC"); similarityShrinkage = cf.getInt("num.shrinkage", 30); } // 2016/8/2 RB Added metric configuration // These are class names LineConfiger metricOptions = cf.getParamOptions("metric.options"); List<String> metrics; boolean defaultMetrics = false; if ((metricOptions == null) || metricOptions.contains("--rating")) { metrics = Arrays.asList(MetricCollection.RatingMetrics); defaultMetrics = true; } else if (metricOptions.contains("--all")) { metrics = Arrays.asList(MetricCollection.AllMetrics); defaultMetrics = true; } else { metrics = metricOptions.getOptions("-metrics"); } //List<String> metricNames = new ArrayList<String>(); metricNames = new ArrayList<String>(); for (String name : metrics) { // If it does not have a . separator for the class name, we assume it is one of the // built-in classes and append the librec class info. if (!name.contains(".")) { name = "librec.metric." + name; } metricNames.add(name); } // These are always included if (!defaultMetrics) { metricNames.add("librec.metric.TrainTime"); metricNames.add("librec.metric.TestTime"); } try { measures = new MetricCollection(metricNames); mesvalid = new MetricCollection(metricNames); } catch (Exception e) { Logs.debug("Failed to initialize metrics: " + e); System.exit(-1); } // training, validation, test data if (validationRatio > 0 && validationRatio < 1) { DataSplitter ds = new DataSplitter(trainMatrix); double ratio = 1 - validationRatio; SparseMatrix[] trainSubsets = isSplitByDate ? ds.getRatioByRatingDate(ratio, timeMatrix) : ds .getRatioByRating(ratio); this.trainMatrix = trainSubsets[0]; this.validationMatrix = trainSubsets[1]; } else { this.trainMatrix = trainMatrix; } this.testMatrix = testMatrix; // fold info this.fold = fold; foldInfo = fold > 0 ? " fold [" + fold + "]" : ""; // whether to write out results LineConfiger outputOptions = cf.getParamOptions("output.setup"); if (outputOptions != null) { isResultsOut = outputOptions.isMainOn(); } // global mean numRates = trainMatrix.size(); globalMean = trainMatrix.sum() / numRates; // class name as the default algorithm name setAlgoName(this.getClass().getSimpleName()); // compute item-item correlations if (measures.hasRankingMetrics() && measures.hasDiversityMetrics()) { corrs = new SymmMatrix(numItems); } } /** * Constructor for Recommender * * @param trainMatrix * train matrix * @param testMatrix * test matrix * @throws IOException */ public Recommender(SparseMatrix trainMatrix, SparseMatrix testMatrix, SparseMatrix validationMatrix, int fold){ //mine minmet.mae = Double.MAX_VALUE ; minmet.rmse = Double.MAX_VALUE ; data_path = cf.getPath("dataset.ratings"); // config recommender if (cf == null || rateMatrix == null) { Logs.error("Recommender is not well configed"); System.exit(-1); } // static initialization (reset), only done once if (resetStatics) { // change the indicator resetStatics = false; ratingScale = rateDao.getRatingScale(); minRate = ratingScale.get(0); maxRate = ratingScale.get(ratingScale.size() - 1); numLevels = ratingScale.size(); numUsers = rateDao.numUsers(); numItems = rateDao.numItems(); // ratings' timestamps minTimestamp = rateDao.getMinTimestamp(); maxTimestamp = rateDao.getMaxTimestamp(); if (testTimeMatrix == null) testTimeMatrix = timeMatrix; initMean = 0.0; initStd = 0.1; cacheSpec = cf.getString("guava.cache.spec", "maximumSize=200,expireAfterAccess=2m"); rankOptions = cf.getParamOptions("item.ranking"); isRankingPred = rankOptions.isMainOn(); isDiverseUsed = rankOptions.contains("-diverse"); numRecs = rankOptions.getInt("-topN", -1); numIgnore = rankOptions.getInt("-ignore", -1); LineConfiger evalOptions = cf.getParamOptions("evaluation.setup"); view = evalOptions.getString("--test-view", "all"); validationRatio = evalOptions.getFloat("-v", 0.0f); isSplitByDate = evalOptions.contains("--by-date"); earlyStopMeasure = evalOptions.getString("--early-stop"); int numProcessors = Runtime.getRuntime().availableProcessors(); numCPUs = evalOptions.getInt("-cpu", numProcessors); // output options LineConfiger outputOptions = cf.getParamOptions("output.setup"); if (outputOptions != null) { verbose = outputOptions.isOn("-verbose", true); isSaveModel = outputOptions.contains("--save-model"); } knn = cf.getInt("num.neighbors", 20); similarityMeasure = cf.getString("similarity", "PCC"); similarityShrinkage = cf.getInt("num.shrinkage", 30); resFile = cf.getString("res.file", "./resFile.txt"); System.out.println(resFile); //mine System.out.println(resFile); try { bw = new BufferedWriter(new FileWriter(resFile,true)); } catch(IOException ioe) { System.out.println(" IOE " + ioe); } } // 2016/8/2 RB Added metric configuration // These are class names LineConfiger metricOptions = cf.getParamOptions("metric.options"); List<String> metrics; boolean defaultMetrics = false; if ((metricOptions == null) || metricOptions.contains("--rating")) { metrics = Arrays.asList(MetricCollection.RatingMetrics); defaultMetrics = true; } else if (metricOptions.contains("--all")) { metrics = Arrays.asList(MetricCollection.AllMetrics); defaultMetrics = true; } else { metrics = metricOptions.getOptions("-metrics"); } //List<String> metricNames = new ArrayList<String>(); metricNames = new ArrayList<String>(); for (String name : metrics) { // If it does not have a . separator for the class name, we assume it is one of the // built-in classes and append the librec class info. if (!name.contains(".")) { name = "librec.metric." + name; } metricNames.add(name); } // These are always included if (!defaultMetrics) { metricNames.add("librec.metric.TrainTime"); metricNames.add("librec.metric.TestTime"); } try { measures = new MetricCollection(metricNames); mesvalid = new MetricCollection(metricNames); } catch (Exception e) { Logs.debug("Failed to initialize metrics: " + e); System.exit(-1); } // training, validation, test data if (validationRatio > 0 && validationRatio < 1) { DataSplitter ds = new DataSplitter(trainMatrix); double ratio = 1 - validationRatio; SparseMatrix[] trainSubsets = isSplitByDate ? ds.getRatioByRatingDate(ratio, timeMatrix) : ds .getRatioByRating(ratio); this.trainMatrix = trainSubsets[0]; this.validationMatrix = trainSubsets[1]; } else { this.validationMatrix = validationMatrix; this.trainMatrix = trainMatrix; } this.testMatrix = testMatrix; this.validationMatrix = validationMatrix; // fold info this.fold = fold; foldInfo = fold > 0 ? " fold [" + fold + "]" : ""; // whether to write out results LineConfiger outputOptions = cf.getParamOptions("output.setup"); if (outputOptions != null) { isResultsOut = outputOptions.isMainOn(); } // global mean numRates = trainMatrix.size(); globalMean = trainMatrix.sum() / numRates; // class name as the default algorithm name setAlgoName(this.getClass().getSimpleName()); // compute item-item correlations if (measures.hasRankingMetrics() && measures.hasDiversityMetrics()) { corrs = new SymmMatrix(numItems); } } public void run() { try { execute(); } catch (Exception e) { // capture error message Logs.error(e.getMessage()); e.printStackTrace(); } } /** * execution method of a recommender * */ public void execute() throws Exception { Stopwatch sw = Stopwatch.createStarted(); if (Debug.ON) { // learn a recommender model initModel(); // show algorithm's configuration printAlgoConfig(); // build the model buildModel(); // post-processing after building a model, e.g., release intermediate memory to avoid memory leak postModel(); } else { /** * load a learned model: this code will not be executed unless "Debug.OFF" mainly for the purpose of * exemplifying how to use the saved models */ loadModel(); } long trainTime = sw.elapsed(TimeUnit.MILLISECONDS); // validation if (validationRatio > 0 && validationRatio < 1) { validateModel(); trainTime = sw.elapsed(TimeUnit.MILLISECONDS); } measures.init(this); // evaluation if (verbose) Logs.debug("{}{} evaluate test data ... ", algoName, foldInfo); // TODO: to predict ratings only, or do item recommendations only if (measures.hasRankingMetrics() && (measures.hasRatingMetrics())) { evalRankings(); evalRatings(); } else if (measures.hasRatingMetrics()) { //MINE evalRatingsValid(); //mine evalRatings(); } else if (measures.hasRankingMetrics()) { evalRankings(); } else { Logs.debug("No metrics found."); } String measurements = measures.getEvalResultString(); sw.stop(); long testTime = sw.elapsed(TimeUnit.MILLISECONDS) - trainTime; // collecting results ITimeMetric trainTimeMetric = measures.getTimeMetric("TrainTime"); ITimeMetric testTimeMetric = measures.getTimeMetric("TestTime"); trainTimeMetric.setTime(trainTime); testTimeMetric.setTime(testTime); // added metric names String evalInfo = "Metrics: " + measures.getMetricNamesString() + "\n"; evalInfo += algoName + foldInfo + ": " + measurements + "\tTime: " + trainTimeMetric.getValueAsString() + ", " + testTimeMetric.getValueAsString(); if (!isRankingPred) evalInfo += "\tView: " + view; if (fold > 0) Logs.debug(evalInfo); if (isSaveModel) saveModel(); } private void printAlgoConfig() { String algoInfo = toString(); Class<? extends Recommender> cl = this.getClass(); // basic annotation String algoConfig = cl.getAnnotation(Configuration.class).value(); // additional algorithm-specific configuration if (cl.isAnnotationPresent(AddConfiguration.class)) { AddConfiguration add = cl.getAnnotation(AddConfiguration.class); String before = add.before(); if (!Strings.isNullOrEmpty(before)) algoConfig = before + ", " + algoConfig; String after = add.after(); if (!Strings.isNullOrEmpty(after)) algoConfig += ", " + after; } if (!algoInfo.isEmpty()) { if (!algoConfig.isEmpty()) Logs.debug("{}: [{}] = [{}]", algoName, algoConfig, algoInfo); else Logs.debug("{}: {}", algoName, algoInfo); } } /** * validate model with held-out validation data */ protected void validateModel() { } /** * initilize recommender model */ protected void initModel() throws Exception { } protected LineConfiger getModelParams(String algoName) { return cf.contains(algoName) ? cf.getParamOptions(algoName) : null; } /** * build user-user or item-item correlation matrix from training data * * @param isUser * whether it is user-user correlation matrix * * @return a upper symmetric matrix with user-user or item-item coefficients * */ protected SymmMatrix buildCorrs(boolean isUser) { Logs.debug("Build {} similarity matrix ...", isUser ? "user" : "item"); int count = isUser ? numUsers : numItems; SymmMatrix corrs = new SymmMatrix(count); for (int i = 0; i < count; i++) { SparseVector iv = isUser ? trainMatrix.row(i) : trainMatrix.column(i); if (iv.getCount() == 0) continue; // user/item itself exclusive for (int j = i + 1; j < count; j++) { SparseVector jv = isUser ? trainMatrix.row(j) : trainMatrix.column(j); double sim = correlation(iv, jv); if (!Double.isNaN(sim)) corrs.set(i, j, sim); } } return corrs; } /** * Compute the correlation between two vectors using method specified by configuration key "similarity" * * @param iv * vector i * @param jv * vector j * @return the correlation between vectors i and j */ protected double correlation(SparseVector iv, SparseVector jv) { return correlation(iv, jv, similarityMeasure); } /** * Compute the correlation between two vectors for a specific method * * @param iv * vector i * @param jv * vector j * @param method * similarity method * @return the correlation between vectors i and j; return NaN if the correlation is not computable. */ protected double correlation(SparseVector iv, SparseVector jv, String method) { // compute similarity List<Double> is = new ArrayList<>(); List<Double> js = new ArrayList<>(); for (Integer idx : jv.getIndex()) { if (iv.contains(idx)) { is.add(iv.get(idx)); js.add(jv.get(idx)); } } double sim = 0; switch (method.toLowerCase()) { case "cos": // for ratings along the overlappings sim = Sims.cos(is, js); break; case "cos-binary": // for ratings along all the vectors (including one-sided 0s) sim = iv.inner(jv) / (Math.sqrt(iv.inner(iv)) * Math.sqrt(jv.inner(jv))); break; case "msd": sim = Sims.msd(is, js); break; case "cpc": sim = Sims.cpc(is, js, (minRate + maxRate) / 2.0); break; case "exjaccard": sim = Sims.exJaccard(is, js); break; case "pcc": default: sim = Sims.pcc(is, js); break; } // shrink to account for vector size if (!Double.isNaN(sim)) { int n = is.size(); int shrinkage = cf.getInt("num.shrinkage"); if (shrinkage > 0) sim *= n / (n + shrinkage + 0.0); } return sim; } /** * Learning method: override this method to build a model, for a model-based method. Default implementation is * useful for memory-based methods. * */ protected void buildModel() throws Exception { } /** * After learning model: release some intermediate data to avoid memory leak */ protected void postModel() throws Exception { } /** * Serializing a learned model (i.e., variable data) to files. */ protected void saveModel() throws Exception { } /** * Deserializing a learned model (i.e., variable data) from files. */ protected void loadModel() throws Exception { } /** * determine whether the rating of a user-item (u, j) is used to predicted * */ protected boolean isTestable(int u, int j) { switch (view) { case "cold-start": return trainMatrix.rowSize(u) < 5 ? true : false; case "cold-user": return trainMatrix.rowSize(u) < 5 ? true : false; case "cold-item": return trainMatrix.columnSize(j) < 5 ? true : false; case "all": default: return true; } } /** * @return the evaluation results of rating predictions */ protected void evalRatings() throws Exception { //System.out.println("\nInside Eval Rating Test"); List<String> preds = null; String toFile = null; if (isResultsOut) { preds = new ArrayList<String>(1500); preds.add("# userId itemId rating prediction"); // optional: file header toFile = tempDirPath + algoName + "-rating-predictions" + foldInfo + ".txt"; // the output-file name FileIO.deleteFile(toFile); // delete possibly old files } int numCount = 0; for (MatrixEntry me : testMatrix) { double rate = me.get(); int u = me.row(); int j = me.column(); if (!isTestable(u, j)) continue; double pred = predict(u, j, true); // 2016/8/2 RB Should the metrics handle this? if (Double.isNaN(pred)) continue; measures.updateRatingMetrics(u, j, pred, rate, this); numCount++; // output predictions if (isResultsOut) { // restore back to the original user/item id preds.add(rateDao.getUserId(u) + " " + rateDao.getItemId(j) + " " + rate + " " + (float) pred); if (preds.size() >= 1000) { FileIO.writeList(toFile, preds, true); preds.clear(); } } } if (isResultsOut && preds.size() > 0) { FileIO.writeList(toFile, preds, true); Logs.debug("{}{} has written rating predictions to {}", algoName, foldInfo, toFile); } measures.computeRatingMetrics(numCount); } /** * MINE * @return the evaluation results of rating predictions */ protected void evalRatingsValid() throws Exception { //System.out.println("\nInside Eval Rating Valid"); List<String> preds = null; String toFile = null; if (isResultsOut) { preds = new ArrayList<String>(1500); preds.add("# userId itemId rating prediction"); // optional: file header toFile = tempDirPath + algoName + "-rating-predictions" + foldInfo + ".txt"; // the output-file name FileIO.deleteFile(toFile); // delete possibly old files } int numCount = 0; for (MatrixEntry me : validationMatrix) { double rate = me.get(); int u = me.row(); int j = me.column(); if (!isTestable(u, j)) continue; double pred = predict(u, j, true); // 2016/8/2 RB Should the metrics handle this? if (Double.isNaN(pred)) continue; mesvalid.updateRatingMetrics(u, j, pred, rate, this); numCount++; // output predictions if (isResultsOut) { // restore back to the original user/item id preds.add(rateDao.getUserId(u) + " " + rateDao.getItemId(j) + " " + rate + " " + (float) pred); if (preds.size() >= 1000) { FileIO.writeList(toFile, preds, true); preds.clear(); } } } if (isResultsOut && preds.size() > 0) { FileIO.writeList(toFile, preds, true); Logs.debug("{}{} has written rating predictions to {}", algoName, foldInfo, toFile); } mesvalid.computeRatingMetrics(numCount); } /** * MINE2 * @return the evaluation results of rating predictions */ protected MetricMine evalRatMetrics(BufferedWriter bw , String paramstr, MetricMine met ,boolean flag) throws Exception { double minrmse = met.rmse; double minmae = met.mae; try { //measures = new MetricCollection(metricNames); mesvalidtemp = new MetricCollection(metricNames); } catch (Exception e) { Logs.debug("Failed to initialize metrics: " + e); System.exit(-1); } int numCount = 0; for (MatrixEntry me : validationMatrix) { double rate = me.get(); int u = me.row(); int j = me.column(); if (!isTestable(u, j)) continue; double pred = predict(u, j, true); // 2016/8/2 RB Should the metrics handle this? if (Double.isNaN(pred)) continue; mesvalidtemp.updateRatingMetrics(u, j, pred, rate, this); numCount++; } mesvalidtemp.computeRatingMetrics(numCount); try { //measures = new MetricCollection(metricNames); mestesttemp = new MetricCollection(metricNames); } catch (Exception e) { Logs.debug("Failed to initialize metrics: " + e); System.exit(-1); } // test matrix numCount = 0; for (MatrixEntry me : testMatrix) { double rate = me.get(); int u = me.row(); int j = me.column(); if (!isTestable(u, j)) continue; double pred = predict(u, j, true); // 2016/8/2 RB Should the metrics handle this? if (Double.isNaN(pred)) continue; mestesttemp.updateRatingMetrics(u, j, pred, rate, this); numCount++; } mestesttemp.computeRatingMetrics(numCount); double newmae = mesvalidtemp.getRatingMetric("MAE").getValue(); double newrmse = mesvalidtemp.getRatingMetric("RMSE").getValue(); if (newmae < minmae) { minmae = newmae; testmae = mestesttemp.getRatingMetric("MAE").getValue(); } if (newrmse < minrmse) { minrmse = newrmse; testrmse = mestesttemp.getRatingMetric("RMSE").getValue(); } if (flag) { bw.write("\n"+algoName + " " +paramstr +" MIN :: valmae:" + String.format("%.4f", minmae) + " testmae:"+ String.format("%.4f", testmae)+ " valrmse:" + String.format("%.4f", minrmse)+ " testrmse:"+ String.format("%.4f", testrmse)); bw.write(" FINAL :: valmae:" + String.format("%.4f", mesvalidtemp.getRatingMetric("MAE").getValue())+" testmae:"+ String.format("%.4f", mestesttemp.getRatingMetric("MAE").getValue())+ " valrmse:" + String.format("%.4f", mesvalidtemp.getRatingMetric("RMSE").getValue())+ " testrmse:"+ String.format("%.4f", mestesttemp.getRatingMetric("RMSE").getValue())); bw.close(); } System.out.print(" val : MAE " + String.format("%.4f", mesvalidtemp.getRatingMetric("MAE").getValue()) + "\t RMSE " + String.format("%.4f", mesvalidtemp.getRatingMetric("RMSE").getValue()) + "\t"); System.out.print(" test : MAE " + String.format("%.4f", mestesttemp.getRatingMetric("MAE").getValue()) + "\t RMSE " + String.format("%.4f", mestesttemp.getRatingMetric("RMSE").getValue()) + "\t"); met.mae = minmae; met.rmse = minrmse; return met; } /** * @return the evaluation results of ranking predictions */ protected void evalRankings() throws Exception { int capacity = Lists.initSize(testMatrix.numRows()); // candidate items for all users: here only training items // use HashSet instead of ArrayList to speedup removeAll() and contains() operations: HashSet: O(1); ArrayList: O(log n). Set<Integer> candItems = new HashSet<>(trainMatrix.columns()); List<String> preds = null; String toFile = null; int numTopNRanks = numRecs < 0 ? 10 : numRecs; if (isResultsOut) { preds = new ArrayList<String>(1500); preds.add("# userId: recommendations in (itemId, ranking score) pairs, where a correct recommendation is denoted by symbol *."); // optional: file header toFile = tempDirPath + String.format("%s-top-%d-items%s.txt", new Object[] { algoName, numTopNRanks, foldInfo }); // the output-file name FileIO.deleteFile(toFile); // delete possibly old files } if (verbose) Logs.debug("{}{} has candidate items: {}", algoName, foldInfo, candItems.size()); // ignore items for all users: most popular items if (numIgnore > 0) { List<Map.Entry<Integer, Integer>> itemDegs = new ArrayList<>(); for (Integer j : candItems) { itemDegs.add(new SimpleImmutableEntry<Integer, Integer>(j, trainMatrix.columnSize(j))); } Lists.sortList(itemDegs, true); int k = 0; for (Map.Entry<Integer, Integer> deg : itemDegs) { // ignore these items from candidate items candItems.remove(deg.getKey()); if (++k >= numIgnore) break; } } // for each test user int numCount = 0; for (int u = 0, um = testMatrix.numRows(); u < um; u++) { if (verbose && ((u + 1) % 100 == 0)) Logs.debug("{}{} evaluates progress: {} / {}", algoName, foldInfo, u + 1, um); // number of candidate items for all users int numCands = candItems.size(); // get positive items from test matrix List<Integer> testItems = testMatrix.getColumns(u); List<Integer> correctItems = new ArrayList<>(); // intersect with the candidate items for (Integer j : testItems) { if (candItems.contains(j)) correctItems.add(j); } if (correctItems.size() == 0) continue; // no testing data for user u // remove rated items from candidate items List<Integer> ratedItems = trainMatrix.getColumns(u); // predict the ranking scores (unordered) of all candidate items List<Map.Entry<Integer, Double>> itemScores = new ArrayList<>(Lists.initSize(candItems)); for (final Integer j : candItems) { // item j is not rated if (!ratedItems.contains(j)) { final double rank = ranking(u, j); if (!Double.isNaN(rank)) { itemScores.add(new SimpleImmutableEntry<Integer, Double>(j, rank)); } } else { numCands--; } } if (itemScores.size() == 0) continue; // no recommendations available for user u // order the ranking scores from highest to lowest: List to preserve orders Lists.sortList(itemScores, true); List<Map.Entry<Integer, Double>> recomd = (numRecs <= 0 || itemScores.size() <= numRecs) ? itemScores : itemScores.subList(0, numRecs); List<Integer> rankedItems = new ArrayList<>(); StringBuilder sb = new StringBuilder(); int count = 0; for (Map.Entry<Integer, Double> kv : recomd) { Integer item = kv.getKey(); rankedItems.add(item); if (isResultsOut && count < numTopNRanks) { // restore back to the original item id sb.append("(").append(rateDao.getItemId(item)); if (testItems.contains(item)) sb.append("*"); // indicating correct recommendation sb.append(", ").append(kv.getValue().floatValue()).append(")"); count++; if (count < numTopNRanks) sb.append(", "); } } numCount++; int numDropped = numCands - rankedItems.size(); measures.updateRankingMetrics(rankedItems, correctItems, numDropped, this); // output predictions if (isResultsOut) { // restore back to the original user id preds.add(rateDao.getUserId(u) + ": " + sb.toString()); if (preds.size() >= 1000) { FileIO.writeList(toFile, preds, true); preds.clear(); } } } // write results out first if (isResultsOut && preds.size() > 0) { FileIO.writeList(toFile, preds, true); Logs.debug("{}{} has written item recommendations to {}", algoName, foldInfo, toFile); } // measure the performance measures.computeRankingMetrics(numCount); } /** * predict a specific rating for user u on item j. It is useful for evalution which requires predictions are * bounded. * * @param u * user id * @param j * item id * @param bound * whether to bound the prediction * @return prediction */ public double predict(int u, int j, boolean bound) throws Exception { double pred = predict(u, j); if (bound) { if (pred > maxRate) pred = maxRate; if (pred < minRate) pred = minRate; } return pred; } /** * predict a specific rating for user u on item j, note that the prediction is not bounded. It is useful for * building models with no need to bound predictions. * * @param u * user id * @param j * item id * @return raw prediction without bounded */ public double predict(int u, int j) throws Exception { return globalMean; } public double perplexity(int u, int j, double r) throws Exception { return 0; } /** * predict a ranking score for user u on item j: default case using the unbounded predicted rating values * * @param u * user id * * @param j * item id * @return a ranking score for user u on item j */ public double ranking(int u, int j) throws Exception { return predict(u, j, false); } /** * * @param rankedItems * the list of ranked items to be recommended * @param cutoff * cutoff in the list * @param corrs * correlations between items * @return diversity at a specific cutoff position */ public double diverseAt(List<Integer> rankedItems, int cutoff) { int num = 0; double sum = 0.0; for (int id = 0; id < cutoff; id++) { int i = rankedItems.get(id); SparseVector iv = trainMatrix.column(i); for (int jd = id + 1; jd < cutoff; jd++) { int j = rankedItems.get(jd); double corr = corrs.get(i, j); if (corr == 0) { // if not found corr = correlation(iv, trainMatrix.column(j)); if (!Double.isNaN(corr)) corrs.set(i, j, corr); } if (!Double.isNaN(corr)) { sum += (1 - corr); num++; } } } return 0.5 * (sum / num); } /** * Below are a set of mathematical functions. As many recommenders often adopts them, for conveniency's sake, we put * these functions in the base Recommender class, though they belong to Math class. * */ /** * logistic function g(x) */ protected double g(double x) { return 1.0 / (1 + Math.exp(-x)); } /** * gradient value of logistic function g(x) */ protected double gd(double x) { return g(x) * g(-x); } /** * @param x * input value * @param mu * mean of normal distribution * @param sigma * standard deviation of normation distribution * * @return a gaussian value with mean {@code mu} and standard deviation {@code sigma}; */ protected double gaussian(double x, double mu, double sigma) { return Math.exp(-0.5 * Math.pow(x - mu, 2) / (sigma * sigma)); } /** * normalize a rating to the region (0, 1) */ protected double normalize(double rate) { return (rate - minRate + 1) / (maxRate - minRate + 1); // MINE added 1 to avoid getting 0 as rating for minRate } /** * Check if ratings have been binarized; useful for methods that require binarized ratings; */ protected void checkBinary() { if (binThold < 0) { Logs.error("val.binary.threshold={}, ratings must be binarized first! Try set a non-negative value.", binThold); System.exit(-1); } } /** * * denormalize a prediction to the region (minRate, maxRate) */ protected double denormalize(double pred) { return minRate -1 + pred * (maxRate - minRate + 1); // MINE changes made to tackle 0 rating value } /** * useful to print out specific recommender's settings */ @Override public String toString() { return ""; } /** * Set a user-specific name of an algorithm * */ protected void setAlgoName(String algoName) { this.algoName = algoName; // get parameters of an algorithm algoOptions = getModelParams(algoName); } }
[ "vijaikumarmylsamy@gmail.com" ]
vijaikumarmylsamy@gmail.com
9958c974d4277568bcc81347335cc42f22be68fe
30eab9ec2113abea2c8143a74779d34abc184357
/app/src/main/java/com/qwert2603/autoselfie/AutoSelfieApplication.java
13e4fcd69626f22eaf14794fae854147da3eae1c
[]
no_license
qwert2603/AutoSelfie
9f72fb7333aa445b7eea402a71d1a85001137b04
abf95d54a3df2bf9cd0d4b228a6eeb5a8bb10c3e
refs/heads/master
2021-01-11T02:40:24.933734
2016-10-17T09:22:44
2016-10-17T09:22:44
70,909,413
0
0
null
null
null
null
UTF-8
Java
false
false
820
java
package com.qwert2603.autoselfie; import android.app.Application; import android.support.v7.app.AppCompatDelegate; import com.qwert2603.autoselfie.utils.InternalStorageViewer; import com.vk.sdk.VKSdk; public class AutoSelfieApplication extends Application { @Override public void onCreate() { super.onCreate(); VKSdk.initialize(AutoSelfieApplication.this); InternalStorageViewer.print(AutoSelfieApplication.this); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // String[] certificateFingerprint = VKUtil.getCertificateFingerprint(AutoSelfieApplication.this, getPackageName()); // if (certificateFingerprint != null) { // for (String s : certificateFingerprint) { // LogUtils.d(s); // } // } } }
[ "qwert2603@mail.ru" ]
qwert2603@mail.ru
8bb928585bf3e0e46b01593957b6f9a14314f169
61e13884681f351814eb1646c18d502cdf1435b6
/hops-transaction/src/main/java/com/yuecheng/hops/rebate/entity/assist/RebateRecordAssist.java
9bcfdea64a49eccc70481a155296ee62287f64cc
[]
no_license
jy02718805/HOPS
d8b2b89db79b2c9d4e4560571c6ad29ffc25049c
e7e834221ea4aec1620ce9716dae2eac4e875430
refs/heads/master
2021-01-10T09:35:27.930434
2016-01-20T08:18:07
2016-01-20T08:18:07
49,999,762
0
0
null
null
null
null
UTF-8
Java
false
false
3,265
java
/* * 文件名:RebateRecordAssist.java * 版权:Copyright by www.365haoyou.com * 描述:返佣元数据辅助类 * 修改人:Jinger * 修改时间:2014年10月23日 * 跟踪单号: * 修改单号: * 修改内容: */ package com.yuecheng.hops.rebate.entity.assist; import java.io.Serializable; import java.util.Date; import java.util.List; import com.yuecheng.hops.rebate.entity.RebateRecord; /** * 返佣元数据辅助类 * 〈一句话功能简述〉 * 〈功能详细描述〉 * @author Jinger * @version 2014年10月23日 * @see RebateRuleAssist * @since */ public class RebateRecordAssist implements Serializable { /** * 意义,目的和功能,以及被用到的地方<br> */ private static final long serialVersionUID = 4543360605369550096L; private RebateRecord rebateRecord; private List<RebateProductAssist> rebateProducts; //返佣产品列表 private String productNames; //产品名称简写 private String productNamesAlt; //产品全名称 private Date beginTime; //清算开始时间 private Date endTime; //清算结束时间 private String merchantName; //发生商户名称 private String rebateMerchantName; //返佣商户名称 public RebateRecord getRebateRecord() { return rebateRecord; } public void setRebateRecord(RebateRecord rebateRecord) { this.rebateRecord = rebateRecord; } public List<RebateProductAssist> getRebateProducts() { return rebateProducts; } public void setRebateProducts(List<RebateProductAssist> rebateProducts) { this.rebateProducts = rebateProducts; } public String getProductNames() { return productNames; } public void setProductNames(String productNames) { this.productNames = productNames; } public String getProductNamesAlt() { return productNamesAlt; } public void setProductNamesAlt(String productNamesAlt) { this.productNamesAlt = productNamesAlt; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getMerchantName() { return merchantName; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public String getRebateMerchantName() { return rebateMerchantName; } public void setRebateMerchantName(String rebateMerchantName) { this.rebateMerchantName = rebateMerchantName; } @Override public String toString() { return "RebateRecordAssist [rebateRecord=" + rebateRecord + ", rebateProducts=" + rebateProducts + ", productNames=" + productNames + ", productNamesAlt=" + productNamesAlt + ", beginTime=" + beginTime + ", endTime=" + endTime + ", merchantName=" + merchantName + ", rebateMerchantName=" + rebateMerchantName + "]"; } }
[ "jy02718858@163.com" ]
jy02718858@163.com
473d48ac8f98aa7dfc8d7118c137bbd976f94715
aee55521c12241d953007176f403aca2e842c056
/src/org/omg/PortableServer/ServantRetentionPolicyValue.java
a263e1fb21bc3de946e7a05214796d0740d9ab95
[]
no_license
XiaZhouxx/jdk1.8
572988fe007bbdd5aa528945a63005c3cb152ffe
5703d895b91571d41ccdab138aefb9b8774f9401
refs/heads/master
2023-08-30T18:53:23.919988
2021-11-01T07:40:49
2021-11-01T07:40:49
420,957,590
0
0
null
null
null
null
UTF-8
Java
false
false
1,766
java
package org.omg.PortableServer; /** * org/omg/PortableServer/ServantRetentionPolicyValue.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/jenkins/workspace/8-2-build-windows-amd64-cygwin/jdk8u301/1513/corba/src/share/classes/org/omg/PortableServer/poa.idl * Wednesday, June 9, 2021 6:48:04 AM PDT */ /** * ServantRetentionPolicyValue can have the following * values. RETAIN - to indicate that the POA will retain * active servants in its Active Object Map. * NON_RETAIN - to indicate Servants are not retained by * the POA. If no ServantRetentionPolicy is specified at * POA creation, the default is RETAIN. */ public class ServantRetentionPolicyValue implements org.omg.CORBA.portable.IDLEntity { private int __value; private static int __size = 2; private static org.omg.PortableServer.ServantRetentionPolicyValue[] __array = new org.omg.PortableServer.ServantRetentionPolicyValue [__size]; public static final int _RETAIN = 0; public static final org.omg.PortableServer.ServantRetentionPolicyValue RETAIN = new org.omg.PortableServer.ServantRetentionPolicyValue(_RETAIN); public static final int _NON_RETAIN = 1; public static final org.omg.PortableServer.ServantRetentionPolicyValue NON_RETAIN = new org.omg.PortableServer.ServantRetentionPolicyValue(_NON_RETAIN); public int value () { return __value; } public static org.omg.PortableServer.ServantRetentionPolicyValue from_int (int value) { if (value >= 0 && value < __size) return __array[value]; else throw new org.omg.CORBA.BAD_PARAM (); } protected ServantRetentionPolicyValue (int value) { __value = value; __array[__value] = this; } } // class ServantRetentionPolicyValue
[ "xiazhou@dgg.net" ]
xiazhou@dgg.net
41fc4fd473e8069c8aeb6c84023453db4e356884
7ce6fae195a37b1bc89aced9e302d051216323cd
/ejb/src/main/java/br/com/dextra/treinamento/model/service/sessionbean/TesteStatefulImpl.java
d6a3f26fac26d6b4df06e372d49e9900a45b4ed3
[]
no_license
felipeYanagiya/ejb
c089d42df554dcb8466bffd7108392ff584c75af
e588d72db1233a0ec54d467146fe5140f3fdf9cf
refs/heads/master
2021-01-01T06:05:12.721553
2014-05-13T23:29:15
2014-05-13T23:29:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package br.com.dextra.treinamento.model.service.sessionbean; import javax.ejb.Local; import javax.ejb.Stateful; @Stateful(name="TesteStatefulImpl") @Local public class TesteStatefulImpl implements TesteStatefulLocal { private Integer contador = 0; @Override public Integer adicionar(){ contador++; return contador; } }
[ "felipe.yanagiya@gmail.com" ]
felipe.yanagiya@gmail.com
2b0d9670e7274725610ce5ea7d5c1760a548c666
447f95a49521c9be22a9012f8065923131205961
/src/main/java/pos/fa7/cursoweb/model/Cep.java
d06da86ebcec0b6c700cf576ae75755b87c17654
[]
no_license
esdrasbb/final-work-jsf
70464c2ea9e924cb5ea4ddd2bac75fa44b19c5c4
540d1df4060e8e489e16ec542c28c741b0036c5f
refs/heads/master
2020-12-03T13:29:48.086235
2016-09-02T00:42:24
2016-09-02T00:42:24
66,790,503
0
0
null
null
null
null
UTF-8
Java
false
false
501
java
package pos.fa7.cursoweb.model; public class Cep { private String regiao; private String sufixo; public Cep(String regiao, String sufixo) { super(); this.regiao = regiao; this.sufixo = sufixo; } public String getRegiao() { return regiao; } public void setRegiao(String regiao) { this.regiao = regiao; } public String getSufixo() { return sufixo; } public void setSufixo(String sufixo) { this.sufixo = sufixo; } public String show() { return regiao + sufixo; } }
[ "esdras.barreto@gmail.com" ]
esdras.barreto@gmail.com
a305edf091c378156ce3e085cee8d4b50be63aec
ac3aba0c258436dd3c521558bca394228b4cc919
/Tec/5to semestre/VizorFlores/src/org/seblab/beans/Flower.java
49e7926237a89b14c28a139950380ad4fa77826c
[]
no_license
Guirdo/hello-world
db70d746f865d171e092a6284ef552e5467f861b
7eb36d6d952cb0fefc5741fd4c534c8f7677aee3
refs/heads/master
2021-07-10T20:10:04.131990
2020-06-25T00:44:55
2020-06-25T00:44:55
65,760,229
0
0
null
2016-08-15T19:58:57
2016-08-15T19:49:05
null
UTF-8
Java
false
false
52
java
package org.seblab.beans; public class Flower { }
[ "produccionesaldo@gmail.com" ]
produccionesaldo@gmail.com
0690dfa04b1bb14a165abde935cc79105230fa47
da59fb56dddd27b1ca4bd95ef7498fb811b1fe6e
/src/main/java/concurrency/Interrupting2.java
bffcccd3c99c88bf49fbc188401a1bbd5302427e
[]
no_license
kenshin579/books-thinking-in-java-4
7c36b8c2b4a4c589cc808ec4aa16ea5f49f49306
a6eaa45f69248008a74ddf07426b21e1c259e7f2
refs/heads/master
2020-04-11T12:38:28.671366
2018-12-15T07:21:46
2018-12-15T07:21:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,452
java
package concurrency; // Interrupting a task blocked with a ReentrantLock. import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static net.mindview.util.Print.print; class BlockedMutex { private Lock lock = new ReentrantLock(); public BlockedMutex() { // Acquire it right away, to demonstrate interruption // of a task blocked on a ReentrantLock: lock.lock(); } public void f() { try { // This will never be available to a second task lock.lockInterruptibly(); // Special call print("lock acquired in f()"); } catch (InterruptedException e) { print("Interrupted from lock acquisition in f()"); } } } class Blocked2 implements Runnable { BlockedMutex blocked = new BlockedMutex(); public void run() { print("Waiting for f() in BlockedMutex"); blocked.f(); print("Broken out of blocked call"); } } public class Interrupting2 { public static void main(String[] args) throws Exception { Thread t = new Thread(new Blocked2()); t.start(); TimeUnit.SECONDS.sleep(1); System.out.println("Issuing t.interrupt()"); t.interrupt(); } } /* Output: Waiting for f() in BlockedMutex Issuing t.interrupt() Interrupted from lock acquisition in f() Broken out of blocked call *///:~
[ "frankyoh@tmon.co.kr" ]
frankyoh@tmon.co.kr
ff56ff3be7f80f5dbb9aec122b1eb8a0a9e5c257
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/20/20_44c0f4e52f90a53f6eb751aee708727a5d7e6340/AdapterCompatibilityTests/20_44c0f4e52f90a53f6eb751aee708727a5d7e6340_AdapterCompatibilityTests_t.java
3108e1ec9b77c81c5d4f2479bbb997fdeca38fef
[]
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
25,098
java
/* * ==================== * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008-2009 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License("CDDL") (the "License"). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at * http://IdentityConnectors.dev.java.net/legal/license.txt * See the License for the specific language governing permissions and limitations * under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each file * and include the License file at identityconnectors/legal/license.txt. * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * ==================== */ package org.identityconnectors.ldap; import static java.util.Collections.singleton; import static org.identityconnectors.common.CollectionUtil.newList; import static org.identityconnectors.common.CollectionUtil.newSet; import static org.identityconnectors.ldap.LdapUtil.checkedListByFilter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.framework.api.ConnectorFacade; import org.identityconnectors.framework.common.exceptions.ConnectorException; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeBuilder; import org.identityconnectors.framework.common.objects.AttributeInfo; import org.identityconnectors.framework.common.objects.AttributeInfoUtil; import org.identityconnectors.framework.common.objects.AttributeUtil; import org.identityconnectors.framework.common.objects.ConnectorObject; import org.identityconnectors.framework.common.objects.Name; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.ObjectClassInfo; import org.identityconnectors.framework.common.objects.OperationOptionsBuilder; import org.identityconnectors.framework.common.objects.OperationalAttributeInfos; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.identityconnectors.framework.common.objects.Uid; import org.identityconnectors.test.common.TestHelpers; import org.junit.Test; public class AdapterCompatibilityTests extends LdapConnectorTestBase { // TODO test authenticate. @Override protected boolean restartServerAfterEachTest() { return true; } @Test public void testAccountOperationalAttributes() { ConnectorFacade facade = newFacade(); ObjectClassInfo oci = facade.schema().findObjectClassInfo(ObjectClass.ACCOUNT_NAME); AttributeInfo info = AttributeInfoUtil.find(OperationalAttributes.PASSWORD_NAME, oci.getAttributeInfo()); assertEquals(OperationalAttributeInfos.PASSWORD, info); } @Test public void testAccountAttributes() { ConnectorFacade facade = newFacade(); ConnectorObject user0 = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(USER_0_DN), "uid", "cn", "givenName", "sn"); assertEquals(USER_0_DN, user0.getName().getNameValue()); assertEquals(USER_0_UID, AttributeUtil.getAsStringValue(user0.getAttributeByName("uid"))); assertEquals(USER_0_CN, AttributeUtil.getAsStringValue(user0.getAttributeByName("cn"))); assertEquals(USER_0_GIVEN_NAME, AttributeUtil.getAsStringValue(user0.getAttributeByName("givenName"))); assertEquals(USER_0_SN, AttributeUtil.getAsStringValue(user0.getAttributeByName("sn"))); } @Test public void testGroupAttributes() { ConnectorFacade facade = newFacade(); ConnectorObject object = searchByAttribute(facade, ObjectClass.GROUP, new Name(UNIQUE_BUGS_AND_FRIENDS_DN), "cn", "uniqueMember"); assertEquals(UNIQUE_BUGS_AND_FRIENDS_CN, AttributeUtil.getAsStringValue(object.getAttributeByName("cn"))); Attribute uniqueMember = object.getAttributeByName("uniqueMember"); assertTrue(uniqueMember.getValue().contains(BUGS_BUNNY_DN)); } @Test public void testOrganizationAttributes() { ConnectorFacade facade = newFacade(); ConnectorObject object = searchByAttribute(facade, new ObjectClass("organization"), new Name(ACME_DN), "dn", "o", "objectClass"); assertEquals(ACME_DN, object.getName().getNameValue()); assertEquals(ACME_DN, AttributeUtil.getAsStringValue(object.getAttributeByName("dn"))); assertEquals(ACME_O, AttributeUtil.getAsStringValue(object.getAttributeByName("o"))); } @Test public void testInetOrgPersonAttributes() { // The LDAP edit group form does exactly this operation. LdapConfiguration config = newConfiguration(); config.setBaseContexts(ACME_DN); ConnectorFacade facade = newFacade(config); OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet("cn", "dn"); List<ConnectorObject> objects = TestHelpers.searchToList(facade, new ObjectClass("inetOrgPerson"), null, builder.build()); ConnectorObject object = findByAttribute(objects, "dn", BUGS_BUNNY_DN); assertEquals(BUGS_BUNNY_CN, AttributeUtil.getStringValue(object.getAttributeByName("cn"))); } @Test public void testRetriveLdapGroups() { ConnectorFacade facade = newFacade(); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.LDAP_GROUPS_NAME); assertAttributeValue(newList(UNIQUE_BUGS_AND_FRIENDS_DN, UNIQUE_EXTERNAL_PEERS_DN), object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME)); LdapConfiguration config = newConfiguration(); config.setGroupMemberAttribute("member"); facade = newFacade(config); object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.LDAP_GROUPS_NAME); assertAttributeValue(newList(BUGS_AND_FRIENDS_DN, EXTERNAL_PEERS_DN), object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME)); } @Test public void testRetrivePosixGroups() { ConnectorFacade facade = newFacade(); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.POSIX_GROUPS_NAME); assertAttributeValue(newList(POSIX_BUGS_AND_FRIENDS_DN, POSIX_EXTERNAL_PEERS_DN), object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME)); } @Test public void testCreateWithUniqueLdapGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.LDAP_GROUPS_NAME, UNIQUE_BUGS_AND_FRIENDS_DN, UNIQUE_EXTERNAL_PEERS_DN); doTestCreateWithGroups(facade, groupsAttr); } @Test public void testCreateWithLdapGroups() { ConnectorFacade facade = newFacade(); LdapConfiguration config = newConfiguration(); config.setGroupMemberAttribute("member"); // For groupOfNames. facade = newFacade(config); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.LDAP_GROUPS_NAME, BUGS_AND_FRIENDS_DN, EXTERNAL_PEERS_DN); doTestCreateWithGroups(facade, groupsAttr); } @Test public void testCreateWithPosixGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.POSIX_GROUPS_NAME, POSIX_BUGS_AND_FRIENDS_DN, POSIX_EXTERNAL_PEERS_DN); doTestCreateWithGroups(facade, groupsAttr); } private void doTestCreateWithGroups(ConnectorFacade facade, Attribute groupsAttr) { Set<Attribute> attributes = new HashSet<Attribute>(); attributes.add(new Name("uid=porky.pig," + ACME_USERS_DN)); attributes.add(AttributeBuilder.build("uid", "porky.pig")); attributes.add(AttributeBuilder.build("cn", "Porky Pig")); attributes.add(AttributeBuilder.build("givenName", "Porky")); attributes.add(AttributeBuilder.build("sn", "Pig")); attributes.add(groupsAttr); Uid uid = facade.create(ObjectClass.ACCOUNT, attributes, null); assertAttributeValue(groupsAttr.getValue(), facade, ObjectClass.ACCOUNT, uid, groupsAttr.getName()); } @Test public void testAddLdapGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.LDAP_GROUPS_NAME, UNIQUE_EMPTY_GROUP_DN); doTestAddGroups(facade, groupsAttr); } @Test public void testAddPosixGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.POSIX_GROUPS_NAME, POSIX_EMPTY_GROUP_DN); doTestAddGroups(facade, groupsAttr); } private void doTestAddGroups(ConnectorFacade facade, Attribute groupsAttr) { ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(BUGS_BUNNY_DN), groupsAttr.getName()); List<Object> oldGroups = newList(object.getAttributeByName(groupsAttr.getName()).getValue()); Uid uid = facade.addAttributeValues(ObjectClass.ACCOUNT, object.getUid(), singleton(groupsAttr), null); oldGroups.addAll(groupsAttr.getValue()); assertAttributeValue(oldGroups, facade, ObjectClass.ACCOUNT, uid, groupsAttr.getName()); } @Test public void testRemoveUniqueLdapGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.LDAP_GROUPS_NAME, UNIQUE_EXTERNAL_PEERS_DN); doTestRemoveGroups(facade, groupsAttr); } @Test public void testRemovePosixGroups() { ConnectorFacade facade = newFacade(); Attribute groupsAttr = AttributeBuilder.build(LdapConstants.POSIX_GROUPS_NAME, POSIX_EXTERNAL_PEERS_DN); doTestRemoveGroups(facade, groupsAttr); } private void doTestRemoveGroups(ConnectorFacade facade, Attribute groupsAttr) { ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), groupsAttr.getName()); List<Object> oldGroups = newList(object.getAttributeByName(groupsAttr.getName()).getValue()); Uid uid = facade.removeAttributeValues(ObjectClass.ACCOUNT, object.getUid(), singleton(groupsAttr), null); oldGroups.removeAll(groupsAttr.getValue()); assertAttributeValue(oldGroups, facade, ObjectClass.ACCOUNT, uid, groupsAttr.getName()); } @Test(expected = ConnectorException.class) public void testCannotRemoveUidWhenInPosixGroups() { ConnectorFacade facade = newFacade(); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(BUGS_BUNNY_DN)); Attribute uidAttr = AttributeBuilder.build("uid", BBUNNY_UID); facade.removeAttributeValues(ObjectClass.ACCOUNT, object.getUid(), singleton(uidAttr), null); } @Test(expected = ConnectorException.class) public void testCannotUpdateUidToNoneWhenInPosixGroups() { LdapConfiguration config = newConfiguration(); config.setBaseContexts(ACME_DN, SMALL_COMPANY_DN); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(OWNER_DN)); Attribute uidAttr = AttributeBuilder.build("uid"); facade.update(ObjectClass.ACCOUNT, object.getUid(), singleton(uidAttr), null); } @Test public void testRenameMaintainsGroupMemberships() { LdapConfiguration config = newConfiguration(); config.setMaintainLdapGroupMembership(true); config.setMaintainPosixGroupMembership(true); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.LDAP_GROUPS_NAME, LdapConstants.POSIX_GROUPS_NAME); List<String> oldLdapGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME).getValue(), String.class); List<String> oldPosixGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME).getValue(), String.class); Name newName = new Name("uid=sylvester.the.cat," + ACME_USERS_DN); Uid uid = facade.update(ObjectClass.ACCOUNT, object.getUid(), singleton((Attribute) newName), null); object = searchByAttribute(facade, ObjectClass.ACCOUNT, uid, LdapConstants.LDAP_GROUPS_NAME, LdapConstants.POSIX_GROUPS_NAME); assertAttributeValue(newList(UNIQUE_BUGS_AND_FRIENDS_DN, UNIQUE_EXTERNAL_PEERS_DN), object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME)); assertAttributeValue(newList(POSIX_BUGS_AND_FRIENDS_DN, POSIX_EXTERNAL_PEERS_DN), object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME)); // Also need to test that the old entries were actually removed from the old groups. for (String group : oldLdapGroups) { object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(group), "uniqueMember"); List<Object> members = object.getAttributeByName("uniqueMember").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_DN, members.contains(SYLVESTER_DN)); } for (String group : oldPosixGroups) { object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(group), "memberUid"); List<Object> members = object.getAttributeByName("memberUid").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_UID, members.contains(SYLVESTER_UID)); } } @Test public void testRenameAndUpdateGroupMemberships() { LdapConfiguration config = newConfiguration(); config.setMaintainLdapGroupMembership(true); config.setMaintainPosixGroupMembership(true); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.LDAP_GROUPS_NAME, LdapConstants.POSIX_GROUPS_NAME); List<String> oldLdapGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME).getValue(), String.class); List<String> oldPosixGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME).getValue(), String.class); Name newName = new Name("uid=sylvester.the.cat," + ACME_USERS_DN); Attribute ldapGroupsAttr = AttributeBuilder.build(LdapConstants.LDAP_GROUPS_NAME, UNIQUE_EXTERNAL_PEERS_DN, UNIQUE_EMPTY_GROUP_DN); Attribute posixGroupsAttr = AttributeBuilder.build(LdapConstants.POSIX_GROUPS_NAME, POSIX_EXTERNAL_PEERS_DN, POSIX_EMPTY_GROUP_DN); Uid uid = facade.update(ObjectClass.ACCOUNT, object.getUid(), newSet(newName, ldapGroupsAttr, posixGroupsAttr), null); object = searchByAttribute(facade, ObjectClass.ACCOUNT, uid, LdapConstants.LDAP_GROUPS_NAME, LdapConstants.POSIX_GROUPS_NAME); assertAttributeValue(ldapGroupsAttr.getValue(), object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME)); assertAttributeValue(posixGroupsAttr.getValue(), object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME)); // Also need to test that the old entries were actually removed from the old groups. for (String group : oldLdapGroups) { object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(group), "uniqueMember"); List<Object> members = object.getAttributeByName("uniqueMember").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_DN, members.contains(SYLVESTER_DN)); } for (String group : oldPosixGroups) { object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(group), "memberUid"); List<Object> members = object.getAttributeByName("memberUid").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_UID, members.contains(SYLVESTER_UID)); } } @Test public void testRenameDoesNotMaintainGroupMembershipsUnlessConfigured() { LdapConfiguration config = newConfiguration(); assertFalse(config.isMaintainLdapGroupMembership()); assertFalse(config.isMaintainPosixGroupMembership()); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN)); String newUid = "sylvester.the.cat"; String newEntryDN = "uid=" + newUid + "," + ACME_USERS_DN; facade.update(ObjectClass.ACCOUNT, object.getUid(), singleton((Attribute) new Name(newEntryDN)), null); object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(UNIQUE_BUGS_AND_FRIENDS_DN), "uniqueMember"); List<Object> members = object.getAttributeByName("uniqueMember").getValue(); assertTrue(members.contains(SYLVESTER_DN)); assertFalse(members.contains(newEntryDN)); object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(UNIQUE_EXTERNAL_PEERS_DN), "uniqueMember"); members = object.getAttributeByName("uniqueMember").getValue(); assertTrue(members.contains(SYLVESTER_DN)); assertFalse(members.contains(newEntryDN)); object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(POSIX_BUGS_AND_FRIENDS_DN), "memberUid"); members = object.getAttributeByName("memberUid").getValue(); assertTrue(members.contains(SYLVESTER_UID)); assertFalse(members.contains(newUid)); object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(POSIX_EXTERNAL_PEERS_DN), "memberUid"); members = object.getAttributeByName("memberUid").getValue(); assertTrue(members.contains(SYLVESTER_UID)); assertFalse(members.contains(newUid)); } @Test public void testDeleteMaintainsGroupMemberships() { LdapConfiguration config = newConfiguration(); config.setMaintainLdapGroupMembership(true); config.setMaintainPosixGroupMembership(true); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN), LdapConstants.LDAP_GROUPS_NAME, LdapConstants.POSIX_GROUPS_NAME); List<String> oldLdapGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.LDAP_GROUPS_NAME).getValue(), String.class); List<String> oldPosixGroups = checkedListByFilter(object.getAttributeByName(LdapConstants.POSIX_GROUPS_NAME).getValue(), String.class); facade.delete(ObjectClass.ACCOUNT, object.getUid(), null); // Need to test that the old entries were actually removed from the old groups. for (String group : oldLdapGroups) { object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(group), "uniqueMember"); List<Object> members = object.getAttributeByName("uniqueMember").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_DN, members.contains(SYLVESTER_DN)); } for (String group : oldPosixGroups) { object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(group), "memberUid"); List<Object> members = object.getAttributeByName("memberUid").getValue(); assertFalse("Group " + group + " should not contain " + SYLVESTER_UID, members.contains(SYLVESTER_UID)); } } @Test public void testDeleteDoesNotMaintainGroupMembershipsUnlessConfigured() { LdapConfiguration config = newConfiguration(); assertFalse(config.isMaintainLdapGroupMembership()); assertFalse(config.isMaintainPosixGroupMembership()); ConnectorFacade facade = newFacade(config); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, new Name(SYLVESTER_DN)); facade.delete(ObjectClass.ACCOUNT, object.getUid(), null); object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(UNIQUE_BUGS_AND_FRIENDS_DN), "uniqueMember"); List<Object> members = object.getAttributeByName("uniqueMember").getValue(); assertTrue(members.contains(SYLVESTER_DN)); object = searchByAttribute(facade, new ObjectClass("groupOfUniqueNames"), new Name(UNIQUE_EXTERNAL_PEERS_DN), "uniqueMember"); members = object.getAttributeByName("uniqueMember").getValue(); assertTrue(members.contains(SYLVESTER_DN)); object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(POSIX_BUGS_AND_FRIENDS_DN), "memberUid"); members = object.getAttributeByName("memberUid").getValue(); assertTrue(members.contains(SYLVESTER_UID)); object = searchByAttribute(facade, new ObjectClass("posixGroup"), new Name(POSIX_EXTERNAL_PEERS_DN), "memberUid"); members = object.getAttributeByName("memberUid").getValue(); assertTrue(members.contains(SYLVESTER_UID)); } @Test public void testPasswordHashing() throws Exception { LdapConfiguration config = newConfiguration(); config.setPasswordHashAlgorithm("SHA"); ConnectorFacade facade = newFacade(config); doTestPasswordHashing(facade, "SHA"); } @Test public void testSaltedPasswordHashing() throws Exception { LdapConfiguration config = newConfiguration(); config.setPasswordHashAlgorithm("SSHA"); ConnectorFacade facade = newFacade(config); doTestPasswordHashing(facade, "SSHA"); } private void doTestPasswordHashing(ConnectorFacade facade, String algorithm) throws UnsupportedEncodingException { String algorithmLabel = "{" + algorithm + "}"; Set<Attribute> attrs = new HashSet<Attribute>(); attrs.add(new Name("uid=daffy.duck," + ACME_USERS_DN)); attrs.add(AttributeBuilder.build("uid", "daffy.duck")); attrs.add(AttributeBuilder.build("cn", "Daffy Duck")); attrs.add(AttributeBuilder.build("sn", "Duck")); attrs.add(AttributeBuilder.build("ds-pwp-password-policy-dn", "cn=Clear Text Password Policy,cn=Password Policies,cn=config")); GuardedString password = new GuardedString("foobar".toCharArray()); attrs.add(AttributeBuilder.buildPassword(password)); Uid uid = facade.create(ObjectClass.ACCOUNT, attrs, null); ConnectorObject object = searchByAttribute(facade, ObjectClass.ACCOUNT, uid, "userPassword"); byte[] passwordBytes = (byte[]) object.getAttributeByName("userPassword").getValue().get(0); assertTrue(new String(passwordBytes, "UTF-8").startsWith(algorithmLabel)); facade.authenticate(ObjectClass.ACCOUNT, "daffy.duck", password, null); password = new GuardedString("newpassword".toCharArray()); facade.update(ObjectClass.ACCOUNT, object.getUid(), singleton(AttributeBuilder.buildPassword(password)), null); object = searchByAttribute(facade, ObjectClass.ACCOUNT, uid, "userPassword"); passwordBytes = (byte[]) object.getAttributeByName("userPassword").getValue().get(0); assertTrue(new String(passwordBytes, "UTF-8").startsWith(algorithmLabel)); facade.authenticate(ObjectClass.ACCOUNT, "daffy.duck", password, null); } private static void assertAttributeValue(List<?> expected, ConnectorFacade facade, ObjectClass oclass, Uid uid, String attrName) { ConnectorObject object = searchByAttribute(facade, oclass, uid, attrName); assertAttributeValue(expected, object.getAttributeByName(attrName)); } private static void assertAttributeValue(List<?> expected, Attribute attr) { Set<?> attrValue = newSet(attr.getValue()); Set<?> expectedValue = newSet(expected); assertEquals(expectedValue, attrValue); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
d262749552af74c679ab594d8155a434625e4f27
04def39429a0015b6d8b52c4d74b926a4cf6e7e8
/Week_01/src/main/java/jvm/JvmClassLoaderPrintPath.java
dfa8e9d67797b5100809d80721fae2e6d157dfac
[]
no_license
mrly202016/JAVA-000
4710693e1e463c2420a9c0d43c8a23413b20a474
fa06e304dffe0cf98f12714f77c6de105d2e2996
refs/heads/main
2023-02-27T18:24:10.863228
2021-02-03T15:24:30
2021-02-03T15:24:30
304,828,480
1
0
null
2020-10-17T08:05:41
2020-10-17T08:05:40
null
UTF-8
Java
false
false
1,910
java
package jvm; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; /** * Created by IntelliJ IDEA * User: yyzz * Date: 2020/10/19 * Time: 22:23 */ public class JvmClassLoaderPrintPath { public static void main(String[] args) { // 启动类加载器 URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs(); System.out.println("启动类加载器"); for(URL url : urls) { System.out.println(" ==> " +url.toExternalForm()); } // 扩展类加载器 printClassLoader("扩展类加载器", JvmClassLoaderPrintPath.class.getClassLoader()); // 应用类加载器 printClassLoader("应用类加载器", JvmClassLoaderPrintPath.class.getClassLoader()); } public static void printClassLoader(String name, ClassLoader CL){ if(CL != null) { System.out.println(name + " ClassLoader ‐> " + CL.toString()); printURLForClassLoader(CL); }else{ System.out.println(name + " ClassLoader ‐> null"); } } public static void printURLForClassLoader(ClassLoader CL){ Object ucp = insightField(CL,"ucp"); Object path = insightField(ucp,"path"); ArrayList ps = (ArrayList) path; for (Object p : ps){ System.out.println(" ==> " + p.toString()); } } private static Object insightField(Object obj, String fName) { try { Field f = null; if(obj instanceof URLClassLoader){ f = URLClassLoader.class.getDeclaredField(fName); }else{ f = obj.getClass().getDeclaredField(fName); } f.setAccessible(true); return f.get(obj); } catch (Exception e) { e.printStackTrace(); return null; } } }
[ "mrly202016@163.com" ]
mrly202016@163.com
4251d11d8c2e28773c7f7f1e3a6080ef51c21fa1
3b9203a48d82012dcff0dc7d070421c4c234b47d
/java/workspace/chapter10/src/chapter10/Calc.java
40b6f50202d59e1b587b205834481ed38eb09009
[]
no_license
ParkJeong/course
3be45a409e12ddc1b6175bca9e9bae349bc0660b
4710b659980fed8caf41640dcb8a8511aecf107a
refs/heads/master
2022-12-31T20:51:57.452788
2020-10-26T00:13:26
2020-10-26T00:13:26
288,903,000
0
0
null
null
null
null
UTF-8
Java
false
false
871
java
package chapter10; public interface Calc { double PI = 3.14; // 인터페이스에서 선언한 변수는 int ERROR = -999999999; // 컴파일 과정에서 상수로 변환됨 int add(int num1, int num2); // 인터페이스 에서 선언한 메서드는 int substract(int num1, int num2); // 컴파일 과정에서 추상 메서드로 변환됨 int times(int num1, int num2); int divide(int num1, int num2); int square(int num); static int total(int[] arr) { int total = 0; for(int i : arr) { total += i; } return total; } default void description() { System.out.println("정수 계산기를 구현합니다."); // myMethod(); } // // private void myMethod() { // System.out.println("private 메서드입니다."); // } // // private static void myStaticMethod() { // System.out.println("private static 메서드입니다."); // } }
[ "kangtak6291@naver.com" ]
kangtak6291@naver.com
38f0ca6f8237b2650e60b1ec910677034eb11631
8ce2b309e342c6eba57c74ade8548010ce9f6d2d
/Module3_AccountName_WBE/src/model/bean/service/Service.java
241d3000cd8922d4a7f3b3cdff5b9b8b3c35f20f
[]
no_license
truongphuc1234/C102020-PhamTruongPhuc
d3041f762b20fdb1faa94fcc503cf51c833bde75
cc9f20459ceedcc5d77ca41599ba1fb7b90e7fbe
refs/heads/main
2023-04-09T04:23:46.942575
2021-04-11T05:13:22
2021-04-11T05:13:22
307,267,307
0
0
null
null
null
null
UTF-8
Java
false
false
3,156
java
package model.bean.service; public class Service { private String serviceId; private String serviceName; private int serviceArea; private double serviceCost; private int serviceMaxPeople; private int rentTypeId; private int serviceTypeId; private String standardRoom; private String descriptionOtherConvenience; private double poolArea; private int numberOfFloor; public Service() { } public Service(String serviceId, String serviceName, int serviceArea, double serviceCost, int serviceMaxPeople, int rentTypeId, int serviceTypeId, String standardRoom, String descriptionOtherConvenience, double poolArea, int numberOfFloor) { this.serviceId = serviceId; this.serviceName = serviceName; this.serviceArea = serviceArea; this.serviceCost = serviceCost; this.serviceMaxPeople = serviceMaxPeople; this.rentTypeId = rentTypeId; this.serviceTypeId = serviceTypeId; this.standardRoom = standardRoom; this.descriptionOtherConvenience = descriptionOtherConvenience; this.poolArea = poolArea; this.numberOfFloor = numberOfFloor; } public String getServiceId() { return serviceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public int getServiceArea() { return serviceArea; } public void setServiceArea(int serviceArea) { this.serviceArea = serviceArea; } public double getServiceCost() { return serviceCost; } public void setServiceCost(double serviceCost) { this.serviceCost = serviceCost; } public int getServiceMaxPeople() { return serviceMaxPeople; } public void setServiceMaxPeople(int serviceMaxPeople) { this.serviceMaxPeople = serviceMaxPeople; } public int getRentTypeId() { return rentTypeId; } public void setRentTypeId(int rentTypeId) { this.rentTypeId = rentTypeId; } public int getServiceTypeId() { return serviceTypeId; } public void setServiceTypeId(int serviceTypeId) { this.serviceTypeId = serviceTypeId; } public String getStandardRoom() { return standardRoom; } public void setStandardRoom(String standardRoom) { this.standardRoom = standardRoom; } public String getDescriptionOtherConvenience() { return descriptionOtherConvenience; } public void setDescriptionOtherConvenience(String descriptionOtherConvenience) { this.descriptionOtherConvenience = descriptionOtherConvenience; } public double getPoolArea() { return poolArea; } public void setPoolArea(double poolArea) { this.poolArea = poolArea; } public int getNumberOfFloor() { return numberOfFloor; } public void setNumberOfFloor(int numberOfFloor) { this.numberOfFloor = numberOfFloor; } }
[ "truongphuc@gmail.com" ]
truongphuc@gmail.com
1785027d4a7d32826b14e1a63641f02a9455e2ac
2869fc39e2e63d994d5dd8876476e473cb8d3986
/Super_passport/src/java/com/lvmama/train/service/response/StationQueryResponse.java
f27f8119a26b24973c18039aade3e4f1d8d8dcc0
[]
no_license
kavt/feiniu_pet
bec739de7c4e2ee896de50962dbd5fb6f1e28fe9
82963e2e87611442d9b338d96e0343f67262f437
refs/heads/master
2020-12-25T17:45:16.166052
2016-06-13T10:02:42
2016-06-13T10:02:42
61,026,061
0
0
null
2016-06-13T10:02:01
2016-06-13T10:02:01
null
UTF-8
Java
false
false
560
java
package com.lvmama.train.service.response; import java.util.List; import com.lvmama.comm.utils.JsonUtil; import com.lvmama.comm.vo.train.product.StationInfo; import com.lvmama.comm.vo.train.product.StationRspVo; public class StationQueryResponse extends AbstractTrainResponse{ @SuppressWarnings("unchecked") @Override public void parse(String response) throws RuntimeException { List<StationInfo> stationInfos = JsonUtil.getList4Json(response, StationInfo.class, null); this.getRsp().setVo(new StationRspVo(stationInfos)); } }
[ "feiniu7903@163.com" ]
feiniu7903@163.com
c4e47d68669c557e9aa700ae6f60a41171abd09c
13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3
/crash-reproduction-ws/results/XWIKI-13377-8-13-Single_Objective_GGA-WeightedSum/com/xpn/xwiki/user/impl/LDAP/XWikiLDAPAuthServiceImpl_ESTest.java
cc9c59bd7b4287afc90bf344294dde83dcd6321d
[ "MIT", "CC-BY-4.0" ]
permissive
STAMP-project/Botsing-basic-block-coverage-application
6c1095c6be945adc0be2b63bbec44f0014972793
80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da
refs/heads/master
2022-07-28T23:05:55.253779
2022-04-20T13:54:11
2022-04-20T13:54:11
285,771,370
0
0
null
null
null
null
UTF-8
Java
false
false
583
java
/* * This file was automatically generated by EvoSuite * Mon Mar 30 20:00:49 UTC 2020 */ package com.xpn.xwiki.user.impl.LDAP; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class XWikiLDAPAuthServiceImpl_ESTest extends XWikiLDAPAuthServiceImpl_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
9dabc54b3bcf52e097b3b9a10e2fda84c8bc64ff
12a13a0fccb0224f80d6904470616cbd8ca1ed6c
/com.kita.second/src/com/kita/second/level1/PhoneTest.java
d199e98d71ccce180e3724e14d5229f4991126f5
[]
no_license
Donghun99/Koreait_java2_weekend
12f5458f4b164dfe34532ef1309529a8d4eac353
162332ab6a575f0d2eac889bd427fa8840e03201
refs/heads/master
2023-03-13T20:47:58.935274
2021-03-21T08:49:56
2021-03-21T08:49:56
342,784,881
0
0
null
null
null
null
UTF-8
Java
false
false
843
java
package com.kita.second.level1; import java.util.Scanner; public class PhoneTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Phone myphone = new Phone(); // myphone.call("엄마"); // myphone.color = "파랑"; // myphone.phoneName ="아이폰10"; // myphone.owner ="이동훈"; // myphone.memory = 512; Phone p1 =new Phone("갤럭시 s20", "빨강", 256); p1.setOwner("박연진"); String p1Owner = p1.getOwner(); System.out.println("p1의 주인은"+p1Owner); int p1Memory = p1.getMemory(); System.out.println("p1의 메모리는" +p1Memory ); p1.setMemory(512); p1Memory = p1.getMemory(); System.out.println("p1의 메모리는"+p1Memory); //Phone.getMemory(); 이렇게하면 오류 myphone.call("엄마"); Phone yourPhone = new Phone(); } }
[ "dbjbgb@naver.com" ]
dbjbgb@naver.com
60e1f45b5a55c69a86714623efa31590ab5abfe0
8d5b63d57577690ef0d3c0df5150628e709799c7
/src/cn/tarena/tick/TickToMysql.java
e6ee33adb2faeccc4b66d740bb507158c356600f
[]
no_license
Justdwiwt/WebLog
9f2ff31250af60350c0e8e8edc9a35817d2c2923
e32b430f98bfd731127b8402a29a7bb61865ec80
refs/heads/master
2020-04-11T12:17:59.403943
2018-12-14T11:29:29
2018-12-14T11:29:29
161,775,827
3
1
null
null
null
null
UTF-8
Java
false
false
1,286
java
package cn.tarena.tick; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Tuple; import cn.tarena.dao.MysqlDao; import cn.tarena.pojo.Tongji2; import java.sql.Date; import java.util.Map; public class TickToMysql extends BaseRichBolt { @Override public void execute(Tuple input) { try { Date time = new Date(input.getLongByField("endtime")); double br = input.getDoubleByField("br"); double avgdeep = input.getDoubleByField("avgdeep"); double avgtime = input.getDoubleByField("avgtime"); Tongji2 t = new Tongji2(); t.setTime(time); t.setBr(br); t.setAvgdeep(avgdeep); t.setAvgtime(avgtime); MysqlDao.tickToMysql(t); } catch (Exception e) { e.printStackTrace(); } } @Override public void prepare(Map arg0, TopologyContext arg1, OutputCollector arg2) { // TODO Auto-generated method stub } @Override public void declareOutputFields(OutputFieldsDeclarer arg0) { // TODO Auto-generated method stub } }
[ "len_master@hotmail.com" ]
len_master@hotmail.com
ee6a81aa61d70b67b7a8dadce351ebbff7f61a7a
d60e287543a95a20350c2caeabafbec517cabe75
/NLPCCd/Camel/1624_1.java
d7bce389193e4fe3f3db1e3d3e7e3ca5864afb95
[ "MIT" ]
permissive
sgholamian/log-aware-clone-detection
242067df2db6fd056f8d917cfbc143615c558b2c
9993cb081c420413c231d1807bfff342c39aa69a
refs/heads/main
2023-07-20T09:32:19.757643
2021-08-27T15:02:50
2021-08-27T15:02:50
337,837,827
0
0
null
null
null
null
UTF-8
Java
false
false
481
java
//,temp,sample_5879.java,2,12,temp,sample_15.java,2,13 //,3 public class xxx { protected void onExchange(Exchange exchange) throws Exception { String path = getResourceUri(); ObjectHelper.notNull(path, "resourceUri"); String newResourceUri = exchange.getIn().getHeader(MvelConstants.MVEL_RESOURCE_URI, String.class); if (newResourceUri != null) { exchange.getIn().removeHeader(MvelConstants.MVEL_RESOURCE_URI); log.info("set to creating new endpoint to handle exchange"); } } };
[ "SHOSHIN\\sgholamian@shoshin.uwaterloo.ca" ]
SHOSHIN\sgholamian@shoshin.uwaterloo.ca
216c3797e357b4aeb7db78c83c7816698ade9a31
bb2cebaf7fecf5bca7931fb7760e4df7da752230
/spring-boot-crud-demo/src/test/java/com/sakx/developer/demo/RestClientUtil.java
1d9a0b76aede69ccecc1345dbb15a84a39166fab
[]
no_license
mksrepo/springboot
8e251d5e20916f7f1d300c92e7b86cd0d13027c0
88a08453c4159b7537ff77338d7745539b35ca88
refs/heads/master
2020-03-27T01:48:51.672552
2018-11-15T06:24:39
2018-11-15T06:24:39
145,744,704
1
1
null
2018-08-23T13:14:13
2018-08-22T18:01:58
Java
UTF-8
Java
false
false
3,672
java
package com.sakx.developer.demo; import java.net.URI; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.sakx.developer.demo.model.Article; public class RestClientUtil { public void getArticleByIdDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article/{id}"; HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<Article> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article.class, 1); Article article = responseEntity.getBody(); System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle() +", Category:"+article.getCategory()); } public void getAllArticlesDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/articles"; HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<Article[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article[].class); Article[] articles = responseEntity.getBody(); for(Article article : articles) { System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle() +", Category: "+article.getCategory()); } } public void addArticleDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article"; Article objArticle = new Article(); objArticle.setTitle("Spring REST Security using Hibernate"); objArticle.setCategory("Spring"); HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers); URI uri = restTemplate.postForLocation(url, requestEntity); System.out.println(uri.getPath()); } public void updateArticleDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article"; Article objArticle = new Article(); objArticle.setArticleId(1); objArticle.setTitle("Update:Java Concurrency"); objArticle.setCategory("Java"); HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers); restTemplate.put(url, requestEntity); } public void deleteArticleDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article/{id}"; HttpEntity<Article> requestEntity = new HttpEntity<Article>(headers); restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Void.class, 1); } public static void main(String args[]) { RestClientUtil util = new RestClientUtil(); //util.getArticleByIdDemo(); //util.addArticleDemo(); //util.updateArticleDemo(); //util.deleteArticleDemo(); // util.getAllArticlesDemo(); } }
[ "264030@PC399852.cts.com" ]
264030@PC399852.cts.com
2a7870833c81fc7a8a701201927b1ab419327743
87696ffe8f864a2ee1e27bcf604db2da417bdcd8
/src/main/java/com/example/intelectusmoney/api/model/TipoLancamento.java
37fd8fde3dd4f87c7ac1b621a3da6ae02767c178
[]
no_license
ctdecampos1/intelectusmoney
c6edf461ed54265e422939bb717970bab5886e88
cc16eebb5c0a73359741416b0fc6f0a7ea7fe7d1
refs/heads/master
2021-08-22T10:11:56.214887
2017-11-21T00:03:36
2017-11-21T00:03:36
104,155,945
1
0
null
2017-10-09T04:05:34
2017-09-20T02:38:04
Java
UTF-8
Java
false
false
98
java
package com.example.intelectusmoney.api.model; public enum TipoLancamento { RECEITA, DESPESA }
[ "ctdecampos1@gmail.com" ]
ctdecampos1@gmail.com
4266ee5653fe156198597ca0b776ea20246eb9a6
4473046026ff215c6c9fbb6ecd1cad9b1f95a67e
/JavaAdvanced/JavaOOPBasics/InterfacesAndAbstraction/MooD3/Archangel.java
dba023904aae88fe6efac922effb1e14c08e2292
[]
no_license
miroslavangelov/Java-Development
e105248d82dd0772902eeeefbeb2389919fec262
61fcc2fb8a5ae9f38647f85eb63f809e7d8df350
refs/heads/master
2022-12-12T04:27:27.932969
2019-12-08T12:38:36
2019-12-08T12:38:36
138,468,780
0
0
null
2022-11-24T08:50:00
2018-06-24T09:18:55
Java
UTF-8
Java
false
false
684
java
package JavaOOPBasics.InterfacesAndAbstraction.MooD3; public class Archangel extends GameObject implements IArchangel { private int mana; public Archangel(String userName, int level, int mana) { super(userName, level); this.mana = mana; } @Override protected String generateHashedPassword() { return new StringBuilder(this.getUserName()).reverse().toString() + Integer.toString(this.getUserName().length()*21); } @Override protected String getSpecialPoints() { return Integer.toString(this.getMana()*this.getLevel()); } @Override public int getMana() { return this.mana; } }
[ "angelov0428@gmail.com" ]
angelov0428@gmail.com
cfa3b20046770a3b6d4ce455c6b6d3e8a83f6f96
c8c9f9799fecb6786297dfcb00c857181a7355c5
/learn/src/main/java/com/kevin/learn/learn/arithmetic/sort/jike/Palindrome.java
2d1d73d5e00836f0721cb75ae736ae3c684ce434
[ "MIT" ]
permissive
KevinHe666/learn-interview
62acc877f2f5c652f78daa669deabc3a8ca19c1d
0540aa9cb119fa83e78eae0cef0474b7e553fcd7
refs/heads/master
2022-07-01T10:39:05.902165
2020-12-19T11:41:52
2020-12-19T11:41:52
194,416,706
5
0
MIT
2022-06-17T02:19:39
2019-06-29T14:50:49
Java
UTF-8
Java
false
false
1,821
java
package com.kevin.learn.learn.arithmetic.sort.jike; /** * @Description: 判断是否是回文字符串 LRU淘汰算法 * @Author: Kevin * @Create 2019-07-08 09:53 */ public class Palindrome { /** * 回文字符串 */ private static String string = "A man, a plan, a canal: Panama"; /** * 非回文字符串 */ private static String unString = "bhhudsp"; public static void main(String[] args) { System.out.println(ifPalindrome2(string)); System.out.println(ifPalindrome2(unString)); } /** * 第一种最笨的方法 O(n) * 转化数组然后对应位置去对比 * * @param str * @return */ public static boolean ifPalindrome1(String str) { str = str.replaceAll("[\\p{Punct}\\p{Space}]+", "").toLowerCase(); System.out.println(str); int times = str.length() / 2; int length = str.length(); for (int i = 0; i < times; i++) { if (str.toCharArray()[i] != str.toCharArray()[length - i - 1]) { return false; } } return true; } /** * 双指针法 * * @param s * @return */ public static boolean ifPalindrome2(String s) { if (s == null) { return false; } if (s.length() == 0) { return true; } //前指针 int i = 0; //后指针 int j = s.length() - 1; while (i < j) { while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++; while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--; if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false; i++; j--; } return true; } }
[ "hewenkai_1992@sina.com" ]
hewenkai_1992@sina.com
df8d076a66c1469ee4702aca030dcc578c0dc8e6
e5aec318f2729c9720c95af842a8e9041ee605be
/examples/src/main/java/reflection/ClassReflection.java
cc04be4995eb8d8d0d815e126e1d5952c5ceed31
[]
no_license
bulaiocht/arrowhead
65074d253cf1b75b624878ba46425d7e824fee62
a04fb3f467f292c8adb255b79ce254e2e249e4c2
refs/heads/master
2020-05-25T07:27:42.212878
2019-10-28T19:14:28
2019-10-28T19:14:28
187,685,355
10
8
null
2019-07-01T14:57:32
2019-05-20T17:30:10
Java
UTF-8
Java
false
false
3,958
java
package reflection; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.function.Function; public class ClassReflection { public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException { SimpleFileReader reader = new SimpleFileReader(); SimpleService service = new SimpleService(reader); // service.doSomething(); Class<SimpleService> simpleServiceClass = SimpleService.class; Class<Integer> integerClass = int.class; // System.out.println(integerClass.isPrimitive()); // Class<Integer> integerClass = int.class; // // Class<Void> voidClass = void.class; // // Class<int[]> aClass = int[].class; // // Class<int[][]> aClass1 = int[][].class; // // // Class<? extends SimpleService> aClass2 = service.getClass(); // // Class<?> aClass3 = Class.forName("reflection.SimpleService"); // // System.out.println(simpleServiceClass.isPrimitive()); // Class<?>[] interfaces = simpleServiceClass.getInterfaces(); // // for (Class<?> i : interfaces) { // System.out.println(i.getName()); // for (final Method method : i.getMethods()) { // System.out.println(method.getName()); // // Class<?>[] parameterTypes = method.getParameterTypes(); // for (final Class<?> parameterType : parameterTypes) { // System.out.println(parameterType.getName()); // } // // System.out.println(method.isSynthetic()); // // } // } // Function<String, Integer> function = s -> { // System.out.println(s); // return s.length(); // }; // // Class<? extends Function> funClass = function.getClass(); // // System.out.println(funClass.isSynthetic()); // // Method[] declaredMethods = funClass.getDeclaredMethods(); // for (Method declaredMethod : declaredMethods) { // int modifiers = declaredMethod.getModifiers(); // if (Modifier.isPublic(modifiers)) { // System.out.print("public "); // Class<?> returnType = declaredMethod.getReturnType(); // System.out.print(returnType.getName() + " "); // System.out.print(declaredMethod.getName()); // System.out.print("("); // Class<?>[] parameterTypes = declaredMethod.getParameterTypes(); // for (final Class<?> parameterType : parameterTypes) { // System.out.println(parameterType.getName()); // } // } // declaredMethod.invoke(function, "Hello"); // // } // for (final Method method : simpleServiceClass.getDeclaredMethods()) { // // // // if ("doStuff".equals(method.getName())){ // // method.setAccessible(true); // method.invoke(service, new Object[]{"Hello"}); // // } // // if ("secretMethod".equals(method.getName())){ // method.setAccessible(true); // method.invoke(service); // } // Class<SingleObject> singleObjectClass = SingleObject.class; Constructor<?>[] constructors = singleObjectClass.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { constructor.setAccessible(true); SingleObject object = (SingleObject)constructor.newInstance("Private constructor says hello"); System.out.println(object.getField()); } String[] array = (String[])Array.newInstance(String.class, 10); System.out.println(array.length); } }
[ "ko4erha@gmail.com" ]
ko4erha@gmail.com
f7a45a712603e375c1da21500d68198834206b93
3deb6a95505074a7948c173023cd299562e43755
/Lab6/src/com/jlcindia/servlets/HelloServlet.java
8f8895dbb12b090a24dae7b0c64187dfabc9e13b
[]
no_license
bashakg404/harsha
e8388c5c0dd9eeddbf6e8d8fdf23115540cbe6a8
c31b187affdafff9c9063ddaac5c023cd90c03da
refs/heads/master
2020-03-18T06:52:08.727481
2018-09-20T21:11:45
2018-09-20T21:11:45
134,418,876
0
0
null
null
null
null
UTF-8
Java
false
false
1,313
java
package com.jlcindia.servlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet{ ServletConfig cfg=null; @Override public void init(ServletConfig cfg) throws ServletException{ this.cfg=cfg; System.out.println("**init() method of HelloServlet**"); } protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ System.out.println("**service() method of HelloServlet**"); String fnm=req.getParameter("fname"); String phn=req.getParameter("Phone"); Writer out=res.getWriter(); res.setContentType("text/html"); out.write("<h1> Response from HelloServlet"); out.write("<hr/> Request Parameters"); out.write("<br/> Fname:" + fnm); out.write("<br/> Phone:" + phn); out.write("<hr> Servlet Config Parameteers"); String eml=cfg.getInitParameter("email"); out.write("<br/>" +cfg); out.write("<br/>Email:" + eml); /*String pn=cfg.getInitParameter("phone"); out.write("<br/>" +cfg); out.write("<br/>Phone:" + phn); PrintWriter printWriter = res.getWriter(); printWriter.println("<h1>Phone No:" + phn);*/ out.write("<hr/> Servlet Context Parameters"); ServletContext ctx=cfg.getServletContext(); String web=ctx.getInitParameter("website"); out.write("<br/>" + ctx); out.write("<br/>Web:" + web); } }
[ "bashasab.gudimani@cgi.com" ]
bashasab.gudimani@cgi.com
7e304a09d58e102134f81d271b90ffc59b1b2fc4
5920e3151c49131b20286bd07e054198d71d9877
/src/main/java/com/flagstone/transform/as3/abcfile/instruction/invocation/InstructionCallpropertyExtd.java
a17f46ac79728387a06ca672fb620ebaa0eb2fe6
[ "MIT" ]
permissive
jguyet/ABCFile
df225ca8321196b7ac0bd08da07eec2417857e05
29ad85ef170a268a008faa49e4ff12f4668a9c15
refs/heads/master
2020-03-27T12:03:02.559452
2018-08-29T00:55:42
2018-08-29T00:55:42
146,522,371
1
0
null
null
null
null
UTF-8
Java
false
false
1,439
java
package com.flagstone.transform.as3.abcfile.instruction.invocation; import java.util.ArrayList; import com.flagstone.transform.as3.abcfile.cpool.MultinameInfo; import com.flagstone.transform.as3.abcfile.structures.CpoolInfo; import com.flagstone.transform.as3.abcfile.utils.ByteBufferFlash; public class InstructionCallpropertyExtd extends InstructionCallproperty { private MultinameInfo multiname_info; protected CpoolInfo cpool; public InstructionCallpropertyExtd(ByteBufferFlash date, int position, CpoolInfo cpool) { super(date, position); this.cpool = cpool; this.multiname_info = ((MultinameInfo) cpool.getMultinames().get(this.index)); } public InstructionCallpropertyExtd(MultinameInfo multiname_info, int arg_count, int position) { super(multiname_info.getId(), arg_count, position); this.multiname_info = multiname_info; } public MultinameInfo getMultiname_info() { return this.multiname_info; } public void setMultiname_info(MultinameInfo multinameInfo) { this.multiname_info = multinameInfo; getIndex(); } public int getIndex() { this.index = this.multiname_info.getId(); return this.index; } public void parseDate(ByteBufferFlash date) throws Exception { super.parseDate(date); this.multiname_info = ((MultinameInfo) this.cpool.getMultinames().get(this.index)); } }
[ "jguyet@student.42.fr" ]
jguyet@student.42.fr
35b77d1c445901765f41eaac90706f914552c0c6
b868b91fdd8dbc41b699d15b9543739d64d91df1
/MG2D/src/main/java/com/mulganov/job/lib/mg2d/mg2dThread.java
427ace95050574a150b645d8cc6c130ed56b1388
[]
no_license
Mulganov/MapsEdition
563e127bcceec7d8eebfd55339ebef4f55821ba9
dfcee204bb5db1ffe72e9355f45c9a68a45a20eb
refs/heads/master
2022-07-09T14:54:02.074714
2020-05-09T08:54:55
2020-05-09T08:54:55
261,426,713
1
0
null
null
null
null
UTF-8
Java
false
false
2,376
java
package com.mulganov.job.lib.mg2d; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.SurfaceHolder; import com.mulganov.job.lib.mg2d.scena.Scena; import java.util.ArrayList; public class mg2dThread extends java.lang.Thread { private MG2D mg2D; private boolean runFlag = true; private SurfaceHolder surfaceHolder; private Scena scena; private boolean newScena; public mg2dThread(SurfaceHolder surfaceHolder, MG2D mg2D) { this.surfaceHolder = surfaceHolder; this.mg2D = mg2D; } public void setRunning(boolean run) { runFlag = run; } @Override public void run() { Canvas canvas; while (runFlag) { canvas = null; try { // получаем объект Canvas и выполняем отрисовку canvas = surfaceHolder.lockCanvas(); if (canvas == null) return; synchronized (surfaceHolder) { canvas.drawColor(mg2D.getSetting().getBackground()); if (scena == null) continue; for (int i = 0; true; i++){ if (newScena){ newScena = false; break; } if (scena.get(i) != null) scena.get(i).draw(canvas); else break; } if (mg2D.getSetting().getBorder().isStatus()){ mg2D.getSetting().getBorder().getGraphGroup(mg2D).draw(canvas); } } } finally { if (canvas != null) { // отрисовка выполнена. выводим результат на экран surfaceHolder.unlockCanvasAndPost(canvas); } } } } public Scena getScena() { return scena; } public void setScena(Scena scena) { this.scena = scena; newScena = true; } public boolean isNewScena(){ return newScena; } public void setNewScena(boolean b) { this.newScena = b; } }
[ "mulganov2001@gmail.com" ]
mulganov2001@gmail.com
cba73c79f9bf8b2b9c4cbdb644d65fa3f7a9b1f6
3ea90852ce844b9fdb21e5d391aed7929013bce5
/rapla-source-1.8.4/src/org/rapla/plugin/tableview/internal/SwingReservationTableView.java
0ca1bdc538a2eee21c8ec9807846bd14462057d6
[]
no_license
Ayce45/OverwatchBTS
5e2b932d9b3d7744b0f6bc2bba1cb2b0f5bfc06c
eb1ece3695b0b34ecad0422e9e878563f486e01f
refs/heads/master
2020-04-12T19:26:13.116600
2019-09-14T12:50:41
2019-09-14T12:50:41
162,708,924
1
0
null
null
null
null
UTF-8
Java
false
false
15,641
java
package org.rapla.plugin.tableview.internal; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import javax.swing.BoxLayout; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import org.rapla.components.calendar.DateChangeEvent; import org.rapla.components.calendar.DateChangeListener; import org.rapla.components.tablesorter.TableSorter; import org.rapla.components.util.TimeInterval; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.entities.User; import org.rapla.entities.configuration.Preferences; import org.rapla.entities.domain.Allocatable; import org.rapla.entities.domain.Reservation; import org.rapla.facade.CalendarModel; import org.rapla.facade.CalendarSelectionModel; import org.rapla.facade.ClientFacade; import org.rapla.framework.Container; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaException; import org.rapla.framework.RaplaLocale; import org.rapla.framework.internal.ConfigTools.RaplaReaderImpl; import org.rapla.gui.MenuContext; import org.rapla.gui.MenuFactory; import org.rapla.gui.RaplaGUIComponent; import org.rapla.gui.ReservationController; import org.rapla.gui.SwingCalendarView; import org.rapla.gui.VisibleTimeInterval; import org.rapla.gui.internal.common.InternMenus; import org.rapla.gui.toolkit.MenuInterface; import org.rapla.gui.toolkit.RaplaMenu; import org.rapla.gui.toolkit.RaplaPopupMenu; import org.rapla.plugin.abstractcalendar.IntervalChooserPanel; import org.rapla.plugin.tableview.RaplaTableColumn; import org.rapla.plugin.tableview.ReservationTableColumn; import org.rapla.plugin.tableview.TableViewExtensionPoints; import org.rapla.plugin.tableview.internal.TableConfig.TableColumnConfig; public class SwingReservationTableView extends RaplaGUIComponent implements SwingCalendarView, Printable, VisibleTimeInterval { ReservationTableModel reservationTableModel; JTable table; CalendarModel model; IntervalChooserPanel dateChooser; JScrollPane scrollpane; JComponent container; TableSorter sorter; CopyListener copyListener = new CopyListener(); CopyListener cutListener = new CopyListener(); public SwingReservationTableView( RaplaContext context, final CalendarModel model, final boolean editable ) throws RaplaException { super( context ); cutListener.setCut(true); table = new JTable() { private static final long serialVersionUID = 1L; public String getToolTipText(MouseEvent e) { if (!editable) return null; int rowIndex = rowAtPoint( e.getPoint() ); Reservation reservation = reservationTableModel.getReservationAt( sorter.modelIndex( rowIndex )); return getInfoFactory().getToolTip( reservation ); } }; scrollpane = new JScrollPane( table); if ( editable ) { container = new JPanel(); container.setLayout( new BorderLayout()); container.add( scrollpane, BorderLayout.CENTER); JPanel extensionPanel = new JPanel(); extensionPanel.setLayout( new BoxLayout(extensionPanel, BoxLayout.X_AXIS)); container.add( extensionPanel, BorderLayout.SOUTH); scrollpane.setPreferredSize( new Dimension(600,800)); PopupTableHandler popupHandler = new PopupTableHandler(); scrollpane.addMouseListener( popupHandler); table.addMouseListener( popupHandler ); Collection< ? extends SummaryExtension> reservationSummaryExtensions = getContainer().lookupServicesFor(TableViewExtensionPoints.RESERVATION_TABLE_SUMMARY); for ( SummaryExtension summary:reservationSummaryExtensions) { summary.init(table, extensionPanel); } } else { Dimension size = table.getPreferredSize(); scrollpane.setBounds( 0,0,600, (int)size.getHeight()); container = scrollpane; } this.model = model; //Map<?,?> map = getContainer().lookupServicesFor(RaplaExtensionPoints.APPOINTMENT_STATUS); //Collection<AppointmentStatusFactory> appointmentStatusFactories = (Collection<AppointmentStatusFactory>) map.values(); User user = model.getUser(); List<RaplaTableColumn<Reservation>> reservationColumnPlugins = TableConfig.loadColumns(getContainer(), "events", TableViewExtensionPoints.RESERVATION_TABLE_COLUMN, user); reservationTableModel = new ReservationTableModel( getLocale(),getI18n(), reservationColumnPlugins ); ReservationTableModel tableModel = reservationTableModel; sorter = createAndSetSorter(model, table, TableViewPlugin.EVENTS_SORTING_STRING_OPTION, tableModel); int column = 0; for (RaplaTableColumn<?> col: reservationColumnPlugins) { col.init(table.getColumnModel().getColumn(column )); column++; } table.setColumnSelectionAllowed( true ); table.setRowSelectionAllowed( true); table.getTableHeader().setReorderingAllowed(false); table.registerKeyboardAction(copyListener,getString("copy"),COPY_STROKE,JComponent.WHEN_FOCUSED); table.registerKeyboardAction(cutListener,getString("cut"),CUT_STROKE,JComponent.WHEN_FOCUSED); dateChooser = new IntervalChooserPanel( context, model); dateChooser.addDateChangeListener( new DateChangeListener() { public void dateChanged( DateChangeEvent evt ) { try { update( ); } catch (RaplaException ex ){ showException( ex, getComponent()); } } }); reservationTableModel.setReservations( model.getReservations() ); Listener listener = new Listener(); table.getSelectionModel().addListSelectionListener( listener); table.addFocusListener( listener); } private final class CopyListener implements ActionListener { boolean cut; public void actionPerformed(ActionEvent evt) { List<Reservation> selectedEvents = getSelectedEvents(); Collection<Allocatable> markedAllocatables = model.getMarkedAllocatables(); try { ReservationController reservationController = getReservationController(); if ( isCut()) { reservationController.cutReservations(selectedEvents, markedAllocatables); } else { reservationController.copyReservations(selectedEvents, markedAllocatables); } } catch (RaplaException ex) { showException(ex, getComponent()); } copy(table, evt); } public boolean isCut() { return cut; } public void setCut(boolean cut) { this.cut = cut; } } class Listener implements ListSelectionListener, FocusListener { public void valueChanged(ListSelectionEvent e) { updateEditMenu(); } public void focusGained(FocusEvent e) { updateEditMenu(); } public void focusLost(FocusEvent e) { } } public static TableSorter createAndSetSorter(final CalendarModel model, final JTable table, final String sortingStringOptionName, TableModel tableModel) { final TableSorter sorter = new TableSorter( tableModel, table.getTableHeader()); String sorting = model.getOption(sortingStringOptionName); if ( sorting != null) { Enumeration<Object> e = new StringTokenizer( sorting,";", false); for (Object stringToCast:Collections.list(e)) { String string = (String) stringToCast; int length = string.length(); int column = Integer.parseInt(string.substring(0,length-1)); char order = string.charAt( length-1); if ( column < tableModel.getColumnCount()) { sorter.setSortingStatus( column, order == '-' ? TableSorter.DESCENDING : TableSorter.ASCENDING); } } } sorter.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { StringBuffer buf = new StringBuffer(); for ( int i=0;i<table.getColumnCount();i++) { int sortingStatus = sorter.getSortingStatus( i); if (sortingStatus == TableSorter.ASCENDING) { buf.append(i + "+;"); } if (sortingStatus == TableSorter.DESCENDING) { buf.append(i + "-;"); } } String sortingString = buf.toString(); ((CalendarSelectionModel)model).setOption(sortingStringOptionName, sortingString.length() > 0 ? sortingString : null); } }); table.setModel( sorter ); return sorter; } protected void updateEditMenu() { List<Reservation> selectedEvents = getSelectedEvents(); if ( selectedEvents.size() == 0 ) { return; } RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE); RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE); editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END"); newMenu.removeAll(); Point p = null; try { updateMenu(editMenu,newMenu, p); boolean canUserAllocateSomething = canUserAllocateSomething(getUser()); boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething; newMenu.setEnabled(enableNewMenu); editMenu.setEnabled(canUserAllocateSomething(getUser())); } catch (RaplaException ex) { showException (ex,getComponent()); } } public void update() throws RaplaException { reservationTableModel.setReservations( model.getReservations() ); dateChooser.update(); } public JComponent getDateSelection() { return dateChooser.getComponent(); } public void scrollToStart() { } public JComponent getComponent() { return container; } protected void updateMenu(MenuInterface editMenu,MenuInterface newMenu, Point p) throws RaplaException { List<Reservation> selectedEvents = getSelectedEvents(); Reservation focusedObject = null; if ( selectedEvents.size() == 1) { focusedObject = selectedEvents.get( 0); } MenuContext menuContext = new MenuContext( getContext(), focusedObject,getComponent(),p); menuContext.setSelectedObjects( selectedEvents); // add the new reservations wizards MenuFactory menuFactory = getService(MenuFactory.class); menuFactory.addReservationWizards( newMenu, menuContext, null); // add the edit methods if ( selectedEvents.size() != 0) { { final JMenuItem copyItem = new JMenuItem(); copyItem.addActionListener( cutListener); copyItem.setText(getString("cut")); copyItem.setIcon( getIcon("icon.cut")); editMenu.insertAfterId(copyItem, "EDIT_BEGIN"); } { final JMenuItem copyItem = new JMenuItem(); copyItem.addActionListener( copyListener); copyItem.setText(getString("copy")); copyItem.setIcon( getIcon("icon.copy")); editMenu.insertAfterId(copyItem, "EDIT_BEGIN"); } menuFactory.addObjectMenu( editMenu, menuContext, "EDIT_BEGIN"); } } List<Reservation> getSelectedEvents() { int[] rows = table.getSelectedRows(); List<Reservation> selectedEvents = new ArrayList<Reservation>(); for (int i=0;i<rows.length;i++) { Reservation reservation =reservationTableModel.getReservationAt( sorter.modelIndex(rows[i]) ); selectedEvents.add( reservation); } return selectedEvents; } class PopupTableHandler extends MouseAdapter { void showPopup(MouseEvent me) { try { RaplaPopupMenu menu= new RaplaPopupMenu(); Point p = new Point(me.getX(), me.getY()); RaplaMenu newMenu = new RaplaMenu("EDIT_BEGIN"); newMenu.setText(getString("new")); menu.add(newMenu); boolean canUserAllocateSomething = canUserAllocateSomething(getUser()); updateMenu(menu,newMenu, p); boolean enableNewMenu = newMenu.getMenuComponentCount() > 0 && canUserAllocateSomething; newMenu.setEnabled(enableNewMenu); menu.show( table, p.x, p.y); } catch (RaplaException ex) { showException (ex,getComponent()); } } /** Implementation-specific. Should be private.*/ public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** Implementation-specific. Should be private.*/ public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) showPopup(me); } /** we want to edit the reservation on double click*/ public void mouseClicked(MouseEvent me) { List<Reservation> selectedEvents = getSelectedEvents(); if (me.getClickCount() > 1 && selectedEvents.size() == 1 ) { Reservation reservation = selectedEvents.get( 0); if (!canModify( reservation )) { return; } try { getReservationController().edit( reservation ); } catch (RaplaException ex) { showException (ex,getComponent()); } } } } Printable printable = null; /** * @see java.awt.print.Printable#print(java.awt.Graphics, java.awt.print.PageFormat, int) */ public int print(Graphics graphics, PageFormat format, int page) throws PrinterException { MessageFormat f1 = new MessageFormat( model.getNonEmptyTitle()); Printable printable = table.getPrintable( JTable.PrintMode.FIT_WIDTH,f1, null ); return printable.print( graphics, format, page); } public TimeInterval getVisibleTimeInterval() { return new TimeInterval(model.getStartDate(), model.getEndDate()); } }
[ "32338891+Ayce45@users.noreply.github.com" ]
32338891+Ayce45@users.noreply.github.com
d98b704c76008536b384ba68022f190aee2d6a36
9dacd87262e7c59246eb3925eab06eb88fae313c
/src/main/java/com/pal/community/dto/ResultDTO.java
ff1f7a542a216c33b1827e5d29267336a96b6308
[]
no_license
cnpal/mycommunity
9538529c9a8b40d7567331aec43f7c325cc7920e
cd9ca186e2e94bce30dac8e97e9572065b5fc4f6
refs/heads/master
2022-07-01T02:14:25.747064
2020-08-06T08:20:06
2020-08-06T08:20:06
225,796,329
1
0
null
2022-06-17T02:42:10
2019-12-04T06:32:27
JavaScript
UTF-8
Java
false
false
1,253
java
package com.pal.community.dto; import com.pal.community.exception.CustomizeErrorCode; import com.pal.community.exception.CustomizeException; import lombok.Data; /** * @Author pal * @Date Created in 2019/12/24 14:06 * @Version: 1.0 */ @Data public class ResultDTO<T> { private Integer code; private String message; private T data; public static ResultDTO errorOf(Integer code,String message){ ResultDTO resultDTO = new ResultDTO(); resultDTO.setCode(code); resultDTO.setMessage(message); return resultDTO; } public static ResultDTO errorOf(CustomizeException e) { return errorOf(e.getCode(),e.getMessage()); } public static ResultDTO errorOf(CustomizeErrorCode errorCode) { return errorOf(errorCode.getCode(),errorCode.getMessage()); } public static ResultDTO okOf(){ ResultDTO resultDTO = new ResultDTO(); resultDTO.setCode(200); resultDTO.setMessage("请求成功"); return resultDTO; } public static <T> ResultDTO okOf(T t){ ResultDTO resultDTO = new ResultDTO(); resultDTO.setCode(200); resultDTO.setMessage("请求成功"); resultDTO.setData(t); return resultDTO; } }
[ "925978482@qq.com" ]
925978482@qq.com
3676266ccf45c980b1996d8846054ccc5b0f1ad0
22153aa413b5fdcc13d4e22bd01d82d8cb4149b5
/LeetCodeChallange/src/leetcode/explore/learn/arrayandstring/DiagonalTraverse.java
fbd6166b45c79582afc91d11f8eb7147cadd46c8
[]
no_license
thakareakshay1709/LeetCodeSolutions
a37e20c904e9c511cb10317f30d82aca31a70917
7942c3585bce65300476f8ac84ccfb00c264358f
refs/heads/master
2021-05-26T19:17:01.574116
2020-11-13T10:37:14
2020-11-13T10:37:14
254,153,377
0
0
null
null
null
null
UTF-8
Java
false
false
1,885
java
package leetcode.explore.learn.arrayandstring; import java.util.ArrayList; import java.util.Collections; public class DiagonalTraverse { public static void main(String[] args) { int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int[] result = findDiagonalOrder(matrix); for (int i = 0; i < result.length; i++) { System.out.print(result[i]+" "); } } public static int[] findDiagonalOrder(int[][] matrix) { // Check for empty matrices if (matrix == null || matrix.length == 0) { return new int[0]; } // Variables to track the size of the matrix int N = matrix.length; int M = matrix[0].length; // The two arrays as explained in the algorithm int[] result = new int[N*M]; int k = 0; ArrayList<Integer> intermediate = new ArrayList<Integer>(); // We have to go over all the elements in the first // row and the last column to cover all possible diagonals for (int d = 0; d < N + M - 1; d++) { // Clear the intermediate array every time we start // to process another diagonal intermediate.clear(); // We need to figure out the "head" of this diagonal // The elements in the first row and the last column // are the respective heads. int r = d < M ? 0 : d - M + 1; int c = d < M ? d : M - 1; // Iterate until one of the indices goes out of scope // Take note of the index math to go down the diagonal while (r < N && c > -1) { intermediate.add(matrix[r][c]); ++r; --c; } // Reverse even numbered diagonals. The // article says we have to reverse odd // numbered articles but here, the numbering // is starting from 0 :P if (d % 2 == 0) { Collections.reverse(intermediate); } for (int i = 0; i < intermediate.size(); i++) { result[k++] = intermediate.get(i); } } return result; } }
[ "thakare.akshay1709@gmail.com" ]
thakare.akshay1709@gmail.com
b7635ef949d77fd8def01317ec62d7631622e4f7
022c4f1ab9d2674802958c4633f6b9a46ad2b039
/backend/src/main/java/com/example/kvoth/myapplication/backend/MyBean.java
7ec12fed799337a632e0de7caa914485204d818c
[]
no_license
kvoththebloodless/Jokes4U
1023d5170b5f1a0f6c17420e5ac1a7aa91ad037e
d191193f5f9aeb6014b7578d96482d5cdaccba95
refs/heads/master
2020-12-25T15:17:49.627136
2016-09-30T15:56:26
2016-09-30T15:56:26
66,110,273
0
0
null
null
null
null
UTF-8
Java
false
false
304
java
package com.example.kvoth.myapplication.backend; /** * The object model for the data we are sending through endpoints */ public class MyBean { private String myData; public String getData() { return myData; } public void setData(String data) { myData = data; } }
[ "kvoththebloodless@gmail.com" ]
kvoththebloodless@gmail.com
6ee9747551aed3b3c2eabd48addd499a01a5f9a5
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Math/79/org/apache/commons/math/linear/ArrayRealVector_projection_1089.java
3058baa50446d64a0b3ee0dbeea8b4c28732b796
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
1,700
java
org apach common math linear link real vector realvector arrai version revis date arrai real vector arrayrealvector real vector realvector serializ inherit doc inheritdoc real vector realvector project real vector realvector map multipli mapmultipli dot product dotproduct dot product dotproduct
[ "hvdthong@gmail.com" ]
hvdthong@gmail.com
f65738a6c6b7e72d3d5b5f0e72237411c5fea714
b94a239a70d684333b383eca4fbee46288224413
/code100/src/code100/main1.java
ed69821fe21a013383db41648cdee3eb499b9b2e
[]
no_license
hmountainn/code100
d6a1e12759dd226fd26ffc92e4225e2523fe8a39
4afd55e77af0a5b3fe30ecc1b2bb836a2f4b171a
refs/heads/master
2023-02-09T04:40:46.223893
2020-12-27T16:05:51
2020-12-27T16:05:51
323,582,883
0
0
null
null
null
null
UTF-8
Java
false
false
289
java
package code100; import java.util.*; public class main1{ public static void main (String[] args) { String a,b; Scanner scan = new Scanner(System.in); a = scan.nextLine(); b = scan.nextLine(); System.out.print(a+":"+b); } }
[ "ghkdw@DESKTOP-RODK7K1" ]
ghkdw@DESKTOP-RODK7K1
46ce83dc6f912dffa46b65e170c28358c1691030
04bb9f74fdfbefa312e4c5540a9f943f7188595d
/src/main/java/cc2018/eurocupservice/PlayersWithGoalsRanked.java
fb1124565c6e0ca894c21ab68256064452350e7b
[]
no_license
Ilamal/Restful-football-service
45453a25972016496443b9b5c90c3f568b682445
f2e0b7be868c779307f8d74f9e20a3b5fd458325
refs/heads/master
2020-04-18T14:50:56.279809
2019-01-26T10:20:29
2019-01-26T10:20:29
167,599,388
0
0
null
null
null
null
UTF-8
Java
false
false
794
java
package cc2018.eurocupservice; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "PlayersWithGoalsRanked") public class PlayersWithGoalsRanked { }
[ "a11817838@unet.univie.ac.at" ]
a11817838@unet.univie.ac.at
e05e08bb249ed6f2ad11933719e78a9fa4e8100d
dc81d298182b2c6addc01249a59f20980af1a863
/KeyBoardDmo/keyboardlibrary/src/main/java/com/key/VibratorCompat.java
7da3e22ee09829b37fce78d551e49b65e65816fa
[]
no_license
Slzdude/KeyBoardDemo
69b6a2952d599d2a4f0931013303bb2ae51bd20f
b8e875721a85b558a5f90d16fb9e7634bf74bdfe
refs/heads/master
2023-06-08T00:16:16.278752
2017-05-13T06:04:54
2017-05-13T06:04:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
620
java
package com.key; import android.app.Service; import android.content.Context; import android.os.Vibrator; /** * Created by Administrator on 2017/4/30. */ class VibratorCompat { public static void Vibrate(final Context context, long milliseconds) { Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(milliseconds); } public static void Vibrate(final Context context, long[] pattern, boolean isRepeat) { Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(pattern, isRepeat ? 1 : -1); } }
[ "773090577@qq.com" ]
773090577@qq.com
b5e3ae92b06b018d5aa8a52140cddc81de753f41
405f054338b8bc164b995fdd229fdc4657196ab1
/src/main/java/com/pankaj/urlshortner/exceptions/UnResponsableEntityException.java
f4e50f6d3413c0b8e1d5141d8712ba328c45cc74
[]
no_license
pnkjshrm816/urlShortnerRalali
df9b5732298ca63f4727cccf8e6a0886cd132393
1d8dd5900088388dfed25ad3a05ab963916244ec
refs/heads/master
2020-08-11T21:44:15.703939
2019-10-12T11:14:12
2019-10-12T11:14:12
214,633,342
0
0
null
null
null
null
UTF-8
Java
false
false
353
java
package com.pankaj.urlshortner.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) public class UnResponsableEntityException extends RuntimeException { public UnResponsableEntityException(String message) { super(message); } }
[ "pankaj.sharma@cars24.com" ]
pankaj.sharma@cars24.com
fc1dfcc66b1b42fc022e23f0bf0e6aa4df534480
dd0208639fc94c663c20aef2adc5d8430b1bac92
/app/src/main/java/com/laioffer/eventreporter/CommentFragment.java
de855077886db789ec1b4aa11943aaabb5510605
[]
no_license
weixirui/EventReporter
d8769293d200bf3cbd5f68bf4044dc72aaa31152
c4e70bd8b866a1cf0801776f11f66779529efde9
refs/heads/master
2020-03-23T13:54:47.545128
2018-07-21T06:58:17
2018-07-21T06:58:17
141,644,772
0
0
null
null
null
null
UTF-8
Java
false
false
1,185
java
package com.laioffer.eventreporter; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; /** * A simple {@link Fragment} subclass. */ public class CommentFragment extends Fragment { private GridView mGridView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_comment, container, false); mGridView = (GridView) view.findViewById(R.id.comment_grid); mGridView.setAdapter(new EventAdapter(getActivity())); return view; } public void onItemSelected(int position){ for (int i = 0; i < mGridView.getChildCount(); i++){ if (position == i) { mGridView.getChildAt(i).setBackgroundColor(Color.BLUE); } else { mGridView.getChildAt(i).setBackgroundColor(Color.parseColor("#FAFAFA")); } } } }
[ "q576077015@gmail.com" ]
q576077015@gmail.com
f05684efcc99a4bd03344e274c15c648d5c92422
ea061388a30ab0fdfa79440b3baceb838c13599e
/desenvolvimento/backend/src/main/java/com/ramon/catchup/domain/Perfil.java
3dcceb19f77994e4b2b8fb1c45cf0846c607bb07
[]
no_license
ramoncgusmao/catchup
dba577ade63609e955a661da2c120ed16e98b157
54bbd83236047d6bf1c519a752ed9c39cad20f24
refs/heads/master
2020-12-02T18:32:17.040628
2020-01-09T02:52:58
2020-01-09T02:52:58
231,079,941
0
0
null
null
null
null
UTF-8
Java
false
false
611
java
package com.ramon.catchup.domain; public enum Perfil { ADMIN(1, "ROLE_ADMIN"), COLABORADOR(2, "ROLE_COLABORADOR"); private int cod; private String descricao; private Perfil(int cod, String descricao) { this.cod = cod; this.descricao = descricao; } public int getCod() { return cod; } public String getDescricao() { return descricao; } public static Perfil toEnum(Integer cod) { if(cod == null) { return null; } for(Perfil x : Perfil.values()) { if(cod.equals(x.getCod())) { return x; } } throw new IllegalArgumentException("id invalido: " + cod); } }
[ "ramoncgusmao@gmail.com" ]
ramoncgusmao@gmail.com
ad7806ea090ee26aae1a0596f69773b46a54e2ff
a355ef7bc1f37c1471b2ea8050115160297613ac
/BoardSevlet/src/action/ListAction.java
51ec662d1ff470c63e3af9add130b68d2c0fe3a7
[]
no_license
kyworkspace/BoardServlet
223af531f35a0e58f43294051fb2632bf49ca067
cca046db2b50a9d861b9a8300b59c8945b3fe40f
refs/heads/master
2021-10-10T12:42:57.157073
2019-01-10T23:32:44
2019-01-10T23:32:44
null
0
0
null
null
null
null
UHC
Java
false
false
2,494
java
package action; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.BoardDAO; import vo.BoardBean; /** * Servlet implementation class ListAction */ @WebServlet("/board/list.bo") public class ListAction extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ListAction() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); BoardDAO dao = BoardDAO.getInstance(); String filed = "";//일반 리스트 이기 때문에 검색값은 없음 String word = ""; String pageNum = request.getParameter("pageNum")==null?"1":request.getParameter("pageNum"); int currentPage = Integer.parseInt(pageNum); int pageSize = 10; int startRow = (currentPage-1)*pageSize+1; int endRow = (currentPage*pageSize); int cnt = dao.BoardCount(filed,word); //게시글 수 int totPage = cnt/pageSize+(cnt%pageSize==0?0:1); int blockPage = 3; int startPage = ((currentPage-1)/blockPage)*blockPage+1; int endPage = startPage+blockPage-1; if(endPage>totPage)endPage=totPage; request.setAttribute("totPage", totPage); request.setAttribute("startPage", startPage); request.setAttribute("endPage", endPage); request.setAttribute("currentPage", currentPage); request.setAttribute("blockPage",blockPage); ArrayList<BoardBean> arr = dao.boardList(startRow,endRow); request.setAttribute("list", arr); request.setAttribute("cnt", cnt); RequestDispatcher rd = request.getRequestDispatcher("nomalList.jsp"); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
[ "it@DESKTOP-6NPBPD7" ]
it@DESKTOP-6NPBPD7
f2b3b0fc9cf24172357e65a4bde265bab031b2d0
4d21ef235bbaaccf4f3b7c1f26440b4263bb62ab
/src/edu/utep/cybershare/ws/RDFAggregater/package-info.java
96bc89d5b5e324cd16c277e9cf2e17ecd7531a13
[ "BSD-2-Clause" ]
permissive
lsalayandia/wdoit
72d4924c46a0f5728f0c3f9927c3cb6f57964f41
f4c4702396496e4f5e8cb93c30febc4328d40f19
refs/heads/master
2016-09-06T09:37:40.017664
2012-06-11T16:20:03
2012-06-11T16:20:03
3,644,132
1
1
null
null
null
null
UTF-8
Java
false
false
1,555
java
/* Copyright (c) 2012, University of Texas at El Paso All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @javax.xml.bind.annotation.XmlSchema(namespace = "http://provenance.trust.utep.edu", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package edu.utep.cybershare.ws.RDFAggregater;
[ "leonardo@utep.edu" ]
leonardo@utep.edu
508f0258b90dbf2506a8e8f8035d72b9a6cd417e
4f4c13e5a7c1949ca90624d950971b021a90fa41
/src/main/java/com/medium/M152_MaximumProductSubarray.java
d270c861897d5f2687c690cd5f7370bb5d6031a9
[]
no_license
iCodeSuperman/LeetCode
a135d3c05d613cfe2ce4b4565ece6cb8265761ac
e01adfe33951ecfca198f1c67305e3fc0cb060c1
refs/heads/master
2023-06-24T18:25:01.171856
2021-07-22T14:47:26
2021-07-22T14:47:26
305,009,862
0
0
null
null
null
null
UTF-8
Java
false
false
1,220
java
package com.medium; import org.junit.Test; public class M152_MaximumProductSubarray { @Test public void t(){ int[] arr = {1, -2}; System.out.println(this.maxProduct(arr)); } public int maxProduct(int[] nums){ int len = nums.length; if(len == 1){ return nums[0]; } int[] dp_max = new int[len]; int[] dp_min = new int[len]; dp_max[0] = nums[0]; dp_min[0] = nums[0]; int res = nums[0]; for (int i = 1; i < len; i++) { int n = nums[i]; dp_max[i] = Math.max(n, Math.max(dp_max[i - 1] * n, dp_min[i - 1] * n)); dp_min[i] = Math.min(n, Math.min(dp_max[i - 1] * n, dp_min[i - 1] * n)); System.out.println("max="+dp_max[i]+"; min="+dp_min[i]); res = Math.max(res, dp_max[i]); } return res; } public int maxProduct2(int[] nums) { int res = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { int temp = 1;; for (int j = i; j < nums.length; j++) { temp *= nums[j]; res = Math.max(temp, res); } } return res; } }
[ "xujunkangchn@gmail.com" ]
xujunkangchn@gmail.com
c2a80f6d32c758fec89ff2444bb8547fa44226be
9f004c3df4413eb826c229332d95130a1d5c8457
/src/poojaJoshi/Assignmnet_14.java
d204b5d7931b0631735b5b8011afe7890508d2ce
[]
no_license
MayurSTechnoCredit/JAVATechnoJuly2021
dd8575c800e8f0cac5bab8d5ea32b25f7131dd0d
3a422553a0d09b6a99e528c73cc2b8efe260a07a
refs/heads/master
2023-08-22T14:43:37.980748
2021-10-16T06:33:34
2021-10-16T06:33:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,457
java
/*prgram 3 : print difference between max and min number from given array. int[] input = {1,11,44,23,55,99,23}; output : 98/ max no -min no */ package poojaJoshi; public class Assignmnet_14 { int max = 0; int count = 0; int min = 99; void minAndMax(int[] num) { for (int index = 0; index < num.length; index++) { if (num[index] >= max) { max = num[index]; count++; } } System.out.println("Maximum number is " +min); System.out.println("*************************************"); } void minNum(int[] num) { for (int index = 0; index < num.length; index++) { if (num[index] <= min) { min = num[index]; count--; } } System.out.println("Minimum number is " +min); System.out.println("*************************************"); } void diffMinMax(int[] num) { int max = 0; int min = 100; int diffnum = 0; for (int index = 0; index < num.length; index++) { if (num[index] > max) { max = num[index]; } } //System.out.println("no is maximum " + max); for (int index = 0; index < num.length; index++) { if (num[index] < min) { min = num[index]; } } //System.out.println("Minimum number is " + min); diffnum = max - min; System.out.println("Diff between min and max num is " + diffnum); System.out.println("*************************************"); } void oddEvenDiff(int[] number) { int odd=0; int even=0; int oddeveDiff=0; for (int index = 0; index < number.length; index++) { if (number[index] % 4 == 0) { even=number[index]; // if (number [index] > even) // even=number[index]; }else { if (number[index] % 2 !=0) if (number[index]> odd) odd=number[index]; } } System.out.println("Given values are {1,11,44,23,55,99,23,22}"); //System.out.println("Output is as below"); System.out.println("Even number is "+even); System.out.println("Odd Number is "+odd); oddeveDiff=odd-even; System.out.println("Difference of odd and even no is "+oddeveDiff); } public static void main(String[] args) { Assignmnet_14 assignmnet_14 = new Assignmnet_14(); int[] input = { 1, 11, 44, 23, 55, 99, 23 }; assignmnet_14.minAndMax(input); assignmnet_14.minNum(input); assignmnet_14.diffMinMax(input); Assignmnet_14 assignmnet_14_3_1 = new Assignmnet_14(); int[] inputoddEven = {1,11,44,23,55,99,23,22}; assignmnet_14_3_1.oddEvenDiff(inputoddEven); } }
[ "pjoshi@ccrn.com" ]
pjoshi@ccrn.com
c9a176895d79a8dd4bc70f4ea3966ad7b662974e
622a775b9584061ebddb34c3fe51c4560de536f4
/src/TemperatureException.java
ff2f6a94e16a980f842c106843405b624561b1b0
[]
no_license
jeffthebrink/HackerRank30DaysOfCodePractice
a5d72d31293b3d233a307be08c443ac5f80d6497
ff61383ee9813154b3daa5da91d7934401cdfdd9
refs/heads/master
2021-03-13T02:55:34.804455
2017-06-08T16:46:22
2017-06-08T16:46:22
91,484,023
0
0
null
null
null
null
UTF-8
Java
false
false
103
java
/** * Created by jeffbrinkley on 5/30/17. */ public class TemperatureException extends Exception { }
[ "jeffthebrink@gmail.com" ]
jeffthebrink@gmail.com
ed87a39b0933676669aaf7192477ab8ad79aabc0
bc402a970ecb3746c4a7b318f0079fc657cce9bf
/src/com/fei/prepravnispolecnost/model/DeviceDTO.java
576c1561078f51aeecc15ac5fa0139fc2255ca8a
[]
no_license
martinspilar/SpediClient
adee3c4cd5516a6f338802beaac256b20413b297
3421051fe5af5785fb762b7b144c6ecaa352a081
refs/heads/master
2020-06-03T01:44:08.104835
2013-07-13T05:28:18
2013-07-13T05:28:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,672
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.fei.prepravnispolecnost.model; /** * * @author Spilda */ public class DeviceDTO implements java.io.Serializable { private Integer id; private String serialNumber; private String brand; private String deviceModel; private String gpsLon; private String gpsLat; public DeviceDTO() { } public DeviceDTO(Integer id, String serialNumber, String brand, String deviceModel, String gpsLon, String gpsLat) { this.id = id; this.serialNumber = serialNumber; this.brand = brand; this.deviceModel = deviceModel; this.gpsLon = gpsLon; this.gpsLat = gpsLat; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getSerialNumber() { return this.serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getBrand() { return this.brand; } public void setBrand(String brand) { this.brand = brand; } public String getDeviceModel() { return this.deviceModel; } public void setDeviceModel(String deviceModel) { this.deviceModel = deviceModel; } public String getGpsLon() { return this.gpsLon; } public void setGpsLon(String gpsLon) { this.gpsLon = gpsLon; } public String getGpsLat() { return this.gpsLat; } public void setGpsLat(String gpsLat) { this.gpsLat = gpsLat; } }
[ "spilar.martin@gmail.com" ]
spilar.martin@gmail.com
6f5dfbaf93807933eace43d70bdff955cfe93601
f17e5144f23c773874f48e6559b34152e983f3d0
/src/com/ipassistat/ipa/bean/response/entity/ProductCommentLabel.java
5c0c2d21a7b515446d428b995dbcb72a2ece5bcd
[]
no_license
shipeifei/ipa
3eb357498fed7e43b0ded6753c4f711db66e383b
5cee4707a9dd7d564593161dc32a419d913186bc
refs/heads/master
2021-01-10T03:50:39.698182
2015-06-04T09:47:51
2015-06-04T09:47:51
35,982,903
0
0
null
null
null
null
UTF-8
Java
false
false
507
java
package com.ipassistat.ipa.bean.response.entity; /** * 印象标签实体类 * @author wr * */ public class ProductCommentLabel { private int label_amount;//印象标签数量 private String label;//印象标签名称 public int getLabel_amount() { return label_amount; } public void setLabel_amount(int label_amount) { this.label_amount = label_amount; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } }
[ "shipeifei_gonghe@163.com" ]
shipeifei_gonghe@163.com
2d86048de29a1d2037585e8ecbf8a8baa1dab355
32e3398946b21b297f35e600e037803b043af32f
/app/src/main/java/cn/itcast/mobilesafe/utils/AsyncTask2.java
7d97ca5a1ff9e6ec412156d4d2ae7c1851eebc28
[]
no_license
luhu888/XuanFengManager-APP
5ed8a9855843b76620eaf78f0578cc79f22402fa
6d3174a3ee51002341a72d20c340e2a00ada221e
refs/heads/master
2021-08-28T19:00:21.181348
2017-12-13T01:32:42
2017-12-13T01:32:42
88,524,947
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package cn.itcast.mobilesafe.utils; import android.os.Handler; public abstract class AsyncTask2 { private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { //后台任务执行后被调用. onPostExecute(); }; }; /** * 耗时操作执行之前调用的方法. */ public abstract void onPreExecute(); /** * 耗时任务执行完毕后调用的方法. */ public abstract void onPostExecute(); /** * 执行一个后台的耗时的任务 */ public abstract void doInBackground(); public void execute(){ onPreExecute(); new Thread(){ public void run() { doInBackground(); //通知耗时任务执行完毕了. handler.sendEmptyMessage(0); }; }.start(); } }
[ "luhu0105@gmail.com" ]
luhu0105@gmail.com
45b5e42c584b464f6e2a40541b5ceee53ce594ea
f0d095f13751bd3e3320f104c33c989f9fb9b376
/src/main/java/org/elasticsearch/action/admin/indices/gateway/snapshot/TransportGatewaySnapshotAction.java
389e20e845254d61bdd92a95c756fb66c07e4f4e
[ "Apache-2.0" ]
permissive
wilsolutions/elasticsearch
1bec2261a1ed15be7663859ad06f3af4e7bc79f7
bb63d38a659dcb5711f4ab4d1db22bd0f4c2bc52
refs/heads/master
2021-01-17T05:31:58.278350
2011-12-28T20:20:09
2011-12-28T20:20:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,467
java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.gateway.snapshot; import com.google.common.collect.Lists; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.TransportActions; import org.elasticsearch.action.support.DefaultShardOperationFailedException; import org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException; import org.elasticsearch.action.support.broadcast.TransportBroadcastOperationAction; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.routing.GroupShardsIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.gateway.IndexShardGatewayService; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import java.util.List; import java.util.concurrent.atomic.AtomicReferenceArray; /** * */ public class TransportGatewaySnapshotAction extends TransportBroadcastOperationAction<GatewaySnapshotRequest, GatewaySnapshotResponse, ShardGatewaySnapshotRequest, ShardGatewaySnapshotResponse> { private final IndicesService indicesService; @Inject public TransportGatewaySnapshotAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; } @Override protected String executor() { return ThreadPool.Names.MANAGEMENT; } @Override protected String transportAction() { return TransportActions.Admin.Indices.Gateway.SNAPSHOT; } @Override protected String transportShardAction() { return "indices/gateway/snapshot/shard"; } @Override protected GatewaySnapshotRequest newRequest() { return new GatewaySnapshotRequest(); } @Override protected boolean ignoreNonActiveExceptions() { return true; } @Override protected GatewaySnapshotResponse newResponse(GatewaySnapshotRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) { int successfulShards = 0; int failedShards = 0; List<ShardOperationFailedException> shardFailures = null; for (int i = 0; i < shardsResponses.length(); i++) { Object shardResponse = shardsResponses.get(i); if (shardResponse == null) { // non active shard, ignore } else if (shardResponse instanceof BroadcastShardOperationFailedException) { failedShards++; if (shardFailures == null) { shardFailures = Lists.newArrayList(); } shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse)); } else { successfulShards++; } } return new GatewaySnapshotResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures); } @Override protected ShardGatewaySnapshotRequest newShardRequest() { return new ShardGatewaySnapshotRequest(); } @Override protected ShardGatewaySnapshotRequest newShardRequest(ShardRouting shard, GatewaySnapshotRequest request) { return new ShardGatewaySnapshotRequest(shard.index(), shard.id()); } @Override protected ShardGatewaySnapshotResponse newShardResponse() { return new ShardGatewaySnapshotResponse(); } @Override protected ShardGatewaySnapshotResponse shardOperation(ShardGatewaySnapshotRequest request) throws ElasticSearchException { IndexShardGatewayService shardGatewayService = indicesService.indexServiceSafe(request.index()) .shardInjectorSafe(request.shardId()).getInstance(IndexShardGatewayService.class); shardGatewayService.snapshot("api"); return new ShardGatewaySnapshotResponse(request.index(), request.shardId()); } /** * The snapshot request works against all primary shards. */ @Override protected GroupShardsIterator shards(GatewaySnapshotRequest request, String[] concreteIndices, ClusterState clusterState) { return clusterState.routingTable().activePrimaryShardsGrouped(concreteIndices, true); } }
[ "kimchy@gmail.com" ]
kimchy@gmail.com
05927591d28a897d5759683eea64e16e74d1b3f7
9a2fe19f0aa93e3df25abd4ac3845a3e38758a8a
/produver consumer/src/Threadexample.java
b9f96c60093d31e1d20d4a8773c952a4c3fe3639
[]
no_license
Akash26-dev/heygithub2
e6e6916c16a262410cfc81897b40fe46de780fa2
23b56091f99160bfb0a6f818c71234da58acf8a7
refs/heads/master
2023-06-27T12:08:55.585321
2021-07-14T10:20:43
2021-07-14T10:20:43
385,901,814
0
0
null
null
null
null
UTF-8
Java
false
false
3,152
java
import java.util.LinkedList; public class Threadexample { public static void main(String[] args) throws InterruptedException { // Object of a class that has both produce() // and consume() methods final PC pc = new PC(); // Create producer thread Thread t1 = new Thread(new Runnable() { @Override public void run() { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // Create consumer thread Thread t2 = new Thread(new Runnable() { @Override public void run() { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } } }); // Start both threads t1.start(); t2.start(); // t1 finishes before t2 t1.join(); t2.join(); } // This class has a list, producer (adds items to list // and consumber (removes items). public static class PC { // Create a list shared by producer and consumer // Size of list is 2. LinkedList<Integer> list = new LinkedList<>(); int capacity = 2; // Function called by producer thread public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { // producer thread waits while list // is full while (list.size() == capacity) wait(); System.out.println("Producer produced-" + value); // to insert the jobs in the list list.add(value++); // notifies the consumer thread that // now it can start consuming notify(); // makes the working of program easier // to understand Thread.sleep(1000); } } } // Function called by consumer thread public void consume() throws InterruptedException { while (true) { synchronized (this) { // consumer thread waits while list // is empty while (list.size() == 0) wait(); // to retrive the ifrst job in the list int val = list.removeFirst(); System.out.println("Consumer consumed-" + val); // Wake up producer thread notify(); // and sleep Thread.sleep(1000); } } } } }
[ "akash@akash-Vostro-3558" ]
akash@akash-Vostro-3558