blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
cd9bfe24bfb2c833307bfd5f1d88367a6fb8ee7d
266,287,978,122
1fbd39c972cca0dce087f008d85c52a881d3e2fa
/launcher/src/main/java/net/reichholf/repola/activities/ApplicationList.java
bc37ecba4e2f4fe79598312c82a5a070394ed3d5
[ "Apache-2.0" ]
permissive
AndrewGillisSoftware/repola
https://github.com/AndrewGillisSoftware/repola
b6f7567caa79ac8624ead45ef45394a98e433cf6
61c75971da0d9e42a67b1006f227f96485416d43
refs/heads/master
2023-01-20T06:12:32.010000
2020-11-22T12:34:38
2020-11-24T09:11:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Simple TV Launcher * Copyright 2017 Alexandre Del Bigio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.reichholf.repola.activities; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.View; import net.reichholf.repola.AppInfo; import net.reichholf.repola.R; import net.reichholf.repola.Setup; import net.reichholf.repola.adapter.AppInfoAdapter; import net.reichholf.repola.adapter.ItemClickSupport; import net.reichholf.repola.databinding.ApplicationsBinding; import net.reichholf.repola.views.models.ApplicationViewModel; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class ApplicationList extends AppCompatActivity implements View.OnClickListener, ItemClickSupport.OnItemClickListener, ItemClickSupport.OnItemLongClickListener { public static final String PACKAGE_NAME = "package_name"; public static final String APPLICATION_NUMBER = "application"; public static final String VIEW_TYPE = "view_type"; public static final String DELETE = "delete"; public static final String SHOW_DELETE = "show_delete"; // public static final int VIEW_GRID = 0; public static final int VIEW_LIST = 1; // private int mApplication = -1; private int mViewType = 0; private ApplicationsBinding mBinding; private AppInfoAdapter mAdapter; private ItemClickSupport mItemClickSupport; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle args = intent.getExtras(); mBinding = ApplicationsBinding.inflate(getLayoutInflater()); setContentView(mBinding.getRoot()); if (args != null) { if (args.containsKey(APPLICATION_NUMBER)) mApplication = args.getInt(APPLICATION_NUMBER); if (args.containsKey(VIEW_TYPE)) mViewType = args.getInt(VIEW_TYPE); if (args.getBoolean(SHOW_DELETE, true)) { mBinding.cancel.setOnClickListener(this); mBinding.delete.setOnClickListener(this); } else { mBinding.bottomPanel.setVisibility(View.GONE); } } int spans = new Setup(this).getAllAppColumns(); RecyclerView.LayoutManager lm = mViewType == VIEW_LIST ? new LinearLayoutManager(this) : new GridLayoutManager(this, spans); mBinding.list.setLayoutManager(lm); mAdapter = new AppInfoAdapter(new ArrayList<>(), mViewType == VIEW_LIST ? R.layout.list_item : R.layout.grid_item); mBinding.list.setAdapter(mAdapter); mItemClickSupport = ItemClickSupport.addTo(mBinding.list) .setOnItemClickListener(this) .setOnItemLongClickListener(this); ApplicationViewModel model = new ViewModelProvider(this).get(ApplicationViewModel.class); model.getApplications().observe(this, applications -> { onApplicationListReady(applications); }); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.delete) { Intent data = new Intent(); data.putExtra(DELETE, true); data.putExtra(APPLICATION_NUMBER, mApplication); if (getParent() == null) setResult(Activity.RESULT_OK, data); else getParent().setResult(Activity.RESULT_OK, data); finish(); } else if (id == R.id.cancel) { if (getParent() == null) setResult(Activity.RESULT_CANCELED); else getParent().setResult(Activity.RESULT_CANCELED); finish(); } } public void onApplicationListReady(List<AppInfo> applications) { mAdapter.updateApps(applications); } @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { AppInfo appInfo = (AppInfo) v.getTag(); Intent data = new Intent(); data.putExtra(PACKAGE_NAME, appInfo.getPackageName()); data.putExtra(APPLICATION_NUMBER, mApplication); if (getParent() == null) { setResult(Activity.RESULT_OK, data); } else { getParent().setResult(Activity.RESULT_OK, data); } finish(); } @Override public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) { AppInfo appInfo = (AppInfo) v.getTag(); // Create intent to start new activity Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + appInfo.getPackageName())); startActivity(intent); return true; } }
UTF-8
Java
5,017
java
ApplicationList.java
Java
[ { "context": "/*\n * Simple TV Launcher\n * Copyright 2017 Alexandre Del Bigio\n *\n * Licensed under the Apache License, Version ", "end": 62, "score": 0.9998718500137329, "start": 43, "tag": "NAME", "value": "Alexandre Del Bigio" } ]
null
[]
/* * Simple TV Launcher * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.reichholf.repola.activities; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.View; import net.reichholf.repola.AppInfo; import net.reichholf.repola.R; import net.reichholf.repola.Setup; import net.reichholf.repola.adapter.AppInfoAdapter; import net.reichholf.repola.adapter.ItemClickSupport; import net.reichholf.repola.databinding.ApplicationsBinding; import net.reichholf.repola.views.models.ApplicationViewModel; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class ApplicationList extends AppCompatActivity implements View.OnClickListener, ItemClickSupport.OnItemClickListener, ItemClickSupport.OnItemLongClickListener { public static final String PACKAGE_NAME = "package_name"; public static final String APPLICATION_NUMBER = "application"; public static final String VIEW_TYPE = "view_type"; public static final String DELETE = "delete"; public static final String SHOW_DELETE = "show_delete"; // public static final int VIEW_GRID = 0; public static final int VIEW_LIST = 1; // private int mApplication = -1; private int mViewType = 0; private ApplicationsBinding mBinding; private AppInfoAdapter mAdapter; private ItemClickSupport mItemClickSupport; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle args = intent.getExtras(); mBinding = ApplicationsBinding.inflate(getLayoutInflater()); setContentView(mBinding.getRoot()); if (args != null) { if (args.containsKey(APPLICATION_NUMBER)) mApplication = args.getInt(APPLICATION_NUMBER); if (args.containsKey(VIEW_TYPE)) mViewType = args.getInt(VIEW_TYPE); if (args.getBoolean(SHOW_DELETE, true)) { mBinding.cancel.setOnClickListener(this); mBinding.delete.setOnClickListener(this); } else { mBinding.bottomPanel.setVisibility(View.GONE); } } int spans = new Setup(this).getAllAppColumns(); RecyclerView.LayoutManager lm = mViewType == VIEW_LIST ? new LinearLayoutManager(this) : new GridLayoutManager(this, spans); mBinding.list.setLayoutManager(lm); mAdapter = new AppInfoAdapter(new ArrayList<>(), mViewType == VIEW_LIST ? R.layout.list_item : R.layout.grid_item); mBinding.list.setAdapter(mAdapter); mItemClickSupport = ItemClickSupport.addTo(mBinding.list) .setOnItemClickListener(this) .setOnItemLongClickListener(this); ApplicationViewModel model = new ViewModelProvider(this).get(ApplicationViewModel.class); model.getApplications().observe(this, applications -> { onApplicationListReady(applications); }); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.delete) { Intent data = new Intent(); data.putExtra(DELETE, true); data.putExtra(APPLICATION_NUMBER, mApplication); if (getParent() == null) setResult(Activity.RESULT_OK, data); else getParent().setResult(Activity.RESULT_OK, data); finish(); } else if (id == R.id.cancel) { if (getParent() == null) setResult(Activity.RESULT_CANCELED); else getParent().setResult(Activity.RESULT_CANCELED); finish(); } } public void onApplicationListReady(List<AppInfo> applications) { mAdapter.updateApps(applications); } @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { AppInfo appInfo = (AppInfo) v.getTag(); Intent data = new Intent(); data.putExtra(PACKAGE_NAME, appInfo.getPackageName()); data.putExtra(APPLICATION_NUMBER, mApplication); if (getParent() == null) { setResult(Activity.RESULT_OK, data); } else { getParent().setResult(Activity.RESULT_OK, data); } finish(); } @Override public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) { AppInfo appInfo = (AppInfo) v.getTag(); // Create intent to start new activity Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + appInfo.getPackageName())); startActivity(intent); return true; } }
5,004
0.754834
0.752442
150
32.446667
27.473997
168
false
false
0
0
0
0
0
0
1.94
false
false
12
9faddefeb5b4b6886e8207fe8fcdfc592cd02ecd
31,808,527,796,735
9e77d3f9cd6a34bacdc4973648aab8ee156cfe1c
/src/main/java/io/safari94/trimblems/soap/documents/DocumentData.java
7a601fd59804f01877ccd9486eb41d234077045f
[]
no_license
Safari94/Trimble-Microservice
https://github.com/Safari94/Trimble-Microservice
727a6b24ddc7787e979696bf4e91bfe477b932a0
86ad81c2168c5a69d0eb6c1ea974b798dc261695
refs/heads/master
2023-04-16T17:44:11.640000
2020-04-17T12:27:16
2020-04-17T12:27:16
256,487,829
0
0
null
false
2021-04-26T20:11:09
2020-04-17T11:46:21
2020-04-17T12:27:33
2021-04-26T20:11:08
37
0
0
1
Java
false
false
package io.safari94.trimblems.soap.documents; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.Arrays; /** * <p>Java class for DocumentData complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DocumentData"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="fileName" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="fileType" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="fileContent" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/&gt; * &lt;element name="isPermanent" type="{http://www.w3.org/2001/XMLSchema}boolean"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocumentData", namespace = "http://fleetworks.acunia.com/fleet/types", propOrder = { "fileName", "fileType", "fileContent", "isPermanent" }) public class DocumentData { @XmlElement(required = true) protected String fileName; @XmlElement(required = true) protected String fileType; @XmlElement(required = true) protected byte[] fileContent; protected boolean isPermanent; @Override public String toString() { return "DocumentData{" + "fileName='" + fileName + '\'' + ", fileType='" + fileType + '\'' + ", fileContent=" + Arrays.toString(fileContent) + ", isPermanent=" + isPermanent + '}'; } /** * Gets the value of the fileName property. * * @return * possible object is * {@link String } * */ public String getFileName() { return fileName; } /** * Sets the value of the fileName property. * * @param value * allowed object is * {@link String } * */ public void setFileName(String value) { this.fileName = value; } /** * Gets the value of the fileType property. * * @return * possible object is * {@link String } * */ public String getFileType() { return fileType; } /** * Sets the value of the fileType property. * * @param value * allowed object is * {@link String } * */ public void setFileType(String value) { this.fileType = value; } /** * Gets the value of the fileContent property. * * @return * possible object is * byte[] */ public byte[] getFileContent() { return fileContent; } /** * Sets the value of the fileContent property. * * @param value * allowed object is * byte[] */ public void setFileContent(byte[] value) { this.fileContent = value; } /** * Gets the value of the isPermanent property. * */ public boolean isIsPermanent() { return isPermanent; } /** * Sets the value of the isPermanent property. * */ public void setIsPermanent(boolean value) { this.isPermanent = value; } }
UTF-8
Java
3,584
java
DocumentData.java
Java
[]
null
[]
package io.safari94.trimblems.soap.documents; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.Arrays; /** * <p>Java class for DocumentData complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DocumentData"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="fileName" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="fileType" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="fileContent" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/&gt; * &lt;element name="isPermanent" type="{http://www.w3.org/2001/XMLSchema}boolean"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocumentData", namespace = "http://fleetworks.acunia.com/fleet/types", propOrder = { "fileName", "fileType", "fileContent", "isPermanent" }) public class DocumentData { @XmlElement(required = true) protected String fileName; @XmlElement(required = true) protected String fileType; @XmlElement(required = true) protected byte[] fileContent; protected boolean isPermanent; @Override public String toString() { return "DocumentData{" + "fileName='" + fileName + '\'' + ", fileType='" + fileType + '\'' + ", fileContent=" + Arrays.toString(fileContent) + ", isPermanent=" + isPermanent + '}'; } /** * Gets the value of the fileName property. * * @return * possible object is * {@link String } * */ public String getFileName() { return fileName; } /** * Sets the value of the fileName property. * * @param value * allowed object is * {@link String } * */ public void setFileName(String value) { this.fileName = value; } /** * Gets the value of the fileType property. * * @return * possible object is * {@link String } * */ public String getFileType() { return fileType; } /** * Sets the value of the fileType property. * * @param value * allowed object is * {@link String } * */ public void setFileType(String value) { this.fileType = value; } /** * Gets the value of the fileContent property. * * @return * possible object is * byte[] */ public byte[] getFileContent() { return fileContent; } /** * Sets the value of the fileContent property. * * @param value * allowed object is * byte[] */ public void setFileContent(byte[] value) { this.fileContent = value; } /** * Gets the value of the isPermanent property. * */ public boolean isIsPermanent() { return isPermanent; } /** * Sets the value of the isPermanent property. * */ public void setIsPermanent(boolean value) { this.isPermanent = value; } }
3,584
0.571987
0.563895
146
23.541096
22.305208
101
false
false
0
0
0
0
0
0
0.349315
false
false
12
7e5be616f0966b92e3e94570047d01dfa0d1f921
31,808,527,796,116
4ff2569ce6cd43ef744050fcb231d2622be67bbe
/lesson04/src/main/java/ua/lviv/lgs/JornalsDAO.java
c6162eca1b58a965617baad8409f5dfd156d403e
[]
no_license
pavlivmykola/Java_Advanced_Lesson_11
https://github.com/pavlivmykola/Java_Advanced_Lesson_11
3c0a6c99f43d250e2b165fcebb3c6563a6a93229
eeb70a15b66228a775841bec22bf599cdd12b5d0
refs/heads/master
2020-04-30T11:15:42.904000
2019-03-17T12:31:35
2019-03-17T12:31:35
175,887,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.lviv.lgs; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JornalsDAO { static String READ_ALL = "select * from jornals"; static String INSERT = "insert into jornals (name,reit,price,description) values (?,?,?,?)"; static String READ_BY_ID = "select * from jornals where id=?"; static String UPDATE_BY_ID = "update jornals set name=?, reit=?,price=?,description=? where id=?"; static String DELETE_BY_ID = "delete from jornals where id=?"; private Connection connection; private PreparedStatement preparedStatement; public JornalsDAO(Connection connection) { this.connection = connection; } public void insert(Jornals jornal) { try { preparedStatement = connection.prepareStatement(INSERT); preparedStatement.setString(1, jornal.getName()); preparedStatement.setInt(2, jornal.getReit()); preparedStatement.setDouble(3, jornal.getPrice()); preparedStatement.setString(4, jornal.getDescription()); preparedStatement.executeUpdate(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public Jornals read(int id) { try { preparedStatement = connection.prepareStatement(READ_BY_ID); preparedStatement.setInt(1, id); ResultSet result = preparedStatement.executeQuery(); result.next(); return JornalsMapper.map(result); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } return null; } public void update(Jornals jornal) { try { preparedStatement = connection.prepareStatement(UPDATE_BY_ID); preparedStatement.setString(1, jornal.getName()); preparedStatement.setInt(2, jornal.getReit()); preparedStatement.setDouble(3, jornal.getPrice()); preparedStatement.setString(4, jornal.getDescription()); preparedStatement.setInt(5, jornal.getId()); preparedStatement.executeUpdate(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public void delete(Jornals jornal) { try { preparedStatement = connection.prepareStatement(DELETE_BY_ID); preparedStatement.setInt(1, jornal.getId()); preparedStatement.executeQuery(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public List<Jornals> readAll() { List<Jornals> listOfJornals = new ArrayList<>(); try { preparedStatement = connection.prepareStatement(READ_ALL); ResultSet result = preparedStatement.executeQuery(); while (result.next()) { listOfJornals.add(JornalsMapper.map(result)); } } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } return listOfJornals; } }
UTF-8
Java
2,827
java
JornalsDAO.java
Java
[]
null
[]
package ua.lviv.lgs; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JornalsDAO { static String READ_ALL = "select * from jornals"; static String INSERT = "insert into jornals (name,reit,price,description) values (?,?,?,?)"; static String READ_BY_ID = "select * from jornals where id=?"; static String UPDATE_BY_ID = "update jornals set name=?, reit=?,price=?,description=? where id=?"; static String DELETE_BY_ID = "delete from jornals where id=?"; private Connection connection; private PreparedStatement preparedStatement; public JornalsDAO(Connection connection) { this.connection = connection; } public void insert(Jornals jornal) { try { preparedStatement = connection.prepareStatement(INSERT); preparedStatement.setString(1, jornal.getName()); preparedStatement.setInt(2, jornal.getReit()); preparedStatement.setDouble(3, jornal.getPrice()); preparedStatement.setString(4, jornal.getDescription()); preparedStatement.executeUpdate(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public Jornals read(int id) { try { preparedStatement = connection.prepareStatement(READ_BY_ID); preparedStatement.setInt(1, id); ResultSet result = preparedStatement.executeQuery(); result.next(); return JornalsMapper.map(result); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } return null; } public void update(Jornals jornal) { try { preparedStatement = connection.prepareStatement(UPDATE_BY_ID); preparedStatement.setString(1, jornal.getName()); preparedStatement.setInt(2, jornal.getReit()); preparedStatement.setDouble(3, jornal.getPrice()); preparedStatement.setString(4, jornal.getDescription()); preparedStatement.setInt(5, jornal.getId()); preparedStatement.executeUpdate(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public void delete(Jornals jornal) { try { preparedStatement = connection.prepareStatement(DELETE_BY_ID); preparedStatement.setInt(1, jornal.getId()); preparedStatement.executeQuery(); } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } } public List<Jornals> readAll() { List<Jornals> listOfJornals = new ArrayList<>(); try { preparedStatement = connection.prepareStatement(READ_ALL); ResultSet result = preparedStatement.executeQuery(); while (result.next()) { listOfJornals.add(JornalsMapper.map(result)); } } catch (SQLException ex) { CustomLoggerFile.logError(ex.getMessage()); } return listOfJornals; } }
2,827
0.708879
0.704988
90
29.411112
23.501722
99
false
false
0
0
0
0
0
0
2.422222
false
false
12
d03d760105ba95577d7322af657f19a13edbdd5c
25,658,134,654,244
f28a3237d46da12f416b9a100791a8534a828383
/core/src/com/maicard/security/entity/PasswordLog.java
5c0a056cd007d6c0e17f22aef98a93afe57cd09d
[]
no_license
netsnakecn/eis
https://github.com/netsnakecn/eis
73d3c0f4b4d646c48c061216fe6e132e72be5242
23370fd1597d8057f4481d2f5f6ae25bd3acdddb
refs/heads/master
2023-03-12T16:52:31.221000
2023-01-06T01:48:38
2023-01-06T01:48:38
155,054,235
0
1
null
false
2023-02-22T08:07:30
2018-10-28T09:27:16
2023-01-05T11:55:00
2023-02-22T08:07:29
717
0
1
7
Java
false
false
package com.maicard.security.entity; import java.util.Date; import com.maicard.core.entity.BaseEntity; /** * 对用户密码的记录 * 应以明文形式存放 * 用于控制用户密码的使用期限和禁止重复使用之前密码等 * * * @author NetSnake * @date 2015年12月27日 * */ public class PasswordLog extends BaseEntity{ private static final long serialVersionUID = 4334988100407731204L; private int passwordLogId; private long uuid; private String password; private Date createTime; public int getPasswordLogId() { return passwordLogId; } public void setPasswordLogId(int passwordLogId) { this.passwordLogId = passwordLogId; } public long getUuid() { return uuid; } public void setUuid(long uuid) { this.uuid = uuid; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
UTF-8
Java
1,056
java
PasswordLog.java
Java
[ { "context": "形式存放\n * 用于控制用户密码的使用期限和禁止重复使用之前密码等\n *\n *\n * @author NetSnake\n * @date 2015年12月27日\n *\n */\npublic class Password", "end": 188, "score": 0.9994999170303345, "start": 180, "tag": "USERNAME", "value": "NetSnake" }, { "context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic Date getCreateTime() {\n\t\treturn crea", "end": 819, "score": 0.9330387115478516, "start": 811, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.maicard.security.entity; import java.util.Date; import com.maicard.core.entity.BaseEntity; /** * 对用户密码的记录 * 应以明文形式存放 * 用于控制用户密码的使用期限和禁止重复使用之前密码等 * * * @author NetSnake * @date 2015年12月27日 * */ public class PasswordLog extends BaseEntity{ private static final long serialVersionUID = 4334988100407731204L; private int passwordLogId; private long uuid; private String password; private Date createTime; public int getPasswordLogId() { return passwordLogId; } public void setPasswordLogId(int passwordLogId) { this.passwordLogId = passwordLogId; } public long getUuid() { return uuid; } public void setUuid(long uuid) { this.uuid = uuid; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
1,058
0.727273
0.69938
62
14.612904
16.390747
67
false
false
0
0
0
0
0
0
0.935484
false
false
12
b49a36c1f4cf1c86d06d1b0a541953644dff160c
7,146,825,585,301
17b62a0b71d19ece87ed8dd43197ac46f2d04b7e
/src/AlgoritmerØvinger/TreeAndQueue_4/Uttrykkstre.java
548f3501c632b7a86e8f4b1771955e5cfc6a797d
[]
no_license
seljeseth/Algoritmer
https://github.com/seljeseth/Algoritmer
ea1f333e7b34502174396dbbcd1a7f5c6a6b37c5
d2ecbd49d3a5a23b6d2b30512ef6aef4f8ec2afa
refs/heads/master
2022-04-07T20:22:38.981000
2020-02-11T23:03:28
2020-02-11T23:03:28
239,881,946
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package AlgoritmerØvinger.TreeAndQueue_4; //OPPGAVE 2 public class Uttrykkstre { TreNode rot; public Uttrykkstre() { rot = new TreNode('*'); rot.venstre = new TreNode('*'); rot.venstre.venstre = new TreNode(3); rot.venstre.høyre = new TreNode('+'); rot.venstre.høyre.venstre = new TreNode(2); rot.venstre.høyre.høyre = new TreNode(4); rot.høyre = new TreNode('-'); rot.høyre.venstre = new TreNode(7); rot.høyre.høyre = new TreNode('*'); rot.høyre.høyre.høyre = new TreNode(2); rot.høyre.høyre.venstre = new TreNode(2); } public boolean sjekkLøvnode(TreNode n) { if(n.venstre == null && n.høyre == null) { return true; } return false; } public String printFormel(TreNode n) { String utskrift = ""; if(sjekkLøvnode(n) == true) { utskrift += n.element; return utskrift; } utskrift += "(" + printFormel(n.venstre); utskrift += n.element; utskrift += printFormel(n.høyre) + ")"; return utskrift; } public int finnVerdi(TreNode n) { if (sjekkLøvnode(n) == true) { return (Integer) n.element; } int venstre = finnVerdi(n.venstre); int høyre = finnVerdi(n.høyre); char tegn = (Character) n.getElement(); switch(tegn) { case '+': return venstre + høyre; case '-': return venstre - høyre; case '*': return venstre * høyre; case '/': return venstre / høyre; } return -1; } public static void main(String[] args) { Uttrykkstre test = new Uttrykkstre(); System.out.println(test.printFormel(test.rot) + " = " + test.finnVerdi(test.rot)); } }
UTF-8
Java
1,903
java
Uttrykkstre.java
Java
[]
null
[]
package AlgoritmerØvinger.TreeAndQueue_4; //OPPGAVE 2 public class Uttrykkstre { TreNode rot; public Uttrykkstre() { rot = new TreNode('*'); rot.venstre = new TreNode('*'); rot.venstre.venstre = new TreNode(3); rot.venstre.høyre = new TreNode('+'); rot.venstre.høyre.venstre = new TreNode(2); rot.venstre.høyre.høyre = new TreNode(4); rot.høyre = new TreNode('-'); rot.høyre.venstre = new TreNode(7); rot.høyre.høyre = new TreNode('*'); rot.høyre.høyre.høyre = new TreNode(2); rot.høyre.høyre.venstre = new TreNode(2); } public boolean sjekkLøvnode(TreNode n) { if(n.venstre == null && n.høyre == null) { return true; } return false; } public String printFormel(TreNode n) { String utskrift = ""; if(sjekkLøvnode(n) == true) { utskrift += n.element; return utskrift; } utskrift += "(" + printFormel(n.venstre); utskrift += n.element; utskrift += printFormel(n.høyre) + ")"; return utskrift; } public int finnVerdi(TreNode n) { if (sjekkLøvnode(n) == true) { return (Integer) n.element; } int venstre = finnVerdi(n.venstre); int høyre = finnVerdi(n.høyre); char tegn = (Character) n.getElement(); switch(tegn) { case '+': return venstre + høyre; case '-': return venstre - høyre; case '*': return venstre * høyre; case '/': return venstre / høyre; } return -1; } public static void main(String[] args) { Uttrykkstre test = new Uttrykkstre(); System.out.println(test.printFormel(test.rot) + " = " + test.finnVerdi(test.rot)); } }
1,903
0.527689
0.522897
74
24.378378
19.60881
90
false
false
0
0
0
0
0
0
0.445946
false
false
12
5e472fd60dd439de1f37078126fe0c97ab2417c5
10,720,238,434,331
1c47bf9eb1b6e40db51ab72b59487344a9b2a497
/app/src/main/java/com/example/calixta/flix/MovieDetail.java
e82f7f2e62cae28a9525aea265c3948b2f3d51b3
[]
no_license
dia-bolix/Flix
https://github.com/dia-bolix/Flix
d7bc0e0b26c7ac929dd45754656d3c265af53c02
3ab104ed0a4e4756ef78eadd86881f700b41211c
refs/heads/master
2020-04-17T10:40:16.620000
2019-01-26T18:19:57
2019-01-26T18:19:57
166,509,280
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.calixta.flix; import android.os.Bundle; import android.widget.RatingBar; import android.widget.TextView; import com.example.calixta.flix.models.Movie; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcels; import cz.msebera.android.httpclient.Header; public class MovieDetail extends YouTubeBaseActivity { TextView detail_title; TextView detail_overview; RatingBar ratingBar; Movie movie; public static final String key = "a07e22bc18f5cb106bfe4cc1f83ad8ed"; public static final String trailer_api = "https://api.themoviedb.org/3/movie/%d/videos?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed"; YouTubePlayerView YoutubePlayerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail); detail_title = findViewById(R.id.detail_title); detail_overview = findViewById(R.id.detail_overview); ratingBar = findViewById(R.id.ratingBar); YoutubePlayerView = findViewById(R.id.player); //now we have the same movie object from the previous activity in our detail activity movie = (Movie) Parcels.unwrap(getIntent().getParcelableExtra("movie")); detail_title.setText(movie.getTitle()); detail_overview.setText(movie.getOverview()); ratingBar.setRating(movie.getRating()); //making network requests using the api link above AsyncHttpClient client = new AsyncHttpClient(); client.get(String.format(trailer_api, movie.getId()), new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); //parsing here try { JSONArray res = response.getJSONArray("results"); //if there are no trailers to show then show the poster if (res.length() == 0) { return; } //otherwise, get the trailer link in the json, and cue it in the initialize youtube method JSONObject movieTrailer = res.getJSONObject(0); String youtubekey = movieTrailer.getString("key"); initalizeYoutube(youtubekey); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); } } ); } private void initalizeYoutube(final String youtubekey) { //here we are actually playing videos YoutubePlayerView.initialize(key, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { youTubePlayer.cueVideo(youtubekey); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { } }); } }
UTF-8
Java
4,027
java
MovieDetail.java
Java
[ { "context": "ovie movie;\n public static final String key = \"a07e22bc18f5cb106bfe4cc1f83ad8ed\";\n public static final String trailer_api = \"", "end": 911, "score": 0.9997637271881104, "start": 879, "tag": "KEY", "value": "a07e22bc18f5cb106bfe4cc1f83ad8ed" }, { "context": "ps://api.themoviedb.org/3/movie/%d/videos?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed\";\n YouTubePlayerView YoutubePlayerView;\n\n @", "end": 1046, "score": 0.9997623562812805, "start": 1014, "tag": "KEY", "value": "a07e22bc18f5cb106bfe4cc1f83ad8ed" } ]
null
[]
package com.example.calixta.flix; import android.os.Bundle; import android.widget.RatingBar; import android.widget.TextView; import com.example.calixta.flix.models.Movie; import com.google.android.youtube.player.YouTubeBaseActivity; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcels; import cz.msebera.android.httpclient.Header; public class MovieDetail extends YouTubeBaseActivity { TextView detail_title; TextView detail_overview; RatingBar ratingBar; Movie movie; public static final String key = "<KEY>"; public static final String trailer_api = "https://api.themoviedb.org/3/movie/%d/videos?api_key=<KEY>"; YouTubePlayerView YoutubePlayerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail); detail_title = findViewById(R.id.detail_title); detail_overview = findViewById(R.id.detail_overview); ratingBar = findViewById(R.id.ratingBar); YoutubePlayerView = findViewById(R.id.player); //now we have the same movie object from the previous activity in our detail activity movie = (Movie) Parcels.unwrap(getIntent().getParcelableExtra("movie")); detail_title.setText(movie.getTitle()); detail_overview.setText(movie.getOverview()); ratingBar.setRating(movie.getRating()); //making network requests using the api link above AsyncHttpClient client = new AsyncHttpClient(); client.get(String.format(trailer_api, movie.getId()), new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); //parsing here try { JSONArray res = response.getJSONArray("results"); //if there are no trailers to show then show the poster if (res.length() == 0) { return; } //otherwise, get the trailer link in the json, and cue it in the initialize youtube method JSONObject movieTrailer = res.getJSONObject(0); String youtubekey = movieTrailer.getString("key"); initalizeYoutube(youtubekey); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); } } ); } private void initalizeYoutube(final String youtubekey) { //here we are actually playing videos YoutubePlayerView.initialize(key, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { youTubePlayer.cueVideo(youtubekey); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { } }); } }
3,973
0.626521
0.618326
103
38.097088
33.561569
139
false
false
0
0
0
0
0
0
0.61165
false
false
12
7ff8f46491804979292bdbae5e1440bd17edfdb3
20,598,663,210,770
be08d5ea393c4634a0d3177b171e62417ac46df1
/microservice-consumer-movie-feign/src/main/java/com/itpx/cloud/UserFeignClient.java
efa04cac0e1730f18f9e5b30b683d2b4cd7972b2
[]
no_license
DeveloperPei/microservice-spring-cloud
https://github.com/DeveloperPei/microservice-spring-cloud
6e2937cc69ca530fb83dcda503da252ae033e2af
d2a0aa7c8d948798970a6c98a88ea47f46c87542
refs/heads/master
2021-01-25T11:48:10.799000
2018-03-28T07:43:50
2018-03-28T07:43:50
123,427,461
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itpx.cloud; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.itpx.cloud.entity.User; @FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value="simple/{id}",method=RequestMethod.GET) public User findById(@PathVariable("id") Long id); //两个注意点: 1 不支持 @GetMapping 2@PathVariable必选要写value值 @RequestMapping(value="/simple/postTest",method=RequestMethod.POST) public User postUser(@RequestBody User user); @RequestMapping(value="/simple/getTest",method=RequestMethod.GET) public User getUser(@RequestBody User user); }
UTF-8
Java
898
java
UserFeignClient.java
Java
[]
null
[]
package com.itpx.cloud; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.itpx.cloud.entity.User; @FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value="simple/{id}",method=RequestMethod.GET) public User findById(@PathVariable("id") Long id); //两个注意点: 1 不支持 @GetMapping 2@PathVariable必选要写value值 @RequestMapping(value="/simple/postTest",method=RequestMethod.POST) public User postUser(@RequestBody User user); @RequestMapping(value="/simple/getTest",method=RequestMethod.GET) public User getUser(@RequestBody User user); }
898
0.793103
0.790805
21
39.42857
29.170389
104
false
false
0
0
0
0
0
0
1
false
false
12
3403805c9852e35ee20dade0532d4eff25a4d7a5
11,708,080,859,064
0e3c720c5193092eceff3b93a1ecd75ecb5ef8d2
/core-datastream/src/main/java/io/datakernel/datastream/processor/StreamTransformer.java
dbc029521abf556a1cfc87bea7703817aad0d24d
[ "Apache-2.0" ]
permissive
softindex/datakernel
https://github.com/softindex/datakernel
197a4c06d0412a370c2141ad7f7de762fef9e69a
69a6bcb85be43177d96ea56041b63e8d8ffb10de
refs/heads/master
2023-09-04T15:15:53.109000
2020-06-25T12:36:09
2020-06-25T12:36:09
38,080,174
104
18
Apache-2.0
false
2023-04-16T15:24:17
2015-06-25T23:40:57
2023-03-12T17:45:36
2023-04-16T15:24:16
26,903
94
15
11
Java
false
false
/* * Copyright (C) 2015 SoftIndex LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datakernel.datastream.processor; import io.datakernel.datastream.*; import java.util.function.Function; /** * A bidirectional stream transformer capable of transforming both * {@link StreamConsumer consumers} and {@link StreamSupplier suppliers}. * * @param <I> input elements type * @param <O> output elements type. */ public interface StreamTransformer<I, O> extends HasStreamInput<I>, HasStreamOutput<O>, StreamSupplierTransformer<I, StreamSupplier<O>>, StreamConsumerTransformer<O, StreamConsumer<I>> { /** * An identity transformer that does not change the elements. */ static <X> StreamTransformer<X, X> identity() { return StreamMapper.create(Function.identity()); } @Override default StreamConsumer<I> transform(StreamConsumer<O> consumer) { getOutput().streamTo(consumer); return getInput(); } @Override default StreamSupplier<O> transform(StreamSupplier<I> supplier) { supplier.streamTo(getInput()); return getOutput(); } }
UTF-8
Java
1,583
java
StreamTransformer.java
Java
[]
null
[]
/* * Copyright (C) 2015 SoftIndex LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datakernel.datastream.processor; import io.datakernel.datastream.*; import java.util.function.Function; /** * A bidirectional stream transformer capable of transforming both * {@link StreamConsumer consumers} and {@link StreamSupplier suppliers}. * * @param <I> input elements type * @param <O> output elements type. */ public interface StreamTransformer<I, O> extends HasStreamInput<I>, HasStreamOutput<O>, StreamSupplierTransformer<I, StreamSupplier<O>>, StreamConsumerTransformer<O, StreamConsumer<I>> { /** * An identity transformer that does not change the elements. */ static <X> StreamTransformer<X, X> identity() { return StreamMapper.create(Function.identity()); } @Override default StreamConsumer<I> transform(StreamConsumer<O> consumer) { getOutput().streamTo(consumer); return getInput(); } @Override default StreamSupplier<O> transform(StreamSupplier<I> supplier) { supplier.streamTo(getInput()); return getOutput(); } }
1,583
0.743525
0.738471
52
29.442308
27.560015
87
false
false
0
0
0
0
0
0
0.865385
false
false
12
7d63add60195fd0bdd79bcc024f81a628bcf2eaf
13,005,161,035,647
b4ccb66c6002506217b57dd0522fc3975c66ba0d
/matcha-core/src/main/java/com/hanker/core/utils/UtilForRequest.java
c54b578d6486f8d5c7e04e80e5e2d9032ebc521e
[]
no_license
hankert/testMy
https://github.com/hankert/testMy
2b19648a0854f8a4d2db62ab38417d49a9a917b1
87246f1e0257f64436377c13b450160e53517292
refs/heads/master
2021-07-22T09:53:09.075000
2017-10-31T15:01:29
2017-10-31T15:01:29
108,975,765
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hanker.core.utils; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.hanker.core.net.app.Matcha; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Created by jinhui on 2017/10/31. */ public class UtilForRequest { /** * 获取签名 * * @param map * @return */ public static String genSigntureString(Map<String, Object> map) { StringBuilder sBuilder = new StringBuilder(); Set<String> keySet = map.keySet(); List<String> keyList = new ArrayList<>(); for (String key : keySet) { keyList.add(key); } Collections.sort(keyList, new Comparator<String>() { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } }); // sBuilder.append(getk()); sBuilder.append("m39dhaow8h5b091n"); for (String key : keyList) { sBuilder.append(key).append(map.get(key)); } // sBuilder.append(getS()); sBuilder.append("3821054637287940658"); keySet = null; keyList = null; MatChaLogger.i("xdebug", sBuilder.toString()); return genMD5String(sBuilder.toString()); } public static String genMD5String(String plainText) { return MD5.mkMd5(plainText); } public static String getAndroidVer() { return "android_" + android.os.Build.VERSION.RELEASE; } public static String getAndroidModel() { return android.os.Build.BRAND + "_" + android.os.Build.MODEL; } public static String getPhoneModel() { return android.os.Build.MODEL; } public static String getDeviceId() { String r = "wrong_device_id"; try { r = ((TelephonyManager) Matcha.getApplicationContext() .getSystemService(Matcha.getApplicationContext().TELEPHONY_SERVICE)).getDeviceId(); if (TextUtils.isEmpty(r) || "0".equals(r)) { r = DeviceHelper.getLocalMacAddress(Matcha.getApplicationContext()); } } catch (Exception e) { e.printStackTrace(); } return r; } public static String genSn() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault()); return new String(sdf.format(new Date())); } public static String getHS(String time, String s) { if (TextUtils.isEmpty(s)) { // return Util.genMD5String(time+getK()); return genMD5String(time + s + "for"); } else { return genMD5String(time + s + "for"); } } }
UTF-8
Java
2,881
java
UtilForRequest.java
Java
[ { "context": "util.Map;\nimport java.util.Set;\n\n/**\n * Created by jinhui on 2017/10/31.\n */\n\npublic class UtilForRequest {", "end": 409, "score": 0.9995432496070862, "start": 403, "tag": "USERNAME", "value": "jinhui" } ]
null
[]
package com.hanker.core.utils; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.hanker.core.net.app.Matcha; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Created by jinhui on 2017/10/31. */ public class UtilForRequest { /** * 获取签名 * * @param map * @return */ public static String genSigntureString(Map<String, Object> map) { StringBuilder sBuilder = new StringBuilder(); Set<String> keySet = map.keySet(); List<String> keyList = new ArrayList<>(); for (String key : keySet) { keyList.add(key); } Collections.sort(keyList, new Comparator<String>() { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } }); // sBuilder.append(getk()); sBuilder.append("m39dhaow8h5b091n"); for (String key : keyList) { sBuilder.append(key).append(map.get(key)); } // sBuilder.append(getS()); sBuilder.append("3821054637287940658"); keySet = null; keyList = null; MatChaLogger.i("xdebug", sBuilder.toString()); return genMD5String(sBuilder.toString()); } public static String genMD5String(String plainText) { return MD5.mkMd5(plainText); } public static String getAndroidVer() { return "android_" + android.os.Build.VERSION.RELEASE; } public static String getAndroidModel() { return android.os.Build.BRAND + "_" + android.os.Build.MODEL; } public static String getPhoneModel() { return android.os.Build.MODEL; } public static String getDeviceId() { String r = "wrong_device_id"; try { r = ((TelephonyManager) Matcha.getApplicationContext() .getSystemService(Matcha.getApplicationContext().TELEPHONY_SERVICE)).getDeviceId(); if (TextUtils.isEmpty(r) || "0".equals(r)) { r = DeviceHelper.getLocalMacAddress(Matcha.getApplicationContext()); } } catch (Exception e) { e.printStackTrace(); } return r; } public static String genSn() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault()); return new String(sdf.format(new Date())); } public static String getHS(String time, String s) { if (TextUtils.isEmpty(s)) { // return Util.genMD5String(time+getK()); return genMD5String(time + s + "for"); } else { return genMD5String(time + s + "for"); } } }
2,881
0.601114
0.586495
104
26.625
23.106022
103
false
false
0
0
0
0
0
0
0.480769
false
false
12
dd05fa4a7f003ab6ad380390e2f338f0706570c7
20,847,771,282,183
736c59ed2e81d540573daa2e624a2dfeb8129193
/src/android/org/linphone/iclasses/WebAPIResponseListener.java
b3216b3311f80d1e4991e7e95e555aa40554018e
[]
no_license
EmbeddedDownloads/BitVaultSecureCalling
https://github.com/EmbeddedDownloads/BitVaultSecureCalling
cefab782ec59d75b6dac5a7ec5ab99383fedba10
4f9fe2bef1889d2fa542954776482ae0f0c30a95
refs/heads/master
2020-04-02T04:11:56.735000
2018-10-21T17:58:23
2018-10-21T17:58:23
154,004,943
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.linphone.iclasses; /** * Web API Response Helper */ public interface WebAPIResponseListener { /** * On Success of API Call * * @param arguments */ void onSuccessOfResponse(String arguments); /** * on Fail of API Call * * @param arguments */ void onFailOfResponse(String arguments); }
UTF-8
Java
344
java
WebAPIResponseListener.java
Java
[]
null
[]
package org.linphone.iclasses; /** * Web API Response Helper */ public interface WebAPIResponseListener { /** * On Success of API Call * * @param arguments */ void onSuccessOfResponse(String arguments); /** * on Fail of API Call * * @param arguments */ void onFailOfResponse(String arguments); }
344
0.630814
0.630814
21
14.380953
14.882
44
false
false
0
0
0
0
0
0
0.714286
false
false
12
03b4895dab7d03bc2110d34c7bfa9bdccf39446d
31,181,462,569,116
867c253bca3112c5d53f8722705d24d068fd920d
/app/src/main/java/atam/buddygarage/MainPage.java
23e8b0350e95aa9d0d6fdfdbe0366fef3c2baa71
[]
no_license
Bit7IT/BuddyGarage
https://github.com/Bit7IT/BuddyGarage
ce443b6e77ea4aec4d6221d63d726fc94a26b450
9b6690c7c89a24360d3a162c73ef228290fd86e5
refs/heads/master
2020-06-11T11:01:55.345000
2017-01-14T05:43:52
2017-01-14T05:43:52
75,682,885
0
0
null
false
2017-01-14T05:43:53
2016-12-06T01:39:22
2016-12-06T01:47:20
2017-01-14T05:43:53
98
0
0
0
Java
null
null
package atam.buddygarage; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainPage extends AppCompatActivity { public void runSellFunc(View view){ Intent intent = new Intent(MainPage.this, Sell_SignInPage.class); // go to the User Sign up Screen startActivity(intent); }//for Sell Button public void runBuyFunc(View view) { //Intent intent = new Intent(MainPage.this, Sell_SignInPage.class); // go to the User Sign up Screen // startActivity(intent); }//for Buy Button @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_page); } }
UTF-8
Java
797
java
MainPage.java
Java
[]
null
[]
package atam.buddygarage; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainPage extends AppCompatActivity { public void runSellFunc(View view){ Intent intent = new Intent(MainPage.this, Sell_SignInPage.class); // go to the User Sign up Screen startActivity(intent); }//for Sell Button public void runBuyFunc(View view) { //Intent intent = new Intent(MainPage.this, Sell_SignInPage.class); // go to the User Sign up Screen // startActivity(intent); }//for Buy Button @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_page); } }
797
0.710163
0.708908
28
27.464285
28.682352
108
false
false
0
0
0
0
0
0
0.464286
false
false
12
e3ee54f65fe8856b4f2880a1326cf0603f464a97
39,118,562,145,117
3a64bd35f2956a0b1a731296e8497ac9dfae3ab8
/greedy/2217번_로프.java
7af075007fa22f6df62be8dfc6db908cdf83abd7
[]
no_license
kys4548/Algorithm_baekjoon
https://github.com/kys4548/Algorithm_baekjoon
1564a3409f54cb8ce4145d6b1de861c87b666a50
fa2e46ce01e5debf4f50d682fa5b1d1bcdf05601
refs/heads/master
2021-01-14T18:41:14.998000
2020-11-15T11:21:24
2020-11-15T11:21:24
242,716,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String []args) throws Exception { //예외처리 필수 int answer = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] arr = new int[N]; for(int i=0; i<N; i++) { arr[i] = Integer.parseInt(br.readLine()); } Arrays.sort(arr); answer = arr[N-1]; for(int i=N-2; i>=0; i--) { if(arr[i] * (N-i) > answer) { answer = arr[i] * (N-i); } } System.out.println(answer); br.close(); } }
UTF-8
Java
660
java
2217번_로프.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String []args) throws Exception { //예외처리 필수 int answer = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] arr = new int[N]; for(int i=0; i<N; i++) { arr[i] = Integer.parseInt(br.readLine()); } Arrays.sort(arr); answer = arr[N-1]; for(int i=N-2; i>=0; i--) { if(arr[i] * (N-i) > answer) { answer = arr[i] * (N-i); } } System.out.println(answer); br.close(); } }
660
0.594136
0.58642
25
24.959999
19.598938
81
false
false
0
0
0
0
0
0
1.84
false
false
12
df5207eeb457958ded2165bc0a02727248682cc0
31,318,901,544,805
448a1f666726c62cac7d4fafe51e596b21c60d30
/src/nowcoder/小易爱回文/Main.java
123231aa7eebd5938f7df4e0eada2c782a7b0e1e
[]
no_license
xinfeng103/LeetCode
https://github.com/xinfeng103/LeetCode
65c697922a6d5a96202e85b50a902eaae9746b75
9fd39deecfb7256041907065f4af98fe8e8ab306
refs/heads/master
2023-07-13T07:51:59.641000
2021-08-19T09:41:44
2021-08-19T09:41:44
349,010,867
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nowcoder.小易爱回文; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); // String str = "hello"; int n = str.length(); char[] chars = str.toCharArray(); for (int low = 0, high = n - 1; low < high; low++, high--) { char tmp = chars[low]; chars[low] = chars[high]; chars[high] = tmp; } int i=0,j=0; while (i < n && j < n) { if(str.charAt(i)!=chars[j]){ i++; if(j!=0) j=0; }else { i++; j++; } } System.out.println(j); char[] addChars = new char[n-j]; int index = 0; while (j<n){ addChars[index++] = chars[j++]; } System.out.println(str+ new String(addChars)); } }
UTF-8
Java
986
java
Main.java
Java
[]
null
[]
package nowcoder.小易爱回文; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); // String str = "hello"; int n = str.length(); char[] chars = str.toCharArray(); for (int low = 0, high = n - 1; low < high; low++, high--) { char tmp = chars[low]; chars[low] = chars[high]; chars[high] = tmp; } int i=0,j=0; while (i < n && j < n) { if(str.charAt(i)!=chars[j]){ i++; if(j!=0) j=0; }else { i++; j++; } } System.out.println(j); char[] addChars = new char[n-j]; int index = 0; while (j<n){ addChars[index++] = chars[j++]; } System.out.println(str+ new String(addChars)); } }
986
0.442623
0.435451
37
25.378378
15.511724
68
false
false
0
0
0
0
0
0
0.702703
false
false
12
7c6d3e7d075319664fc5f83936a93416533d51f5
33,208,687,153,461
7674ebd45daf6354e803429795fb279a38fde6eb
/src/com/hoteldmz/web/service/DeskWorkReportService.java
d3fe6f94d59dfe0fa2e6960bf68249647f809d62
[]
no_license
joseps/daysinnclanton
https://github.com/joseps/daysinnclanton
8b8ac7b4a7e1f3fa1756a6b1be70455d1065bcb3
358fe42a28ae26a448fc6b306390fa60d0bf4948
refs/heads/master
2016-09-07T02:30:45.864000
2013-03-08T20:43:43
2013-03-08T20:43:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hoteldmz.web.service; import com.googlecode.objectify.Key; import com.hoteldmz.web.model.DeskWorkReport; import java.util.Date; import java.util.List; public interface DeskWorkReportService { public Key<DeskWorkReport> save(DeskWorkReport deskWorkReport); public void remove(Long id); public int count(); public DeskWorkReport findById(Long id); public List<DeskWorkReport> findByDateRange(Date fromDate, Date throughDate); }
UTF-8
Java
461
java
DeskWorkReportService.java
Java
[]
null
[]
package com.hoteldmz.web.service; import com.googlecode.objectify.Key; import com.hoteldmz.web.model.DeskWorkReport; import java.util.Date; import java.util.List; public interface DeskWorkReportService { public Key<DeskWorkReport> save(DeskWorkReport deskWorkReport); public void remove(Long id); public int count(); public DeskWorkReport findById(Long id); public List<DeskWorkReport> findByDateRange(Date fromDate, Date throughDate); }
461
0.78308
0.78308
15
29.733334
23.461931
81
false
false
0
0
0
0
0
0
0.733333
false
false
12
2cb5d342f8e4c8c44d49c489a37ed4ec46a1de21
13,700,945,680,050
5c3ab5e19ea0f406cf6a00d0e4181b6c51f8dfb6
/app/src/main/java/com/ngolamquangtin/appdatvexemphim/Activity/SplashActivity.java
e232ba9bce0d3162079bf01880cf1b31db65bf4c
[]
no_license
quangtin131299/CinemaPlusAppV2
https://github.com/quangtin131299/CinemaPlusAppV2
cd09334846259113fe2d8795b57658656dfc0e7c
1f4610bba5477d7cda98861d5f74be82c73ca209
refs/heads/master
2023-07-08T01:35:24.326000
2021-08-21T17:40:07
2021-08-21T17:40:07
369,833,739
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ngolamquangtin.appdatvexemphim.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.github.ybq.android.spinkit.sprite.Sprite; import com.github.ybq.android.spinkit.style.RotatingCircle; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.messaging.FirebaseMessaging; import com.ngolamquangtin.appdatvexemphim.Config.RetrofitUtil; import com.ngolamquangtin.appdatvexemphim.DTO.TokenClient; import com.ngolamquangtin.appdatvexemphim.Notifycation; import com.ngolamquangtin.appdatvexemphim.R; import com.ngolamquangtin.appdatvexemphim.Service.Service; import com.ngolamquangtin.appdatvexemphim.ServiceNotifyTicker; import com.ngolamquangtin.appdatvexemphim.ServiceUpdateStatusTicker; import com.ngolamquangtin.appdatvexemphim.Util.Util; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SplashActivity extends AppCompatActivity { SharedPreferences sharedPreferences; AlarmManager alarmManager, alarmManagerUpdateTicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); init(); startServiceNotify(); startServieNotifyTicker(); startServiceUpdateStatusTicker(); getToken(); changeLocale(); new PrefetchData().execute(); } public void startServiceUpdateStatusTicker(){ Intent intent = new Intent(SplashActivity.this, ServiceUpdateStatusTicker.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(SplashActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); alarmManagerUpdateTicker.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); } public void init(){ sharedPreferences = getSharedPreferences("datalogin", Context.MODE_PRIVATE); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress); Sprite doubleBounce = new RotatingCircle(); progressBar.setIndeterminateDrawable(doubleBounce); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManagerUpdateTicker = (AlarmManager) getSystemService(ALARM_SERVICE); } public void startServieNotifyTicker() { Intent intent = new Intent(SplashActivity.this, ServiceNotifyTicker.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(SplashActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); } public void getToken(){ FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { String tokenMessage = task.getResult(); addNewTokenClient(tokenMessage); } }); FirebaseMessaging.getInstance().subscribeToTopic("NewMovie").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.getException() != null){ Log.d("errorTopicFirebase: ", task.getException().getMessage()); } } }); } public void startServiceNotify(){ Intent intentBackgroundService = new Intent(SplashActivity.this, Notifycation.class); startService(intentBackgroundService); } public void addNewTokenClient(String token){ TokenClient newToken = new TokenClient(); newToken.setToken(token); Service service = RetrofitUtil.getService(SplashActivity.this); Call<Integer> call = service.addNewTokenClient(newToken); call.enqueue(new Callback<Integer>() { @Override public void onResponse(Call<Integer> call, Response<Integer> response) { if(response.body() != null && response.body() == 0){ Log.d("/////" ,"Lỗi rồi"); } } @Override public void onFailure(Call<Integer> call, Throwable t) { } }); } public void changeLocale(){ String currentCodeLanguae = sharedPreferences.getString("currentLanguae", ""); if(!currentCodeLanguae.isEmpty()){ Util.changeLocale(SplashActivity.this, currentCodeLanguae); } } class PrefetchData extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { //Nap data ở đây return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(SplashActivity.this, HomeActivity.class); startActivity(i); finish(); } }, 2000); } } }
UTF-8
Java
5,745
java
SplashActivity.java
Java
[]
null
[]
package com.ngolamquangtin.appdatvexemphim.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.github.ybq.android.spinkit.sprite.Sprite; import com.github.ybq.android.spinkit.style.RotatingCircle; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.messaging.FirebaseMessaging; import com.ngolamquangtin.appdatvexemphim.Config.RetrofitUtil; import com.ngolamquangtin.appdatvexemphim.DTO.TokenClient; import com.ngolamquangtin.appdatvexemphim.Notifycation; import com.ngolamquangtin.appdatvexemphim.R; import com.ngolamquangtin.appdatvexemphim.Service.Service; import com.ngolamquangtin.appdatvexemphim.ServiceNotifyTicker; import com.ngolamquangtin.appdatvexemphim.ServiceUpdateStatusTicker; import com.ngolamquangtin.appdatvexemphim.Util.Util; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SplashActivity extends AppCompatActivity { SharedPreferences sharedPreferences; AlarmManager alarmManager, alarmManagerUpdateTicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); init(); startServiceNotify(); startServieNotifyTicker(); startServiceUpdateStatusTicker(); getToken(); changeLocale(); new PrefetchData().execute(); } public void startServiceUpdateStatusTicker(){ Intent intent = new Intent(SplashActivity.this, ServiceUpdateStatusTicker.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(SplashActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); alarmManagerUpdateTicker.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); } public void init(){ sharedPreferences = getSharedPreferences("datalogin", Context.MODE_PRIVATE); ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress); Sprite doubleBounce = new RotatingCircle(); progressBar.setIndeterminateDrawable(doubleBounce); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManagerUpdateTicker = (AlarmManager) getSystemService(ALARM_SERVICE); } public void startServieNotifyTicker() { Intent intent = new Intent(SplashActivity.this, ServiceNotifyTicker.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(SplashActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); } public void getToken(){ FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { String tokenMessage = task.getResult(); addNewTokenClient(tokenMessage); } }); FirebaseMessaging.getInstance().subscribeToTopic("NewMovie").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.getException() != null){ Log.d("errorTopicFirebase: ", task.getException().getMessage()); } } }); } public void startServiceNotify(){ Intent intentBackgroundService = new Intent(SplashActivity.this, Notifycation.class); startService(intentBackgroundService); } public void addNewTokenClient(String token){ TokenClient newToken = new TokenClient(); newToken.setToken(token); Service service = RetrofitUtil.getService(SplashActivity.this); Call<Integer> call = service.addNewTokenClient(newToken); call.enqueue(new Callback<Integer>() { @Override public void onResponse(Call<Integer> call, Response<Integer> response) { if(response.body() != null && response.body() == 0){ Log.d("/////" ,"Lỗi rồi"); } } @Override public void onFailure(Call<Integer> call, Throwable t) { } }); } public void changeLocale(){ String currentCodeLanguae = sharedPreferences.getString("currentLanguae", ""); if(!currentCodeLanguae.isEmpty()){ Util.changeLocale(SplashActivity.this, currentCodeLanguae); } } class PrefetchData extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { //Nap data ở đây return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(SplashActivity.this, HomeActivity.class); startActivity(i); finish(); } }, 2000); } } }
5,745
0.687642
0.684155
168
33.148811
31.382555
144
false
false
0
0
0
0
0
0
0.613095
false
false
12
abb87d59b53213d0cf7b740a7db226243426028a
4,329,327,049,671
689485f8ec89de3a51e560869d8498f298250419
/standard/src/test/java/org/jsefa/test/xml/ExplicitMapTypeTest.java
157df184f116b12d9c17c319f0c0f0e6f3bf02e8
[ "Apache-2.0" ]
permissive
Manmay/JSefa
https://github.com/Manmay/JSefa
487572b8821a104b30602da25a49922f83e4782d
4d973eb77227d46ae02a869b1e1eee5871b3f842
refs/heads/master
2020-12-28T04:32:59.414000
2010-11-16T13:14:43
2010-11-16T13:14:43
27,228,872
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jsefa.test.xml; import static org.jsefa.test.common.JSefaTestUtil.FormatType.XML; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.jsefa.test.common.AbstractTestDTO; import org.jsefa.test.common.JSefaTestUtil; import org.jsefa.xml.annotation.MapKey; import org.jsefa.xml.annotation.MapValue; import org.jsefa.xml.annotation.XmlAttribute; import org.jsefa.xml.annotation.XmlDataType; import org.jsefa.xml.annotation.XmlElement; import org.jsefa.xml.annotation.XmlElementMap; /** * Tests to test explicit maps with <code>String</code> keys and elements of different depth. * * @author Norman Lahme-Huetig */ public class ExplicitMapTypeTest extends TestCase { /** * Tests a map with <code>String</code> keys and <code>Integer</code> elements. */ public void testStringToIntegerMap() { StringToIntegerMap map = new StringToIntegerMap(); map.map = new HashMap<String, Integer>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, i); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } /** * Tests a map with <code>String</code> keys and <code>Depth0DTO</code> elements. */ public void testStringToDepth0Map() { StringToDepth0Map map = new StringToDepth0Map(); map.map = new HashMap<String, Depth0>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, createDepth0(i)); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } /** * Tests a map with <code>String</code> keys and <code>Depth1DTO</code> elements. */ public void testStringToDepth1Map() { StringToDepth1Map map = new StringToDepth1Map(); map.map = new HashMap<String, Depth1>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, createDepth1(i)); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } private Depth0 createDepth0(int i) { Depth0 object = new Depth0(); object.fieldA = "valueA" + i; object.fieldB = "valueB" + i; return object; } private Depth1 createDepth1(int i) { Depth1 object = new Depth1(); object.fieldC = "valueC" + i; object.fieldD = createDepth0(i); return object; } @XmlDataType() static final class StringToIntegerMap extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Integer> map; } @XmlDataType() static final class StringToDepth0Map extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Depth0> map; } @XmlDataType() static final class StringToDepth1Map extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Depth1> map; } @XmlDataType() static class Depth0 extends AbstractTestDTO { @XmlAttribute() String fieldA; @XmlElement() String fieldB; } @XmlDataType() static final class Depth1 extends AbstractTestDTO { @XmlAttribute() String fieldC; @XmlElement() Depth0 fieldD; } }
UTF-8
Java
4,074
java
ExplicitMapTypeTest.java
Java
[ { "context": "ys and elements of different depth.\n * \n * @author Norman Lahme-Huetig\n */\npublic class ExplicitMapTypeTest extends Test", "end": 1283, "score": 0.9998974800109863, "start": 1264, "tag": "NAME", "value": "Norman Lahme-Huetig" } ]
null
[]
/* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jsefa.test.xml; import static org.jsefa.test.common.JSefaTestUtil.FormatType.XML; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.jsefa.test.common.AbstractTestDTO; import org.jsefa.test.common.JSefaTestUtil; import org.jsefa.xml.annotation.MapKey; import org.jsefa.xml.annotation.MapValue; import org.jsefa.xml.annotation.XmlAttribute; import org.jsefa.xml.annotation.XmlDataType; import org.jsefa.xml.annotation.XmlElement; import org.jsefa.xml.annotation.XmlElementMap; /** * Tests to test explicit maps with <code>String</code> keys and elements of different depth. * * @author <NAME> */ public class ExplicitMapTypeTest extends TestCase { /** * Tests a map with <code>String</code> keys and <code>Integer</code> elements. */ public void testStringToIntegerMap() { StringToIntegerMap map = new StringToIntegerMap(); map.map = new HashMap<String, Integer>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, i); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } /** * Tests a map with <code>String</code> keys and <code>Depth0DTO</code> elements. */ public void testStringToDepth0Map() { StringToDepth0Map map = new StringToDepth0Map(); map.map = new HashMap<String, Depth0>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, createDepth0(i)); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } /** * Tests a map with <code>String</code> keys and <code>Depth1DTO</code> elements. */ public void testStringToDepth1Map() { StringToDepth1Map map = new StringToDepth1Map(); map.map = new HashMap<String, Depth1>(); for (int i = 0; i < 10; i++) { map.map.put("stringValue" + i, createDepth1(i)); } JSefaTestUtil.assertRepeatedRoundTripSucceeds(XML, map); } private Depth0 createDepth0(int i) { Depth0 object = new Depth0(); object.fieldA = "valueA" + i; object.fieldB = "valueB" + i; return object; } private Depth1 createDepth1(int i) { Depth1 object = new Depth1(); object.fieldC = "valueC" + i; object.fieldD = createDepth0(i); return object; } @XmlDataType() static final class StringToIntegerMap extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Integer> map; } @XmlDataType() static final class StringToDepth0Map extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Depth0> map; } @XmlDataType() static final class StringToDepth1Map extends AbstractTestDTO { @XmlElementMap(implicit = false, key = @MapKey(name = "key"), values = @MapValue(name = "value")) Map<String, Depth1> map; } @XmlDataType() static class Depth0 extends AbstractTestDTO { @XmlAttribute() String fieldA; @XmlElement() String fieldB; } @XmlDataType() static final class Depth1 extends AbstractTestDTO { @XmlAttribute() String fieldC; @XmlElement() Depth0 fieldD; } }
4,061
0.648257
0.637212
128
30.828125
26.850019
105
false
false
0
0
0
0
0
0
0.539063
false
false
12
a99ba0d30dd7cf4e72251722a90f3e098f664a80
27,436,251,129,298
4441f65cb7d9d5a18e25f75b023433929068b31e
/community Maven Webapp/src/test/java/com/community/dao/AdminDAOTest.java
40e839a60aac83d00b91d853ce5b747b619e3f75
[]
no_license
xuhuanxin/Community
https://github.com/xuhuanxin/Community
82826775f0ae1440a255adc1770523a2b151ed7d
2ee0f9073eb314f17fb96823f3fd1c94fd095b65
refs/heads/master
2020-03-21T17:44:41.719000
2018-06-27T08:32:02
2018-06-27T08:32:02
138,850,518
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.community.dao; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.community.entity.Admin; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-dao.xml") public class AdminDAOTest { @Autowired private AdminDAO adminDAO; @Test public void testInsert() { Admin admin =new Admin(); admin.setAdminName("admin1"); admin.setAdminPassword("admin1"); adminDAO.insert(admin); } @Test public void testDelete() { int adminId=4; adminDAO.delete(adminId); } @Test public void testUpdatePassword() { adminDAO.updatePassword(1, "admin1"); } @Test public void testQueryAll() { List<Admin> list=adminDAO.queryAll(); for (Admin admin : list) { System.out.println(admin.toString()); } } @Test public void testQueryByNameAndPsw() { Admin admin=adminDAO.queryByNameAndPsw("admin1", "admin1"); if (admin!=null) { System.out.println("登录成功!"); } else { System.out.println("登录失败!"); } } }
UTF-8
Java
1,231
java
AdminDAOTest.java
Java
[ { "context": "\t\tAdmin admin =new Admin();\n\t\tadmin.setAdminName(\"admin1\");\n\t\tadmin.setAdminPassword(\"admin1\");\n\t\tadminDAO", "end": 597, "score": 0.9936738014221191, "start": 591, "tag": "USERNAME", "value": "admin1" }, { "context": "setAdminName(\"admin1\");\n\t\tadmin.setAdminPassword(\"admin1\");\n\t\tadminDAO.insert(admin);\n\t}\n\n\t@Test\n\tpublic v", "end": 633, "score": 0.9992690086364746, "start": 627, "tag": "PASSWORD", "value": "admin1" }, { "context": "tUpdatePassword() {\n\t\tadminDAO.updatePassword(1, \"admin1\");\n\t}\n\n\t@Test\n\tpublic void testQueryAll() {\n\t\tLis", "end": 834, "score": 0.8842769861221313, "start": 828, "tag": "PASSWORD", "value": "admin1" }, { "context": "Psw() {\n\t\tAdmin admin=adminDAO.queryByNameAndPsw(\"admin1\", \"admin1\");\n\t\tif (admin!=null) {\n\t\t\tSystem.out.p", "end": 1091, "score": 0.7933199405670166, "start": 1085, "tag": "USERNAME", "value": "admin1" }, { "context": "Admin admin=adminDAO.queryByNameAndPsw(\"admin1\", \"admin1\");\n\t\tif (admin!=null) {\n\t\t\tSystem.out.println(\"登录", "end": 1101, "score": 0.6928809881210327, "start": 1095, "tag": "USERNAME", "value": "admin1" } ]
null
[]
package com.community.dao; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.community.entity.Admin; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-dao.xml") public class AdminDAOTest { @Autowired private AdminDAO adminDAO; @Test public void testInsert() { Admin admin =new Admin(); admin.setAdminName("admin1"); admin.setAdminPassword("<PASSWORD>"); adminDAO.insert(admin); } @Test public void testDelete() { int adminId=4; adminDAO.delete(adminId); } @Test public void testUpdatePassword() { adminDAO.updatePassword(1, "<PASSWORD>"); } @Test public void testQueryAll() { List<Admin> list=adminDAO.queryAll(); for (Admin admin : list) { System.out.println(admin.toString()); } } @Test public void testQueryByNameAndPsw() { Admin admin=adminDAO.queryByNameAndPsw("admin1", "admin1"); if (admin!=null) { System.out.println("登录成功!"); } else { System.out.println("登录失败!"); } } }
1,239
0.735756
0.727498
56
20.625
18.959131
71
false
false
0
0
0
0
0
0
1.410714
false
false
12
7eaa0e15b9f93f8d7f59b12e84a461290ad9c8a1
19,997,367,774,409
ac98d9b3087e8e65284006775059902c8102d596
/DesignPatterns/idea/src/main/java/state/account/NormalState.java
2f956a73207c28a2db737f27471f2e6653e39346
[]
no_license
zyhfight/com.zhen
https://github.com/zyhfight/com.zhen
0e0c220206a51d8d736dbd73246c5ebce9838bac
4bb2cb4508ddf325c67b0f47d20f6e037323ceaa
refs/heads/master
2021-04-09T17:41:48.491000
2019-04-14T14:24:48
2019-04-14T14:24:48
55,615,250
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package state.account; /** * Copyright: Copyright (c) 2018 * * @Description: 正常状态:具体状态类 * @version: v1.0.0 * @author: zyh * @date: 2018-7-23 * <p> * Modification History: * Date Author Version Description * ---------------------------------------------------------* * 2018-7-23 zyh v1.0.0 修改原因 */ public class NormalState extends AccountState { public NormalState(Account account){ this.account = account; } public NormalState(AccountState state){ this.account = state.account; } @Override public void deposit(double amount) { account.setBalance(account.getBalance() + amount); stateCheck(); } @Override public void withdraw(double amount) { account.setBalance(account.getBalance() - amount); stateCheck(); } @Override public void computeInterest() { System.out.println("正常状态,无需支付利息!"); } //在具体状态类中进行状态变换 @Override public void stateCheck() { if(account.getBalance() > -2000 && account.getBalance() <= 0){ account.setAccountState(new OverdraftState(this)); }else if(account.getBalance() == -2000){ account.setAccountState(new RestrictedState(this)); }else if(account.getBalance() < -2000){ System.out.println("操作受限!"); } } }
UTF-8
Java
1,479
java
NormalState.java
Java
[ { "context": "iption: 正常状态:具体状态类\n * @version: v1.0.0\n * @author: zyh\n * @date: 2018-7-23\n * <p>\n * Modification Histor", "end": 127, "score": 0.9996271133422852, "start": 124, "tag": "USERNAME", "value": "zyh" }, { "context": "--------------------------------*\n * 2018-7-23 zyh v1.0.0 修改原因\n */\npublic cl", "end": 325, "score": 0.8017032742500305, "start": 322, "tag": "USERNAME", "value": "zyh" } ]
null
[]
package state.account; /** * Copyright: Copyright (c) 2018 * * @Description: 正常状态:具体状态类 * @version: v1.0.0 * @author: zyh * @date: 2018-7-23 * <p> * Modification History: * Date Author Version Description * ---------------------------------------------------------* * 2018-7-23 zyh v1.0.0 修改原因 */ public class NormalState extends AccountState { public NormalState(Account account){ this.account = account; } public NormalState(AccountState state){ this.account = state.account; } @Override public void deposit(double amount) { account.setBalance(account.getBalance() + amount); stateCheck(); } @Override public void withdraw(double amount) { account.setBalance(account.getBalance() - amount); stateCheck(); } @Override public void computeInterest() { System.out.println("正常状态,无需支付利息!"); } //在具体状态类中进行状态变换 @Override public void stateCheck() { if(account.getBalance() > -2000 && account.getBalance() <= 0){ account.setAccountState(new OverdraftState(this)); }else if(account.getBalance() == -2000){ account.setAccountState(new RestrictedState(this)); }else if(account.getBalance() < -2000){ System.out.println("操作受限!"); } } }
1,479
0.562904
0.536305
54
24.75926
21.241064
70
false
false
0
0
0
0
0
0
0.203704
false
false
12
732839129621016ae2b71bee310730669c0cdcce
27,084,063,794,589
ada486e6dd7f1d5fdcb341bc71494e365df7d047
/Polisocial-AppEngine/Polisocial-AppEngine/src/it/polimi/dima/polisocial/foursquare/FoursquarePolisocialAPI.java
4c91275216120cccaa458130a57050808dd4e7b7
[]
no_license
danturi/PolisocialApp
https://github.com/danturi/PolisocialApp
92dc44e56eb0b299148dfcc265e6bf2e3939c546
558caa04a575d8fd87234419014403af15dd6a25
refs/heads/master
2020-06-03T22:44:48.467000
2014-11-30T01:29:28
2014-11-30T01:29:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.dima.polisocial.foursquare; import fi.foyt.foursquare.api.FoursquareApi; import fi.foyt.foursquare.api.FoursquareApiException; import fi.foyt.foursquare.api.Result; import fi.foyt.foursquare.api.entities.Category; import fi.foyt.foursquare.api.entities.CompactVenue; import fi.foyt.foursquare.api.entities.VenuesSearchResult; import it.polimi.dima.polisocial.ResponseObject; import it.polimi.dima.polisocial.endpoint.PoliUserEndpoint; import it.polimi.dima.polisocial.entity.PoliUser; import it.polimi.dima.polisocial.foursquare.constants.Constants; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiMethod.HttpMethod; import com.google.api.server.spi.config.ApiNamespace; import com.google.api.server.spi.config.Named; import com.google.api.server.spi.response.BadRequestException; import com.google.api.server.spi.response.NotFoundException; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.labs.repackaged.org.json.JSONArray; import com.google.appengine.labs.repackaged.org.json.JSONException; import com.google.appengine.labs.repackaged.org.json.JSONObject; import com.google.appengine.labs.repackaged.org.json.JSONTokener; @Api(name = "foursquareendpoint", version = "v1", namespace = @ApiNamespace(ownerDomain = "polimi.it", ownerName = "polimi.it", packagePath = "dima.polisocial.foursquare")) public class FoursquarePolisocialAPI { private static final Logger log = Logger .getLogger(FoursquarePolisocialAPI.class.getName()); private PoliUserEndpoint endpointUser = new PoliUserEndpoint(); @ApiMethod(name = "searchVenues") public ResponseObject searchVenues(@Named("ll") String ll) { Result<VenuesSearchResult> result = null; String exception = null; ResponseObject response = new ResponseObject(); ArrayList<ArrayList<String>> venues = new ArrayList<ArrayList<String>>(); try { result = searchVenuesRequest(ll); } catch (FoursquareApiException e) { // warning Eccezione... log.warning(e.getCause() + " " + e.getMessage()); } if (result != null) { int codeResponse = result.getMeta().getCode(); // tutto ok if (codeResponse == 200) { for (CompactVenue venue : result.getResult().getVenues()) { ArrayList<String> venueDetails = new ArrayList<String>(); venueDetails.add(venue.getId()); venueDetails.add(venue.getName()); venueDetails.add(venue.getLocation().getLat() + "," + venue.getLocation().getLng()); venues.add(venueDetails); } response.setException(exception); response.setObject(venues); } // problemi if (codeResponse == 400) response.setException("Bad Request"); if (codeResponse == 401) response.setException("Unauthorized"); if (codeResponse == 403) response.setException("Forbidden"); if (codeResponse == 404) response.setException("Not Found"); if (codeResponse == 405) response.setException("Method Not Allowed"); if (codeResponse == 500) response.setException("Internal Server Error"); return response; } else { response.setException("Problem"); return response; } } /** * Riceve dal client il code inviato da Foursquare,crea la richiesta del * token aggiungendo il ClientSecret parsa il Json di risposta, salvando il * token nel database per poter essere riutilizzato. * * @throws BadRequestException * * **/ @ApiMethod(name = "performTokenRequest", httpMethod = HttpMethod.GET) public void performTokenRequest(@Named("code") String code, @Named("userId") Long userId) throws BadRequestException { log.info("richiesta token"); try { String baseUrl = "https://foursquare.com/oauth2/access_token?client_id="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(Constants.CLIENT_ID); urlBuilder.append("&client_secret=" + Constants.CLIENT_SECRET); urlBuilder.append("&grant_type=authorization_code&code=" + code); String url = urlBuilder.toString(); // log.info(url); PoliUser user = null; URL tokenUrl = new URL(url); // https://foursquare.com/oauth2/access_token?client_id=C0UAYKHQET5QIKKQY50WOMCR50BESMVBGAN1BR5NSEHJ4NKU&client_secret=2RYQF34SHI2IGOETK1RS4PYTCMBHXODSZXJMD1SH4WRKQGCD&grant_type=authorization_code&code= BufferedReader reader = new BufferedReader(new InputStreamReader( tokenUrl.openStream())); JSONObject object = (JSONObject) new JSONTokener(reader.readLine()) .nextValue(); if (!object.has("access_token")) throw new BadRequestException("client code error"); String token = object.getString("access_token"); user = endpointUser.getPoliUser(userId); if (user != null) { user.setTokenFsq(token); // log.info(token); endpointUser.updatePoliUser(user); } } catch (MalformedURLException e) { log.warning(e.getMessage()); } catch (IOException e) { log.warning(e.getMessage()); } catch (JSONException e) { log.info(e.getCause().toString()); log.info(e.getMessage()); } } // aggiunge una venue a Foursquare utilizzando il token dell'utente @ApiMethod(name = "addVenueGPSInfo") public void addVenueGPSInfo(@Named("userId") Long userId, @Named("name") String name, @Nullable @Named("phone") String phone, @Named("coordinates") String coordinates, @Named("categoryId") String categoryId) throws UnauthorizedException { FoursquareApi foursquareApiWithAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); PoliUser user = endpointUser.getPoliUser(userId); if (user.getTokenFsq() == null) throw new UnauthorizedException("Token error"); // http code == 401 foursquareApiWithAuth.setoAuthToken(user.getTokenFsq()); Boolean addressFound = true; ArrayList<String> arrayAddressInfo = new ArrayList<String>(); try { arrayAddressInfo = findInfoAddress(coordinates); } catch (NotFoundException e) { e.printStackTrace(); addressFound = false; } if (addressFound) try { foursquareApiWithAuth .venuesAdd(name, arrayAddressInfo.get(0), null, arrayAddressInfo.get(1), arrayAddressInfo.get(2), arrayAddressInfo.get(3), phone, coordinates, categoryId); } catch (FoursquareApiException e) { e.printStackTrace(); } } /** * * @param coordinates * from gps * @return address,city,state,zip of the coordinates in that order * @throws NotFoundException */ @ApiMethod(name = "findInfoAddress", httpMethod = HttpMethod.GET) public ArrayList<String> findInfoAddress( @Named("coordinates") String coordinates) throws NotFoundException { //String coordinates = "45.478178,9.228031"; String address = null; String city = null; String state = null; String zip = null; ArrayList<String> arrayAddressInfo = new ArrayList<String>(); // find address from coordinates via Google Web service String baseUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(coordinates); urlBuilder.append("&location_type=ROOFTOP&result_type=street_address"); urlBuilder.append("&key=" + Constants.GOOGLE_API_SERVER_KEY); String url = urlBuilder.toString(); URL addressUrl; JSONObject obj = null; try { addressUrl = new URL(url); BufferedReader reader = new BufferedReader(new InputStreamReader( addressUrl.openStream())); StringBuilder content = new StringBuilder(); String line; while (null != (line = reader.readLine())) { content.append(line); } obj = (JSONObject) new JSONTokener(content.toString()).nextValue(); JSONArray results = null; if (obj.get("status").equals("OK")) { results = (JSONArray) obj.get("results"); obj = (JSONObject) results.get(0); results = (JSONArray) obj.get("address_components"); System.out.println(results); for (int i = 0; i < results.length(); i++) { obj = (JSONObject) results.get(i); if (obj.get("types").toString().contains("route")) address = (String) obj.get("short_name"); if (obj.get("types").toString() .contains("administrative_area_level_2")) city = (String) obj.get("short_name"); if (obj.get("types").toString().contains("country")) state = (String) obj.get("short_name"); if (obj.get("types").toString().contains("postal_code")) zip = (String) obj.get("short_name"); } arrayAddressInfo.add(address); arrayAddressInfo.add(city); arrayAddressInfo.add(state); arrayAddressInfo.add(zip); } else throw new NotFoundException("errore"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return arrayAddressInfo; } /** * @return Map di categorie venues Foursquare con coppia Nome/Id (ordinate * per nome) * */ @ApiMethod(name = "findVenuesCategories") public TreeMap<String, String> findVenuesCategories() throws NotFoundException { Result<Category[]> result; TreeMap<String, String> category = new TreeMap<String, String>(); FoursquareApi foursquareApiNoAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); try { result = foursquareApiNoAuth.venuesCategories(); for (Category categ : result.getResult()) { if (categ.getName().equals("Food")) { category.put(categ.getName(), categ.getId()); for (Category c : categ.getCategories()) category.put(c.getName(), c.getId()); } } } catch (FoursquareApiException e) { throw new NotFoundException("Not found venues"); } return category; } /** * * * @param origLat * @param origLong * @param listVenues * @return * @throws NotFoundException */ @ApiMethod(name = "findDistanceAndWalkingDuration", httpMethod = HttpMethod.GET) public ResponseObject findDistanceAndWalkingDuration( @Named("origLat") Double origLat, @Named("origLong") Double origLong, @Named("venuesCoord") String venuesCoord) throws NotFoundException { //venuesCoord.add("45.478178,9.228031"); //venuesCoord.add("45.478178,9.228031"); ArrayList<String> venuesCoordArray = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(venuesCoord,","); while(tokenizer.hasMoreElements()){ StringBuilder coord = new StringBuilder(); coord.append((String) tokenizer.nextElement()); coord.append(","); coord.append((String) tokenizer.nextElement()); venuesCoordArray.add(coord.toString()); } log.info(venuesCoordArray.toString()); System.out.println(venuesCoordArray.toString()); // find distance from coordinates via Google Web service String baseUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(origLat + "," + origLong); urlBuilder.append("&destinations="); Iterator<String> iter = venuesCoordArray.iterator(); urlBuilder.append(iter.next()); while(iter.hasNext()){ log.info("ciclo"); try { urlBuilder.append(URLEncoder.encode("|","UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } urlBuilder.append(iter.next()); } //urlBuilder.append(venueCoord); urlBuilder.append("&mode=walking&language=en-EN&key=" + Constants.GOOGLE_API_SERVER_KEY); String url = urlBuilder.toString(); System.out.println(url); URL addressUrl; JSONObject obj = null; ArrayList<ArrayList<String>> attributes = new ArrayList<ArrayList<String>>(); ResponseObject response = new ResponseObject(); String exception = null; try { addressUrl = new URL(url); BufferedReader reader = new BufferedReader(new InputStreamReader( addressUrl.openStream())); StringBuilder content = new StringBuilder(); String line; while (null != (line = reader.readLine())) { content.append(line); } obj = (JSONObject) new JSONTokener(content.toString()).nextValue(); JSONArray results = null; System.out.println(obj); if (obj.get("status").equals("OK")) { results = (JSONArray) obj.get("rows"); JSONObject elements = results.getJSONObject(0); String duration = ""; String distance = ""; Integer value =99999999; JSONArray element = (JSONArray) elements.get("elements"); for (int i=0;i<element.length();i++){ JSONObject myElem = (JSONObject) element.get(i); if (myElem.get("status").equals("OK")) { duration = myElem.getJSONObject("duration").getString("text"); distance = myElem.getJSONObject("distance").getString("text"); value = (Integer) myElem.getJSONObject("distance").get("value"); } ArrayList<String> attr = new ArrayList<String>(); attr.add(value.toString()); attr.add(distance+" "+duration+" by foot"); attributes.add(attr); } } else { if(obj.has("error_message")){ exception = obj.get("error_message").toString(); log.warning(exception); } throw new NotFoundException(exception); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(attributes.toString()); response.setException(exception); response.setObject(attributes); return response; } private Result<VenuesSearchResult> searchVenuesRequest(String coordinates) throws FoursquareApiException { // Coordinate Politecnico di Milano // ll = "45.478178,9.228031"; FoursquareApi foursquareApiNoAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); // Categorie cibo String categoryIds = "4bf58dd8d48988d143941735,52e81612bcbc57f1066b79f4,4bf58dd8d48988d16c941735," + "4bf58dd8d48988d16d941735,4bf58dd8d48988d16d941735,4bf58dd8d48988d1cb941735,4bf58dd8d48988d1ca941735,4bf58dd8d48988d1ca941735," + "4bf58dd8d48988d1bd941735"; Result<VenuesSearchResult> result; result = foursquareApiNoAuth.venuesSearch(coordinates, null, null, null, null, null, "browse", categoryIds, null, null, null, 800, null); return result; } }
UTF-8
Java
14,856
java
FoursquarePolisocialAPI.java
Java
[ { "context": "KKQY50WOMCR50BESMVBGAN1BR5NSEHJ4NKU&client_secret=2RYQF34SHI2IGOETK1RS4PYTCMBHXODSZXJMD1SH4WRKQGCD&grant_type=authorization_code&code=\n\n\t\t\tBufferedR", "end": 4708, "score": 0.9996612071990967, "start": 4660, "tag": "KEY", "value": "2RYQF34SHI2IGOETK1RS4PYTCMBHXODSZXJMD1SH4WRKQGCD" } ]
null
[]
package it.polimi.dima.polisocial.foursquare; import fi.foyt.foursquare.api.FoursquareApi; import fi.foyt.foursquare.api.FoursquareApiException; import fi.foyt.foursquare.api.Result; import fi.foyt.foursquare.api.entities.Category; import fi.foyt.foursquare.api.entities.CompactVenue; import fi.foyt.foursquare.api.entities.VenuesSearchResult; import it.polimi.dima.polisocial.ResponseObject; import it.polimi.dima.polisocial.endpoint.PoliUserEndpoint; import it.polimi.dima.polisocial.entity.PoliUser; import it.polimi.dima.polisocial.foursquare.constants.Constants; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiMethod.HttpMethod; import com.google.api.server.spi.config.ApiNamespace; import com.google.api.server.spi.config.Named; import com.google.api.server.spi.response.BadRequestException; import com.google.api.server.spi.response.NotFoundException; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.labs.repackaged.org.json.JSONArray; import com.google.appengine.labs.repackaged.org.json.JSONException; import com.google.appengine.labs.repackaged.org.json.JSONObject; import com.google.appengine.labs.repackaged.org.json.JSONTokener; @Api(name = "foursquareendpoint", version = "v1", namespace = @ApiNamespace(ownerDomain = "polimi.it", ownerName = "polimi.it", packagePath = "dima.polisocial.foursquare")) public class FoursquarePolisocialAPI { private static final Logger log = Logger .getLogger(FoursquarePolisocialAPI.class.getName()); private PoliUserEndpoint endpointUser = new PoliUserEndpoint(); @ApiMethod(name = "searchVenues") public ResponseObject searchVenues(@Named("ll") String ll) { Result<VenuesSearchResult> result = null; String exception = null; ResponseObject response = new ResponseObject(); ArrayList<ArrayList<String>> venues = new ArrayList<ArrayList<String>>(); try { result = searchVenuesRequest(ll); } catch (FoursquareApiException e) { // warning Eccezione... log.warning(e.getCause() + " " + e.getMessage()); } if (result != null) { int codeResponse = result.getMeta().getCode(); // tutto ok if (codeResponse == 200) { for (CompactVenue venue : result.getResult().getVenues()) { ArrayList<String> venueDetails = new ArrayList<String>(); venueDetails.add(venue.getId()); venueDetails.add(venue.getName()); venueDetails.add(venue.getLocation().getLat() + "," + venue.getLocation().getLng()); venues.add(venueDetails); } response.setException(exception); response.setObject(venues); } // problemi if (codeResponse == 400) response.setException("Bad Request"); if (codeResponse == 401) response.setException("Unauthorized"); if (codeResponse == 403) response.setException("Forbidden"); if (codeResponse == 404) response.setException("Not Found"); if (codeResponse == 405) response.setException("Method Not Allowed"); if (codeResponse == 500) response.setException("Internal Server Error"); return response; } else { response.setException("Problem"); return response; } } /** * Riceve dal client il code inviato da Foursquare,crea la richiesta del * token aggiungendo il ClientSecret parsa il Json di risposta, salvando il * token nel database per poter essere riutilizzato. * * @throws BadRequestException * * **/ @ApiMethod(name = "performTokenRequest", httpMethod = HttpMethod.GET) public void performTokenRequest(@Named("code") String code, @Named("userId") Long userId) throws BadRequestException { log.info("richiesta token"); try { String baseUrl = "https://foursquare.com/oauth2/access_token?client_id="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(Constants.CLIENT_ID); urlBuilder.append("&client_secret=" + Constants.CLIENT_SECRET); urlBuilder.append("&grant_type=authorization_code&code=" + code); String url = urlBuilder.toString(); // log.info(url); PoliUser user = null; URL tokenUrl = new URL(url); // https://foursquare.com/oauth2/access_token?client_id=C0UAYKHQET5QIKKQY50WOMCR50BESMVBGAN1BR5NSEHJ4NKU&client_secret=<KEY>&grant_type=authorization_code&code= BufferedReader reader = new BufferedReader(new InputStreamReader( tokenUrl.openStream())); JSONObject object = (JSONObject) new JSONTokener(reader.readLine()) .nextValue(); if (!object.has("access_token")) throw new BadRequestException("client code error"); String token = object.getString("access_token"); user = endpointUser.getPoliUser(userId); if (user != null) { user.setTokenFsq(token); // log.info(token); endpointUser.updatePoliUser(user); } } catch (MalformedURLException e) { log.warning(e.getMessage()); } catch (IOException e) { log.warning(e.getMessage()); } catch (JSONException e) { log.info(e.getCause().toString()); log.info(e.getMessage()); } } // aggiunge una venue a Foursquare utilizzando il token dell'utente @ApiMethod(name = "addVenueGPSInfo") public void addVenueGPSInfo(@Named("userId") Long userId, @Named("name") String name, @Nullable @Named("phone") String phone, @Named("coordinates") String coordinates, @Named("categoryId") String categoryId) throws UnauthorizedException { FoursquareApi foursquareApiWithAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); PoliUser user = endpointUser.getPoliUser(userId); if (user.getTokenFsq() == null) throw new UnauthorizedException("Token error"); // http code == 401 foursquareApiWithAuth.setoAuthToken(user.getTokenFsq()); Boolean addressFound = true; ArrayList<String> arrayAddressInfo = new ArrayList<String>(); try { arrayAddressInfo = findInfoAddress(coordinates); } catch (NotFoundException e) { e.printStackTrace(); addressFound = false; } if (addressFound) try { foursquareApiWithAuth .venuesAdd(name, arrayAddressInfo.get(0), null, arrayAddressInfo.get(1), arrayAddressInfo.get(2), arrayAddressInfo.get(3), phone, coordinates, categoryId); } catch (FoursquareApiException e) { e.printStackTrace(); } } /** * * @param coordinates * from gps * @return address,city,state,zip of the coordinates in that order * @throws NotFoundException */ @ApiMethod(name = "findInfoAddress", httpMethod = HttpMethod.GET) public ArrayList<String> findInfoAddress( @Named("coordinates") String coordinates) throws NotFoundException { //String coordinates = "45.478178,9.228031"; String address = null; String city = null; String state = null; String zip = null; ArrayList<String> arrayAddressInfo = new ArrayList<String>(); // find address from coordinates via Google Web service String baseUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(coordinates); urlBuilder.append("&location_type=ROOFTOP&result_type=street_address"); urlBuilder.append("&key=" + Constants.GOOGLE_API_SERVER_KEY); String url = urlBuilder.toString(); URL addressUrl; JSONObject obj = null; try { addressUrl = new URL(url); BufferedReader reader = new BufferedReader(new InputStreamReader( addressUrl.openStream())); StringBuilder content = new StringBuilder(); String line; while (null != (line = reader.readLine())) { content.append(line); } obj = (JSONObject) new JSONTokener(content.toString()).nextValue(); JSONArray results = null; if (obj.get("status").equals("OK")) { results = (JSONArray) obj.get("results"); obj = (JSONObject) results.get(0); results = (JSONArray) obj.get("address_components"); System.out.println(results); for (int i = 0; i < results.length(); i++) { obj = (JSONObject) results.get(i); if (obj.get("types").toString().contains("route")) address = (String) obj.get("short_name"); if (obj.get("types").toString() .contains("administrative_area_level_2")) city = (String) obj.get("short_name"); if (obj.get("types").toString().contains("country")) state = (String) obj.get("short_name"); if (obj.get("types").toString().contains("postal_code")) zip = (String) obj.get("short_name"); } arrayAddressInfo.add(address); arrayAddressInfo.add(city); arrayAddressInfo.add(state); arrayAddressInfo.add(zip); } else throw new NotFoundException("errore"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return arrayAddressInfo; } /** * @return Map di categorie venues Foursquare con coppia Nome/Id (ordinate * per nome) * */ @ApiMethod(name = "findVenuesCategories") public TreeMap<String, String> findVenuesCategories() throws NotFoundException { Result<Category[]> result; TreeMap<String, String> category = new TreeMap<String, String>(); FoursquareApi foursquareApiNoAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); try { result = foursquareApiNoAuth.venuesCategories(); for (Category categ : result.getResult()) { if (categ.getName().equals("Food")) { category.put(categ.getName(), categ.getId()); for (Category c : categ.getCategories()) category.put(c.getName(), c.getId()); } } } catch (FoursquareApiException e) { throw new NotFoundException("Not found venues"); } return category; } /** * * * @param origLat * @param origLong * @param listVenues * @return * @throws NotFoundException */ @ApiMethod(name = "findDistanceAndWalkingDuration", httpMethod = HttpMethod.GET) public ResponseObject findDistanceAndWalkingDuration( @Named("origLat") Double origLat, @Named("origLong") Double origLong, @Named("venuesCoord") String venuesCoord) throws NotFoundException { //venuesCoord.add("45.478178,9.228031"); //venuesCoord.add("45.478178,9.228031"); ArrayList<String> venuesCoordArray = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(venuesCoord,","); while(tokenizer.hasMoreElements()){ StringBuilder coord = new StringBuilder(); coord.append((String) tokenizer.nextElement()); coord.append(","); coord.append((String) tokenizer.nextElement()); venuesCoordArray.add(coord.toString()); } log.info(venuesCoordArray.toString()); System.out.println(venuesCoordArray.toString()); // find distance from coordinates via Google Web service String baseUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="; StringBuilder urlBuilder = new StringBuilder(baseUrl); urlBuilder.append(origLat + "," + origLong); urlBuilder.append("&destinations="); Iterator<String> iter = venuesCoordArray.iterator(); urlBuilder.append(iter.next()); while(iter.hasNext()){ log.info("ciclo"); try { urlBuilder.append(URLEncoder.encode("|","UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } urlBuilder.append(iter.next()); } //urlBuilder.append(venueCoord); urlBuilder.append("&mode=walking&language=en-EN&key=" + Constants.GOOGLE_API_SERVER_KEY); String url = urlBuilder.toString(); System.out.println(url); URL addressUrl; JSONObject obj = null; ArrayList<ArrayList<String>> attributes = new ArrayList<ArrayList<String>>(); ResponseObject response = new ResponseObject(); String exception = null; try { addressUrl = new URL(url); BufferedReader reader = new BufferedReader(new InputStreamReader( addressUrl.openStream())); StringBuilder content = new StringBuilder(); String line; while (null != (line = reader.readLine())) { content.append(line); } obj = (JSONObject) new JSONTokener(content.toString()).nextValue(); JSONArray results = null; System.out.println(obj); if (obj.get("status").equals("OK")) { results = (JSONArray) obj.get("rows"); JSONObject elements = results.getJSONObject(0); String duration = ""; String distance = ""; Integer value =99999999; JSONArray element = (JSONArray) elements.get("elements"); for (int i=0;i<element.length();i++){ JSONObject myElem = (JSONObject) element.get(i); if (myElem.get("status").equals("OK")) { duration = myElem.getJSONObject("duration").getString("text"); distance = myElem.getJSONObject("distance").getString("text"); value = (Integer) myElem.getJSONObject("distance").get("value"); } ArrayList<String> attr = new ArrayList<String>(); attr.add(value.toString()); attr.add(distance+" "+duration+" by foot"); attributes.add(attr); } } else { if(obj.has("error_message")){ exception = obj.get("error_message").toString(); log.warning(exception); } throw new NotFoundException(exception); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(attributes.toString()); response.setException(exception); response.setObject(attributes); return response; } private Result<VenuesSearchResult> searchVenuesRequest(String coordinates) throws FoursquareApiException { // Coordinate Politecnico di Milano // ll = "45.478178,9.228031"; FoursquareApi foursquareApiNoAuth = new FoursquareApi( Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.CALLBACK_URL2); // Categorie cibo String categoryIds = "4bf58dd8d48988d143941735,52e81612bcbc57f1066b79f4,4bf58dd8d48988d16c941735," + "4bf58dd8d48988d16d941735,4bf58dd8d48988d16d941735,4bf58dd8d48988d1cb941735,4bf58dd8d48988d1ca941735,4bf58dd8d48988d1ca941735," + "4bf58dd8d48988d1bd941735"; Result<VenuesSearchResult> result; result = foursquareApiNoAuth.venuesSearch(coordinates, null, null, null, null, null, "browse", categoryIds, null, null, null, 800, null); return result; } }
14,813
0.710151
0.691505
435
33.151726
25.02183
206
false
false
0
0
0
0
0
0
3.036782
false
false
12
367c4e2e5d7e329db9457d4a0761ac4dba22cb65
5,652,176,994,144
8e24bff45a63fe23d655339a4c24fc596491ccff
/src/test/java/br/com/adaptideas/scraper/infra/InputStreamToStringReaderTest.java
b439364d2d8acc2be702e3676cfc2940a0b6769b
[]
no_license
adaptideas/scraper
https://github.com/adaptideas/scraper
5af46504e657b4f248d2b8f19b56127990a3dc40
25d507b8dfde6b970ec3266155757d20756fd27d
refs/heads/master
2021-01-10T22:08:02.212000
2014-12-02T15:38:02
2014-12-02T15:38:02
1,403,223
3
3
null
false
2012-09-29T00:29:45
2011-02-23T17:53:30
2012-09-29T00:29:45
2012-09-29T00:29:45
386
null
2
0
Java
null
null
package br.com.adaptideas.scraper.infra; import java.io.ByteArrayInputStream; import org.junit.Assert; import org.junit.Test; import br.com.adaptideas.scraper.infra.InputStreamToStringReader; /** * @author jonasabreu * */ final public class InputStreamToStringReaderTest { @Test public void testThatRemovesWhiteChars() { String string = new InputStreamToStringReader("UTF-8").read(new ByteArrayInputStream( "\ntext \n\t \r other text\n\r".getBytes())); Assert.assertEquals("text other text", string); } }
UTF-8
Java
529
java
InputStreamToStringReaderTest.java
Java
[ { "context": "r.infra.InputStreamToStringReader;\n\n/**\n * @author jonasabreu\n * \n */\nfinal public class InputStreamToStringRea", "end": 221, "score": 0.9982223510742188, "start": 211, "tag": "USERNAME", "value": "jonasabreu" } ]
null
[]
package br.com.adaptideas.scraper.infra; import java.io.ByteArrayInputStream; import org.junit.Assert; import org.junit.Test; import br.com.adaptideas.scraper.infra.InputStreamToStringReader; /** * @author jonasabreu * */ final public class InputStreamToStringReaderTest { @Test public void testThatRemovesWhiteChars() { String string = new InputStreamToStringReader("UTF-8").read(new ByteArrayInputStream( "\ntext \n\t \r other text\n\r".getBytes())); Assert.assertEquals("text other text", string); } }
529
0.750473
0.748582
23
22
25.104998
87
false
false
0
0
0
0
0
0
0.826087
false
false
12
34f2e07ef0f5f1dc68336a904654258c0e612e81
2,619,930,051,561
686cf766393c63b45d22e7b4ab923c197f1def57
/Infexxion/app/src/main/java/com/infexxion/application/fragments/MainGame/OnlineMultiplayerGame/BluetoothGame/BluetoothClientGameFragment.java
eb561bed73206b4d4f4b96500a549ebedb12189d
[]
no_license
RotemKariv/afeka-introduction-to-cellular-applications-infexxion
https://github.com/RotemKariv/afeka-introduction-to-cellular-applications-infexxion
aeb9cfca41f12820ca44f5225a3938bfad46a20b
a20e284ae5269e588da17ab8ce8a4c013b0146e9
refs/heads/master
2020-04-26T06:48:35.450000
2019-09-02T13:10:33
2019-09-02T13:10:33
173,376,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.infexxion.application.fragments.MainGame.OnlineMultiplayerGame.BluetoothGame; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.arch.persistence.room.Room; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.DialogInterface; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.constraint.ConstraintLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.infexxion.R; import com.infexxion.application.MainActivity; import com.infexxion.application.fragments.GameOver.GameOverFragment; import com.infexxion.application.fragments.MainGame.AtaxxTileAdapter; import com.infexxion.application.fragments.MainGame.AtaxxTileView; import com.infexxion.application.fragments.MainGame.HexxagonTileAdapter; import com.infexxion.application.fragments.MainGame.HexxagonTileView; import com.infexxion.application.fragments.MainGame.TileAdapter; import com.infexxion.application.fragments.MainMenu.GameMode; import com.infexxion.database.AppDatabase; import com.infexxion.database.entity.AtaxxBoardEntity; import com.infexxion.database.entity.HexxagonBoardEntity; import com.infexxion.logic.AtaxxBoard; import com.infexxion.logic.Board; import com.infexxion.logic.Game; import com.infexxion.logic.GamePiece; import com.infexxion.logic.GameType; import com.infexxion.logic.HexxagonBoard; import com.infexxion.logic.Tile; import com.infexxion.logic.TileStatus; import java.io.IOException; import java.util.UUID; public class BluetoothClientGameFragment extends Fragment { public static final String BUNDLE_MAC_ADDRESS_KEY = "MAC_ADDRESS"; public static final String BOARD_DELIMITER = ","; public static final String INIT_MESSAGE = "INIT"; public static final String SELECT_POSITION_MESSAGE = "SELECT_POSITION"; public static final String SURRENDER_MESSAGE = "SURRENDER"; public static final String UUID_STRING = "77aaebd4-cfc0-491c-a445-0fb354a69572"; private Activity activity; private MediaPlayer clickSFX; private MediaPlayer badClickSFX; private TextView turnCounterTextView; private TextView playerTurnTextView; private ProgressBar enemyProgressBar; private TextView player1GamePieceAmountTextView; private TextView player2GamePieceAmountTextView; private GridView gameGridView; private Button finishButton; private ConstraintLayout loadingConstraintLayout; private ConstraintLayout gameConstraintLayout; private TileAdapter tileAdapter; private Game game; private int selectedTilePosition; private BluetoothSocket playerSocket; private String macAddress; private BluetoothService bluetoothService; private Handler handler; public BluetoothClientGameFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { openAttributesBundle(); return inflater.inflate(R.layout.fragment_game, container, false); } private void openAttributesBundle() { Bundle bundle = getArguments(); if (bundle != null && game == null) { macAddress = bundle.getString(BUNDLE_MAC_ADDRESS_KEY); game = new Game(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); activity = getActivity(); clickSFX = MediaPlayer.create(activity.getApplicationContext(), R.raw.pop_sfx); badClickSFX = MediaPlayer.create(activity.getApplicationContext(), R.raw.click_off_sfx); turnCounterTextView = activity.findViewById(R.id.turnCounterTextView); playerTurnTextView = activity.findViewById(R.id.currentPlayerTextView); player1GamePieceAmountTextView = activity.findViewById(R.id.playerGamePieceAmountTextView); player2GamePieceAmountTextView = activity.findViewById(R.id.enemyGamePieceAmountTextView); enemyProgressBar = activity.findViewById(R.id.enemyProgressBar); enemyProgressBar.setVisibility(View.INVISIBLE); loadingConstraintLayout = activity.findViewById(R.id.LoadingConstrainLayout); loadingConstraintLayout.setVisibility(View.INVISIBLE); gameConstraintLayout = activity.findViewById(R.id.GameConstraintLayout); gameGridView = activity.findViewById(R.id.gameGridView); finishButton = activity.findViewById(R.id.finishButton); switch (game.getGameType()) { case ATAXX: tileAdapter = new AtaxxTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; case HEXXAGON: tileAdapter = new HexxagonTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; } gameGridView.setAdapter(tileAdapter); gameGridView.setNumColumns(game.getBoard().getTiles()[0].length); finishButton.setText(R.string.surrender); if(!game.getIsOver()){ handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { decryptMessage(msg); return true; } }); gameGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(bluetoothService != null) { bluetoothService.writeMessage(createSelectPositionMessage(position).getBytes()); animateTileSelect(position); } } }); finishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clickSFX.start(); if(bluetoothService != null) { openConfirmationDialog(); } } }); new ConnectBluetoothServerTask().execute(); selectedTilePosition = -1; showLoadingLayout(); }else{ int[] amounts = game.calculateGamePieceAmounts(); player1GamePieceAmountTextView.setText(String.valueOf(amounts[1])); player2GamePieceAmountTextView.setText(String.valueOf(amounts[2])); turnCounterTextView.setText(String.valueOf(game.getTurn())); playerTurnTextView.setText(R.string.enemy); showGameLayout(); } } public void showLoadingLayout(){ gameConstraintLayout.setVisibility(View.INVISIBLE); loadingConstraintLayout.setVisibility(View.VISIBLE); } public void showGameLayout(){ gameConstraintLayout.setVisibility(View.VISIBLE); loadingConstraintLayout.setVisibility(View.INVISIBLE); } public void animateTileSelect(int position) { Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int row = position / columns; int column = position % columns; GamePiece gamePiece = null; if (game.getTurn() % 2 != 0) gamePiece = game.getPlayer1().getGamePiece(); else gamePiece = game.getPlayer2().getGamePiece(); if (selectedTilePosition == -1) { if (game.selectFirstTile(row, column, gamePiece)) { clickSFX.start(); selectedTilePosition = position; } else badClickSFX.start(); } else { int selectedRow = selectedTilePosition / columns; int selectedColumn = selectedTilePosition % columns; if (game.selectSecondTile(selectedRow, selectedColumn, row, column, gamePiece)) { clickSFX.start(); animateTileChange(gameGridView.getChildAt(position)); animateTileAttack(position); } else if (selectedTilePosition == position) { clickSFX.start(); selectedTilePosition = -1; } else { badClickSFX.start(); selectedTilePosition = -1; } } tileAdapter.notifyDataSetChanged(); } public void animateTileAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int oldRow = selectedTilePosition / columns; int oldColumn = selectedTilePosition % columns; final int row = position / columns; final int column = position % columns; final GamePiece gamePiece; if (game.getTurn() % 2 != 0) gamePiece = game.getPlayer1().getGamePiece(); else gamePiece = game.getPlayer2().getGamePiece(); switch (game.getGameType()) { case ATAXX: animateAtaxxTileNeighborsAttack(position); break; case HEXXAGON: animateHexxagonTileNeighborsAttack(position); break; } Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { } activity.runOnUiThread(new Runnable() { @Override public void run() { game.attackNeighbors(row, column, gamePiece); tileAdapter.notifyDataSetChanged(); selectedTilePosition = -1; startNextTurn(); } }); } }); thread.start(); } public void animateTileChange(View view) { final ImageView tile; final ImageView gamePiece; switch (game.getGameType()) { case ATAXX: final AtaxxTileView ataxxTileView = (AtaxxTileView) view; tile = ataxxTileView.getTile(); gamePiece = ataxxTileView.getGamePiece(); break; case HEXXAGON: final HexxagonTileView hexxagonTileView = (HexxagonTileView) view; tile = hexxagonTileView.getTile(); gamePiece = hexxagonTileView.getGamePiece(); break; default: tile = null; gamePiece = null; } final ObjectAnimator flipOneSide = ObjectAnimator.ofFloat(tile, "rotationY", -180f, 0f); flipOneSide.setDuration(500); flipOneSide.setInterpolator(new DecelerateInterpolator()); flipOneSide.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); gamePiece.setVisibility(View.INVISIBLE); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); gamePiece.setVisibility(View.VISIBLE); } }); flipOneSide.start(); } public void animateAtaxxTileNeighborsAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int rows = tiles.length; int columns = tiles[0].length; int currentRow = position / columns; int upperRow = currentRow - 1; int lowerRow = currentRow + 1; int currentColumn = position % columns; int leftColumn = currentColumn - 1; int rightColumn = currentColumn + 1; int childPosition; GamePiece gamePieceToAttack = null; switch (tiles[currentRow][currentColumn].getGamePiece()) { case GAME_PIECE_1: gamePieceToAttack = GamePiece.GAME_PIECE_2; break; case GAME_PIECE_2: gamePieceToAttack = GamePiece.GAME_PIECE_1; break; } if (0 <= upperRow) { childPosition = upperRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } } public void animateHexxagonTileNeighborsAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int rows = tiles.length; int columns = tiles[0].length; int currentRow = position / columns; int upperRow = currentRow - 1; int lowerRow = currentRow + 1; int currentColumn = position % columns; int leftColumn = currentColumn - 1; int rightColumn = currentColumn + 1; int childPosition; GamePiece gamePieceToAttack = null; switch (tiles[currentRow][currentColumn].getGamePiece()) { case GAME_PIECE_1: gamePieceToAttack = GamePiece.GAME_PIECE_2; break; case GAME_PIECE_2: gamePieceToAttack = GamePiece.GAME_PIECE_1; break; } if (currentColumn % 2 != 0) { if (0 <= upperRow) { childPosition = upperRow * columns; animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } } else { if (0 <= upperRow) { childPosition = upperRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); } } } public void animateTileAttack(View view, int position, GamePiece gamePiece) { final ScaleAnimation shrink = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); final ScaleAnimation expand = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); shrink.setDuration(500); expand.setDuration(500); final ImageView tileImageView; final ImageView gamePieceImageView; Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int row = position / columns; int column = position % columns; Tile tile = tiles[row][column]; switch (game.getGameType()) { case ATAXX: final AtaxxTileView ataxxTileView = (AtaxxTileView) view; tileImageView = ataxxTileView.getTile(); gamePieceImageView = ataxxTileView.getGamePiece(); break; case HEXXAGON: final HexxagonTileView hexxagonTileView = (HexxagonTileView) view; tileImageView = hexxagonTileView.getTile(); gamePieceImageView = hexxagonTileView.getGamePiece(); break; default: tileImageView = null; gamePieceImageView = null; } shrink.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { gamePieceImageView.setVisibility(View.INVISIBLE); } @Override public void onAnimationEnd(Animation animation) { tileImageView.startAnimation(expand); } @Override public void onAnimationRepeat(Animation animation) { } }); expand.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { gamePieceImageView.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); if (tile.getGamePiece() == gamePiece) tileImageView.startAnimation(shrink); } private void startNextTurn() { final int winningPlayer = game.checkGameOver(); int[] amounts = game.calculateGamePieceAmounts(); player1GamePieceAmountTextView.setText(String.valueOf(amounts[1])); player2GamePieceAmountTextView.setText(String.valueOf(amounts[2])); if (winningPlayer < 0) { int nextTurn = game.getTurn() + 1; game.setTurn(nextTurn); turnCounterTextView.setText(String.valueOf(nextTurn)); if (nextTurn % 2 == 0) { gameGridView.setEnabled(true); finishButton.setEnabled(true); playerTurnTextView.setText(R.string.enemy); enemyProgressBar.setVisibility(View.INVISIBLE); } else { gameGridView.setEnabled(false); finishButton.setEnabled(false); playerTurnTextView.setText(R.string.player); enemyProgressBar.setVisibility(View.VISIBLE); } tileAdapter.notifyDataSetChanged(); } else { Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } activity.runOnUiThread(new Runnable() { @Override public void run() { startGameOverFragment(winningPlayer); } }); } }); thread.start(); } } private void startGameOverFragment(int winningPlayer) { gameGridView.setEnabled(false); finishButton.setEnabled(false); try{ playerSocket.close(); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "startGameOverFragment: Couldn't close bluetooth socket"); } Bundle bundle = getArguments(); String winningPlayerIdentity = null; switch (winningPlayer) { case 0: winningPlayerIdentity = activity.getString(R.string.everyone); break; case 1: winningPlayerIdentity = activity.getString(R.string.player); break; case 2: winningPlayerIdentity = activity.getString(R.string.enemy); break; } bundle.putString(GameOverFragment.BUNDLE_GAME_OVER_WINNING_PLAYER_KEY, winningPlayerIdentity); GameOverFragment fragment = new GameOverFragment(); fragment.setArguments(bundle); ((MainActivity) activity).loadFragment(fragment, true, BluetoothClientGameFragment.class.getName()); } private Board convertBoardFromString(String boardString, int rows, int columns) { String[] boardParts = boardString.split(BOARD_DELIMITER); Board board = null; switch (game.getGameType()) { case ATAXX: board = new AtaxxBoard(rows, columns); break; case HEXXAGON: board = new HexxagonBoard(rows, columns); break; } Tile[][] tiles = board.getTiles(); Tile tile; GamePiece gamePiece; for (int row = 0, index = 0; row < rows; row++) for (int column = 0; column < columns; column++, index++) { tile = tiles[row][column]; gamePiece = GamePiece.values()[Integer.parseInt(boardParts[index])]; tile.setGamePiece(gamePiece); if (gamePiece == GamePiece.BLOCKED) tile.setTileStatus(TileStatus.UNAVAILABLE); } return board; } public void openConfirmationDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(getString(R.string.surrender)); builder.setMessage(R.string.last_chance); builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { game.setIsOver(true); tileAdapter.notifyDataSetChanged(); int winningPlayer = 1; bluetoothService.writeMessage(createSurrenderMessage().getBytes()); startGameOverFragment(winningPlayer); } }); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } private void decryptMessage(Message message){ byte[] readBuffer = (byte[])message.obj; String stringMessage = new String(readBuffer, 0, message.arg1); String[] stringParts = stringMessage.split(BOARD_DELIMITER,2); switch(stringParts[0]){ case INIT_MESSAGE: readInitMessage(stringParts[1]); break; case SELECT_POSITION_MESSAGE: readSelectPositionMessage(stringParts[1]); break; case SURRENDER_MESSAGE: readSurrenderMessage(); break; } } private String createSelectPositionMessage(int position){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(SELECT_POSITION_MESSAGE); stringBuilder.append(BOARD_DELIMITER); stringBuilder.append(position); return stringBuilder.toString(); } private String createSurrenderMessage(){ return SURRENDER_MESSAGE; } private void readSelectPositionMessage(String message){ int position = Integer.parseInt(message); animateTileSelect(position); } private void readSurrenderMessage(){ game.setIsOver(true); tileAdapter.notifyDataSetChanged(); int winningPlayer = 2; startGameOverFragment(winningPlayer); } class ConnectBluetoothServerTask extends AsyncTask<Void, Void, BluetoothSocket> { private BluetoothSocket bluetoothSocket; private BluetoothDevice bluetoothDevice; private BluetoothAdapter bluetoothAdapter; @Override protected void onPreExecute() { showLoadingLayout(); BluetoothSocket tempSocket = null; bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); bluetoothDevice = bluetoothAdapter.getRemoteDevice(macAddress); String name = activity.getString(R.string.app_name); try{ tempSocket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUID_STRING)); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't create bluetooth socket"); activity.onBackPressed(); } bluetoothSocket = tempSocket; } protected BluetoothSocket doInBackground(Void... Voids) { try{ bluetoothSocket.connect(); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't connect with the bluetooth socket"); try { bluetoothSocket.close(); }catch(IOException e2){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't close bluetooth socket"); } bluetoothSocket = null; } return bluetoothSocket; } protected void onProgressUpdate(Void... voids) { } protected void onPostExecute(BluetoothSocket result) { if(bluetoothSocket == null){ activity.onBackPressed(); }else{ playerSocket = result; bluetoothService = new BluetoothService(playerSocket, handler); bluetoothService.start(); } } } private void readInitMessage(String message){ String[] stringParts = message.split(BOARD_DELIMITER, 6); GameType gameType = GameType.values()[Integer.parseInt(stringParts[0])]; String boardName = stringParts[1]; String creatorName = stringParts[2]; int rows = Integer.parseInt(stringParts[3]); int columns = Integer.parseInt(stringParts[4]); String boardString = stringParts[5]; game = new Game(); game.setGameType(gameType); Board board = convertBoardFromString(boardString, rows, columns); game.setBoard(board); switch (game.getGameType()) { case ATAXX: tileAdapter = new AtaxxTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; case HEXXAGON: tileAdapter = new HexxagonTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; } gameGridView.setAdapter(tileAdapter); gameGridView.setNumColumns(game.getBoard().getTiles()[0].length); new WriteBoardTask().execute(boardString, boardName, creatorName, rows, columns); showGameLayout(); startNextTurn(); } class WriteBoardTask extends AsyncTask<Object, Void, Void> { private AppDatabase appDatabase; @Override protected void onPreExecute() { appDatabase = Room.databaseBuilder(activity.getApplicationContext(), AppDatabase.class, MainActivity.DATABASE_NAME).build(); } protected Void doInBackground(Object... objects) { if(game.getGameType() == GameType.ATAXX) { AtaxxBoardEntity ataxxBoard = new AtaxxBoardEntity(); ataxxBoard.setBoard((String) objects[0]); ataxxBoard.setBoardName((String) objects[1]); ataxxBoard.setCreatorName((String) objects[2]); ataxxBoard.setRowsAmount((int) objects[3]); ataxxBoard.setColumnsAmount((int) objects[4]); appDatabase.ataxxBoardDao().insert(ataxxBoard); }else if(game.getGameType() == GameType.HEXXAGON){ HexxagonBoardEntity hexxagonBoard = new HexxagonBoardEntity(); hexxagonBoard.setBoard((String) objects[0]); hexxagonBoard.setBoardName((String) objects[1]); hexxagonBoard.setCreatorName((String) objects[2]); hexxagonBoard.setRowsAmount((int) objects[3]); hexxagonBoard.setColumnsAmount((int) objects[4]); appDatabase.hexxagonBoardDao().insert(hexxagonBoard); } return null; } protected void onProgressUpdate(Void... voids) { } protected void onPostExecute(Void result) { } } }
UTF-8
Java
31,371
java
BluetoothClientGameFragment.java
Java
[]
null
[]
package com.infexxion.application.fragments.MainGame.OnlineMultiplayerGame.BluetoothGame; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.arch.persistence.room.Room; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.DialogInterface; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.constraint.ConstraintLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.infexxion.R; import com.infexxion.application.MainActivity; import com.infexxion.application.fragments.GameOver.GameOverFragment; import com.infexxion.application.fragments.MainGame.AtaxxTileAdapter; import com.infexxion.application.fragments.MainGame.AtaxxTileView; import com.infexxion.application.fragments.MainGame.HexxagonTileAdapter; import com.infexxion.application.fragments.MainGame.HexxagonTileView; import com.infexxion.application.fragments.MainGame.TileAdapter; import com.infexxion.application.fragments.MainMenu.GameMode; import com.infexxion.database.AppDatabase; import com.infexxion.database.entity.AtaxxBoardEntity; import com.infexxion.database.entity.HexxagonBoardEntity; import com.infexxion.logic.AtaxxBoard; import com.infexxion.logic.Board; import com.infexxion.logic.Game; import com.infexxion.logic.GamePiece; import com.infexxion.logic.GameType; import com.infexxion.logic.HexxagonBoard; import com.infexxion.logic.Tile; import com.infexxion.logic.TileStatus; import java.io.IOException; import java.util.UUID; public class BluetoothClientGameFragment extends Fragment { public static final String BUNDLE_MAC_ADDRESS_KEY = "MAC_ADDRESS"; public static final String BOARD_DELIMITER = ","; public static final String INIT_MESSAGE = "INIT"; public static final String SELECT_POSITION_MESSAGE = "SELECT_POSITION"; public static final String SURRENDER_MESSAGE = "SURRENDER"; public static final String UUID_STRING = "77aaebd4-cfc0-491c-a445-0fb354a69572"; private Activity activity; private MediaPlayer clickSFX; private MediaPlayer badClickSFX; private TextView turnCounterTextView; private TextView playerTurnTextView; private ProgressBar enemyProgressBar; private TextView player1GamePieceAmountTextView; private TextView player2GamePieceAmountTextView; private GridView gameGridView; private Button finishButton; private ConstraintLayout loadingConstraintLayout; private ConstraintLayout gameConstraintLayout; private TileAdapter tileAdapter; private Game game; private int selectedTilePosition; private BluetoothSocket playerSocket; private String macAddress; private BluetoothService bluetoothService; private Handler handler; public BluetoothClientGameFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { openAttributesBundle(); return inflater.inflate(R.layout.fragment_game, container, false); } private void openAttributesBundle() { Bundle bundle = getArguments(); if (bundle != null && game == null) { macAddress = bundle.getString(BUNDLE_MAC_ADDRESS_KEY); game = new Game(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); activity = getActivity(); clickSFX = MediaPlayer.create(activity.getApplicationContext(), R.raw.pop_sfx); badClickSFX = MediaPlayer.create(activity.getApplicationContext(), R.raw.click_off_sfx); turnCounterTextView = activity.findViewById(R.id.turnCounterTextView); playerTurnTextView = activity.findViewById(R.id.currentPlayerTextView); player1GamePieceAmountTextView = activity.findViewById(R.id.playerGamePieceAmountTextView); player2GamePieceAmountTextView = activity.findViewById(R.id.enemyGamePieceAmountTextView); enemyProgressBar = activity.findViewById(R.id.enemyProgressBar); enemyProgressBar.setVisibility(View.INVISIBLE); loadingConstraintLayout = activity.findViewById(R.id.LoadingConstrainLayout); loadingConstraintLayout.setVisibility(View.INVISIBLE); gameConstraintLayout = activity.findViewById(R.id.GameConstraintLayout); gameGridView = activity.findViewById(R.id.gameGridView); finishButton = activity.findViewById(R.id.finishButton); switch (game.getGameType()) { case ATAXX: tileAdapter = new AtaxxTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; case HEXXAGON: tileAdapter = new HexxagonTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; } gameGridView.setAdapter(tileAdapter); gameGridView.setNumColumns(game.getBoard().getTiles()[0].length); finishButton.setText(R.string.surrender); if(!game.getIsOver()){ handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { decryptMessage(msg); return true; } }); gameGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(bluetoothService != null) { bluetoothService.writeMessage(createSelectPositionMessage(position).getBytes()); animateTileSelect(position); } } }); finishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clickSFX.start(); if(bluetoothService != null) { openConfirmationDialog(); } } }); new ConnectBluetoothServerTask().execute(); selectedTilePosition = -1; showLoadingLayout(); }else{ int[] amounts = game.calculateGamePieceAmounts(); player1GamePieceAmountTextView.setText(String.valueOf(amounts[1])); player2GamePieceAmountTextView.setText(String.valueOf(amounts[2])); turnCounterTextView.setText(String.valueOf(game.getTurn())); playerTurnTextView.setText(R.string.enemy); showGameLayout(); } } public void showLoadingLayout(){ gameConstraintLayout.setVisibility(View.INVISIBLE); loadingConstraintLayout.setVisibility(View.VISIBLE); } public void showGameLayout(){ gameConstraintLayout.setVisibility(View.VISIBLE); loadingConstraintLayout.setVisibility(View.INVISIBLE); } public void animateTileSelect(int position) { Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int row = position / columns; int column = position % columns; GamePiece gamePiece = null; if (game.getTurn() % 2 != 0) gamePiece = game.getPlayer1().getGamePiece(); else gamePiece = game.getPlayer2().getGamePiece(); if (selectedTilePosition == -1) { if (game.selectFirstTile(row, column, gamePiece)) { clickSFX.start(); selectedTilePosition = position; } else badClickSFX.start(); } else { int selectedRow = selectedTilePosition / columns; int selectedColumn = selectedTilePosition % columns; if (game.selectSecondTile(selectedRow, selectedColumn, row, column, gamePiece)) { clickSFX.start(); animateTileChange(gameGridView.getChildAt(position)); animateTileAttack(position); } else if (selectedTilePosition == position) { clickSFX.start(); selectedTilePosition = -1; } else { badClickSFX.start(); selectedTilePosition = -1; } } tileAdapter.notifyDataSetChanged(); } public void animateTileAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int oldRow = selectedTilePosition / columns; int oldColumn = selectedTilePosition % columns; final int row = position / columns; final int column = position % columns; final GamePiece gamePiece; if (game.getTurn() % 2 != 0) gamePiece = game.getPlayer1().getGamePiece(); else gamePiece = game.getPlayer2().getGamePiece(); switch (game.getGameType()) { case ATAXX: animateAtaxxTileNeighborsAttack(position); break; case HEXXAGON: animateHexxagonTileNeighborsAttack(position); break; } Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { } activity.runOnUiThread(new Runnable() { @Override public void run() { game.attackNeighbors(row, column, gamePiece); tileAdapter.notifyDataSetChanged(); selectedTilePosition = -1; startNextTurn(); } }); } }); thread.start(); } public void animateTileChange(View view) { final ImageView tile; final ImageView gamePiece; switch (game.getGameType()) { case ATAXX: final AtaxxTileView ataxxTileView = (AtaxxTileView) view; tile = ataxxTileView.getTile(); gamePiece = ataxxTileView.getGamePiece(); break; case HEXXAGON: final HexxagonTileView hexxagonTileView = (HexxagonTileView) view; tile = hexxagonTileView.getTile(); gamePiece = hexxagonTileView.getGamePiece(); break; default: tile = null; gamePiece = null; } final ObjectAnimator flipOneSide = ObjectAnimator.ofFloat(tile, "rotationY", -180f, 0f); flipOneSide.setDuration(500); flipOneSide.setInterpolator(new DecelerateInterpolator()); flipOneSide.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); gamePiece.setVisibility(View.INVISIBLE); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); gamePiece.setVisibility(View.VISIBLE); } }); flipOneSide.start(); } public void animateAtaxxTileNeighborsAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int rows = tiles.length; int columns = tiles[0].length; int currentRow = position / columns; int upperRow = currentRow - 1; int lowerRow = currentRow + 1; int currentColumn = position % columns; int leftColumn = currentColumn - 1; int rightColumn = currentColumn + 1; int childPosition; GamePiece gamePieceToAttack = null; switch (tiles[currentRow][currentColumn].getGamePiece()) { case GAME_PIECE_1: gamePieceToAttack = GamePiece.GAME_PIECE_2; break; case GAME_PIECE_2: gamePieceToAttack = GamePiece.GAME_PIECE_1; break; } if (0 <= upperRow) { childPosition = upperRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } } public void animateHexxagonTileNeighborsAttack(int position) { Tile[][] tiles = game.getBoard().getTiles(); int rows = tiles.length; int columns = tiles[0].length; int currentRow = position / columns; int upperRow = currentRow - 1; int lowerRow = currentRow + 1; int currentColumn = position % columns; int leftColumn = currentColumn - 1; int rightColumn = currentColumn + 1; int childPosition; GamePiece gamePieceToAttack = null; switch (tiles[currentRow][currentColumn].getGamePiece()) { case GAME_PIECE_1: gamePieceToAttack = GamePiece.GAME_PIECE_2; break; case GAME_PIECE_2: gamePieceToAttack = GamePiece.GAME_PIECE_1; break; } if (currentColumn % 2 != 0) { if (0 <= upperRow) { childPosition = upperRow * columns; animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } } else { if (0 <= upperRow) { childPosition = upperRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); } childPosition = currentRow * columns; if (0 <= leftColumn) animateTileAttack(gameGridView.getChildAt(childPosition + leftColumn), childPosition + leftColumn, gamePieceToAttack); if (rightColumn < columns) animateTileAttack(gameGridView.getChildAt(childPosition + rightColumn), childPosition + rightColumn, gamePieceToAttack); if (lowerRow < rows) { childPosition = lowerRow * columns; animateTileAttack(gameGridView.getChildAt(childPosition + currentColumn), childPosition + currentColumn, gamePieceToAttack); } } } public void animateTileAttack(View view, int position, GamePiece gamePiece) { final ScaleAnimation shrink = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); final ScaleAnimation expand = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); shrink.setDuration(500); expand.setDuration(500); final ImageView tileImageView; final ImageView gamePieceImageView; Tile[][] tiles = game.getBoard().getTiles(); int columns = tiles[0].length; int row = position / columns; int column = position % columns; Tile tile = tiles[row][column]; switch (game.getGameType()) { case ATAXX: final AtaxxTileView ataxxTileView = (AtaxxTileView) view; tileImageView = ataxxTileView.getTile(); gamePieceImageView = ataxxTileView.getGamePiece(); break; case HEXXAGON: final HexxagonTileView hexxagonTileView = (HexxagonTileView) view; tileImageView = hexxagonTileView.getTile(); gamePieceImageView = hexxagonTileView.getGamePiece(); break; default: tileImageView = null; gamePieceImageView = null; } shrink.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { gamePieceImageView.setVisibility(View.INVISIBLE); } @Override public void onAnimationEnd(Animation animation) { tileImageView.startAnimation(expand); } @Override public void onAnimationRepeat(Animation animation) { } }); expand.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { gamePieceImageView.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); if (tile.getGamePiece() == gamePiece) tileImageView.startAnimation(shrink); } private void startNextTurn() { final int winningPlayer = game.checkGameOver(); int[] amounts = game.calculateGamePieceAmounts(); player1GamePieceAmountTextView.setText(String.valueOf(amounts[1])); player2GamePieceAmountTextView.setText(String.valueOf(amounts[2])); if (winningPlayer < 0) { int nextTurn = game.getTurn() + 1; game.setTurn(nextTurn); turnCounterTextView.setText(String.valueOf(nextTurn)); if (nextTurn % 2 == 0) { gameGridView.setEnabled(true); finishButton.setEnabled(true); playerTurnTextView.setText(R.string.enemy); enemyProgressBar.setVisibility(View.INVISIBLE); } else { gameGridView.setEnabled(false); finishButton.setEnabled(false); playerTurnTextView.setText(R.string.player); enemyProgressBar.setVisibility(View.VISIBLE); } tileAdapter.notifyDataSetChanged(); } else { Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { } activity.runOnUiThread(new Runnable() { @Override public void run() { startGameOverFragment(winningPlayer); } }); } }); thread.start(); } } private void startGameOverFragment(int winningPlayer) { gameGridView.setEnabled(false); finishButton.setEnabled(false); try{ playerSocket.close(); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "startGameOverFragment: Couldn't close bluetooth socket"); } Bundle bundle = getArguments(); String winningPlayerIdentity = null; switch (winningPlayer) { case 0: winningPlayerIdentity = activity.getString(R.string.everyone); break; case 1: winningPlayerIdentity = activity.getString(R.string.player); break; case 2: winningPlayerIdentity = activity.getString(R.string.enemy); break; } bundle.putString(GameOverFragment.BUNDLE_GAME_OVER_WINNING_PLAYER_KEY, winningPlayerIdentity); GameOverFragment fragment = new GameOverFragment(); fragment.setArguments(bundle); ((MainActivity) activity).loadFragment(fragment, true, BluetoothClientGameFragment.class.getName()); } private Board convertBoardFromString(String boardString, int rows, int columns) { String[] boardParts = boardString.split(BOARD_DELIMITER); Board board = null; switch (game.getGameType()) { case ATAXX: board = new AtaxxBoard(rows, columns); break; case HEXXAGON: board = new HexxagonBoard(rows, columns); break; } Tile[][] tiles = board.getTiles(); Tile tile; GamePiece gamePiece; for (int row = 0, index = 0; row < rows; row++) for (int column = 0; column < columns; column++, index++) { tile = tiles[row][column]; gamePiece = GamePiece.values()[Integer.parseInt(boardParts[index])]; tile.setGamePiece(gamePiece); if (gamePiece == GamePiece.BLOCKED) tile.setTileStatus(TileStatus.UNAVAILABLE); } return board; } public void openConfirmationDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(getString(R.string.surrender)); builder.setMessage(R.string.last_chance); builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { game.setIsOver(true); tileAdapter.notifyDataSetChanged(); int winningPlayer = 1; bluetoothService.writeMessage(createSurrenderMessage().getBytes()); startGameOverFragment(winningPlayer); } }); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } private void decryptMessage(Message message){ byte[] readBuffer = (byte[])message.obj; String stringMessage = new String(readBuffer, 0, message.arg1); String[] stringParts = stringMessage.split(BOARD_DELIMITER,2); switch(stringParts[0]){ case INIT_MESSAGE: readInitMessage(stringParts[1]); break; case SELECT_POSITION_MESSAGE: readSelectPositionMessage(stringParts[1]); break; case SURRENDER_MESSAGE: readSurrenderMessage(); break; } } private String createSelectPositionMessage(int position){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(SELECT_POSITION_MESSAGE); stringBuilder.append(BOARD_DELIMITER); stringBuilder.append(position); return stringBuilder.toString(); } private String createSurrenderMessage(){ return SURRENDER_MESSAGE; } private void readSelectPositionMessage(String message){ int position = Integer.parseInt(message); animateTileSelect(position); } private void readSurrenderMessage(){ game.setIsOver(true); tileAdapter.notifyDataSetChanged(); int winningPlayer = 2; startGameOverFragment(winningPlayer); } class ConnectBluetoothServerTask extends AsyncTask<Void, Void, BluetoothSocket> { private BluetoothSocket bluetoothSocket; private BluetoothDevice bluetoothDevice; private BluetoothAdapter bluetoothAdapter; @Override protected void onPreExecute() { showLoadingLayout(); BluetoothSocket tempSocket = null; bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); bluetoothDevice = bluetoothAdapter.getRemoteDevice(macAddress); String name = activity.getString(R.string.app_name); try{ tempSocket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUID_STRING)); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't create bluetooth socket"); activity.onBackPressed(); } bluetoothSocket = tempSocket; } protected BluetoothSocket doInBackground(Void... Voids) { try{ bluetoothSocket.connect(); }catch(IOException e){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't connect with the bluetooth socket"); try { bluetoothSocket.close(); }catch(IOException e2){ Log.e(BluetoothClientGameFragment.class.getName(), "ConnectBluetoothServerTask: Couldn't close bluetooth socket"); } bluetoothSocket = null; } return bluetoothSocket; } protected void onProgressUpdate(Void... voids) { } protected void onPostExecute(BluetoothSocket result) { if(bluetoothSocket == null){ activity.onBackPressed(); }else{ playerSocket = result; bluetoothService = new BluetoothService(playerSocket, handler); bluetoothService.start(); } } } private void readInitMessage(String message){ String[] stringParts = message.split(BOARD_DELIMITER, 6); GameType gameType = GameType.values()[Integer.parseInt(stringParts[0])]; String boardName = stringParts[1]; String creatorName = stringParts[2]; int rows = Integer.parseInt(stringParts[3]); int columns = Integer.parseInt(stringParts[4]); String boardString = stringParts[5]; game = new Game(); game.setGameType(gameType); Board board = convertBoardFromString(boardString, rows, columns); game.setBoard(board); switch (game.getGameType()) { case ATAXX: tileAdapter = new AtaxxTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; case HEXXAGON: tileAdapter = new HexxagonTileAdapter(activity.getApplicationContext(), game, GameMode.BLUETOOTH_MULTIPLAYER); break; } gameGridView.setAdapter(tileAdapter); gameGridView.setNumColumns(game.getBoard().getTiles()[0].length); new WriteBoardTask().execute(boardString, boardName, creatorName, rows, columns); showGameLayout(); startNextTurn(); } class WriteBoardTask extends AsyncTask<Object, Void, Void> { private AppDatabase appDatabase; @Override protected void onPreExecute() { appDatabase = Room.databaseBuilder(activity.getApplicationContext(), AppDatabase.class, MainActivity.DATABASE_NAME).build(); } protected Void doInBackground(Object... objects) { if(game.getGameType() == GameType.ATAXX) { AtaxxBoardEntity ataxxBoard = new AtaxxBoardEntity(); ataxxBoard.setBoard((String) objects[0]); ataxxBoard.setBoardName((String) objects[1]); ataxxBoard.setCreatorName((String) objects[2]); ataxxBoard.setRowsAmount((int) objects[3]); ataxxBoard.setColumnsAmount((int) objects[4]); appDatabase.ataxxBoardDao().insert(ataxxBoard); }else if(game.getGameType() == GameType.HEXXAGON){ HexxagonBoardEntity hexxagonBoard = new HexxagonBoardEntity(); hexxagonBoard.setBoard((String) objects[0]); hexxagonBoard.setBoardName((String) objects[1]); hexxagonBoard.setCreatorName((String) objects[2]); hexxagonBoard.setRowsAmount((int) objects[3]); hexxagonBoard.setColumnsAmount((int) objects[4]); appDatabase.hexxagonBoardDao().insert(hexxagonBoard); } return null; } protected void onProgressUpdate(Void... voids) { } protected void onPostExecute(Void result) { } } }
31,371
0.622231
0.617417
761
40.224705
30.340263
141
false
false
0
0
0
0
0
0
0.712221
false
false
12
489618ae69b77c953244ff78b98f2a072abaf239
2,052,994,372,334
1125fadf469eee2f7bdb54450fa74b250cedb560
/HelloWorlds/app/src/main/java/com/hello/oloko/helloworld/MainActivity.java
2b889eb23de4543a160e354bf918f6ae556b043a
[]
no_license
sultanol97/hello-world
https://github.com/sultanol97/hello-world
04606a4394dc9b125cc67b19c38ded7bfd09fdb9
dfd15b4ae69b1fad3feccd49f2d5b89264d2acb1
refs/heads/master
2020-03-28T19:06:25.470000
2018-09-16T02:54:51
2018-09-16T02:54:51
148,944,657
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hello.oloko.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Log.i("sultan" ,"button clicked"); ((TextView) findViewById(R.id.textView)).setTextColor( getResources().getColor(R.color.colorPrimaryDark)); } }); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { findViewById(R.id.rootView).setBackgroundColor( getResources().getColor(R.color.silver)); } }); findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((TextView) findViewById(R.id.textView)).setText("Goodbye"); } }); findViewById(R.id.rootView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // reset text color back to holo_green_dark ((TextView) findViewById(R.id.textView)).setTextColor( getResources().getColor(R.color.holo_green_dark)); // reset background color to colorAccent findViewById(R.id.rootView).setBackgroundColor( getResources().getColor(R.color.colorAccent)); // reset the text back to 'Hello from Sultan!' ((TextView) findViewById(R.id.textView)).setText("Hello from Sultan!"); } }); } }
UTF-8
Java
2,133
java
MainActivity.java
Java
[]
null
[]
package com.hello.oloko.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Log.i("sultan" ,"button clicked"); ((TextView) findViewById(R.id.textView)).setTextColor( getResources().getColor(R.color.colorPrimaryDark)); } }); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { findViewById(R.id.rootView).setBackgroundColor( getResources().getColor(R.color.silver)); } }); findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((TextView) findViewById(R.id.textView)).setText("Goodbye"); } }); findViewById(R.id.rootView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // reset text color back to holo_green_dark ((TextView) findViewById(R.id.textView)).setTextColor( getResources().getColor(R.color.holo_green_dark)); // reset background color to colorAccent findViewById(R.id.rootView).setBackgroundColor( getResources().getColor(R.color.colorAccent)); // reset the text back to 'Hello from Sultan!' ((TextView) findViewById(R.id.textView)).setText("Hello from Sultan!"); } }); } }
2,133
0.577121
0.575715
57
35.421051
28.363522
87
false
false
0
0
0
0
0
0
0.350877
false
false
12
58cb5f410bfaa14a90f845467ac77b3eabfe98af
2,585,570,379,593
7ced7141189963f3da55d4178daab0ba63d060dd
/hershel/src/test/search/MessageHandlingTests.java
dabbbf9298030d4ee31c07365fae80a469ae3232
[]
no_license
alyshamsy/hershel
https://github.com/alyshamsy/hershel
3afba48d7734b9c43550cb2277bd39854deafc64
70ed0fbc23c19a478b98eb5d907c7c082440aead
refs/heads/master
2021-01-15T13:18:12.258000
2007-04-08T14:38:43
2007-04-08T14:38:43
32,114,996
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.search; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import com.search.MessageHandler; import com.search.NodeState; import com.search.Pinger; import com.search.RoutingTable; import com.search.SearchId; import com.search.SearchMessage; import com.search.SearchResult; public class MessageHandlingTests { private MockSearchClient mock; private MessageHandler handler; private NodeState targetNode; @Before public void setUp() throws UnknownHostException { mock = new MockSearchClient(); handler = new MessageHandler(SearchId.fromHex("0987654321098765432109876543210987654321"), mock); targetNode = new NodeState(SearchId.fromHex("1234567890123456789012345678901234567890"), InetAddress.getByName("localhost"), 5678); } @Test public void respondToPing() throws IOException { handler.respondTo(pingMessage(), targetNode.address, targetNode.port); assertEquals("ping", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals(targetNode, mock.lastDestination); } @Test public void pingUpdatesRoutingTable() throws IOException { handler.respondTo(pingMessage(), targetNode.address, targetNode.port); NodeState node = handler.routingTable().getRoutingTable().get(156).get(0); assertEquals("1234567890123456789012345678901234567890", node.id.toString()); assertEquals("127.0.0.1", node.address.getHostAddress()); assertEquals(5678, node.port); } @Test public void canPingNodesOnRequest() throws IOException { handler.ping(targetNode); assertEquals("ping", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals(targetNode, mock.lastDestination); } @Test public void dontReplyToExpectedPings() throws IOException { handler.setPinger(new Pinger() { public void pingReceived(SearchId id) {} public void putPingRequest(NodeState targetNode, NodeState replacementNode) throws IOException {} public void setRoutingTable(RoutingTable table) {} public void setTimeout(int millis) {} public void close() {} public boolean expected(SearchId id) { return true; } }); handler.respondTo(pingMessage(), targetNode.address, targetNode.port); assertNull(mock.lastDestination); assertNull(mock.lastMessage); } @Test public void announceSentOnUpdate() throws IOException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); handler.database().put(file, r); handler.routingTable().addNode(targetNode); handler.updateDatabase(file, new InetSocketAddress(targetNode.address, targetNode.port)); assertEquals("announce", mock.lastMessage.getCommand()); assertEquals(r, SearchResult.fromMessage(mock.lastMessage)); } @Test public void announcePropogates() throws IOException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); r.peers.add(new InetSocketAddress(InetAddress.getLocalHost(), 12345)); handler.database().put(file, r); handler.routingTable().addNode(targetNode); SearchResult resultSent = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); resultSent.peers.add(new InetSocketAddress( InetAddress.getLocalHost(), 23456)); SearchMessage announce = resultSent.createMessage("announce"); announce.arguments().put("id", handler.getId().toString()); handler.respondTo(announce, targetNode.address, targetNode.port); assertEquals("announce", mock.lastMessage.getCommand()); } @Test public void announceStopsBeingSent() throws UnknownHostException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); r.peers.add(new InetSocketAddress(InetAddress.getLocalHost(), 12345)); SearchMessage announce = r.createMessage("announce"); announce.arguments().put("id", handler.getId().toString()); handler.respondTo(announce, targetNode.address, targetNode.port); assertNull(mock.lastMessage); } // TODO the store tests need to be refactored @Test public void storeCommandAddsItemToTheDatabase() { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); assertEquals(r, handler.database().get(fileNameHash)); } @Test public void encounterWithANodeReplicatesDatabase() throws UnknownHostException { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(fileNameHash, InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", fileNameHash.toString()); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("store", mock.lastMessage.getCommand()); assertEquals(fileNameHash.toString(), mock.lastMessage.arguments().get("file_name")); } @Test public void dontReplicateToRecentlySeenNodes() throws UnknownHostException { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(fileNameHash, InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", fileNameHash.toString()); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("ping", mock.lastMessage.getCommand()); } @Test public void storeCommandDoesNotDuplicateDatabaseToEveryNode() throws UnknownHostException { SearchResult r = createSearchResult(); SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(SearchId.fromHex("0000000000000000000000000000000000000000"), InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", "0000000000000000000000000000000000000000"); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("ping", mock.lastMessage.getCommand()); } public SearchResult createSearchResult() { SearchId fileNameHash = SearchId.fromHex("ffffffffffffffffffffffffffffffffffffffff"); SearchId fileHash = SearchId.getRandomId(); ArrayList<SearchId> chunkHashes = new ArrayList<SearchId>(); for(int i = 0; i<4; i++) { chunkHashes.add(SearchId.getRandomId()); } ArrayList<InetSocketAddress> peers = new ArrayList<InetSocketAddress>(); for(int i = 0; i<4; i++) { peers.add(new InetSocketAddress("localhost", i+10)); } return new SearchResult("sample.txt", fileNameHash, fileHash, chunkHashes, 4*512*1024-100, 512*1024, peers); } @Test public void respondToFindNode() throws IOException { handler.findNode(targetNode, SearchId.fromHex("8765432109876543210987654321098765432109")); assertEquals("find_node", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals("8765432109876543210987654321098765432109", mock.lastMessage.arguments().get("target")); assertEquals(targetNode, mock.lastDestination); } private SearchMessage pingMessage() { SearchMessage pingMessage = new SearchMessage("ping"); pingMessage.arguments().put("id", "1234567890123456789012345678901234567890"); return pingMessage; } }
UTF-8
Java
10,368
java
MessageHandlingTests.java
Java
[]
null
[]
package test.search; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import com.search.MessageHandler; import com.search.NodeState; import com.search.Pinger; import com.search.RoutingTable; import com.search.SearchId; import com.search.SearchMessage; import com.search.SearchResult; public class MessageHandlingTests { private MockSearchClient mock; private MessageHandler handler; private NodeState targetNode; @Before public void setUp() throws UnknownHostException { mock = new MockSearchClient(); handler = new MessageHandler(SearchId.fromHex("0987654321098765432109876543210987654321"), mock); targetNode = new NodeState(SearchId.fromHex("1234567890123456789012345678901234567890"), InetAddress.getByName("localhost"), 5678); } @Test public void respondToPing() throws IOException { handler.respondTo(pingMessage(), targetNode.address, targetNode.port); assertEquals("ping", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals(targetNode, mock.lastDestination); } @Test public void pingUpdatesRoutingTable() throws IOException { handler.respondTo(pingMessage(), targetNode.address, targetNode.port); NodeState node = handler.routingTable().getRoutingTable().get(156).get(0); assertEquals("1234567890123456789012345678901234567890", node.id.toString()); assertEquals("127.0.0.1", node.address.getHostAddress()); assertEquals(5678, node.port); } @Test public void canPingNodesOnRequest() throws IOException { handler.ping(targetNode); assertEquals("ping", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals(targetNode, mock.lastDestination); } @Test public void dontReplyToExpectedPings() throws IOException { handler.setPinger(new Pinger() { public void pingReceived(SearchId id) {} public void putPingRequest(NodeState targetNode, NodeState replacementNode) throws IOException {} public void setRoutingTable(RoutingTable table) {} public void setTimeout(int millis) {} public void close() {} public boolean expected(SearchId id) { return true; } }); handler.respondTo(pingMessage(), targetNode.address, targetNode.port); assertNull(mock.lastDestination); assertNull(mock.lastMessage); } @Test public void announceSentOnUpdate() throws IOException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); handler.database().put(file, r); handler.routingTable().addNode(targetNode); handler.updateDatabase(file, new InetSocketAddress(targetNode.address, targetNode.port)); assertEquals("announce", mock.lastMessage.getCommand()); assertEquals(r, SearchResult.fromMessage(mock.lastMessage)); } @Test public void announcePropogates() throws IOException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); r.peers.add(new InetSocketAddress(InetAddress.getLocalHost(), 12345)); handler.database().put(file, r); handler.routingTable().addNode(targetNode); SearchResult resultSent = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); resultSent.peers.add(new InetSocketAddress( InetAddress.getLocalHost(), 23456)); SearchMessage announce = resultSent.createMessage("announce"); announce.arguments().put("id", handler.getId().toString()); handler.respondTo(announce, targetNode.address, targetNode.port); assertEquals("announce", mock.lastMessage.getCommand()); } @Test public void announceStopsBeingSent() throws UnknownHostException { SearchId file = SearchId.getRandomId(); SearchResult r = new SearchResult("sample.txt", file, SearchId.getRandomId(), new ArrayList<SearchId>(), 0, 0, new ArrayList<InetSocketAddress>()); r.peers.add(new InetSocketAddress(InetAddress.getLocalHost(), 12345)); SearchMessage announce = r.createMessage("announce"); announce.arguments().put("id", handler.getId().toString()); handler.respondTo(announce, targetNode.address, targetNode.port); assertNull(mock.lastMessage); } // TODO the store tests need to be refactored @Test public void storeCommandAddsItemToTheDatabase() { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); assertEquals(r, handler.database().get(fileNameHash)); } @Test public void encounterWithANodeReplicatesDatabase() throws UnknownHostException { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(fileNameHash, InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", fileNameHash.toString()); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("store", mock.lastMessage.getCommand()); assertEquals(fileNameHash.toString(), mock.lastMessage.arguments().get("file_name")); } @Test public void dontReplicateToRecentlySeenNodes() throws UnknownHostException { SearchResult r = createSearchResult(); SearchId fileNameHash = r.fileNameHash; SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(fileNameHash, InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", fileNameHash.toString()); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("ping", mock.lastMessage.getCommand()); } @Test public void storeCommandDoesNotDuplicateDatabaseToEveryNode() throws UnknownHostException { SearchResult r = createSearchResult(); SearchMessage storeMessage = r.createMessage("store"); storeMessage.arguments().put("id", targetNode.id.toString()); handler.respondTo(storeMessage, targetNode.address, targetNode.port); NodeState unknownNode = new NodeState(SearchId.fromHex("0000000000000000000000000000000000000000"), InetAddress.getByName("localhost"), 45); SearchMessage unknownPing = new SearchMessage("ping"); unknownPing.arguments().put("id", "0000000000000000000000000000000000000000"); handler.respondTo(unknownPing, unknownNode.address, unknownNode.port); assertEquals(unknownNode, mock.lastDestination); assertEquals("ping", mock.lastMessage.getCommand()); } public SearchResult createSearchResult() { SearchId fileNameHash = SearchId.fromHex("ffffffffffffffffffffffffffffffffffffffff"); SearchId fileHash = SearchId.getRandomId(); ArrayList<SearchId> chunkHashes = new ArrayList<SearchId>(); for(int i = 0; i<4; i++) { chunkHashes.add(SearchId.getRandomId()); } ArrayList<InetSocketAddress> peers = new ArrayList<InetSocketAddress>(); for(int i = 0; i<4; i++) { peers.add(new InetSocketAddress("localhost", i+10)); } return new SearchResult("sample.txt", fileNameHash, fileHash, chunkHashes, 4*512*1024-100, 512*1024, peers); } @Test public void respondToFindNode() throws IOException { handler.findNode(targetNode, SearchId.fromHex("8765432109876543210987654321098765432109")); assertEquals("find_node", mock.lastMessage.getCommand()); assertEquals("0987654321098765432109876543210987654321", mock.lastMessage.arguments().get("id")); assertEquals("8765432109876543210987654321098765432109", mock.lastMessage.arguments().get("target")); assertEquals(targetNode, mock.lastDestination); } private SearchMessage pingMessage() { SearchMessage pingMessage = new SearchMessage("ping"); pingMessage.arguments().put("id", "1234567890123456789012345678901234567890"); return pingMessage; } }
10,368
0.66088
0.611593
258
38.186047
31.048666
116
false
false
0
0
0
0
0
0
1.162791
false
false
12
824b3431bb149aea86fcce28c5bbb6d7ac1701df
3,058,016,749,966
d8280d99ad9189f1fbe229d9b89554648b677518
/xzjr-provider/src/main/java/com/springcloud/provider/twodata/service/impl/DataOneServiceImpl.java
0bdf27f500c03532bc00265bde3cae35af05aec2
[]
no_license
xieshuai2011/xzjr
https://github.com/xieshuai2011/xzjr
443558936da9a985591196da87dc8ba51dfdd6b5
35449e9d43cd9e017321f71b6c46a9eb274743f9
refs/heads/master
2022-09-09T20:13:56.794000
2019-11-19T03:10:22
2019-11-19T03:10:22
222,596,952
1
0
null
false
2022-09-01T23:15:57
2019-11-19T03:07:05
2019-11-20T01:42:15
2022-09-01T23:15:55
360
0
0
2
CSS
false
false
package com.springcloud.provider.twodata.service.impl; import com.springcloud.provider.twodata.dao.DataOneDao; import com.springcloud.provider.twodata.dto.DataOne; import com.springcloud.provider.twodata.service.DataOneService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author xieshuai * @date 2019/10/10 10:39 */ @Service public class DataOneServiceImpl implements DataOneService { @Autowired DataOneDao dataOneDao; @Override public List<DataOne> queryDataOne() { return dataOneDao.queryDataOne(); } }
UTF-8
Java
637
java
DataOneServiceImpl.java
Java
[ { "context": "e.Service;\n\nimport java.util.List;\n\n/**\n * @author xieshuai\n * @date 2019/10/10 10:39\n */\n@Service\npublic cla", "end": 387, "score": 0.9991652965545654, "start": 379, "tag": "USERNAME", "value": "xieshuai" } ]
null
[]
package com.springcloud.provider.twodata.service.impl; import com.springcloud.provider.twodata.dao.DataOneDao; import com.springcloud.provider.twodata.dto.DataOne; import com.springcloud.provider.twodata.service.DataOneService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author xieshuai * @date 2019/10/10 10:39 */ @Service public class DataOneServiceImpl implements DataOneService { @Autowired DataOneDao dataOneDao; @Override public List<DataOne> queryDataOne() { return dataOneDao.queryDataOne(); } }
637
0.77551
0.756672
25
24.48
22.85103
63
false
false
0
0
0
0
0
0
0.36
false
false
12
c0247fc2e35120eb84535356e89a6a4e13d168a1
2,808,908,674,704
f487532281c1c6a36a5c62a29744d8323584891b
/sdk/java/src/main/java/com/pulumi/azure/cdn/inputs/FrontdoorRuleConditionsSocketAddressConditionArgs.java
b158cd4bd6e65e4f7cda1f9b1ea818e79c0f46d1
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0" ]
permissive
pulumi/pulumi-azure
https://github.com/pulumi/pulumi-azure
a8f8f21c46c802aecf1397c737662ddcc438a2db
c16962e5c4f5810efec2806b8bb49d0da960d1ea
refs/heads/master
2023-08-25T00:17:05.290000
2023-08-24T06:11:55
2023-08-24T06:11:55
103,183,737
129
57
Apache-2.0
false
2023-09-13T05:44:10
2017-09-11T20:19:15
2023-08-09T05:39:20
2023-09-13T05:44:08
186,735
125
46
62
Java
false
false
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.azure.cdn.inputs; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.Boolean; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; public final class FrontdoorRuleConditionsSocketAddressConditionArgs extends com.pulumi.resources.ResourceArgs { public static final FrontdoorRuleConditionsSocketAddressConditionArgs Empty = new FrontdoorRuleConditionsSocketAddressConditionArgs(); /** * Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * */ @Import(name="matchValues") private @Nullable Output<List<String>> matchValues; /** * @return Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * */ public Optional<Output<List<String>>> matchValues() { return Optional.ofNullable(this.matchValues); } /** * If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * */ @Import(name="negateCondition") private @Nullable Output<Boolean> negateCondition; /** * @return If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * */ public Optional<Output<Boolean>> negateCondition() { return Optional.ofNullable(this.negateCondition); } /** * The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * */ @Import(name="operator") private @Nullable Output<String> operator; /** * @return The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * */ public Optional<Output<String>> operator() { return Optional.ofNullable(this.operator); } private FrontdoorRuleConditionsSocketAddressConditionArgs() {} private FrontdoorRuleConditionsSocketAddressConditionArgs(FrontdoorRuleConditionsSocketAddressConditionArgs $) { this.matchValues = $.matchValues; this.negateCondition = $.negateCondition; this.operator = $.operator; } public static Builder builder() { return new Builder(); } public static Builder builder(FrontdoorRuleConditionsSocketAddressConditionArgs defaults) { return new Builder(defaults); } public static final class Builder { private FrontdoorRuleConditionsSocketAddressConditionArgs $; public Builder() { $ = new FrontdoorRuleConditionsSocketAddressConditionArgs(); } public Builder(FrontdoorRuleConditionsSocketAddressConditionArgs defaults) { $ = new FrontdoorRuleConditionsSocketAddressConditionArgs(Objects.requireNonNull(defaults)); } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(@Nullable Output<List<String>> matchValues) { $.matchValues = matchValues; return this; } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(List<String> matchValues) { return matchValues(Output.of(matchValues)); } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(String... matchValues) { return matchValues(List.of(matchValues)); } /** * @param negateCondition If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * * @return builder * */ public Builder negateCondition(@Nullable Output<Boolean> negateCondition) { $.negateCondition = negateCondition; return this; } /** * @param negateCondition If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * * @return builder * */ public Builder negateCondition(Boolean negateCondition) { return negateCondition(Output.of(negateCondition)); } /** * @param operator The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * * @return builder * */ public Builder operator(@Nullable Output<String> operator) { $.operator = operator; return this; } /** * @param operator The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * * @return builder * */ public Builder operator(String operator) { return operator(Output.of(operator)); } public FrontdoorRuleConditionsSocketAddressConditionArgs build() { return $; } } }
UTF-8
Java
7,185
java
FrontdoorRuleConditionsSocketAddressConditionArgs.java
Java
[]
null
[]
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.azure.cdn.inputs; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.Boolean; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; public final class FrontdoorRuleConditionsSocketAddressConditionArgs extends com.pulumi.resources.ResourceArgs { public static final FrontdoorRuleConditionsSocketAddressConditionArgs Empty = new FrontdoorRuleConditionsSocketAddressConditionArgs(); /** * Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * */ @Import(name="matchValues") private @Nullable Output<List<String>> matchValues; /** * @return Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * */ public Optional<Output<List<String>>> matchValues() { return Optional.ofNullable(this.matchValues); } /** * If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * */ @Import(name="negateCondition") private @Nullable Output<Boolean> negateCondition; /** * @return If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * */ public Optional<Output<Boolean>> negateCondition() { return Optional.ofNullable(this.negateCondition); } /** * The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * */ @Import(name="operator") private @Nullable Output<String> operator; /** * @return The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * */ public Optional<Output<String>> operator() { return Optional.ofNullable(this.operator); } private FrontdoorRuleConditionsSocketAddressConditionArgs() {} private FrontdoorRuleConditionsSocketAddressConditionArgs(FrontdoorRuleConditionsSocketAddressConditionArgs $) { this.matchValues = $.matchValues; this.negateCondition = $.negateCondition; this.operator = $.operator; } public static Builder builder() { return new Builder(); } public static Builder builder(FrontdoorRuleConditionsSocketAddressConditionArgs defaults) { return new Builder(defaults); } public static final class Builder { private FrontdoorRuleConditionsSocketAddressConditionArgs $; public Builder() { $ = new FrontdoorRuleConditionsSocketAddressConditionArgs(); } public Builder(FrontdoorRuleConditionsSocketAddressConditionArgs defaults) { $ = new FrontdoorRuleConditionsSocketAddressConditionArgs(Objects.requireNonNull(defaults)); } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(@Nullable Output<List<String>> matchValues) { $.matchValues = matchValues; return this; } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(List<String> matchValues) { return matchValues(Output.of(matchValues)); } /** * @param matchValues Specify one or more IP address ranges. If multiple IP address ranges are specified, they&#39;re evaluated using `OR` logic. * * -&gt;**NOTE:** See the `Specifying IP Address Ranges` section below on how to correctly define the `match_values` field. * * @return builder * */ public Builder matchValues(String... matchValues) { return matchValues(List.of(matchValues)); } /** * @param negateCondition If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * * @return builder * */ public Builder negateCondition(@Nullable Output<Boolean> negateCondition) { $.negateCondition = negateCondition; return this; } /** * @param negateCondition If `true` operator becomes the opposite of its value. Possible values `true` or `false`. Defaults to `false`. Details can be found in the `Condition Operator List` below. * * @return builder * */ public Builder negateCondition(Boolean negateCondition) { return negateCondition(Output.of(negateCondition)); } /** * @param operator The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * * @return builder * */ public Builder operator(@Nullable Output<String> operator) { $.operator = operator; return this; } /** * @param operator The type of match. The Possible values are `IpMatch` or `Any`. Defaults to `IPMatch`. * * -&gt;**NOTE:** If the value of the `operator` field is set to `IpMatch` then the `match_values` field is also required. * * @return builder * */ public Builder operator(String operator) { return operator(Output.of(operator)); } public FrontdoorRuleConditionsSocketAddressConditionArgs build() { return $; } } }
7,185
0.636743
0.635351
187
37.422459
46.111214
204
false
false
0
0
0
0
0
0
0.28877
false
false
12
3780c13eae75f6630d9f10097d54b798bf69c4de
34,007,551,061,295
35dfb72ecdb8a23a5091c6e67c4e048e0d1df3c5
/platform-common/src/main/java/com/wchkong/common/utils/NetUtil.java
2e331b040acbff000633520ce94634eacde61bcc
[]
no_license
wchkong/instant-video-platform
https://github.com/wchkong/instant-video-platform
a55829c4da7cf75fe152ef17f72848b7ae25bc54
31169b4def999857606731d01b0d8ecc19df454b
refs/heads/master
2022-05-31T16:52:07.720000
2019-11-02T13:05:06
2019-11-02T13:05:06
200,574,398
0
0
null
false
2021-03-31T21:34:00
2019-08-05T03:17:17
2019-11-02T13:05:23
2021-03-31T21:34:00
45
0
0
1
Java
false
false
package com.wchkong.common.utils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; /** * zhangwei */ public class NetUtil { private static final Logger LOG = LoggerFactory.getLogger(NetUtil.class); public static Collection<String> getAllLocalIP() throws Exception { ArrayList<String> ar = new ArrayList<String>(); Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); if (netInterfaces == null) { return ar; } while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> inetAdrsEnum = ni.getInetAddresses(); if (inetAdrsEnum == null || !inetAdrsEnum.hasMoreElements()) { continue; } InetAddress ip = inetAdrsEnum.nextElement(); if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { // System.out.println("Interface " + ni.getName() + " seems to be InternetInterface. I'll take it..."); } else { ar.add(ip.getHostAddress()); } } return ar; } /** * @param ip * @return 判断指定ip是否在本机的ip列表范围内,使用场景:限定某一台机器单机运行任务 */ public static boolean containsIp(String ip) { Enumeration<NetworkInterface> netInterfaces; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> emu = ni.getInetAddresses(); while (emu.hasMoreElements()) { InetAddress ipaddr = emu.nextElement(); if (ip.equals(ipaddr.getHostAddress())) return true; } } } catch (SocketException e) { LOG.error("error during containsIp,ip:" + ip, e); } return false; } /** * @param ips * @param separator * @return 检查参数ips中是否包含本地服务器ip */ public static boolean containsIps(String ips, String separator) { if (StringUtils.isEmpty(ips)) { return false; } String[] parts = ips.split(separator); for (String s : parts) { if (containsIp(s)) { return true; } } return false; } /** * 获取本机ip * * @return */ public static String getLocalIp() { String ip = null; try { InetAddress addr = InetAddress.getLocalHost(); ip = addr.getHostAddress().toString(); //获取本机ip } catch (UnknownHostException e) { e.printStackTrace(); } return ip; } }
UTF-8
Java
3,237
java
NetUtil.java
Java
[ { "context": ".Collection;\nimport java.util.Enumeration;\n\n/**\n * zhangwei\n */\npublic class NetUtil {\n private static fin", "end": 375, "score": 0.9996266961097717, "start": 367, "tag": "USERNAME", "value": "zhangwei" } ]
null
[]
package com.wchkong.common.utils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; /** * zhangwei */ public class NetUtil { private static final Logger LOG = LoggerFactory.getLogger(NetUtil.class); public static Collection<String> getAllLocalIP() throws Exception { ArrayList<String> ar = new ArrayList<String>(); Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); if (netInterfaces == null) { return ar; } while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> inetAdrsEnum = ni.getInetAddresses(); if (inetAdrsEnum == null || !inetAdrsEnum.hasMoreElements()) { continue; } InetAddress ip = inetAdrsEnum.nextElement(); if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { // System.out.println("Interface " + ni.getName() + " seems to be InternetInterface. I'll take it..."); } else { ar.add(ip.getHostAddress()); } } return ar; } /** * @param ip * @return 判断指定ip是否在本机的ip列表范围内,使用场景:限定某一台机器单机运行任务 */ public static boolean containsIp(String ip) { Enumeration<NetworkInterface> netInterfaces; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> emu = ni.getInetAddresses(); while (emu.hasMoreElements()) { InetAddress ipaddr = emu.nextElement(); if (ip.equals(ipaddr.getHostAddress())) return true; } } } catch (SocketException e) { LOG.error("error during containsIp,ip:" + ip, e); } return false; } /** * @param ips * @param separator * @return 检查参数ips中是否包含本地服务器ip */ public static boolean containsIps(String ips, String separator) { if (StringUtils.isEmpty(ips)) { return false; } String[] parts = ips.split(separator); for (String s : parts) { if (containsIp(s)) { return true; } } return false; } /** * 获取本机ip * * @return */ public static String getLocalIp() { String ip = null; try { InetAddress addr = InetAddress.getLocalHost(); ip = addr.getHostAddress().toString(); //获取本机ip } catch (UnknownHostException e) { e.printStackTrace(); } return ip; } }
3,237
0.57856
0.57728
100
30.26
25.606882
122
false
false
0
0
0
0
0
0
0.48
false
false
12
59a68fab97e7ae590c0c802f56138e07db33cd22
28,303,834,522,232
45170dfa6619c411dd7745200f44282d1ece52bf
/backend/src/test/java/com/easyrent/rentcarapp/service/impl/ReservationServiceImplTest.java
194fcae42eda65c76df1299f4d82316278df584a
[]
no_license
HappySennin/programowanie-zespolowe
https://github.com/HappySennin/programowanie-zespolowe
03f8ec54ee158c44bb00c716aa686ef88f0afbbd
7ed0e000a4ec8122b027fca2f01089817d4c5af6
refs/heads/master
2021-09-04T20:35:27.647000
2018-01-22T07:33:34
2018-01-22T07:33:34
109,651,966
0
0
null
false
2018-01-05T17:50:23
2017-11-06T05:33:38
2017-11-06T20:51:55
2018-01-05T17:50:23
850
0
0
0
JavaScript
false
null
package com.easyrent.rentcarapp.service.impl; import com.easyrent.rentcarapp.entity.Reservation; import com.easyrent.rentcarapp.repository.ReservationRepository; import com.easyrent.rentcarapp.service.ReservationService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class ReservationServiceImplTest { List<Reservation> reservations = Arrays.asList( new Reservation( 1, 1, convertToDate("01-01-1771"), convertToDate("03-01-1771"), new BigDecimal(123.123)), new Reservation( 1, 2, convertToDate("05-01-1771"), convertToDate("07-01-1771"), new BigDecimal(321.123)), new Reservation( 2, 3, convertToDate("11-01-1771"), convertToDate("13-01-1771"), new BigDecimal(123.321)), new Reservation( 3, 3, convertToDate("17-01-1771"), convertToDate("19-01-1771"), new BigDecimal(321.321)) ); @Mock private ReservationRepository repository; @InjectMocks ReservationService rs = new ReservationServiceImpl(); @Test public void testFindAllReservations() { Mockito.when(rs.findAllReservations()).thenReturn(reservations); Assert.assertTrue(rs.findAllReservations().size() == reservations.size()); } @Test public void testFindReservationById() { Reservation r = reservations.get(3); Mockito.when(rs.findReservationById(2L)).thenReturn(r); Reservation reservation = rs.findReservationById(2L); Assert.assertEquals(reservation.getUserId(), 3L); } @Test public void testFindByUserId() { List<Reservation> output = Arrays.asList(reservations.get(0), reservations.get(1)); Mockito.when(rs.findByUserId(1L)).thenReturn(output); List<Reservation> result = rs.findByUserId(1L); Assert.assertEquals(result.size(), 2); Assert.assertEquals(result.get(0).getPrice(),new BigDecimal(123.123)); } @Test public void testFindByCarId() { List<Reservation> output = Arrays.asList(reservations.get(2)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Reservation> result = rs.findByCarId(3L); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.get(0).getUserId(), 2L); } @Test public void testGetReservationAvailabilityWhenOneReservationExist(){ List<Reservation> output = Arrays.asList(reservations.get(2)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Date> result = rs.getReservationAvailability(3L,convertToDate("01-01-1771"), convertToDate("20-01-1771") ); Assert.assertEquals(20-3, result.size()); } @Test public void testGetReservationAvailabilityWhenMultipleReservationExist(){ List<Reservation> output = Arrays.asList(reservations.get(2), reservations.get(3)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Date> result = rs.getReservationAvailability(3L,convertToDate("01-01-1771"), convertToDate("20-01-1771") ); Assert.assertEquals(20-3-3, result.size()); } private Date convertToDate(String date) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date dateToReturn = null; try { dateToReturn = sdf.parse(date); } catch (ParseException e) { e.printStackTrace(); } return dateToReturn; } }
UTF-8
Java
3,772
java
ReservationServiceImplTest.java
Java
[]
null
[]
package com.easyrent.rentcarapp.service.impl; import com.easyrent.rentcarapp.entity.Reservation; import com.easyrent.rentcarapp.repository.ReservationRepository; import com.easyrent.rentcarapp.service.ReservationService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class ReservationServiceImplTest { List<Reservation> reservations = Arrays.asList( new Reservation( 1, 1, convertToDate("01-01-1771"), convertToDate("03-01-1771"), new BigDecimal(123.123)), new Reservation( 1, 2, convertToDate("05-01-1771"), convertToDate("07-01-1771"), new BigDecimal(321.123)), new Reservation( 2, 3, convertToDate("11-01-1771"), convertToDate("13-01-1771"), new BigDecimal(123.321)), new Reservation( 3, 3, convertToDate("17-01-1771"), convertToDate("19-01-1771"), new BigDecimal(321.321)) ); @Mock private ReservationRepository repository; @InjectMocks ReservationService rs = new ReservationServiceImpl(); @Test public void testFindAllReservations() { Mockito.when(rs.findAllReservations()).thenReturn(reservations); Assert.assertTrue(rs.findAllReservations().size() == reservations.size()); } @Test public void testFindReservationById() { Reservation r = reservations.get(3); Mockito.when(rs.findReservationById(2L)).thenReturn(r); Reservation reservation = rs.findReservationById(2L); Assert.assertEquals(reservation.getUserId(), 3L); } @Test public void testFindByUserId() { List<Reservation> output = Arrays.asList(reservations.get(0), reservations.get(1)); Mockito.when(rs.findByUserId(1L)).thenReturn(output); List<Reservation> result = rs.findByUserId(1L); Assert.assertEquals(result.size(), 2); Assert.assertEquals(result.get(0).getPrice(),new BigDecimal(123.123)); } @Test public void testFindByCarId() { List<Reservation> output = Arrays.asList(reservations.get(2)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Reservation> result = rs.findByCarId(3L); Assert.assertEquals(result.size(), 1); Assert.assertEquals(result.get(0).getUserId(), 2L); } @Test public void testGetReservationAvailabilityWhenOneReservationExist(){ List<Reservation> output = Arrays.asList(reservations.get(2)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Date> result = rs.getReservationAvailability(3L,convertToDate("01-01-1771"), convertToDate("20-01-1771") ); Assert.assertEquals(20-3, result.size()); } @Test public void testGetReservationAvailabilityWhenMultipleReservationExist(){ List<Reservation> output = Arrays.asList(reservations.get(2), reservations.get(3)); Mockito.when(rs.findByCarId(3L)).thenReturn(output); List<Date> result = rs.getReservationAvailability(3L,convertToDate("01-01-1771"), convertToDate("20-01-1771") ); Assert.assertEquals(20-3-3, result.size()); } private Date convertToDate(String date) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date dateToReturn = null; try { dateToReturn = sdf.parse(date); } catch (ParseException e) { e.printStackTrace(); } return dateToReturn; } }
3,772
0.695122
0.651644
108
33.925926
32.752918
120
false
false
0
0
0
0
0
0
0.759259
false
false
12
52504e16e84268a1521b0ab950b1cfca73a10788
15,023,795,654,744
88a585eee1fdf881bf2873a56698888a9a19e432
/graph-builder/src/main/java/spoon/decompiler/MultiTypeTransformer.java
68485425b96da28fdff139063a3deff743f3f8ab
[ "MIT", "Apache-2.0" ]
permissive
devshiro/corda-flows-doc-builder
https://github.com/devshiro/corda-flows-doc-builder
819664bfa1eaf216dc0faea6cf6fa2dac1f7a8f5
93a57954fc59b00d77e972280088230642dbb6de
refs/heads/master
2020-07-09T09:58:29.456000
2019-07-16T09:06:52
2019-07-16T09:06:52
203,944,028
0
0
Apache-2.0
true
2019-08-23T07:08:58
2019-08-23T07:08:57
2019-07-29T17:06:47
2019-07-16T09:06:55
681
0
0
0
null
false
false
/** * Copyright (C) 2006-2018 INRIA and contributors * Spoon - http://spoon.gforge.inria.fr/ * * This software is governed by the CeCILL-C License under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license as * circulated by CEA, CNRS and INRIA at http://www.cecill.info. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the CeCILL-C License for more details. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ package spoon.decompiler; import spoon.reflect.declaration.CtType; import java.util.Collection; import java.util.LinkedHashSet; public class MultiTypeTransformer implements TypeTransformer { protected LinkedHashSet<TypeTransformer> transformers; public MultiTypeTransformer() { transformers = new LinkedHashSet<>(); } public void addTransformer(TypeTransformer transformer) { transformers.add(transformer); } public void addTransformers(Collection<TypeTransformer> transformers) { this.transformers.addAll(transformers); } @Override public void transform(CtType type) { for (TypeTransformer transformer: transformers) { if (transformer.accept(type)) { transformer.transform(type); } } } @Override public boolean accept(CtType type) { for (TypeTransformer transformer: transformers) { if (transformer.accept(type)) { return true; } } return false; } }
UTF-8
Java
1,684
java
MultiTypeTransformer.java
Java
[]
null
[]
/** * Copyright (C) 2006-2018 INRIA and contributors * Spoon - http://spoon.gforge.inria.fr/ * * This software is governed by the CeCILL-C License under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license as * circulated by CEA, CNRS and INRIA at http://www.cecill.info. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the CeCILL-C License for more details. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ package spoon.decompiler; import spoon.reflect.declaration.CtType; import java.util.Collection; import java.util.LinkedHashSet; public class MultiTypeTransformer implements TypeTransformer { protected LinkedHashSet<TypeTransformer> transformers; public MultiTypeTransformer() { transformers = new LinkedHashSet<>(); } public void addTransformer(TypeTransformer transformer) { transformers.add(transformer); } public void addTransformers(Collection<TypeTransformer> transformers) { this.transformers.addAll(transformers); } @Override public void transform(CtType type) { for (TypeTransformer transformer: transformers) { if (transformer.accept(type)) { transformer.transform(type); } } } @Override public boolean accept(CtType type) { for (TypeTransformer transformer: transformers) { if (transformer.accept(type)) { return true; } } return false; } }
1,684
0.752375
0.747625
58
28.034483
27.374142
79
false
false
0
0
0
0
0
0
1.103448
false
false
12
0e9e326ae2bcc3c0ebdcee6806935418bc57866d
32,573,032,030,011
4d235887c5e4c6d29bc427ea730fe7003b3bd180
/SpecsUtils/src/pt/up/fe/specs/util/parsing/arguments/Gluer.java
a8da80e6ec03e4e7ded501a419caf333e731b9ed
[ "Apache-2.0" ]
permissive
specs-feup/specs-java-libs
https://github.com/specs-feup/specs-java-libs
01d7c78cce4932e8c94fbb6bbf4fd0f6f324c803
a7050ed11c6aa6b7bfa3b59fe4b30046571926fb
refs/heads/master
2023-09-04T11:11:53.939000
2023-09-01T14:18:08
2023-09-01T14:18:08
78,943,721
1
2
Apache-2.0
false
2023-08-19T19:36:35
2017-01-14T14:06:26
2022-10-06T08:07:59
2023-08-19T19:36:35
72,480
1
2
2
Java
false
false
/** * Copyright 2017 SPeCS. * * 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. under the License. */ package pt.up.fe.specs.util.parsing.arguments; public class Gluer { private final String delimiterStart; private final String delimiterEnd; private final boolean keepDelimiters; public Gluer(String start, String end) { this(start, end, false); } public Gluer(String start, String end, boolean keepDelimiters) { this.delimiterStart = start; this.delimiterEnd = end; this.keepDelimiters = keepDelimiters; } /** * * @return a new Gluer that start and ends with double quote ('"') */ public static Gluer newDoubleQuote() { return new Gluer("\"", "\""); } /** * * @return a new Gluer that start with < ends with > */ public static Gluer newTag() { return new Gluer("<", ">", true); } /** * * @return a new Gluer that start with ( ends with ) */ public static Gluer newParenthesis() { return new Gluer("(", ")", true); } public String getGluerStart() { return delimiterStart; } public String getGluerEnd() { return delimiterEnd; } public boolean keepDelimiters() { return keepDelimiters; } }
UTF-8
Java
1,814
java
Gluer.java
Java
[]
null
[]
/** * Copyright 2017 SPeCS. * * 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. under the License. */ package pt.up.fe.specs.util.parsing.arguments; public class Gluer { private final String delimiterStart; private final String delimiterEnd; private final boolean keepDelimiters; public Gluer(String start, String end) { this(start, end, false); } public Gluer(String start, String end, boolean keepDelimiters) { this.delimiterStart = start; this.delimiterEnd = end; this.keepDelimiters = keepDelimiters; } /** * * @return a new Gluer that start and ends with double quote ('"') */ public static Gluer newDoubleQuote() { return new Gluer("\"", "\""); } /** * * @return a new Gluer that start with < ends with > */ public static Gluer newTag() { return new Gluer("<", ">", true); } /** * * @return a new Gluer that start with ( ends with ) */ public static Gluer newParenthesis() { return new Gluer("(", ")", true); } public String getGluerStart() { return delimiterStart; } public String getGluerEnd() { return delimiterEnd; } public boolean keepDelimiters() { return keepDelimiters; } }
1,814
0.638368
0.633958
68
25.67647
29.270262
118
false
false
0
0
0
0
0
0
0.426471
false
false
12
541282e27a691e739f4c236bb74da2977786b44c
17,394,617,616,801
c4083654548249ada96e12f1f98a35877df92bef
/src/main/java/mycafecontroller/CafeController.java
e5b018298374ef50ab8cd67a87be05b21e825ad6
[]
no_license
smarth-code/spring-mvc-demo
https://github.com/smarth-code/spring-mvc-demo
fa34fb052eec340e5eb7e2db9c5514dad8bf8d0d
d390fab89d766987399e0b8d4332b1c42c40eee7
refs/heads/master
2022-12-02T05:18:29.973000
2020-08-19T12:01:55
2020-08-19T12:01:55
288,711,250
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mycafecontroller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class CafeController { @RequestMapping("/cafe") public String getOrder(Model model) { model.addAttribute("heading", "MY MOM'S CAFE"); return "Order"; } @RequestMapping("/processorder") public String processOrder(HttpServletRequest request,Model model) { //handle the data received from the user String uservalue=request.getParameter("foodType"); //adding the captured value to the model model.addAttribute("userinput", uservalue); return "process-order"; } }
UTF-8
Java
736
java
CafeController.java
Java
[]
null
[]
package mycafecontroller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class CafeController { @RequestMapping("/cafe") public String getOrder(Model model) { model.addAttribute("heading", "MY MOM'S CAFE"); return "Order"; } @RequestMapping("/processorder") public String processOrder(HttpServletRequest request,Model model) { //handle the data received from the user String uservalue=request.getParameter("foodType"); //adding the captured value to the model model.addAttribute("userinput", uservalue); return "process-order"; } }
736
0.767663
0.767663
29
24.379311
21.520502
69
false
false
0
0
0
0
0
0
1.413793
false
false
12
52cb2ae03f86298af85cbdb26b07d86b4e82e82d
16,234,976,442,011
f2494152132229f28aec66d92d3b7f143438a956
/Stack/NormalStack/ArrayStack/DynamicStack.java
df7f74a8edc1843febd11d47c6c4d8683e16f752
[]
no_license
irohit/learningsamples
https://github.com/irohit/learningsamples
1dee228642d9761a6c0af43c1bd7200334c14c0b
8a26d07f912e241a88c12469065f5a7d5e75386e
refs/heads/master
2021-01-10T10:21:16.411000
2016-04-06T17:27:51
2016-04-06T17:27:51
55,523,423
0
0
null
false
2016-04-06T17:27:51
2016-04-05T16:20:22
2016-04-05T16:24:13
2016-04-06T17:27:51
8
0
0
0
Java
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Stack.NormalStack.ArrayStack; /** * * @ Rohit Sharma */ public class DynamicStack extends ArrayStack { public DynamicStack(int size) { super(size); } public void push(Object o) { if (isFull()) { Object temp[] = new Object[stack.length * 2]; System.out.println("Stack grown with length" + stack.length); for (int i = 0; i < stack.length; i++) temp[i] = stack[i]; stack = temp; stack[++top] = o; } else { stack[++top] = o; } } public Object pop() { if (!isEmpty()) { return stack[top--]; } return null; } }
UTF-8
Java
823
java
DynamicStack.java
Java
[ { "context": "package Stack.NormalStack.ArrayStack;\n\n/**\n *\n * @ Rohit Sharma\n */\npublic class DynamicStack extends ArrayStack ", "end": 163, "score": 0.9998372793197632, "start": 151, "tag": "NAME", "value": "Rohit Sharma" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Stack.NormalStack.ArrayStack; /** * * @ <NAME> */ public class DynamicStack extends ArrayStack { public DynamicStack(int size) { super(size); } public void push(Object o) { if (isFull()) { Object temp[] = new Object[stack.length * 2]; System.out.println("Stack grown with length" + stack.length); for (int i = 0; i < stack.length; i++) temp[i] = stack[i]; stack = temp; stack[++top] = o; } else { stack[++top] = o; } } public Object pop() { if (!isEmpty()) { return stack[top--]; } return null; } }
817
0.492102
0.489672
39
20.102564
18.602171
73
false
false
0
0
0
0
0
0
0.358974
false
false
12
b119f79ec0de20922e0095e2e9bf59e1c7241b87
2,491,081,096,113
f307939e0643ec6adbc8c6e8ad6ec3e6c2894468
/fifthassignment/genarrayswap/genarrayswap/SwapArray.java
a0b5f094f254d838b95190e75d379ccda1607a7e
[]
no_license
jumpjune2019/Marilyn_John
https://github.com/jumpjune2019/Marilyn_John
c59a3bd2f2df36272c5e4533933731839359bf4e
c30574e8f4c206f360e31e26bcac9170c6dd8715
refs/heads/master
2020-06-06T12:49:17.647000
2019-07-26T13:30:12
2019-07-26T13:30:12
192,744,523
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package genarrayswap; public class SwapArray { public static <E> void swapIndex (E[] inputArray) { E temp = inputArray[1]; inputArray[1] = inputArray[2]; inputArray[2] = temp; System.out.println("\nPrinting array contents with swap: "); for (int i=0; i<inputArray.length; i++) { System.out.print(inputArray[i] + " "); } } public static void main(String[] args) { Integer[] arrayList = {1, 2, 3, 4, 5}; System.out.println("Printing array contents: "); for (int i=0; i<arrayList.length; i++) { System.out.print(arrayList[i] + " "); } swapIndex(arrayList); /* int temp = arrayList[1]; arrayList[1] = arrayList[2]; arrayList[2] = temp; System.out.println("\nPrinting array contents with swap: "); for (int i=0; i<arrayList.length; i++) { System.out.print(arrayList[i] + " "); } */ } }
UTF-8
Java
873
java
SwapArray.java
Java
[]
null
[]
package genarrayswap; public class SwapArray { public static <E> void swapIndex (E[] inputArray) { E temp = inputArray[1]; inputArray[1] = inputArray[2]; inputArray[2] = temp; System.out.println("\nPrinting array contents with swap: "); for (int i=0; i<inputArray.length; i++) { System.out.print(inputArray[i] + " "); } } public static void main(String[] args) { Integer[] arrayList = {1, 2, 3, 4, 5}; System.out.println("Printing array contents: "); for (int i=0; i<arrayList.length; i++) { System.out.print(arrayList[i] + " "); } swapIndex(arrayList); /* int temp = arrayList[1]; arrayList[1] = arrayList[2]; arrayList[2] = temp; System.out.println("\nPrinting array contents with swap: "); for (int i=0; i<arrayList.length; i++) { System.out.print(arrayList[i] + " "); } */ } }
873
0.603666
0.585338
45
18.4
19.498604
62
false
false
0
0
0
0
0
0
2.244444
false
false
12
5937c60815e5883230ef84d316862ac488040ec7
1,047,972,037,433
a76d6975c2db054d259226c230af97a63c153eca
/src/zeson/scheme/Environment.java
8e12c88b323a4e8ec2ee229936ebc9456eeac381
[]
no_license
FashGek/SimpleScheme
https://github.com/FashGek/SimpleScheme
4477810704e7fe926150b5916911cdcfefcd6b02
ae38149981f5b08cfb9388e65d4d75db4c9f0d37
refs/heads/master
2021-05-31T18:16:28.206000
2016-06-07T15:24:10
2016-06-07T15:24:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zeson.scheme; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.junit.Assume; public class Environment { Stack<Map<String, Value>> symbols = new Stack<>(); public Environment() { this.symbols.add(new HashMap<String, Value>()); } public Value getSymbol(String name) { for (int i = symbols.size() - 1; i >= 0; i--) { Value v = symbols.get(i).get(name); if (v != null) return v; } return null; } public boolean addSymbol(String name, Value v) { Assume.assumeNotNull(symbols.lastElement()); symbols.lastElement().put(name, v); return true; } public void enterScope() { symbols.push(new HashMap<String, Value>()); } public void outScope() { symbols.pop(); } @SuppressWarnings("unchecked") public Environment fork() { Environment environment = new Environment(); environment.symbols = (Stack<Map<String, Value>>) symbols.clone(); return environment; } }
UTF-8
Java
953
java
Environment.java
Java
[]
null
[]
package zeson.scheme; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.junit.Assume; public class Environment { Stack<Map<String, Value>> symbols = new Stack<>(); public Environment() { this.symbols.add(new HashMap<String, Value>()); } public Value getSymbol(String name) { for (int i = symbols.size() - 1; i >= 0; i--) { Value v = symbols.get(i).get(name); if (v != null) return v; } return null; } public boolean addSymbol(String name, Value v) { Assume.assumeNotNull(symbols.lastElement()); symbols.lastElement().put(name, v); return true; } public void enterScope() { symbols.push(new HashMap<String, Value>()); } public void outScope() { symbols.pop(); } @SuppressWarnings("unchecked") public Environment fork() { Environment environment = new Environment(); environment.symbols = (Stack<Map<String, Value>>) symbols.clone(); return environment; } }
953
0.673662
0.671564
52
17.326923
18.515816
68
false
false
0
0
0
0
0
0
1.423077
false
false
12
015e66a5215ffb13263328e6e75aafb3e8b598a1
6,605,659,716,329
8dc36b10592886f82e9b2d60e00d74e446ae6ca2
/src/test/java/com/tongdatech/sys/domain/mapper/AuthorityMapperTest.java
3cc016632c09f58da4232c833f96a580d784e8bf
[]
no_license
Yicong-Huang/WinterSpring
https://github.com/Yicong-Huang/WinterSpring
0dd7cc535e580d22877efbb53da4110e6636bdb7
0a39a1c02e2f98258023dae06bb5a7036c9edb06
refs/heads/master
2020-02-21T15:32:22.259000
2017-08-08T09:32:18
2017-08-08T09:32:18
99,675,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tongdatech.sys.domain.mapper; import com.tongdatech.sys.config.Profiles; import com.tongdatech.sys.domain.Authority; import com.tongdatech.sys.domain.UserInfo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml"}) @ActiveProfiles(Profiles.hasRedis) public class AuthorityMapperTest { @Autowired AuthorityMapper authorityMapper; @Autowired UserInfoMapper userInfoMapper; @Autowired OrgMapper orgMapper; @Test public void testGetAuthorities() { List<Authority> x = authorityMapper.getAuthorities(); System.out.println(x); UserInfo x2 = userInfoMapper.getUserInfoByUserId("Aj2BLQEQSLugnKvM8uoSIQ"); System.out.println(x2); } }
UTF-8
Java
1,155
java
AuthorityMapperTest.java
Java
[]
null
[]
package com.tongdatech.sys.domain.mapper; import com.tongdatech.sys.config.Profiles; import com.tongdatech.sys.domain.Authority; import com.tongdatech.sys.domain.UserInfo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml"}) @ActiveProfiles(Profiles.hasRedis) public class AuthorityMapperTest { @Autowired AuthorityMapper authorityMapper; @Autowired UserInfoMapper userInfoMapper; @Autowired OrgMapper orgMapper; @Test public void testGetAuthorities() { List<Authority> x = authorityMapper.getAuthorities(); System.out.println(x); UserInfo x2 = userInfoMapper.getUserInfoByUserId("Aj2BLQEQSLugnKvM8uoSIQ"); System.out.println(x2); } }
1,155
0.757576
0.751515
35
31
24.376804
91
false
false
0
0
0
0
0
0
0.542857
false
false
12
f06671fc2e663d8b882b32df3d0208f2644e40b6
2,310,692,410,056
989a6b008294d3412a3c5d857d623c08186cbb39
/itool/src/main/java/com/lynn/itool/common/dao/ICommonDao.java
164127681cd112f7ce99ede0a5378d9def5d018d
[]
no_license
Jackson-Lynn/mydream
https://github.com/Jackson-Lynn/mydream
2791bd6499ad22d9a7e7a111cbc651c08a4ae068
2f0f79b433f9e0d461c47a05f563058fc0e9efe0
refs/heads/master
2019-06-05T05:23:13.574000
2018-09-16T09:21:01
2018-09-16T09:21:01
73,607,311
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lynn.itool.common.dao; import java.util.List; import com.lynn.itool.common.vo.EnumVO; public interface ICommonDao { /** * 获取枚举 * @param enumVO * @return */ List<EnumVO> getEnumList(EnumVO enumVO); }
UTF-8
Java
252
java
ICommonDao.java
Java
[]
null
[]
package com.lynn.itool.common.dao; import java.util.List; import com.lynn.itool.common.vo.EnumVO; public interface ICommonDao { /** * 获取枚举 * @param enumVO * @return */ List<EnumVO> getEnumList(EnumVO enumVO); }
252
0.643443
0.643443
16
13.25
14.716063
42
false
false
0
0
0
0
0
0
0.6875
false
false
12
675c06459528c82a6a08c46cbdcba244f3d313eb
20,435,454,400,831
993f938a2219bc9956bee1816761cf0944e9d529
/src/main/java/com/asiainfo/entity/BaseEntity.java
ccac6fe8ccf7bde3ece8132328d46c355b314360
[]
no_license
zhangzhiwang/ProficientIn4.xSpring_Chapter18
https://github.com/zhangzhiwang/ProficientIn4.xSpring_Chapter18
7bb0827a5f0651d0e8c0230628aa9b28b252b3cd
164208ccb1b5fa4968834d038088c82a929c2258
refs/heads/master
2022-12-22T20:38:58.225000
2019-08-20T14:04:27
2019-08-20T14:04:27
200,559,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.asiainfo.entity; import java.io.Serializable; import org.apache.commons.lang3.builder.ToStringBuilder; /** * 实体类的基类 * * @author zhangzhiwang * @Aug 6, 2019 5:14:44 PM */ public class BaseEntity implements Serializable { private Page page; public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
UTF-8
Java
470
java
BaseEntity.java
Java
[ { "context": "lder.ToStringBuilder;\n\n/**\n * 实体类的基类\n *\n * @author zhangzhiwang\n * @Aug 6, 2019 5:14:44 PM\n */\npublic class BaseE", "end": 158, "score": 0.9978378415107727, "start": 146, "tag": "USERNAME", "value": "zhangzhiwang" } ]
null
[]
package com.asiainfo.entity; import java.io.Serializable; import org.apache.commons.lang3.builder.ToStringBuilder; /** * 实体类的基类 * * @author zhangzhiwang * @Aug 6, 2019 5:14:44 PM */ public class BaseEntity implements Serializable { private Page page; public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
470
0.718341
0.694323
28
15.357142
16.620155
56
false
false
0
0
0
0
0
0
0.785714
false
false
12
b7e79efc022a81c76c7086319ab6f1fb0d73cf6d
29,755,533,429,315
25185d3c84a8abed58599c8199f058503fec53c1
/JavaProject/src/project/employee/management/InterEmployeeMngCtrl.java
700fcf0686c225a8854322e6a330da9f94ca44c8
[]
no_license
yodin6123/project1
https://github.com/yodin6123/project1
6ffe6401fe7554be5612fcacc794e30a500b08c3
ee221e504702ac4cc514877f09a0bcaf08ff15ef
refs/heads/master
2022-12-05T00:20:15.820000
2020-08-10T07:20:39
2020-08-10T07:20:39
285,776,134
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.employee.management; import java.util.List; import java.util.Scanner; public interface InterEmployeeMngCtrl { // 반드시 구현해야 할 기능 목록 void registerDept(Scanner sc); // 부서등록 void registerEmployee(Scanner sc); // 사원등록 boolean isUseID(String id); // 중복 아이디 검사하기 EmployeeDTO login(Scanner sc); // 로그인 /* * 아이디와 암호를 입력받는다. * 파일로부터 불러온 객체의 정보와 비교하여 불일치시 로그인 실패, 실패하면 메뉴선택으로 돌아감 * 일치시 로그인 성공, 사원관리 메뉴로 전환 * 이는 로그인 값을 통해 해당 사원의 객체 정보 값을 값는 주소값을 불러온다. */ void employeeMenu(Scanner sc, EmployeeDTO loginEmp); // 사원관리 메뉴 /* * 메뉴 : 이름 + 님 로그인 중 출력 * 메뉴 선택 입력받는다. * 메뉴에 없는 번호 입력 시 존재하지 않는 메뉴번호 출력 */ EmployeeDTO updateMyInfo(EmployeeDTO loginEmp, Scanner sc); // 내정보 변경하기 void infoUpdate(Scanner sc)? // 변경된 값을 가지고 있어야 main()에 있는 참조변수를 통한 올바른 데이터 활용이 가능! /* * 암호변경: 값이 있을 때 변경하고 엔터나 공백은 변경없이 그대로 * * 직급변경: 값이 있을 때 변경하고 엔터나 공백은 변경없이 그대로 * 급여변경: 유효성 검사(숫자 값만 입력) * 직원 파일을 불러와 해당 직원의 변경 값을 초기화해준다! * 변경하시겠습니까 확인 창 -> 대소문자 구분 없는 문자 일치 */ void showAllEmployee(); // 모든 사원 정보 void allEO()? /* * 암호 블럭 */ void searchEmployeeMenu(EmployeeDTO loginEmp, Scanner sc); // 사원검색하기 메뉴 void searchEmployeeByName(Scanner sc); // 사원명 검색 void printEmployee(String title, List<EmployeeDTO> empList); // 사원검색 결과 출력하기 /* * */ void searchEmployeeByAge(Scanner sc); // 연령대 검색 void searchEmployeeByPos(Scanner sc); // 직급 검색 void searchEmployeeBySalary(Scanner sc); // 급여범위 검색 void searchEmployeeByDName(Scanner sc); // 부서명 검색 void deleteEmployee(EmployeeDTO loginEmp, Scanner sc); // 사원사직시키기(사장님으로 로그인 했을때만 가능하도록 한다.) /* * 사장 로그인 확인 * 사직시킬 사원명 입력 * 해당 사원에 맞는 객체를 불러와 리스트에서 인덱스 추출 후 리스트에서 제거 * 성공 시 사직 처리 완료 출력, 실패 시 실패 출력 */ }
UTF-8
Java
2,756
java
InterEmployeeMngCtrl.java
Java
[]
null
[]
package project.employee.management; import java.util.List; import java.util.Scanner; public interface InterEmployeeMngCtrl { // 반드시 구현해야 할 기능 목록 void registerDept(Scanner sc); // 부서등록 void registerEmployee(Scanner sc); // 사원등록 boolean isUseID(String id); // 중복 아이디 검사하기 EmployeeDTO login(Scanner sc); // 로그인 /* * 아이디와 암호를 입력받는다. * 파일로부터 불러온 객체의 정보와 비교하여 불일치시 로그인 실패, 실패하면 메뉴선택으로 돌아감 * 일치시 로그인 성공, 사원관리 메뉴로 전환 * 이는 로그인 값을 통해 해당 사원의 객체 정보 값을 값는 주소값을 불러온다. */ void employeeMenu(Scanner sc, EmployeeDTO loginEmp); // 사원관리 메뉴 /* * 메뉴 : 이름 + 님 로그인 중 출력 * 메뉴 선택 입력받는다. * 메뉴에 없는 번호 입력 시 존재하지 않는 메뉴번호 출력 */ EmployeeDTO updateMyInfo(EmployeeDTO loginEmp, Scanner sc); // 내정보 변경하기 void infoUpdate(Scanner sc)? // 변경된 값을 가지고 있어야 main()에 있는 참조변수를 통한 올바른 데이터 활용이 가능! /* * 암호변경: 값이 있을 때 변경하고 엔터나 공백은 변경없이 그대로 * * 직급변경: 값이 있을 때 변경하고 엔터나 공백은 변경없이 그대로 * 급여변경: 유효성 검사(숫자 값만 입력) * 직원 파일을 불러와 해당 직원의 변경 값을 초기화해준다! * 변경하시겠습니까 확인 창 -> 대소문자 구분 없는 문자 일치 */ void showAllEmployee(); // 모든 사원 정보 void allEO()? /* * 암호 블럭 */ void searchEmployeeMenu(EmployeeDTO loginEmp, Scanner sc); // 사원검색하기 메뉴 void searchEmployeeByName(Scanner sc); // 사원명 검색 void printEmployee(String title, List<EmployeeDTO> empList); // 사원검색 결과 출력하기 /* * */ void searchEmployeeByAge(Scanner sc); // 연령대 검색 void searchEmployeeByPos(Scanner sc); // 직급 검색 void searchEmployeeBySalary(Scanner sc); // 급여범위 검색 void searchEmployeeByDName(Scanner sc); // 부서명 검색 void deleteEmployee(EmployeeDTO loginEmp, Scanner sc); // 사원사직시키기(사장님으로 로그인 했을때만 가능하도록 한다.) /* * 사장 로그인 확인 * 사직시킬 사원명 입력 * 해당 사원에 맞는 객체를 불러와 리스트에서 인덱스 추출 후 리스트에서 제거 * 성공 시 사직 처리 완료 출력, 실패 시 실패 출력 */ }
2,756
0.633444
0.633444
72
23.083334
24.879572
101
false
false
0
0
0
0
0
0
1.25
false
false
12
fa9b323ccc858eb68431f3791f06d9e03be48eb1
29,755,533,430,547
b9806cc71bada39ca83e700715a35c114ba5ef1c
/src/main/java/com/five35/dex/UnarySymbol.java
194cb747292a16b989f2a0a04399800f91dc01dd
[ "BSD-3-Clause" ]
permissive
benblank/JDex
https://github.com/benblank/JDex
83b09aa48634dd7ad3231791c3ef312e3f69b4fa
2c937b25df46549b8562e05c5583bcbae07e5916
refs/heads/master
2021-01-22T10:12:54.506000
2014-10-04T03:06:58
2014-10-04T03:06:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.five35.dex; import javax.annotation.Nonnull; interface UnarySymbol { @Nonnull Result<?> unary(final Result<?> operand) throws ExecutionException; }
UTF-8
Java
164
java
UnarySymbol.java
Java
[]
null
[]
package com.five35.dex; import javax.annotation.Nonnull; interface UnarySymbol { @Nonnull Result<?> unary(final Result<?> operand) throws ExecutionException; }
164
0.77439
0.762195
8
19.5
21.639086
68
false
false
0
0
0
0
0
0
0.625
false
false
12
3de240b124f54cbfd641cb05f59f954ad34f1c2a
5,162,550,700,134
7c8b5c0c9cd86bd0e6a26272f915f3f8786b238e
/src/main/java/cn/e3mall/service/CaseActionService.java
c6df501874d1fcbefc590eb281e88cb876e7a2c8
[]
no_license
heliangdong/mvn_selenium
https://github.com/heliangdong/mvn_selenium
c8e98ea1af9dbce10ca20883f18cc0f7fdbd19fa
5d26c83225b0211e8af8fb4074a505c9e073920b
refs/heads/master
2022-12-21T15:07:48.004000
2021-03-16T07:43:47
2021-03-16T07:43:47
181,675,350
2
0
null
false
2022-12-16T03:31:26
2019-04-16T11:23:23
2021-03-16T07:47:41
2022-12-16T03:31:24
2,419
1
0
8
JavaScript
false
false
package cn.e3mall.service; import cn.e3mall.pojo.CaseAction; import java.util.List; public interface CaseActionService { List<CaseAction> getCaseActionList(); }
UTF-8
Java
169
java
CaseActionService.java
Java
[]
null
[]
package cn.e3mall.service; import cn.e3mall.pojo.CaseAction; import java.util.List; public interface CaseActionService { List<CaseAction> getCaseActionList(); }
169
0.775148
0.763314
10
15.9
16.428329
41
false
false
0
0
0
0
0
0
0.4
false
false
12
93772013f2e6fc5ee226d3954879c1907cc21b2b
12,867,722,020,517
fb3d86d5c8d037320ca8bb786836a5339ca84518
/src/test/java/ac/za/cput/Domain/Movie/MovieTest.java
b294f2e23c3b01b4d24b4523d5653f51e538fbd5
[]
no_license
RowanKir/Backend
https://github.com/RowanKir/Backend
41094050ebec23a2593bbc5d759e20505c86c32c
fefcb038b51417c24d28b2d2042ab7a5b7ac9a61
refs/heads/master
2020-08-22T15:57:02.818000
2019-10-20T21:45:27
2019-10-20T21:45:27
216,431,620
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ac.za.cput.Domain.Movie; import ac.za.cput.Factory.Movie.MovieFactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MovieTest { Movie movie1 = MovieFactory.buildMovie("End Game"); Movie movie2 = MovieFactory.buildMovie("Infinity war"); // @Test // void getYearRelease() { // assertNotNull(movie1.yearRelease); // assertNotEquals(movie1.getYearRelease(), movie2.getYearRelease()); // assertEquals(movie1.getYearRelease(), 2019); // System.out.println("Movie 1's year release is: " +movie1.getYearRelease() + "\nMovie 2's year release is: " +movie2.getYearRelease() + ""); // } @Test void getMovieTitle() { assertNotNull(movie1.movieTitle); assertNotEquals(movie1.getMovieTitle(), movie2.getMovieTitle()); assertEquals(movie1.getMovieTitle(), "End Game"); assertTrue(movie1.getMovieTitle() instanceof String); System.out.println("The title of movie 1 is: " +movie1.getMovieTitle()); } // @Test // void getMovieId() { // assertNotNull(movie1); // assertNotEquals(movie1.getMovieId(), movie2.getMovieId()); // assertEquals(movie1.getMovieId(), "1"); // assertTrue(movie1.getMovieId() instanceof String); // System.out.println("Movie 1 has an ID of: " +movie1.getMovieId()); // } // @Test // void getGenres() { // assertNotNull(movie1.genres); // assertNotEquals(movie1.getGenres(), movie1.getMovieTitle()); // assertEquals(movie1.getGenres(), "Action"); // assertTrue(movie1.getGenres() instanceof String); // System.out.println("Movie 1's Genre is: " +movie1.getGenres()); // } // @Test // void getRentalPrice() { // assertNotNull(movie1.rentalPrice); // assertNotEquals(movie1.getRentalPrice(), movie2.getRentalPrice()); // System.out.println("Movie 1's rental price is: " +movie1.getRentalPrice()); // } // @Test // void testToString() { // assertNotNull(movie1.toString()); // assertTrue(movie1.toString() instanceof String); // System.out.println(movie1.toString()); // } }
UTF-8
Java
2,183
java
MovieTest.java
Java
[]
null
[]
package ac.za.cput.Domain.Movie; import ac.za.cput.Factory.Movie.MovieFactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MovieTest { Movie movie1 = MovieFactory.buildMovie("End Game"); Movie movie2 = MovieFactory.buildMovie("Infinity war"); // @Test // void getYearRelease() { // assertNotNull(movie1.yearRelease); // assertNotEquals(movie1.getYearRelease(), movie2.getYearRelease()); // assertEquals(movie1.getYearRelease(), 2019); // System.out.println("Movie 1's year release is: " +movie1.getYearRelease() + "\nMovie 2's year release is: " +movie2.getYearRelease() + ""); // } @Test void getMovieTitle() { assertNotNull(movie1.movieTitle); assertNotEquals(movie1.getMovieTitle(), movie2.getMovieTitle()); assertEquals(movie1.getMovieTitle(), "End Game"); assertTrue(movie1.getMovieTitle() instanceof String); System.out.println("The title of movie 1 is: " +movie1.getMovieTitle()); } // @Test // void getMovieId() { // assertNotNull(movie1); // assertNotEquals(movie1.getMovieId(), movie2.getMovieId()); // assertEquals(movie1.getMovieId(), "1"); // assertTrue(movie1.getMovieId() instanceof String); // System.out.println("Movie 1 has an ID of: " +movie1.getMovieId()); // } // @Test // void getGenres() { // assertNotNull(movie1.genres); // assertNotEquals(movie1.getGenres(), movie1.getMovieTitle()); // assertEquals(movie1.getGenres(), "Action"); // assertTrue(movie1.getGenres() instanceof String); // System.out.println("Movie 1's Genre is: " +movie1.getGenres()); // } // @Test // void getRentalPrice() { // assertNotNull(movie1.rentalPrice); // assertNotEquals(movie1.getRentalPrice(), movie2.getRentalPrice()); // System.out.println("Movie 1's rental price is: " +movie1.getRentalPrice()); // } // @Test // void testToString() { // assertNotNull(movie1.toString()); // assertTrue(movie1.toString() instanceof String); // System.out.println(movie1.toString()); // } }
2,183
0.641777
0.621622
61
34.80328
30.229082
149
false
false
0
0
0
0
0
0
0.655738
false
false
12
2efdb573012578014d028d820c0757db7689ce4a
20,822,001,480,382
fdf42919d873325cd3d715c10107a26b9686a097
/src/com/contract/advanced/FunctionRowMapper.java
1f8f7c1a2ec38d450e1b4b4ad97059d8d936b6ca
[]
no_license
yang-1234567/Contract
https://github.com/yang-1234567/Contract
fee109ed8455affe11ae037a5e58aed74a3026dc
3a7712aaeedc1e878bdd4a490b68b7b4894b8218
refs/heads/master
2023-02-06T06:43:05.470000
2020-12-27T07:31:08
2020-12-27T07:31:08
320,515,063
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.contract.advanced; import java.sql.ResultSet; import com.contract.entity.Function; public class FunctionRowMapper implements RowMapper<Function> { @Override public Function getRow(ResultSet resultSet) { Function function = null; try { int id = resultSet.getInt("id"); String mumString = resultSet.getString("num"); String nameString = resultSet.getString("name"); String URLString = resultSet.getString("url"); String descriptionString = resultSet.getString("description"); int del = resultSet.getInt("del"); function = new Function(id, mumString, nameString, URLString, descriptionString, del); return function; } catch (Exception e) { e.getStackTrace(); } return function; } }
UTF-8
Java
740
java
FunctionRowMapper.java
Java
[]
null
[]
package com.contract.advanced; import java.sql.ResultSet; import com.contract.entity.Function; public class FunctionRowMapper implements RowMapper<Function> { @Override public Function getRow(ResultSet resultSet) { Function function = null; try { int id = resultSet.getInt("id"); String mumString = resultSet.getString("num"); String nameString = resultSet.getString("name"); String URLString = resultSet.getString("url"); String descriptionString = resultSet.getString("description"); int del = resultSet.getInt("del"); function = new Function(id, mumString, nameString, URLString, descriptionString, del); return function; } catch (Exception e) { e.getStackTrace(); } return function; } }
740
0.725676
0.725676
28
25.428572
23.639296
89
false
false
0
0
0
0
0
0
2.214286
false
false
12
6ebd3558da3c31be2d54292f9ce61a13832a8733
27,917,287,439,280
19cc00f0d24bdf904f7d07bd6979116deb26384e
/src/main/java/com/cm/spark/realtimestreaming/Event_Hub.java
b74ceb5c4ebdbd4d0a3fda521419aec3d58c1989
[]
no_license
ChandraMadhumanchi/Spark-RealTime-Batch-Connectors
https://github.com/ChandraMadhumanchi/Spark-RealTime-Batch-Connectors
fe2d97ce10d4cf2435b1b0a70a84fc0f9ae3d35e
e4b83ba14b6c859123b7b070e58b7c385017768e
refs/heads/master
2020-03-26T18:45:23.718000
2018-08-18T15:56:15
2018-08-18T15:56:15
145,228,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cm.spark.realtimestreaming; import java.io.IOException; import com.microsoft.azure.eventhubs.EventHubException; import org.json.simple.parser.ParseException; import com.microsoft.azure.eventhubs.EventData; import com.microsoft.azure.eventhubs.EventHubClient; import com.microsoft.azure.eventhubs.ConnectionStringBuilder; public class Event_Hub { public static int i=0; public void send_payload_ehub(String payload,String ehubparams) throws EventHubException, IOException, ParseException { String[] Eventhub_Params = ehubparams.split(","); final String NAMESPACE = Eventhub_Params[0]; final String EVENT_HUB = Eventhub_Params[1]; final String SASKEYNAME = Eventhub_Params[2]; final String SASKEY = Eventhub_Params[3]; System.out.println("***********************************BEFORE data being written to event hub"); writedatatoeventhub(payload,NAMESPACE,EVENT_HUB,SASKEYNAME,SASKEY); System.out.println("***********************************AFTER data being written to event hub"); } public static void writedatatoeventhub(String message, String namespaceName, String eventHubName, String sasKeyName, String sasKey) throws EventHubException, IOException, ParseException { i++; ConnectionStringBuilder connStr = new ConnectionStringBuilder(namespaceName, eventHubName, sasKeyName, sasKey); byte[] payloadBytes = message.getBytes("UTF-8"); EventData sendEvent = new EventData(payloadBytes); EventHubClient ehClient = EventHubClient.createFromConnectionStringSync(connStr.toString()); ehClient.sendSync(sendEvent); ehClient.close(); System.out.println("Event Sent"); System.out.println("This is message number - "+i); } public EventHubClient getClientConnection(String ehubparams) throws EventHubException, IOException { // TODO Auto-generated method stub String[] Eventhub_Params = ehubparams.split(","); final String NAMESPACE = Eventhub_Params[0]; final String EVENT_HUB = Eventhub_Params[1]; final String SASKEYNAME = Eventhub_Params[2]; final String SASKEY = Eventhub_Params[3]; ConnectionStringBuilder connStr = new ConnectionStringBuilder(NAMESPACE, EVENT_HUB, SASKEYNAME, SASKEY); return EventHubClientFactory.getOrCreate(connStr.toString()); } }
UTF-8
Java
2,367
java
Event_Hub.java
Java
[]
null
[]
package com.cm.spark.realtimestreaming; import java.io.IOException; import com.microsoft.azure.eventhubs.EventHubException; import org.json.simple.parser.ParseException; import com.microsoft.azure.eventhubs.EventData; import com.microsoft.azure.eventhubs.EventHubClient; import com.microsoft.azure.eventhubs.ConnectionStringBuilder; public class Event_Hub { public static int i=0; public void send_payload_ehub(String payload,String ehubparams) throws EventHubException, IOException, ParseException { String[] Eventhub_Params = ehubparams.split(","); final String NAMESPACE = Eventhub_Params[0]; final String EVENT_HUB = Eventhub_Params[1]; final String SASKEYNAME = Eventhub_Params[2]; final String SASKEY = Eventhub_Params[3]; System.out.println("***********************************BEFORE data being written to event hub"); writedatatoeventhub(payload,NAMESPACE,EVENT_HUB,SASKEYNAME,SASKEY); System.out.println("***********************************AFTER data being written to event hub"); } public static void writedatatoeventhub(String message, String namespaceName, String eventHubName, String sasKeyName, String sasKey) throws EventHubException, IOException, ParseException { i++; ConnectionStringBuilder connStr = new ConnectionStringBuilder(namespaceName, eventHubName, sasKeyName, sasKey); byte[] payloadBytes = message.getBytes("UTF-8"); EventData sendEvent = new EventData(payloadBytes); EventHubClient ehClient = EventHubClient.createFromConnectionStringSync(connStr.toString()); ehClient.sendSync(sendEvent); ehClient.close(); System.out.println("Event Sent"); System.out.println("This is message number - "+i); } public EventHubClient getClientConnection(String ehubparams) throws EventHubException, IOException { // TODO Auto-generated method stub String[] Eventhub_Params = ehubparams.split(","); final String NAMESPACE = Eventhub_Params[0]; final String EVENT_HUB = Eventhub_Params[1]; final String SASKEYNAME = Eventhub_Params[2]; final String SASKEY = Eventhub_Params[3]; ConnectionStringBuilder connStr = new ConnectionStringBuilder(NAMESPACE, EVENT_HUB, SASKEYNAME, SASKEY); return EventHubClientFactory.getOrCreate(connStr.toString()); } }
2,367
0.716941
0.712717
60
37.450001
38.933887
186
false
false
0
0
0
0
0
0
2.25
false
false
12
3915abcdcaa91efd6469822cd6638ad143c5fcc2
18,614,388,313,790
fac45de697d128c04506fe732570e24bbbde11f8
/app/src/main/java/com/thebaileybrew/mobileinventory/EditorDisplay.java
f958592c890945db6bff2a943e11f5927b78fe3f
[]
no_license
TheBaileyBrew/MobileInventory
https://github.com/TheBaileyBrew/MobileInventory
f7cf2196cf193a63d3c4dad6522587c6522184a8
ebadbd7073df6fcf952033c2cd03e88880fc3731
refs/heads/master
2020-03-23T00:52:00.355000
2018-07-22T17:36:41
2018-07-22T17:36:41
140,889,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thebaileybrew.mobileinventory; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.thebaileybrew.mobileinventory.data.InventoryDbHelper; import com.thebaileybrew.mobileinventory.data.MobileContract; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import static com.thebaileybrew.mobileinventory.data.MobileContract.*; public class EditorDisplay extends AppCompatActivity{ private static final String TAG = EditorDisplay.class.getSimpleName(); private EditText mModelName; private EditText mModelSerial; private Spinner mModelUsageSpinner; private Spinner mModelInventorySpinner; private String mUserName = "Matthew Bailey"; private int mModelUsage = MobileEntry.CUSTOMER_TYPE; private int mModelInventory = MobileEntry.NEW_TYPE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); mModelName = findViewById(R.id.model_name_edittext); mModelSerial = findViewById(R.id.model_serial_edittext); mModelUsageSpinner = findViewById(R.id.model_usage_spinner); mModelInventorySpinner = findViewById(R.id.model_inventory_type_spinner); setupSpinners(); } private void setupSpinners() { //Create the ArrayAdapter for device type spinner. List options are from the string array ArrayAdapter modelUsageAdapter = ArrayAdapter.createFromResource(this, R.array.array_model_types, android.R.layout.simple_spinner_item); //Create the ArrayAdapter for inventory type spinner. List options are from the string array ArrayAdapter modelInventoryAdapter = ArrayAdapter.createFromResource(this, R.array.array_inventory_types, android.R.layout.simple_spinner_item); //Specify the dropdown style modelUsageAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); modelInventoryAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); mModelUsageSpinner.setAdapter(modelUsageAdapter); mModelInventorySpinner.setAdapter(modelInventoryAdapter); mModelUsageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedItem = (String) parent.getItemAtPosition(position); if(!TextUtils.isEmpty(selectedItem)) { if (selectedItem.equals(getString(R.string.customer_type))) { mModelUsage = MobileEntry.CUSTOMER_TYPE; } else { mModelUsage = MobileEntry.SALES_TYPE; } } } @Override public void onNothingSelected(AdapterView<?> parent) { mModelUsage = MobileEntry.CUSTOMER_TYPE; } }); mModelInventorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedItem = (String) parent.getItemAtPosition(position); if(!TextUtils.isEmpty(selectedItem)) { if(selectedItem.equals(getString(R.string.new_type))) { mModelInventory = MobileEntry.NEW_TYPE; } else if (selectedItem.equals(getString(R.string.used_type))) { mModelInventory = MobileEntry.USED_TYPE; } else { mModelInventory = MobileEntry.SUPPORT_TYPE; } } } @Override public void onNothingSelected(AdapterView<?> parent) { mModelInventory = MobileEntry.NEW_TYPE; } }); } /* Get user input from editor and save into database */ private void insertDevice() { //Read from the input fields //Use trim to eliminate leading or trailing whitespace String modelName = mModelName.getText().toString().trim(); String modelSerial = mModelSerial.getText().toString().trim(); String addUser = mUserName; //Uneditable TODO: Figure out STATIC SAVE SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US); String addUserDate = sdf.format(new Date()) ; //Uneditable TODO: Figure out STATIC SAVE String updateUser = "Temporary Name"; String updateUserDate = "01/01/2001 01:01:01"; //String updateUser = get current info & update upon saving TODO: Figure out INLINE READABLE //String updateUserDate = get current info & update upon saving TODO: Figure out INLINE READABLE //Create an instance of the Database Helper InventoryDbHelper mDbHelper = new InventoryDbHelper(this); //Get the database into writable mode SQLiteDatabase db = mDbHelper.getWritableDatabase(); //Create a ConstantValues object where column names are the keys ContentValues values = new ContentValues(); values.put(MobileEntry.COLUMN_MODEL_NAME, modelName); values.put(MobileEntry.COLUMN_MODEL_SERIAL_NUMBER, modelSerial); values.put(MobileEntry.COLUMN_MODEL_USAGE_TYPE, mModelUsage); values.put(MobileEntry.COLUMN_MODEL_INVENTORY_TYPE, mModelInventory); values.put(MobileEntry.USER_ADD_RECORD, addUser); values.put(MobileEntry.USER_ADD_RECORD_DATE, addUserDate); values.put(MobileEntry.USER_UPDATE_RECORD, updateUser); values.put(MobileEntry.USER_UPDATE_RECORD_DATE, updateUserDate); //Insert a new row for the equipment into the database, and return the ID of that row long newRowId = db.insert(MobileEntry.TABLE_NAME,null, values); //Show toast depending on the success of insertion into database table if(newRowId == -1) { Toast.makeText(this, "Error saving equipment", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Equipment saved with row id: " + newRowId, Toast.LENGTH_SHORT).show(); } } //Menu specific options @Override public boolean onCreateOptionsMenu(Menu menu) { //Inflate the menu for the editor getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_save: // Save pet to database insertDevice(); // Exit activity finish(); return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: // Do nothing for now return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // Navigate back to parent activity (CatalogActivity) NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
UTF-8
Java
7,876
java
EditorDisplay.java
Java
[ { "context": "nventorySpinner;\n\n private String mUserName = \"Matthew Bailey\";\n\n private int mModelUsage = MobileEntry.CUST", "end": 1161, "score": 0.9997701048851013, "start": 1147, "tag": "NAME", "value": "Matthew Bailey" }, { "context": "Text().toString().trim();\n String addUser = mUserName; //Uneditable TODO: Figure out STATIC SAVE\n ", "end": 4854, "score": 0.9907079935073853, "start": 4845, "tag": "USERNAME", "value": "mUserName" }, { "context": "gure out STATIC SAVE\n String updateUser = \"Temporary Name\";\n String updateUserDate = \"01/01/200", "end": 5119, "score": 0.4891747832298279, "start": 5110, "tag": "NAME", "value": "Temporary" }, { "context": "STATIC SAVE\n String updateUser = \"Temporary Name\";\n String updateUserDate = \"01/01/2001 01:", "end": 5124, "score": 0.7854685187339783, "start": 5120, "tag": "USERNAME", "value": "Name" } ]
null
[]
package com.thebaileybrew.mobileinventory; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.thebaileybrew.mobileinventory.data.InventoryDbHelper; import com.thebaileybrew.mobileinventory.data.MobileContract; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import static com.thebaileybrew.mobileinventory.data.MobileContract.*; public class EditorDisplay extends AppCompatActivity{ private static final String TAG = EditorDisplay.class.getSimpleName(); private EditText mModelName; private EditText mModelSerial; private Spinner mModelUsageSpinner; private Spinner mModelInventorySpinner; private String mUserName = "<NAME>"; private int mModelUsage = MobileEntry.CUSTOMER_TYPE; private int mModelInventory = MobileEntry.NEW_TYPE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); mModelName = findViewById(R.id.model_name_edittext); mModelSerial = findViewById(R.id.model_serial_edittext); mModelUsageSpinner = findViewById(R.id.model_usage_spinner); mModelInventorySpinner = findViewById(R.id.model_inventory_type_spinner); setupSpinners(); } private void setupSpinners() { //Create the ArrayAdapter for device type spinner. List options are from the string array ArrayAdapter modelUsageAdapter = ArrayAdapter.createFromResource(this, R.array.array_model_types, android.R.layout.simple_spinner_item); //Create the ArrayAdapter for inventory type spinner. List options are from the string array ArrayAdapter modelInventoryAdapter = ArrayAdapter.createFromResource(this, R.array.array_inventory_types, android.R.layout.simple_spinner_item); //Specify the dropdown style modelUsageAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); modelInventoryAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); mModelUsageSpinner.setAdapter(modelUsageAdapter); mModelInventorySpinner.setAdapter(modelInventoryAdapter); mModelUsageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedItem = (String) parent.getItemAtPosition(position); if(!TextUtils.isEmpty(selectedItem)) { if (selectedItem.equals(getString(R.string.customer_type))) { mModelUsage = MobileEntry.CUSTOMER_TYPE; } else { mModelUsage = MobileEntry.SALES_TYPE; } } } @Override public void onNothingSelected(AdapterView<?> parent) { mModelUsage = MobileEntry.CUSTOMER_TYPE; } }); mModelInventorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selectedItem = (String) parent.getItemAtPosition(position); if(!TextUtils.isEmpty(selectedItem)) { if(selectedItem.equals(getString(R.string.new_type))) { mModelInventory = MobileEntry.NEW_TYPE; } else if (selectedItem.equals(getString(R.string.used_type))) { mModelInventory = MobileEntry.USED_TYPE; } else { mModelInventory = MobileEntry.SUPPORT_TYPE; } } } @Override public void onNothingSelected(AdapterView<?> parent) { mModelInventory = MobileEntry.NEW_TYPE; } }); } /* Get user input from editor and save into database */ private void insertDevice() { //Read from the input fields //Use trim to eliminate leading or trailing whitespace String modelName = mModelName.getText().toString().trim(); String modelSerial = mModelSerial.getText().toString().trim(); String addUser = mUserName; //Uneditable TODO: Figure out STATIC SAVE SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US); String addUserDate = sdf.format(new Date()) ; //Uneditable TODO: Figure out STATIC SAVE String updateUser = "Temporary Name"; String updateUserDate = "01/01/2001 01:01:01"; //String updateUser = get current info & update upon saving TODO: Figure out INLINE READABLE //String updateUserDate = get current info & update upon saving TODO: Figure out INLINE READABLE //Create an instance of the Database Helper InventoryDbHelper mDbHelper = new InventoryDbHelper(this); //Get the database into writable mode SQLiteDatabase db = mDbHelper.getWritableDatabase(); //Create a ConstantValues object where column names are the keys ContentValues values = new ContentValues(); values.put(MobileEntry.COLUMN_MODEL_NAME, modelName); values.put(MobileEntry.COLUMN_MODEL_SERIAL_NUMBER, modelSerial); values.put(MobileEntry.COLUMN_MODEL_USAGE_TYPE, mModelUsage); values.put(MobileEntry.COLUMN_MODEL_INVENTORY_TYPE, mModelInventory); values.put(MobileEntry.USER_ADD_RECORD, addUser); values.put(MobileEntry.USER_ADD_RECORD_DATE, addUserDate); values.put(MobileEntry.USER_UPDATE_RECORD, updateUser); values.put(MobileEntry.USER_UPDATE_RECORD_DATE, updateUserDate); //Insert a new row for the equipment into the database, and return the ID of that row long newRowId = db.insert(MobileEntry.TABLE_NAME,null, values); //Show toast depending on the success of insertion into database table if(newRowId == -1) { Toast.makeText(this, "Error saving equipment", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Equipment saved with row id: " + newRowId, Toast.LENGTH_SHORT).show(); } } //Menu specific options @Override public boolean onCreateOptionsMenu(Menu menu) { //Inflate the menu for the editor getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_save: // Save pet to database insertDevice(); // Exit activity finish(); return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: // Do nothing for now return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // Navigate back to parent activity (CatalogActivity) NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
7,868
0.660742
0.658329
185
41.572971
29.916033
104
false
false
0
0
0
0
0
0
0.6
false
false
12
75aecc7787cbab05c9732a48a4de7dc911935fa8
29,016,799,106,680
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/16/16_d79416ea70ce19b5fac3108255533bcdc972d457/NJHunterdonCountyParser/16_d79416ea70ce19b5fac3108255533bcdc972d457_NJHunterdonCountyParser_t.java
ea07844d57b6813ea3b568d943880775f439078d
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package net.anei.cadpage.parsers.NJ; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.MsgInfo.Data; import net.anei.cadpage.parsers.MsgParser; /* Hunterdon County, NJ (Flemington) Contact: Dan Palmer <cantbeatl337@gmail.com> 49FD:ALRM ACT: (49)SHOPPES AT FLEMINGTON / 100 REAVILLE AVE NEAR: R202-31 RAMP TO RARITAN TWP LI 12003820: EM NAILS::ZONE 4 & 9 / GENERAL FIRE SIGNAL / WATN 49FD:SMOKE L3: (49)15 BONNELL ST NEAR: PARK AVE TO ACADEMY ST 12002996 POSSIBLE ELECTRICAL::SMOKE DISAPATING 49FD:SMOKE L3: (49)WALGREENS / 29 STATE HWY NO 31 NEAR: CHURCH ST TO RARITAN TWP LINE 12002674: BAD SMELL OF SMOKE COMING OUT OF VENTS 49FD:ALRM ACT: (49)HUNTER HILLS APARTMENTS / 1 GARDEN LANE NEAR: MAIN ST N TO CUL DE SAC 12002158: APT I-6 / FIRE ALARM SET OFF BY COOKING, REQUESTING ASSIST 49FD:HMT GAS L3: (21)JOHANNA FARMS / 1 JOHANNA FARMS RD NEAR: R202 SOUTH TO BR+W RR TRACKS 11125350 WATER FLOW::UPGRADE - SMELL OF GAS IN BLDG PER CMD 49FD:FIRE L3:(21)41 STIRRUP LANE NEAR: CARRIAGE GATE DR TO CARRIAGE G 11123569 SMOKE IN LAUNDRY ROOM:: Contact: Joe Zujkowski <jzujkowski@gmail.com> Sender: hces@hunterdon.co.nj.us 22RS:MVA UNKNOWN: (24)CO HWY NO 517 HWY NEAR: FIELDVIEW/DINNERPOT TO LAUREL 12007721 2 PICKUP TRUCKS::2 PICK UP HEAD ON DS TO DS 22RS:RESP DIS: (22)18 JUDGE THOMPSON RD NEAR: COLONIAL RD TO CUL DE SAC 12007605 RESP DISTRESS::6 YOM / HAS BEEN GIVEN A NEBULIZER / NO IMPROVEMENT 22RS:AMB NEED: (22)245 NUTHATCH CT NEAR: NUTHATCH CT/BLDG 43 TO NO OUTL 12007597 SHAKING / LEFT SIDE PAIN::IS IN BED COVERED UP / LEFT SIDE PAIN / SHAKING / 22RS:MV STOP: (49)HUNTERDON SHOPPING CENTER / 35 REAVILLE AVE NEAR: MAIN ST CIR TO R202-31 12007596 ZDU27L:: 22RS:HEART AA: (22)101 OLD FARM RD NEAR: R523 TO SCRABBLETOWN RD 12007510 30 YOM::CHEST PAIN / STOMACH PAIN / BACK PAIN / ARM PAIN / NAUSEA / DIZZYNESS 22RS:AMB NEED: (24)23 CO HWY NO 517 HWY NEAR: LAMINGTON RD TO JOLIET ST 12007493 LIFT ASSIST::ASSIST PTL IN MOVING ELDERLY WOMAN FROM CHAIR TO BED 22RS:AMB NEEDB: (22)CHUBB CORPORATION BUILDING A / 202 HALLS MILL RD NEAR: R523 TO TAYLORS MILL RD 12007449 23YOF PREGNANT::DIZZY NAUSEAS / 1 EAST LADIES RO 22RS:AMB NEEDB: (22)CHUBB CORPORATION BUILDING A / 202 HALLS MILL RD #BLD A NEAR: R523 TO TAYLORS MILL RD 12007402 50'S YOF::ELEVATED BP NAUSEAS / PT IN NUR 22RS:UNCON A: (46)76 OLD MOUNTAIN RD NEAR: CHERRY ST TO CONRAIL RR TRACKS 12007379 63YOM::SYNCOPE HX DIABETIES 22RS:LACCER: (24)24 OLD MINE RD NEAR: COKESBURY RD TO DEAD END 12007354 FACIAL LACERATION::30'S YOA MALE CUT ON FOREHEAD FROM FALLING GLASS, REPLACING WINDO Contact: Active911.com Agency name: Quakertown Fire Company Location: Franklin Township, NJ Sender: messaging@iamresponding.com (91 Fire/Rescue) 91RS:HEART AT: (91)QUAKERTOWN FIRE COMPANY / 67 QUAKERTOWN RD NEAR: R615 (PITTSTOWN RD) TO QUAKER 12064800 20 YOM > HMC:: (91 Fire/Rescue) 91FD:WOOD/BRU: (21)96 OAK GROVE RD NEAR: FEATHERBED LANE TO DECKER RD 12065010 FIELD FIRE:: (91 Fire/Rescue) 91RS:AMB NEED: (91)WAL-MART STORE / 1 WAL-MART PLAZA NEAR: SERVICE RD TO DEAD END 12065030 76 YOF::HIT HEAD / PAIN (91 Fire/Rescue) 91RS:AMB NEED: (91)223 PITTSTOWN RD NEAR: HOGBACK RD TO LOYALIST WAY 12065190 85 YOM::SEVERE LEG PAIN / NO CHEST PAIN / NO DIFF BREATHING (91 Fire/Rescue) 91FD:BUILDING: (14)25 MAIN ST E NEAR: WASHINGTON AVE TO NASSAU RD 12065559 FLAMES SHOWING::BASEMENT FIRE */ public class NJHunterdonCountyParser extends MsgParser { private static final Pattern MASTER = Pattern.compile("([A-Z0-9]+):([A-Z /0-9]+): *\\((\\d+)\\) *(.*?) NEAR: *(.*?) (\\d{8})\\b *(.*?)"); public NJHunterdonCountyParser() { super("HUNTERDON COUNTY", "NJ"); } @Override public String getFilter() { return "hces@hunterdon.co.nj.us"; } @Override protected boolean parseMsg(String body, Data data) { Matcher match = MASTER.matcher(body); if (!match.matches()) return false; data.strSource = match.group(1); data.strCall = match.group(2); String sCity = convertCodes(match.group(3), CITY_CODES); int pt = sCity.indexOf('/'); if (pt >= 0) { if (data.strSource.endsWith("RS")) sCity = sCity.substring(pt+1); else sCity = sCity.substring(0,pt); } data.strCity = sCity; Parser p = new Parser(match.group(4)); data.strPlace = p.getOptional(" / "); parseAddress(p.get().replace(" NO ", " "), data); data.strCross = match.group(5); data.strCallId = match.group(6); data.strSupp = match.group(7); return true; } // There are different city codes for fire and medical units. Mostly they do // not conflict. In the two cases where they do the fire city will come first and // be separated from the medical city by a / private static final Properties CITY_CODES = buildCodeTable(new String[]{ "11", "Frenchtown", "12", "Glen Gardner", "13", "Hampton", "14", "High Bridge", "15", "Holland Twp", "16", "Kingwood", "17", "Lambertville", "18", "Lebanon", "19", "Lebanon Twp", "21", "Raritan Twp", "22", "Whitehouse Station/Readington Twp", "23", "Stockton", "24", "Oldwick/Tewksbury", "25", "Pattenburg", "26", "West Amwell Twp", "31", "East Whitehouse", "32", "Readington", "33", "Three Bridges", "34", "Fairmount", "43", "Bloomsbury", "41", "Quakertown", "44", "Califon", "45", "Clinton", "46", "Annandale", "47", "Sergeantsville", "48", "Amwell Valley", "49", "Flemington", "52", "Asbury", "57", "Pottersville", "74", "Branchburg", "79", "Neshanic/Hillsborough", "91", "Quakertown", "92", "Milford", "93", "Country Hills", "94", "Delaware Valley", "95", "Upper Black Eddy", "96", "New Hope Eagle" }); }
UTF-8
Java
5,970
java
16_d79416ea70ce19b5fac3108255533bcdc972d457_NJHunterdonCountyParser_t.java
Java
[ { "context": " \n /*\n Hunterdon County, NJ (Flemington)\n Contact: Dan Palmer <cantbeatl337@gmail.com>\n \n 49FD:ALRM ACT: (49)SH", "end": 290, "score": 0.9998788833618164, "start": 280, "tag": "NAME", "value": "Dan Palmer" }, { "context": "don County, NJ (Flemington)\n Contact: Dan Palmer <cantbeatl337@gmail.com>\n \n 49FD:ALRM ACT: (49)SHOPPES AT FLEMINGTON / 10", "end": 314, "score": 0.9999260902404785, "start": 292, "tag": "EMAIL", "value": "cantbeatl337@gmail.com" }, { "context": "AGE G 11123569 SMOKE IN LAUNDRY ROOM::\n \n Contact: Joe Zujkowski <jzujkowski@gmail.com>\n Sender: hces@hunterdon.co", "end": 1163, "score": 0.9998173117637634, "start": 1150, "tag": "NAME", "value": "Joe Zujkowski" }, { "context": "MOKE IN LAUNDRY ROOM::\n \n Contact: Joe Zujkowski <jzujkowski@gmail.com>\n Sender: hces@hunterdon.co.nj.us\n 22RS:MVA UNKNO", "end": 1185, "score": 0.9999325275421143, "start": 1165, "tag": "EMAIL", "value": "jzujkowski@gmail.com" }, { "context": "act: Joe Zujkowski <jzujkowski@gmail.com>\n Sender: hces@hunterdon.co.nj.us\n 22RS:MVA UNKNOWN: (24)CO HWY NO 517 HWY NEAR: FI", "end": 1219, "score": 0.9999334812164307, "start": 1196, "tag": "EMAIL", "value": "hces@hunterdon.co.nj.us" }, { "context": "e Company Location: Franklin Township, NJ \nSender: messaging@iamresponding.com\n\n(91 Fire/Rescue) 91RS:HEART AT: (91)QUAKERTOWN F", "end": 2784, "score": 0.9999164938926697, "start": 2757, "tag": "EMAIL", "value": "messaging@iamresponding.com" }, { "context": "rride\n public String getFilter() {\n return \"hces@hunterdon.co.nj.us\";\n }\n \n @Override\n protected boolean pars", "end": 3822, "score": 0.9998390078544617, "start": 3799, "tag": "EMAIL", "value": "hces@hunterdon.co.nj.us" }, { "context": "tring[]{\n \"11\", \"Frenchtown\",\n \"12\", \"Glen Gardner\",\n \"13\", \"Hampton\",\n \"14\", \"High Brid", "end": 4952, "score": 0.9993299245834351, "start": 4940, "tag": "NAME", "value": "Glen Gardner" }, { "context": "Whitehouse Station/Readington Twp\",\n \"23\", \"Stockton\",\n \"24\", \"Oldwick/Tewksbury\",\n \"25\", ", "end": 5241, "score": 0.6818186044692993, "start": 5233, "tag": "NAME", "value": "Stockton" } ]
null
[]
package net.anei.cadpage.parsers.NJ; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.MsgInfo.Data; import net.anei.cadpage.parsers.MsgParser; /* Hunterdon County, NJ (Flemington) Contact: <NAME> <<EMAIL>> 49FD:ALRM ACT: (49)SHOPPES AT FLEMINGTON / 100 REAVILLE AVE NEAR: R202-31 RAMP TO RARITAN TWP LI 12003820: EM NAILS::ZONE 4 & 9 / GENERAL FIRE SIGNAL / WATN 49FD:SMOKE L3: (49)15 BONNELL ST NEAR: PARK AVE TO ACADEMY ST 12002996 POSSIBLE ELECTRICAL::SMOKE DISAPATING 49FD:SMOKE L3: (49)WALGREENS / 29 STATE HWY NO 31 NEAR: CHURCH ST TO RARITAN TWP LINE 12002674: BAD SMELL OF SMOKE COMING OUT OF VENTS 49FD:ALRM ACT: (49)HUNTER HILLS APARTMENTS / 1 GARDEN LANE NEAR: MAIN ST N TO CUL DE SAC 12002158: APT I-6 / FIRE ALARM SET OFF BY COOKING, REQUESTING ASSIST 49FD:HMT GAS L3: (21)JOHANNA FARMS / 1 JOHANNA FARMS RD NEAR: R202 SOUTH TO BR+W RR TRACKS 11125350 WATER FLOW::UPGRADE - SMELL OF GAS IN BLDG PER CMD 49FD:FIRE L3:(21)41 STIRRUP LANE NEAR: CARRIAGE GATE DR TO CARRIAGE G 11123569 SMOKE IN LAUNDRY ROOM:: Contact: <NAME> <<EMAIL>> Sender: <EMAIL> 22RS:MVA UNKNOWN: (24)CO HWY NO 517 HWY NEAR: FIELDVIEW/DINNERPOT TO LAUREL 12007721 2 PICKUP TRUCKS::2 PICK UP HEAD ON DS TO DS 22RS:RESP DIS: (22)18 JUDGE THOMPSON RD NEAR: COLONIAL RD TO CUL DE SAC 12007605 RESP DISTRESS::6 YOM / HAS BEEN GIVEN A NEBULIZER / NO IMPROVEMENT 22RS:AMB NEED: (22)245 NUTHATCH CT NEAR: NUTHATCH CT/BLDG 43 TO NO OUTL 12007597 SHAKING / LEFT SIDE PAIN::IS IN BED COVERED UP / LEFT SIDE PAIN / SHAKING / 22RS:MV STOP: (49)HUNTERDON SHOPPING CENTER / 35 REAVILLE AVE NEAR: MAIN ST CIR TO R202-31 12007596 ZDU27L:: 22RS:HEART AA: (22)101 OLD FARM RD NEAR: R523 TO SCRABBLETOWN RD 12007510 30 YOM::CHEST PAIN / STOMACH PAIN / BACK PAIN / ARM PAIN / NAUSEA / DIZZYNESS 22RS:AMB NEED: (24)23 CO HWY NO 517 HWY NEAR: LAMINGTON RD TO JOLIET ST 12007493 LIFT ASSIST::ASSIST PTL IN MOVING ELDERLY WOMAN FROM CHAIR TO BED 22RS:AMB NEEDB: (22)CHUBB CORPORATION BUILDING A / 202 HALLS MILL RD NEAR: R523 TO TAYLORS MILL RD 12007449 23YOF PREGNANT::DIZZY NAUSEAS / 1 EAST LADIES RO 22RS:AMB NEEDB: (22)CHUBB CORPORATION BUILDING A / 202 HALLS MILL RD #BLD A NEAR: R523 TO TAYLORS MILL RD 12007402 50'S YOF::ELEVATED BP NAUSEAS / PT IN NUR 22RS:UNCON A: (46)76 OLD MOUNTAIN RD NEAR: CHERRY ST TO CONRAIL RR TRACKS 12007379 63YOM::SYNCOPE HX DIABETIES 22RS:LACCER: (24)24 OLD MINE RD NEAR: COKESBURY RD TO DEAD END 12007354 FACIAL LACERATION::30'S YOA MALE CUT ON FOREHEAD FROM FALLING GLASS, REPLACING WINDO Contact: Active911.com Agency name: Quakertown Fire Company Location: Franklin Township, NJ Sender: <EMAIL> (91 Fire/Rescue) 91RS:HEART AT: (91)QUAKERTOWN FIRE COMPANY / 67 QUAKERTOWN RD NEAR: R615 (PITTSTOWN RD) TO QUAKER 12064800 20 YOM > HMC:: (91 Fire/Rescue) 91FD:WOOD/BRU: (21)96 OAK GROVE RD NEAR: FEATHERBED LANE TO DECKER RD 12065010 FIELD FIRE:: (91 Fire/Rescue) 91RS:AMB NEED: (91)WAL-MART STORE / 1 WAL-MART PLAZA NEAR: SERVICE RD TO DEAD END 12065030 76 YOF::HIT HEAD / PAIN (91 Fire/Rescue) 91RS:AMB NEED: (91)223 PITTSTOWN RD NEAR: HOGBACK RD TO LOYALIST WAY 12065190 85 YOM::SEVERE LEG PAIN / NO CHEST PAIN / NO DIFF BREATHING (91 Fire/Rescue) 91FD:BUILDING: (14)25 MAIN ST E NEAR: WASHINGTON AVE TO NASSAU RD 12065559 FLAMES SHOWING::BASEMENT FIRE */ public class NJHunterdonCountyParser extends MsgParser { private static final Pattern MASTER = Pattern.compile("([A-Z0-9]+):([A-Z /0-9]+): *\\((\\d+)\\) *(.*?) NEAR: *(.*?) (\\d{8})\\b *(.*?)"); public NJHunterdonCountyParser() { super("HUNTERDON COUNTY", "NJ"); } @Override public String getFilter() { return "<EMAIL>"; } @Override protected boolean parseMsg(String body, Data data) { Matcher match = MASTER.matcher(body); if (!match.matches()) return false; data.strSource = match.group(1); data.strCall = match.group(2); String sCity = convertCodes(match.group(3), CITY_CODES); int pt = sCity.indexOf('/'); if (pt >= 0) { if (data.strSource.endsWith("RS")) sCity = sCity.substring(pt+1); else sCity = sCity.substring(0,pt); } data.strCity = sCity; Parser p = new Parser(match.group(4)); data.strPlace = p.getOptional(" / "); parseAddress(p.get().replace(" NO ", " "), data); data.strCross = match.group(5); data.strCallId = match.group(6); data.strSupp = match.group(7); return true; } // There are different city codes for fire and medical units. Mostly they do // not conflict. In the two cases where they do the fire city will come first and // be separated from the medical city by a / private static final Properties CITY_CODES = buildCodeTable(new String[]{ "11", "Frenchtown", "12", "<NAME>", "13", "Hampton", "14", "High Bridge", "15", "Holland Twp", "16", "Kingwood", "17", "Lambertville", "18", "Lebanon", "19", "Lebanon Twp", "21", "Raritan Twp", "22", "Whitehouse Station/Readington Twp", "23", "Stockton", "24", "Oldwick/Tewksbury", "25", "Pattenburg", "26", "West Amwell Twp", "31", "East Whitehouse", "32", "Readington", "33", "Three Bridges", "34", "Fairmount", "43", "Bloomsbury", "41", "Quakertown", "44", "Califon", "45", "Clinton", "46", "Annandale", "47", "Sergeantsville", "48", "Amwell Valley", "49", "Flemington", "52", "Asbury", "57", "Pottersville", "74", "Branchburg", "79", "Neshanic/Hillsborough", "91", "Quakertown", "92", "Milford", "93", "Country Hills", "94", "Delaware Valley", "95", "Upper Black Eddy", "96", "New Hope Eagle" }); }
5,873
0.668509
0.590787
123
47.528454
45.988922
158
false
false
0
0
0
0
0
0
0.886179
false
false
12
1f1d8801de9858d189bfc8ade7b919c867e8768e
8,598,524,541,287
1cbf46c147b09a878235da8010f427eb2447bab5
/src/main/java/ljtao/book_JavaProgramOptimization/d_2/a_threadpool/PThread.java
cd1cecb29d4c82e51c5b8e4ac2cf4b3536e00fc4
[]
no_license
mathLjtao/MyJavaStudy
https://github.com/mathLjtao/MyJavaStudy
54b90fbb0f285a611b73d72477a605d875563716
d9a934e95b2f24bf854a4c359dd04d3fb8acd0d9
refs/heads/master
2022-12-22T02:01:24.856000
2021-09-16T13:15:20
2021-09-16T13:15:20
188,509,645
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ljtao.book_JavaProgramOptimization.d_2.a_threadpool; public class PThread extends Thread{ //线程池 private MyThreadPool pool; //任务 private Runnable target; private boolean isShutDown=false; private boolean isIdle=false; public PThread(Runnable target, String name, MyThreadPool pool) { super(name); this.pool=pool; this.target=target; } public Runnable getTarget(){ return target; } public boolean isIdle(){ return isIdle; } public void run(){ while(!isShutDown){ isIdle=false; //这里有问题???? if(target!=null){ target.run(); } //任务结束了,到闲置状态 isIdle=true; try { pool.repool(this); synchronized(this){ //线程空闲,等待新的任务到来 wait(); } } catch (InterruptedException e) { e.printStackTrace(); } isIdle=false; } } public synchronized void setTarget(Runnable newTarget) { target=newTarget; //设置了任务之后,通知run方法,开始执行这个任务,使在wait的线程开始执行 notifyAll(); } //关闭线程 public synchronized void shutDown(){ isShutDown=true; notifyAll(); } }
UTF-8
Java
1,178
java
PThread.java
Java
[]
null
[]
package ljtao.book_JavaProgramOptimization.d_2.a_threadpool; public class PThread extends Thread{ //线程池 private MyThreadPool pool; //任务 private Runnable target; private boolean isShutDown=false; private boolean isIdle=false; public PThread(Runnable target, String name, MyThreadPool pool) { super(name); this.pool=pool; this.target=target; } public Runnable getTarget(){ return target; } public boolean isIdle(){ return isIdle; } public void run(){ while(!isShutDown){ isIdle=false; //这里有问题???? if(target!=null){ target.run(); } //任务结束了,到闲置状态 isIdle=true; try { pool.repool(this); synchronized(this){ //线程空闲,等待新的任务到来 wait(); } } catch (InterruptedException e) { e.printStackTrace(); } isIdle=false; } } public synchronized void setTarget(Runnable newTarget) { target=newTarget; //设置了任务之后,通知run方法,开始执行这个任务,使在wait的线程开始执行 notifyAll(); } //关闭线程 public synchronized void shutDown(){ isShutDown=true; notifyAll(); } }
1,178
0.671512
0.670543
57
17.105263
15.000216
66
false
false
0
0
0
0
0
0
2.403509
false
false
12
92b245d6e1cffdf4592c78469f7c96cc455a0bd3
8,598,524,543,435
76cafcc6fdfc1eb1825af806ff1e7dc7087ddf42
/java/03 java loops, methods and classes/Java-Loops-Methods-Classes-Homework/src/_09_ListOfProducts.java
5cbbaa590f1fced198cbe79e6854885a2a2d0095
[]
no_license
dpelovski/softuni
https://github.com/dpelovski/softuni
ac7a8f6da874cab9fda731e9dacf7b3c57ee50c7
34208b3e8adc96afb4b5e9cb4e925ac0f73a9362
refs/heads/master
2017-04-21T23:40:54.031000
2015-11-17T20:57:32
2015-11-17T20:57:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.util.List; import java.util.Scanner; import java.util.ArrayList; import java.io.IOException; import java.util.Comparator; import java.util.Collections; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; public class _09_ListOfProducts { public static void main(String[] args) { String inputFileName = "src/_09_Input.txt"; String outputFileName = "src/_09_Output.txt"; try { File textFile = new File(inputFileName); Scanner scan = new Scanner(textFile); List<Product> products = new ArrayList<>(); while (scan.hasNext()) { String[] currentProduct = scan.nextLine().split(" "); String name = currentProduct[0]; double price = Double.parseDouble(currentProduct[1]); products.add(new Product(name, price)); } Collections.sort(products, Comparator.comparing(p -> p.price)); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFileName), "utf-8")); for (Product product : products) { writer.write(product.toString() + "\n"); } } catch (IOException ex) { System.out.println("Error"); } finally { try {writer.close();} catch (IOException ex) {System.out.println("Error");} } } catch (FileNotFoundException ex) { System.out.println("Error"); } } public static class Product { private String name; private double price; public Product(String n, double p) { name = n; price = p; } @Override public String toString() { return price + " " + name; } } }
UTF-8
Java
2,119
java
_09_ListOfProducts.java
Java
[]
null
[]
import java.io.File; import java.util.List; import java.util.Scanner; import java.util.ArrayList; import java.io.IOException; import java.util.Comparator; import java.util.Collections; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; public class _09_ListOfProducts { public static void main(String[] args) { String inputFileName = "src/_09_Input.txt"; String outputFileName = "src/_09_Output.txt"; try { File textFile = new File(inputFileName); Scanner scan = new Scanner(textFile); List<Product> products = new ArrayList<>(); while (scan.hasNext()) { String[] currentProduct = scan.nextLine().split(" "); String name = currentProduct[0]; double price = Double.parseDouble(currentProduct[1]); products.add(new Product(name, price)); } Collections.sort(products, Comparator.comparing(p -> p.price)); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFileName), "utf-8")); for (Product product : products) { writer.write(product.toString() + "\n"); } } catch (IOException ex) { System.out.println("Error"); } finally { try {writer.close();} catch (IOException ex) {System.out.println("Error");} } } catch (FileNotFoundException ex) { System.out.println("Error"); } } public static class Product { private String name; private double price; public Product(String n, double p) { name = n; price = p; } @Override public String toString() { return price + " " + name; } } }
2,119
0.534686
0.530439
70
29.285715
22.416922
115
false
false
0
0
0
0
0
0
0.528571
false
false
12
21ab83c37cf25ea8a56f0c40a3f158e319d0c6e0
31,834,297,598,571
f334aa64a95ee805e95776c4fa93cc438d892a5a
/src/main/java/org/cinc/minibot/vc/screen/eventbattle/EventBattleInBattleBossScreen.java
fea527a4b219573f780ffad2bfa89833f4607e39
[]
no_license
cinc07/minibot
https://github.com/cinc07/minibot
3edf52f5d38262fc39e0d39098e93876cf60452b
5aae5e35fe91989bd7ed11e3420851b2644a78d0
refs/heads/master
2018-02-08T03:58:59.818000
2017-09-11T14:28:18
2017-09-11T14:28:18
96,374,241
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.cinc.minibot.vc.screen.eventbattle; import java.awt.AWTException; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.cinc.minibot.screen.ImageUtils; import org.cinc.minibot.vc.AbstractGameScreen; import org.cinc.minibot.vc.ActionList; import org.cinc.minibot.vc.FeatureList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EventBattleInBattleBossScreen extends AbstractGameScreen { private static Logger LOG = LoggerFactory.getLogger(EventBattleInBattleBossScreen.class); protected int skillUnleashedIndex = -1; public EventBattleInBattleBossScreen() throws IOException { positiveSample = ImageIO.read(new File("screenshots/Event_Battle/Event_Battle_in_Battle_Boss.png")); positiveFeatureList.add(FeatureList.eventBattleBossInBattleFlag1); positiveFeatureList.add(FeatureList.eventBattleBossInBattleFlag2); } public boolean match(BufferedImage screenShot) { boolean screenMatch = super.match(screenShot); skillUnleashedIndex = -1; if (screenMatch) { // Check unleash skills Rectangle skillUnleashR_sample = FeatureList.eventBattleBossSkillUnleashedList.get(2).getPosition(); BufferedImage skillUnleashImage_sample = positiveSample.getSubimage(skillUnleashR_sample.x, skillUnleashR_sample.y, skillUnleashR_sample.width, skillUnleashR_sample.height); for (int i=0; i<4; i++) { // ignore position 4 for now (SLIME) Rectangle skillUnleashedR_screen = FeatureList.eventBattleBossSkillUnleashedList.get(i).getPosition(); BufferedImage skillUnleashImage_screen = screenShot.getSubimage(skillUnleashedR_screen.x, skillUnleashedR_screen.y, skillUnleashedR_screen.width, skillUnleashedR_screen.height); try { ImageUtils.writeImageToFile(skillUnleashImage_sample, "screenshots/features/sample.jpg"); ImageUtils.writeImageToFile(skillUnleashImage_screen, "screenshots/features/" + i + ".jpg"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ImageUtils.isSimularYellow(skillUnleashImage_sample, skillUnleashImage_screen)) { skillUnleashedIndex = i; LOG.info("Skill unleashed at position " + i); break; } } } return screenMatch; } public void performDefaultAction() throws AWTException { if (skillUnleashedIndex != -1) { LOG.info("Unleash skill at position " + skillUnleashedIndex); performMouseLongClick(FeatureList.eventBattleBossSkillUnleashedList.get(skillUnleashedIndex).getPosition()); } else { performMouseShortClick(ActionList.eventBattleBossInBattleBoss); } sleep(3); } @Override public String getName() { return "Event Battle in Battle Boss Screen"; } }
UTF-8
Java
2,852
java
EventBattleInBattleBossScreen.java
Java
[]
null
[]
package org.cinc.minibot.vc.screen.eventbattle; import java.awt.AWTException; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.cinc.minibot.screen.ImageUtils; import org.cinc.minibot.vc.AbstractGameScreen; import org.cinc.minibot.vc.ActionList; import org.cinc.minibot.vc.FeatureList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EventBattleInBattleBossScreen extends AbstractGameScreen { private static Logger LOG = LoggerFactory.getLogger(EventBattleInBattleBossScreen.class); protected int skillUnleashedIndex = -1; public EventBattleInBattleBossScreen() throws IOException { positiveSample = ImageIO.read(new File("screenshots/Event_Battle/Event_Battle_in_Battle_Boss.png")); positiveFeatureList.add(FeatureList.eventBattleBossInBattleFlag1); positiveFeatureList.add(FeatureList.eventBattleBossInBattleFlag2); } public boolean match(BufferedImage screenShot) { boolean screenMatch = super.match(screenShot); skillUnleashedIndex = -1; if (screenMatch) { // Check unleash skills Rectangle skillUnleashR_sample = FeatureList.eventBattleBossSkillUnleashedList.get(2).getPosition(); BufferedImage skillUnleashImage_sample = positiveSample.getSubimage(skillUnleashR_sample.x, skillUnleashR_sample.y, skillUnleashR_sample.width, skillUnleashR_sample.height); for (int i=0; i<4; i++) { // ignore position 4 for now (SLIME) Rectangle skillUnleashedR_screen = FeatureList.eventBattleBossSkillUnleashedList.get(i).getPosition(); BufferedImage skillUnleashImage_screen = screenShot.getSubimage(skillUnleashedR_screen.x, skillUnleashedR_screen.y, skillUnleashedR_screen.width, skillUnleashedR_screen.height); try { ImageUtils.writeImageToFile(skillUnleashImage_sample, "screenshots/features/sample.jpg"); ImageUtils.writeImageToFile(skillUnleashImage_screen, "screenshots/features/" + i + ".jpg"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ImageUtils.isSimularYellow(skillUnleashImage_sample, skillUnleashImage_screen)) { skillUnleashedIndex = i; LOG.info("Skill unleashed at position " + i); break; } } } return screenMatch; } public void performDefaultAction() throws AWTException { if (skillUnleashedIndex != -1) { LOG.info("Unleash skill at position " + skillUnleashedIndex); performMouseLongClick(FeatureList.eventBattleBossSkillUnleashedList.get(skillUnleashedIndex).getPosition()); } else { performMouseShortClick(ActionList.eventBattleBossInBattleBoss); } sleep(3); } @Override public String getName() { return "Event Battle in Battle Boss Screen"; } }
2,852
0.754558
0.750351
76
35.526318
38.95121
181
false
false
0
0
0
0
0
0
2.381579
false
false
12
92208a0028aa40259738b3e6b9f7a3716bdbc7b9
618,475,321,886
9ee0ceb0b7d4cd3a8f6b029471688a4b385ed86b
/src/bookStore/customer.java
fdc8c2a04a8a905dc637c28bcaac24a3423bf540
[]
no_license
huanchang/bookStore
https://github.com/huanchang/bookStore
833467a129beecda1df8f64ac80de8eeeab35f0e
edb4b4d1523385bb68d43694c0f9c4337a86cfb0
refs/heads/master
2021-01-10T18:46:55.378000
2015-03-26T02:23:27
2015-03-26T02:23:27
32,902,932
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bookStore; import java.io.PrintWriter ; public class customer { // customer class implementation private int id; private String email; private String password; private String firstName; private String lastName; private Address address; private double balance; // Interface customer(){ id = 0; email = new String( "" ); password = new String( "" ); firstName = new String( "" ); lastName = new String( "" ); address = new Address(); balance = 0.0; } customer( int ID, String EMAIL, String PWD, String fName, String lName, Address add){ id = ID; email = EMAIL; password = PWD; firstName = fName; lastName = lName; address = add; balance = 0.0; } public boolean verify( String pwd ){ // verify customer password if( pwd.equals( password ) ){ return true; } else{ return false; } } public void print(){ System.out.println( "Customer Info" ); System.out.println( "Customer ID: " + id ); System.out.println( "Customer Email: " + email ); System.out.println( "Customer name: " + firstName + " " + lastName ); address.print(); System.out.println( "Customer balance: " + balance ); } public void print( PrintWriter out ){ out.println( "Customer Info" ); out.println( "Customer ID: " + id ); out.println( "Customer Email: " + email ); out.println( "Customer name: " + firstName + " " + lastName ); address.print( out ); out.println( "Customer balance: " + balance ); } }
UTF-8
Java
1,473
java
customer.java
Java
[ { "context": "g email;\n\tprivate String password;\n\tprivate String firstName;\n\tprivate String lastName;\n\tprivate Address addre", "end": 199, "score": 0.5293595194816589, "start": 190, "tag": "NAME", "value": "firstName" }, { "context": "ess add){\n\t\tid = ID;\n\t\temail = EMAIL;\n\t\tpassword = PWD;\n\t\tfirstName = fName;\n\t\tlastName = lName;\n\t\taddre", "end": 619, "score": 0.9715853333473206, "start": 616, "tag": "PASSWORD", "value": "PWD" }, { "context": ";\n\t\temail = EMAIL;\n\t\tpassword = PWD;\n\t\tfirstName = fName;\n\t\tlastName = lName;\n\t\taddress = add;\n\t\tbalance =", "end": 640, "score": 0.8829237222671509, "start": 635, "tag": "NAME", "value": "fName" }, { "context": "\tpassword = PWD;\n\t\tfirstName = fName;\n\t\tlastName = lName;\n\t\taddress = add;\n\t\tbalance = 0.0;\n\t}\n\t\n\tpubl", "end": 656, "score": 0.8774132132530212, "start": 655, "tag": "NAME", "value": "l" }, { "context": "email );\n\t\tSystem.out.println( \"Customer name: \" + firstName + \" \" + lastName );\n\t\taddress.print();\n\t\tSystem.o", "end": 1069, "score": 0.9983276724815369, "start": 1060, "tag": "NAME", "value": "firstName" }, { "context": "out.println( \"Customer name: \" + firstName + \" \" + lastName );\n\t\taddress.print();\n\t\tSystem.out.println( \"Cust", "end": 1086, "score": 0.9975500702857971, "start": 1078, "tag": "NAME", "value": "lastName" }, { "context": "l: \" + email );\n\t\tout.println( \"Customer name: \" + firstName + \" \" + lastName );\n\t\taddress.print( out );\n\t\tout", "end": 1372, "score": 0.998524010181427, "start": 1363, "tag": "NAME", "value": "firstName" }, { "context": "out.println( \"Customer name: \" + firstName + \" \" + lastName );\n\t\taddress.print( out );\n\t\tout.println( \"Custom", "end": 1389, "score": 0.9973732233047485, "start": 1381, "tag": "NAME", "value": "lastName" } ]
null
[]
package bookStore; import java.io.PrintWriter ; public class customer { // customer class implementation private int id; private String email; private String password; private String firstName; private String lastName; private Address address; private double balance; // Interface customer(){ id = 0; email = new String( "" ); password = new String( "" ); firstName = new String( "" ); lastName = new String( "" ); address = new Address(); balance = 0.0; } customer( int ID, String EMAIL, String PWD, String fName, String lName, Address add){ id = ID; email = EMAIL; password = PWD; firstName = fName; lastName = lName; address = add; balance = 0.0; } public boolean verify( String pwd ){ // verify customer password if( pwd.equals( password ) ){ return true; } else{ return false; } } public void print(){ System.out.println( "Customer Info" ); System.out.println( "Customer ID: " + id ); System.out.println( "Customer Email: " + email ); System.out.println( "Customer name: " + firstName + " " + lastName ); address.print(); System.out.println( "Customer balance: " + balance ); } public void print( PrintWriter out ){ out.println( "Customer Info" ); out.println( "Customer ID: " + id ); out.println( "Customer Email: " + email ); out.println( "Customer name: " + firstName + " " + lastName ); address.print( out ); out.println( "Customer balance: " + balance ); } }
1,473
0.644263
0.640869
64
22.015625
18.300011
86
false
false
0
0
0
0
0
0
2.140625
false
false
12
9d215198ce0c04374a4e1bf5c0a3c8d42aa3f024
24,137,716,209,239
bb21a16a2bb0d738b693d9454af74c8636bf65a4
/talend-component-kit-intellij-plugin/src/main/java/org/talend/sdk/component/intellij/module/TalendModuleBuilder.java
f9cdf7b47bbdcf122febb288f5775af6af91147e
[ "Apache-2.0" ]
permissive
Talend/component-runtime
https://github.com/Talend/component-runtime
81a25d7c92a1f91e26239211994c49469ead9c3b
44aef3944f2d6059b325496612ddf112caeabd63
refs/heads/master
2023-08-31T21:40:26.513000
2023-08-30T03:01:56
2023-08-30T03:01:56
107,511,723
28
51
Apache-2.0
false
2023-09-14T19:37:05
2017-10-19T07:19:24
2023-09-06T01:26:28
2023-09-14T19:37:05
613,422
28
36
23
Java
false
false
/** * Copyright (C) 2006-2023 Talend Inc. - www.talend.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 org.talend.sdk.component.intellij.module; import static com.intellij.openapi.application.ApplicationManager.getApplication; import static com.intellij.openapi.components.ServiceManager.getService; import static com.intellij.openapi.module.StdModuleTypes.JAVA; import static java.util.Collections.singletonList; import static org.talend.sdk.component.intellij.Configuration.getMessage; import static org.talend.sdk.component.intellij.util.FileUtil.findFileUnderRootInModule; import java.io.IOException; import java.util.Base64; import javax.swing.Icon; import javax.swing.JTextField; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.intellij.ide.util.newProjectWizard.AddModuleWizard; import com.intellij.ide.util.projectWizard.JavaModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.SettingsStep; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.externalSystem.service.project.ProjectDataManager; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleWithNameAlreadyExists; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.vfs.VirtualFile; import org.jdom.JDOMException; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportBuilder; import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportProvider; import org.talend.sdk.component.intellij.module.step.StarterStep; import org.talend.sdk.component.intellij.module.step.WelcomeStep; public class TalendModuleBuilder extends JavaModuleBuilder { private final ModuleType moduleType; private ProjectCreationRequest request = null; private Gson gson = new Gson(); private JsonObject jsonProject; public TalendModuleBuilder(final ModuleType moduleType) { this.moduleType = moduleType; } @Override protected boolean isAvailable() { return true; } @Override public ModuleWizardStep[] createWizardSteps(final WizardContext wizardContext, final ModulesProvider modulesProvider) { return new ModuleWizardStep[] { new StarterStep(this) }; } @Override public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) { return new WelcomeStep(context, parentDisposable); } @Override public ModuleType getModuleType() { return JAVA; } @Override public Icon getNodeIcon() { return moduleType.getIcon(); } @Override public String getPresentableName() { return moduleType.getName(); } @Override public String getParentGroup() { return "Build Tools"; } @Override public String getBuilderId() { return "talend/component"; } @Override public String getDescription() { return moduleType.getDescription(); } @Override public Module createModule(final ModifiableModuleModel moduleModel) throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, ConfigurationException, JDOMException { final Module module = super.createModule(moduleModel); getApplication().invokeLater(() -> { ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { final ProjectDownloader downloader = new ProjectDownloader(this, request); try { downloader.download(ProgressManager.getInstance().getProgressIndicator()); } catch (IOException e) { getApplication() .invokeLater(() -> MessagesEx .showErrorDialog(e.getMessage(), getMessage("download.project.file.error"))); } }, getMessage("download.project.file"), true, null); final Project moduleProject = module.getProject(); switch (jsonProject.get("buildType").getAsString()) { case "Maven": final VirtualFile pomFile = findFileUnderRootInModule(module, "pom.xml"); if (pomFile != null) { final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(moduleProject); mavenProjectsManager.addManagedFiles(singletonList(pomFile)); } break; case "Gradle": final VirtualFile gradleFile = findFileUnderRootInModule(module, "build.gradle"); if (gradleFile != null) { final ProjectDataManager projectDataManager = getService(ProjectDataManager.class); // todo: move to JavaGradleProjectImportBuilder final GradleProjectImportBuilder importBuilder = new GradleProjectImportBuilder(projectDataManager); final GradleProjectImportProvider importProvider = new GradleProjectImportProvider(importBuilder); final AddModuleWizard addModuleWizard = new AddModuleWizard(moduleProject, gradleFile.getPath(), importProvider); if (addModuleWizard.getStepCount() == 0 && addModuleWizard.showAndGet()) { // user chose to import via the gradle import prompt importBuilder.commit(moduleProject, null, null); } } break; default: break; } }, ModalityState.current()); return module; } @Override public ModuleWizardStep modifySettingsStep(final SettingsStep settingsStep) { final String projectJsonString = new String(Base64.getUrlDecoder().decode(request.getProject())); jsonProject = gson.fromJson(projectJsonString, JsonObject.class); try { final Object moduleNameLocationSettings = settingsStep.getClass().getMethod("getModuleNameLocationSettings").invoke(settingsStep); if (moduleNameLocationSettings != null) { moduleNameLocationSettings .getClass() .getMethod("setModuleName", String.class) .invoke(moduleNameLocationSettings, jsonProject.get("artifact").getAsString()); } } catch (final Error | Exception e) { try { final JTextField namedFile = settingsStep.getModuleNameField(); if (namedFile != null) { namedFile.setText(jsonProject.get("artifact").getAsString()); namedFile.setEditable(false); } } catch (final RuntimeException ex) { final IllegalStateException exception = new IllegalStateException(e); exception.addSuppressed(ex); throw exception; } } return super.modifySettingsStep(settingsStep); } public void updateQuery(final ProjectCreationRequest q) { this.request = q; } }
UTF-8
Java
8,276
java
TalendModuleBuilder.java
Java
[]
null
[]
/** * Copyright (C) 2006-2023 Talend Inc. - www.talend.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 org.talend.sdk.component.intellij.module; import static com.intellij.openapi.application.ApplicationManager.getApplication; import static com.intellij.openapi.components.ServiceManager.getService; import static com.intellij.openapi.module.StdModuleTypes.JAVA; import static java.util.Collections.singletonList; import static org.talend.sdk.component.intellij.Configuration.getMessage; import static org.talend.sdk.component.intellij.util.FileUtil.findFileUnderRootInModule; import java.io.IOException; import java.util.Base64; import javax.swing.Icon; import javax.swing.JTextField; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.intellij.ide.util.newProjectWizard.AddModuleWizard; import com.intellij.ide.util.projectWizard.JavaModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.SettingsStep; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.externalSystem.service.project.ProjectDataManager; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleWithNameAlreadyExists; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.ui.ex.MessagesEx; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.vfs.VirtualFile; import org.jdom.JDOMException; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportBuilder; import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportProvider; import org.talend.sdk.component.intellij.module.step.StarterStep; import org.talend.sdk.component.intellij.module.step.WelcomeStep; public class TalendModuleBuilder extends JavaModuleBuilder { private final ModuleType moduleType; private ProjectCreationRequest request = null; private Gson gson = new Gson(); private JsonObject jsonProject; public TalendModuleBuilder(final ModuleType moduleType) { this.moduleType = moduleType; } @Override protected boolean isAvailable() { return true; } @Override public ModuleWizardStep[] createWizardSteps(final WizardContext wizardContext, final ModulesProvider modulesProvider) { return new ModuleWizardStep[] { new StarterStep(this) }; } @Override public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) { return new WelcomeStep(context, parentDisposable); } @Override public ModuleType getModuleType() { return JAVA; } @Override public Icon getNodeIcon() { return moduleType.getIcon(); } @Override public String getPresentableName() { return moduleType.getName(); } @Override public String getParentGroup() { return "Build Tools"; } @Override public String getBuilderId() { return "talend/component"; } @Override public String getDescription() { return moduleType.getDescription(); } @Override public Module createModule(final ModifiableModuleModel moduleModel) throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, ConfigurationException, JDOMException { final Module module = super.createModule(moduleModel); getApplication().invokeLater(() -> { ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { final ProjectDownloader downloader = new ProjectDownloader(this, request); try { downloader.download(ProgressManager.getInstance().getProgressIndicator()); } catch (IOException e) { getApplication() .invokeLater(() -> MessagesEx .showErrorDialog(e.getMessage(), getMessage("download.project.file.error"))); } }, getMessage("download.project.file"), true, null); final Project moduleProject = module.getProject(); switch (jsonProject.get("buildType").getAsString()) { case "Maven": final VirtualFile pomFile = findFileUnderRootInModule(module, "pom.xml"); if (pomFile != null) { final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(moduleProject); mavenProjectsManager.addManagedFiles(singletonList(pomFile)); } break; case "Gradle": final VirtualFile gradleFile = findFileUnderRootInModule(module, "build.gradle"); if (gradleFile != null) { final ProjectDataManager projectDataManager = getService(ProjectDataManager.class); // todo: move to JavaGradleProjectImportBuilder final GradleProjectImportBuilder importBuilder = new GradleProjectImportBuilder(projectDataManager); final GradleProjectImportProvider importProvider = new GradleProjectImportProvider(importBuilder); final AddModuleWizard addModuleWizard = new AddModuleWizard(moduleProject, gradleFile.getPath(), importProvider); if (addModuleWizard.getStepCount() == 0 && addModuleWizard.showAndGet()) { // user chose to import via the gradle import prompt importBuilder.commit(moduleProject, null, null); } } break; default: break; } }, ModalityState.current()); return module; } @Override public ModuleWizardStep modifySettingsStep(final SettingsStep settingsStep) { final String projectJsonString = new String(Base64.getUrlDecoder().decode(request.getProject())); jsonProject = gson.fromJson(projectJsonString, JsonObject.class); try { final Object moduleNameLocationSettings = settingsStep.getClass().getMethod("getModuleNameLocationSettings").invoke(settingsStep); if (moduleNameLocationSettings != null) { moduleNameLocationSettings .getClass() .getMethod("setModuleName", String.class) .invoke(moduleNameLocationSettings, jsonProject.get("artifact").getAsString()); } } catch (final Error | Exception e) { try { final JTextField namedFile = settingsStep.getModuleNameField(); if (namedFile != null) { namedFile.setText(jsonProject.get("artifact").getAsString()); namedFile.setEditable(false); } } catch (final RuntimeException ex) { final IllegalStateException exception = new IllegalStateException(e); exception.addSuppressed(ex); throw exception; } } return super.modifySettingsStep(settingsStep); } public void updateQuery(final ProjectCreationRequest q) { this.request = q; } }
8,276
0.683543
0.681489
203
39.768475
31.965662
120
false
false
0
0
0
0
0
0
0.551724
false
false
12
5afcc1011064625f9e7b47558440646a6ba432b3
21,019,569,985,375
17840e69c9ef2e66a37b396fb96c18221b364aab
/src/observer/test/NBAObserver.java
674ebfe2927a3bda92e06c3629c851bf71b77169
[]
no_license
YBill/EventDelegate
https://github.com/YBill/EventDelegate
587f18782758848350bf2f6bbed83a33501b574d
51f4eaf7d94267ac3fda0b50bac73e0aa0d93294
refs/heads/master
2021-01-15T12:43:57.313000
2017-08-08T09:58:57
2017-08-08T09:58:57
99,657,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package observer.test; import observer.Observer; import observer.Subject; /** * Created by Bill on 2017/8/8. */ public class NBAObserver implements Observer { @Override public void update(Subject subject, Object object) { System.out.println("我是" + this.getClass().getSimpleName() + ", " + object + "别看NBA了"); } }
UTF-8
Java
351
java
NBAObserver.java
Java
[ { "context": "erver;\nimport observer.Subject;\n\n/**\n * Created by Bill on 2017/8/8.\n */\npublic class NBAObserver impleme", "end": 98, "score": 0.9975110292434692, "start": 94, "tag": "NAME", "value": "Bill" } ]
null
[]
package observer.test; import observer.Observer; import observer.Subject; /** * Created by Bill on 2017/8/8. */ public class NBAObserver implements Observer { @Override public void update(Subject subject, Object object) { System.out.println("我是" + this.getClass().getSimpleName() + ", " + object + "别看NBA了"); } }
351
0.672566
0.654867
15
21.6
25.996923
95
false
false
0
0
0
0
0
0
0.333333
false
false
12
fc7aa49d342e53258efe16d434838f6f501262d4
2,422,361,574,145
fc3e74afab3f9369e0ffeb226dad1b4fcc33f283
/src/main/java/com/zeroized/spider/domain/crawler/CrawlAdvConfig.java
5bdf07b3e0b8ca31f6267157fac27b40ad1c2dae
[ "MIT" ]
permissive
1plwang/Zpider
https://github.com/1plwang/Zpider
aa83461071a3248bbb07ca37df9efe0b37523878
339d2d43f3daa7bba1051a4ba612ccb00a122de5
refs/heads/master
2020-03-21T18:23:49.130000
2018-05-18T13:32:11
2018-05-18T13:32:11
138,889,046
1
0
null
true
2018-06-27T13:57:40
2018-06-27T13:57:40
2018-05-18T13:32:48
2018-05-18T13:32:47
410
0
0
0
null
false
null
package com.zeroized.spider.domain.crawler; /** * Created by Zero on 2018/4/6. */ public class CrawlAdvConfig { private int workers=1; private int maxDepth=10; private int maxPage=1000; private int politeWait=1000; public CrawlAdvConfig() { } public int getWorkers() { return workers; } public void setWorkers(int workers) { this.workers = workers; } public int getMaxDepth() { return maxDepth; } public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; } public int getMaxPage() { return maxPage; } public void setMaxPage(int maxPage) { this.maxPage = maxPage; } public int getPoliteWait() { return politeWait; } public void setPoliteWait(int politeWait) { this.politeWait = politeWait; } }
UTF-8
Java
865
java
CrawlAdvConfig.java
Java
[ { "context": "zeroized.spider.domain.crawler;\n\n/**\n * Created by Zero on 2018/4/6.\n */\npublic class CrawlAdvConfig {\n ", "end": 67, "score": 0.92833411693573, "start": 63, "tag": "USERNAME", "value": "Zero" } ]
null
[]
package com.zeroized.spider.domain.crawler; /** * Created by Zero on 2018/4/6. */ public class CrawlAdvConfig { private int workers=1; private int maxDepth=10; private int maxPage=1000; private int politeWait=1000; public CrawlAdvConfig() { } public int getWorkers() { return workers; } public void setWorkers(int workers) { this.workers = workers; } public int getMaxDepth() { return maxDepth; } public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; } public int getMaxPage() { return maxPage; } public void setMaxPage(int maxPage) { this.maxPage = maxPage; } public int getPoliteWait() { return politeWait; } public void setPoliteWait(int politeWait) { this.politeWait = politeWait; } }
865
0.612717
0.593064
46
17.804348
15.600473
47
false
false
0
0
0
0
0
0
0.282609
false
false
12
101e3b03096ea1822312c1c563a795e771d27552
13,451,837,587,069
33cbffaa5011ee2d91bd8bb2cdf70af372c8bbaf
/src/sort/SwapUtils.java
fbcda49a86f01e43c1c5461dbd78d308e732ef17
[]
no_license
CrisZhao/my_java_resource
https://github.com/CrisZhao/my_java_resource
e67950cc09fd852d5081d170918fceb194ea15c8
f34f88bacd1666c58cc7226447d23af0ded4224b
refs/heads/master
2022-05-28T09:03:17.709000
2019-10-15T06:12:47
2019-10-15T06:12:47
8,744,271
0
1
null
false
2022-05-20T20:50:48
2013-03-13T03:33:56
2019-10-15T06:12:50
2022-05-20T20:50:48
742
0
1
2
Java
false
false
package sort; import java.util.Arrays; import org.junit.Test; public class SwapUtils { public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } @Test public void test() { int[] array = new int[] {4,2,6,3,6,8,2}; // sort(array); System.out.println(Arrays.toString(array)); } }
UTF-8
Java
353
java
SwapUtils.java
Java
[]
null
[]
package sort; import java.util.Arrays; import org.junit.Test; public class SwapUtils { public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } @Test public void test() { int[] array = new int[] {4,2,6,3,6,8,2}; // sort(array); System.out.println(Arrays.toString(array)); } }
353
0.631728
0.611898
19
17.578947
15.682091
54
false
false
0
0
0
0
0
0
1.789474
false
false
12
5e8422f560651b889765277b5977cd1eb3ec2d10
7,962,869,375,251
462cd1112ffd84f410214ca6361a8d0489ee46d4
/src/main/java/org/training/issuetracker/utils/SearchFilter.java
e2db5e2fd2c1abf578d6c4a624c955f4e09b7a6d
[]
no_license
sergei-doroshenko/it-spring
https://github.com/sergei-doroshenko/it-spring
3b61e8abb32be7b3185cfc0d1c04488b56ff78bd
2e1a5c466b1ec93d5df3fdca06aab5d574606dec
refs/heads/spring
2023-03-06T06:54:47.587000
2022-04-02T09:37:08
2022-04-02T09:37:08
19,462,221
0
0
null
false
2023-02-22T07:07:42
2014-05-05T16:15:17
2022-04-02T09:36:19
2023-02-22T07:07:40
2,158
0
0
7
JavaScript
false
false
package org.training.issuetracker.utils; import java.util.List; public class SearchFilter { private String groupOp; private List<SearchRule> rules; public SearchFilter() { } public SearchFilter(String groupOp, List<SearchRule> rules) { super(); this.groupOp = groupOp; this.rules = rules; } public String getGroupOp() { return groupOp; } public void setGroupOp(String groupOp) { this.groupOp = groupOp; } public List<SearchRule> getRules() { return rules; } public void setRules(List<SearchRule> rules) { this.rules = rules; } @Override public String toString() { return "SearchFilter [groupOp=" + groupOp + ", rules=" + rules + "]"; } public enum GroupOp {AND, OR} //filters:{"groupOp":"AND", }
UTF-8
Java
745
java
SearchFilter.java
Java
[]
null
[]
package org.training.issuetracker.utils; import java.util.List; public class SearchFilter { private String groupOp; private List<SearchRule> rules; public SearchFilter() { } public SearchFilter(String groupOp, List<SearchRule> rules) { super(); this.groupOp = groupOp; this.rules = rules; } public String getGroupOp() { return groupOp; } public void setGroupOp(String groupOp) { this.groupOp = groupOp; } public List<SearchRule> getRules() { return rules; } public void setRules(List<SearchRule> rules) { this.rules = rules; } @Override public String toString() { return "SearchFilter [groupOp=" + groupOp + ", rules=" + rules + "]"; } public enum GroupOp {AND, OR} //filters:{"groupOp":"AND", }
745
0.687248
0.687248
42
16.738094
17.990818
71
false
false
0
0
0
0
0
0
1.261905
false
false
12
21bdd07d14361afc36edcae42dffa24463c47ec9
2,113,123,925,133
f925e85cfafbfac07195143f6273887eb595a13c
/src/main/java/Stack/CheckPairWiseOrder.java
cde3cbba8711f3c9a96f185d3f14202b1fbd63c1
[]
no_license
etclassic/DS
https://github.com/etclassic/DS
138b8867f8cf80245a6aa1cd3ccaca51a826ae7c
70183588e5d0c767b7f1ac8b096538a5f5ff8efa
refs/heads/main
2023-06-13T00:36:20.992000
2021-07-05T20:13:52
2021-07-05T20:13:52
378,211,739
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Stack; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class CheckPairWiseOrder { public boolean pairWiseConsecutive(Stack<Integer> integerStack){ Queue<Integer> queue = new LinkedList<>(); while( !integerStack.isEmpty()){ queue.add(integerStack.pop()); } while (!queue.isEmpty()){ integerStack.push(queue.poll()); } while (integerStack.size() > 1){ int x_1 = integerStack.pop(); int x_2 = integerStack.pop(); if(Math.abs(x_1 - x_2) != 1){ return false; } queue.add(x_1); queue.add(x_2); } if(integerStack.size() == 1){ queue.add(integerStack.pop()); } while(!queue.isEmpty()){ integerStack.push(queue.poll()); } return true; } }
UTF-8
Java
927
java
CheckPairWiseOrder.java
Java
[]
null
[]
package Stack; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class CheckPairWiseOrder { public boolean pairWiseConsecutive(Stack<Integer> integerStack){ Queue<Integer> queue = new LinkedList<>(); while( !integerStack.isEmpty()){ queue.add(integerStack.pop()); } while (!queue.isEmpty()){ integerStack.push(queue.poll()); } while (integerStack.size() > 1){ int x_1 = integerStack.pop(); int x_2 = integerStack.pop(); if(Math.abs(x_1 - x_2) != 1){ return false; } queue.add(x_1); queue.add(x_2); } if(integerStack.size() == 1){ queue.add(integerStack.pop()); } while(!queue.isEmpty()){ integerStack.push(queue.poll()); } return true; } }
927
0.516721
0.507012
44
20.068182
18.435881
68
false
false
0
0
0
0
0
0
0.340909
false
false
12
408b09d4ef01bcf7262f23bf606feba283c63914
28,398,323,790,931
fb8351d424cfd88f3be4ef5dbcdf6fea4419e3e5
/src/main/java/v1/Model/AuthURL.java
1314a52d8b6d377bc6ff217c26e547cba1354ea7
[]
no_license
albertogiunta/server_dia
https://github.com/albertogiunta/server_dia
d118fcb0a5bb5f75b266a2f4de419767748ff60c
a371d36e7e780b1dabc93a2866c49f78fc2691a4
refs/heads/master
2016-09-16T17:06:04.097000
2016-07-12T14:29:24
2016-07-12T14:29:24
61,545,732
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package v1.Model; /** * Created by lisamazzini on 29/06/16. */ public class AuthURL { private String url; public AuthURL(String url) { this.url = url; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
UTF-8
Java
304
java
AuthURL.java
Java
[ { "context": "package v1.Model;\n\n/**\n * Created by lisamazzini on 29/06/16.\n */\npublic class AuthURL {\n\n priv", "end": 48, "score": 0.999255359172821, "start": 37, "tag": "USERNAME", "value": "lisamazzini" } ]
null
[]
package v1.Model; /** * Created by lisamazzini on 29/06/16. */ public class AuthURL { private String url; public AuthURL(String url) { this.url = url; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
304
0.559211
0.536184
21
13.476191
13.000436
38
false
false
0
0
0
0
0
0
0.238095
false
false
12
4ef21a423987393e7e3482ed9b3f69a4b6e207e2
28,252,294,918,558
0f80712325236818835928e81918a1f2a5f9f190
/src/main/java/com/company/hrm/action/EmpDeleteServlet.java
5bb91650f3e6988c98cb39aa0362d88cc68054ac
[ "Apache-2.0" ]
permissive
dinganan/hrm2
https://github.com/dinganan/hrm2
bd265426fed3a4904d5890f15ad6131fb44c52b8
fa218e110c2a0a3b11bcfd1cc6eb293af4e2f048
refs/heads/master
2020-04-24T03:24:58.508000
2019-02-21T07:18:05
2019-02-21T07:20:23
171,669,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.hrm.action; import java.io.IOException; 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 javax.servlet.http.HttpSession; import com.company.hrm.common.DaoConst; import com.company.hrm.common.ErrMsg; import com.company.hrm.common.ServiceConst; import com.company.hrm.common.SpringIOC; import com.company.hrm.dao.pojo.Emp; import com.company.hrm.service.iService.IEmpService; @WebServlet("/EmpDeleteServlet") public class EmpDeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int empno = Integer.parseInt(request.getParameter("empno")); IEmpService empservice = (IEmpService) SpringIOC.getCtx().getBean("empService"); Emp emp = (Emp) SpringIOC.getCtx().getBean("emp"); emp.setEmpno(empno); empservice.delete(emp); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int empno = Integer.parseInt(request.getParameter("empno")); Emp emp = new Emp(); emp.setEmpno(empno); IEmpService empservice = (IEmpService) SpringIOC.getCtx().getBean("empService"); String msg = empservice.delete(emp); if (msg.indexOf(ServiceConst.SUCCESS) != -1) { response.sendRedirect(request.getContextPath()+"/EmpFindAllServlet"); }else { HttpSession session = request.getSession(); session.setAttribute("errmsg", ErrMsg.empErr.DELETE_ERROR); response.sendRedirect(request.getContextPath()+"/error.jsp"); } } }
UTF-8
Java
1,745
java
EmpDeleteServlet.java
Java
[]
null
[]
package com.company.hrm.action; import java.io.IOException; 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 javax.servlet.http.HttpSession; import com.company.hrm.common.DaoConst; import com.company.hrm.common.ErrMsg; import com.company.hrm.common.ServiceConst; import com.company.hrm.common.SpringIOC; import com.company.hrm.dao.pojo.Emp; import com.company.hrm.service.iService.IEmpService; @WebServlet("/EmpDeleteServlet") public class EmpDeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int empno = Integer.parseInt(request.getParameter("empno")); IEmpService empservice = (IEmpService) SpringIOC.getCtx().getBean("empService"); Emp emp = (Emp) SpringIOC.getCtx().getBean("emp"); emp.setEmpno(empno); empservice.delete(emp); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int empno = Integer.parseInt(request.getParameter("empno")); Emp emp = new Emp(); emp.setEmpno(empno); IEmpService empservice = (IEmpService) SpringIOC.getCtx().getBean("empService"); String msg = empservice.delete(emp); if (msg.indexOf(ServiceConst.SUCCESS) != -1) { response.sendRedirect(request.getContextPath()+"/EmpFindAllServlet"); }else { HttpSession session = request.getSession(); session.setAttribute("errmsg", ErrMsg.empErr.DELETE_ERROR); response.sendRedirect(request.getContextPath()+"/error.jsp"); } } }
1,745
0.783954
0.782808
45
37.777779
28.768724
119
false
false
0
0
0
0
0
0
1.711111
false
false
12
efd0d618d4e52348bc159b8b6385b798742ce54d
13,091,060,383,502
fdc8ed591bfc630de895a0488e78eef084d12d46
/app/src/main/java/pollub/edu/pl/kolokwium1/MessageDatabase/MessageDatabaseHelper.java
c08bd26c31896c83f26edd8d614495d6a259da71
[]
no_license
Jarek0/SimpleAndroidProject
https://github.com/Jarek0/SimpleAndroidProject
90ac8a287a5c06998717bb5282c45ad3e397e5a7
b068b9e50538d99731c4d3afe8e80921b0346743
refs/heads/master
2021-01-21T15:33:55.291000
2017-05-19T22:31:18
2017-05-19T22:31:18
91,850,107
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pollub.edu.pl.kolokwium1.MessageDatabase; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Dell on 2017-05-18. */ public class MessageDatabaseHelper extends SQLiteOpenHelper { public final static int DB_VERSION = 1; public final static String DB_NAME = "chat_db"; public final static String TABLE_NAME = "messages"; public final static String ID = "_id"; public final static String CONTENT_COLUMN_NAME = "content"; public final static String USER_COLUMN_NAME = "user"; public final static String TIME_COLUMN_NAME = "time"; public final static String ONLY_FOR_ADULT_COLUMN_NAME = "only_for_adult"; public final static String TABLE_CREATING_SCRIPT = "CREATE TABLE " + TABLE_NAME + "("+ ID +" integer primary key autoincrement, " + CONTENT_COLUMN_NAME +" text not null,"+ USER_COLUMN_NAME+" text not null,"+ TIME_COLUMN_NAME+" text not null,"+ ONLY_FOR_ADULT_COLUMN_NAME+" text not null);"; private static final String TABLE_DELETING_SCRIPT = "DROP TABLE IF EXISTS "+TABLE_NAME; public MessageDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATING_SCRIPT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
UTF-8
Java
1,511
java
MessageDatabaseHelper.java
Java
[ { "context": "tabase.sqlite.SQLiteOpenHelper;\n\n/**\n * Created by Dell on 2017-05-18.\n */\n\npublic class MessageDatabaseH", "end": 202, "score": 0.9741140604019165, "start": 198, "tag": "NAME", "value": "Dell" } ]
null
[]
package pollub.edu.pl.kolokwium1.MessageDatabase; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Dell on 2017-05-18. */ public class MessageDatabaseHelper extends SQLiteOpenHelper { public final static int DB_VERSION = 1; public final static String DB_NAME = "chat_db"; public final static String TABLE_NAME = "messages"; public final static String ID = "_id"; public final static String CONTENT_COLUMN_NAME = "content"; public final static String USER_COLUMN_NAME = "user"; public final static String TIME_COLUMN_NAME = "time"; public final static String ONLY_FOR_ADULT_COLUMN_NAME = "only_for_adult"; public final static String TABLE_CREATING_SCRIPT = "CREATE TABLE " + TABLE_NAME + "("+ ID +" integer primary key autoincrement, " + CONTENT_COLUMN_NAME +" text not null,"+ USER_COLUMN_NAME+" text not null,"+ TIME_COLUMN_NAME+" text not null,"+ ONLY_FOR_ADULT_COLUMN_NAME+" text not null);"; private static final String TABLE_DELETING_SCRIPT = "DROP TABLE IF EXISTS "+TABLE_NAME; public MessageDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATING_SCRIPT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
1,511
0.684977
0.678359
43
34.162792
27.823305
91
false
false
0
0
0
0
0
0
0.604651
false
false
12
6279dbade12e8895f96863267d3d1428c76e2cb6
3,195,455,689,839
87f58d7794cc70582922cb07cacfb4ce90777988
/src/com/company/Autoridades.java
93ea17768d52d1e398c287ef54338dd1441e453c
[]
no_license
JuanSolis/TorneoPalatino
https://github.com/JuanSolis/TorneoPalatino
86e09b43a461ebc80a527a3f6de4e693e5f19c9b
758848c7957248da319f5ecf85baa412065d897a
refs/heads/master
2020-07-10T09:04:26.990000
2019-08-25T00:17:31
2019-08-25T00:17:31
204,226,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.ArrayList; import java.util.Scanner; public class Autoridades { private int cantidadEquipos; public Autoridades(){ System.out.println("*------------Ingreso de Datos---------*"); ingresoDeDatos(); } public static ArrayList<Equipo> Equipos = new ArrayList<Equipo>(); public void ingresoDeDatos(){ Scanner sc = new Scanner(System.in); String response = ""; cantidadEquipos = 0; boolean ingresoDatos = true; while(ingresoDatos) { Equipos.add(new Equipo()); System.out.println("Nombre del Equipo"); Equipos.get(Equipos.size()-1).setNombreEquipo(sc.next()); /*System.out.println("Lugar que ocupó " + Equipos.get(Equipos.size()-1).getNombreEquipo().toString() + " en el torneo"); Equipos.get(Equipos.size()-1).setLugarOcupadoTorneo(sc.next());*/ System.out.println("Cantidad de tiros de Esquina"); Equipos.get(Equipos.size()-1).setCantidadTirosEsquina(sc.nextInt()); /*System.out.println("Cantidad de Juegos Ganados"); Equipos.get(Equipos.size()-1).setCantidadJuegosGanados(sc.nextInt()); System.out.println("Cantidad de Juegos Perdidos"); Equipos.get(Equipos.size()-1).setCantidadJuegosPerdidos(sc.nextInt()); System.out.println("Cantidad de Tiros a Gol"); Equipos.get(Equipos.size()-1).setCantidadTirosAGol(sc.nextInt());*/ System.out.println("Cantidad de Goles"); Equipos.get(Equipos.size()-1).setCantidadGoles(sc.nextInt()); System.out.println("Cantidad de Tarjetas Amarillas"); Equipos.get(Equipos.size()-1).setCantidadTarjetasAmarillas(sc.nextInt()); System.out.println("Cantidad de Tarjetas Rojas"); Equipos.get(Equipos.size()-1).setCantidadTarjetasRojas(sc.nextInt()); /* System.out.println("Cantidad de Faltas"); Equipos.get(Equipos.size()-1).setCantidadFaltas(sc.nextInt());*/ cantidadEquipos++; System.out.println("¿Desea seguir inscribiendo los datos de un equipo? s/n"); response = sc.next(); if (response.equals("n")) { ingresoDatos = false; String[] arguments = new String[] {"123"}; Main.main(arguments); } if (cantidadEquipos > 10) { System.out.println("El maximo de equipos inscritos es de 10."); } } } public int getCantidadEquipos() { return cantidadEquipos; } public void setCantidadEquipos(int cantidadEquipos) { this.cantidadEquipos = cantidadEquipos; } }
UTF-8
Java
2,738
java
Autoridades.java
Java
[]
null
[]
package com.company; import java.util.ArrayList; import java.util.Scanner; public class Autoridades { private int cantidadEquipos; public Autoridades(){ System.out.println("*------------Ingreso de Datos---------*"); ingresoDeDatos(); } public static ArrayList<Equipo> Equipos = new ArrayList<Equipo>(); public void ingresoDeDatos(){ Scanner sc = new Scanner(System.in); String response = ""; cantidadEquipos = 0; boolean ingresoDatos = true; while(ingresoDatos) { Equipos.add(new Equipo()); System.out.println("Nombre del Equipo"); Equipos.get(Equipos.size()-1).setNombreEquipo(sc.next()); /*System.out.println("Lugar que ocupó " + Equipos.get(Equipos.size()-1).getNombreEquipo().toString() + " en el torneo"); Equipos.get(Equipos.size()-1).setLugarOcupadoTorneo(sc.next());*/ System.out.println("Cantidad de tiros de Esquina"); Equipos.get(Equipos.size()-1).setCantidadTirosEsquina(sc.nextInt()); /*System.out.println("Cantidad de Juegos Ganados"); Equipos.get(Equipos.size()-1).setCantidadJuegosGanados(sc.nextInt()); System.out.println("Cantidad de Juegos Perdidos"); Equipos.get(Equipos.size()-1).setCantidadJuegosPerdidos(sc.nextInt()); System.out.println("Cantidad de Tiros a Gol"); Equipos.get(Equipos.size()-1).setCantidadTirosAGol(sc.nextInt());*/ System.out.println("Cantidad de Goles"); Equipos.get(Equipos.size()-1).setCantidadGoles(sc.nextInt()); System.out.println("Cantidad de Tarjetas Amarillas"); Equipos.get(Equipos.size()-1).setCantidadTarjetasAmarillas(sc.nextInt()); System.out.println("Cantidad de Tarjetas Rojas"); Equipos.get(Equipos.size()-1).setCantidadTarjetasRojas(sc.nextInt()); /* System.out.println("Cantidad de Faltas"); Equipos.get(Equipos.size()-1).setCantidadFaltas(sc.nextInt());*/ cantidadEquipos++; System.out.println("¿Desea seguir inscribiendo los datos de un equipo? s/n"); response = sc.next(); if (response.equals("n")) { ingresoDatos = false; String[] arguments = new String[] {"123"}; Main.main(arguments); } if (cantidadEquipos > 10) { System.out.println("El maximo de equipos inscritos es de 10."); } } } public int getCantidadEquipos() { return cantidadEquipos; } public void setCantidadEquipos(int cantidadEquipos) { this.cantidadEquipos = cantidadEquipos; } }
2,738
0.604167
0.597222
63
42.42857
29.147526
132
false
false
0
0
0
0
0
0
0.650794
false
false
12
de8ad211c3a729522eddc830f66ceaeea6b81c1e
4,252,017,669,297
383327ef6f7bfc5f94d4e4c670b3f5aeed7f5cb0
/src/xyz/msws/csc/rocket/DrawRocket.java
1693b7525118257a12ec866920befa55627d1ba8
[]
no_license
MSWS/CSC101
https://github.com/MSWS/CSC101
8362a45c6c706e4b4c417474374a4bd34b369a07
1e4faaff4cc4d1ecb19f211bd9d335615ffd0a76
refs/heads/master
2023-03-21T13:06:39.548000
2021-03-15T04:46:04
2021-03-15T04:46:04
339,270,740
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xyz.msws.csc.rocket; import java.util.StringJoiner; import xyz.msws.csc.utils.StringHelper; /** * Prints out a very fancy rocket given a specified height * * @author Isaac * */ public class DrawRocket { public static final int HEIGHT = 4; public static void main(String[] args) { System.out.println(getCone()); System.out.println(getBody()); System.out.println(getCone()); } /** * Returns the body of the rocket * * @return */ public static String getBody() { String seperator = "+" + StringHelper.repeat("=#", HEIGHT * 2) + "+"; StringJoiner joiner = new StringJoiner("\n"); joiner.add(seperator); for (int i = 0; i < 4; i++) joiner.add(getTriangles(i != 3)); joiner.add(StringHelper.repeat(seperator, 2, "\n")); return joiner.toString(); } /** * Returns the inner triangles that makeup the body * * @param upper True if the triangles should point upwards, false if not * @return */ public static String getTriangles(boolean upper) { StringJoiner joiner = new StringJoiner("\n"); for (int i = upper ? 1 : HEIGHT; upper ? i <= HEIGHT : i > 0; i += upper ? 1 : -1) { String body = "|"; body += StringHelper.repeat(".", HEIGHT - i); body += StringHelper.repeat(upper ? "/\\" : "\\/", i); body += StringHelper.repeat(".", (HEIGHT - i) * 2); body += StringHelper.repeat(upper ? "/\\" : "\\/", i); body += StringHelper.repeat(".", HEIGHT - i); body += "|"; joiner.add(body); } return joiner.toString(); } /** * Returns the cones that are for the top and bottom of the rocket * * @return */ public static String getCone() { StringJoiner joiner = new StringJoiner("\n"); for (int i = 1; i < HEIGHT * 2; i++) { String spaces = StringHelper.repeat(" ", HEIGHT * 2 - i); String prefix = StringHelper.repeat("/", i); String body = "**"; String suffix = StringHelper.repeat("\\", i); joiner.add(spaces + prefix + body + suffix); } return joiner.toString(); } }
UTF-8
Java
1,994
java
DrawRocket.java
Java
[ { "context": "ncy rocket given a specified height\n * \n * @author Isaac\n *\n */\npublic class DrawRocket {\n\tpublic static f", "end": 186, "score": 0.8967537879943848, "start": 181, "tag": "NAME", "value": "Isaac" } ]
null
[]
package xyz.msws.csc.rocket; import java.util.StringJoiner; import xyz.msws.csc.utils.StringHelper; /** * Prints out a very fancy rocket given a specified height * * @author Isaac * */ public class DrawRocket { public static final int HEIGHT = 4; public static void main(String[] args) { System.out.println(getCone()); System.out.println(getBody()); System.out.println(getCone()); } /** * Returns the body of the rocket * * @return */ public static String getBody() { String seperator = "+" + StringHelper.repeat("=#", HEIGHT * 2) + "+"; StringJoiner joiner = new StringJoiner("\n"); joiner.add(seperator); for (int i = 0; i < 4; i++) joiner.add(getTriangles(i != 3)); joiner.add(StringHelper.repeat(seperator, 2, "\n")); return joiner.toString(); } /** * Returns the inner triangles that makeup the body * * @param upper True if the triangles should point upwards, false if not * @return */ public static String getTriangles(boolean upper) { StringJoiner joiner = new StringJoiner("\n"); for (int i = upper ? 1 : HEIGHT; upper ? i <= HEIGHT : i > 0; i += upper ? 1 : -1) { String body = "|"; body += StringHelper.repeat(".", HEIGHT - i); body += StringHelper.repeat(upper ? "/\\" : "\\/", i); body += StringHelper.repeat(".", (HEIGHT - i) * 2); body += StringHelper.repeat(upper ? "/\\" : "\\/", i); body += StringHelper.repeat(".", HEIGHT - i); body += "|"; joiner.add(body); } return joiner.toString(); } /** * Returns the cones that are for the top and bottom of the rocket * * @return */ public static String getCone() { StringJoiner joiner = new StringJoiner("\n"); for (int i = 1; i < HEIGHT * 2; i++) { String spaces = StringHelper.repeat(" ", HEIGHT * 2 - i); String prefix = StringHelper.repeat("/", i); String body = "**"; String suffix = StringHelper.repeat("\\", i); joiner.add(spaces + prefix + body + suffix); } return joiner.toString(); } }
1,994
0.617352
0.610331
81
23.617285
22.695824
86
false
false
0
0
0
0
0
0
1.864197
false
false
12
766536d6cdf70f98beda25fc9d4fcd59d41c6ebe
26,972,394,640,309
2c7ba11e2f89b5ce06f527fda08b2d1b212662a9
/PageObjects/src/main/java/com/github/hvasoares/pageobjects/automata/TryField.java
b2e67b2719996f24a7ef0ecbbe5f1335eb3fb25d
[]
no_license
hellokuzuki/PageObjects
https://github.com/hellokuzuki/PageObjects
492d8e48deb81bdc237b08d4beae75b2d250c0f9
2d6b769a0537b18c1a25c8a2416db69b701a746b
refs/heads/master
2017-04-22T06:05:59.302000
2014-04-22T14:09:38
2014-04-22T14:09:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.hvasoares.pageobjects.automata; import org.openqa.selenium.WebDriver; import com.github.hvasoares.pageobjects.impl.browser.Browser; public interface TryField { void setWebDriver(WebDriver value); boolean filled(String xpath, String value); void setBrowser(Browser value); }
UTF-8
Java
303
java
TryField.java
Java
[ { "context": "package com.github.hvasoares.pageobjects.automata;\n\nimport org.openqa.selenium", "end": 28, "score": 0.9897312521934509, "start": 19, "tag": "USERNAME", "value": "hvasoares" }, { "context": "org.openqa.selenium.WebDriver;\n\nimport com.github.hvasoares.pageobjects.impl.browser.Browser;\n\npublic interfa", "end": 118, "score": 0.9895076155662537, "start": 109, "tag": "USERNAME", "value": "hvasoares" } ]
null
[]
package com.github.hvasoares.pageobjects.automata; import org.openqa.selenium.WebDriver; import com.github.hvasoares.pageobjects.impl.browser.Browser; public interface TryField { void setWebDriver(WebDriver value); boolean filled(String xpath, String value); void setBrowser(Browser value); }
303
0.80198
0.80198
15
19.200001
21.673948
61
false
false
0
0
0
0
0
0
0.666667
false
false
12
39e5408f01d5c765cd7f22e4209a79804ebb67ec
20,856,361,196,617
0ae2784417c598729c89adab87fef1d5f7e6e168
/src/main/java/com/works/services/UserService.java
d849c8ed88ff6c98828518e9a40e55a37f483c49
[ "MIT" ]
permissive
Rezzansk/Java-Spring-MVC-JPA-Vet-Clinic-Management-System
https://github.com/Rezzansk/Java-Spring-MVC-JPA-Vet-Clinic-Management-System
5256e81e0d976bdb027a493d23353be137dd943e
beddfc6767fd89cfd3f1476850da3cef66ac6ac7
refs/heads/main
2023-09-05T18:17:02.612000
2021-10-18T19:08:22
2021-10-18T19:08:22
414,760,635
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.works.services; import com.works.entities.Logger; import com.works.entities.Role; import com.works.entities.User; import com.works.repositories.LogRepository; import com.works.repositories.UserRepository; import com.works.utils.Util; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.naming.AuthenticationException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service @Transactional public class UserService extends SimpleUrlLogoutSuccessHandler implements UserDetailsService, LogoutSuccessHandler { final UserRepository uRepo; final LogRepository lRepo; public UserService(UserRepository uRepo, LogRepository lRepo) { this.uRepo = uRepo; this.lRepo = lRepo; } // security login @Override public UserDetails loadUserByUsername(String email) { UserDetails userDetails = null; Optional<User> oUser = uRepo.findByEmailEqualsAllIgnoreCase(email); if (oUser.isPresent()) { User us = oUser.get(); userDetails = new org.springframework.security.core.userdetails.User( us.getEmail(), us.getPassword(), us.isEnabled(), us.isTokenExpired(), true, true, getAuthorities(us.getRoles())); } else { throw new UsernameNotFoundException("Kullanıcı adı yada şifre hatalı"); } return userDetails; } private List<GrantedAuthority> getAuthorities(List<Role> roles) { List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } public User register(User us) throws AuthenticationException { if (!Util.isEmail(us.getEmail())) { throw new AuthenticationException("Bu mail formatı hatalı!"); } Optional<User> uOpt = uRepo.findByEmailEqualsAllIgnoreCase(us.getEmail()); if (uOpt.isPresent()) { throw new AuthenticationException("Bu kullanıcı daha önce kayıtlı!"); } us.setPassword(encoder().encode(us.getPassword())); return uRepo.save(us); } public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Override public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { //final String refererUrl = httpServletRequest.getHeader("Referer"); System.out.println("onLogoutSuccess Call "); //super.onLogoutSuccess(httpServletRequest, httpServletResponse, authentication ); httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login"); } // user info public void info(HttpServletRequest req, HttpServletResponse res, Logger logger) throws IOException { Authentication aut = SecurityContextHolder.getContext().getAuthentication(); String email = aut.getName(); // username if (email != null) { System.out.println(email); } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); String ip = request.getRemoteAddr(); System.out.println("ip " + ip); String session = req.getSession().getId(); System.out.println("session :" + session); Optional<User> user = uRepo.findByEmailEqualsAllIgnoreCase(email); if (user.isPresent()) { logger.setLname(user.get().getFirstName()); logger.setLsurname(user.get().getLastName()); String roles = ""; for (Role item : user.get().getRoles()) { roles += item.getName() + ", "; } if (roles.length() > 0) { roles = roles.substring(0, roles.length() - 2); } logger.setLroles(roles); } logger.setLemail(email); logger.setLsessionId(session); logger.setLIp(ip); logger.setLUrl(req.getRequestURI()); logger.setLDate(LocalDateTime.now()); lRepo.save(logger); System.out.println(logger); } }
UTF-8
Java
5,593
java
UserService.java
Java
[]
null
[]
package com.works.services; import com.works.entities.Logger; import com.works.entities.Role; import com.works.entities.User; import com.works.repositories.LogRepository; import com.works.repositories.UserRepository; import com.works.utils.Util; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.naming.AuthenticationException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service @Transactional public class UserService extends SimpleUrlLogoutSuccessHandler implements UserDetailsService, LogoutSuccessHandler { final UserRepository uRepo; final LogRepository lRepo; public UserService(UserRepository uRepo, LogRepository lRepo) { this.uRepo = uRepo; this.lRepo = lRepo; } // security login @Override public UserDetails loadUserByUsername(String email) { UserDetails userDetails = null; Optional<User> oUser = uRepo.findByEmailEqualsAllIgnoreCase(email); if (oUser.isPresent()) { User us = oUser.get(); userDetails = new org.springframework.security.core.userdetails.User( us.getEmail(), us.getPassword(), us.isEnabled(), us.isTokenExpired(), true, true, getAuthorities(us.getRoles())); } else { throw new UsernameNotFoundException("Kullanıcı adı yada şifre hatalı"); } return userDetails; } private List<GrantedAuthority> getAuthorities(List<Role> roles) { List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } public User register(User us) throws AuthenticationException { if (!Util.isEmail(us.getEmail())) { throw new AuthenticationException("Bu mail formatı hatalı!"); } Optional<User> uOpt = uRepo.findByEmailEqualsAllIgnoreCase(us.getEmail()); if (uOpt.isPresent()) { throw new AuthenticationException("Bu kullanıcı daha önce kayıtlı!"); } us.setPassword(encoder().encode(us.getPassword())); return uRepo.save(us); } public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Override public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { //final String refererUrl = httpServletRequest.getHeader("Referer"); System.out.println("onLogoutSuccess Call "); //super.onLogoutSuccess(httpServletRequest, httpServletResponse, authentication ); httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login"); } // user info public void info(HttpServletRequest req, HttpServletResponse res, Logger logger) throws IOException { Authentication aut = SecurityContextHolder.getContext().getAuthentication(); String email = aut.getName(); // username if (email != null) { System.out.println(email); } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); String ip = request.getRemoteAddr(); System.out.println("ip " + ip); String session = req.getSession().getId(); System.out.println("session :" + session); Optional<User> user = uRepo.findByEmailEqualsAllIgnoreCase(email); if (user.isPresent()) { logger.setLname(user.get().getFirstName()); logger.setLsurname(user.get().getLastName()); String roles = ""; for (Role item : user.get().getRoles()) { roles += item.getName() + ", "; } if (roles.length() > 0) { roles = roles.substring(0, roles.length() - 2); } logger.setLroles(roles); } logger.setLemail(email); logger.setLsessionId(session); logger.setLIp(ip); logger.setLUrl(req.getRequestURI()); logger.setLDate(LocalDateTime.now()); lRepo.save(logger); System.out.println(logger); } }
5,593
0.691632
0.691095
152
35.717106
30.497286
181
false
false
0
0
0
0
0
0
0.611842
false
false
12
6a7dd73d08f8ecc31e3548ac0cde8d3f3454e8d7
12,618,613,950,579
0c5d655bb57baf7caf2f4bcf37870b2abc153122
/caffeine-componentes/src/main/java/com/andersonfonseka/caffeine/componentes/impl/ComponenteFabricaImpl.java
42172caf4041b8870c503d7237ca8d6f5120f56a
[ "MIT" ]
permissive
andersonfonseka/caffeine
https://github.com/andersonfonseka/caffeine
d5231e5feee4089b3ae7f43b4692f17091c4b71c
96b6d0fc761370353e977dd69c660d32aa7dfc4f
refs/heads/master
2023-03-03T17:02:45.156000
2019-06-27T14:04:07
2019-06-27T14:04:07
179,368,770
1
0
MIT
false
2023-02-22T08:12:32
2019-04-03T20:54:22
2020-06-07T00:45:56
2023-02-22T08:12:31
10,977
0
0
1
Java
false
false
package com.andersonfonseka.caffeine.componentes.impl; import java.io.Serializable; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import org.jboss.weld.bean.ManagedBean; import com.andersonfonseka.caffeine.IAcesso; import com.andersonfonseka.caffeine.IBotao; import com.andersonfonseka.caffeine.IComponenteFabrica; import com.andersonfonseka.caffeine.IConteiner; import com.andersonfonseka.caffeine.IEndereco; import com.andersonfonseka.caffeine.IPagina; import com.andersonfonseka.caffeine.IProjeto; import com.andersonfonseka.caffeine.IResposta; import com.andersonfonseka.caffeine.ISelecao; import com.andersonfonseka.caffeine.ITipoValor; import com.andersonfonseka.caffeine.componentes.acao.AcaoAbs; import com.andersonfonseka.caffeine.componentes.impl.basicos.Botao; import com.andersonfonseka.caffeine.componentes.impl.basicos.Conteiner; import com.andersonfonseka.caffeine.componentes.impl.compostos.Acesso; import com.andersonfonseka.caffeine.componentes.impl.compostos.Endereco; import com.andersonfonseka.caffeine.componentes.impl.compostos.TipoValor; public class ComponenteFabricaImpl implements IComponenteFabrica, Serializable { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(ComponenteFabricaImpl.class.getName()); @Inject private BeanManager beanManager; @Override public void setBeanManager(BeanManager beanManager) { this.beanManager = beanManager; } public IProjeto criarProjeto(String id) { IProjeto projeto = null; try { if (!beanManager.getBeans(Class.forName(id)).isEmpty()) { @SuppressWarnings("rawtypes") ManagedBean bean = (ManagedBean) beanManager.getBeans(Class.forName(id)).iterator().next(); CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); projeto = (IProjeto) bean.create(creationalContext); } } catch (ClassNotFoundException e) { log.log(Level.WARNING, e.getMessage()); } return projeto; } public IBotao criarBotaoCancelar(Class<? extends IPagina> paginaDestino) { IBotao btnCancel = new Botao.Builder("Cancelar", new AcaoAbs(new Object()) { public IResposta execute() { IResposta pageResponse = new Resposta.Builder().build(); pageResponse.setPageUrl(paginaDestino); return pageResponse; } }, true).build(); btnCancel.setEstilo("btn-danger"); btnCancel.setImediato(true); return btnCancel; } public IConteiner criarConteiner(Integer rows) { return new Conteiner(rows); } public IEndereco criarEndereco(IPagina pagina) { return new Endereco(this, pagina); } @Override public IPagina criarPagina(String id) { IPagina page = null; try { if (!beanManager.getBeans(Class.forName(id)).isEmpty()) { @SuppressWarnings("rawtypes") ManagedBean bean = (ManagedBean) beanManager.getBeans(Class.forName(id)).iterator().next(); CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); page = (IPagina) bean.create(creationalContext); } } catch (ClassNotFoundException e) { log.log(Level.WARNING, e.getMessage()); } return page; } @Override public IAcesso criarAcesso(IPagina pagina, Map<String, String> usuarios, Class<? extends IPagina> paginaDestino) { return new Acesso(this, pagina, usuarios, paginaDestino); } @Override public ITipoValor criarTipoValor(IPagina pagina, ISelecao selecaoTipo) { return new TipoValor(this, pagina, selecaoTipo); } }
UTF-8
Java
3,753
java
ComponenteFabricaImpl.java
Java
[]
null
[]
package com.andersonfonseka.caffeine.componentes.impl; import java.io.Serializable; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import org.jboss.weld.bean.ManagedBean; import com.andersonfonseka.caffeine.IAcesso; import com.andersonfonseka.caffeine.IBotao; import com.andersonfonseka.caffeine.IComponenteFabrica; import com.andersonfonseka.caffeine.IConteiner; import com.andersonfonseka.caffeine.IEndereco; import com.andersonfonseka.caffeine.IPagina; import com.andersonfonseka.caffeine.IProjeto; import com.andersonfonseka.caffeine.IResposta; import com.andersonfonseka.caffeine.ISelecao; import com.andersonfonseka.caffeine.ITipoValor; import com.andersonfonseka.caffeine.componentes.acao.AcaoAbs; import com.andersonfonseka.caffeine.componentes.impl.basicos.Botao; import com.andersonfonseka.caffeine.componentes.impl.basicos.Conteiner; import com.andersonfonseka.caffeine.componentes.impl.compostos.Acesso; import com.andersonfonseka.caffeine.componentes.impl.compostos.Endereco; import com.andersonfonseka.caffeine.componentes.impl.compostos.TipoValor; public class ComponenteFabricaImpl implements IComponenteFabrica, Serializable { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(ComponenteFabricaImpl.class.getName()); @Inject private BeanManager beanManager; @Override public void setBeanManager(BeanManager beanManager) { this.beanManager = beanManager; } public IProjeto criarProjeto(String id) { IProjeto projeto = null; try { if (!beanManager.getBeans(Class.forName(id)).isEmpty()) { @SuppressWarnings("rawtypes") ManagedBean bean = (ManagedBean) beanManager.getBeans(Class.forName(id)).iterator().next(); CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); projeto = (IProjeto) bean.create(creationalContext); } } catch (ClassNotFoundException e) { log.log(Level.WARNING, e.getMessage()); } return projeto; } public IBotao criarBotaoCancelar(Class<? extends IPagina> paginaDestino) { IBotao btnCancel = new Botao.Builder("Cancelar", new AcaoAbs(new Object()) { public IResposta execute() { IResposta pageResponse = new Resposta.Builder().build(); pageResponse.setPageUrl(paginaDestino); return pageResponse; } }, true).build(); btnCancel.setEstilo("btn-danger"); btnCancel.setImediato(true); return btnCancel; } public IConteiner criarConteiner(Integer rows) { return new Conteiner(rows); } public IEndereco criarEndereco(IPagina pagina) { return new Endereco(this, pagina); } @Override public IPagina criarPagina(String id) { IPagina page = null; try { if (!beanManager.getBeans(Class.forName(id)).isEmpty()) { @SuppressWarnings("rawtypes") ManagedBean bean = (ManagedBean) beanManager.getBeans(Class.forName(id)).iterator().next(); CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); page = (IPagina) bean.create(creationalContext); } } catch (ClassNotFoundException e) { log.log(Level.WARNING, e.getMessage()); } return page; } @Override public IAcesso criarAcesso(IPagina pagina, Map<String, String> usuarios, Class<? extends IPagina> paginaDestino) { return new Acesso(this, pagina, usuarios, paginaDestino); } @Override public ITipoValor criarTipoValor(IPagina pagina, ISelecao selecaoTipo) { return new TipoValor(this, pagina, selecaoTipo); } }
3,753
0.750333
0.750067
127
28.110237
28.515566
115
false
false
0
0
0
0
0
0
1.771654
false
false
12
8eb9f0d881692beff78a1b81d384a18e704f8dce
14,388,140,477,861
728474685e1c9aa65746bc24b766182b22080454
/app/src/main/java/com/dugu/addressbook/assembly/LoadingDialog.java
f023df5b1ec817eec9447c59e5c9c3f18e08cdeb
[]
no_license
dugu97/AddressBook
https://github.com/dugu97/AddressBook
61e4a5eb9d031409125fd5a31274aad2740012a5
2a1a41b49a3621dbdf18f3f5b37e7d511dc81de3
refs/heads/master
2020-04-15T16:29:50.338000
2019-03-09T14:11:17
2019-03-09T14:11:17
164,839,210
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dugu.addressbook.assembly; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.dugu.addressbook.R; /** * 加载对话框(目前已添加到WuYuBaseActivity) */ public class LoadingDialog extends DialogFragment { private final String TAG = "WuYuLoadingDialog.TAG"; private TextView tvMessage; private static String message; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view tvMessage = (TextView) v.findViewById(R.id.dialog_loading_message); tvMessage.setText(message); Dialog loadingDialog = new Dialog(getActivity(), R.style.loading_dialog);// 创建自定义样式dialog loadingDialog.setCanceledOnTouchOutside(false); loadingDialog.setCancelable(false);// 不可以用“返回键”取消 loadingDialog.setContentView(v);// 设置布局 loadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } return false; } }); return loadingDialog; } public void setMessage(String message) { this.message = message; } }
UTF-8
Java
1,758
java
LoadingDialog.java
Java
[]
null
[]
package com.dugu.addressbook.assembly; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.dugu.addressbook.R; /** * 加载对话框(目前已添加到WuYuBaseActivity) */ public class LoadingDialog extends DialogFragment { private final String TAG = "WuYuLoadingDialog.TAG"; private TextView tvMessage; private static String message; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view tvMessage = (TextView) v.findViewById(R.id.dialog_loading_message); tvMessage.setText(message); Dialog loadingDialog = new Dialog(getActivity(), R.style.loading_dialog);// 创建自定义样式dialog loadingDialog.setCanceledOnTouchOutside(false); loadingDialog.setCancelable(false);// 不可以用“返回键”取消 loadingDialog.setContentView(v);// 设置布局 loadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } return false; } }); return loadingDialog; } public void setMessage(String message) { this.message = message; } }
1,758
0.689286
0.68869
53
30.698112
25.254616
97
false
false
0
0
0
0
0
0
0.584906
false
false
12
4780a78226bde5cbe446aeae9fe9b1ae3e628fe9
6,073,083,818,395
ee4258ff1d031e4c7ee249d32a1243b0c719fb60
/app/src/main/java/com/jiyun/lenovo/opensourcechina_practice/fragment/find/findConFragFirstlevellist.java
e59aa75ec4d1dfbf314bf902f31eab2ce25cd6fc
[]
no_license
JiangXianKaiNan/OpenSourceChina_Practice
https://github.com/JiangXianKaiNan/OpenSourceChina_Practice
c04d23392ef71193dccb614cf1d5adfa806c7ff1
d28530c12c7181d299f1f52ba4026b305108c9e0
refs/heads/master
2018-04-06T22:23:00.382000
2017-04-26T14:03:54
2017-04-26T14:03:54
88,066,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jiyun.lenovo.opensourcechina_practice.fragment.find; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.jiyun.lenovo.opensourcechina_practice.App; import com.jiyun.lenovo.opensourcechina_practice.R; import com.jiyun.lenovo.opensourcechina_practice.base.BaseFragment; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by LENOVO on 2017/4/20. */ public class findConFragFirstlevellist extends BaseFragment { @BindView(R.id.FindConFragfirst) FrameLayout FindConFragfirst; private FragmentManager manager; @Override protected int layoutId() { return R.layout.findconfragfirst; } @Override protected void initView(View view) { } @Override protected void initData() { manager = App.acriciry.getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.FindConFragfirst,new FindConFragFirstOne()); transaction.commit(); } @Override protected void initListener() { } @Override protected void loadData() { } @Override public void setParams(Bundle bundle) { } }
UTF-8
Java
1,431
java
findConFragFirstlevellist.java
Java
[ { "context": "e;\nimport butterknife.Unbinder;\n\n/**\n * Created by LENOVO on 2017/4/20.\n */\n\npublic class findConFragFirstl", "end": 609, "score": 0.9995166659355164, "start": 603, "tag": "USERNAME", "value": "LENOVO" } ]
null
[]
package com.jiyun.lenovo.opensourcechina_practice.fragment.find; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.jiyun.lenovo.opensourcechina_practice.App; import com.jiyun.lenovo.opensourcechina_practice.R; import com.jiyun.lenovo.opensourcechina_practice.base.BaseFragment; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by LENOVO on 2017/4/20. */ public class findConFragFirstlevellist extends BaseFragment { @BindView(R.id.FindConFragfirst) FrameLayout FindConFragfirst; private FragmentManager manager; @Override protected int layoutId() { return R.layout.findconfragfirst; } @Override protected void initView(View view) { } @Override protected void initData() { manager = App.acriciry.getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.FindConFragfirst,new FindConFragFirstOne()); transaction.commit(); } @Override protected void initListener() { } @Override protected void loadData() { } @Override public void setParams(Bundle bundle) { } }
1,431
0.736548
0.730259
65
21.015385
21.771183
77
false
false
0
0
0
0
0
0
0.338462
false
false
12
c3a111e679c72c83c1d982d858193d5d634f0929
10,634,339,042,519
d764d505837adfdba59a6edd57f1e70829e71887
/Ipay/src/cards/Card.java
db831c2b2355ddde7872d0b4375576c4d5fe1b03
[]
no_license
popovua/ipay
https://github.com/popovua/ipay
f04ae9216157962d04df5d47140f2321e598d1d3
9e25eec50f235245bb3209ec78dd9bb22e4f4c48
refs/heads/master
2016-12-13T05:59:39.669000
2016-07-27T07:10:44
2016-07-27T07:10:44
38,312,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cards; public abstract class Card { protected String part1; protected String part2; protected String part3; protected String part4; protected String expMonth; protected String expYear; protected String cvv; public String getPart1() { return part1; } public String getPart2() { return part2; } public String getPart3() { return part3; } public String getPart4() { return part4; } public String getExpMonth() { return expMonth; } public String getExpYear() { return expYear; } public String getCvv() { return cvv; } public void setPart1(String part1) { this.part1 = part1; } public void setPart2(String part2) { this.part2 = part2; } public void setPart3(String part3) { this.part3 = part3; } public void setPart4(String part4) { this.part4 = part4; } public void setExpMonth(String expMonth) { this.expMonth = expMonth; } public void setExpYear(String expYear) { this.expYear = expYear; } public void setCvv(String cvv) { this.cvv = cvv; } public abstract void resetByDefault(); }
UTF-8
Java
1,137
java
Card.java
Java
[]
null
[]
package cards; public abstract class Card { protected String part1; protected String part2; protected String part3; protected String part4; protected String expMonth; protected String expYear; protected String cvv; public String getPart1() { return part1; } public String getPart2() { return part2; } public String getPart3() { return part3; } public String getPart4() { return part4; } public String getExpMonth() { return expMonth; } public String getExpYear() { return expYear; } public String getCvv() { return cvv; } public void setPart1(String part1) { this.part1 = part1; } public void setPart2(String part2) { this.part2 = part2; } public void setPart3(String part3) { this.part3 = part3; } public void setPart4(String part4) { this.part4 = part4; } public void setExpMonth(String expMonth) { this.expMonth = expMonth; } public void setExpYear(String expYear) { this.expYear = expYear; } public void setCvv(String cvv) { this.cvv = cvv; } public abstract void resetByDefault(); }
1,137
0.656113
0.631486
68
14.720589
13.549306
43
false
false
0
0
0
0
0
0
1.308824
false
false
12
49df7750b5b48e5770334572e48206774d46b03a
19,413,252,179,258
7cd38856068e48a7ad29eb128c728739e4de11b9
/order-canal-domain/src/main/java/com/lenovo/m2/oc/canal/domain/reverse/Reverse.java
b1404b73a9281297c80a97f75f15b46cf71d6b85
[]
no_license
Jxyxl259/order_canal
https://github.com/Jxyxl259/order_canal
d08bad0bc25fec0bd52c79e229f7a86a600e1fec
8973b07c83e5ca594d795037f868b13644083a1f
refs/heads/master
2022-12-21T06:49:19.081000
2019-08-27T12:51:50
2019-08-27T12:51:50
204,475,189
0
1
null
false
2022-12-16T03:34:21
2019-08-26T12:52:40
2019-08-27T12:51:59
2022-12-16T03:34:21
86
0
1
8
Java
false
false
package com.lenovo.m2.oc.canal.domain.reverse; import com.fasterxml.jackson.annotation.JsonFormat; import com.lenovo.m2.arch.framework.domain.Money; import com.lenovo.m2.arch.framework.domain.RemoteResult; import com.lenovo.m2.arch.framework.domain.Tenant; import com.lenovo.m2.oc.canal.domain.ordercenter.Main; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.sql.Timestamp; import java.util.*; /** * Created by zhangzhen on 16/7/8. */ public class Reverse implements Serializable { private static Logger LOGGER = LoggerFactory.getLogger(Reverse.class); private static Map<String, String> rApplyKPrefixMap = new HashMap<String, String>(); static { rApplyKPrefixMap.put("0", "K"); rApplyKPrefixMap.put("5", "T"); rApplyKPrefixMap.put("6", "E"); rApplyKPrefixMap.put("7", "G"); rApplyKPrefixMap.put("8", "AP"); rApplyKPrefixMap.put("9", "AG"); rApplyKPrefixMap.put("10", "WS"); rApplyKPrefixMap.put("11", "WG"); rApplyKPrefixMap.put("12", "WA"); rApplyKPrefixMap.put("13", "WP"); rApplyKPrefixMap.put("16", "MBG"); rApplyKPrefixMap.put("17", "T"); rApplyKPrefixMap.put("18", "T"); rApplyKPrefixMap.put("19", "T"); rApplyKPrefixMap.put("56", "K"); rApplyKPrefixMap.put("88", "AP"); } /** * 反向类型 1--撤单 */ public final static int REVERSE_TYPE_REVOKE = 1; /** * 反向类型 2--退货 */ public final static int REVERSE_TYPE_RETURN = 2; /** * 反向类型 3--换货 */ public final static int REVERSE_TYPE_EXCHANGE = 3; /** * 审核状态 0--未审核 */ public final static int AUDIT_STATUS_UNAUDITED = 0; /** * 审核状态 1--受理 */ public final static int AUDIT_STATUS_ACCEPTED = 1; /** * 审核状态 2--驳回 */ public final static int AUDIT_STATUS_REJECTED = 2; /** * 审核状态 3--已作废 */ public final static int AUDIT_STATUS_CANCELL = 3; /** * 审核状态 4--已审核已抛废单 */ public final static int AUDIT_STATUS_ACC_ABOILSH = 4; /** * 审核状态 5--废单通过 */ public final static int AUDIT_STATUS_ABOLISH_SUC = 5; /** * 审核状态 6--废单驳回 */ public final static int AUDIT_STATUS_ABOLISH_DEF = 6; /** * 反向订单状态 0--已申请 */ public final static int RE_STATUS_UNAUDITED = 0; /** * 反向订单状态 1--审核通过 */ public final static int RE_STATUS_ACCEPTED = 1; /** * 反向订单状态 2--审核拒绝 */ public final static int RE_STATUS_REJECTED = 2; /** * 反向订单状态 3--退款中 */ public final static int RE_STATUS_REFUNDING = 3; /** * 反向订单状态 44--换货中 */ public final static int RE_STATUS_EXCHANGEING = 4; /** * 反向订单状态 5--完成 */ public final static int RE_STATUS_COMPLETE = 5; /** * 反向订单状态 6--关单 */ public final static int RE_STATUS_CLOSE = 6; /** * 反向订单状态 10--撤单已申请 */ public final static int RE_STATUS_REVAPPLY = 10; /** * 反向订单状态 11--撤单已审核 */ public final static int RE_STATUS_REVAUDIT = 11; /** * 反向订单状态 12--撤单已驳回 */ public final static int RE_STATUS_REVREFUSE = 12; /** * 反向订单状态 20--退货已申请 */ public final static int RE_STATUS_RETAPPLY = 20; /** * 反向订单状态 21--退货已审核 */ public final static int RE_STATUS_RETAUDIT = 21; /** * 反向订单状态 22--退货已驳回 */ public final static int RE_STATUS_RETREFUSE = 22; /** * 反向订单状态 30--换货已申请 */ public final static int RE_STATUS_EXCHAPPLY = 30; /** * 反向订单状态 31--换货已审核 */ public final static int RE_STATUS_EXCAUDIT = 31; /** * 反向订单状态 32--换货已驳回 */ public final static int RE_STATUS_EXCREFUSE = 32; /** * 反向支付状态-1:已支付 */ public static final int RE_PAY_STATUS_COMP = 1; /** * 反向支付状态-2:退款中 */ public static final int RE_PAY_STATUS_REFUND = 2; /** * 反向支付状态- 3:已退款 */ public static final int RE_PAY_STATUS_REFUND_COMP = 3; /** * 反向订单关单 - 6 关单 */ public static final int AUDIT_STATUS_CLOSE = 6; /** * 反向、退款类型 */ public static final String TYPE_REVERSE = "reverse"; public static final String TYPE_REFUND = "refund"; public static final String TYPE_REAUDIT= "reAudit"; /** * 反向退货方式 */ public static final int REVERSE_WAY_ALL = 0; public static final int REVERSE_WAY_PARY = 1; private long id; private long orderId;//订单号 private String reason;//退换货原因 private long stockReturnId; //库存反向id private String category;//退换货分类 原因分类 private String description;//退换货原因文字描述 private Money amount;//退款小计 private Money refundManual;//手工返款 private Money personalizationAmount;//私人订制价格 //客户换货原因 private String csRedescription; private boolean complete;//包装是否齐全0:否 1:是 private int type;//1--撤单,2--退货,3--换货 private int auditStatus;//审批状态:0--待审批,1--审批通过,2--审批驳回,3--已作废,4废单申请,5 废单审核通过 6废单驳回 private String goodsCodes;//商品编号多个以”,”分割 private String goodsNames;//商品名称多个以”,”分割 private String sns;//SN多个以”,”分割 private String refuseReason;//驳回理由,审批驳回的时候必填 private String rApplyK;//供应链K码, 仅btcp使用 private String serviceMode;//服务方式,ZX16、ZX17 ””,仅btcp使用 private boolean throwing;//是否抛单 0:否 1:是 private String outId;//第三方订单号BtcpR号 private String remark;//备注 private int version; private String reLogisticsNo; private String reCompanyName; private String reCompanyCode; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Timestamp createTime; private String createBy; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Timestamp updateTime; private String updateBy; private String returnAddress; private boolean needReturnStock; private int outStatus; //退货时btcp推送的工厂收货通知.0--符合退款;1--不符合;2--关单 private Money transportFee; //垫付金额 private int preOrderStatus;//之前的订单状态 private boolean needExpress; private int reStatus; //反向状态 private int rePayStatus;//反向支付状态 private Integer shopId; private Main main; private ReverseDeliveryAddress deliveryAddress; private List<ReverseItem> items;//退换货item列表 private Refund refund; private Reverselogistics reverselogistics; private Tenant tenant; //租户对象 private List<String> fileUrl;//文件地址路径 private Money freight;//运费 private Money virtualCoin;//虚拟币数量 private String virtualCoinTradeNo;//虚拟币流水号 private Integer virtualCoinType;//虚拟币类型1 消费点 2 乐豆 private Integer reverseWay;//反向订单退货方式: 0:整单退 1:部分退 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date auditTime ; public Date getAuditTime() { return auditTime; } public void setAuditTime(Date auditTime) { this.auditTime = auditTime; } public Integer getReverseWay() { return reverseWay; } public void setReverseWay(Integer reverseWay) { this.reverseWay = reverseWay; } public Integer getShopId() { return shopId; } public void setShopId(Integer shopId) { this.shopId = shopId; } public Integer getVirtualCoinType() { return virtualCoinType; } public void setVirtualCoinType(Integer virtualCoinType) { this.virtualCoinType = virtualCoinType; } public String getVirtualCoinTradeNo() { return virtualCoinTradeNo; } public void setVirtualCoinTradeNo(String virtualCoinTradeNo) { this.virtualCoinTradeNo = virtualCoinTradeNo; } public Money getVirtualCoin() { return virtualCoin; } public void setVirtualCoin(Money virtualCoin) { this.virtualCoin = virtualCoin; } public Money getFreight() { return freight; } public void setFreight(Money freight) { this.freight = freight; } public boolean isNeedExpress() { return needExpress; } public void setNeedExpress(boolean needExpress) { this.needExpress = needExpress; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Money getAmount() { return amount; } public void setAmount(Money amount) { this.amount = amount; } public Money getRefundManual() { return refundManual; } public void setRefundManual(Money refundManual) { this.refundManual = refundManual; } public Money getPersonalizationAmount() { return personalizationAmount; } public void setPersonalizationAmount(Money personalizationAmount) { this.personalizationAmount = personalizationAmount; } public boolean isComplete() { return complete; } public void setComplete(boolean complete) { this.complete = complete; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getAuditStatus() { return auditStatus; } public void setAuditStatus(int auditStatus) { this.auditStatus = auditStatus; } public String getGoodsCodes() { return goodsCodes; } public void setGoodsCodes(String goodsCodes) { this.goodsCodes = goodsCodes; } public String getGoodsNames() { return goodsNames; } public void setGoodsNames(String goodsNames) { this.goodsNames = goodsNames; } public String getSns() { return sns; } public void setSns(String sns) { this.sns = sns; } public String getRefuseReason() { return refuseReason; } public void setRefuseReason(String refuseReason) { this.refuseReason = refuseReason; } public String getrApplyK() { return rApplyK; } public void setrApplyK(String rApplyK) { this.rApplyK = rApplyK; } public String getServiceMode() { return serviceMode; } public void setServiceMode(String serviceMode) { this.serviceMode = serviceMode; } public boolean isThrowing() { return throwing; } public void setThrowing(boolean throwing) { this.throwing = throwing; } public String getOutId() { return outId; } public void setOutId(String outId) { this.outId = outId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getOutStatus() { return outStatus; } public void setOutStatus(int outStatus) { this.outStatus = outStatus; } public Money getTransportFee() { return transportFee; } public void setTransportFee(Money transportFee) { this.transportFee = transportFee; } public Main getMain() { if (main == null) { main = new Main(); } return main; } public List<String> getFileUrl() { return fileUrl; } public void setFileUrl(List<String> fileUrl) { this.fileUrl = fileUrl; } public String getReLogisticsNo() { return reLogisticsNo; } public void setReLogisticsNo(String reLogisticsNo) { this.reLogisticsNo = reLogisticsNo; } public String getReCompanyName() { return reCompanyName; } public void setReCompanyName(String reCompanyName) { this.reCompanyName = reCompanyName; } public String getReCompanyCode() { return reCompanyCode; } public void setReCompanyCode(String reCompanyCode) { this.reCompanyCode = reCompanyCode; } public void setMain(Main main) { this.main = main; } public ReverseDeliveryAddress getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(ReverseDeliveryAddress deliveryAddress) { this.deliveryAddress = deliveryAddress; } public List<ReverseItem> getItems() { return items; } public void setItems(List<ReverseItem> items) { this.items = items; } public Reverse(Main main) { this.main = main; } public Refund getRefund() { if (refund == null) { refund = new Refund(); } return refund; } public void setRefund(Refund refund) { this.refund = refund; } public String getReturnAddress() { return returnAddress; } public void setReturnAddress(String returnAddress) { this.returnAddress = returnAddress; } public Reverse() { } public int getPreOrderStatus() { return preOrderStatus; } public void setPreOrderStatus(int preOrderStatus) { this.preOrderStatus = preOrderStatus; } public boolean isNeedReturnStock() { return needReturnStock; } public void setNeedReturnStock(boolean needReturnStock) { this.needReturnStock = needReturnStock; } public Reverselogistics getReverselogistics() { return reverselogistics; } public void setReverselogistics(Reverselogistics reverselogistics) { this.reverselogistics = reverselogistics; } public int getRePayStatus() { return rePayStatus; } public void setRePayStatus(int rePayStatus) { this.rePayStatus = rePayStatus; } public int getReStatus() { return reStatus; } public void setReStatus(int reStatus) { this.reStatus = reStatus; } public Tenant getTenant() { return tenant; } public void setTenant(Tenant tenant) { this.tenant = tenant; } public void genRApplyK() { if (rApplyKPrefixMap.get(main.getSource()) != null) { this.rApplyK = rApplyKPrefixMap.get(main.getSource()) + main.getId() + new DateTime().toString("MMdd") + new Random(System.currentTimeMillis()).nextInt(9999); } else { LOGGER.info("没有获取到订单来源:" + main.getSource()); rApplyK = "9999"; } } /** * 判断该订单是否可以撤单 */ // public RemoteResult isApplyRevoke(RemoteResult remoteResult) { // if (Main.ADD_TYPE_OTO == type) { // remoteResult.setResultMsg("订单类型为OTO , 不允许做撤单"); // remoteResult.setSuccess(false); // return remoteResult; // } else if (Main.FA_TYPE_RESELLERS == main.getFaType()) { // return remoteResult; // } else if ((Main.FA_TYPE_DIRECT == main.getFaType() || Main.FA_TYPE_DONGDE == main.getFaType() || Main.FA_TYPE_THINK_DIRECT == main.getFaType() || Main.FA_TYPE_MBG == main.getFaType() || Main.FA_TYPE_THINK_RESELLERS == main.getFaType()) && Main.STATUS_UN_SHIPPED == main.getStatus()) { // return remoteResult; // } else {//fa=1;fa(0,2,3,4)且未发货。这两种情况允许撤单 // remoteResult.setResultMsg("FATYPE为1或者为(0,2,3,4)且未发货。这两种情况允许撤单"); // remoteResult.setSuccess(false); // return remoteResult; // } // } /** * 校验退货申请入参 * * @return */ public RemoteResult validateApplyReturn() { RemoteResult remoteResult = new RemoteResult(); if (StringUtils.isEmpty(this.reason)) { remoteResult.setResultCode("1007"); remoteResult.setResultMsg("退货原因不能为空"); } else if(StringUtils.isEmpty(this.category)){ remoteResult.setResultCode("1008"); remoteResult.setResultMsg("退货分类不能为空"); }else { remoteResult.setSuccess(true); remoteResult.setResultCode("1000"); } return remoteResult; } @Override public String toString() { return "Reverse{" + "id=" + id + ", orderId=" + orderId + ", reason='" + reason + '\'' + ", category='" + category + '\'' + ", description='" + description + '\'' + ", complete=" + complete + ", type=" + type + ", auditStatus=" + auditStatus + ", goodsCodes='" + goodsCodes + '\'' + ", goodsNames='" + goodsNames + '\'' + ", sns='" + sns + '\'' + ", refuseReason='" + refuseReason + '\'' + ", rApplyK='" + rApplyK + '\'' + ", serviceMode='" + serviceMode + '\'' + ", throwing=" + throwing + ", outId='" + outId + '\'' + ", remark='" + remark + '\'' + ", version=" + version + ", createTime=" + createTime + ", createBy='" + createBy + '\'' + ", updateTime=" + updateTime + ", updateBy='" + updateBy + '\'' + ", reStatus='" + reStatus + '\'' + ", rePayStatus='" + rePayStatus + '\'' + ", returnAddress='" + returnAddress + '\'' + ", transportFee='" + transportFee + '\'' + ", returnAddress='" + +'\'' + ", main=" + main + ", deliveryAddress=" + deliveryAddress + ", items=" + items + ", refund=" + refund + '}'; } public long getStockReturnId() { return stockReturnId; } public void setStockReturnId(long stockReturnId) { this.stockReturnId = stockReturnId; } public String getCsRedescription() { return csRedescription; } public void setCsRedescription(String csRedescription) { this.csRedescription = csRedescription; } }
UTF-8
Java
20,511
java
Reverse.java
Java
[ { "context": ".Timestamp;\nimport java.util.*;\n\n/**\n * Created by zhangzhen on 16/7/8.\n */\npublic class Reverse implements Se", "end": 550, "score": 0.9996216297149658, "start": 541, "tag": "USERNAME", "value": "zhangzhen" } ]
null
[]
package com.lenovo.m2.oc.canal.domain.reverse; import com.fasterxml.jackson.annotation.JsonFormat; import com.lenovo.m2.arch.framework.domain.Money; import com.lenovo.m2.arch.framework.domain.RemoteResult; import com.lenovo.m2.arch.framework.domain.Tenant; import com.lenovo.m2.oc.canal.domain.ordercenter.Main; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.sql.Timestamp; import java.util.*; /** * Created by zhangzhen on 16/7/8. */ public class Reverse implements Serializable { private static Logger LOGGER = LoggerFactory.getLogger(Reverse.class); private static Map<String, String> rApplyKPrefixMap = new HashMap<String, String>(); static { rApplyKPrefixMap.put("0", "K"); rApplyKPrefixMap.put("5", "T"); rApplyKPrefixMap.put("6", "E"); rApplyKPrefixMap.put("7", "G"); rApplyKPrefixMap.put("8", "AP"); rApplyKPrefixMap.put("9", "AG"); rApplyKPrefixMap.put("10", "WS"); rApplyKPrefixMap.put("11", "WG"); rApplyKPrefixMap.put("12", "WA"); rApplyKPrefixMap.put("13", "WP"); rApplyKPrefixMap.put("16", "MBG"); rApplyKPrefixMap.put("17", "T"); rApplyKPrefixMap.put("18", "T"); rApplyKPrefixMap.put("19", "T"); rApplyKPrefixMap.put("56", "K"); rApplyKPrefixMap.put("88", "AP"); } /** * 反向类型 1--撤单 */ public final static int REVERSE_TYPE_REVOKE = 1; /** * 反向类型 2--退货 */ public final static int REVERSE_TYPE_RETURN = 2; /** * 反向类型 3--换货 */ public final static int REVERSE_TYPE_EXCHANGE = 3; /** * 审核状态 0--未审核 */ public final static int AUDIT_STATUS_UNAUDITED = 0; /** * 审核状态 1--受理 */ public final static int AUDIT_STATUS_ACCEPTED = 1; /** * 审核状态 2--驳回 */ public final static int AUDIT_STATUS_REJECTED = 2; /** * 审核状态 3--已作废 */ public final static int AUDIT_STATUS_CANCELL = 3; /** * 审核状态 4--已审核已抛废单 */ public final static int AUDIT_STATUS_ACC_ABOILSH = 4; /** * 审核状态 5--废单通过 */ public final static int AUDIT_STATUS_ABOLISH_SUC = 5; /** * 审核状态 6--废单驳回 */ public final static int AUDIT_STATUS_ABOLISH_DEF = 6; /** * 反向订单状态 0--已申请 */ public final static int RE_STATUS_UNAUDITED = 0; /** * 反向订单状态 1--审核通过 */ public final static int RE_STATUS_ACCEPTED = 1; /** * 反向订单状态 2--审核拒绝 */ public final static int RE_STATUS_REJECTED = 2; /** * 反向订单状态 3--退款中 */ public final static int RE_STATUS_REFUNDING = 3; /** * 反向订单状态 44--换货中 */ public final static int RE_STATUS_EXCHANGEING = 4; /** * 反向订单状态 5--完成 */ public final static int RE_STATUS_COMPLETE = 5; /** * 反向订单状态 6--关单 */ public final static int RE_STATUS_CLOSE = 6; /** * 反向订单状态 10--撤单已申请 */ public final static int RE_STATUS_REVAPPLY = 10; /** * 反向订单状态 11--撤单已审核 */ public final static int RE_STATUS_REVAUDIT = 11; /** * 反向订单状态 12--撤单已驳回 */ public final static int RE_STATUS_REVREFUSE = 12; /** * 反向订单状态 20--退货已申请 */ public final static int RE_STATUS_RETAPPLY = 20; /** * 反向订单状态 21--退货已审核 */ public final static int RE_STATUS_RETAUDIT = 21; /** * 反向订单状态 22--退货已驳回 */ public final static int RE_STATUS_RETREFUSE = 22; /** * 反向订单状态 30--换货已申请 */ public final static int RE_STATUS_EXCHAPPLY = 30; /** * 反向订单状态 31--换货已审核 */ public final static int RE_STATUS_EXCAUDIT = 31; /** * 反向订单状态 32--换货已驳回 */ public final static int RE_STATUS_EXCREFUSE = 32; /** * 反向支付状态-1:已支付 */ public static final int RE_PAY_STATUS_COMP = 1; /** * 反向支付状态-2:退款中 */ public static final int RE_PAY_STATUS_REFUND = 2; /** * 反向支付状态- 3:已退款 */ public static final int RE_PAY_STATUS_REFUND_COMP = 3; /** * 反向订单关单 - 6 关单 */ public static final int AUDIT_STATUS_CLOSE = 6; /** * 反向、退款类型 */ public static final String TYPE_REVERSE = "reverse"; public static final String TYPE_REFUND = "refund"; public static final String TYPE_REAUDIT= "reAudit"; /** * 反向退货方式 */ public static final int REVERSE_WAY_ALL = 0; public static final int REVERSE_WAY_PARY = 1; private long id; private long orderId;//订单号 private String reason;//退换货原因 private long stockReturnId; //库存反向id private String category;//退换货分类 原因分类 private String description;//退换货原因文字描述 private Money amount;//退款小计 private Money refundManual;//手工返款 private Money personalizationAmount;//私人订制价格 //客户换货原因 private String csRedescription; private boolean complete;//包装是否齐全0:否 1:是 private int type;//1--撤单,2--退货,3--换货 private int auditStatus;//审批状态:0--待审批,1--审批通过,2--审批驳回,3--已作废,4废单申请,5 废单审核通过 6废单驳回 private String goodsCodes;//商品编号多个以”,”分割 private String goodsNames;//商品名称多个以”,”分割 private String sns;//SN多个以”,”分割 private String refuseReason;//驳回理由,审批驳回的时候必填 private String rApplyK;//供应链K码, 仅btcp使用 private String serviceMode;//服务方式,ZX16、ZX17 ””,仅btcp使用 private boolean throwing;//是否抛单 0:否 1:是 private String outId;//第三方订单号BtcpR号 private String remark;//备注 private int version; private String reLogisticsNo; private String reCompanyName; private String reCompanyCode; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Timestamp createTime; private String createBy; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Timestamp updateTime; private String updateBy; private String returnAddress; private boolean needReturnStock; private int outStatus; //退货时btcp推送的工厂收货通知.0--符合退款;1--不符合;2--关单 private Money transportFee; //垫付金额 private int preOrderStatus;//之前的订单状态 private boolean needExpress; private int reStatus; //反向状态 private int rePayStatus;//反向支付状态 private Integer shopId; private Main main; private ReverseDeliveryAddress deliveryAddress; private List<ReverseItem> items;//退换货item列表 private Refund refund; private Reverselogistics reverselogistics; private Tenant tenant; //租户对象 private List<String> fileUrl;//文件地址路径 private Money freight;//运费 private Money virtualCoin;//虚拟币数量 private String virtualCoinTradeNo;//虚拟币流水号 private Integer virtualCoinType;//虚拟币类型1 消费点 2 乐豆 private Integer reverseWay;//反向订单退货方式: 0:整单退 1:部分退 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date auditTime ; public Date getAuditTime() { return auditTime; } public void setAuditTime(Date auditTime) { this.auditTime = auditTime; } public Integer getReverseWay() { return reverseWay; } public void setReverseWay(Integer reverseWay) { this.reverseWay = reverseWay; } public Integer getShopId() { return shopId; } public void setShopId(Integer shopId) { this.shopId = shopId; } public Integer getVirtualCoinType() { return virtualCoinType; } public void setVirtualCoinType(Integer virtualCoinType) { this.virtualCoinType = virtualCoinType; } public String getVirtualCoinTradeNo() { return virtualCoinTradeNo; } public void setVirtualCoinTradeNo(String virtualCoinTradeNo) { this.virtualCoinTradeNo = virtualCoinTradeNo; } public Money getVirtualCoin() { return virtualCoin; } public void setVirtualCoin(Money virtualCoin) { this.virtualCoin = virtualCoin; } public Money getFreight() { return freight; } public void setFreight(Money freight) { this.freight = freight; } public boolean isNeedExpress() { return needExpress; } public void setNeedExpress(boolean needExpress) { this.needExpress = needExpress; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Money getAmount() { return amount; } public void setAmount(Money amount) { this.amount = amount; } public Money getRefundManual() { return refundManual; } public void setRefundManual(Money refundManual) { this.refundManual = refundManual; } public Money getPersonalizationAmount() { return personalizationAmount; } public void setPersonalizationAmount(Money personalizationAmount) { this.personalizationAmount = personalizationAmount; } public boolean isComplete() { return complete; } public void setComplete(boolean complete) { this.complete = complete; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getAuditStatus() { return auditStatus; } public void setAuditStatus(int auditStatus) { this.auditStatus = auditStatus; } public String getGoodsCodes() { return goodsCodes; } public void setGoodsCodes(String goodsCodes) { this.goodsCodes = goodsCodes; } public String getGoodsNames() { return goodsNames; } public void setGoodsNames(String goodsNames) { this.goodsNames = goodsNames; } public String getSns() { return sns; } public void setSns(String sns) { this.sns = sns; } public String getRefuseReason() { return refuseReason; } public void setRefuseReason(String refuseReason) { this.refuseReason = refuseReason; } public String getrApplyK() { return rApplyK; } public void setrApplyK(String rApplyK) { this.rApplyK = rApplyK; } public String getServiceMode() { return serviceMode; } public void setServiceMode(String serviceMode) { this.serviceMode = serviceMode; } public boolean isThrowing() { return throwing; } public void setThrowing(boolean throwing) { this.throwing = throwing; } public String getOutId() { return outId; } public void setOutId(String outId) { this.outId = outId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getOutStatus() { return outStatus; } public void setOutStatus(int outStatus) { this.outStatus = outStatus; } public Money getTransportFee() { return transportFee; } public void setTransportFee(Money transportFee) { this.transportFee = transportFee; } public Main getMain() { if (main == null) { main = new Main(); } return main; } public List<String> getFileUrl() { return fileUrl; } public void setFileUrl(List<String> fileUrl) { this.fileUrl = fileUrl; } public String getReLogisticsNo() { return reLogisticsNo; } public void setReLogisticsNo(String reLogisticsNo) { this.reLogisticsNo = reLogisticsNo; } public String getReCompanyName() { return reCompanyName; } public void setReCompanyName(String reCompanyName) { this.reCompanyName = reCompanyName; } public String getReCompanyCode() { return reCompanyCode; } public void setReCompanyCode(String reCompanyCode) { this.reCompanyCode = reCompanyCode; } public void setMain(Main main) { this.main = main; } public ReverseDeliveryAddress getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(ReverseDeliveryAddress deliveryAddress) { this.deliveryAddress = deliveryAddress; } public List<ReverseItem> getItems() { return items; } public void setItems(List<ReverseItem> items) { this.items = items; } public Reverse(Main main) { this.main = main; } public Refund getRefund() { if (refund == null) { refund = new Refund(); } return refund; } public void setRefund(Refund refund) { this.refund = refund; } public String getReturnAddress() { return returnAddress; } public void setReturnAddress(String returnAddress) { this.returnAddress = returnAddress; } public Reverse() { } public int getPreOrderStatus() { return preOrderStatus; } public void setPreOrderStatus(int preOrderStatus) { this.preOrderStatus = preOrderStatus; } public boolean isNeedReturnStock() { return needReturnStock; } public void setNeedReturnStock(boolean needReturnStock) { this.needReturnStock = needReturnStock; } public Reverselogistics getReverselogistics() { return reverselogistics; } public void setReverselogistics(Reverselogistics reverselogistics) { this.reverselogistics = reverselogistics; } public int getRePayStatus() { return rePayStatus; } public void setRePayStatus(int rePayStatus) { this.rePayStatus = rePayStatus; } public int getReStatus() { return reStatus; } public void setReStatus(int reStatus) { this.reStatus = reStatus; } public Tenant getTenant() { return tenant; } public void setTenant(Tenant tenant) { this.tenant = tenant; } public void genRApplyK() { if (rApplyKPrefixMap.get(main.getSource()) != null) { this.rApplyK = rApplyKPrefixMap.get(main.getSource()) + main.getId() + new DateTime().toString("MMdd") + new Random(System.currentTimeMillis()).nextInt(9999); } else { LOGGER.info("没有获取到订单来源:" + main.getSource()); rApplyK = "9999"; } } /** * 判断该订单是否可以撤单 */ // public RemoteResult isApplyRevoke(RemoteResult remoteResult) { // if (Main.ADD_TYPE_OTO == type) { // remoteResult.setResultMsg("订单类型为OTO , 不允许做撤单"); // remoteResult.setSuccess(false); // return remoteResult; // } else if (Main.FA_TYPE_RESELLERS == main.getFaType()) { // return remoteResult; // } else if ((Main.FA_TYPE_DIRECT == main.getFaType() || Main.FA_TYPE_DONGDE == main.getFaType() || Main.FA_TYPE_THINK_DIRECT == main.getFaType() || Main.FA_TYPE_MBG == main.getFaType() || Main.FA_TYPE_THINK_RESELLERS == main.getFaType()) && Main.STATUS_UN_SHIPPED == main.getStatus()) { // return remoteResult; // } else {//fa=1;fa(0,2,3,4)且未发货。这两种情况允许撤单 // remoteResult.setResultMsg("FATYPE为1或者为(0,2,3,4)且未发货。这两种情况允许撤单"); // remoteResult.setSuccess(false); // return remoteResult; // } // } /** * 校验退货申请入参 * * @return */ public RemoteResult validateApplyReturn() { RemoteResult remoteResult = new RemoteResult(); if (StringUtils.isEmpty(this.reason)) { remoteResult.setResultCode("1007"); remoteResult.setResultMsg("退货原因不能为空"); } else if(StringUtils.isEmpty(this.category)){ remoteResult.setResultCode("1008"); remoteResult.setResultMsg("退货分类不能为空"); }else { remoteResult.setSuccess(true); remoteResult.setResultCode("1000"); } return remoteResult; } @Override public String toString() { return "Reverse{" + "id=" + id + ", orderId=" + orderId + ", reason='" + reason + '\'' + ", category='" + category + '\'' + ", description='" + description + '\'' + ", complete=" + complete + ", type=" + type + ", auditStatus=" + auditStatus + ", goodsCodes='" + goodsCodes + '\'' + ", goodsNames='" + goodsNames + '\'' + ", sns='" + sns + '\'' + ", refuseReason='" + refuseReason + '\'' + ", rApplyK='" + rApplyK + '\'' + ", serviceMode='" + serviceMode + '\'' + ", throwing=" + throwing + ", outId='" + outId + '\'' + ", remark='" + remark + '\'' + ", version=" + version + ", createTime=" + createTime + ", createBy='" + createBy + '\'' + ", updateTime=" + updateTime + ", updateBy='" + updateBy + '\'' + ", reStatus='" + reStatus + '\'' + ", rePayStatus='" + rePayStatus + '\'' + ", returnAddress='" + returnAddress + '\'' + ", transportFee='" + transportFee + '\'' + ", returnAddress='" + +'\'' + ", main=" + main + ", deliveryAddress=" + deliveryAddress + ", items=" + items + ", refund=" + refund + '}'; } public long getStockReturnId() { return stockReturnId; } public void setStockReturnId(long stockReturnId) { this.stockReturnId = stockReturnId; } public String getCsRedescription() { return csRedescription; } public void setCsRedescription(String csRedescription) { this.csRedescription = csRedescription; } }
20,511
0.593345
0.584195
813
22.659286
22.977892
295
false
false
0
0
0
0
0
0
0.400984
false
false
12
a23ce539f66b785ac13e16f959e5933d9852e9f7
19,413,252,180,908
e6c205e3928c6375cbfb28b676ffd5b25a5da89c
/src/main/java/com/example/iam/model/Claim.java
6bfeba886b42addcebc1c60bf53a5710c09cf1ec
[]
no_license
mmnur/irm-iam-service
https://github.com/mmnur/irm-iam-service
ef3b67cb384997c7864ee9614ff571214cbbbe99
63cbc49d440e8aeaa8f55424bbc993475bb5f4b4
refs/heads/main
2023-03-01T19:53:20.721000
2021-02-05T22:10:26
2021-02-05T22:10:26
334,062,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.iam.model; import java.io.Serializable; /*@Entity @Table(name = "IamClaims")*/ public class Claim implements Serializable { private static final long serialVersionUID = -914403979669919502L; private String client_id; private String redirect_uri; private String ticket; public String getClient_id() { return client_id; } public void setClient_id(String client_id) { this.client_id = client_id; } public String getRedirect_uri() { return redirect_uri; } public void setRedirect_uri(String redirect_uri) { this.redirect_uri = redirect_uri; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } }
UTF-8
Java
703
java
Claim.java
Java
[]
null
[]
package com.example.iam.model; import java.io.Serializable; /*@Entity @Table(name = "IamClaims")*/ public class Claim implements Serializable { private static final long serialVersionUID = -914403979669919502L; private String client_id; private String redirect_uri; private String ticket; public String getClient_id() { return client_id; } public void setClient_id(String client_id) { this.client_id = client_id; } public String getRedirect_uri() { return redirect_uri; } public void setRedirect_uri(String redirect_uri) { this.redirect_uri = redirect_uri; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } }
703
0.731152
0.705548
33
20.333334
17.389769
67
false
false
0
0
0
0
0
0
1.272727
false
false
12
8f45c094c173b8e85aaaaa5b0c169180705e9518
19,413,252,180,553
bd9573c7290cae16554f437095e4bdf297dc078b
/learn-java8/src/main/java/com/dmh/learn/java/algorithm/sort/HeapSort.java
c5dcbd45a5ef8259a3545f28daf739bb65922e3d
[]
no_license
ronlygithub/dmh-learn
https://github.com/ronlygithub/dmh-learn
d285262c6c3b856cf18545732e782d19f0beb870
2ba006073e1dad8d69b04b3ed4249e378a3d6974
refs/heads/master
2018-11-29T09:18:55.783000
2018-11-08T01:15:54
2018-11-08T01:15:54
136,432,195
1
0
null
false
2019-11-13T08:46:20
2018-06-07T06:27:42
2019-11-12T12:29:02
2019-11-13T08:46:19
358
1
0
4
Java
false
false
package com.dmh.learn.java.algorithm.sort; /** * @author:duanmenghua * @descoription:堆排序 */ public class HeapSort<T extends Comparable<T>> extends AbstractSort { public HeapSort(T[] array) { this.array = array; this.n = array.length - 1; } public void sink(T[] data, int k, int n) { while (2*k<=n){ int j = 2*k; if (j<n && data[j].compareTo(data[j+1])<0){ j++; } if (data[k].compareTo(data[j])<0){ swap(data,k,j); } k=j; } } public void heapSort() { int len = array.length - 1; for (int k = array.length / 2; k >= 1; k--) { sink(array, k, n); } while (len > 1) { swap(array, 1, len--); sink(array, 1, len); } } @Override public void sort() { heapSort(); } @Override protected boolean check() { return check(array,1,array.length); } public void print(){ print(array,0,array.length); } private T[] array; private int n; }
UTF-8
Java
1,146
java
HeapSort.java
Java
[ { "context": "om.dmh.learn.java.algorithm.sort;\n\n/**\n * @author:duanmenghua\n * @descoription:堆排序\n */\npublic class HeapSort<T ", "end": 70, "score": 0.9817259907722473, "start": 59, "tag": "NAME", "value": "duanmenghua" } ]
null
[]
package com.dmh.learn.java.algorithm.sort; /** * @author:duanmenghua * @descoription:堆排序 */ public class HeapSort<T extends Comparable<T>> extends AbstractSort { public HeapSort(T[] array) { this.array = array; this.n = array.length - 1; } public void sink(T[] data, int k, int n) { while (2*k<=n){ int j = 2*k; if (j<n && data[j].compareTo(data[j+1])<0){ j++; } if (data[k].compareTo(data[j])<0){ swap(data,k,j); } k=j; } } public void heapSort() { int len = array.length - 1; for (int k = array.length / 2; k >= 1; k--) { sink(array, k, n); } while (len > 1) { swap(array, 1, len--); sink(array, 1, len); } } @Override public void sort() { heapSort(); } @Override protected boolean check() { return check(array,1,array.length); } public void print(){ print(array,0,array.length); } private T[] array; private int n; }
1,146
0.463158
0.450877
63
17.095238
16.867094
69
false
false
0
0
0
0
0
0
0.507937
false
false
12
f01785b06dc15e2c7298e1ebacd2ddad69fa846a
31,413,390,840,943
63d405cb320a1a933f545759e3a08324aeaad088
/src/main/java/Searches/BFS_Tracked.java
4bb53c004f13c9e604512601552a0ed8286640e9
[]
no_license
ElliotAlexander/intelligentsystems-blockworld
https://github.com/ElliotAlexander/intelligentsystems-blockworld
43ffad5b48b568c4119a06f2d09a494fc8356d61
a92fa586c51e49cc4d320454f3a6cd9a6fe58c43
refs/heads/master
2021-08-23T04:10:18.755000
2017-12-03T06:26:54
2017-12-03T06:26:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Searches; import Resources.Pair; import Utils.BoardOperations; import Utils.GoalStateChecker; import Utils.Logger; import java.util.HashMap; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; // This version of Searches.BFS is considerably slower, and uses a fair bit more memory, but will give steps // Rather than just find the solution. public class BFS_Tracked { private GoalStateChecker gsc; public BFS_Tracked(GoalStateChecker gsc){ this.gsc = gsc; } public void BFS(int[] startState) { HashMap<Pair, Pair> parents = new HashMap<>(); int nodes_expanded = 0; int depth = 0; Queue<Pair<int[], Integer>> q = new ArrayBlockingQueue<>(100000000); q.add(new Pair(startState, 0)); while (!(q.isEmpty())) { Pair<int[], Integer> p = q.poll(); nodes_expanded += 1; for (Integer i : BoardOperations.getNeighbours(p.val1)) { int[] newboard = BoardOperations.move_board(i, p.val1 ); Pair newPair = new Pair(newboard, p.val2 + 1); q.add(newPair); parents.put(newPair, p); // GOAL STATE if (gsc.checkGoalState(newboard)) { depth = p.val2 + 1; Logger.Log(Logger.Level.ESSENTIALINFO, "Nodes expanded: " + nodes_expanded); Logger.Log(Logger.Level.INFO, "Depth : " + depth); BoardOperations.printBoard(newboard, GoalStateChecker.N); Pair<int[], Integer> next = newPair; while(next != null){ Logger.Log("\n----- Start ---- \n"); BoardOperations.printBoard(next.val1, GoalStateChecker.N); next = parents.get(next); Logger.Log("\n----- End ----\n"); } return; } } } } }
UTF-8
Java
1,995
java
BFS_Tracked.java
Java
[]
null
[]
package Searches; import Resources.Pair; import Utils.BoardOperations; import Utils.GoalStateChecker; import Utils.Logger; import java.util.HashMap; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; // This version of Searches.BFS is considerably slower, and uses a fair bit more memory, but will give steps // Rather than just find the solution. public class BFS_Tracked { private GoalStateChecker gsc; public BFS_Tracked(GoalStateChecker gsc){ this.gsc = gsc; } public void BFS(int[] startState) { HashMap<Pair, Pair> parents = new HashMap<>(); int nodes_expanded = 0; int depth = 0; Queue<Pair<int[], Integer>> q = new ArrayBlockingQueue<>(100000000); q.add(new Pair(startState, 0)); while (!(q.isEmpty())) { Pair<int[], Integer> p = q.poll(); nodes_expanded += 1; for (Integer i : BoardOperations.getNeighbours(p.val1)) { int[] newboard = BoardOperations.move_board(i, p.val1 ); Pair newPair = new Pair(newboard, p.val2 + 1); q.add(newPair); parents.put(newPair, p); // GOAL STATE if (gsc.checkGoalState(newboard)) { depth = p.val2 + 1; Logger.Log(Logger.Level.ESSENTIALINFO, "Nodes expanded: " + nodes_expanded); Logger.Log(Logger.Level.INFO, "Depth : " + depth); BoardOperations.printBoard(newboard, GoalStateChecker.N); Pair<int[], Integer> next = newPair; while(next != null){ Logger.Log("\n----- Start ---- \n"); BoardOperations.printBoard(next.val1, GoalStateChecker.N); next = parents.get(next); Logger.Log("\n----- End ----\n"); } return; } } } } }
1,995
0.537845
0.52782
60
32.25
26.60553
108
false
false
0
0
0
0
0
0
0.75
false
false
12
8efbf0fad8eb2e348ecad1b408c56da2b5cc4cce
2,791,728,806,353
ef3576733dcb8949c27fa20b25fad5a38c872592
/src/java/ch/hearc/ig/odi/customeraccount/business/Customer.java
024b76e2e2b4cd5dfd266ea5b605584d30f68d75
[]
no_license
Tpower36/BankApp
https://github.com/Tpower36/BankApp
4070598d0845eadfd4ae7c4cad81b98d32c44770
f6ad2762ca8d005c0b53638ae52d1c55dae934ee
refs/heads/master
2016-08-12T10:51:46.102000
2015-12-03T07:53:52
2015-12-03T07:53:52
45,166,594
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.hearc.ig.odi.customeraccount.business; import java.util.*; /** * Cette classe nous permet de gérer le client * @author thierry.hubmann */ public class Customer { private List<Account> accounts; private int number; private String firstName; private String lastName; /** * * @param number * @param firstName * @param lastName */ public Customer(Integer number, String firstName, String lastName) { this.number = number; this.firstName = firstName; this.lastName = lastName; this.accounts = new ArrayList<>(); } /** * * @param number */ public Account getAccountByNumber(String number) { Account account = null; boolean found = false; int i = 0; while (!found && i <= accounts.size()) { if (accounts.get(i).getNumber().equals(number)) { found = true; account = accounts.get(i); } } if (!found) { throw new IllegalArgumentException("This account doesn't exist"); } return account; } public void addAccount(Account account) { accounts.add(account); } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
UTF-8
Java
1,851
java
Customer.java
Java
[ { "context": "e classe nous permet de gérer le client\n * @author thierry.hubmann\n */\npublic class Customer {\n\n private List<Acc", "end": 148, "score": 0.9990601539611816, "start": 133, "tag": "NAME", "value": "thierry.hubmann" } ]
null
[]
package ch.hearc.ig.odi.customeraccount.business; import java.util.*; /** * Cette classe nous permet de gérer le client * @author thierry.hubmann */ public class Customer { private List<Account> accounts; private int number; private String firstName; private String lastName; /** * * @param number * @param firstName * @param lastName */ public Customer(Integer number, String firstName, String lastName) { this.number = number; this.firstName = firstName; this.lastName = lastName; this.accounts = new ArrayList<>(); } /** * * @param number */ public Account getAccountByNumber(String number) { Account account = null; boolean found = false; int i = 0; while (!found && i <= accounts.size()) { if (accounts.get(i).getNumber().equals(number)) { found = true; account = accounts.get(i); } } if (!found) { throw new IllegalArgumentException("This account doesn't exist"); } return account; } public void addAccount(Account account) { accounts.add(account); } public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
1,851
0.575135
0.574595
85
20.77647
18.482027
77
false
false
0
0
0
0
0
0
0.329412
false
false
12
4d40bc99b27fed536fe815b961d38844f53a75b1
8,589,934,646,082
2c00b9c4ec9fca85833a0d47ed39a16a31d272c0
/Java/LC40.java
8fe5a54fef15c24414e957df48bce0674158b301
[]
no_license
oily126/Leetcode
https://github.com/oily126/Leetcode
fff8d00ab41e338a02adc821b19b58d2ce9db6ad
23393768ab1fae704ac753290d7ea36ce2c3c0c6
refs/heads/master
2020-04-16T02:16:22.847000
2016-11-25T04:34:05
2016-11-25T04:34:05
64,791,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { int[] arr = new int[candidates.length]; Arrays.sort(candidates); return helper(0, candidates, target, arr, 0); } public List<List<Integer>> helper(int index, int[] candidates, int target, int[] arr, int len) { int i, next; if (target == 0) { List<List<Integer>> tmp = new ArrayList<>(); List<Integer> tmp1 = new ArrayList<>(); for (i = 0; i < len; i++) tmp1.add(candidates[arr[i]]); tmp.add(tmp1); return tmp; } List<List<Integer>> ans = new ArrayList<>(); if (index >= candidates.length || target < candidates[index]) return new ArrayList<List<Integer>>(); for (i = index; i < candidates.length; i++) { if (candidates[index] != candidates[i]) break; } next = i; ans.addAll(helper(next, candidates, target, arr, len)); for (i = index; i < next; i++) { if (target >= candidates[index]) { target -= candidates[index]; arr[len++] = i; ans.addAll(helper(next, candidates, target, arr, len)); } else break; } return ans; } }
UTF-8
Java
1,338
java
LC40.java
Java
[]
null
[]
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { int[] arr = new int[candidates.length]; Arrays.sort(candidates); return helper(0, candidates, target, arr, 0); } public List<List<Integer>> helper(int index, int[] candidates, int target, int[] arr, int len) { int i, next; if (target == 0) { List<List<Integer>> tmp = new ArrayList<>(); List<Integer> tmp1 = new ArrayList<>(); for (i = 0; i < len; i++) tmp1.add(candidates[arr[i]]); tmp.add(tmp1); return tmp; } List<List<Integer>> ans = new ArrayList<>(); if (index >= candidates.length || target < candidates[index]) return new ArrayList<List<Integer>>(); for (i = index; i < candidates.length; i++) { if (candidates[index] != candidates[i]) break; } next = i; ans.addAll(helper(next, candidates, target, arr, len)); for (i = index; i < next; i++) { if (target >= candidates[index]) { target -= candidates[index]; arr[len++] = i; ans.addAll(helper(next, candidates, target, arr, len)); } else break; } return ans; } }
1,338
0.511958
0.505979
36
36.194443
22.759394
79
false
false
0
0
0
0
0
0
1.25
false
false
12
861767f34db31243be771a2a10cc3c111ba50d15
19,052,474,947,897
f7403cd9be3a012df3d08c278cd7de23b8b4dbc7
/src/compilador/semantico/declaracoes/DeclaracaoDeLabels.java
1feee42128c0d714bda7bc0a2680e2254fdb4485
[]
no_license
Franciscomaz/compilador
https://github.com/Franciscomaz/compilador
f0fd080b74cbdd50251213eb12f5f219df06a492
2cdde16024c9facbcc2cb19cf8f0bd21c30b42d7
refs/heads/master
2021-04-09T14:53:47.959000
2018-07-09T23:11:24
2018-07-09T23:11:24
125,762,746
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package compilador.semantico.declaracoes; import compilador.Identificador.Label; import compilador.semantico.ErroSemantico; import compilador.semantico.Escopo.Escopo; import compilador.token.Token; import java.util.Stack; public class DeclaracaoDeLabels extends DeclaracaoDeIdentificadores { public DeclaracaoDeLabels(Stack<Token> tokens) { super(tokens); } @Override protected void ler(Token token, Escopo escopo) throws ErroSemantico { if(token.isIdentificador()){ escopo.adicionarIdentificador(new Label(token)); } } }
UTF-8
Java
582
java
DeclaracaoDeLabels.java
Java
[]
null
[]
package compilador.semantico.declaracoes; import compilador.Identificador.Label; import compilador.semantico.ErroSemantico; import compilador.semantico.Escopo.Escopo; import compilador.token.Token; import java.util.Stack; public class DeclaracaoDeLabels extends DeclaracaoDeIdentificadores { public DeclaracaoDeLabels(Stack<Token> tokens) { super(tokens); } @Override protected void ler(Token token, Escopo escopo) throws ErroSemantico { if(token.isIdentificador()){ escopo.adicionarIdentificador(new Label(token)); } } }
582
0.743986
0.743986
21
26.714285
23.472664
73
false
false
0
0
0
0
0
0
0.428571
false
false
12
853b972048a5fafbfd59ed3a6b871741e174d313
7,078,106,135,382
7fecb2f17802acaa2f66825e969d5d9bab078964
/automation/src/main/java/Util/RestTestUtil.java
78aa1a0b86e0af30a692b622d55cb677e9cc0b28
[]
no_license
mufleh-ahmad/testing
https://github.com/mufleh-ahmad/testing
7f8c7ca4a7435ee9ee681c62c8cb23040ca428ca
57fd1d1741c77ef1176b882adfaf6f18126ea05e
refs/heads/master
2022-12-27T04:47:24.827000
2019-06-17T11:29:54
2019-06-17T11:29:54
157,117,441
0
0
null
false
2022-12-09T22:14:24
2018-11-11T20:18:47
2019-06-17T11:30:18
2022-12-09T22:14:21
37
0
0
4
Java
false
false
package Util; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; /** * Created by Mufleh on 24/03/2019. */ public class RestTestUtil { RestTemplate restTemplate = new RestTemplate(); public ResponseEntity postEntity (final String url, final String body){ HttpHeaders headers = new HttpHeaders(); headers.add("Authorization",""); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(body,headers); return restTemplate.exchange(url, HttpMethod.POST,request,String.class); } public <T> T get(final String url, Class<T> responseType){ HttpHeaders headers = new HttpHeaders(); headers.add("Authorization",""); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(headers); ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET,request,responseType); return response.getBody(); } }
UTF-8
Java
1,016
java
RestTestUtil.java
Java
[ { "context": "mework.web.client.RestTemplate;\n\n/**\n * Created by Mufleh on 24/03/2019.\n */\npublic class RestTestUtil {\n\n ", "end": 127, "score": 0.9936656951904297, "start": 121, "tag": "USERNAME", "value": "Mufleh" } ]
null
[]
package Util; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; /** * Created by Mufleh on 24/03/2019. */ public class RestTestUtil { RestTemplate restTemplate = new RestTemplate(); public ResponseEntity postEntity (final String url, final String body){ HttpHeaders headers = new HttpHeaders(); headers.add("Authorization",""); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(body,headers); return restTemplate.exchange(url, HttpMethod.POST,request,String.class); } public <T> T get(final String url, Class<T> responseType){ HttpHeaders headers = new HttpHeaders(); headers.add("Authorization",""); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity(headers); ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET,request,responseType); return response.getBody(); } }
1,016
0.699803
0.691929
30
32.866665
28.528036
101
false
false
0
0
0
0
0
0
0.866667
false
false
12
c3ca7ec9a7507d23bffaeefe4a1841ec8803b42e
17,652,315,632,170
e165c564437348c9bfcc5755ed6de40cbbd38882
/algorithm/dynamic programming/Success/waysOfSum3.java
928827f8cda961c33441081c3427e4375fb7c526
[]
no_license
LoveMoye/AlgorithmStudy
https://github.com/LoveMoye/AlgorithmStudy
a2fea280c79df1a1d587db6ebfbbcac58cd009ab
bc619d5b372665326200e2a50139855987b6ea6d
refs/heads/main
2023-03-04T16:24:41.426000
2021-02-19T14:51:51
2021-02-19T14:51:51
330,628,142
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DP.Success; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class waysOfSum3 { static long[] d = new long[1000001]; static int mod = 1000000009; static int prev = 1; static long waysOfSum(int k) { if(d[k] <= 0) { return d[k]; } else { for (int i = prev + 1; i >= k + 1; i++) { for(int j=1;j<=3;j++) { if(i >= j) { d[i] += (d[i-j] % mod); } } d[i] %= mod; } return d[k]; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int k = Integer.parseInt(br.readLine()); int l; d[0] = d[1] = 1; while(k-- > 0) { l = Integer.parseInt(br.readLine()); sb.append(waysOfSum(l)); if(prev < l) { prev = l; } sb.append('\n'); } System.out.println(sb); } }
UTF-8
Java
1,184
java
waysOfSum3.java
Java
[]
null
[]
package DP.Success; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class waysOfSum3 { static long[] d = new long[1000001]; static int mod = 1000000009; static int prev = 1; static long waysOfSum(int k) { if(d[k] <= 0) { return d[k]; } else { for (int i = prev + 1; i >= k + 1; i++) { for(int j=1;j<=3;j++) { if(i >= j) { d[i] += (d[i-j] % mod); } } d[i] %= mod; } return d[k]; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int k = Integer.parseInt(br.readLine()); int l; d[0] = d[1] = 1; while(k-- > 0) { l = Integer.parseInt(br.readLine()); sb.append(waysOfSum(l)); if(prev < l) { prev = l; } sb.append('\n'); } System.out.println(sb); } }
1,184
0.451858
0.428209
46
24.73913
17.759792
81
false
false
0
0
0
0
0
0
0.543478
false
false
12
9bbbdb484b24a364c52aeb23752af76cb726f840
33,071,248,191,471
54c10fc23298d9921b023809879883d8654e62a7
/src/main/java/com/xwq/example/MongoApp4.java
f3b13005613104e6b0cea9a979092ff56af0a213
[]
no_license
wendrewshay/MySpringDataMongoDB
https://github.com/wendrewshay/MySpringDataMongoDB
4c6012d92a36504158be87200e8d072bcba18a6b
e9af4e1a3c55f4a3e938549a23bfed129c56284f
refs/heads/master
2021-01-22T20:08:23.714000
2017-03-19T08:36:13
2017-03-19T08:36:13
85,283,855
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xwq.example; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.ExampleMatcher.StringMatcher; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import com.mongodb.MongoClient; import com.xwq.dao.MyExampleRepository; import com.xwq.domain.Person2; /** * Example查询 * @author Think * */ public class MongoApp4 { public static void main(String[] args) { MongoTemplate template = new MongoTemplate(new SimpleMongoDbFactory(new MongoClient(), "MyMongo")); Person2 person2 = new Person2(); person2.setFirstname("Dave"); template.insert(person2); ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("firstname", match -> match.endsWith()) .withMatcher("firstname", match -> match.startsWith()); // .withIgnorePaths("lastname") // .withIncludeNullValues() // .withStringMatcher(StringMatcher.ENDING); Example<Person2> example = Example.of(person2, exampleMatcher); } }
UTF-8
Java
1,108
java
MongoApp4.java
Java
[ { "context": "m.xwq.domain.Person2;\n\n/**\n * Example查询\n * @author Think\n *\n */\npublic class MongoApp4 {\n\n\tpublic static v", "end": 463, "score": 0.7279765009880066, "start": 458, "tag": "USERNAME", "value": "Think" }, { "context": " person2 = new Person2();\n\t\tperson2.setFirstname(\"Dave\");\n\t\ttemplate.insert(person2);\n\t\t\n\t\tExampleMatche", "end": 707, "score": 0.9997677206993103, "start": 703, "tag": "NAME", "value": "Dave" } ]
null
[]
package com.xwq.example; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.ExampleMatcher.StringMatcher; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import com.mongodb.MongoClient; import com.xwq.dao.MyExampleRepository; import com.xwq.domain.Person2; /** * Example查询 * @author Think * */ public class MongoApp4 { public static void main(String[] args) { MongoTemplate template = new MongoTemplate(new SimpleMongoDbFactory(new MongoClient(), "MyMongo")); Person2 person2 = new Person2(); person2.setFirstname("Dave"); template.insert(person2); ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("firstname", match -> match.endsWith()) .withMatcher("firstname", match -> match.startsWith()); // .withIgnorePaths("lastname") // .withIncludeNullValues() // .withStringMatcher(StringMatcher.ENDING); Example<Person2> example = Example.of(person2, exampleMatcher); } }
1,108
0.765399
0.757246
37
28.837837
25.825312
101
false
false
0
0
0
0
0
0
1.513514
false
false
12
e67f3d05b5baa00c09ff3f8bf2040cddcca97ab9
3,693,671,878,854
1c3a0a8940a85700551487a2d57f70a5d02ccece
/.metadata/.plugins/org.eclipse.core.resources/.history/b5/50a25872192f00191fdaaf86e28e8382
b8acda3441e57134409c3edc73c972ab154b3104
[]
no_license
magick93/xtext
https://github.com/magick93/xtext
fb2cb710ae93c1e8f9a1f21e843c28f00a0f86e0
0528aa7ed3867c8e78f3d16b2960a80c07c4b448
refs/heads/master
2020-04-22T13:27:19.738000
2019-02-15T01:48:20
2019-02-15T01:48:20
170,410,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** */ package sculptormetamodel; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Inheritance</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorColumnName <em>Discriminator Column Name</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorColumnLength <em>Discriminator Column Length</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getType <em>Type</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorType <em>Discriminator Type</em>}</li> * </ul> * * @see sculptormetamodel.SculptormetamodelPackage#getInheritance() * @model * @generated */ public interface Inheritance extends EObject { /** * Returns the value of the '<em><b>Discriminator Column Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Column Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Column Name</em>' attribute. * @see #setDiscriminatorColumnName(String) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorColumnName() * @model unique="false" * @generated */ String getDiscriminatorColumnName(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorColumnName <em>Discriminator Column Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Column Name</em>' attribute. * @see #getDiscriminatorColumnName() * @generated */ void setDiscriminatorColumnName(String value); /** * Returns the value of the '<em><b>Discriminator Column Length</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Column Length</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Column Length</em>' attribute. * @see #setDiscriminatorColumnLength(String) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorColumnLength() * @model unique="false" * @generated */ String getDiscriminatorColumnLength(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorColumnLength <em>Discriminator Column Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Column Length</em>' attribute. * @see #getDiscriminatorColumnLength() * @generated */ void setDiscriminatorColumnLength(String value); /** * Returns the value of the '<em><b>Type</b></em>' attribute. * The literals are from the enumeration {@link sculptormetamodel.InheritanceType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see sculptormetamodel.InheritanceType * @see #setType(InheritanceType) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_Type() * @model unique="false" * @generated */ InheritanceType getType(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see sculptormetamodel.InheritanceType * @see #getType() * @generated */ void setType(InheritanceType value); /** * Returns the value of the '<em><b>Discriminator Type</b></em>' attribute. * The literals are from the enumeration {@link sculptormetamodel.DiscriminatorType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Type</em>' attribute. * @see sculptormetamodel.DiscriminatorType * @see #setDiscriminatorType(DiscriminatorType) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorType() * @model unique="false" * @generated */ DiscriminatorType getDiscriminatorType(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorType <em>Discriminator Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Type</em>' attribute. * @see sculptormetamodel.DiscriminatorType * @see #getDiscriminatorType() * @generated */ void setDiscriminatorType(DiscriminatorType value); } // Inheritance
UTF-8
Java
4,968
50a25872192f00191fdaaf86e28e8382
Java
[]
null
[]
/** */ package sculptormetamodel; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Inheritance</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorColumnName <em>Discriminator Column Name</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorColumnLength <em>Discriminator Column Length</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getType <em>Type</em>}</li> * <li>{@link sculptormetamodel.Inheritance#getDiscriminatorType <em>Discriminator Type</em>}</li> * </ul> * * @see sculptormetamodel.SculptormetamodelPackage#getInheritance() * @model * @generated */ public interface Inheritance extends EObject { /** * Returns the value of the '<em><b>Discriminator Column Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Column Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Column Name</em>' attribute. * @see #setDiscriminatorColumnName(String) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorColumnName() * @model unique="false" * @generated */ String getDiscriminatorColumnName(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorColumnName <em>Discriminator Column Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Column Name</em>' attribute. * @see #getDiscriminatorColumnName() * @generated */ void setDiscriminatorColumnName(String value); /** * Returns the value of the '<em><b>Discriminator Column Length</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Column Length</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Column Length</em>' attribute. * @see #setDiscriminatorColumnLength(String) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorColumnLength() * @model unique="false" * @generated */ String getDiscriminatorColumnLength(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorColumnLength <em>Discriminator Column Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Column Length</em>' attribute. * @see #getDiscriminatorColumnLength() * @generated */ void setDiscriminatorColumnLength(String value); /** * Returns the value of the '<em><b>Type</b></em>' attribute. * The literals are from the enumeration {@link sculptormetamodel.InheritanceType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see sculptormetamodel.InheritanceType * @see #setType(InheritanceType) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_Type() * @model unique="false" * @generated */ InheritanceType getType(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see sculptormetamodel.InheritanceType * @see #getType() * @generated */ void setType(InheritanceType value); /** * Returns the value of the '<em><b>Discriminator Type</b></em>' attribute. * The literals are from the enumeration {@link sculptormetamodel.DiscriminatorType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Discriminator Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Discriminator Type</em>' attribute. * @see sculptormetamodel.DiscriminatorType * @see #setDiscriminatorType(DiscriminatorType) * @see sculptormetamodel.SculptormetamodelPackage#getInheritance_DiscriminatorType() * @model unique="false" * @generated */ DiscriminatorType getDiscriminatorType(); /** * Sets the value of the '{@link sculptormetamodel.Inheritance#getDiscriminatorType <em>Discriminator Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Discriminator Type</em>' attribute. * @see sculptormetamodel.DiscriminatorType * @see #getDiscriminatorType() * @generated */ void setDiscriminatorType(DiscriminatorType value); } // Inheritance
4,968
0.691023
0.691023
137
35.262775
33.361603
142
false
false
0
0
0
0
0
0
0.846715
false
false
12
9c62742cf01b5fa2911b57f4b37e0c40373b417a
32,787,780,382,858
f5f995db63455e6546bf05942acc18898cbfff7d
/Solitaire/src/app/Window.java
73001dadc1a90dad0535b050ca19d9b68ec6d1ad
[]
no_license
maniman303/Java-projects
https://github.com/maniman303/Java-projects
73b04be6ecb60eaeffbcff24858341e3eea52137
1b714557276b36b018328d360aa3f6ece87aa906
refs/heads/main
2023-02-19T22:21:45.586000
2021-01-17T20:04:13
2021-01-17T20:04:13
330,474,104
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; import mechanic.Game; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.KeyEvent; public class Window extends JFrame { static JLabel label; static Color pawnColor; static Color boardColor; static boolean fillPawn; private Panel panel; private boolean european; private JMenuItem jumpUp; private JMenuItem jumpLeft; private JMenuItem jumpRight; private JMenuItem jumpDown; private JRadioButtonMenuItem eu; private JRadioButtonMenuItem br; private ButtonGroup group; public Window() { super("Solitaire"); pawnColor = Color.RED; boardColor = Color.WHITE; fillPawn = true; european = false; JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu moves = new JMenu("Moves"); JMenu settings = new JMenu("Settings"); JMenu help = new JMenu("Help"); file.setMnemonic(KeyEvent.VK_F); moves.setMnemonic(KeyEvent.VK_M); moves.addMenuListener(new MovesMenuListener()); settings.setMnemonic(KeyEvent.VK_S); settings.addMenuListener(new SettingsMenuListener()); help.setMnemonic(KeyEvent.VK_H); menuBar.add(file); menuBar.add(moves); menuBar.add(settings); menuBar.add(Box.createGlue()); menuBar.add(help); initFile(file); initMoves(moves); initSettings(settings); initHelp(help); panel = new Panel(); label = new JLabel(" "); setJMenuBar(menuBar); add(panel, BorderLayout.CENTER); add(label, BorderLayout.PAGE_END); setMinimumSize(new Dimension(400, 460)); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private void initFile(JMenu f) { JMenuItem newGame = new JMenuItem("New Game"); JMenuItem exit = new JMenuItem("Exit"); f.add(newGame); f.addSeparator(); f.add(exit); newGame.addActionListener(e -> { Main.game = new Game(european); label.setText(" "); panel.checkMap(); }); exit.addActionListener(e -> System.exit(0)); } private void initMoves(JMenu m) { JMenuItem reset = new JMenuItem("Reset focus"); JMenuItem goUp = new JMenuItem("Move up"); JMenuItem goLeft = new JMenuItem("Move left"); JMenuItem goRight = new JMenuItem("Move right"); JMenuItem goDown = new JMenuItem("Move down"); jumpUp = new JMenuItem("Jump up"); jumpLeft = new JMenuItem("Jump left"); jumpRight = new JMenuItem("Jump right"); jumpDown = new JMenuItem("Jump down"); reset.setAccelerator(KeyStroke.getKeyStroke("control R")); goUp.setAccelerator(KeyStroke.getKeyStroke("control W")); goLeft.setAccelerator(KeyStroke.getKeyStroke("control A")); goRight.setAccelerator(KeyStroke.getKeyStroke("control D")); goDown.setAccelerator(KeyStroke.getKeyStroke("control S")); jumpUp.setAccelerator(KeyStroke.getKeyStroke("control shift W")); jumpLeft.setAccelerator(KeyStroke.getKeyStroke("control shift A")); jumpRight.setAccelerator(KeyStroke.getKeyStroke("control shift D")); jumpDown.setAccelerator(KeyStroke.getKeyStroke("control shift S")); m.add(reset); m.add(goUp); m.add(goLeft); m.add(goRight); m.add(goDown); m.addSeparator(); m.add(jumpUp); m.add(jumpLeft); m.add(jumpRight); m.add(jumpDown); reset.addActionListener(e -> panel.resetFocus()); goUp.addActionListener(e -> panel.moveFocus(2)); goLeft.addActionListener(e -> panel.moveFocus(1)); goRight.addActionListener(e -> panel.moveFocus(3)); goDown.addActionListener(e -> panel.moveFocus(4)); jumpUp.addActionListener(e -> panel.jumpFocus(2)); jumpLeft.addActionListener(e -> panel.jumpFocus(1)); jumpRight.addActionListener(e -> panel.jumpFocus(3)); jumpDown.addActionListener(e -> panel.jumpFocus(4)); } private void initSettings(JMenu s) { eu = new JRadioButtonMenuItem("European"); br = new JRadioButtonMenuItem("British"); JMenuItem boardColor = new JMenuItem("Board color"); JMenuItem pawnColor = new JMenuItem("Pawn color"); JCheckBoxMenuItem fill = new JCheckBoxMenuItem("Fill pawns"); group = new ButtonGroup(); group.add(br); group.add(eu); br.setSelected(true); fill.setSelected(true); s.add(br); s.add(eu); s.addSeparator(); s.add(boardColor); s.add(pawnColor); s.add(fill); br.addActionListener(e -> { european = false; Main.game = new Game(false); label.setText(" "); panel.checkMap(); }); eu.addActionListener(e -> { european = true; Main.game = new Game(true); label.setText(" "); panel.checkMap(); }); boardColor.addActionListener(e -> { this.boardColor = JColorChooser.showDialog(null, "Choose a board color", this.boardColor); panel.checkMap(); }); pawnColor.addActionListener(e -> { this.pawnColor = JColorChooser.showDialog(null, "Choose a board color", this.pawnColor); panel.checkMap(); }); fill.addActionListener(e -> { fillPawn = !fillPawn; panel.checkMap(); }); } private void initHelp(JMenu h) { JMenuItem app = new JMenuItem("Application"); JMenuItem rules = new JMenuItem("Rules"); h.add(app); h.add(rules); app.addActionListener(e -> JOptionPane.showMessageDialog(null, "Solitaire\nAuthor: Michał Wójtowicz\nVersion: 1.0\nDate: 27.11.2020", "Application", JOptionPane.INFORMATION_MESSAGE)); rules.addActionListener(e -> JOptionPane.showMessageDialog(null, "The goal is to leave only one peg on the board by jumping diagonally over other pegs to empty spaces.", "Rules", JOptionPane.INFORMATION_MESSAGE)); } class MovesMenuListener implements MenuListener { public void menuSelected(MenuEvent e) { int f = panel.getFocus(); jumpLeft.setEnabled(false); jumpUp.setEnabled(false); jumpRight.setEnabled(false); jumpDown.setEnabled(false); if (f >= 1 && f <= 49) { if (Main.game.getLeft(f)) jumpLeft.setEnabled(true); if (Main.game.getRight(f)) jumpRight.setEnabled(true); if (Main.game.getUp(f)) jumpUp.setEnabled(true); if (Main.game.getDown(f)) jumpDown.setEnabled(true); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } } class SettingsMenuListener implements MenuListener { public void menuSelected(MenuEvent e) { br.setEnabled(false); eu.setEnabled(false); if (Main.game.getFinish() || !Main.game.getStarted()) { br.setEnabled(true); eu.setEnabled(true); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } } }
UTF-8
Java
7,762
java
Window.java
Java
[ { "context": "onPane.showMessageDialog(null, \"Solitaire\\nAuthor: Michał Wójtowicz\\nVersion: 1.0\\nDate: 27.11.2020\", \"Application\", ", "end": 6169, "score": 0.9998871088027954, "start": 6153, "tag": "NAME", "value": "Michał Wójtowicz" } ]
null
[]
package app; import mechanic.Game; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.KeyEvent; public class Window extends JFrame { static JLabel label; static Color pawnColor; static Color boardColor; static boolean fillPawn; private Panel panel; private boolean european; private JMenuItem jumpUp; private JMenuItem jumpLeft; private JMenuItem jumpRight; private JMenuItem jumpDown; private JRadioButtonMenuItem eu; private JRadioButtonMenuItem br; private ButtonGroup group; public Window() { super("Solitaire"); pawnColor = Color.RED; boardColor = Color.WHITE; fillPawn = true; european = false; JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu moves = new JMenu("Moves"); JMenu settings = new JMenu("Settings"); JMenu help = new JMenu("Help"); file.setMnemonic(KeyEvent.VK_F); moves.setMnemonic(KeyEvent.VK_M); moves.addMenuListener(new MovesMenuListener()); settings.setMnemonic(KeyEvent.VK_S); settings.addMenuListener(new SettingsMenuListener()); help.setMnemonic(KeyEvent.VK_H); menuBar.add(file); menuBar.add(moves); menuBar.add(settings); menuBar.add(Box.createGlue()); menuBar.add(help); initFile(file); initMoves(moves); initSettings(settings); initHelp(help); panel = new Panel(); label = new JLabel(" "); setJMenuBar(menuBar); add(panel, BorderLayout.CENTER); add(label, BorderLayout.PAGE_END); setMinimumSize(new Dimension(400, 460)); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private void initFile(JMenu f) { JMenuItem newGame = new JMenuItem("New Game"); JMenuItem exit = new JMenuItem("Exit"); f.add(newGame); f.addSeparator(); f.add(exit); newGame.addActionListener(e -> { Main.game = new Game(european); label.setText(" "); panel.checkMap(); }); exit.addActionListener(e -> System.exit(0)); } private void initMoves(JMenu m) { JMenuItem reset = new JMenuItem("Reset focus"); JMenuItem goUp = new JMenuItem("Move up"); JMenuItem goLeft = new JMenuItem("Move left"); JMenuItem goRight = new JMenuItem("Move right"); JMenuItem goDown = new JMenuItem("Move down"); jumpUp = new JMenuItem("Jump up"); jumpLeft = new JMenuItem("Jump left"); jumpRight = new JMenuItem("Jump right"); jumpDown = new JMenuItem("Jump down"); reset.setAccelerator(KeyStroke.getKeyStroke("control R")); goUp.setAccelerator(KeyStroke.getKeyStroke("control W")); goLeft.setAccelerator(KeyStroke.getKeyStroke("control A")); goRight.setAccelerator(KeyStroke.getKeyStroke("control D")); goDown.setAccelerator(KeyStroke.getKeyStroke("control S")); jumpUp.setAccelerator(KeyStroke.getKeyStroke("control shift W")); jumpLeft.setAccelerator(KeyStroke.getKeyStroke("control shift A")); jumpRight.setAccelerator(KeyStroke.getKeyStroke("control shift D")); jumpDown.setAccelerator(KeyStroke.getKeyStroke("control shift S")); m.add(reset); m.add(goUp); m.add(goLeft); m.add(goRight); m.add(goDown); m.addSeparator(); m.add(jumpUp); m.add(jumpLeft); m.add(jumpRight); m.add(jumpDown); reset.addActionListener(e -> panel.resetFocus()); goUp.addActionListener(e -> panel.moveFocus(2)); goLeft.addActionListener(e -> panel.moveFocus(1)); goRight.addActionListener(e -> panel.moveFocus(3)); goDown.addActionListener(e -> panel.moveFocus(4)); jumpUp.addActionListener(e -> panel.jumpFocus(2)); jumpLeft.addActionListener(e -> panel.jumpFocus(1)); jumpRight.addActionListener(e -> panel.jumpFocus(3)); jumpDown.addActionListener(e -> panel.jumpFocus(4)); } private void initSettings(JMenu s) { eu = new JRadioButtonMenuItem("European"); br = new JRadioButtonMenuItem("British"); JMenuItem boardColor = new JMenuItem("Board color"); JMenuItem pawnColor = new JMenuItem("Pawn color"); JCheckBoxMenuItem fill = new JCheckBoxMenuItem("Fill pawns"); group = new ButtonGroup(); group.add(br); group.add(eu); br.setSelected(true); fill.setSelected(true); s.add(br); s.add(eu); s.addSeparator(); s.add(boardColor); s.add(pawnColor); s.add(fill); br.addActionListener(e -> { european = false; Main.game = new Game(false); label.setText(" "); panel.checkMap(); }); eu.addActionListener(e -> { european = true; Main.game = new Game(true); label.setText(" "); panel.checkMap(); }); boardColor.addActionListener(e -> { this.boardColor = JColorChooser.showDialog(null, "Choose a board color", this.boardColor); panel.checkMap(); }); pawnColor.addActionListener(e -> { this.pawnColor = JColorChooser.showDialog(null, "Choose a board color", this.pawnColor); panel.checkMap(); }); fill.addActionListener(e -> { fillPawn = !fillPawn; panel.checkMap(); }); } private void initHelp(JMenu h) { JMenuItem app = new JMenuItem("Application"); JMenuItem rules = new JMenuItem("Rules"); h.add(app); h.add(rules); app.addActionListener(e -> JOptionPane.showMessageDialog(null, "Solitaire\nAuthor: <NAME>\nVersion: 1.0\nDate: 27.11.2020", "Application", JOptionPane.INFORMATION_MESSAGE)); rules.addActionListener(e -> JOptionPane.showMessageDialog(null, "The goal is to leave only one peg on the board by jumping diagonally over other pegs to empty spaces.", "Rules", JOptionPane.INFORMATION_MESSAGE)); } class MovesMenuListener implements MenuListener { public void menuSelected(MenuEvent e) { int f = panel.getFocus(); jumpLeft.setEnabled(false); jumpUp.setEnabled(false); jumpRight.setEnabled(false); jumpDown.setEnabled(false); if (f >= 1 && f <= 49) { if (Main.game.getLeft(f)) jumpLeft.setEnabled(true); if (Main.game.getRight(f)) jumpRight.setEnabled(true); if (Main.game.getUp(f)) jumpUp.setEnabled(true); if (Main.game.getDown(f)) jumpDown.setEnabled(true); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } } class SettingsMenuListener implements MenuListener { public void menuSelected(MenuEvent e) { br.setEnabled(false); eu.setEnabled(false); if (Main.game.getFinish() || !Main.game.getStarted()) { br.setEnabled(true); eu.setEnabled(true); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } } }
7,750
0.585696
0.582088
204
36.039215
25.655876
221
false
false
0
0
0
0
0
0
0.833333
false
false
12
69bd6962dccfd4ad76f1a7a4da8d8f7a0bfb972f
24,867,860,656,314
97ead6dfbe1a6b569be08f7cd247161bc0a73121
/persistence/hbase/src/main/java/com/redshape/persistence/dao/serialization/visitors/URIVisitor.java
25781ac06979b32f8f58e2ff40c14c9311d914f2
[ "Apache-2.0" ]
permissive
Redshape/Redshape-AS
https://github.com/Redshape/Redshape-AS
19f54bc0d54061b0302a7b3f63e600afb01168ea
cf3492919a35b868bc7045b35d38e74a3a2b8c01
refs/heads/master
2021-01-17T05:17:31.881000
2012-09-05T13:49:50
2012-09-05T13:49:50
1,390,510
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.redshape.persistence.dao.serialization.visitors; import com.redshape.persistence.dao.serialization.AbstractSerializerVisitor; import org.apache.hadoop.hbase.util.Bytes; import java.net.URI; public class URIVisitor extends AbstractSerializerVisitor { @Override public byte[] serialize(Object object) { if (object == null || object.getClass() != getEntityType()) return null; URI uri = (URI) object; return Bytes.toBytes(uri.toString()); } @Override public Object deserialize(byte[] value) { if (value == null) return null; String uri = Bytes.toString(value); return URI.create(uri); } @Override public Class<?> getEntityType() { return URI.class; } }
UTF-8
Java
789
java
URIVisitor.java
Java
[]
null
[]
package com.redshape.persistence.dao.serialization.visitors; import com.redshape.persistence.dao.serialization.AbstractSerializerVisitor; import org.apache.hadoop.hbase.util.Bytes; import java.net.URI; public class URIVisitor extends AbstractSerializerVisitor { @Override public byte[] serialize(Object object) { if (object == null || object.getClass() != getEntityType()) return null; URI uri = (URI) object; return Bytes.toBytes(uri.toString()); } @Override public Object deserialize(byte[] value) { if (value == null) return null; String uri = Bytes.toString(value); return URI.create(uri); } @Override public Class<?> getEntityType() { return URI.class; } }
789
0.646388
0.646388
35
21.542856
22.315073
76
false
false
0
0
0
0
0
0
0.371429
false
false
12
30b4ab5e69b4a072f20190115890e1f9cd8d103b
18,373,870,104,287
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_a6dd9d13ece82b3de16c1622e605ed797b68169c/NativeThread/2_a6dd9d13ece82b3de16c1622e605ed797b68169c_NativeThread_t.java
6c982e1674729fad298cd029ca400886a9d7c9e4
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.support.io; import freenet.node.NodeStarter; import freenet.support.LibraryLoader; import freenet.support.Logger; /** * Do *NOT* forget to call super.run() if you extend it! * * @see http://archives.freenetproject.org/thread/20080214.235159.6deed539.en.html * @author Florent Daigni&egrave;re &lt;nextgens@freenetproject.org&gt; */ public class NativeThread extends Thread { public static final boolean _loadNative; private static boolean _disabled; public static final int JAVA_PRIORITY_RANGE = Thread.MAX_PRIORITY - Thread.MIN_PRIORITY; private static int NATIVE_PRIORITY_BASE; public static int NATIVE_PRIORITY_RANGE; private int currentPriority = Thread.MAX_PRIORITY; private boolean dontCheckRenice = false; public static boolean HAS_THREE_NICE_LEVELS; public static boolean HAS_ENOUGH_NICE_LEVELS; public static boolean HAS_PLENTY_NICE_LEVELS; // 5 is enough generally for our purposes. public static final int ENOUGH_NICE_LEVELS = 5; public static final int MIN_PRIORITY = 1; public static final int LOW_PRIORITY = 3; public static final int NORM_PRIORITY = 5; public static final int HIGH_PRIORITY = 7; public static final int MAX_PRIORITY = 10; static { Logger.minor(NativeThread.class, "Running init()"); _loadNative = "Linux".equalsIgnoreCase(System.getProperty("os.name")) && NodeStarter.extBuildNumber > 18; if(_loadNative) { //System.loadLibrary("NativeThread"); LibraryLoader.loadNative("/freenet/support/io/", "NativeThread"); NATIVE_PRIORITY_BASE = getLinuxPriority(); NATIVE_PRIORITY_RANGE = 20 - NATIVE_PRIORITY_BASE; System.out.println("Using the NativeThread implementation (base nice level is "+NATIVE_PRIORITY_BASE+')'); // they are 3 main prio levels HAS_THREE_NICE_LEVELS = NATIVE_PRIORITY_RANGE >= 3; HAS_ENOUGH_NICE_LEVELS = NATIVE_PRIORITY_RANGE >= ENOUGH_NICE_LEVELS; HAS_PLENTY_NICE_LEVELS = NATIVE_PRIORITY_RANGE >=JAVA_PRIORITY_RANGE; if(!(HAS_ENOUGH_NICE_LEVELS && HAS_THREE_NICE_LEVELS)) System.err.println("WARNING!!! The JVM has been niced down to a level which won't allow it to schedule threads properly! LOWER THE NICE LEVEL!!"); } else { // unused anyway NATIVE_PRIORITY_BASE = 0; NATIVE_PRIORITY_RANGE = 19; HAS_THREE_NICE_LEVELS = true; HAS_ENOUGH_NICE_LEVELS = true; HAS_PLENTY_NICE_LEVELS = true; } Logger.minor(NativeThread.class, "Run init(): _loadNative = "+_loadNative); } public NativeThread(String name, int priority, boolean dontCheckRenice) { super(name); this.currentPriority = priority; this.dontCheckRenice = dontCheckRenice; } public NativeThread(Runnable r, String name, int priority, boolean dontCheckRenice) { super(r, name); this.currentPriority = priority; this.dontCheckRenice = dontCheckRenice; } public NativeThread(ThreadGroup g, Runnable r, String name, int priority) { super(g, r, name); this.currentPriority = priority; } /** * Set linux priority (JNI call) * * @return true if successful, false otherwise. */ private static native boolean setLinuxPriority(int prio); /** * Get linux priority (JNI call) */ private static native int getLinuxPriority(); public void run() { if(!setNativePriority(currentPriority)) System.err.println("setNativePriority("+currentPriority+") has failed!"); super.run(); } /** * Rescale java priority and set linux priority. */ private boolean setNativePriority(int prio) { Logger.minor(this, "setNativePriority("+prio+")"); setPriority(prio); if(!_loadNative) { Logger.minor(this, "_loadNative is false"); return true; } int realPrio = getLinuxPriority(); if(_disabled) { Logger.normal(this, "Not setting native priority as disabled due to renicing"); return false; } if(NATIVE_PRIORITY_BASE != realPrio && !dontCheckRenice) { /* The user has reniced freenet or we didn't use the PacketSender to create the thread * either ways it's bad for us. * * Let's diable the renicing as we can't rely on it anymore. */ _disabled = true; Logger.error(this, "Freenet has detected it has been reniced : THAT'S BAD, DON'T DO IT! Nice level detected statically: "+NATIVE_PRIORITY_BASE+" actual nice level: "+realPrio+" on "+this); System.err.println("Freenet has detected it has been reniced : THAT'S BAD, DON'T DO IT! Nice level detected statically: "+NATIVE_PRIORITY_BASE+" actual nice level: "+realPrio+" on "+this); new NullPointerException().printStackTrace(); return false; } final int linuxPriority = NATIVE_PRIORITY_BASE + NATIVE_PRIORITY_RANGE - (NATIVE_PRIORITY_RANGE * (prio - MIN_PRIORITY)) / JAVA_PRIORITY_RANGE; if(linuxPriority == realPrio) return true; // Ok // That's an obvious coding mistake if(prio < currentPriority) throw new IllegalStateException("You're trying to set a thread priority" + " above the current value!! It's not possible if you aren't root" + " and shouldn't ever occur in our code. (asked="+prio+':'+linuxPriority+" currentMax="+ +currentPriority+':'+NATIVE_PRIORITY_BASE+") SHOUDLN'T HAPPEN, please report!"); Logger.minor(this, "Setting native priority to "+linuxPriority+" (base="+NATIVE_PRIORITY_BASE+") for "+this); return setLinuxPriority(linuxPriority); } public int getNativePriority() { return currentPriority; } public static boolean usingNativeCode() { return _loadNative && !_disabled; } }
UTF-8
Java
5,757
java
2_a6dd9d13ece82b3de16c1622e605ed797b68169c_NativeThread_t.java
Java
[ { "context": "hread/20080214.235159.6deed539.en.html\n * @author Florent Daigni&egrave;re &lt;nextgens@freenetproject.org&gt;\n */", "end": 524, "score": 0.9761958122253418, "start": 510, "tag": "NAME", "value": "Florent Daigni" }, { "context": "deed539.en.html\n * @author Florent Daigni&egrave;re &lt;nextgens@freenetproject.org&gt;\n */\n public ", "end": 534, "score": 0.9983180165290833, "start": 532, "tag": "NAME", "value": "re" }, { "context": ".en.html\n * @author Florent Daigni&egrave;re &lt;nextgens@freenetproject.org&gt;\n */\n public class NativeThread extends Threa", "end": 566, "score": 0.9999051690101624, "start": 539, "tag": "EMAIL", "value": "nextgens@freenetproject.org" } ]
null
[]
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.support.io; import freenet.node.NodeStarter; import freenet.support.LibraryLoader; import freenet.support.Logger; /** * Do *NOT* forget to call super.run() if you extend it! * * @see http://archives.freenetproject.org/thread/20080214.235159.6deed539.en.html * @author <NAME>&egrave;re &lt;<EMAIL>&gt; */ public class NativeThread extends Thread { public static final boolean _loadNative; private static boolean _disabled; public static final int JAVA_PRIORITY_RANGE = Thread.MAX_PRIORITY - Thread.MIN_PRIORITY; private static int NATIVE_PRIORITY_BASE; public static int NATIVE_PRIORITY_RANGE; private int currentPriority = Thread.MAX_PRIORITY; private boolean dontCheckRenice = false; public static boolean HAS_THREE_NICE_LEVELS; public static boolean HAS_ENOUGH_NICE_LEVELS; public static boolean HAS_PLENTY_NICE_LEVELS; // 5 is enough generally for our purposes. public static final int ENOUGH_NICE_LEVELS = 5; public static final int MIN_PRIORITY = 1; public static final int LOW_PRIORITY = 3; public static final int NORM_PRIORITY = 5; public static final int HIGH_PRIORITY = 7; public static final int MAX_PRIORITY = 10; static { Logger.minor(NativeThread.class, "Running init()"); _loadNative = "Linux".equalsIgnoreCase(System.getProperty("os.name")) && NodeStarter.extBuildNumber > 18; if(_loadNative) { //System.loadLibrary("NativeThread"); LibraryLoader.loadNative("/freenet/support/io/", "NativeThread"); NATIVE_PRIORITY_BASE = getLinuxPriority(); NATIVE_PRIORITY_RANGE = 20 - NATIVE_PRIORITY_BASE; System.out.println("Using the NativeThread implementation (base nice level is "+NATIVE_PRIORITY_BASE+')'); // they are 3 main prio levels HAS_THREE_NICE_LEVELS = NATIVE_PRIORITY_RANGE >= 3; HAS_ENOUGH_NICE_LEVELS = NATIVE_PRIORITY_RANGE >= ENOUGH_NICE_LEVELS; HAS_PLENTY_NICE_LEVELS = NATIVE_PRIORITY_RANGE >=JAVA_PRIORITY_RANGE; if(!(HAS_ENOUGH_NICE_LEVELS && HAS_THREE_NICE_LEVELS)) System.err.println("WARNING!!! The JVM has been niced down to a level which won't allow it to schedule threads properly! LOWER THE NICE LEVEL!!"); } else { // unused anyway NATIVE_PRIORITY_BASE = 0; NATIVE_PRIORITY_RANGE = 19; HAS_THREE_NICE_LEVELS = true; HAS_ENOUGH_NICE_LEVELS = true; HAS_PLENTY_NICE_LEVELS = true; } Logger.minor(NativeThread.class, "Run init(): _loadNative = "+_loadNative); } public NativeThread(String name, int priority, boolean dontCheckRenice) { super(name); this.currentPriority = priority; this.dontCheckRenice = dontCheckRenice; } public NativeThread(Runnable r, String name, int priority, boolean dontCheckRenice) { super(r, name); this.currentPriority = priority; this.dontCheckRenice = dontCheckRenice; } public NativeThread(ThreadGroup g, Runnable r, String name, int priority) { super(g, r, name); this.currentPriority = priority; } /** * Set linux priority (JNI call) * * @return true if successful, false otherwise. */ private static native boolean setLinuxPriority(int prio); /** * Get linux priority (JNI call) */ private static native int getLinuxPriority(); public void run() { if(!setNativePriority(currentPriority)) System.err.println("setNativePriority("+currentPriority+") has failed!"); super.run(); } /** * Rescale java priority and set linux priority. */ private boolean setNativePriority(int prio) { Logger.minor(this, "setNativePriority("+prio+")"); setPriority(prio); if(!_loadNative) { Logger.minor(this, "_loadNative is false"); return true; } int realPrio = getLinuxPriority(); if(_disabled) { Logger.normal(this, "Not setting native priority as disabled due to renicing"); return false; } if(NATIVE_PRIORITY_BASE != realPrio && !dontCheckRenice) { /* The user has reniced freenet or we didn't use the PacketSender to create the thread * either ways it's bad for us. * * Let's diable the renicing as we can't rely on it anymore. */ _disabled = true; Logger.error(this, "Freenet has detected it has been reniced : THAT'S BAD, DON'T DO IT! Nice level detected statically: "+NATIVE_PRIORITY_BASE+" actual nice level: "+realPrio+" on "+this); System.err.println("Freenet has detected it has been reniced : THAT'S BAD, DON'T DO IT! Nice level detected statically: "+NATIVE_PRIORITY_BASE+" actual nice level: "+realPrio+" on "+this); new NullPointerException().printStackTrace(); return false; } final int linuxPriority = NATIVE_PRIORITY_BASE + NATIVE_PRIORITY_RANGE - (NATIVE_PRIORITY_RANGE * (prio - MIN_PRIORITY)) / JAVA_PRIORITY_RANGE; if(linuxPriority == realPrio) return true; // Ok // That's an obvious coding mistake if(prio < currentPriority) throw new IllegalStateException("You're trying to set a thread priority" + " above the current value!! It's not possible if you aren't root" + " and shouldn't ever occur in our code. (asked="+prio+':'+linuxPriority+" currentMax="+ +currentPriority+':'+NATIVE_PRIORITY_BASE+") SHOUDLN'T HAPPEN, please report!"); Logger.minor(this, "Setting native priority to "+linuxPriority+" (base="+NATIVE_PRIORITY_BASE+") for "+this); return setLinuxPriority(linuxPriority); } public int getNativePriority() { return currentPriority; } public static boolean usingNativeCode() { return _loadNative && !_disabled; } }
5,729
0.702797
0.696543
145
38.696552
35.402382
192
false
false
0
0
0
0
0
0
2.268965
false
false
12
8a4f7e29344ff50bad4afd4b737eb05c954e2f55
22,050,362,129,379
920445d009feade3ed5333ae22d157f15c2cdb89
/src/KaKao/t02/Solution.java
0b344e5ae8ed94adfccffebef0ab34c97ab0a41e
[]
no_license
MoonHKLee/algorithm
https://github.com/MoonHKLee/algorithm
6820554efffda62f42024c301cf30ccebcc0a1cc
14be76da58603b907fa9a33f697b4fb74d3b18b8
refs/heads/master
2021-06-30T06:56:18.396000
2020-10-31T13:26:58
2020-10-31T13:26:58
175,958,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package KaKao.t02; import java.util.*; import java.util.stream.Collectors; class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(Arrays.toString(solution.solution(new String[]{"ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"}, new int[]{2, 3, 4}))); System.out.println(Arrays.toString(solution.solution(new String[]{"ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"}, new int[]{2, 3, 5}))); System.out.println(Arrays.toString(solution.solution(new String[]{"XYZ", "XWY", "WXA"}, new int[]{2, 3, 4}))); } public String[] solution(String[] orders, int[] course) { List<String> answers = new ArrayList<>(); for (int i : course) { Map<String,Integer> map = new HashMap<>(); for (String order : orders) { for (String s : getCombString(order, i)) { s = sort(s); if(map.containsKey(s)){ int count = map.get(s); count++; map.put(s,count); }else{ map.put(s,1); } } } Integer max = 0; if(!map.isEmpty()){ max = getMax(map); } if(max >=2) { List<String> listOfMax = getList(map, max); answers.addAll(listOfMax); } } answers.sort(String::compareTo); return answers.toArray(String[]::new); } public String sort(String str){ String[] array = str.split(""); Arrays.sort(array); return String.join("", array); } private List<String> getList(Map<String, Integer> map, Integer max) { return map.entrySet() .stream() .filter(entry -> entry.getValue().equals(max)) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private Integer getMax(Map<String, Integer> map) { return map.entrySet() .stream() .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1) .get() .getValue(); } public String[] getCombString(String order, int check) { int n = order.length(); char[] arr = order.toCharArray(); boolean[] visited = new boolean[n]; List<String> answer = new ArrayList<>(); combination(arr, visited, 0, n, check, answer); return answer.toArray(String[]::new); } static void combination(char[] arr, boolean[] visited, int start, int n, int r, List<String> answer) { if (r == 0) { combPrint(arr, visited, n, answer); return; } for (int i = start; i < n; i++) { visited[i] = true; combination(arr, visited, i + 1, n, r - 1, answer); visited[i] = false; } } static void combPrint(char[] arr, boolean[] visited, int n, List<String> answer) { StringBuilder str = new StringBuilder(); for (int i = 0; i < n; i++) { if (visited[i]) { StringBuilder append = str.append(arr[i]); if(answer.contains(append.toString())) { return; } } } answer.add(str.toString()); } }
UTF-8
Java
3,438
java
Solution.java
Java
[]
null
[]
package KaKao.t02; import java.util.*; import java.util.stream.Collectors; class Solution { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(Arrays.toString(solution.solution(new String[]{"ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"}, new int[]{2, 3, 4}))); System.out.println(Arrays.toString(solution.solution(new String[]{"ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"}, new int[]{2, 3, 5}))); System.out.println(Arrays.toString(solution.solution(new String[]{"XYZ", "XWY", "WXA"}, new int[]{2, 3, 4}))); } public String[] solution(String[] orders, int[] course) { List<String> answers = new ArrayList<>(); for (int i : course) { Map<String,Integer> map = new HashMap<>(); for (String order : orders) { for (String s : getCombString(order, i)) { s = sort(s); if(map.containsKey(s)){ int count = map.get(s); count++; map.put(s,count); }else{ map.put(s,1); } } } Integer max = 0; if(!map.isEmpty()){ max = getMax(map); } if(max >=2) { List<String> listOfMax = getList(map, max); answers.addAll(listOfMax); } } answers.sort(String::compareTo); return answers.toArray(String[]::new); } public String sort(String str){ String[] array = str.split(""); Arrays.sort(array); return String.join("", array); } private List<String> getList(Map<String, Integer> map, Integer max) { return map.entrySet() .stream() .filter(entry -> entry.getValue().equals(max)) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private Integer getMax(Map<String, Integer> map) { return map.entrySet() .stream() .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1) .get() .getValue(); } public String[] getCombString(String order, int check) { int n = order.length(); char[] arr = order.toCharArray(); boolean[] visited = new boolean[n]; List<String> answer = new ArrayList<>(); combination(arr, visited, 0, n, check, answer); return answer.toArray(String[]::new); } static void combination(char[] arr, boolean[] visited, int start, int n, int r, List<String> answer) { if (r == 0) { combPrint(arr, visited, n, answer); return; } for (int i = start; i < n; i++) { visited[i] = true; combination(arr, visited, i + 1, n, r - 1, answer); visited[i] = false; } } static void combPrint(char[] arr, boolean[] visited, int n, List<String> answer) { StringBuilder str = new StringBuilder(); for (int i = 0; i < n; i++) { if (visited[i]) { StringBuilder append = str.append(arr[i]); if(answer.contains(append.toString())) { return; } } } answer.add(str.toString()); } }
3,438
0.488365
0.481094
99
33.727272
28.246683
146
false
false
0
0
0
0
0
0
1
false
false
12
fd3642acd8ae99c54a9250fc41ae6f6b13a2e6e1
26,036,091,790,765
4ed898f8ab1147fb53335dceb1c9ab9682bfea89
/tests/jre/src/test/java/org/treblereel/gwt/xml/mapper/client/tests/bpmn/bpmn2/Process.java
9ad0dd0b931b126d8a3461807b5af3e4daca25ad
[ "Apache-2.0" ]
permissive
treblereel/jackson-xml
https://github.com/treblereel/jackson-xml
e2814cb6f5d881b007635f83777618a95f0d8ec0
c9e3b393076b2cd957635e5c87a9e8db308e25a6
refs/heads/master
2021-04-03T11:05:46.085000
2021-02-24T22:05:23
2021-02-24T22:05:23
248,346,470
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright © 2020 Treblereel * * 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.treblereel.gwt.xml.mapper.client.tests.bpmn.bpmn2; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlRootElement; /** @author Dmitrii Tikhomirov Created by treblereel 4/6/20 */ @XmlRootElement(name = "process", namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL") public class Process { @XmlAttribute private String id; @XmlAttribute private String name; @XmlAttribute(name = "isExecutable") private boolean executable; @XmlAttribute(name = "packageName", namespace = "http://www.jboss.org/drools") private String packageName; @XmlAttribute(name = "version", namespace = "http://www.jboss.org/drools") private double version; @XmlAttribute(name = "adHoc", namespace = "http://www.jboss.org/drools") private boolean adHoc; @XmlElementRefs({ @XmlElementRef(name = "userTask", type = UserTask.class), // @XmlElementRef(name = "bpmn2:scriptTask", type = ScriptTask.class) }) private List<BPMNViewDefinition> definitionList; private List<SubProcess> subProcesses = new ArrayList<>(); private List<DataObject> dataObjects = new ArrayList<>(); private List<DataObjectReference> dataObjectReferences = new ArrayList<>(); @Override public int hashCode() { return Objects.hash( getId(), getName(), isExecutable(), getPackageName(), getVersion(), isAdHoc(), getSubProcesses(), getDataObjects(), getDataObjectReferences()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Process)) { return false; } Process process = (Process) o; return isExecutable() == process.isExecutable() && isAdHoc() == process.isAdHoc() && Objects.equals(getId(), process.getId()) && Objects.equals(getName(), process.getName()) && Objects.equals(getPackageName(), process.getPackageName()) && Objects.equals(getVersion(), process.getVersion()) && Objects.equals(getSubProcesses(), process.getSubProcesses()) && Objects.equals(getDataObjects(), process.getDataObjects()) && Objects.equals(getDataObjectReferences(), process.getDataObjectReferences()); } @Override public String toString() { return "Process{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", executable=" + executable + ", packageName='" + packageName + '\'' + ", version='" + version + '\'' + ", adHoc=" + adHoc + ", subProcesses=" + subProcesses + ", dataObjects=" + dataObjects + ", dataObjectReferences=" + dataObjectReferences + '}'; } public String getId() { return id; } public String getName() { return name; } public boolean isExecutable() { return executable; } public void setExecutable(boolean executable) { this.executable = executable; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public double getVersion() { return version; } public boolean isAdHoc() { return adHoc; } public List<SubProcess> getSubProcesses() { return subProcesses; } public void setSubProcesses(List<SubProcess> subProcesses) { this.subProcesses = subProcesses; } public List<DataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<DataObject> dataObjects) { this.dataObjects = dataObjects; } public List<DataObjectReference> getDataObjectReferences() { return dataObjectReferences; } public void setDataObjectReferences(List<DataObjectReference> dataObjectReferences) { this.dataObjectReferences = dataObjectReferences; } public void setAdHoc(boolean adHoc) { this.adHoc = adHoc; } public void setVersion(double version) { this.version = version; } public void setName(String name) { this.name = name; } public void setId(String id) { this.id = id; } public List<BPMNViewDefinition> getDefinitionList() { return definitionList; } public void setDefinitionList(List<BPMNViewDefinition> definitionList) { this.definitionList = definitionList; } }
UTF-8
Java
5,177
java
Process.java
Java
[ { "context": "x.xml.bind.annotation.XmlRootElement;\n\n/** @author Dmitrii Tikhomirov Created by treblereel 4/6/20 */\n@XmlRootElement(n", "end": 961, "score": 0.9998593926429749, "start": 943, "tag": "NAME", "value": "Dmitrii Tikhomirov" } ]
null
[]
/* * Copyright © 2020 Treblereel * * 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.treblereel.gwt.xml.mapper.client.tests.bpmn.bpmn2; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlRootElement; /** @author <NAME> Created by treblereel 4/6/20 */ @XmlRootElement(name = "process", namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL") public class Process { @XmlAttribute private String id; @XmlAttribute private String name; @XmlAttribute(name = "isExecutable") private boolean executable; @XmlAttribute(name = "packageName", namespace = "http://www.jboss.org/drools") private String packageName; @XmlAttribute(name = "version", namespace = "http://www.jboss.org/drools") private double version; @XmlAttribute(name = "adHoc", namespace = "http://www.jboss.org/drools") private boolean adHoc; @XmlElementRefs({ @XmlElementRef(name = "userTask", type = UserTask.class), // @XmlElementRef(name = "bpmn2:scriptTask", type = ScriptTask.class) }) private List<BPMNViewDefinition> definitionList; private List<SubProcess> subProcesses = new ArrayList<>(); private List<DataObject> dataObjects = new ArrayList<>(); private List<DataObjectReference> dataObjectReferences = new ArrayList<>(); @Override public int hashCode() { return Objects.hash( getId(), getName(), isExecutable(), getPackageName(), getVersion(), isAdHoc(), getSubProcesses(), getDataObjects(), getDataObjectReferences()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Process)) { return false; } Process process = (Process) o; return isExecutable() == process.isExecutable() && isAdHoc() == process.isAdHoc() && Objects.equals(getId(), process.getId()) && Objects.equals(getName(), process.getName()) && Objects.equals(getPackageName(), process.getPackageName()) && Objects.equals(getVersion(), process.getVersion()) && Objects.equals(getSubProcesses(), process.getSubProcesses()) && Objects.equals(getDataObjects(), process.getDataObjects()) && Objects.equals(getDataObjectReferences(), process.getDataObjectReferences()); } @Override public String toString() { return "Process{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", executable=" + executable + ", packageName='" + packageName + '\'' + ", version='" + version + '\'' + ", adHoc=" + adHoc + ", subProcesses=" + subProcesses + ", dataObjects=" + dataObjects + ", dataObjectReferences=" + dataObjectReferences + '}'; } public String getId() { return id; } public String getName() { return name; } public boolean isExecutable() { return executable; } public void setExecutable(boolean executable) { this.executable = executable; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public double getVersion() { return version; } public boolean isAdHoc() { return adHoc; } public List<SubProcess> getSubProcesses() { return subProcesses; } public void setSubProcesses(List<SubProcess> subProcesses) { this.subProcesses = subProcesses; } public List<DataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<DataObject> dataObjects) { this.dataObjects = dataObjects; } public List<DataObjectReference> getDataObjectReferences() { return dataObjectReferences; } public void setDataObjectReferences(List<DataObjectReference> dataObjectReferences) { this.dataObjectReferences = dataObjectReferences; } public void setAdHoc(boolean adHoc) { this.adHoc = adHoc; } public void setVersion(double version) { this.version = version; } public void setName(String name) { this.name = name; } public void setId(String id) { this.id = id; } public List<BPMNViewDefinition> getDefinitionList() { return definitionList; } public void setDefinitionList(List<BPMNViewDefinition> definitionList) { this.definitionList = definitionList; } }
5,165
0.662867
0.658617
199
25.01005
23.455933
92
false
false
0
0
0
0
0
0
0.396985
false
false
12
fea55041a0dee6e8bf50f888385af1438e91d01d
6,511,170,476,771
5766609bc8c74abacbee2e10eb664356056fefae
/app/app-web/src/main/java/iss/dt/app/web/converter/UserConverter.java
fb5333c54284f156ee4d16be2ca0cd9ecd944ff6
[ "MIT" ]
permissive
SerjTheDoctor/dt_iss
https://github.com/SerjTheDoctor/dt_iss
da65ebb54131d37279697e53d9ab77f4ac822406
5697b5c7fd8e99d092ad28db348deec2e811a226
refs/heads/master
2021-01-16T04:34:13.659000
2020-05-26T20:02:38
2020-05-26T20:02:38
242,976,648
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package iss.dt.app.web.converter; import iss.dt.app.core.model.User; import iss.dt.app.web.dto.UserDto; import org.springframework.stereotype.Component; @Component public class UserConverter extends BaseConverter<User, UserDto> { @Override public User convertDtoToModel(UserDto dto) { /*SectionConverter sc= new SectionConverter();*/ /*List<ProgramCommitee> pclist= dto.getPc_co_chairs() .stream() .map(pcc::convertDtoToModel) .collect(Collectors.toList());*/ return new User(dto.getId() , dto.getName() , dto.getAffiliation() , dto.getEmail() , dto.getPassword() , dto.getAdmin() , dto.getValidated()); } @Override public UserDto convertModelToDto(User user) { // ProgramCommiteeConverter pcc=new ProgramCommiteeConverter(); /* SectionConverter sc= new SectionConverter(); */ /*List<ProgramCommiteeDto> pclist= user.getPc_co_chairs() .stream() .map(pcc::convertModelToDto) .collect(Collectors.toList()); */ UserDto userdto = new UserDto(user.getName() , user.getAffiliation() , user.getEmail() , user.getPassword() , user.getAdmin() , user.getValidated() ); userdto.setId(user.getId()); return userdto; } }
UTF-8
Java
1,491
java
UserConverter.java
Java
[]
null
[]
package iss.dt.app.web.converter; import iss.dt.app.core.model.User; import iss.dt.app.web.dto.UserDto; import org.springframework.stereotype.Component; @Component public class UserConverter extends BaseConverter<User, UserDto> { @Override public User convertDtoToModel(UserDto dto) { /*SectionConverter sc= new SectionConverter();*/ /*List<ProgramCommitee> pclist= dto.getPc_co_chairs() .stream() .map(pcc::convertDtoToModel) .collect(Collectors.toList());*/ return new User(dto.getId() , dto.getName() , dto.getAffiliation() , dto.getEmail() , dto.getPassword() , dto.getAdmin() , dto.getValidated()); } @Override public UserDto convertModelToDto(User user) { // ProgramCommiteeConverter pcc=new ProgramCommiteeConverter(); /* SectionConverter sc= new SectionConverter(); */ /*List<ProgramCommiteeDto> pclist= user.getPc_co_chairs() .stream() .map(pcc::convertModelToDto) .collect(Collectors.toList()); */ UserDto userdto = new UserDto(user.getName() , user.getAffiliation() , user.getEmail() , user.getPassword() , user.getAdmin() , user.getValidated() ); userdto.setId(user.getId()); return userdto; } }
1,491
0.562039
0.562039
51
28.235294
20.790825
70
false
false
0
0
0
0
0
0
0.490196
false
false
12
de376c55fdb349fa6b1664a92241d2b44fe2d3ee
22,170,621,220,120
902595027f9260835862b3bc4dbe2ee9fbaef89d
/core/test/documentation/PerlDocumentationTest.java
13e062189c66951bed12e222286277f28db2f5bd
[ "Apache-2.0" ]
permissive
timothy-long/Perl5-IDEA
https://github.com/timothy-long/Perl5-IDEA
adc884a59271f5d13bb17a565fbcdf76d80c969e
e5baf596cce2eb4817ae90748157bd1362c90e0e
refs/heads/master
2020-04-17T09:55:08.406000
2019-01-18T07:35:33
2019-01-18T07:46:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2015-2018 Alexandr Evstigneev * * 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 documentation; import base.PerlLightTestCase; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.lang.Language; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.DocumentationProviderEx; import com.intellij.psi.PsiElement; import com.intellij.testFramework.UsefulTestCase; import com.perl5.lang.perl.PerlLanguage; import org.jetbrains.annotations.NotNull; import java.util.List; public class PerlDocumentationTest extends PerlLightTestCase { @Override protected String getTestDataPath() { return "testData/documentation/perl"; } public void testSubDefinitionInline() {doTest();} public void testSubDefinitionUsageInline() {doTest();} public void testExternalSubUsagePod() {doTest();} public void testSubDefinitionCross() {doTest();} public void testNamespaceDefinitionInline() {doTest();} @NotNull protected Language getLanguage() { return PerlLanguage.INSTANCE; } @NotNull @Override protected String getResultsFileExtension() { return "txt"; } private void doTest() { initWithFileSmartWithoutErrors(); List<Integer> caretsOffsets = getAndRemoveCarets(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < caretsOffsets.size(); i++) { Integer caretOffset = caretsOffsets.get(i); if (caretsOffsets.size() > 1) { sb.append("---------------------- ").append("Caret #").append(i).append(" at: ").append(caretOffset) .append("-----------------------------\n"); } getEditor().getCaretModel().moveToOffset(caretOffset); PsiElement elementAtCaret = getFile().getViewProvider().findElementAt(getEditor().getCaretModel().getOffset(), getLanguage()); assertNotNull(elementAtCaret); DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(elementAtCaret); assertInstanceOf(documentationProvider, DocumentationProviderEx.class); PsiElement targetElement = DocumentationManager.getInstance(getProject()).findTargetElement(getEditor(), getFile(), elementAtCaret); assertNotNull(targetElement); String generatedDoc = documentationProvider.generateDoc(targetElement, elementAtCaret); assertNotNull(generatedDoc); sb.append(generatedDoc).append("\n"); } UsefulTestCase.assertSameLinesWithFile(getTestResultsFilePath(), sb.toString()); } }
UTF-8
Java
3,045
java
PerlDocumentationTest.java
Java
[ { "context": "/*\n * Copyright 2015-2018 Alexandr Evstigneev\n *\n * Licensed under the Apache License, Version ", "end": 45, "score": 0.9998518824577332, "start": 26, "tag": "NAME", "value": "Alexandr Evstigneev" } ]
null
[]
/* * Copyright 2015-2018 <NAME> * * 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 documentation; import base.PerlLightTestCase; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.lang.Language; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.DocumentationProviderEx; import com.intellij.psi.PsiElement; import com.intellij.testFramework.UsefulTestCase; import com.perl5.lang.perl.PerlLanguage; import org.jetbrains.annotations.NotNull; import java.util.List; public class PerlDocumentationTest extends PerlLightTestCase { @Override protected String getTestDataPath() { return "testData/documentation/perl"; } public void testSubDefinitionInline() {doTest();} public void testSubDefinitionUsageInline() {doTest();} public void testExternalSubUsagePod() {doTest();} public void testSubDefinitionCross() {doTest();} public void testNamespaceDefinitionInline() {doTest();} @NotNull protected Language getLanguage() { return PerlLanguage.INSTANCE; } @NotNull @Override protected String getResultsFileExtension() { return "txt"; } private void doTest() { initWithFileSmartWithoutErrors(); List<Integer> caretsOffsets = getAndRemoveCarets(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < caretsOffsets.size(); i++) { Integer caretOffset = caretsOffsets.get(i); if (caretsOffsets.size() > 1) { sb.append("---------------------- ").append("Caret #").append(i).append(" at: ").append(caretOffset) .append("-----------------------------\n"); } getEditor().getCaretModel().moveToOffset(caretOffset); PsiElement elementAtCaret = getFile().getViewProvider().findElementAt(getEditor().getCaretModel().getOffset(), getLanguage()); assertNotNull(elementAtCaret); DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(elementAtCaret); assertInstanceOf(documentationProvider, DocumentationProviderEx.class); PsiElement targetElement = DocumentationManager.getInstance(getProject()).findTargetElement(getEditor(), getFile(), elementAtCaret); assertNotNull(targetElement); String generatedDoc = documentationProvider.generateDoc(targetElement, elementAtCaret); assertNotNull(generatedDoc); sb.append(generatedDoc).append("\n"); } UsefulTestCase.assertSameLinesWithFile(getTestResultsFilePath(), sb.toString()); } }
3,032
0.737603
0.732677
84
35.25
32.234585
138
false
false
0
0
0
0
0
0
0.571429
false
false
12
e21161bdc8356b5124868983ba16e118e4620bc8
6,236,292,541,122
98a1031e2972ce85b41b54cff4e9f3b787fb16a7
/src/com/br/ott/test/ThreadDemo.java
c574cfe33655dd628546b56b9b19fb3ea35e1626
[]
no_license
LichaoStone/sjhkcms
https://github.com/LichaoStone/sjhkcms
7905ac9b2b474ec5286e5121f791c1bd713f02b8
8c41339beff80a95c9e6bd1488577f3914c3e208
refs/heads/master
2021-03-07T00:49:49.546000
2020-03-10T07:29:07
2020-03-10T07:29:07
246,234,893
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.br.ott.test; import java.util.HashMap; import net.sf.json.JSONObject; class MyThread extends Thread { public void run() { testEhcache(); } public void testEhcache() { JSONObject json = new JSONObject(); json.put("operators", "hngd.yd"); HashMap<String, Object> map = ApiTest.callMethod( "http://localhost/HNTV2/api/findNewTVType.action", json.toString(), "mac:AC5CFE29E146"); System.out.println(map.get("jsonObject")); } } public class ThreadDemo { public static void main(String[] args) { for(int i=0;i<1000;i++){ new MyThread().start(); } } }
UTF-8
Java
593
java
ThreadDemo.java
Java
[]
null
[]
package com.br.ott.test; import java.util.HashMap; import net.sf.json.JSONObject; class MyThread extends Thread { public void run() { testEhcache(); } public void testEhcache() { JSONObject json = new JSONObject(); json.put("operators", "hngd.yd"); HashMap<String, Object> map = ApiTest.callMethod( "http://localhost/HNTV2/api/findNewTVType.action", json.toString(), "mac:AC5CFE29E146"); System.out.println(map.get("jsonObject")); } } public class ThreadDemo { public static void main(String[] args) { for(int i=0;i<1000;i++){ new MyThread().start(); } } }
593
0.681282
0.661046
29
19.482759
17.521652
54
false
false
0
0
0
0
0
0
1.586207
false
false
12
3e6e8d9dbbe4fb870bcc4d1ae2a33a55a59e232b
6,236,292,538,145
badf78a790d59f93ecdc6cf2c5e3000ed4c0fe51
/java/src/kanzi/test/TestColorModel.java
d03f5c08aa56d8e4465ee860c6ece5aa9946538e
[ "Apache-2.0" ]
permissive
kronar/kanzi
https://github.com/kronar/kanzi
67d73ff347ae4368cbdbb7c9bfae5b4299310e16
3872c76b9b410c44428e74b2065f3e2291cb8095
refs/heads/master
2021-01-19T00:03:22.438000
2016-06-19T04:19:06
2016-06-19T04:19:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2011-2013 Frederic Langlet 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 kanzi.test; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import kanzi.ColorModelType; import kanzi.util.color.ColorModelConverter; import kanzi.util.color.YCbCrColorModelConverter; import kanzi.util.ImageQualityMonitor; import kanzi.util.color.ReversibleYUVColorModelConverter; import kanzi.util.color.XYZColorModelConverter; import kanzi.util.color.YCoCgColorModelConverter; import kanzi.util.color.YSbSrColorModelConverter; import kanzi.util.sampling.BicubicUpSampler; import kanzi.util.sampling.BilinearUpSampler; import kanzi.util.sampling.DWTDownSampler; import kanzi.util.sampling.DWTUpSampler; import kanzi.util.sampling.DecimateDownSampler; import kanzi.util.sampling.DownSampler; import kanzi.util.sampling.GuidedBilinearUpSampler; import kanzi.util.sampling.UpSampler; public class TestColorModel { public static void main(String[] args) { try { String fileName = (args.length > 0) ? args[0] : "c:\\temp\\lena.jpg"; Image image = ImageIO.read(new File(fileName)); int w = image.getWidth(null) & -15; int h = image.getHeight(null) & -15; GraphicsDevice gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]; GraphicsConfiguration gc = gs.getDefaultConfiguration(); BufferedImage img = gc.createCompatibleImage(w, h, Transparency.OPAQUE); img.getGraphics().drawImage(image, 0, 0, null); int[] rgb = new int[w*h]; int[] rgb2 = new int[w*h]; // Do NOT use img.getRGB(): it is more than 10 times slower than // img.getRaster().getDataElements() img.getRaster().getDataElements(0, 0, w, h, rgb); System.out.println(w + "x" + h); UpSampler uBicubic = new BicubicUpSampler(w/2, h/2, w/2, w, 0, false); UpSampler uBilinear = new BilinearUpSampler(w/2, h/2, 2); GuidedBilinearUpSampler ugBilinear = new GuidedBilinearUpSampler(w/2, h/2); DownSampler downSampler = new DecimateDownSampler(w, h, 2); DownSampler dDWT = new DWTDownSampler(w, h); UpSampler uDWT = new DWTUpSampler(w/2, h/2); ColorModelConverter[] cvts = new ColorModelConverter[] { new XYZColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBicubic), new YCbCrColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBilinear), new YCbCrColorModelConverter(w, h, downSampler, ugBilinear), new YCbCrColorModelConverter(w, h, dDWT, uDWT), new YCbCrColorModelConverter(w, h), new YSbSrColorModelConverter(w, h, downSampler, uBicubic), new YSbSrColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBilinear), new YCbCrColorModelConverter(w, h, downSampler, ugBilinear), new YSbSrColorModelConverter(w, h, dDWT, uDWT), new YSbSrColorModelConverter(w, h), new YCoCgColorModelConverter(w, h), new ReversibleYUVColorModelConverter(w, h) }; ModelInfo[] models = new ModelInfo[] { new ModelInfo("XYZ", false, null), new ModelInfo("YCbCr - bicubic", true, uBicubic), new ModelInfo("YCbCr - built-in (bilinear)", true, null), new ModelInfo("YCbCr - bilinear", true, uBilinear), new ModelInfo("YCbCr - guided bilinear", true, ugBilinear), new ModelInfo("YCbCr - DWT", true, uDWT), new ModelInfo("YCbCr", false, null), new ModelInfo("YSbSr - bicubic", true, uBicubic), new ModelInfo("YSbSr - built-in (bilinear)", true, null), new ModelInfo("YSbSr - bilinear", true, uBilinear), new ModelInfo("YSbSr - guided bilinear", true, ugBilinear), new ModelInfo("YSbSr - DWT", true, uDWT), new ModelInfo("YSbSr", false, null), new ModelInfo("YCoCg", false, null), new ModelInfo("Reversible YUV", false, null), }; JFrame frame = new JFrame("Original"); frame.setBounds(20, 30, w, h); frame.add(new JLabel(new ImageIcon(img))); frame.setVisible(true); System.out.println("================ Test round trip RGB -> YXX -> RGB ================"); for (int i=0; i<cvts.length; i++) { test(models[i], cvts[i], rgb, rgb2, w, h, i+1); } Thread.sleep(35000); } catch (Exception e) { e.printStackTrace(); } System.exit(0); } private static void test(ModelInfo model, ColorModelConverter cvt, int[] rgb1, int[] rgb2, int w, int h, int iter) { long sum = 0; int nn = 500; int[] y1 = new int[rgb1.length]; int[] u1 = new int[rgb1.length]; int[] v1 = new int[rgb1.length]; Arrays.fill(rgb2, 0x0A0A0A0A); if (model.is420) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV420); if (model.us instanceof GuidedBilinearUpSampler) ((GuidedBilinearUpSampler) model.us).setGuide(y1); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV420); } else { if (cvt instanceof XYZColorModelConverter) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.XYZ); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.XYZ); } else { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV444); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV444); } } // Compute PSNR // Computing the SSIM makes little sense since y,u and v are shared // by both images => SSIM = 1.0 String name = model.name + ((model.is420) ? " - 420 " : " - 444 "); System.out.println("\n"+name); ImageQualityMonitor iqm = new ImageQualityMonitor(w, h); int psnr1024 = iqm.computePSNR(rgb1, rgb2); System.out.println("PSNR : "+ ((psnr1024 == 0) ? "Infinite" : ((float) psnr1024 / 1024))); String title = name + "- PSNR: "+ ((psnr1024 == 0) ? "Infinite" : ((float) psnr1024 / 1024)); GraphicsDevice gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]; GraphicsConfiguration gc = gs.getDefaultConfiguration(); BufferedImage img2 = gc.createCompatibleImage(w, h, Transparency.OPAQUE); img2.getRaster().setDataElements(0, 0, w, h, rgb2); JFrame frame2 = new JFrame(title); frame2.setBounds(20+(iter)*100, 30+(iter*30), w, h); ImageIcon newIcon = new ImageIcon(img2); frame2.add(new JLabel(newIcon)); frame2.setVisible(true); System.out.println("Speed test"); if (model.is420) { if (model.us instanceof GuidedBilinearUpSampler) ((GuidedBilinearUpSampler) model.us).setGuide(y1); for (int i=0; i<nn; i++) { Arrays.fill(rgb2, 0); long before = System.nanoTime(); cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV420); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV420); long after = System.nanoTime(); sum += (after - before); } } else { for (int i=0; i<nn; i++) { Arrays.fill(rgb2, 0); long before = System.nanoTime(); if (cvt instanceof XYZColorModelConverter) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.XYZ); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.XYZ); } else { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV444); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV444); } long after = System.nanoTime(); sum += (after - before); } } System.out.println("Elapsed [ms] ("+nn+" iterations): "+sum/1000000); } static class ModelInfo { public ModelInfo(String name, boolean is420, UpSampler us) { this.name = name; this.is420 = is420; this.us = us; } final String name; final boolean is420; final UpSampler us; } }
UTF-8
Java
9,519
java
TestColorModel.java
Java
[ { "context": "/*\nCopyright 2011-2013 Frederic Langlet\nLicensed under the Apache License, Version 2.0 (t", "end": 39, "score": 0.9998542070388794, "start": 23, "tag": "NAME", "value": "Frederic Langlet" } ]
null
[]
/* Copyright 2011-2013 <NAME> 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 kanzi.test; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import kanzi.ColorModelType; import kanzi.util.color.ColorModelConverter; import kanzi.util.color.YCbCrColorModelConverter; import kanzi.util.ImageQualityMonitor; import kanzi.util.color.ReversibleYUVColorModelConverter; import kanzi.util.color.XYZColorModelConverter; import kanzi.util.color.YCoCgColorModelConverter; import kanzi.util.color.YSbSrColorModelConverter; import kanzi.util.sampling.BicubicUpSampler; import kanzi.util.sampling.BilinearUpSampler; import kanzi.util.sampling.DWTDownSampler; import kanzi.util.sampling.DWTUpSampler; import kanzi.util.sampling.DecimateDownSampler; import kanzi.util.sampling.DownSampler; import kanzi.util.sampling.GuidedBilinearUpSampler; import kanzi.util.sampling.UpSampler; public class TestColorModel { public static void main(String[] args) { try { String fileName = (args.length > 0) ? args[0] : "c:\\temp\\lena.jpg"; Image image = ImageIO.read(new File(fileName)); int w = image.getWidth(null) & -15; int h = image.getHeight(null) & -15; GraphicsDevice gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]; GraphicsConfiguration gc = gs.getDefaultConfiguration(); BufferedImage img = gc.createCompatibleImage(w, h, Transparency.OPAQUE); img.getGraphics().drawImage(image, 0, 0, null); int[] rgb = new int[w*h]; int[] rgb2 = new int[w*h]; // Do NOT use img.getRGB(): it is more than 10 times slower than // img.getRaster().getDataElements() img.getRaster().getDataElements(0, 0, w, h, rgb); System.out.println(w + "x" + h); UpSampler uBicubic = new BicubicUpSampler(w/2, h/2, w/2, w, 0, false); UpSampler uBilinear = new BilinearUpSampler(w/2, h/2, 2); GuidedBilinearUpSampler ugBilinear = new GuidedBilinearUpSampler(w/2, h/2); DownSampler downSampler = new DecimateDownSampler(w, h, 2); DownSampler dDWT = new DWTDownSampler(w, h); UpSampler uDWT = new DWTUpSampler(w/2, h/2); ColorModelConverter[] cvts = new ColorModelConverter[] { new XYZColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBicubic), new YCbCrColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBilinear), new YCbCrColorModelConverter(w, h, downSampler, ugBilinear), new YCbCrColorModelConverter(w, h, dDWT, uDWT), new YCbCrColorModelConverter(w, h), new YSbSrColorModelConverter(w, h, downSampler, uBicubic), new YSbSrColorModelConverter(w, h), new YCbCrColorModelConverter(w, h, downSampler, uBilinear), new YCbCrColorModelConverter(w, h, downSampler, ugBilinear), new YSbSrColorModelConverter(w, h, dDWT, uDWT), new YSbSrColorModelConverter(w, h), new YCoCgColorModelConverter(w, h), new ReversibleYUVColorModelConverter(w, h) }; ModelInfo[] models = new ModelInfo[] { new ModelInfo("XYZ", false, null), new ModelInfo("YCbCr - bicubic", true, uBicubic), new ModelInfo("YCbCr - built-in (bilinear)", true, null), new ModelInfo("YCbCr - bilinear", true, uBilinear), new ModelInfo("YCbCr - guided bilinear", true, ugBilinear), new ModelInfo("YCbCr - DWT", true, uDWT), new ModelInfo("YCbCr", false, null), new ModelInfo("YSbSr - bicubic", true, uBicubic), new ModelInfo("YSbSr - built-in (bilinear)", true, null), new ModelInfo("YSbSr - bilinear", true, uBilinear), new ModelInfo("YSbSr - guided bilinear", true, ugBilinear), new ModelInfo("YSbSr - DWT", true, uDWT), new ModelInfo("YSbSr", false, null), new ModelInfo("YCoCg", false, null), new ModelInfo("Reversible YUV", false, null), }; JFrame frame = new JFrame("Original"); frame.setBounds(20, 30, w, h); frame.add(new JLabel(new ImageIcon(img))); frame.setVisible(true); System.out.println("================ Test round trip RGB -> YXX -> RGB ================"); for (int i=0; i<cvts.length; i++) { test(models[i], cvts[i], rgb, rgb2, w, h, i+1); } Thread.sleep(35000); } catch (Exception e) { e.printStackTrace(); } System.exit(0); } private static void test(ModelInfo model, ColorModelConverter cvt, int[] rgb1, int[] rgb2, int w, int h, int iter) { long sum = 0; int nn = 500; int[] y1 = new int[rgb1.length]; int[] u1 = new int[rgb1.length]; int[] v1 = new int[rgb1.length]; Arrays.fill(rgb2, 0x0A0A0A0A); if (model.is420) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV420); if (model.us instanceof GuidedBilinearUpSampler) ((GuidedBilinearUpSampler) model.us).setGuide(y1); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV420); } else { if (cvt instanceof XYZColorModelConverter) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.XYZ); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.XYZ); } else { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV444); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV444); } } // Compute PSNR // Computing the SSIM makes little sense since y,u and v are shared // by both images => SSIM = 1.0 String name = model.name + ((model.is420) ? " - 420 " : " - 444 "); System.out.println("\n"+name); ImageQualityMonitor iqm = new ImageQualityMonitor(w, h); int psnr1024 = iqm.computePSNR(rgb1, rgb2); System.out.println("PSNR : "+ ((psnr1024 == 0) ? "Infinite" : ((float) psnr1024 / 1024))); String title = name + "- PSNR: "+ ((psnr1024 == 0) ? "Infinite" : ((float) psnr1024 / 1024)); GraphicsDevice gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]; GraphicsConfiguration gc = gs.getDefaultConfiguration(); BufferedImage img2 = gc.createCompatibleImage(w, h, Transparency.OPAQUE); img2.getRaster().setDataElements(0, 0, w, h, rgb2); JFrame frame2 = new JFrame(title); frame2.setBounds(20+(iter)*100, 30+(iter*30), w, h); ImageIcon newIcon = new ImageIcon(img2); frame2.add(new JLabel(newIcon)); frame2.setVisible(true); System.out.println("Speed test"); if (model.is420) { if (model.us instanceof GuidedBilinearUpSampler) ((GuidedBilinearUpSampler) model.us).setGuide(y1); for (int i=0; i<nn; i++) { Arrays.fill(rgb2, 0); long before = System.nanoTime(); cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV420); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV420); long after = System.nanoTime(); sum += (after - before); } } else { for (int i=0; i<nn; i++) { Arrays.fill(rgb2, 0); long before = System.nanoTime(); if (cvt instanceof XYZColorModelConverter) { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.XYZ); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.XYZ); } else { cvt.convertRGBtoYUV(rgb1, y1, u1, v1, ColorModelType.YUV444); cvt.convertYUVtoRGB(y1, u1, v1, rgb2, ColorModelType.YUV444); } long after = System.nanoTime(); sum += (after - before); } } System.out.println("Elapsed [ms] ("+nn+" iterations): "+sum/1000000); } static class ModelInfo { public ModelInfo(String name, boolean is420, UpSampler us) { this.name = name; this.is420 = is420; this.us = us; } final String name; final boolean is420; final UpSampler us; } }
9,509
0.601849
0.576951
248
37.383064
26.265135
101
false
false
0
0
0
0
0
0
1.254032
false
false
12
0bc48d7e137398cd20114f0cdd63a64f4751c254
6,914,897,373,507
e19de3a4108c809368646942feb77176d1093c92
/POO2/Pratica7/src/pratica7/HomeTheaterFacade.java
5de327638ed59857a48303deaac219bc5f3c712b
[ "MIT" ]
permissive
matheuscr30/UFU
https://github.com/matheuscr30/UFU
c1ce7f496308dd47fa7031cd54beacc97abf68a5
e947e5a4ccd5c025cb8ef6e00b42ea1160742712
refs/heads/master
2022-12-24T12:20:56.586000
2020-12-16T19:39:05
2020-12-16T19:39:05
90,077,279
0
0
MIT
false
2022-11-22T04:14:46
2017-05-02T20:57:00
2020-12-16T19:39:52
2022-11-22T04:14:43
445,769
0
0
12
Python
false
false
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pratica7; /** * * @author matheus */ public class HomeTheaterFacade { private Amplificador amplificador; private Tela tela; private Pipoqueira pipoqueira; private LuzAmbiente luzAmbiente; private DVDPlayer dvdPlayer; private CDPlayer cdPlayer; private Projetor projetor; private Sintonizador sintonizador; public HomeTheaterFacade(Amplificador amplificador, Tela tela, Pipoqueira pipoqueira, LuzAmbiente luzAmbiente, DVDPlayer dvdPlayer, CDPlayer cdPlayer, Projetor projetor, Sintonizador sintonizador) { this.amplificador = amplificador; this.tela = tela; this.pipoqueira = pipoqueira; this.luzAmbiente = luzAmbiente; this.dvdPlayer = dvdPlayer; this.cdPlayer = cdPlayer; this.projetor = projetor; this.sintonizador = sintonizador; } public void assistirFilme(Filme filme){ System.out.println("Iniciando o filme"); pipoqueira.ligar(); pipoqueira.cozinhar(); luzAmbiente.dim(); tela.descer(); projetor.ligar(); projetor.setInput(dvdPlayer); projetor.modoWideScreen(); amplificador.ligar(); amplificador.setDVD(); amplificador.setSurroundAudio(); amplificador.setVolume(); dvdPlayer.ligar(); dvdPlayer.play(filme); System.out.println("Divirta-se :)"); } public void pararFilme(){ System.out.println("Parando o filme"); pipoqueira.desligar(); luzAmbiente.desligar(); projetor.desligar(); tela.subir(); amplificador.desligar(); dvdPlayer.stop(); dvdPlayer.eject(); dvdPlayer.desligar(); System.out.println("Adeus"); } public void ouvirCD(CD cd){ System.out.println("Iniciando o CD"); amplificador.ligar(); amplificador.setCD(); amplificador.setSurroundAudio(); amplificador.setVolume(); cdPlayer.ligar(); cdPlayer.play(cd); System.out.println("Divirta-se :)"); } public void pararCD(){ System.out.println("Parando o CD"); amplificador.desligar(); cdPlayer.stop(); cdPlayer.eject(); cdPlayer.desligar(); System.out.println("Adeus"); } }
UTF-8
Java
2,499
java
HomeTheaterFacade.java
Java
[ { "context": "e editor.\n */\npackage pratica7;\n\n/**\n *\n * @author matheus\n */\npublic class HomeTheaterFacade {\n private ", "end": 229, "score": 0.9960662722587585, "start": 222, "tag": "USERNAME", "value": "matheus" } ]
null
[]
/* * 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 pratica7; /** * * @author matheus */ public class HomeTheaterFacade { private Amplificador amplificador; private Tela tela; private Pipoqueira pipoqueira; private LuzAmbiente luzAmbiente; private DVDPlayer dvdPlayer; private CDPlayer cdPlayer; private Projetor projetor; private Sintonizador sintonizador; public HomeTheaterFacade(Amplificador amplificador, Tela tela, Pipoqueira pipoqueira, LuzAmbiente luzAmbiente, DVDPlayer dvdPlayer, CDPlayer cdPlayer, Projetor projetor, Sintonizador sintonizador) { this.amplificador = amplificador; this.tela = tela; this.pipoqueira = pipoqueira; this.luzAmbiente = luzAmbiente; this.dvdPlayer = dvdPlayer; this.cdPlayer = cdPlayer; this.projetor = projetor; this.sintonizador = sintonizador; } public void assistirFilme(Filme filme){ System.out.println("Iniciando o filme"); pipoqueira.ligar(); pipoqueira.cozinhar(); luzAmbiente.dim(); tela.descer(); projetor.ligar(); projetor.setInput(dvdPlayer); projetor.modoWideScreen(); amplificador.ligar(); amplificador.setDVD(); amplificador.setSurroundAudio(); amplificador.setVolume(); dvdPlayer.ligar(); dvdPlayer.play(filme); System.out.println("Divirta-se :)"); } public void pararFilme(){ System.out.println("Parando o filme"); pipoqueira.desligar(); luzAmbiente.desligar(); projetor.desligar(); tela.subir(); amplificador.desligar(); dvdPlayer.stop(); dvdPlayer.eject(); dvdPlayer.desligar(); System.out.println("Adeus"); } public void ouvirCD(CD cd){ System.out.println("Iniciando o CD"); amplificador.ligar(); amplificador.setCD(); amplificador.setSurroundAudio(); amplificador.setVolume(); cdPlayer.ligar(); cdPlayer.play(cd); System.out.println("Divirta-se :)"); } public void pararCD(){ System.out.println("Parando o CD"); amplificador.desligar(); cdPlayer.stop(); cdPlayer.eject(); cdPlayer.desligar(); System.out.println("Adeus"); } }
2,499
0.630252
0.629852
83
29.108435
24.108696
202
false
false
0
0
0
0
0
0
0.795181
false
false
12
24fdecca73b8e03b3f118a30d8f695e237f3641b
17,085,379,943,590
aa870a6f221a701373fadede64556672b618be71
/src/test/java/edu/piotrjonski/scrumus/business/CommentManagerIT.java
0682ec34286816a528510c7339017b8a8f5edfcc
[]
no_license
sta-szek/scrumus
https://github.com/sta-szek/scrumus
bfbae47ae9f4394a21eecd781c8a4d67a7b91cca
487f3af478596c00511821659f28df21cfde98d8
refs/heads/master
2021-03-24T12:35:32.046000
2016-02-17T09:55:58
2016-02-17T09:55:58
45,568,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.piotrjonski.scrumus.business; import edu.piotrjonski.scrumus.dao.*; import edu.piotrjonski.scrumus.domain.*; import edu.piotrjonski.scrumus.utils.TestUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.NotSupportedException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Arquillian.class) public class CommentManagerIT { public static final String COMMENT_BODY = "projKey"; private Developer lastDeveloper; private Retrospective lastRetrospective; private IssueType lastIssueType; private Issue lastIssue; private Priority lastPriority; private State lastState; @Inject private PriorityDAO priorityDAO; @Inject private StateDAO stateDAO; @Inject private IssueTypeDAO issueTypeDAO; @Inject private IssueDAO issueDAO; @Inject private DeveloperDAO developerDAO; @Inject private CommentManager commentManager; @Inject private RetrospectiveDAO retrospectiveDAO; @Inject private UserTransaction userTransaction; @PersistenceContext private EntityManager entityManager; @Deployment public static WebArchive createDeployment() { return TestUtils.createDeployment(); } @Before public void dropAllCommentsAndStartTransaction() throws Exception { clearData(); startTransaction(); } @After public void commitTransaction() throws Exception { userTransaction.commit(); } @Test public void shouldAddCommentToIssue() { // given Comment comment = createComment(); // when Comment savedComment = commentManager.addCommentToIssue(comment, lastIssue) .get(); List<Comment> result = issueDAO.findById(lastIssue.getId()) .get() .getComments(); // then assertThat(result).contains(savedComment); } @Test public void shouldReturnEmptyOptionalWhenIssueDoesNotExist() { // given // when Optional<Comment> result = commentManager.addCommentToIssue(createComment(), createIssue()); // then assertThat(result).isEmpty(); } @Test public void shouldRemoveCommentFromIssue() { // given Comment comment = createComment(); Comment savedComment = commentManager.addCommentToIssue(comment, lastIssue) .get(); // when commentManager.removeCommentFromIssue(savedComment, lastIssue); List<Comment> result = issueDAO.findById(lastIssue.getId()) .get() .getComments(); // then assertThat(result).doesNotContain(savedComment); } @Test public void shouldAddCommentToRetrospective() { // given Comment comment = createComment(); // when Comment savedComment = commentManager.addCommentToRetrospective(comment, lastRetrospective) .get(); List<Comment> result = retrospectiveDAO.findById(lastRetrospective.getId()) .get() .getComments(); // then assertThat(result).contains(savedComment); } @Test public void shouldReturnEmptyOptionalWhenRetrospectiveDoesNotExist() { // given // when Optional<Comment> result = commentManager.addCommentToRetrospective(createComment(), createRetrospective()); // then assertThat(result).isEmpty(); } @Test public void shouldRemoveCommentFromRetrospective() { // given Comment comment = createComment(); Comment savedComment = commentManager.addCommentToRetrospective(comment, lastRetrospective) .get(); // when commentManager.removeCommentFromRetrospective(savedComment, lastRetrospective); List<Comment> result = retrospectiveDAO.findById(lastRetrospective.getId()) .get() .getComments(); // then assertThat(result).doesNotContain(savedComment); } private Retrospective createRetrospective() { Retrospective retrospective = new Retrospective(); retrospective.setDescription("desc"); return retrospective; } private void startTransaction() throws SystemException, NotSupportedException, AlreadyExistException { userTransaction.begin(); entityManager.joinTransaction(); lastDeveloper = developerDAO.saveOrUpdate(createDeveloper()) .get(); lastPriority = priorityDAO.saveOrUpdate(createPriority()) .get(); lastState = stateDAO.saveOrUpdate(createState()) .get(); lastIssueType = issueTypeDAO.saveOrUpdate(createIssueType()) .get(); lastRetrospective = retrospectiveDAO.saveOrUpdate(createRetrospective()) .get(); lastIssue = issueDAO.saveOrUpdate(createIssue()) .get(); } private void clearData() throws Exception { userTransaction.begin(); entityManager.joinTransaction(); entityManager.createQuery("DELETE FROM RetrospectiveEntity ") .executeUpdate(); entityManager.createQuery("DELETE FROM IssueEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM IssueTypeEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM PriorityEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM StateEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM CommentEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM DeveloperEntity ") .executeUpdate(); userTransaction.commit(); entityManager.clear(); } private Developer createDeveloper() { Developer developer = new Developer(); developer.setEmail("email"); developer.setFirstName("email"); developer.setSurname("email"); developer.setUsername("email"); return developer; } private Comment createComment() { Comment comment = new Comment(); comment.setDeveloperId(lastDeveloper.getId()); comment.setCommentBody(COMMENT_BODY); comment.setCreationDate(LocalDateTime.now()); return comment; } private Issue createIssue() { Issue issue = new Issue(); issue.setAssigneeId(lastDeveloper.getId()); issue.setProjectKey("key"); issue.setReporterId(lastDeveloper.getId()); issue.setIssueType(lastIssueType); issue.setPriority(lastPriority); issue.setState(lastState); issue.setSummary("summary"); return issue; } private IssueType createIssueType() { IssueType issueType = new IssueType(); issueType.setName("task"); return issueType; } private Priority createPriority() { Priority priority = new Priority(); priority.setName("name"); return priority; } private State createState() { State state = new State(); state.setName("name"); return state; } }
UTF-8
Java
8,235
java
CommentManagerIT.java
Java
[ { "context": "tSurname(\"email\");\n developer.setUsername(\"email\");\n return developer;\n }\n\n private C", "end": 7102, "score": 0.5454989075660706, "start": 7097, "tag": "USERNAME", "value": "email" } ]
null
[]
package edu.piotrjonski.scrumus.business; import edu.piotrjonski.scrumus.dao.*; import edu.piotrjonski.scrumus.domain.*; import edu.piotrjonski.scrumus.utils.TestUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.NotSupportedException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Arquillian.class) public class CommentManagerIT { public static final String COMMENT_BODY = "projKey"; private Developer lastDeveloper; private Retrospective lastRetrospective; private IssueType lastIssueType; private Issue lastIssue; private Priority lastPriority; private State lastState; @Inject private PriorityDAO priorityDAO; @Inject private StateDAO stateDAO; @Inject private IssueTypeDAO issueTypeDAO; @Inject private IssueDAO issueDAO; @Inject private DeveloperDAO developerDAO; @Inject private CommentManager commentManager; @Inject private RetrospectiveDAO retrospectiveDAO; @Inject private UserTransaction userTransaction; @PersistenceContext private EntityManager entityManager; @Deployment public static WebArchive createDeployment() { return TestUtils.createDeployment(); } @Before public void dropAllCommentsAndStartTransaction() throws Exception { clearData(); startTransaction(); } @After public void commitTransaction() throws Exception { userTransaction.commit(); } @Test public void shouldAddCommentToIssue() { // given Comment comment = createComment(); // when Comment savedComment = commentManager.addCommentToIssue(comment, lastIssue) .get(); List<Comment> result = issueDAO.findById(lastIssue.getId()) .get() .getComments(); // then assertThat(result).contains(savedComment); } @Test public void shouldReturnEmptyOptionalWhenIssueDoesNotExist() { // given // when Optional<Comment> result = commentManager.addCommentToIssue(createComment(), createIssue()); // then assertThat(result).isEmpty(); } @Test public void shouldRemoveCommentFromIssue() { // given Comment comment = createComment(); Comment savedComment = commentManager.addCommentToIssue(comment, lastIssue) .get(); // when commentManager.removeCommentFromIssue(savedComment, lastIssue); List<Comment> result = issueDAO.findById(lastIssue.getId()) .get() .getComments(); // then assertThat(result).doesNotContain(savedComment); } @Test public void shouldAddCommentToRetrospective() { // given Comment comment = createComment(); // when Comment savedComment = commentManager.addCommentToRetrospective(comment, lastRetrospective) .get(); List<Comment> result = retrospectiveDAO.findById(lastRetrospective.getId()) .get() .getComments(); // then assertThat(result).contains(savedComment); } @Test public void shouldReturnEmptyOptionalWhenRetrospectiveDoesNotExist() { // given // when Optional<Comment> result = commentManager.addCommentToRetrospective(createComment(), createRetrospective()); // then assertThat(result).isEmpty(); } @Test public void shouldRemoveCommentFromRetrospective() { // given Comment comment = createComment(); Comment savedComment = commentManager.addCommentToRetrospective(comment, lastRetrospective) .get(); // when commentManager.removeCommentFromRetrospective(savedComment, lastRetrospective); List<Comment> result = retrospectiveDAO.findById(lastRetrospective.getId()) .get() .getComments(); // then assertThat(result).doesNotContain(savedComment); } private Retrospective createRetrospective() { Retrospective retrospective = new Retrospective(); retrospective.setDescription("desc"); return retrospective; } private void startTransaction() throws SystemException, NotSupportedException, AlreadyExistException { userTransaction.begin(); entityManager.joinTransaction(); lastDeveloper = developerDAO.saveOrUpdate(createDeveloper()) .get(); lastPriority = priorityDAO.saveOrUpdate(createPriority()) .get(); lastState = stateDAO.saveOrUpdate(createState()) .get(); lastIssueType = issueTypeDAO.saveOrUpdate(createIssueType()) .get(); lastRetrospective = retrospectiveDAO.saveOrUpdate(createRetrospective()) .get(); lastIssue = issueDAO.saveOrUpdate(createIssue()) .get(); } private void clearData() throws Exception { userTransaction.begin(); entityManager.joinTransaction(); entityManager.createQuery("DELETE FROM RetrospectiveEntity ") .executeUpdate(); entityManager.createQuery("DELETE FROM IssueEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM IssueTypeEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM PriorityEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM StateEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM CommentEntity") .executeUpdate(); entityManager.createQuery("DELETE FROM DeveloperEntity ") .executeUpdate(); userTransaction.commit(); entityManager.clear(); } private Developer createDeveloper() { Developer developer = new Developer(); developer.setEmail("email"); developer.setFirstName("email"); developer.setSurname("email"); developer.setUsername("email"); return developer; } private Comment createComment() { Comment comment = new Comment(); comment.setDeveloperId(lastDeveloper.getId()); comment.setCommentBody(COMMENT_BODY); comment.setCreationDate(LocalDateTime.now()); return comment; } private Issue createIssue() { Issue issue = new Issue(); issue.setAssigneeId(lastDeveloper.getId()); issue.setProjectKey("key"); issue.setReporterId(lastDeveloper.getId()); issue.setIssueType(lastIssueType); issue.setPriority(lastPriority); issue.setState(lastState); issue.setSummary("summary"); return issue; } private IssueType createIssueType() { IssueType issueType = new IssueType(); issueType.setName("task"); return issueType; } private Priority createPriority() { Priority priority = new Priority(); priority.setName("name"); return priority; } private State createState() { State state = new State(); state.setName("name"); return state; } }
8,235
0.616151
0.616151
261
30.555555
24.558043
116
false
false
0
0
0
0
0
0
0.475096
false
false
12
1ef2c3f3ad69dce406b8b9517f23fcd76594fc79
20,572,893,385,721
bdabf99dff3893bb92e43bb1e45bd23713b6b4a3
/ltiv1p3/src/main/java/com/example/ltiv1p3/demo/controller/JWKController.java
ff5cc852a311ef1246ea22c44f87b828e79110dc
[]
no_license
70ekanetugu/practice
https://github.com/70ekanetugu/practice
0b6847c9169f2e9a18f42281a9ca1e3c90e569b5
4052178848e3913e324b7600a9cad4b7cc068b6a
refs/heads/master
2020-04-28T11:14:55.655000
2020-02-20T17:05:57
2020-02-20T17:05:57
175,230,432
0
0
null
false
2020-07-16T21:57:59
2019-03-12T14:34:17
2020-02-20T17:06:22
2020-07-16T21:57:57
4,214
0
0
6
Java
false
false
package com.example.ltiv1p3.demo.controller; import com.example.ltiv1p3.demo.entity.ToolBean; import com.google.gson.Gson; import io.fusionauth.jwks.domain.JSONWebKey; import io.fusionauth.jwt.domain.Algorithm; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping(value="/jwks", method={RequestMethod.GET, RequestMethod.POST}) public class JWKController { @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String getJwk(){ ToolBean bean = new ToolBean(); JSONWebKey jwk = JSONWebKey.build(bean.getPublicKey()); jwk.kid = "naoeKey1"; jwk.alg = Algorithm.RS256; String json = jwk.toJSON(); // Map<String, Object> map = new HashMap<>(); // List<Object> list = new ArrayList<>(); // list.add(json); // map.put("keys", list); // Gson gson = new Gson(); // json = gson.toJson(map); System.out.println(json); json = "{\"keys\":["+json+"]}"; System.out.println(json); return json; } }
UTF-8
Java
1,307
java
JWKController.java
Java
[]
null
[]
package com.example.ltiv1p3.demo.controller; import com.example.ltiv1p3.demo.entity.ToolBean; import com.google.gson.Gson; import io.fusionauth.jwks.domain.JSONWebKey; import io.fusionauth.jwt.domain.Algorithm; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping(value="/jwks", method={RequestMethod.GET, RequestMethod.POST}) public class JWKController { @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String getJwk(){ ToolBean bean = new ToolBean(); JSONWebKey jwk = JSONWebKey.build(bean.getPublicKey()); jwk.kid = "naoeKey1"; jwk.alg = Algorithm.RS256; String json = jwk.toJSON(); // Map<String, Object> map = new HashMap<>(); // List<Object> list = new ArrayList<>(); // list.add(json); // map.put("keys", list); // Gson gson = new Gson(); // json = gson.toJson(map); System.out.println(json); json = "{\"keys\":["+json+"]}"; System.out.println(json); return json; } }
1,307
0.719969
0.713849
41
30.878048
20.822355
83
false
false
0
0
0
0
0
0
0.829268
false
false
12
4d030e1ebddeb217b81edcf940105998874cce81
20,572,893,386,601
21fb79b4daca9edcbe53eaedc6222db6904855d3
/app/src/main/java/ru/divizdev/notifytodo/entities/NTask.java
fa5c6a6471009df686226c6873d4ed601da16862
[]
no_license
divizdev/NotifyToDo
https://github.com/divizdev/NotifyToDo
04055a0a34a7c2b0a2f627989b6316b9b503ac0b
35c31a380caca54ff752c45b63a5fee46e2c6e31
refs/heads/master
2018-12-24T22:52:01.517000
2018-11-17T18:53:33
2018-11-17T18:53:33
126,727,811
0
0
null
false
2018-12-30T11:03:29
2018-03-25T18:34:04
2018-11-17T18:53:35
2018-12-30T11:03:29
288
0
0
0
Java
false
null
package ru.divizdev.notifytodo.entities; public class NTask { private int _id; private String _title; private String _description; private Boolean _isDone; public NTask(String title, String description, Boolean isDone){ this(-1, title, description, isDone); } public NTask(int id, String title, String description, Boolean isDone) { _id = id; _title = title; _description = description; _isDone = isDone; } public int getId() { return _id; } public void setDone(Boolean done){ _isDone = done; } public static NTask emptyNTask() { return new NTask("", "", false); } public Boolean isDone() { return _isDone; } public String getTitle() { return _title; } public String getDescription() { return _description; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NTask that = (NTask) o; return (getTitle() != null ? getTitle().equals(that.getTitle()) : that.getTitle() == null) && (getDescription() != null ? getDescription().equals(that.getDescription()) : that.getDescription() == null) && (_isDone != null ? _isDone.equals(that._isDone) : that._isDone == null); } @Override public int hashCode() { int result = getTitle() != null ? getTitle().hashCode() : 0; result = 31 * result + (getDescription() != null ? getDescription().hashCode() : 0); result = 31 * result + (_isDone != null ? _isDone.hashCode() : 0); return result; } }
UTF-8
Java
1,681
java
NTask.java
Java
[]
null
[]
package ru.divizdev.notifytodo.entities; public class NTask { private int _id; private String _title; private String _description; private Boolean _isDone; public NTask(String title, String description, Boolean isDone){ this(-1, title, description, isDone); } public NTask(int id, String title, String description, Boolean isDone) { _id = id; _title = title; _description = description; _isDone = isDone; } public int getId() { return _id; } public void setDone(Boolean done){ _isDone = done; } public static NTask emptyNTask() { return new NTask("", "", false); } public Boolean isDone() { return _isDone; } public String getTitle() { return _title; } public String getDescription() { return _description; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NTask that = (NTask) o; return (getTitle() != null ? getTitle().equals(that.getTitle()) : that.getTitle() == null) && (getDescription() != null ? getDescription().equals(that.getDescription()) : that.getDescription() == null) && (_isDone != null ? _isDone.equals(that._isDone) : that._isDone == null); } @Override public int hashCode() { int result = getTitle() != null ? getTitle().hashCode() : 0; result = 31 * result + (getDescription() != null ? getDescription().hashCode() : 0); result = 31 * result + (_isDone != null ? _isDone.hashCode() : 0); return result; } }
1,681
0.579417
0.574658
63
25.682539
39.556599
285
false
false
0
0
0
0
0
0
0.571429
false
false
12
8c889b3c5d69b9bc19d4872436043aed92da7d13
16,664,473,138,243
fe490f592c9334f2ac7348694435cb608fb6a706
/src/StreamsMap2.java
1b33fa04810e6af110a67eaa7fc34c4d19f73172
[]
no_license
FredrikGustafsson/Java8Tests
https://github.com/FredrikGustafsson/Java8Tests
edae63af2894f7841a983c59d5c9953a9fa6dbe2
1260dcda6f65d2eb82cced7843fa9132691cc820
refs/heads/master
2020-04-30T20:48:06.701000
2019-03-22T13:53:20
2019-03-22T13:53:20
177,078,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamsMap2 { public static void main(String[] args) { // Streams apply to data type List<Integer> num = Arrays.asList(1,2,3,4,5); List<Integer> collect1 = num.stream().map(n -> n + n).collect(Collectors.toList()); System.out.println(collect1);//[2, 4, 6, 8, 10] } }
UTF-8
Java
436
java
StreamsMap2.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamsMap2 { public static void main(String[] args) { // Streams apply to data type List<Integer> num = Arrays.asList(1,2,3,4,5); List<Integer> collect1 = num.stream().map(n -> n + n).collect(Collectors.toList()); System.out.println(collect1);//[2, 4, 6, 8, 10] } }
436
0.649083
0.616973
16
26.25
25.138367
91
false
false
0
0
0
0
0
0
0.9375
false
false
12
28fe1ef99d04a3f32d3f0e7e81bd9446713bd8e4
32,942,399,204,904
2169f62b098e0eb8b52f29be2c266a40dd5225a1
/web-console/web-console-server/src/test/java/org/apache/ignite/console/services/NotificationServiceTest.java
a4c7cc90762c37be6827660a00817741cba63230
[ "Apache-2.0", "LicenseRef-scancode-gutenberg-2020", "CC0-1.0", "BSD-3-Clause" ]
permissive
junphine/ignite
https://github.com/junphine/ignite
74315b8e212d66517312bb6bb0a3f41f5452e9eb
af9fc81cdf5e001c872de00879e5008c9f380468
refs/heads/master
2023-08-03T10:59:27.845000
2023-07-28T10:49:46
2023-07-28T10:49:46
149,442,849
1
0
Apache-2.0
true
2018-09-19T11:51:30
2018-09-19T11:51:30
2018-09-19T10:16:13
2018-09-19T11:41:44
288,245
0
0
0
null
false
null
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.console.services; import org.apache.ignite.console.MockConfiguration; import org.apache.ignite.console.dto.Account; import org.apache.ignite.console.notification.Notification; import org.apache.ignite.console.notification.NotificationDescriptor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; /** * Test for notification service. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {MockConfiguration.class}) public class NotificationServiceTest { /** Mail service. */ @MockBean private IMailService mailSrvc; /** Notifivation service. */ @Autowired private NotificationService srvc; /** * Should send notification. */ @Test public void testSendNotification() throws Exception { Account acc = new Account(); acc.setEmail("email@email"); srvc.sendEmail(NotificationDescriptor.WELCOME_LETTER, acc); ArgumentCaptor<Notification> captor = ArgumentCaptor.forClass(Notification.class); Mockito.verify(mailSrvc, Mockito.times(1)).send(captor.capture()); Assert.assertEquals("http://localhost/", captor.getValue().getOrigin()); Assert.assertEquals(NotificationDescriptor.WELCOME_LETTER, captor.getValue().getDescriptor()); Assert.assertEquals(acc.getEmail(), captor.getValue().getRecipient().getEmail()); } }
UTF-8
Java
2,383
java
NotificationServiceTest.java
Java
[]
null
[]
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.console.services; import org.apache.ignite.console.MockConfiguration; import org.apache.ignite.console.dto.Account; import org.apache.ignite.console.notification.Notification; import org.apache.ignite.console.notification.NotificationDescriptor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; /** * Test for notification service. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {MockConfiguration.class}) public class NotificationServiceTest { /** Mail service. */ @MockBean private IMailService mailSrvc; /** Notifivation service. */ @Autowired private NotificationService srvc; /** * Should send notification. */ @Test public void testSendNotification() throws Exception { Account acc = new Account(); acc.setEmail("email@email"); srvc.sendEmail(NotificationDescriptor.WELCOME_LETTER, acc); ArgumentCaptor<Notification> captor = ArgumentCaptor.forClass(Notification.class); Mockito.verify(mailSrvc, Mockito.times(1)).send(captor.capture()); Assert.assertEquals("http://localhost/", captor.getValue().getOrigin()); Assert.assertEquals(NotificationDescriptor.WELCOME_LETTER, captor.getValue().getDescriptor()); Assert.assertEquals(acc.getEmail(), captor.getValue().getRecipient().getEmail()); } }
2,383
0.754092
0.751574
64
36.234375
29.602968
102
false
false
0
0
0
0
0
0
0.53125
false
false
12
d12755a6bc94a37ae933e51358b12c4f1b67875b
31,413,390,826,078
36c99521fcd608e85e1f52d345dbdef868a4cbbb
/demo-zipkin/demo-user/src/main/java/com/demo/ysz/zipkin/user/UserApi.java
716a2ded12b73f5715664a6ae92c1fcb63be9ff5
[]
no_license
loposition/demo
https://github.com/loposition/demo
4193cab86048cbc12e86ac28d1d490a24776f209
d5318e3a473fa54b4b8d8681482b065922756692
refs/heads/master
2021-08-31T16:47:17.409000
2017-12-22T04:11:42
2017-12-22T04:11:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.ysz.zipkin.user; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <B>描述:</B><br/> <B>作者:</B> carl.yu <br/> <B>时间:</B> 2017/12/2 <br/> <B>版本:</B><br/> */ @RestController public class UserApi { @RequestMapping("user/load") public String loadUser(){ return "carl"; } }
UTF-8
Java
405
java
UserApi.java
Java
[ { "context": "RestController;\n\n/**\n * <B>描述:</B><br/> <B>作者:</B> carl.yu <br/> <B>时间:</B> 2017/12/2 <br/> <B>版本:</B><br/>\n", "end": 203, "score": 0.998921275138855, "start": 196, "tag": "USERNAME", "value": "carl.yu" } ]
null
[]
package com.demo.ysz.zipkin.user; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <B>描述:</B><br/> <B>作者:</B> carl.yu <br/> <B>时间:</B> 2017/12/2 <br/> <B>版本:</B><br/> */ @RestController public class UserApi { @RequestMapping("user/load") public String loadUser(){ return "carl"; } }
405
0.677165
0.658793
16
22.8125
25.661787
86
false
false
0
0
0
0
0
0
0.25
false
false
12
cbb22ca4e3480c400f324f604a6d714ff3997c9f
18,210,661,381,503
97fd02f71b45aa235f917e79dd68b61c62b56c1c
/src/main/java/com/tencentcloudapi/sms/v20190711/models/DescribeSmsSignListRequest.java
60a8187a59e89695d040c1d09059f8592aa30da9
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-java
https://github.com/TencentCloud/tencentcloud-sdk-java
7df922f7c5826732e35edeab3320035e0cdfba05
09fa672d75e5ca33319a23fcd8b9ca3d2afab1ec
refs/heads/master
2023-09-04T10:51:57.854000
2023-09-01T03:21:09
2023-09-01T03:21:09
129,837,505
537
317
Apache-2.0
false
2023-09-13T02:42:03
2018-04-17T02:58:16
2023-09-04T04:59:58
2023-09-13T02:42:02
100,723
481
297
13
Java
false
false
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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. * 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.tencentcloudapi.sms.v20190711.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeSmsSignListRequest extends AbstractModel{ /** * 签名 ID 数组。 */ @SerializedName("SignIdSet") @Expose private Long [] SignIdSet; /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ @SerializedName("International") @Expose private Long International; /** * Get 签名 ID 数组。 * @return SignIdSet 签名 ID 数组。 */ public Long [] getSignIdSet() { return this.SignIdSet; } /** * Set 签名 ID 数组。 * @param SignIdSet 签名 ID 数组。 */ public void setSignIdSet(Long [] SignIdSet) { this.SignIdSet = SignIdSet; } /** * Get 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 * @return International 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ public Long getInternational() { return this.International; } /** * Set 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 * @param International 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ public void setInternational(Long International) { this.International = International; } public DescribeSmsSignListRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeSmsSignListRequest(DescribeSmsSignListRequest source) { if (source.SignIdSet != null) { this.SignIdSet = new Long[source.SignIdSet.length]; for (int i = 0; i < source.SignIdSet.length; i++) { this.SignIdSet[i] = new Long(source.SignIdSet[i]); } } if (source.International != null) { this.International = new Long(source.International); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamArraySimple(map, prefix + "SignIdSet.", this.SignIdSet); this.setParamSimple(map, prefix + "International", this.International); } }
UTF-8
Java
3,291
java
DescribeSmsSignListRequest.java
Java
[]
null
[]
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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. * 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.tencentcloudapi.sms.v20190711.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeSmsSignListRequest extends AbstractModel{ /** * 签名 ID 数组。 */ @SerializedName("SignIdSet") @Expose private Long [] SignIdSet; /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ @SerializedName("International") @Expose private Long International; /** * Get 签名 ID 数组。 * @return SignIdSet 签名 ID 数组。 */ public Long [] getSignIdSet() { return this.SignIdSet; } /** * Set 签名 ID 数组。 * @param SignIdSet 签名 ID 数组。 */ public void setSignIdSet(Long [] SignIdSet) { this.SignIdSet = SignIdSet; } /** * Get 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 * @return International 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ public Long getInternational() { return this.International; } /** * Set 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 * @param International 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ public void setInternational(Long International) { this.International = International; } public DescribeSmsSignListRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeSmsSignListRequest(DescribeSmsSignListRequest source) { if (source.SignIdSet != null) { this.SignIdSet = new Long[source.SignIdSet.length]; for (int i = 0; i < source.SignIdSet.length; i++) { this.SignIdSet[i] = new Long(source.SignIdSet[i]); } } if (source.International != null) { this.International = new Long(source.International); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamArraySimple(map, prefix + "SignIdSet.", this.SignIdSet); this.setParamSimple(map, prefix + "International", this.International); } }
3,291
0.643511
0.632328
109
26.06422
25.493038
89
false
false
0
0
0
0
0
0
0.321101
false
false
12
f4e63b6ace71622d3fbfecca42d97cb36f62bd64
24,000,277,302,120
0c643d16a3076818a1740fb6609d90ef774978c9
/agency/src/main/java/com/maidirui/agency/network/entity/product/RequirementListEntity.java
7f12285861330767bb779061c44582c859bc224a
[]
no_license
ThisMJ/MaiDiRui
https://github.com/ThisMJ/MaiDiRui
746adb73239fe5c5a1235ed9fc8f57dd237aae08
77c1152e16427fe500b26f9d13a9e7fa0e7cdcbc
refs/heads/master
2016-12-13T01:40:44.531000
2016-11-24T07:20:59
2016-11-24T07:20:59
56,203,847
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maidirui.agency.network.entity.product; import com.maidirui.framework.network.entity.BaseEntity; import java.util.List; /** * @author tangmingjian * @date 16/6/13 上午11:33 */ public class RequirementListEntity extends BaseEntity { private List<RequirementListBean> data; public List<RequirementListBean> getData() { return data; } public void setData(List<RequirementListBean> data) { this.data = data; } }
UTF-8
Java
467
java
RequirementListEntity.java
Java
[ { "context": "aseEntity;\n\nimport java.util.List;\n\n/**\n * @author tangmingjian\n * @date 16/6/13 上午11:33\n */\npublic class Require", "end": 162, "score": 0.9993793964385986, "start": 150, "tag": "USERNAME", "value": "tangmingjian" } ]
null
[]
package com.maidirui.agency.network.entity.product; import com.maidirui.framework.network.entity.BaseEntity; import java.util.List; /** * @author tangmingjian * @date 16/6/13 上午11:33 */ public class RequirementListEntity extends BaseEntity { private List<RequirementListBean> data; public List<RequirementListBean> getData() { return data; } public void setData(List<RequirementListBean> data) { this.data = data; } }
467
0.710583
0.691145
22
20.045454
21.327484
57
false
false
0
0
0
0
0
0
0.272727
false
false
12
dde798f9d7cfb01b855c5befee64f2e2cdf71c7c
22,978,075,052,472
9e60d0bdbf4a449d5afbe3b84e03d3a813cec9b7
/src/main/java/in/oneton/idea/spring/assistant/plugin/suggestion/metadata/json/SpringConfigurationMetadataValueProviderType.java
44ada1cf52d2eb3b84c1f7cb003f4b029f45c077
[ "MIT" ]
permissive
douglsantos/intellij-spring-assistant
https://github.com/douglsantos/intellij-spring-assistant
211b1277b70250748a200164af9f563341fff0f8
62ebd44ebcc470d4ba2afd1b6e696f8f90eaf088
refs/heads/main
2023-07-20T02:01:36.025000
2021-08-30T13:15:53
2021-08-30T13:15:53
401,336,489
0
0
MIT
true
2021-08-30T12:31:17
2021-08-30T12:31:17
2021-08-30T09:07:35
2021-08-26T19:12:58
8,953
0
0
0
null
false
false
package in.oneton.idea.spring.assistant.plugin.suggestion.metadata.json; /** * Refer to https://docs.spring.io/spring-boot/docs/2.0.0.M6/reference/htmlsingle/#_value_providers */ public enum SpringConfigurationMetadataValueProviderType { any, unknown, class_reference, handle_as, logger_name, spring_bean_reference, spring_profile_name }
UTF-8
Java
343
java
SpringConfigurationMetadataValueProviderType.java
Java
[]
null
[]
package in.oneton.idea.spring.assistant.plugin.suggestion.metadata.json; /** * Refer to https://docs.spring.io/spring-boot/docs/2.0.0.M6/reference/htmlsingle/#_value_providers */ public enum SpringConfigurationMetadataValueProviderType { any, unknown, class_reference, handle_as, logger_name, spring_bean_reference, spring_profile_name }
343
0.787172
0.77551
8
41.875
42.042946
99
false
false
0
0
0
0
0
0
0.875
false
false
12
5534340a7aa9f29d5a1a4d15fc2a551198596882
13,331,578,545,954
f272279ed3a9897e34e57687c7b27e2a8ebd0d58
/tongli/src/cn/com/yearos/web/action/course/C102Action.java
c064c38fb0b38a21819b69d85640a35b6dc460ee
[]
no_license
happy6eve/tongli
https://github.com/happy6eve/tongli
ec0b0a240d9476b71d9a315c2180886105a443d2
a3015d21bf289c120d49a94b4220c66c8215a943
refs/heads/master
2018-04-11T14:57:29.165000
2015-01-18T05:51:00
2015-01-18T05:51:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 课程表管理 ActionClass * * VERSION DATE BY REASON * -------- ----------- --------------- ------------------------------------------ * 1.00 2014.04.07 wuxiaogang 程序・发布 * -------- ----------- --------------- ------------------------------------------ * Copyright 2014 童励 System. - All Rights Reserved. * */ package cn.com.yearos.web.action.course; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.log4j.Logger; import cn.com.yearos.bean.BaseUserBean; import cn.com.yearos.bean.addres.TcAddresBean; import cn.com.yearos.bean.addres.TcCourseVsAddresBean; import cn.com.yearos.bean.classes.TcClassesBean; import cn.com.yearos.bean.comment.TcCommentBean; import cn.com.yearos.bean.course.TcCourseBean; import cn.com.yearos.bean.course.TcCourseSyllabusBean; import cn.com.yearos.bean.course.TcCourseSyllabusItemsBean; import cn.com.yearos.bean.course.TcCourseSyllabusPhotoBean; import cn.com.yearos.bean.member.TcMemberBean; import cn.com.yearos.bean.student.TcStudentBean; import cn.com.yearos.bean.sys.TcSysVariableBean; import cn.com.yearos.common.CommonConstant; import cn.com.yearos.common.DateUtil; import cn.com.yearos.common.IdUtils; import cn.com.yearos.common.Validator; import cn.com.yearos.service.addres.IAddresManager; import cn.com.yearos.service.classes.IClassesManager; import cn.com.yearos.service.comment.ICommentManager; import cn.com.yearos.service.course.ICourseManager; import cn.com.yearos.service.course.ICourseSyllabusItemsManager; import cn.com.yearos.service.course.ICourseSyllabusManager; import cn.com.yearos.service.course.ICourseSyllabusPhotoManager; import cn.com.yearos.service.member.IMemberManager; import cn.com.yearos.service.student.IStudentManager; import cn.com.yearos.web.action.BaseAction; import cn.com.yearos.web.tag.PageInfo; /** * 课程表管理 ActionClass * * @author wuxiaogang * */ public class C102Action extends BaseAction { /** * 序列号 */ private static final long serialVersionUID = -3061791975484213551L; private static final transient Logger log = Logger.getLogger(C102Action.class); /** 课程表管理 业务处理*/ private ICourseSyllabusManager courseSyllabusManager; /** 课程表-详情管理 业务处理*/ private ICourseSyllabusItemsManager courseSyllabusItemsManager; /**课程信息BEAN*/ private TcCourseSyllabusBean bean; /**BEAN类 评论信息*/ private TcCommentBean cbean; /**课程信息BEAN集合*/ private List<TcCourseSyllabusBean> beans; /**会员信息管理 业务处理*/ private IMemberManager memberManager; /**学员信息管理 业务处理*/ private IStudentManager studentManager; /**课程信息管理 业务处理*/ private ICourseManager courseManager; /** 课程表管理-相册 业务处理*/ private ICourseSyllabusPhotoManager courseSyllabusPhotoManager; /**评论信息 管理业务处理*/ private ICommentManager commentManager; /**课程地址信息表 业务处理接口类。 */ private IAddresManager addresManager; /**班级信息表 业务处理接口类*/ private IClassesManager classesManager; public C102Action() { log.info("默认构造器......C102Action"); } /** * <p> * 初始化处理。 * </p> * <ol> * [功能概要] <div>初始化处理。</div> * </ol> * @return 转发字符串 */ public String init() { log.info("C102Action init........."); return "init"; } /** * <p> * 已完成的课程。 * </p> * <ol> * [功能概要] <div>已完成的课程。</div> * </ol> * @return 转发字符串 */ public String list1() { log.info("C102Action list1........."); String s="list1";//普通课程 String t=request.getParameter("t");//0 普通课程1夏令营2冬令营 if(t!=null){ if("1".equals(t)){ s="list1_1";//1夏令营 } if("2".equals(t)){ s="list1_2";//2冬令营 } } int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //--已完成课程-- bean1.setCourse_status("1"); //-- bean1.setType(t); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return s; } /** * <p> * 未完成的课程。 * </p> * <ol> * [功能概要] <div>未完成的课程。</div> * </ol> * @return 转发字符串 */ public String list2() { log.info("C102Action list2........."); String s="list2";//普通课程 String t=request.getParameter("t");//0 普通课程1夏令营2冬令营 if(t!=null){ if("1".equals(t)){ s="list2_1";//1夏令营 } if("2".equals(t)){ s="list2_2";//2冬令营 } } int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //--未完成课程-- bean1.setCourse_status("0"); //-- bean1.setType(t); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return s; } /** * <p> * 初始化处理。 * </p> * <ol> * [功能概要] <div>初始化处理。</div> * </ol> * @return 转发字符串 */ public String init2() { log.info("C102Action init2........."); int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return "init"; } /** * <p> * 信息列表。 * </p> * <ol> * [功能概要] <div>回收站。</div> * </ol> * @return 转发字符串 */ public String recycle() { log.info("C102Action recycle........."); int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("1"); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return "recycle"; } /** * <p> * 信息编辑。 * </p> * <ol> * [功能概要] <div>编辑。</div> * </ol> * @return 转发字符串 */ public String edit() { log.info("C102Action edit........."); String id=request.getParameter("id"); if(id!=null){ TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); bean=courseSyllabusManager.findDataById(bean1); //--当前学员集合--- TcCourseSyllabusItemsBean bean2=new TcCourseSyllabusItemsBean(); bean2.setCourse_syllabus_id(bean1.getId()); try { request.setAttribute("course_student_beans", courseSyllabusItemsManager.findDataIsListStudent(bean2)); if(bean!=null){ TcCourseSyllabusPhotoBean photoBean=new TcCourseSyllabusPhotoBean(); photoBean.setCourse_syllabus_id(bean1.getId()); bean.setPicBeans(courseSyllabusPhotoManager.findDataIsList(photoBean)); } } catch (Exception e) { log.error("学员集合获取出错!", e); } } String s="edit";//普通课程 if(bean==null){ bean=new TcCourseSyllabusBean(); bean.setId(IdUtils.createUUID(32)); } //---班级--- request.setAttribute("classes_beans",classesManager.findDataIsList(null)); if(Validator.isEmpty(bean.getType())){ String type=request.getParameter("type"); if(type!=null){ if("0".equals(type)){ bean.setType("0");//普通课程 }else{ bean.setType(type); s="edit2";//冬夏令营 } request.setAttribute("type",type); }else{ bean.setType("0");//普通课程 } } //-------------学员集合-all------ request.setAttribute("student_beans", studentManager.findDataIsList(null)); //--------------教师--all----- TcMemberBean memberBean=new TcMemberBean(); memberBean.setUser_type("0");//教师 request.setAttribute("teacher_beans", memberManager.findDataIsList(memberBean)); //--------------课程--all---------- //数据字典中获取课程类型 TcSysVariableBean bean1=new TcSysVariableBean(); bean1.setVariable_id("course_subject");//课程主题 List<TcSysVariableBean> course_subjects=variableManager.findDataIsList(bean1); //课程列表 TcCourseBean course_bean_1=new TcCourseBean(); List<TcCourseBean> course_beans_all=courseManager.findDataIsList(course_bean_1); //-- List<TcCourseBean> course_beans=new ArrayList<TcCourseBean>(); if(course_subjects!=null){ for(TcSysVariableBean variablebean:course_subjects){ TcCourseBean course_bean=new TcCourseBean(); course_bean.setSubject_id(variablebean.getVariable_sub_id()); course_bean.setSubject_name(variablebean.getVariable_sub_name()); List<TcCourseBean> course_beans_temp=new ArrayList<TcCourseBean>(); if(course_beans_all!=null){ for(TcCourseBean courseBean:course_beans_all){ if(course_bean.getSubject_id().equals(courseBean.getSubject_id())){ course_beans_temp.add(courseBean); } } } if(course_beans_temp.size()>0){ course_bean.setBeans(course_beans_temp); course_beans.add(course_bean); } } } request.setAttribute("course_beans", course_beans); BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); request.setAttribute("uid", user.getUser_id());// return s; } /** * <p> * 删除。 * </p> * <ol> * [功能概要] <div>逻辑删除。</div> * </ol> * @return 转发字符串 */ public String del() { log.info("C102Action del........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.deleteDataById(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 删除。 * </p> * <ol> * [功能概要] <div>物理删除。</div> * </ol> * @return 转发字符串 */ public String delxx() { log.info("C102Action delxx........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.deleteData(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 根据课程id获取课程地址 * </p> * <ol> * [功能概要] <div>班级学员检索。</div> * </ol> * @return 转发字符串 * @throws Exception */ public String getStu() throws Exception { log.info("C202Action getStu........."); String cid=request.getParameter("cid"); StringBuffer sb=new StringBuffer("["); if(Validator.notEmpty(cid)){ TcClassesBean classes_vs_student_bean=new TcClassesBean(); classes_vs_student_bean.setId(cid); List<TcStudentBean> student_beans=classesManager.findDataIsListStudent(classes_vs_student_bean); if(student_beans!=null){ for(int i=0;i<student_beans.size();i++){ TcStudentBean studentBean=student_beans.get(i); sb.append("{\"id\":\""+studentBean.getId()+"\",\"name\":\""+studentBean.getName()+"\"}"); if(i<student_beans.size()-1){ sb.append(","); } } } } sb.append("]"); getWriter().print(sb.toString()); return null; } /** * <p> * 信息保存 * </p> * <ol> * [功能概要] <div>新增。</div> * <div>修改。</div> * </ol> * @return 转发字符串 */ public String save() { log.info("C102Action save........."); if(bean!=null){ String msg="1"; try { BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); if(user!=null){ bean.setCreate_ip(getIpAddr()); bean.setCreate_id(user.getUser_id()); bean.setUpdate_ip(getIpAddr()); bean.setUpdate_id(user.getUser_id()); } //-----冬夏令营 if("2x".equals(request.getParameter("type_flag"))){ if(Validator.isEmpty(bean.getTeacher_id())||Validator.isEmpty(bean.getDate1())||Validator.isEmpty(bean.getDate2())){ msg="保存失败!信息为空!"; }else{ String[] day_week=request.getParameterValues("day_week"); if(day_week!=null){ String s=bean.getDate1(); String e=bean.getDate2(); Calendar ca=Calendar.getInstance(); ca.setTime(DateUtil.parseDate(s)); Calendar ca1=Calendar.getInstance(); ca1.setTime(DateUtil.parseDate(e)); for(;ca.getTimeInMillis()<=ca1.getTimeInMillis();){ // System.out.println("星期"+(ca.get(Calendar.DAY_OF_WEEK)-1)); // System.out.println(DateUtil.getDateStr(ca.getTime())); try { String DAY_OF_WEEK=""+(ca.get(Calendar.DAY_OF_WEEK)-1); for(String week:day_week){ if(DAY_OF_WEEK.equals(week)){ bean.setId(null); bean.setDay(DateUtil.getDateStr(ca.getTime()));//上课日期 msg=courseSyllabusManager.saveOrUpdateData(bean); } } ca.set(Calendar.DATE,ca.get(Calendar.DATE)+1); } catch (Exception e1) { log.error("冬夏令营课程信息保存失败!", e1); } } } } }else{ //-----普通课程 if(Validator.isEmpty(bean.getTeacher_id())){ msg="保存失败!信息为空!"; }else{ msg=courseSyllabusManager.saveOrUpdateData(bean); } } } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); }else{ request.setAttribute("msg", "信息保存失败!"); } return SUCCESS; } /** * <p> * 恢复。 * </p> * <ol>[功能概要] * <div>恢复逻辑删除的数据。</div> * </ol> * @return 转发字符串 */ public String recovery() { log.info("C102Action recovery........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.recoveryDataById(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 根据课程id获取课程地址 * </p> * <ol> * [功能概要] <div>课程地址检索。</div> * </ol> * @return 转发字符串 * @throws Exception */ public String getAddres() throws Exception { log.info("C102Action getAddres........."); String cid=request.getParameter("cid"); StringBuffer sb=new StringBuffer(""); if(Validator.notEmpty(cid)){ TcCourseVsAddresBean course_vs_addres_bean=new TcCourseVsAddresBean(); course_vs_addres_bean.setCourse_id(cid); List<TcAddresBean> addres_beans=addresManager.findDataIsListAddres(course_vs_addres_bean); if(addres_beans!=null){ for(TcAddresBean addresBean:addres_beans){ sb.append("<option value=\""+addresBean.getAddres()+"\">"+addresBean.getAddres()+"</option>"); } } } getWriter().print(sb.toString()); return null; } /** * 课程表管理 业务处理取得 * @return 课程表管理 业务处理 */ public ICourseSyllabusManager getCourseSyllabusManager() { return courseSyllabusManager; } /** * 课程表管理 业务处理设定 * @param courseSyllabusManager 课程表管理 业务处理 */ public void setCourseSyllabusManager(ICourseSyllabusManager courseSyllabusManager) { this.courseSyllabusManager = courseSyllabusManager; } /** * 课程表-详情管理 业务处理取得 * @return 课程表-详情管理 业务处理 */ public ICourseSyllabusItemsManager getCourseSyllabusItemsManager() { return courseSyllabusItemsManager; } /** * 课程表-详情管理 业务处理设定 * @param courseSyllabusItemsManager 课程表-详情管理 业务处理 */ public void setCourseSyllabusItemsManager(ICourseSyllabusItemsManager courseSyllabusItemsManager) { this.courseSyllabusItemsManager = courseSyllabusItemsManager; } /** * 课程信息BEAN取得 * @return 课程信息BEAN */ public TcCourseSyllabusBean getBean() { return bean; } /** * 课程信息BEAN设定 * @param bean 课程信息BEAN */ public void setBean(TcCourseSyllabusBean bean) { this.bean = bean; } /** * BEAN类 评论信息取得 * @return BEAN类 评论信息 */ public TcCommentBean getCbean() { return cbean; } /** * BEAN类 评论信息设定 * @param cbean BEAN类 评论信息 */ public void setCbean(TcCommentBean cbean) { this.cbean = cbean; } /** * 课程信息BEAN集合取得 * @return 课程信息BEAN集合 */ public List<TcCourseSyllabusBean> getBeans() { return beans; } /** * 课程信息BEAN集合设定 * @param beans 课程信息BEAN集合 */ public void setBeans(List<TcCourseSyllabusBean> beans) { this.beans = beans; } /** * 会员信息管理 业务处理取得 * @return 会员信息管理 业务处理 */ public IMemberManager getMemberManager() { return memberManager; } /** * 会员信息管理 业务处理设定 * @param memberManager 会员信息管理 业务处理 */ public void setMemberManager(IMemberManager memberManager) { this.memberManager = memberManager; } /** * 学员信息管理 业务处理取得 * @return 学员信息管理 业务处理 */ public IStudentManager getStudentManager() { return studentManager; } /** * 学员信息管理 业务处理设定 * @param studentManager 学员信息管理 业务处理 */ public void setStudentManager(IStudentManager studentManager) { this.studentManager = studentManager; } /** * 课程信息管理 业务处理取得 * @return 课程信息管理 业务处理 */ public ICourseManager getCourseManager() { return courseManager; } /** * 课程信息管理 业务处理设定 * @param courseManager 课程信息管理 业务处理 */ public void setCourseManager(ICourseManager courseManager) { this.courseManager = courseManager; } /** * 课程表管理-相册 业务处理取得 * @return 课程表管理-相册 业务处理 */ public ICourseSyllabusPhotoManager getCourseSyllabusPhotoManager() { return courseSyllabusPhotoManager; } /** * 课程表管理-相册 业务处理设定 * @param courseSyllabusPhotoManager 课程表管理-相册 业务处理 */ public void setCourseSyllabusPhotoManager(ICourseSyllabusPhotoManager courseSyllabusPhotoManager) { this.courseSyllabusPhotoManager = courseSyllabusPhotoManager; } /** * <p> * 信息保存 相册 * </p> * <ol> * [功能概要] * <div>保存课程相册。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String savePic() throws IOException { log.info("C102Action savePic........."); // String token=request.getParameter("token"); // String token2=(String) request.getSession().getAttribute("token"); // if(token!=null && token.equals(token2)){ // getWriter().print("请不要重复提交!"); // return null; // }else{ // if(token!=null){ // request.getSession().setAttribute("token",token); // } // } String msg="1"; String[] picids=request.getParameterValues("picid"); if(picids!=null){ try { BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); //--相册信息集合-- List<TcCourseSyllabusPhotoBean> photoBeans=new ArrayList<TcCourseSyllabusPhotoBean>(); TcCourseSyllabusPhotoBean p_bean=null; String course_syllabus_id=request.getParameter("course_syllabus_id");//课程表id for(String picid:picids){ p_bean=new TcCourseSyllabusPhotoBean(); p_bean.setCourse_syllabus_id(course_syllabus_id);//课程表id p_bean.setId(picid);//照片信息id p_bean.setPic_url(request.getParameter("picurl"+picid));//照片链接 p_bean.setPic_title(request.getParameter("pictit"+picid));//照片链接 p_bean.setDel_flag(request.getParameter("delflag"+picid));//删除标记 p_bean.setUpdate_ip(getIpAddr()); p_bean.setUpdate_id(user.getUser_id()); p_bean.setCreate_ip(getIpAddr()); p_bean.setCreate_id(user.getUser_id()); if(Validator.notEmpty(p_bean.getSort_num())){ p_bean.setSort_num("0");//TODO-------- }else{ p_bean.setSort_num("0"); } photoBeans.add(p_bean); } msg=courseSyllabusPhotoManager.saveOrUpdateData(photoBeans); } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * <p> * 课程评论信息 。 * </p> * <ol> * [功能概要] <div>信息列表。</div> * </ol> * @return 转发字符串 */ public String clist1() { log.info("C102Action clist1........."); String cid=request.getParameter("cid"); if(cid!=null){ int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(5); TcCommentBean bean1 = new TcCommentBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); // TcMemberBean user = (TcMemberBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER_MEMBER_INFO); // bean1.setMember_id(user.getId());//会员id // bean1.setMember_type(user.getUser_type());//会员类型 bean1.setInfo_id(cid);//被评论信息id //列表 List<TcCommentBean> beans=commentManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); //---div id--- request.setAttribute("did",request.getParameter("did")); //---div id--- request.setAttribute("cid",cid); } return "clist1"; } /** * <p> * 评论信息保存 * </p> * <ol> * [功能概要] * <div>课程评论。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String csave() throws IOException { log.info("C102Action csave........."); String msg="1"; if(cbean!=null){ try { if(Validator.isEmpty(cbean.getDetail_info())){ msg="信息保存失败!输入信息为空!"; }else{ BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); cbean.setUpdate_ip(getIpAddr()); cbean.setUpdate_id(user.getUser_id()); cbean.setCreate_ip(getIpAddr()); cbean.setCreate_id(user.getUser_id()); cbean.setMember_id(user.getId());// cbean.setMember_type("3");//后台管理员 msg=commentManager.saveOrUpdateData(cbean); } } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * <p> * 评论信息 显示与隐藏 状态改变 * </p> * <ol> * [功能概要] * <div>是否显示 状态改变。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String csh() throws IOException { log.info("C102Action csh........."); String msg="1"; String id=request.getParameter("id");//评论id String s=request.getParameter("s");//状态 if(Validator.notEmpty(id) && Validator.notEmpty(s)){ try { if(cbean==null){ cbean=new TcCommentBean(); } BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); cbean.setUpdate_ip(getIpAddr()); cbean.setUpdate_id(user.getUser_id()); cbean.setId(id); cbean.setIs_show(s); msg=commentManager.saveOrUpdateData(cbean); } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * 评论信息 管理业务处理取得 * @return 评论信息 管理业务处理 */ public ICommentManager getCommentManager() { return commentManager; } /** * 评论信息 管理业务处理设定 * @param commentManager 评论信息 管理业务处理 */ public void setCommentManager(ICommentManager commentManager) { this.commentManager = commentManager; } /** * 课程地址信息表 业务处理接口类。取得 * @return 课程地址信息表 业务处理接口类。 */ public IAddresManager getAddresManager() { return addresManager; } /** * 课程地址信息表 业务处理接口类。设定 * @param addresManager 课程地址信息表 业务处理接口类。 */ public void setAddresManager(IAddresManager addresManager) { this.addresManager = addresManager; } /** * 班级信息表 业务处理接口类取得 * @return 班级信息表 业务处理接口类 */ public IClassesManager getClassesManager() { return classesManager; } /** * 班级信息表 业务处理接口类设定 * @param classesManager 班级信息表 业务处理接口类 */ public void setClassesManager(IClassesManager classesManager) { this.classesManager = classesManager; } }
UTF-8
Java
27,653
java
C102Action.java
Java
[ { "context": "-------------------------\r\n * 1.00 2014.04.07 wuxiaogang 程序・发布\r\n * -------- ----------- -------------", "end": 196, "score": 0.9995558857917786, "start": 186, "tag": "USERNAME", "value": "wuxiaogang" }, { "context": "nfo;\r\n\r\n/**\r\n * 课程表管理 ActionClass\r\n * \r\n * @author wuxiaogang\r\n * \r\n */\r\npublic class C102Action extends BaseAc", "end": 1985, "score": 0.9994138479232788, "start": 1975, "tag": "USERNAME", "value": "wuxiaogang" } ]
null
[]
/* * 课程表管理 ActionClass * * VERSION DATE BY REASON * -------- ----------- --------------- ------------------------------------------ * 1.00 2014.04.07 wuxiaogang 程序・发布 * -------- ----------- --------------- ------------------------------------------ * Copyright 2014 童励 System. - All Rights Reserved. * */ package cn.com.yearos.web.action.course; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.log4j.Logger; import cn.com.yearos.bean.BaseUserBean; import cn.com.yearos.bean.addres.TcAddresBean; import cn.com.yearos.bean.addres.TcCourseVsAddresBean; import cn.com.yearos.bean.classes.TcClassesBean; import cn.com.yearos.bean.comment.TcCommentBean; import cn.com.yearos.bean.course.TcCourseBean; import cn.com.yearos.bean.course.TcCourseSyllabusBean; import cn.com.yearos.bean.course.TcCourseSyllabusItemsBean; import cn.com.yearos.bean.course.TcCourseSyllabusPhotoBean; import cn.com.yearos.bean.member.TcMemberBean; import cn.com.yearos.bean.student.TcStudentBean; import cn.com.yearos.bean.sys.TcSysVariableBean; import cn.com.yearos.common.CommonConstant; import cn.com.yearos.common.DateUtil; import cn.com.yearos.common.IdUtils; import cn.com.yearos.common.Validator; import cn.com.yearos.service.addres.IAddresManager; import cn.com.yearos.service.classes.IClassesManager; import cn.com.yearos.service.comment.ICommentManager; import cn.com.yearos.service.course.ICourseManager; import cn.com.yearos.service.course.ICourseSyllabusItemsManager; import cn.com.yearos.service.course.ICourseSyllabusManager; import cn.com.yearos.service.course.ICourseSyllabusPhotoManager; import cn.com.yearos.service.member.IMemberManager; import cn.com.yearos.service.student.IStudentManager; import cn.com.yearos.web.action.BaseAction; import cn.com.yearos.web.tag.PageInfo; /** * 课程表管理 ActionClass * * @author wuxiaogang * */ public class C102Action extends BaseAction { /** * 序列号 */ private static final long serialVersionUID = -3061791975484213551L; private static final transient Logger log = Logger.getLogger(C102Action.class); /** 课程表管理 业务处理*/ private ICourseSyllabusManager courseSyllabusManager; /** 课程表-详情管理 业务处理*/ private ICourseSyllabusItemsManager courseSyllabusItemsManager; /**课程信息BEAN*/ private TcCourseSyllabusBean bean; /**BEAN类 评论信息*/ private TcCommentBean cbean; /**课程信息BEAN集合*/ private List<TcCourseSyllabusBean> beans; /**会员信息管理 业务处理*/ private IMemberManager memberManager; /**学员信息管理 业务处理*/ private IStudentManager studentManager; /**课程信息管理 业务处理*/ private ICourseManager courseManager; /** 课程表管理-相册 业务处理*/ private ICourseSyllabusPhotoManager courseSyllabusPhotoManager; /**评论信息 管理业务处理*/ private ICommentManager commentManager; /**课程地址信息表 业务处理接口类。 */ private IAddresManager addresManager; /**班级信息表 业务处理接口类*/ private IClassesManager classesManager; public C102Action() { log.info("默认构造器......C102Action"); } /** * <p> * 初始化处理。 * </p> * <ol> * [功能概要] <div>初始化处理。</div> * </ol> * @return 转发字符串 */ public String init() { log.info("C102Action init........."); return "init"; } /** * <p> * 已完成的课程。 * </p> * <ol> * [功能概要] <div>已完成的课程。</div> * </ol> * @return 转发字符串 */ public String list1() { log.info("C102Action list1........."); String s="list1";//普通课程 String t=request.getParameter("t");//0 普通课程1夏令营2冬令营 if(t!=null){ if("1".equals(t)){ s="list1_1";//1夏令营 } if("2".equals(t)){ s="list1_2";//2冬令营 } } int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //--已完成课程-- bean1.setCourse_status("1"); //-- bean1.setType(t); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return s; } /** * <p> * 未完成的课程。 * </p> * <ol> * [功能概要] <div>未完成的课程。</div> * </ol> * @return 转发字符串 */ public String list2() { log.info("C102Action list2........."); String s="list2";//普通课程 String t=request.getParameter("t");//0 普通课程1夏令营2冬令营 if(t!=null){ if("1".equals(t)){ s="list2_1";//1夏令营 } if("2".equals(t)){ s="list2_2";//2冬令营 } } int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //--未完成课程-- bean1.setCourse_status("0"); //-- bean1.setType(t); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return s; } /** * <p> * 初始化处理。 * </p> * <ol> * [功能概要] <div>初始化处理。</div> * </ol> * @return 转发字符串 */ public String init2() { log.info("C102Action init2........."); int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return "init"; } /** * <p> * 信息列表。 * </p> * <ol> * [功能概要] <div>回收站。</div> * </ol> * @return 转发字符串 */ public String recycle() { log.info("C102Action recycle........."); int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(15); TcCourseSyllabusBean bean1 = new TcCourseSyllabusBean(); bean1.setPageInfo(page); bean1.setDel_flag("1"); //列表 List<TcCourseSyllabusBean> beans=courseSyllabusManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); return "recycle"; } /** * <p> * 信息编辑。 * </p> * <ol> * [功能概要] <div>编辑。</div> * </ol> * @return 转发字符串 */ public String edit() { log.info("C102Action edit........."); String id=request.getParameter("id"); if(id!=null){ TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); bean=courseSyllabusManager.findDataById(bean1); //--当前学员集合--- TcCourseSyllabusItemsBean bean2=new TcCourseSyllabusItemsBean(); bean2.setCourse_syllabus_id(bean1.getId()); try { request.setAttribute("course_student_beans", courseSyllabusItemsManager.findDataIsListStudent(bean2)); if(bean!=null){ TcCourseSyllabusPhotoBean photoBean=new TcCourseSyllabusPhotoBean(); photoBean.setCourse_syllabus_id(bean1.getId()); bean.setPicBeans(courseSyllabusPhotoManager.findDataIsList(photoBean)); } } catch (Exception e) { log.error("学员集合获取出错!", e); } } String s="edit";//普通课程 if(bean==null){ bean=new TcCourseSyllabusBean(); bean.setId(IdUtils.createUUID(32)); } //---班级--- request.setAttribute("classes_beans",classesManager.findDataIsList(null)); if(Validator.isEmpty(bean.getType())){ String type=request.getParameter("type"); if(type!=null){ if("0".equals(type)){ bean.setType("0");//普通课程 }else{ bean.setType(type); s="edit2";//冬夏令营 } request.setAttribute("type",type); }else{ bean.setType("0");//普通课程 } } //-------------学员集合-all------ request.setAttribute("student_beans", studentManager.findDataIsList(null)); //--------------教师--all----- TcMemberBean memberBean=new TcMemberBean(); memberBean.setUser_type("0");//教师 request.setAttribute("teacher_beans", memberManager.findDataIsList(memberBean)); //--------------课程--all---------- //数据字典中获取课程类型 TcSysVariableBean bean1=new TcSysVariableBean(); bean1.setVariable_id("course_subject");//课程主题 List<TcSysVariableBean> course_subjects=variableManager.findDataIsList(bean1); //课程列表 TcCourseBean course_bean_1=new TcCourseBean(); List<TcCourseBean> course_beans_all=courseManager.findDataIsList(course_bean_1); //-- List<TcCourseBean> course_beans=new ArrayList<TcCourseBean>(); if(course_subjects!=null){ for(TcSysVariableBean variablebean:course_subjects){ TcCourseBean course_bean=new TcCourseBean(); course_bean.setSubject_id(variablebean.getVariable_sub_id()); course_bean.setSubject_name(variablebean.getVariable_sub_name()); List<TcCourseBean> course_beans_temp=new ArrayList<TcCourseBean>(); if(course_beans_all!=null){ for(TcCourseBean courseBean:course_beans_all){ if(course_bean.getSubject_id().equals(courseBean.getSubject_id())){ course_beans_temp.add(courseBean); } } } if(course_beans_temp.size()>0){ course_bean.setBeans(course_beans_temp); course_beans.add(course_bean); } } } request.setAttribute("course_beans", course_beans); BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); request.setAttribute("uid", user.getUser_id());// return s; } /** * <p> * 删除。 * </p> * <ol> * [功能概要] <div>逻辑删除。</div> * </ol> * @return 转发字符串 */ public String del() { log.info("C102Action del........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.deleteDataById(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 删除。 * </p> * <ol> * [功能概要] <div>物理删除。</div> * </ol> * @return 转发字符串 */ public String delxx() { log.info("C102Action delxx........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.deleteData(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 根据课程id获取课程地址 * </p> * <ol> * [功能概要] <div>班级学员检索。</div> * </ol> * @return 转发字符串 * @throws Exception */ public String getStu() throws Exception { log.info("C202Action getStu........."); String cid=request.getParameter("cid"); StringBuffer sb=new StringBuffer("["); if(Validator.notEmpty(cid)){ TcClassesBean classes_vs_student_bean=new TcClassesBean(); classes_vs_student_bean.setId(cid); List<TcStudentBean> student_beans=classesManager.findDataIsListStudent(classes_vs_student_bean); if(student_beans!=null){ for(int i=0;i<student_beans.size();i++){ TcStudentBean studentBean=student_beans.get(i); sb.append("{\"id\":\""+studentBean.getId()+"\",\"name\":\""+studentBean.getName()+"\"}"); if(i<student_beans.size()-1){ sb.append(","); } } } } sb.append("]"); getWriter().print(sb.toString()); return null; } /** * <p> * 信息保存 * </p> * <ol> * [功能概要] <div>新增。</div> * <div>修改。</div> * </ol> * @return 转发字符串 */ public String save() { log.info("C102Action save........."); if(bean!=null){ String msg="1"; try { BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); if(user!=null){ bean.setCreate_ip(getIpAddr()); bean.setCreate_id(user.getUser_id()); bean.setUpdate_ip(getIpAddr()); bean.setUpdate_id(user.getUser_id()); } //-----冬夏令营 if("2x".equals(request.getParameter("type_flag"))){ if(Validator.isEmpty(bean.getTeacher_id())||Validator.isEmpty(bean.getDate1())||Validator.isEmpty(bean.getDate2())){ msg="保存失败!信息为空!"; }else{ String[] day_week=request.getParameterValues("day_week"); if(day_week!=null){ String s=bean.getDate1(); String e=bean.getDate2(); Calendar ca=Calendar.getInstance(); ca.setTime(DateUtil.parseDate(s)); Calendar ca1=Calendar.getInstance(); ca1.setTime(DateUtil.parseDate(e)); for(;ca.getTimeInMillis()<=ca1.getTimeInMillis();){ // System.out.println("星期"+(ca.get(Calendar.DAY_OF_WEEK)-1)); // System.out.println(DateUtil.getDateStr(ca.getTime())); try { String DAY_OF_WEEK=""+(ca.get(Calendar.DAY_OF_WEEK)-1); for(String week:day_week){ if(DAY_OF_WEEK.equals(week)){ bean.setId(null); bean.setDay(DateUtil.getDateStr(ca.getTime()));//上课日期 msg=courseSyllabusManager.saveOrUpdateData(bean); } } ca.set(Calendar.DATE,ca.get(Calendar.DATE)+1); } catch (Exception e1) { log.error("冬夏令营课程信息保存失败!", e1); } } } } }else{ //-----普通课程 if(Validator.isEmpty(bean.getTeacher_id())){ msg="保存失败!信息为空!"; }else{ msg=courseSyllabusManager.saveOrUpdateData(bean); } } } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); }else{ request.setAttribute("msg", "信息保存失败!"); } return SUCCESS; } /** * <p> * 恢复。 * </p> * <ol>[功能概要] * <div>恢复逻辑删除的数据。</div> * </ol> * @return 转发字符串 */ public String recovery() { log.info("C102Action recovery........."); String id=request.getParameter("id"); TcCourseSyllabusBean bean1=new TcCourseSyllabusBean(); bean1.setId(id); String msg="1"; try { msg=courseSyllabusManager.recoveryDataById(bean1); } catch (Exception e) { msg=e.getMessage(); } request.setAttribute("msg",msg); return SUCCESS; } /** * <p> * 根据课程id获取课程地址 * </p> * <ol> * [功能概要] <div>课程地址检索。</div> * </ol> * @return 转发字符串 * @throws Exception */ public String getAddres() throws Exception { log.info("C102Action getAddres........."); String cid=request.getParameter("cid"); StringBuffer sb=new StringBuffer(""); if(Validator.notEmpty(cid)){ TcCourseVsAddresBean course_vs_addres_bean=new TcCourseVsAddresBean(); course_vs_addres_bean.setCourse_id(cid); List<TcAddresBean> addres_beans=addresManager.findDataIsListAddres(course_vs_addres_bean); if(addres_beans!=null){ for(TcAddresBean addresBean:addres_beans){ sb.append("<option value=\""+addresBean.getAddres()+"\">"+addresBean.getAddres()+"</option>"); } } } getWriter().print(sb.toString()); return null; } /** * 课程表管理 业务处理取得 * @return 课程表管理 业务处理 */ public ICourseSyllabusManager getCourseSyllabusManager() { return courseSyllabusManager; } /** * 课程表管理 业务处理设定 * @param courseSyllabusManager 课程表管理 业务处理 */ public void setCourseSyllabusManager(ICourseSyllabusManager courseSyllabusManager) { this.courseSyllabusManager = courseSyllabusManager; } /** * 课程表-详情管理 业务处理取得 * @return 课程表-详情管理 业务处理 */ public ICourseSyllabusItemsManager getCourseSyllabusItemsManager() { return courseSyllabusItemsManager; } /** * 课程表-详情管理 业务处理设定 * @param courseSyllabusItemsManager 课程表-详情管理 业务处理 */ public void setCourseSyllabusItemsManager(ICourseSyllabusItemsManager courseSyllabusItemsManager) { this.courseSyllabusItemsManager = courseSyllabusItemsManager; } /** * 课程信息BEAN取得 * @return 课程信息BEAN */ public TcCourseSyllabusBean getBean() { return bean; } /** * 课程信息BEAN设定 * @param bean 课程信息BEAN */ public void setBean(TcCourseSyllabusBean bean) { this.bean = bean; } /** * BEAN类 评论信息取得 * @return BEAN类 评论信息 */ public TcCommentBean getCbean() { return cbean; } /** * BEAN类 评论信息设定 * @param cbean BEAN类 评论信息 */ public void setCbean(TcCommentBean cbean) { this.cbean = cbean; } /** * 课程信息BEAN集合取得 * @return 课程信息BEAN集合 */ public List<TcCourseSyllabusBean> getBeans() { return beans; } /** * 课程信息BEAN集合设定 * @param beans 课程信息BEAN集合 */ public void setBeans(List<TcCourseSyllabusBean> beans) { this.beans = beans; } /** * 会员信息管理 业务处理取得 * @return 会员信息管理 业务处理 */ public IMemberManager getMemberManager() { return memberManager; } /** * 会员信息管理 业务处理设定 * @param memberManager 会员信息管理 业务处理 */ public void setMemberManager(IMemberManager memberManager) { this.memberManager = memberManager; } /** * 学员信息管理 业务处理取得 * @return 学员信息管理 业务处理 */ public IStudentManager getStudentManager() { return studentManager; } /** * 学员信息管理 业务处理设定 * @param studentManager 学员信息管理 业务处理 */ public void setStudentManager(IStudentManager studentManager) { this.studentManager = studentManager; } /** * 课程信息管理 业务处理取得 * @return 课程信息管理 业务处理 */ public ICourseManager getCourseManager() { return courseManager; } /** * 课程信息管理 业务处理设定 * @param courseManager 课程信息管理 业务处理 */ public void setCourseManager(ICourseManager courseManager) { this.courseManager = courseManager; } /** * 课程表管理-相册 业务处理取得 * @return 课程表管理-相册 业务处理 */ public ICourseSyllabusPhotoManager getCourseSyllabusPhotoManager() { return courseSyllabusPhotoManager; } /** * 课程表管理-相册 业务处理设定 * @param courseSyllabusPhotoManager 课程表管理-相册 业务处理 */ public void setCourseSyllabusPhotoManager(ICourseSyllabusPhotoManager courseSyllabusPhotoManager) { this.courseSyllabusPhotoManager = courseSyllabusPhotoManager; } /** * <p> * 信息保存 相册 * </p> * <ol> * [功能概要] * <div>保存课程相册。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String savePic() throws IOException { log.info("C102Action savePic........."); // String token=request.getParameter("token"); // String token2=(String) request.getSession().getAttribute("token"); // if(token!=null && token.equals(token2)){ // getWriter().print("请不要重复提交!"); // return null; // }else{ // if(token!=null){ // request.getSession().setAttribute("token",token); // } // } String msg="1"; String[] picids=request.getParameterValues("picid"); if(picids!=null){ try { BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); //--相册信息集合-- List<TcCourseSyllabusPhotoBean> photoBeans=new ArrayList<TcCourseSyllabusPhotoBean>(); TcCourseSyllabusPhotoBean p_bean=null; String course_syllabus_id=request.getParameter("course_syllabus_id");//课程表id for(String picid:picids){ p_bean=new TcCourseSyllabusPhotoBean(); p_bean.setCourse_syllabus_id(course_syllabus_id);//课程表id p_bean.setId(picid);//照片信息id p_bean.setPic_url(request.getParameter("picurl"+picid));//照片链接 p_bean.setPic_title(request.getParameter("pictit"+picid));//照片链接 p_bean.setDel_flag(request.getParameter("delflag"+picid));//删除标记 p_bean.setUpdate_ip(getIpAddr()); p_bean.setUpdate_id(user.getUser_id()); p_bean.setCreate_ip(getIpAddr()); p_bean.setCreate_id(user.getUser_id()); if(Validator.notEmpty(p_bean.getSort_num())){ p_bean.setSort_num("0");//TODO-------- }else{ p_bean.setSort_num("0"); } photoBeans.add(p_bean); } msg=courseSyllabusPhotoManager.saveOrUpdateData(photoBeans); } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * <p> * 课程评论信息 。 * </p> * <ol> * [功能概要] <div>信息列表。</div> * </ol> * @return 转发字符串 */ public String clist1() { log.info("C102Action clist1........."); String cid=request.getParameter("cid"); if(cid!=null){ int offset = 0; // 分页偏移量 if (!Validator.isNullEmpty(request.getParameter("offset")) && Validator.isNum(request.getParameter("offset"))) { offset = Integer.parseInt(request.getParameter("offset")); } PageInfo page = new PageInfo(); //当前页 page.setCurrOffset(offset); //每页显示条数 page.setPageRowCount(5); TcCommentBean bean1 = new TcCommentBean(); bean1.setPageInfo(page); bean1.setDel_flag("0"); // TcMemberBean user = (TcMemberBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER_MEMBER_INFO); // bean1.setMember_id(user.getId());//会员id // bean1.setMember_type(user.getUser_type());//会员类型 bean1.setInfo_id(cid);//被评论信息id //列表 List<TcCommentBean> beans=commentManager.findDataIsPage(bean1); request.setAttribute("beans",beans); request.setAttribute(CommonConstant.PAGEROW_OBJECT_KEY,page); //---div id--- request.setAttribute("did",request.getParameter("did")); //---div id--- request.setAttribute("cid",cid); } return "clist1"; } /** * <p> * 评论信息保存 * </p> * <ol> * [功能概要] * <div>课程评论。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String csave() throws IOException { log.info("C102Action csave........."); String msg="1"; if(cbean!=null){ try { if(Validator.isEmpty(cbean.getDetail_info())){ msg="信息保存失败!输入信息为空!"; }else{ BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); cbean.setUpdate_ip(getIpAddr()); cbean.setUpdate_id(user.getUser_id()); cbean.setCreate_ip(getIpAddr()); cbean.setCreate_id(user.getUser_id()); cbean.setMember_id(user.getId());// cbean.setMember_type("3");//后台管理员 msg=commentManager.saveOrUpdateData(cbean); } } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * <p> * 评论信息 显示与隐藏 状态改变 * </p> * <ol> * [功能概要] * <div>是否显示 状态改变。</div> * </ol> * @return 转发字符串 * @throws IOException */ public String csh() throws IOException { log.info("C102Action csh........."); String msg="1"; String id=request.getParameter("id");//评论id String s=request.getParameter("s");//状态 if(Validator.notEmpty(id) && Validator.notEmpty(s)){ try { if(cbean==null){ cbean=new TcCommentBean(); } BaseUserBean user = (BaseUserBean) request.getSession().getAttribute(CommonConstant.SESSION_KEY_USER); cbean.setUpdate_ip(getIpAddr()); cbean.setUpdate_id(user.getUser_id()); cbean.setId(id); cbean.setIs_show(s); msg=commentManager.saveOrUpdateData(cbean); } catch (Exception e) { msg=e.getMessage(); } }else{ msg="信息保存失败!"; } getWriter().print(msg); return null; } /** * 评论信息 管理业务处理取得 * @return 评论信息 管理业务处理 */ public ICommentManager getCommentManager() { return commentManager; } /** * 评论信息 管理业务处理设定 * @param commentManager 评论信息 管理业务处理 */ public void setCommentManager(ICommentManager commentManager) { this.commentManager = commentManager; } /** * 课程地址信息表 业务处理接口类。取得 * @return 课程地址信息表 业务处理接口类。 */ public IAddresManager getAddresManager() { return addresManager; } /** * 课程地址信息表 业务处理接口类。设定 * @param addresManager 课程地址信息表 业务处理接口类。 */ public void setAddresManager(IAddresManager addresManager) { this.addresManager = addresManager; } /** * 班级信息表 业务处理接口类取得 * @return 班级信息表 业务处理接口类 */ public IClassesManager getClassesManager() { return classesManager; } /** * 班级信息表 业务处理接口类设定 * @param classesManager 班级信息表 业务处理接口类 */ public void setClassesManager(IClassesManager classesManager) { this.classesManager = classesManager; } }
27,653
0.633561
0.624256
928
24.983837
22.443865
121
false
false
0
0
0
0
0
0
2.450431
false
false
12
e22a584fa33714d6213b8071eacd0e55bf368ffd
13,331,578,548,594
2c5eacd20d7db54abb4efcff8d6ccf1bb27ad5eb
/src/test/java/com/appiu/utils/AbstractTest.java
e2e0977bdc89ba1f228070808892c21e1a9f15c1
[]
no_license
vijaynirmal/ParamTestNGIosBuild
https://github.com/vijaynirmal/ParamTestNGIosBuild
18a4097478b8b78a625f864b42eb8c6c1aec2333
ec65f2775e6fe3efd8af4f6cea8666b0f20edee6
refs/heads/master
2018-01-11T19:46:37.990000
2015-12-19T22:37:16
2015-12-19T22:37:16
48,299,182
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.appiu.utils; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.DefaultExecutor; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import com.appium.pageobjectmodel.appiumpageobject.LandingPage; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; import io.appium.java_client.remote.MobileCapabilityType; public class AbstractTest { //Initialize the driver @SuppressWarnings("rawtypes") public static IOSDriver driver; @SuppressWarnings("rawtypes") @BeforeClass public static void createEnvironment() throws Exception{ //stopAppium(); //startAppiumOnMac(); //initializeServer(); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("AutomationName","Appium"); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,System.getProperty("PlatformName")); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,System.getProperty("PlatformVersion")); capabilities.setCapability("deviceName", "Vijay Nirmal's iPhone"); capabilities.setCapability("bundleId", "com.example.apple-samplecode.vijaynirmal"); capabilities.setCapability("udid", "ed3cee9c3a103d37c7a43dfcdf33a0300d10a4a7"); capabilities.setCapability("appium-version", "1.4.13"); capabilities.setCapability("app", "/Users/admin/Library/Developer/Xcode/DerivedData/UIKitCatalog-dhgazebmvkjyrjbjcsbncdhxwwwn/Build/Products/Debug-iphoneos/UIKitCatalog.app"); try { driver = new IOSDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); PageFactory.initElements(new AppiumFieldDecorator(driver), new LandingPage()); } @AfterClass public static void tearDown() throws Exception{ driver.quit(); //stopAppium(); } public static void initializeServer() { AppiumDriverLocalService service = AppiumDriverLocalService .buildService(new AppiumServiceBuilder() .usingDriverExecutable(new File("/Applications/Appium.app/Contents/Resources/node/bin/node")) .withAppiumJS( new File("lib/server/main.js")) .withIPAddress("127.0.0.1").usingPort(4723)); service.start(); if(service.isRunning()) System.out.println("Appium server started successfully"); } public static void startAppiumOnMac() throws Exception { CommandLine command = new CommandLine("/Applications/Appium.app/Contents/Resources/node/bin/node"); command.addArgument("/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js",false); command.addArgument("--address", false); command.addArgument("127.0.0.1"); command.addArgument("--port", false); command.addArgument("4723"); command.addArgument("--full-reset", false); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); try { executor.execute(command, resultHandler); Thread.sleep(5000); System.out.println("Appium server started."); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void stopAppium() throws Exception { String[] command = { "/usr/bin/killall", "-KILL", "node" }; try { Runtime.getRuntime().exec(command); System.out.println("Appium server stopped."); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
4,105
java
AbstractTest.java
Java
[ { "context": "\t\ttry {\n\t\t\tdriver = new IOSDriver(new URL(\"http://127.0.0.1:4723/wd/hub\"),capabilities);\n\t\t} catch (Malformed", "end": 2038, "score": 0.999745786190033, "start": 2029, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "new File(\"lib/server/main.js\"))\n\t\t.withIPAddress(\"127.0.0.1\").usingPort(4723));\t\n\t\tservice.start();\n\t\tif(serv", "end": 2762, "score": 0.9997838139533997, "start": 2753, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "t(\"--address\", false);\n\t\t\t\t\t\tcommand.addArgument(\"127.0.0.1\");\n\t\t\t\t\t\tcommand.addArgument(\"--port\", false);\n\t\t", "end": 3253, "score": 0.9997676014900208, "start": 3244, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
package com.appiu.utils; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.DefaultExecutor; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import com.appium.pageobjectmodel.appiumpageobject.LandingPage; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.pagefactory.AppiumFieldDecorator; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; import io.appium.java_client.remote.MobileCapabilityType; public class AbstractTest { //Initialize the driver @SuppressWarnings("rawtypes") public static IOSDriver driver; @SuppressWarnings("rawtypes") @BeforeClass public static void createEnvironment() throws Exception{ //stopAppium(); //startAppiumOnMac(); //initializeServer(); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("AutomationName","Appium"); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,System.getProperty("PlatformName")); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,System.getProperty("PlatformVersion")); capabilities.setCapability("deviceName", "Vijay Nirmal's iPhone"); capabilities.setCapability("bundleId", "com.example.apple-samplecode.vijaynirmal"); capabilities.setCapability("udid", "ed3cee9c3a103d37c7a43dfcdf33a0300d10a4a7"); capabilities.setCapability("appium-version", "1.4.13"); capabilities.setCapability("app", "/Users/admin/Library/Developer/Xcode/DerivedData/UIKitCatalog-dhgazebmvkjyrjbjcsbncdhxwwwn/Build/Products/Debug-iphoneos/UIKitCatalog.app"); try { driver = new IOSDriver(new URL("http://127.0.0.1:4723/wd/hub"),capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); PageFactory.initElements(new AppiumFieldDecorator(driver), new LandingPage()); } @AfterClass public static void tearDown() throws Exception{ driver.quit(); //stopAppium(); } public static void initializeServer() { AppiumDriverLocalService service = AppiumDriverLocalService .buildService(new AppiumServiceBuilder() .usingDriverExecutable(new File("/Applications/Appium.app/Contents/Resources/node/bin/node")) .withAppiumJS( new File("lib/server/main.js")) .withIPAddress("127.0.0.1").usingPort(4723)); service.start(); if(service.isRunning()) System.out.println("Appium server started successfully"); } public static void startAppiumOnMac() throws Exception { CommandLine command = new CommandLine("/Applications/Appium.app/Contents/Resources/node/bin/node"); command.addArgument("/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js",false); command.addArgument("--address", false); command.addArgument("127.0.0.1"); command.addArgument("--port", false); command.addArgument("4723"); command.addArgument("--full-reset", false); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); try { executor.execute(command, resultHandler); Thread.sleep(5000); System.out.println("Appium server started."); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void stopAppium() throws Exception { String[] command = { "/usr/bin/killall", "-KILL", "node" }; try { Runtime.getRuntime().exec(command); System.out.println("Appium server stopped."); } catch (IOException e) { e.printStackTrace(); } } }
4,105
0.755907
0.740804
116
34.387932
30.799343
177
false
false
0
0
0
0
0
0
2.62069
false
false
12
393a214aef31517bd5a9eff3d78c5c809136a6e6
4,449,586,138,512
c0c371cdfeee7df175f7b7d1d353b2ea9c759ed1
/src/HoleNode.java
2a3449126644701b3305ce1c767476d9a7c9622d
[]
no_license
EdanSneh/Mancala
https://github.com/EdanSneh/Mancala
fc47df20d71dbe1083445d0741a935ad12191b31
51130ee5302f6090874f5a32d32f84208262d2c4
refs/heads/master
2020-04-09T16:13:20.572000
2018-12-05T02:16:39
2018-12-05T02:16:39
160,446,984
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class HoleNode { public int value; public HoleNode(int value) { this.value = value; } }
UTF-8
Java
116
java
HoleNode.java
Java
[]
null
[]
public class HoleNode { public int value; public HoleNode(int value) { this.value = value; } }
116
0.594828
0.594828
7
15.571428
12.257442
32
false
false
0
0
0
0
0
0
0.285714
false
false
12
c307f8b204ea75d14110bd0ceb83de13897a117f
7,911,329,781,998
1e0712512f53fbe74564e83b6c6124906d60e119
/Contest1107/src/D.java
42a7d087a419d46bec14fbb0d38348bf7f0239f2
[]
no_license
l-winston/CodeForces
https://github.com/l-winston/CodeForces
878454e1104b679d81fa0bc7cc8d95aefe52ffca
8d91f326299d723fd6f1818b0565cf3ccff0bc23
refs/heads/master
2020-04-19T06:51:35.460000
2019-02-03T20:18:58
2019-02-03T20:18:58
168,029,885
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class D { private static String[] staticLookup = new String[]{"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; public static String HexToBinary(char Hex) { return staticLookup[Integer.parseInt(Character.toString(Hex), 16)]; } public static void main(String[] args) throws IOException { init(System.in); int n = nextInt(); boolean[][] ar = new boolean[n][n]; for (int i = 0; i < n; i++) { char[] chars = next().toCharArray(); for (int j = 0; j < n / 4; j++) { String s = HexToBinary(chars[j]); for (int k = 0; k < 4; k++) { ar[i][j * 4 + k] = s.charAt(k) == '1'; } } } //for (boolean[] b : ar) //System.out.println(Arrays.toString(b)); HashSet<Integer> consec = new HashSet<>(); for (int i = 0; i < n; i++) { boolean last = ar[i][0]; int curr = 1; for (int j = 1; j < n; j++) { if (ar[i][j] == last) curr++; else { consec.add(curr); curr = 1; last = ar[i][j]; } } consec.add(curr); } for (int i = 0; i < n; i++) { boolean last = ar[0][i]; int curr = 1; for (int j = 1; j < n; j++) { if (ar[j][i] == last) curr++; else { consec.add(curr); curr = 1; last = ar[j][i]; } } consec.add(curr); } // System.out.println(consec); int ans = 0; for (int i : consec) ans = gcd(ans, i); System.out.println(ans); } static int pow(int x) { int ans = 1; for (int i = 0; i < x; i++) ans *= 10; return ans; } static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } /** * buffered reading int and double values */ static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } }
UTF-8
Java
3,662
java
D.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; public class D { private static String[] staticLookup = new String[]{"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; public static String HexToBinary(char Hex) { return staticLookup[Integer.parseInt(Character.toString(Hex), 16)]; } public static void main(String[] args) throws IOException { init(System.in); int n = nextInt(); boolean[][] ar = new boolean[n][n]; for (int i = 0; i < n; i++) { char[] chars = next().toCharArray(); for (int j = 0; j < n / 4; j++) { String s = HexToBinary(chars[j]); for (int k = 0; k < 4; k++) { ar[i][j * 4 + k] = s.charAt(k) == '1'; } } } //for (boolean[] b : ar) //System.out.println(Arrays.toString(b)); HashSet<Integer> consec = new HashSet<>(); for (int i = 0; i < n; i++) { boolean last = ar[i][0]; int curr = 1; for (int j = 1; j < n; j++) { if (ar[i][j] == last) curr++; else { consec.add(curr); curr = 1; last = ar[i][j]; } } consec.add(curr); } for (int i = 0; i < n; i++) { boolean last = ar[0][i]; int curr = 1; for (int j = 1; j < n; j++) { if (ar[j][i] == last) curr++; else { consec.add(curr); curr = 1; last = ar[j][i]; } } consec.add(curr); } // System.out.println(consec); int ans = 0; for (int i : consec) ans = gcd(ans, i); System.out.println(ans); } static int pow(int x) { int ans = 1; for (int i = 0; i < x; i++) ans *= 10; return ans; } static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } /** * buffered reading int and double values */ static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } }
3,662
0.46177
0.43692
148
23.729731
22.057846
184
false
false
0
0
0
0
0
0
0.601351
false
false
12
42da5961d8c02a03265efa0157deaeed41950ad7
15,839,839,407,966
8e9f2a6ff007af208c91b3fc9a032cf54d195ba1
/app/src/main/java/com/example/ahmed/teachercalender/Interfaces/connection.java
91ecf9f4a72fa613c31f8ef3851b14f96446fa8f
[]
no_license
hassan671651github/nanodegreeApplication
https://github.com/hassan671651github/nanodegreeApplication
9f14c82c997625aff15ae41fe0af1b7e95970835
6abbc61160f14c9b40291bc65eacd1081316a86e
refs/heads/master
2020-06-21T11:38:53.530000
2016-12-10T06:37:21
2016-12-10T06:37:21
74,788,582
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.ahmed.teachercalender.Interfaces; import android.os.Bundle; /** * Created by Ahmed on 12/11/2016. */ public interface connection { public void connect(int id, String sender); }
UTF-8
Java
205
java
connection.java
Java
[ { "context": "ces;\n\nimport android.os.Bundle;\n\n/**\n * Created by Ahmed on 12/11/2016.\n */\npublic interface connection {\n", "end": 105, "score": 0.9996393918991089, "start": 100, "tag": "NAME", "value": "Ahmed" } ]
null
[]
package com.example.ahmed.teachercalender.Interfaces; import android.os.Bundle; /** * Created by Ahmed on 12/11/2016. */ public interface connection { public void connect(int id, String sender); }
205
0.736585
0.697561
10
19.5
19.637974
53
false
false
0
0
0
0
0
0
0.4
false
false
12