{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \", HttpStatus.OK);\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1364,"cells":{"blob_id":{"kind":"string","value":"0ba0ccd2d0ed28c05506d40a00c9c72ae5e2332d"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"mikuluna/Design-patterns"},"path":{"kind":"string","value":"/02-Structural Patterns/Decorator Pattern/src/com/luna/decorator/impl/Vest.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":331,"string":"331"},"score":{"kind":"number","value":2.375,"string":"2.375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.luna.decorator.impl;\n\nimport com.luna.decorator.Player;\nimport com.luna.decorator.PlayerDecorator;\n\n/**\n * 防弹衣\n */\npublic class Vest extends PlayerDecorator {\n public Vest(Player player) {\n super(player);\n }\n @Override\n public String equip(){\n return super.equip()+\"+防弹衣\";\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1365,"cells":{"blob_id":{"kind":"string","value":"997b79440eae9f86efa794ae6169e26512599dba"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"if-050java/ATM_Locator"},"path":{"kind":"string","value":"/src/main/java/com/ss/atmlocator/entity/AtmNetwork.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":927,"string":"927"},"score":{"kind":"number","value":2.3125,"string":"2.3125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.ss.atmlocator.entity;\n\nimport org.codehaus.jackson.annotate.JsonIgnore;\nimport javax.persistence.*;\nimport java.util.Set;\n\n/**\n * Created by Olavin on 18.11.2014.\n */\n@Entity\n@Table(name=\"atmnetworks\")\npublic class AtmNetwork {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n\n @Column\n private String name;\n\n/*\n @JsonIgnore //Ignoring this field in JSON serializing\n @OneToMany(cascade = CascadeType.ALL, mappedBy = \"network\", fetch = FetchType.LAZY)\n private Set Banks;\n*/\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n/*\n public Set getBanks() {\n return Banks;\n }\n\n public void setBanks(Set banks) {\n Banks = banks;\n }\n*/\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1366,"cells":{"blob_id":{"kind":"string","value":"019321f9ff3329f3c3e49fafb157c90276365c54"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"Li-jiabing/JavaSE"},"path":{"kind":"string","value":"/src/com/company/day01_02_03/OperatorTest01.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1905,"string":"1,905"},"score":{"kind":"number","value":4.46875,"string":"4.46875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.company.day01_02_03;\n\n/**\n * 关于java编程中运算符之:算数运算符\n * + 加\n * - 减\n * * 乘\n * / 除\n * % 取模\n * ++ 自加1\n * -- 自减1\n *\n * 注意:一个表达式中有多个运算符,运算符有优先级,不确定的加小括号,优先级得到提升\n */\npublic class OperatorTest01 {\n\n public static void main(String[] args) {\n int i = 10;\n int j = 3;\n System.out.println(i+j);//13\n System.out.println(i-j);//7\n System.out.println(i*j);//30\n System.out.println(i/j);//3\n System.out.println(i%j);//1\n\n //以下以++为例,--自学\n //关于++运算符【自加1】\n int k = 10;\n //++运算符可以出现在变量后面【单目运算符】\n k++;\n System.out.println(k);\n\n int y = 10;\n //++运算副可以出现在变量前面[单目运算符]\n ++y;\n System.out.println(y);//11\n\n /**\n * 小结:++运算符可以出现在变量前,也可以出现在变量后,无论是变量前还是变量后,只要++运算结束,该变量中的值一定会自加1\n */\n\n //++出现在变量后\n int a = 100;\n int b = a++;//++出现在变量后面,先赋值再运算\n System.out.println(a);//101\n System.out.println(b);//100\n\n //++出现在变量前\n //规则:先进行自加1运算,然后再进行赋值操作\n int c = 100;\n System.err.println(c);\n int d = ++c;\n System.err.println(c);//101\n System.err.println(d);//101\n\n int xx = 500;\n System.out.println(xx++);//500\n System.out.println(xx);//501\n\n int s = 100;\n System.out.println(++s);//101\n System.out.println(s);//101\n\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1367,"cells":{"blob_id":{"kind":"string","value":"c22d31e5722e76c21a2712c357abd39bfaff83b5"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"jonathansantana19/projetos"},"path":{"kind":"string","value":"/TesteJSFPRIMAFACES/src/GuicheController.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1657,"string":"1,657"},"score":{"kind":"number","value":2.25,"string":"2.25"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import java.io.Serializable;\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.time.format.FormatStyle;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\n\nimport javax.annotation.PostConstruct;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.ViewScoped;\n\n@ViewScoped\n@ManagedBean\npublic class GuicheController implements Serializable {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\t\n\t\n\tprivate List lista;\n\t\n\tprivate GuicheVO guiche;\n\t\n\tprivate String dataHora;\n\t\n\t@PostConstruct\n\tpublic void init(){\n\t\t\n\t\tSystem.out.println(\"iniciando\");\n\t\tGuicheVO obj = new GuicheVO();\n\t\t\n\t\tlista = new ArrayList();\n\t\tguiche = new GuicheVO(); \n\t\t\n\t\tobj.setNomePaciente(\"Anderson\");\n\t\tobj.setSala(\"Ambulatorio3\");\n\t\tlista.add(obj);\n\t\t\n\t\tobj.setNomePaciente(\"Carlos\");\n\t\tobj.setSala(\"Ambulatorio1\");\n\t\tlista.add(obj);\n\t\t\n\t\tobj.setNomePaciente(\"Fernando\");\n\t\tobj.setSala(\"Sala2\");\n\t\tlista.add(obj);\n\t\t\n\t\t\n\t\tLocalDateTime agora = LocalDateTime.now();\n\t\tDateTimeFormatter formatador = DateTimeFormatter.\n\t\t\t\tofLocalizedDateTime(FormatStyle.SHORT).withLocale(new Locale(\"pt\", \"br\"));\n//\t\tagora.format(formatador); //08/04/14 10:02\n\t\t\n\t\tdataHora = agora.format(formatador);\n\t}\n\n\n\tpublic List getLista() {\n\t\treturn lista;\n\t}\n\tpublic void setLista(List lista) {\n\t\tthis.lista = lista;\n\t}\n\tpublic GuicheVO getGuiche() {\n\t\treturn guiche;\n\t}\n\tpublic void setGuiche(GuicheVO guiche) {\n\t\tthis.guiche = guiche;\n\t}\n\n\n\tpublic String getDataHora() {\n\t\treturn dataHora;\n\t}\n\n\n\tpublic void setDataHora(String dataHora) {\n\t\tthis.dataHora = dataHora;\n\t}\n\t\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1368,"cells":{"blob_id":{"kind":"string","value":"03bf313edf3d49f064c13283e10c287147e5b685"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"tfisher1226/ARIES"},"path":{"kind":"string","value":"/bookshop2/bookshop2-seller/bookshop2-seller-service/src/main/java/bookshop2/seller/SellerProcessMBean.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":197,"string":"197"},"score":{"kind":"number","value":1.6015625,"string":"1.601563"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package bookshop2.seller;\n\nimport javax.management.MXBean;\n\n\n@MXBean\npublic interface SellerProcessMBean {\n\t\n\tpublic static final String MBEAN_NAME = \"bookshop2.buyer:name=SellerProcessMBean\";\n\t\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1369,"cells":{"blob_id":{"kind":"string","value":"53330a949020acbc4cd77de46b04f64a5c579fd7"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"DeepaMalviya/OfficeProject"},"path":{"kind":"string","value":"/app/src/main/java/com/daffodil/officeproject/SplashModule/SplashActivity.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9793,"string":"9,793"},"score":{"kind":"number","value":1.8359375,"string":"1.835938"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.daffodil.officeproject.SplashModule;\n\nimport android.Manifest;\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Handler;\nimport android.support.annotation.NonNull;\nimport androidx.core.app.ActivityCompat;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.telephony.TelephonyManager;\nimport android.util.Log;\nimport android.widget.TextView;\n\nimport com.daffodil.officeproject.HomeModule.Main2Activity;\nimport com.daffodil.officeproject.LoginModule.LoginnActivity;\nimport com.daffodil.officeproject.R;\n\npublic class SplashActivity extends AppCompatActivity {\n private static final String TAG = \"SplashActivity\";\n /**\n * Duration of wait\n **/\n private final int SPLASH_DISPLAY_LENGTH = 1000;\n private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;\n private TextView loading_tv2;\n private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999;\n private TelephonyManager mTelephonyManager;\n private String userid, imei;\n SharedPreferences sharedpref;\n int PERMISSION_ALL = 1;\n\n /* String[] PERMISSIONS = {\n android.Manifest.permission.ACCESS_FINE_LOCATION,\n android.Manifest.permission.ACCESS_COARSE_LOCATION,\n android.Manifest.permission.WRITE_EXTERNAL_STORAGE,\n Manifest.permission.READ_EXTERNAL_STORAGE,\n android.Manifest.permission.CAMERA\n };*/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setTheme(R.style.splashScreenTheme);\n setContentView(R.layout.activity_splash);\n // Log.e(TAG, \"onCreate:-===== \"+!hasPermissions(this, PERMISSIONS) );\n /* if (!hasPermissions(this, PERMISSIONS)) {\n ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);\n }*/\n initView();\n\n\n }\n\n\n /**\n * Callback received when a permissions request has been completed.\n */\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,\n @NonNull int[] grantResults) {\n\n /* if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {\n // Received permission result for READ_PHONE_STATE permission.est.\");\n // Check if the only required permission has been granted\n if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number\n //alertAlert(getString(R.string.permision_available_read_phone_state));\n //doPermissionGrantedStuffs();\n } else {\n alertAlert(\"permissions_not_granted_read_phone_state\");\n }\n }\n if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {\n // Received permission result for READ_PHONE_STATE permission.est.\");\n // Check if the only required permission has been granted\n if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number\n //alertAlert(getString(R.string.permision_available_read_phone_state));\n //doPermissionGrantedStuffs();\n } else {\n alertAlert(\"permissions_not_granted_read_phone_state\");\n }\n }*/\n /* if (requestCode == PERMISSIONS_REQUEST_READ_PHONE_STATE\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n getDeviceImei();\n } *//*if (requestCode == PERMISSION_ALL\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n getDeviceImei();\n }*/\n }\n\n public static boolean hasPermissions(Context context, String... permissions) {\n if (context != null && permissions != null) {\n for (String permission : permissions) {\n if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {\n return false;\n }\n }\n }\n return true;\n }\n\n private void alertAlert(String msg) {\n new AlertDialog.Builder(SplashActivity.this)\n .setTitle(\"Permission Request\")\n .setMessage(msg)\n .setCancelable(false)\n .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n // do somthing here\n }\n })\n // .setIcon(R.drawable.onlinlinew_warning_sign)\n .show();\n }\n\n\n String mobile, time_in, time_out, user_id, otp, user_role, user_name, company_id, company_name;\n\n private void initView() {\n Log.e(TAG, \"initView: \");\n\n sharedpref = getSharedPreferences(\"opark\", Context.MODE_PRIVATE);\n mobile = sharedpref.getString(\"mobile\", \"\");\n user_id = sharedpref.getString(\"user_id\", \"\");\n otp = sharedpref.getString(\"otp\", \"\");\n user_role = sharedpref.getString(\"user_role\", \"\");\n user_name = sharedpref.getString(\"user_name\", \"\");\n company_id = sharedpref.getString(\"company_id\", \"\");\n company_name = sharedpref.getString(\"company_name\", \"\");\n Log.e(TAG, \"initView:user_id\" + user_id);\n time_in = sharedpref.getString(\"time_in\", \"\");\n time_out = sharedpref.getString(\"time_out\", \"\");\n\n Log.e(TAG, \"initView:time_in \" + time_in);\n Log.e(TAG, \"initView:time_out \" + time_out);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE)\n != PackageManager.PERMISSION_GRANTED) {\n requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},\n PERMISSIONS_REQUEST_READ_PHONE_STATE);\n Log.e(TAG, \"initView: if permission\");\n } else {\n Log.e(TAG, \"initView: else permission\");\n getDeviceImei();\n }\n }\n\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n try {\n if (user_id.equals(\"\")) {\n Log.e(TAG, \"run1\" + user_id.equals(\"\"));\n Intent intentSplash = new Intent(SplashActivity.this, LoginnActivity.class);\n startActivity(intentSplash);\n overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);\n finish();\n } else if (user_name.equals(\"\") && user_id.equals(\"\") && company_name.equals(\"\") && user_name.equals(\"\")) {\n Log.e(TAG, \"run2:user_name \");\n Intent intentSplash = new Intent(SplashActivity.this, LoginnActivity.class);\n startActivity(intentSplash);\n overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);\n finish();\n } else if (!user_id.equals(\"\")) {\n Log.e(TAG, \"run7: else\" + !user_id.equals(\"\"));\n Log.e(TAG, \"run7: else user_id\" + user_id);\n Intent intentSplash = new Intent(SplashActivity.this, Main2Activity.class);\n startActivity(intentSplash);\n overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);\n finish();\n } else {\n Log.e(TAG, \"run: final else\" );\n }\n\n\n //}\n\n\n } catch (Exception err) {\n initView();\n Intent mainIntent = new Intent(SplashActivity.this, LoginnActivity.class);\n startActivity(mainIntent);\n finish();\n err.printStackTrace();\n }\n }\n\n }, SPLASH_DISPLAY_LENGTH);\n }\n\n /* @Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions,\n int[] grantResults) {\n if (requestCode == PERMISSIONS_REQUEST_READ_PHONE_STATE\n && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n getDeviceImei();\n }\n }*/\n\n @SuppressLint(\"NewApi\")\n private void getDeviceImei() {\n Log.e(TAG, \"getDeviceImei: \");\n mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n // TODO: Consider calling\n // Activity#requestPermissions\n // here to request the missing permissions, and then overriding\n // public void onRequestPermissionsResult(int requestCode, String[] permissions,\n // int[] grantResults)\n // to handle the case where the user grants the permission. See the documentation\n // for Activity#requestPermissions for more details.\n return;\n }\n imei = mTelephonyManager.getDeviceId();\n Log.e(\"msg\", \"DeviceImei \" + imei);\n }\n\n\n}\n\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1370,"cells":{"blob_id":{"kind":"string","value":"f79343edcb02ef3ba732f37eeffcdfddda866ab2"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"Pig-Everest/GoodsPromotion"},"path":{"kind":"string","value":"/src/main/java/com/haut/promotion/service/impl/FullCouponServiceImpl.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":800,"string":"800"},"score":{"kind":"number","value":2.265625,"string":"2.265625"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.haut.promotion.service.impl;\n\nimport com.haut.promotion.domain.FullCoupon;\nimport org.springframework.stereotype.Service;\nimport javax.annotation.Resource;\nimport com.haut.promotion.mapper.FullCouponMapper;\nimport com.haut.promotion.service.FullCouponService;\n@Service\npublic class FullCouponServiceImpl implements FullCouponService{\n\n @Resource\n private FullCouponMapper fullCouponMapper;\n\n /**\n * 新建新的满减券\n *\n * @param full 满多少\n * @param reduction 减多少\n */\n @Override\n public void createFullCoupon(Integer full, Integer reduction) {\n FullCoupon fullCoupon = new FullCoupon();\n fullCoupon.setFull(full);\n fullCoupon.setReduction(reduction);\n fullCouponMapper.insertSelective(fullCoupon);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1371,"cells":{"blob_id":{"kind":"string","value":"7f427a48879fbbb13b202425face2d6a61f077d8"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"chenhongbao/adminsys"},"path":{"kind":"string","value":"/src/chb/client/Login.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8427,"string":"8,427"},"score":{"kind":"number","value":2.390625,"string":"2.390625"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package chb.client;\n\nimport chb.base.LoggingProxy;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\n\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.*;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathExpression;\nimport javax.xml.xpath.XPathFactory;\nimport java.io.File;\nimport java.io.IOException;\nimport java.sql.*;\n\npublic class Login extends AServlet{\n\n protected File configFile = null;\n protected HttpServletRequest reqst = null;\n protected HttpServletResponse respos = null;\n\n @Override\n protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n\n this.reqst = req;\n this.respos =resp;\n String oper = req.getParameter(\"operation\");\n\n if(oper.equals(\"login\")) {\n /**\n * If login succeeds, jump to the review.se, otherwise goes back to login.html.\n */\n if(checkUserLogin(req.getParameter(\"identityNo\"), req.getParameter(\"pwd\"))) {\n RequestDispatcher dispatcher = req.getRequestDispatcher(\"/review.se\");\n dispatcher.forward(req, resp);\n }else {\n RequestDispatcher dispatcher = req.getRequestDispatcher(\"/index.html\");\n dispatcher.forward(req, resp);\n }\n } else if (oper.equals(\"register\")) {\n /**\n * If the user clicks the register button, goes to register page.\n * NOTE:\n * Give top = 1, will show the top banner, other value will hid the banner.\n */\n RequestDispatcher dispatcher = req.getRequestDispatcher(\"/register.jsp?top=1\");\n dispatcher.forward(req, resp);\n } else {\n /**\n * Bad incoming parameter.\n */\n String lp = getInitParameterPath(\"path.login.error.log\");\n LoggingProxy logger = new LoggingProxy(lp);\n logger.log(LoggingProxy.ERROR, \"[\"+getHash(req.getParameterMap())+\"]Login abused, wrong field name.\");\n\n req.setAttribute(\"info\", \"登陆参数错误,请联系管理员。\");\n RequestDispatcher dispatcher = req.getRequestDispatcher(\"/error.jsp\");\n dispatcher.forward(req, resp);\n }\n }\n\n /**\n * Check whether the user has registered.\n * @param idNo the identity number of the user.\n * @param pwd the password of the user\n * @return true if user exists.\n */\n protected boolean checkUserLogin(String idNo, String pwd) {\n String p = getInitParameterPath(\"path.datasource.config\");\n /* in order to build the connection string, we need configuration file. */\n this.configFile = new File(p);\n if(this.configFile.exists() == false || this.configFile.canRead() == false) {\n return false;\n }\n\n String url = buildConnectionString();\n Connection conn = getConnection(url, \"com.mysql.jdbc.Driver\");\n if(conn == null) {\n String lp = getInitParameterPath(\"path.login.error.log\");\n LoggingProxy logger = new LoggingProxy(lp);\n logger.log(LoggingProxy.ERROR, \"[\"+getHash(reqst.getParameterMap())+\"]Login error. Database connection error, return null.\");\n\n return false;\n }\n try {\n Statement stat = conn.createStatement();\n String query = \"select 1 from register_info where pwd = \\'\" + pwd + \"\\' and identityNo = \\'\" + idNo +\"\\';\";\n ResultSet set = stat.executeQuery(query);\n\n return set.next();\n } catch (SQLException e) {\n\n String lp = getInitParameterPath(\"path.login.error.log\");\n LoggingProxy logger = new LoggingProxy(lp);\n logger.log(LoggingProxy.ERROR, \"[\"+getHash(reqst.getParameterMap())+\"]Login error.\" + e.getMessage());\n\n return false;\n }\n }\n\n /**\n * Build connection string from XML configuration file.\n *\n * @return connection string\n */\n protected String buildConnectionString() {\n String conn = \"\";\n\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n DocumentBuilder builder = null;\n Document doc = null;\n XPath xpath = null;\n try {\n builder = factory.newDocumentBuilder();\n doc = builder.parse(this.configFile);\n xpath = XPathFactory.newInstance().newXPath();\n } catch (Exception e) {\n return null;\n }\n\n conn += getSingleValueFromXML(xpath, \"//datasource/header/@value\", doc);\n conn += \"//\" + getSingleValueFromXML(xpath, \"//datasource/address/@value\", doc);\n conn += \":\" + getSingleValueFromXML(xpath, \"//datasource/port/@value\", doc);\n conn += \"/\" + getSingleValueFromXML(xpath, \"//datasource/database/@value\", doc);\n conn += \"?\" + getPairValueFromXML(xpath, \"//datasource/param\", doc);\n\n return conn;\n }\n\n /**\n * Draw the value from XML by XPath.\n *\n * @param xpath instance of XPath\n * @param path XPath expression\n * @param doc Document instance\n * @return string value\n */\n protected String getSingleValueFromXML(XPath xpath, String path, Document doc) {\n if (doc == null || xpath == null || path == null) {\n return \"\";\n }\n try {\n XPathExpression expr = xpath.compile(path);\n Object res = expr.evaluate(doc, XPathConstants.NODESET);\n NodeList nodes = (NodeList) res;\n if (nodes.getLength() < 1) {\n return null;\n }\n Node n = nodes.item(0);\n String v = n.getNodeValue();\n\n return v;\n } catch (Exception e) {\n return \"\";\n }\n }\n\n /**\n * Get key-value pairs in the form 'name1=value1&name2=value2'.\n *\n * @param xpath instance of XPath\n * @param path XPath expression\n * @param doc Document instance\n * @return string value\n */\n protected String getPairValueFromXML(XPath xpath, String path, Document doc) {\n if (doc == null || xpath == null || path == null) {\n return \"\";\n }\n try {\n XPathExpression expr = xpath.compile(path);\n Object res = expr.evaluate(doc, XPathConstants.NODESET);\n NodeList nodes = (NodeList) res;\n if (nodes.getLength() < 1) {\n return null;\n }\n String v = \"\";\n for (int i = 0; i < nodes.getLength(); ++i) {\n Node n = nodes.item(i);\n NamedNodeMap nnm = n.getAttributes();\n\n Node n1 = nnm.getNamedItem(\"name\");\n Node n2 = nnm.getNamedItem(\"value\");\n\n if(n1 == null || n2 == null) {\n continue;\n }\n v += n1.getNodeValue();\n v += \"=\" + n2.getNodeValue();\n\n if (i != nodes.getLength() - 1) {\n v += \"&\";\n }\n }\n\n return v;\n } catch (Exception e) {\n return \"\";\n }\n }\n\n\n /**\n * Create JDBC connection.\n * @param url connection url\n * @param classname Class name used in Class.forName().\n * @return connection instance\n */\n public Connection getConnection(String url, String classname) {\n try {\n Class.forName(classname);\n Connection con = DriverManager.getConnection(url);\n\n return con;\n } catch (ClassNotFoundException e) {\n String lp = getInitParameterPath(\"path.login.error.log\");\n LoggingProxy logger = new LoggingProxy(lp);\n logger.log(LoggingProxy.ERROR, \"[\"+getHash(reqst.getParameterMap())+\"]\" +\"Login error.\\t\"+ e.getMessage());\n\n return null;\n } catch (SQLException e) {\n String lp = getInitParameterPath(\"path.login.error.log\");\n LoggingProxy logger = new LoggingProxy(lp);\n logger.log(LoggingProxy.ERROR, \"[\"+getHash(reqst.getParameterMap())+\"]\"+\"Login error.\\t\"+e.getMessage());\n\n return null;\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1372,"cells":{"blob_id":{"kind":"string","value":"172c128e3344135d169beab00c5d4ba761ed8c26"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"stbischof/bnd"},"path":{"kind":"string","value":"/bndtools.m2e/src/bndtools/m2e/WorkspaceProjectPostProcessor.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2035,"string":"2,035"},"score":{"kind":"number","value":2,"string":"2"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["EPL-2.0","Apache-2.0"],"string":"[\n \"EPL-2.0\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package bndtools.m2e;\n\nimport java.io.File;\nimport java.nio.file.Paths;\n\nimport org.apache.maven.model.Build;\nimport org.apache.maven.plugin.MojoExecutionException;\nimport org.apache.maven.project.MavenProject;\nimport org.eclipse.aether.artifact.Artifact;\nimport org.eclipse.aether.artifact.DefaultArtifact;\nimport org.eclipse.aether.resolution.ArtifactResult;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.m2e.core.project.IMavenProjectFacade;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport aQute.bnd.maven.lib.resolve.PostProcessor;\n\nclass WorkspaceProjectPostProcessor implements MavenRunListenerHelper, PostProcessor {\n\n\tprivate static final Logger\t\tlogger\t= LoggerFactory.getLogger(WorkspaceProjectPostProcessor.class);\n\n\tprivate final IProgressMonitor\tmonitor;\n\n\tWorkspaceProjectPostProcessor(IProgressMonitor monitor) {\n\t\tthis.monitor = monitor;\n\t}\n\n\t@Override\n\tpublic ArtifactResult postProcessResult(ArtifactResult resolvedArtifact) throws MojoExecutionException {\n\t\tArtifact artifact = resolvedArtifact.getArtifact();\n\t\tIMavenProjectFacade projectFacade = mavenProjectRegistry.getMavenProject(artifact.getGroupId(),\n\t\t\tartifact.getArtifactId(), artifact.getVersion());\n\t\tif (projectFacade != null) {\n\t\t\ttry {\n\t\t\t\tMavenProject mavenProject = projectFacade.getMavenProject(monitor);\n\t\t\t\tBuild build = mavenProject.getBuild();\n\t\t\t\tFile file = Paths.get(build.getDirectory(), build.getFinalName()\n\t\t\t\t\t.concat(\".\")\n\t\t\t\t\t.concat(artifact.getExtension()))\n\t\t\t\t\t.toFile();\n\t\t\t\tresolvedArtifact = new ArtifactResult(resolvedArtifact.getRequest());\n\t\t\t\tresolvedArtifact.setArtifact(\n\t\t\t\t\tnew DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(),\n\t\t\t\t\t\tartifact.getExtension(), artifact.getVersion(), artifact.getProperties(), file));\n\t\t\t} catch (Exception e) {\n\t\t\t\tif (logger.isWarnEnabled()) {\n\t\t\t\t\tlogger.warn(\"Could not obtain project artifact for {} due to: {}\", resolvedArtifact,\n\t\t\t\t\t\te.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn resolvedArtifact;\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1373,"cells":{"blob_id":{"kind":"string","value":"9d7f43e1a18b02126502677b1e7419c4f63d7606"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"SuzyWu2014/coprhd-controller"},"path":{"kind":"string","value":"/controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/discovery/smis/processor/detailedDiscovery/FastPolicyProcessor.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2762,"string":"2,762"},"score":{"kind":"number","value":1.921875,"string":"1.921875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\n * Copyright (c) 2014-2015 EMC Corporation\n * All Rights Reserved\n */\npackage com.emc.storageos.volumecontroller.impl.plugins.discovery.smis.processor.detailedDiscovery;\n\nimport com.emc.storageos.plugins.BaseCollectionException;\nimport com.emc.storageos.plugins.common.Constants;\nimport com.emc.storageos.plugins.common.Processor;\nimport com.emc.storageos.plugins.common.domainmodel.Operation;\nimport com.emc.storageos.volumecontroller.impl.plugins.discovery.smis.processor.fast.FASTPolicyProcessor;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.cim.CIMObjectPath;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * This processor is responsible for discovering VNX and VNAX fast policies.\n */\npublic class FastPolicyProcessor extends Processor {\n private Logger log = LoggerFactory.getLogger(FastPolicyProcessor.class);\n\n @Override\n public void processResult(Operation operation, Object resultObj, Map keyMap)\n throws BaseCollectionException {\n try {\n final Iterator it = (Iterator) resultObj;\n\n while (it.hasNext()) {\n final CIMObjectPath policyObjectPath = it.next();\n String systemName = policyObjectPath.getKey(Constants.SYSTEMNAME).getValue().toString();\n\n if (!systemName.contains((String) keyMap.get(Constants._serialID))) {\n continue;\n }\n String[] array = systemName.split(Constants.PATH_DELIMITER_REGEX);\n String policyRuleName = policyObjectPath.getKey(Constants.POLICYRULENAME)\n .getValue().toString();\n log.info(\"Policy Name {}\", policyRuleName);\n String policyKey = validateFastPolicy(array[0], policyRuleName);\n if (null != policyKey) {\n log.info(\"Adding Policy Object Path {}\", policyObjectPath);\n addPath(keyMap, policyKey, policyObjectPath);\n }\n\n }\n } catch (Exception e) {\n log.error(\"Fast Policy discovery failed during UnManaged Volume discovery\", e);\n }\n\n }\n\n public static String validateFastPolicy(String arrayType, String policyRuleName) {\n if (Constants.CLARIION.equalsIgnoreCase(arrayType)) {\n return Constants.VNXFASTPOLICIES;\n }\n if (Constants.SYMMETRIX.equalsIgnoreCase(arrayType)\n && !FASTPolicyProcessor.GlobalVMAXPolicies.contains(policyRuleName)) {\n return Constants.VMAXFASTPOLICIES;\n }\n return null;\n\n }\n\n @Override\n protected void setPrerequisiteObjects(List inputArgs) throws BaseCollectionException {\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1374,"cells":{"blob_id":{"kind":"string","value":"05f1629fd8dde6cea01556b35082bb7e46ce827f"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"kaueelias/Geometria-Arq.Dev.Sis.Mult"},"path":{"kind":"string","value":"/Tresde.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":96,"string":"96"},"score":{"kind":"number","value":1.828125,"string":"1.828125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package BR.USJT.OO;\r\n\r\npublic abstract class Tresde {\r\n\t\r\n\tpublic abstract double volume();\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1375,"cells":{"blob_id":{"kind":"string","value":"3f23d7b97966ffafccf749add891b9d49a3e6e92"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"muka-robusta/salon"},"path":{"kind":"string","value":"/salon-data/src/main/java/io/github/onetwostory/salon/repositories/MasterRepo.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":337,"string":"337"},"score":{"kind":"number","value":1.8203125,"string":"1.820313"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package io.github.onetwostory.salon.repositories;\n\nimport io.github.onetwostory.salon.domain.Master;\nimport org.springframework.data.repository.CrudRepository;\n\nimport java.util.List;\nimport java.util.Optional;\n\npublic interface MasterRepo extends CrudRepository {\n\n Optional findByLastName(String lastName);\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1376,"cells":{"blob_id":{"kind":"string","value":"ebd8507045243626f1442949dd730e2366c88991"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"mdsaleem1804/Android"},"path":{"kind":"string","value":"/KalviSeithi_AadharConnections/app/src/main/java/nellaibill/aadharconnections/AadharMobile.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4071,"string":"4,071"},"score":{"kind":"number","value":2.109375,"string":"2.109375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package nellaibill.aadharconnections;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.ActionBar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.Toolbar;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.Toast;\n\nimport com.kirianov.multisim.MultiSimTelephonyManager;\npublic class AadharMobile extends AppCompatActivity {\n MultiSimTelephonyManager multiSimTelephonyManager;\n Button xBtn1, xBtn2;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_aadhar_mobile);\n customBar();\n try {\n xBtn1 = (Button) findViewById(R.id.btnsim1);\n xBtn2 = (Button) findViewById(R.id.btnsim2);\n multiSimTelephonyManager = new MultiSimTelephonyManager(this, new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n useInfo();\n }\n });\n }catch(Exception e)\n {\n Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();\n }\n }\n public void refresh(View v)\n {\n Intent intent = getIntent();\n finish();\n startActivity(intent);\n }\n public void sim1(View v)\n {\n try {\n Intent callIntent = new Intent(Intent.ACTION_CALL);\n callIntent.setData(Uri.parse(\"tel:14546\"));\n callIntent.putExtra(\"com.android.phone.extra.slot\", 0);\n startActivity(callIntent);\n } catch (Exception e) {\n //TODO smth\n }\n }\n public void sim2(View v)\n {\n try {\n Intent callIntent = new Intent(Intent.ACTION_CALL);\n callIntent.putExtra(\"com.android.phone.extra.slot\",1);\n callIntent.setData(Uri.parse(\"tel:14546\"));\n startActivity(callIntent);\n } catch (Exception e) {\n //TODO smth\n }\n }\n\n public void customBar(){\n ActionBar actionBar = getSupportActionBar();\n actionBar.setDisplayShowHomeEnabled(false);\n actionBar.setDisplayShowTitleEnabled(false);\n\n LayoutInflater inflater = LayoutInflater.from(this);\n View customView = inflater.inflate(R.layout.custom_actionbar, null);\n\n ImageView menus =(ImageView) customView.findViewById(R.id.slidingmenu);\n\n actionBar.setCustomView(customView);\n actionBar.setDisplayShowCustomEnabled(true);\n\n\n actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);\n\n Toolbar toolbar=(Toolbar)actionBar.getCustomView().getParent();\n toolbar.setContentInsetsAbsolute(0, 0);\n toolbar.getContentInsetEnd();\n toolbar.setPadding(0, 0, 0, 0);\n }\n public void useInfo() {\n // get number of slots:\n if (multiSimTelephonyManager != null) {\n multiSimTelephonyManager.sizeSlots();\n }\n // get info from each slot:\n if (multiSimTelephonyManager != null) {\n for(int i = 0; i < multiSimTelephonyManager.sizeSlots(); i++) {\n if(i==0) {\n xBtn1.setText(\"Connect Aadhar -\"+multiSimTelephonyManager.getSlot(i).getNetworkOperatorName().toString());\n }\n else {\n xBtn2.setText(\"Connect Aadhar -\"+multiSimTelephonyManager.getSlot(i).getNetworkOperatorName().toString());\n }\n }\n }\n }public void updateInfo() {\n // for update UI\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n multiSimTelephonyManager.update();\n useInfo();\n }\n });\n // for update background information\n multiSimTelephonyManager.update();\n useInfo();\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1377,"cells":{"blob_id":{"kind":"string","value":"6548614fc601c86e931807cb9417aed97a2c1b3c"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"zh2333/LeetCode"},"path":{"kind":"string","value":"/src/com/leetcode/p365/Solution.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1817,"string":"1,817"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.leetcode.p365;\n\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.Queue;\nimport java.util.Set;\n\n/**\n * 有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?\n\t如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。\n\t你允许:\n\t装满任意一个水壶\n\t清空任意一个水壶\n\t从一个水壶向另外一个水壶倒水,直到装满或者倒空\n\t示例 1: (From the famous \"Die Hard\" example)\n\t输入: x = 3, y = 5, z = 4\n\t输出: True\n\t示例 2:\n\t输入: x = 2, y = 6, z = 5\n\t输出: False\n * @author 张恒\n *\tgcd方法:如果z%(x和y的最大公约数)==0,表示可以\n */\nclass Solution {\n public boolean canMeasureWater(int x, int y, int z) {\n \tif(z < 0 || x+y < z) return false;\n \t\n \tint big = Math.max(x, y);\n \tint small = Math.min(x, y);\n \t\n \tif(small ==0 ) return big == z;\n \twhile(big % small != 0){\n \t\tint tmp = small;\n \t\tsmall = big % small;\n \t\tbig = tmp;\n \t}\n \treturn small == z;\n }\n}\n\nclass Solution2 {\n public boolean canMeasureWater(int x, int y, int z) {\n \tif(z < 0 || x+y < z) return false;\n \t\n \tSet set = new HashSet();//记录状态,防止重复计算\n \tQueue q = new LinkedList<>();\n \tq.offer(0);\n \t\n \twhile(!q.isEmpty()){\n \t\tint n = q.poll();\n \t\t\n \t\tif(n + x <= x+y && set.add(n+x)){\n \t\t\tq.add(n+x);\n \t\t}\n \t\tif(n + y <= x+y && set.add(n+y)){\n \t\t\tq.add(n+y);\n \t\t}\n \t\t\n \t\tif(n-x>=0 && set.add(n-x)){\n \t\t\tq.add(n-x);\n \t\t}\n \t\t\n \t\tif(n-y >= 0 && set.add(n-y)){\n \t\t\tq.add(n-y);\n \t\t}\n \t\t\n \t\tif(set.contains(z)){\n \t\t\treturn true;\n \t\t}\n \t\t\n \t}\n \treturn false;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1378,"cells":{"blob_id":{"kind":"string","value":"6464d107dd771e6b1402ad6bb25fa259620bcbd7"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"JuliaKodosova/Mytasks"},"path":{"kind":"string","value":"/Task5/src/core/Main.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":516,"string":"516"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package core;\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tTester tester1 = new Tester(\"Julia\", \"Kodosova\", 7, \"advanced\", 23);\n\t\tSystem.out.println(tester1.printInfo());\n\t\ttester1.printInfo(tester1.getSalary());\n\t\ttester1.printInfo(tester1.getName(), tester1.getSurname());\n\t\ttester1.printInfo(tester1.getExpirienceInYears(), tester1.getEnglishLevel(), tester1.getSalary());\n\t\tTester.printSmth();\n\n\t\tSystem.out.println(RegularExp.test(\"abcd\"));\n\t\tSystem.out.print(RegularExp.test2(\"124\"));\n\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1379,"cells":{"blob_id":{"kind":"string","value":"0ff17a17b7ca22dd54c219f7eda6da785ea8b2fb"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"pabloscotto87/pro3."},"path":{"kind":"string","value":"/src/main/java/pro3maven/pro3/Main.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2397,"string":"2,397"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage pro3maven.pro3;\n\nimport Factories.FactoryDao;\nimport Factories.FactoryService;\nimport IDao.UsuarioDao;\nimport Modelos.Log;\nimport Modelos.LogUsuario;\nimport Modelos.Usuario;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Properties;\nimport java.util.Scanner;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\n/**\n *\n * @author pabloscotto87\n */\npublic class Main {\n\n public static String usuarioLogueado;\n public static Scanner s = new Scanner(System.in);\n\n public static void main(String[] arg) {\n Log.mapLog.clear();\n boolean salir = false;\n while (!salir) {\n System.out.println(\"Seleccione Opción\");\n System.out.println(\"L-Login\");\n System.out.println(\"P-Imprime Log\");\n System.out.println(\"S-Salir\");\n switch (s.next()) {\n case \"L\":\n logueo();\n break;\n case \"P\":\n Log.imprimeLog();\n break;\n case \"S\":\n salir = true;\n break;\n }\n }\n }\n\n public static void logueo() {\n //Login\n FactoryService factory = new FactoryService();\n UsuarioDao usuarioDao = factory.crearUsuarioServicio();\n Usuario[] usuarios = usuarioDao.getAll();\n\n String usuario;\n String pass;\n boolean logueado = false;\n while (!logueado) {\n System.out.println(\"Ingrese Usuario: \");\n usuario = s.next();\n System.out.println(\"Ingrese Password: \");\n pass = s.next();\n for (Usuario user : usuarios) {\n if (user.getNombre().equals(usuario) && user.getPass().equals(pass)) {\n usuarioLogueado = usuario;\n LogUsuario logUsuario = new LogUsuario(usuarioLogueado, \"Logueo\", new Date());\n Log.mapLog.put(Log.mapLog.size(), logUsuario);\n logueado = true;\n break;\n }\n }\n }\n }\n\n public static void menu() {\n\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1380,"cells":{"blob_id":{"kind":"string","value":"b522fcf80f09e2e6e7a8d8f07345a1b0315bb744"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"twewyttst777/2017-APCSA-Casino"},"path":{"kind":"string","value":"/misc/BingoCard.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":907,"string":"907"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"import java.util.ArrayList;\nimport java.util.Collections;\npublic class BingoCard{\n BingoNum[][] nums;\n public BingoCard(){\n for(int j = 0; j < 5; j++){\n ArrayList num = new ArrayList();\n for(int k = 1; k <= 15; k++){\n num.add(k);\n }\n Collections.shuffle(num);\n for(int r = 0; r < 5; r++){\n if(j == 2 && r == 2){\n nums[r][j] = new BingoNum(0);\n } else {\n nums[r][j] = new BingoNum(num.remove(0));\n }\n }\n }\n }\n \n public void mark(int col, int row){\n nums[col][row].mark();\n }\n \n public BingoNum[][] showCard(){\n return nums;\n }\n \n public BingoNum seeNumber(int col, int row){\n return nums[col][row];\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1381,"cells":{"blob_id":{"kind":"string","value":"102fbdbda097b92cf31e5b36aee872129798a407"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"jaumevn/lipidianSoccer"},"path":{"kind":"string","value":"/src/domain/Estadisticas.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1027,"string":"1,027"},"score":{"kind":"number","value":2.21875,"string":"2.21875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\n * Alexandre Vidal Obiols\n */\n\n\npackage domain;\n\n\npublic abstract class Estadisticas {\n\t\n\tprivate Integer golesRecibidos;\n\t\n\tprivate Integer golesMarcados;\n\t\n\tprivate Integer tarjetasAmarillas;\n\t\n\tprivate Integer tarjetasRojas;\n\n\t\n\tpublic Estadisticas() {\n\t\tgolesRecibidos = 0;\n\t\tgolesMarcados = 0;\n\t\ttarjetasAmarillas = 0;\n\t\ttarjetasRojas = 0;\n\t}\n\t\n\t\n\tpublic Integer getGolesRecibidos() {\n\t\treturn golesRecibidos;\n\t}\n\t\n\tpublic void setGolesRecibidos(Integer golesRecibidos) {\n\t\tthis.golesRecibidos = golesRecibidos;\n\t}\n\n\tpublic Integer getGolesMarcados() {\n\t\treturn golesMarcados;\n\t}\n\t\n\tpublic void setGolesMarcados(Integer golesMarcados) {\n\t\tthis.golesMarcados = golesMarcados;\n\t}\n\t\n\tpublic Integer getTarjetasAmarillas() {\n\t\treturn tarjetasAmarillas;\n\t}\n\t\n\tpublic void setTarjetasAmarillas(Integer tarjetasAmarillas) {\n\t\tthis.tarjetasAmarillas = tarjetasAmarillas;\n\t}\n\t\n\tpublic Integer getTarjetasRojas() {\n\t\treturn tarjetasRojas;\n\t}\n\t\n\tpublic void setTarjetasRojas(Integer tarjetasRojas) {\n\t\tthis.tarjetasRojas = tarjetasRojas;\n\t}\n\n \n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1382,"cells":{"blob_id":{"kind":"string","value":"9300735b99ec75e8610f3431b29307c54fe0fd41"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"zhanght86/HSBC20171018"},"path":{"kind":"string","value":"/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/cbcheckgrp/ImpartToICDBL.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5927,"string":"5,927"},"score":{"kind":"number","value":2.03125,"string":"2.03125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.sinosoft.lis.cbcheckgrp;\nimport org.apache.log4j.Logger;\n\nimport com.sinosoft.lis.db.LCDiseaseResultDB;\nimport com.sinosoft.lis.db.LDPersonDB;\nimport com.sinosoft.lis.pubfun.GlobalInput;\nimport com.sinosoft.lis.pubfun.MMap;\nimport com.sinosoft.lis.pubfun.PubFun;\nimport com.sinosoft.lis.pubfun.PubSubmit;\nimport com.sinosoft.lis.schema.LDPersonSchema;\nimport com.sinosoft.lis.vschema.LCDiseaseResultSet;\nimport com.sinosoft.utility.CError;\nimport com.sinosoft.utility.CErrors;\nimport com.sinosoft.utility.VData;\n\n/**\n *

\n * Title:\n *

\n *

\n * Description:\n *

\n *

\n * Copyright: Copyright (c) 2004\n *

\n *

\n * Company: SinoSoft\n *

\n * \n * @author HYQ\n * @version 1.0\n */\n\npublic class ImpartToICDBL {\nprivate static Logger logger = Logger.getLogger(ImpartToICDBL.class);\n\t// 错误处理类,每个需要错误处理的类中都放置该类\n\tpublic CErrors mErrors = new CErrors();\n\n\t/** 往界面传输数据的容器 */\n\tprivate VData mResult = new VData();\n\tprivate VData mInputData;\n\tprivate GlobalInput tGI = new GlobalInput();\n\n\t/** 数据操作字符串 */\n\tprivate String mOperate;\n\tprivate String mOperator;\n\tprivate String mManageCom;\n\n\t/** 业务操作类 */\n\tprivate LCDiseaseResultSet mLCDiseaseResultSet = new LCDiseaseResultSet();\n\n\t/** 业务数据 */\n\tprivate String mName = \"\";\n\tprivate String mDelSql = \"\";\n\n\tpublic ImpartToICDBL() {\n\t}\n\n\t/**\n\t * 传输数据的公共方法\n\t * \n\t * @param cInputData\n\t * VData\n\t * @param cOperate\n\t * String\n\t * @return boolean\n\t */\n\tpublic boolean submitData(VData cInputData, String cOperate) {\n\t\t// 将操作数据拷贝到本类中\n\t\tthis.mOperate = cOperate;\n\t\tlogger.debug(\"Operate==\" + cOperate);\n\t\t// 得到外部传入的数据,将数据备份到本类中\n\t\tif (!getInputData(cInputData)) {\n\t\t\treturn false;\n\t\t}\n\t\tlogger.debug(\"After getinputdata\");\n\n\t\tif (!checkData()) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// 进行业务处理\n\t\tif (!dealData()) {\n\t\t\treturn false;\n\t\t}\n\t\tlogger.debug(\"After dealData!\");\n\t\t// 准备往后台的数据\n\t\tif (!prepareOutputData()) {\n\t\t\treturn false;\n\t\t}\n\t\tlogger.debug(\"After prepareOutputData\");\n\n\t\tlogger.debug(\"Start ImpartToICDBL Submit...\");\n\n\t\tPubSubmit tSubmit = new PubSubmit();\n\n\t\tif (!tSubmit.submitData(mResult, \"\")) {\n\t\t\t// @@错误处理\n\t\t\tthis.mErrors.copyAllErrors(tSubmit.mErrors);\n\n\t\t\tCError tError = new CError();\n\t\t\ttError.moduleName = \"GrpUWAutoChkBL\";\n\t\t\ttError.functionName = \"submitData\";\n\t\t\ttError.errorMessage = \"数据提交失败!\";\n\t\t\tthis.mErrors.addOneError(tError);\n\n\t\t\treturn false;\n\t\t}\n\n\t\tlogger.debug(\"ImpartToICDBL end\");\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * prepareOutputData\n\t * \n\t * @return boolean\n\t */\n\tprivate boolean prepareOutputData() {\n\t\tmResult.clear();\n\t\tMMap map = new MMap();\n\n\t\tmap.put(mLCDiseaseResultSet, \"INSERT\");\n\n\t\tmResult.add(map);\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * dealData 业务逻辑处理\n\t * \n\t * @return boolean\n\t */\n\tprivate boolean dealData() {\n\t\tint tDisSerialNo;\n\t\tLCDiseaseResultDB tLCDiseaseResultDB = new LCDiseaseResultDB();\n\t\ttLCDiseaseResultDB.setContNo(mLCDiseaseResultSet.get(1).getContNo());\n\t\ttLCDiseaseResultDB.setCustomerNo(mLCDiseaseResultSet.get(1)\n\t\t\t\t.getCustomerNo());\n\t\tLCDiseaseResultSet tLCDiseaseResultSet = tLCDiseaseResultDB.query();\n\t\tif (tLCDiseaseResultSet.size() == 0) {\n\t\t\ttDisSerialNo = 0;\n\t\t} else {\n\t\t\ttDisSerialNo = tLCDiseaseResultSet.size() + 1;\n\t\t}\n\n\t\tfor (int i = 1; i <= mLCDiseaseResultSet.size(); i++) {\n\t\t\tmLCDiseaseResultSet.get(i).setName(mName);\n\t\t\tmLCDiseaseResultSet.get(i).setSerialNo(\"\" + tDisSerialNo);\n\t\t\tmLCDiseaseResultSet.get(i).setOperator(mOperator);\n\t\t\tmLCDiseaseResultSet.get(i).setMakeDate(PubFun.getCurrentDate());\n\t\t\tmLCDiseaseResultSet.get(i).setMakeTime(PubFun.getCurrentTime());\n\t\t\tmLCDiseaseResultSet.get(i).setModifyDate(PubFun.getCurrentDate());\n\t\t\tmLCDiseaseResultSet.get(i).setModifyTime(PubFun.getCurrentTime());\n\n\t\t\ttDisSerialNo++;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * checkData 数据校验\n\t * \n\t * @return boolean\n\t */\n\tprivate boolean checkData() {\n\t\tLDPersonDB tLDPersonDB = new LDPersonDB();\n\t\tLDPersonSchema tLDPersonSchema = new LDPersonSchema();\n\t\ttLDPersonDB.setCustomerNo(mLCDiseaseResultSet.get(1).getCustomerNo());\n\t\tif (!tLDPersonDB.getInfo()) {\n\t\t\t// @@错误处理\n\t\t\t// this.mErrors.copyAllErrors( tLCGrpContDB.mErrors );\n\t\t\tCError tError = new CError();\n\t\t\ttError.moduleName = \"ImpartToICDBL\";\n\t\t\ttError.functionName = \"checkData\";\n\t\t\ttError.errorMessage = \"客户信息查询失败!\";\n\t\t\tthis.mErrors.addOneError(tError);\n\t\t\treturn false;\n\t\t}\n\t\ttLDPersonSchema = tLDPersonDB.getSchema();\n\t\tmName = tLDPersonSchema.getName();\n\t\treturn true;\n\t}\n\n\t/**\n\t * getInputData\n\t * \n\t * @param cInputData\n\t * VData\n\t * @return boolean\n\t */\n\tprivate boolean getInputData(VData cInputData) {\n\t\t// 公用变量\n\t\ttGI = (GlobalInput) cInputData.getObjectByObjectName(\"GlobalInput\", 0);\n\t\tmLCDiseaseResultSet = (LCDiseaseResultSet) cInputData\n\t\t\t\t.getObjectByObjectName(\"LCDiseaseResultSet\", 0);\n\n\t\tmOperator = tGI.Operator;\n\t\tif (mOperator == null || mOperator.length() <= 0) {\n\t\t\t// @@错误处理\n\t\t\t// this.mErrors.copyAllErrors( tLCGrpContDB.mErrors );\n\t\t\tCError tError = new CError();\n\t\t\ttError.moduleName = \"ImpartToICDBL\";\n\t\t\ttError.functionName = \"getInputData\";\n\t\t\ttError.errorMessage = \"前台传输全局公共数据Operator失败!\";\n\t\t\tthis.mErrors.addOneError(tError);\n\t\t\treturn false;\n\t\t}\n\n\t\t// 取得疾病信息\n\t\tif (mLCDiseaseResultSet == null || mLCDiseaseResultSet.size() <= 0) {\n\t\t\t// @@错误处理\n\t\t\t// this.mErrors.copyAllErrors( tLCGrpContDB.mErrors );\n\t\t\tCError tError = new CError();\n\t\t\ttError.moduleName = \"ImpartToICDBL\";\n\t\t\ttError.functionName = \"getInputData\";\n\t\t\ttError.errorMessage = \"前台传输数据LCDiseaseResultSet失败!\";\n\t\t\tthis.mErrors.addOneError(tError);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * 返回结果\n\t * \n\t * @return VData\n\t */\n\tpublic VData getResult() {\n\t\treturn mResult;\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1383,"cells":{"blob_id":{"kind":"string","value":"20bd310fa2d6d2f9aa381f19c5b1fa396106dd6e"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"boonto/landsofcinder"},"path":{"kind":"string","value":"/core/src/de/loc/quest/QuestLog.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1301,"string":"1,301"},"score":{"kind":"number","value":2.453125,"string":"2.453125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package de.loc.quest;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\n\nimport de.loc.event.Event;\nimport de.loc.event.EventListener;\nimport de.loc.event.EventSystem;\nimport de.loc.event.Observable;\n\npublic class QuestLog implements Observable, EventListener {\n private final List listeners;\n private final HashMap activeQuests;\n\n public QuestLog(HashMap questList) {\n this.listeners = new ArrayList<>();\n this.activeQuests = questList;\n EventSystem.getInstance().addListener(this, EventSystem.EventType.QUEST_EVENT);\n }\n\n public HashMap getActiveQuests() {\n return this.activeQuests;\n }\n\n public void addListener(EventListener listener) {\n this.listeners.add(listener);\n }\n\n public void removeListener(EventListener listener) {\n this.listeners.remove(listener);\n }\n\n @Override\n public void fire(EventSystem.EventType eventType, Object... args) {\n for ( EventListener listener : this.listeners ) {\n listener.update(new Event(eventType));\n }\n }\n\n @Override\n public void update(Event e) {\n if ( e.eventType == EventSystem.EventType.QUEST_EVENT ) {\n this.fire(null);\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1384,"cells":{"blob_id":{"kind":"string","value":"773ffc7aa4103efb57a496ce6d20885d01fe0f0c"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"biadebeatriz/Trabalho1"},"path":{"kind":"string","value":"/Interfaces/ITableReceptacle.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":154,"string":"154"},"score":{"kind":"number","value":1.71875,"string":"1.71875"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package Interfaces;\n\npublic interface ITableReceptacle {\n\tpublic void updateTable(String[][] instances);\n\tpublic void connect(ITableProducer producer);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1385,"cells":{"blob_id":{"kind":"string","value":"0cad164ea21c2c958466dad3b8bbac1f4ed6eb7d"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"mihai9-lab/Document-handler"},"path":{"kind":"string","value":"/src/gui/listeners/change/DocumentViewsSelectionListener.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":646,"string":"646"},"score":{"kind":"number","value":2.34375,"string":"2.34375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package gui.listeners.change;\n\nimport javax.swing.JTabbedPane;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\n\nimport tree.model.Document;\nimport view.DocumentView;\n\npublic class DocumentViewsSelectionListener implements ChangeListener {\n \n\tpublic void stateChanged(ChangeEvent e) {\n JTabbedPane tabbedPane = (JTabbedPane) e.getSource();\n int n = tabbedPane.getComponentCount();\n if(n==0) return;\n int selectedIndex = tabbedPane.getSelectedIndex();\n \tDocument d = ((DocumentView)tabbedPane.getComponentAt(selectedIndex)).getDocument();\n \tif(!d.isSelected()) d.select();\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1386,"cells":{"blob_id":{"kind":"string","value":"c68375f0e089d64306bd0a4fa76dcb3406113c1c"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"zjsyhjh/leetcode"},"path":{"kind":"string","value":"/95.Unique Binary Search Trees II/Solution.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":887,"string":"887"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Solution {\n\n public List generateTrees(int n) {\n\n \tif (n == 0) {\n \t\treturn new ArrayList<>();\n \t}\n\n \treturn dfs(1, n);\n }\n\n private List dfs(int st, int ed) {\n\n \tList tree = new ArrayList<>();\n\n \tif (st > ed) {\n \t\ttree.add(null);\n \t\treturn tree;\n \t}\n\n \tfor (int mid = st; mid <= ed; mid++) {\n \t\tList ltree = dfs(st, mid - 1);\n \t\tList rtree = dfs(mid + 1, ed);\n\n \t\tfor (TreeNode lnode : ltree) {\n \t\t\tfor (TreeNode rnode : rtree) {\n \t\t\t\tTreeNode rt = new TreeNode(mid);\n \t\t\t\trt.left = lnode;\n \t\t\t\trt.right = rnode;\n \t\t\t\ttree.add(rt);\n \t\t\t}\n \t\t}\n \t}\n\n \treturn tree;\n }\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1387,"cells":{"blob_id":{"kind":"string","value":"7d678b074c378d3337505f65e38fbbf0a00fb7c1"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"JeffersonLab/clas12-offline-software"},"path":{"kind":"string","value":"/common-tools/clas-io/src/main/java/org/jlab/utils/BoardDecoderVSCM.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":14883,"string":"14,883"},"score":{"kind":"number","value":1.78125,"string":"1.78125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage org.jlab.utils;\n\nimport java.util.ArrayList;\nimport org.jlab.io.evio.EvioDataBank;\nimport org.jlab.io.evio.EvioDataDictionary;\nimport org.jlab.io.evio.EvioDataEvent;\nimport org.jlab.io.evio.EvioDataSync;\nimport org.jlab.io.evio.EvioSource;\n\n/**\n *\n * @author gavalian\n */\npublic class BoardDecoderVSCM {\n //ArrayList< ArrayList > boardEvents = new ArrayList< ArrayList >();\n ArrayList boardEvent = new ArrayList();\n \n final static int DATA_TYPE_BLKHDR = 0x00;\n final static int DATA_TYPE_BLKTLR = 0x01;\n final static int DATA_TYPE_EVTHDR = 0x02;\n final static int DATA_TYPE_TRGTIME = 0x03;\n final static int DATA_TYPE_BCOTIME = 0x04;\n final static int DATA_TYPE_FSSREVT = 0x08;\n final static int DATA_TYPE_DNV = 0x0E;\n final static int DATA_TYPE_FILLER = 0x0F;\n final static int UNIX_TYPE_FILLER = 0x0D;\n \n public BoardDecoderVSCM(){\n \n }\n \n \n public int getLayer(int slotid, int hfcbid,int chipid){\n if(slotid==10&&hfcbid==0){\n if(chipid==1||chipid==2){\n return 5;\n } \n if(chipid==3||chipid==4){\n return 6;\n }\n }\n \n if(slotid==9&&hfcbid==1){\n if(chipid==1||chipid==2){\n return 1;\n } \n if(chipid==3||chipid==4){\n return 2;\n } \n }\n \n if(slotid==9&&hfcbid==0){\n if(chipid==1||chipid==2){\n return 1;\n } \n if(chipid==3||chipid==4){\n return 2;\n }\n }\n \n if(slotid==8&&hfcbid==1){\n if(chipid==1||chipid==2){\n return 5;\n } \n if(chipid==3||chipid==4){\n return 6;\n }\n }\n return 0;\n /*\n int ring = this.getRing(slotid,hfcbid);\n int locallayer = 2;\n if(chipid<=2) locallayer = 1;\n return (ring-1)*2 + locallayer;*/\n }\n \n public int getStrip(int chipid, int chan){\n if(chipid==1){\n return chan+1;\n }\n \n if(chipid==2){\n return chan + 129;\n }\n \n if(chipid==3){\n return chan + 1;\n }\n \n if(chipid==4){\n return chan + 129;\n }\n return 0;\n /*\n int coef = chipid;\n if(coef>2) coef = coef - 1;\n return chan*coef + 1;*/\n }\n \n public int getRing(int slotid, int hfcbid){\n int sector = (slotid-3)*2 + hfcbid + 1;\n if(sector>10 && sector <=24){\n return 2;\n }\n if(sector>24 && sector <=42){\n return 3;\n }\n if(sector > 42) return 4;\n return 1; \n }\n \n public int getSector(int slotid, int hfcbid){\n \n if(slotid==10&&hfcbid==0){\n return 1;\n }\n \n if(slotid==9&&hfcbid==1){\n return 1;\n }\n \n if(slotid==9&&hfcbid==0){\n return 6;\n }\n \n if(slotid==8&&hfcbid==1){\n return 10;\n }\n \n return 0;\n /*\n int sector = (slotid-3)*2 + hfcbid + 1;\n if(sector>10 && sector <=24){\n return sector-10;\n }\n \n if(sector>24 && sector <=42){\n return sector-24;\n }\n if(sector > 42){\n return sector - 42;\n }\n return sector;*/\n }\n \n \n public ArrayList getRecords(){ return this.boardEvent;}\n \n public void decode(int[] array){\n int unixtime = 0;\n int totalLength = array.length;\n int icount = 0;\n int ievent = 0;\n int bcostart = 0;\n int bcostop = 0;\n boardEvent.clear();\n //ArrayList boardevent = null;\n int slotid = 0; \n while(icount<=totalLength){\n if(icount>=totalLength) break;\n long word = this.getWord(array[icount]);\n if ((word & 0x80000000) != -1){\n int type = (int) ((word >> 27) & 0xF); \n switch(type){\n case DATA_TYPE_BLKHDR:\n int nevents = (int) ((word>>11) & 0x3FF);\n slotid = (int) ((word >> 22) & 0x1f);\n //System.err.println(\"-> BLOCK HEADER in position = \" + icount \n //+ \" N EVENTS = \" + nevents + \" SLOT = \" + slotid);\n break;\n case DATA_TYPE_BLKTLR:\n int nwords = (int) ((word) & 0xFFFFF);\n /*\n if(boardevent!=null){\n for(BoardRecordVSCM rec : boardevent){\n rec.slotid = slotid;\n }\n }*/\n //System.err.println(\"-> BLOCK TRAILER in position = \" + icount \n //+ \" N WORDS = \" + nwords + \" slot id = \" + slotid);\n break;\n case DATA_TYPE_BCOTIME:\n //System.out.println(\"FOUND BCO TIME \" + String.format(\"%X\", word));\n bcostop = (int) ((word>>16) & 0x00FF);\n bcostart = (int) ((word) & 0x00FF);\n break;\n case DATA_TYPE_EVTHDR:\n ievent = 0;\n //System.out.println(\"FOUND EVENT HEADER \" + String.format(\"%X\", word));\n //System.err.println(\"---------> EVENT HEADER in position = \" + icount); \n break;\n case DATA_TYPE_TRGTIME: \n //System.err.println(\"----> TRIGGER TIME found at position = \" + icount);\n icount++;\n break;\n case DATA_TYPE_FSSREVT:\n {\n int chipID = (int) (word >> 19) & 0x7; // get chip id\n int channel = (int) (word >> 12) & 0x7F; // get channel\n int bco = (int) (word >> 4) & 0xFF; // get bco time\n int adc = (int) (word >> 0) & 0x7; // get adc -- value starts at 0\n int hfcbID = (int) (word >> 22) & 0x1;\n BoardRecordVSCM record = new BoardRecordVSCM();\n record.slotid = slotid;\n //if(record.slotid>=11) record.slotid = slotid - 2;\n record.adc = adc;\n record.channel = channel;\n record.bco = bco;\n record.chipid = chipID;\n record.hfcbid = hfcbID;\n record.bcostart = bcostart;\n record.bcostop = bcostop;\n if(boardEvent!=null) {\n //System.err.println(record);\n boardEvent.add(record);\n }\n //System.err.println(\"----------------> EVENT \" + ievent + \" slot = \" + \" chip = \" + chipID + \" chan = \" + channel \n //+ \" time = \" + bco + \" adc = \" + adc + \" hfcID = \"\n //+ hfcbID);\n ievent++;\n }\n break;\n default:\n break;\n }\n }\n icount++;\n }\n }\n \n \n public EvioDataBank getConvertedBanks(EvioDataEvent event){\n EvioDataBank bstBank = (EvioDataBank) event.getDictionary().createBank(\"BST::dgtz\", boardEvent.size());\n //System.err.println(\" CREATE BST BANK with size = \" + boardEvent.size());\n int counter = 0;\n for(BoardRecordVSCM rec : boardEvent){\n int sector = this.getSector(rec.slotid, rec.hfcbid);\n int layer = this.getLayer(rec.slotid, rec.hfcbid,rec.chipid);\n int strip = this.getStrip(rec.chipid,rec.channel);\n //System.err.println(\" slot ID = \" + rec.slotid + \" HFCBID = \" + rec.hfcbid\n // + \" CHIPID = \" + rec.chipid + \" CHANNEL = \" + rec.channel + \" SECTOR = \" + sector +\n // \" LAYAR = \" + layer + \" STRIP = \" + strip);\n //System.err.println(\"entry \" + counter + \" SLOT = \" +\n //rec.slotid + \" HFCBID = \" + rec.hfcbid + \" CHIP = \" + rec.chipid + \" CHANNEL = \" + rec.channel\n //+ \" SECTOR = \" + sector + \" LAYER = \" + layer );\n bstBank.setInt(\"layer\",counter,layer);\n bstBank.setInt(\"strip\",counter,strip);\n bstBank.setInt(\"sector\",counter,sector);\n bstBank.setInt(\"ADC\", counter,rec.adc);\n counter++;\n }\n return bstBank;\n //return null;\n }\n \n public void decodeold(int[] array){\n int unixtime=0;\n for(int loop = 3; loop < array.length; loop++){\n if(unixtime==1)\n {\n unixtime = 0;\n continue;\n }\n long word = getWord(array[loop]);\n if ((word & 0x80000000) != -1) {\n int type = (int) ((word >> 27) & 0xF);\n \n int slotID = 0;\n int hfcbID = 0;\n int chipID = 0;\n int channel = 0;\n int bco = 0;\n int adc = 0;\n /* HEADER */\n if(type==DATA_TYPE_BLKHDR) {\n \n System.err.println(\"-------> block started here = \" + loop);\n }\n\n if(type==DATA_TYPE_BLKTLR) {\n slotID = (int) ((word >> 22) & 0x1f);\n //System.err.println(\"-------> block ends here = \" + loop);\n }\n if(type==DATA_TYPE_EVTHDR) {\n //System.err.println(\"-------> event started here = \" + loop);\n }\n if(type==DATA_TYPE_TRGTIME) {\n //System.err.println(\"-------> TRIG TIME = \" + loop);\n }\n \n if(type==UNIX_TYPE_FILLER ) {\n unixtime = 1;\n }\n if(type==DATA_TYPE_BCOTIME) {\n \n }\n if(type==DATA_TYPE_FSSREVT) {\n //\t// System.out.printf(\" {FSSREVT}\");\n //\t// System.out.printf(\" HFCBID: %1d\", (word >> 22) & 0x1);\n //\t// System.out.printf(\" CHIPID: %1d\", (word >> 19) & 0x7);\n //\t// System.out.printf(\" CH: %3d\", (word >> 12) & 0x7F);\n //\t// System.out.printf(\" BCO: %3d\", (word >> 4) & 0xFF);\n //\t// System.out.printf(\" \\n\");\n //// System.out.printf(\" ADC: %1d\\n\", (word >> 0) & 0x7);\n chipID = (int) (word >> 19) & 0x7; // get chip id\n channel = (int) (word >> 12) & 0x7F; // get channel\n bco = (int) (word >> 4) & 0xFF; // get bco time\n adc = (int) (word >> 0) & 0x7; // get adc -- value starts at 0\n hfcbID = (int) (word >> 22) & 0x1;\n System.err.println(\"slot = \" + slotID + \" chip = \" + chipID + \" chan = \" + channel \n + \" time = \" + bco + \" adc = \" + adc + \" hfcID = \"\n + hfcbID);\n }\n if(type==DATA_TYPE_DNV) { \n System.exit(0);\n }\n if(type==DATA_TYPE_FILLER) {\n \n }\n \n if(slotID==3 || slotID==4) {\n //\t// System.out.println(\" stored hits \" ); \n }\n \n }\n\n }\n }\n \n public long getWord(int value){\n return (long) value;\n }\n \n public static void main(String[] args){\n \n String inputFileName = args[0];\n \n BoardDecoderVSCM decoder = new BoardDecoderVSCM();\n EvioSource reader = new EvioSource();\n //reader.open(\"/Users/gavalian/Work/DataSpace/svt2test.dat_000819.evio\");\n reader.open(inputFileName);\n EvioDataSync writer = new EvioDataSync();\n writer.open(\"BST_decoded_data.evio\");\n int evcounter = 0;\n int writecounter = 0; \n while(reader.hasEvent()){\n if(evcounter%400==0){\n System.err.println(\"-----------> processed events = \" + evcounter\n + \" events written = \" + writecounter);\n }\n EvioDataEvent event = (EvioDataEvent) reader.getNextEvent();\n //event.getDictionary().show();\n //event.showNodes();\n //System.err.println(\"\\n\\n\");\n //System.err.println(\"***************************************************************\");\n //System.err.println(\"********************* EVENT START \" + evcounter);\n //System.err.println(\"***************************************************************\");\n //System.err.println(\"\\n\\n\");\n int[] buffer = event.getInt(57604, 1);\n \n if(buffer!=null){\n System.err.println(\" BUFFER LENGTH = \" + buffer.length);\n \n try {\n //System.err.println(\" buffer length = \" + buffer.length);\n decoder.decode(buffer);\n \n EvioDataEvent outevent = writer.createEvent((EvioDataDictionary) event.getDictionary());\n \n EvioDataBank bstbank = decoder.getConvertedBanks(event);\n System.err.println(\" writing event \" + evcounter + \" with \" +\n bstbank.rows() + \" banks\");\n EvioDataEvent evout = writer.createEvent((EvioDataDictionary) event.getDictionary());\n if(bstbank.rows()>4){\n evout.appendBank(bstbank);\n writer.writeEvent(evout); \n writecounter++; \n }\n } catch (Exception e){\n System.err.println(\"********* ERROR : something went wrong with event # \"\n + evcounter);\n }\n }\n evcounter++;\n }\n writer.close();\n System.err.println(\"\\n\\n FINAL ------> processed events = \" + evcounter\n + \" events written = \" + writecounter);\n System.err.println(\"\\n\\n Done...\\n\\n\");\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1388,"cells":{"blob_id":{"kind":"string","value":"6ccdeb239cb98aa27bb321d3f8cfd122c93cced3"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"antonio90protom/myTimeMaster"},"path":{"kind":"string","value":"/mytime-master/src/main/java/com/protom/mytime/controller/ControllerStatus.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":106,"string":"106"},"score":{"kind":"number","value":1.703125,"string":"1.703125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.protom.mytime.controller;\n\npublic interface ControllerStatus {\n\n\tint OK = 0;\n\tint KO = -1;\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1389,"cells":{"blob_id":{"kind":"string","value":"2536daa0ffc81fdd380bcec0ca4b3573f7acbc40"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"joaomarccos/AirSoft-Association"},"path":{"kind":"string","value":"/pos-airsoft-business-rules/src/main/java/io/github/joaomarccos/pos/airsoft/repositories/GameRepositoryImpl.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1528,"string":"1,528"},"score":{"kind":"number","value":2.4375,"string":"2.4375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package io.github.joaomarccos.pos.airsoft.repositories;\n\nimport io.github.joaomarccos.pos.airsoft.dao.DaoJPAFactory;\nimport io.github.joaomarccos.pos.airsoft.dao.GameDAO;\nimport io.github.joaomarccos.pos.airsoft.enums.GameStatus;\nimport io.github.joaomarccos.pos.airsoft.entitys.Game;\nimport io.github.joaomarccos.pos.airsoft.repositories.interfaces.GameRepository;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n *\n * @author João Marcos \n */\npublic class GameRepositoryImpl implements GameRepository {\n\n private final GameDAO dao;\n\n public GameRepositoryImpl() {\n this.dao = DaoJPAFactory.createGameDao();\n }\n\n @Override\n public void save(Game entity) {\n entity.setStatus(GameStatus.DEFAULT.name());\n dao.save(entity);\n }\n\n @Override\n public void delete(Game entity) {\n dao.delete(entity);\n }\n\n @Override\n public void update(Game entity) {\n dao.update(entity);\n }\n\n @Override\n public List findAll() {\n List listQuery = dao.listQuery(\"games.all\", null);\n return listQuery;\n }\n\n @Override\n public Game findById(long id) {\n Map params = new HashMap<>();\n params.put(\"id\", id);\n return dao.simpleQuery(\"games.findbyid\", params);\n }\n\n @Override\n public long numberOfGames() {\n return dao.numberOfGames();\n }\n\n @Override\n public List findPerPage(int page) {\n return dao.findPerPage(page);\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1390,"cells":{"blob_id":{"kind":"string","value":"01a869a23f153abd39322ad7eebde70adc50f3d6"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"TarasFiliuk/calm_down"},"path":{"kind":"string","value":"/src/main/java/com/epam/ua/trainingProject/error/ErrorUtils.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":915,"string":"915"},"score":{"kind":"number","value":2.484375,"string":"2.484375"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.epam.ua.trainingProject.error;\n\nimport lombok.AccessLevel;\nimport lombok.NoArgsConstructor;\n\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\nimport static org.hibernate.validator.internal.metadata.core.ConstraintHelper.MESSAGE;\n\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class ErrorUtils {\n\n public static Error newError(String field, String message) {\n return new Error(field, message);\n }\n\n public static Errors newErrorsList(Error... phone) {\n return new Errors(asList(phone));\n }\n\n public static Errors newSingletonErrors(String message) {\n return new Errors(singletonList(new Error(MESSAGE, message)));\n }\n\n public static Errors newSingletonErrors(String message, String exceptionMessage) {\n return new Errors(singletonList(new Error(MESSAGE, message + \" \" + exceptionMessage)));\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1391,"cells":{"blob_id":{"kind":"string","value":"98eb28d47667a2508ba75d4f71f17481e74745c1"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"lixingluo/JAVA-Design-Pattern"},"path":{"kind":"string","value":"/DesignPattern-13-Decorator/src/designpattern/component/Label.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":307,"string":"307"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package designpattern.component;\n\npublic class Label extends Decorator {\n\n\tpublic Label(Component component) {\n\t\t// TODO Auto-generated constructor stub\n\t\tsuper(component);\n\t}\n\n\t@Override\n\tpublic void show() {\n\t\t// TODO Auto-generated method stub\n\t\tSystem.out.println(\"Get the Label\");\n\t\tsuper.show();\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1392,"cells":{"blob_id":{"kind":"string","value":"1354e9bcb7ae244a0b29018b4c1b18946c073c25"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"FanBeginner/MVPDemo"},"path":{"kind":"string","value":"/app/src/main/java/com/example/mvpdemo/adapter/NewsRecycleViewAdapter.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2446,"string":"2,446"},"score":{"kind":"number","value":2.265625,"string":"2.265625"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.example.mvpdemo.adapter;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\n\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\n\nimport com.bumptech.glide.Glide;\nimport com.example.mvpdemo.R;\nimport com.example.mvpdemo.bean.TitleData;\n\n\n\npublic class NewsRecycleViewAdapter extends RecyclerView.Adapter {\n private Context mContext;\n private TitleData titleData;\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.adp_recycler_news,parent,false);\n ViewHolder holder=new ViewHolder(view);\n return holder;\n }\n\n public NewsRecycleViewAdapter(Context mContext, TitleData data) {\n this.mContext = mContext;\n this.titleData = data;\n }\n\n @Override\n public void onBindViewHolder(@NonNull ViewHolder holder, int position) {\n Glide.with(mContext)\n .load(titleData.getResult().getData().get(position).getThumbnail_pic_s())\n .into(holder.imageView);\n holder.tv_title.setText(titleData.getResult().getData().get(position).getTitle());\n holder.tv_author.setText(titleData.getResult().getData().get(position).getAuthor_name());\n holder.tv_category.setText(titleData.getResult().getData().get(position).getCategory());\n holder.tv_date.setText(titleData.getResult().getData().get(position).getDate());\n\n }\n\n @Override\n public int getItemCount() {\n return titleData.getResult().getData().size();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n private ImageView imageView;\n private TextView tv_title;\n private TextView tv_author;\n private TextView tv_date;\n private TextView tv_category;\n public ViewHolder(@NonNull View itemView) {\n super(itemView);\n imageView=itemView.findViewById(R.id.dap_news_image);\n tv_title=itemView.findViewById(R.id.adp_news_title);\n tv_author=itemView.findViewById(R.id.adp_news_author);\n tv_date=itemView.findViewById(R.id.adp_news_date);\n tv_category=itemView.findViewById(R.id.adp_news_category);\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1393,"cells":{"blob_id":{"kind":"string","value":"26550f4d1d6f79ebf8d45d01ccc549b9963f9d81"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"gitter-badger/decksy"},"path":{"kind":"string","value":"/src/main/java/com/decksy/controller/DeckController.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1478,"string":"1,478"},"score":{"kind":"number","value":2.328125,"string":"2.328125"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package com.decksy.controller;\n\nimport com.decksy.model.Deck;\nimport com.decksy.service.DeckService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.validation.BindingResult;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.servlet.mvc.support.RedirectAttributes;\n\nimport javax.validation.Valid;\nimport java.util.Optional;\n\n@Controller\n@RequestMapping(\"/deck\")\npublic class DeckController {\n\n @Autowired private DeckService deckService;\n\n @GetMapping(value = \"/\")\n public String index(Model model) {\n model.addAttribute(\"deck\", new Deck());\n return \"deck/index\";\n }\n\n @GetMapping(value = \"/{id}\")\n public String show(@PathVariable long id, Model model) {\n Optional deck = deckService.findById(id);\n if (!deck.isPresent()) {\n return \"redirect:/deck/\";\n }\n\n model.addAttribute(\"deck\", deck.get());\n return \"deck/deck\";\n }\n\n @PostMapping(value = \"/\")\n public String create(@Valid Deck deck, BindingResult result) {\n if (result.hasErrors()) {\n return \"deck/index\";\n }\n\n return \"redirect:/deck/\" + deckService.save(deck).getId();\n }\n\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1394,"cells":{"blob_id":{"kind":"string","value":"858e6492504638c7753f338c501fe2807f5eec8f"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"shwetha4praneeth/JavaOld"},"path":{"kind":"string","value":"/src/test/java/javabasics/Sample12.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":382,"string":"382"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package javabasics;\r\n\r\npublic class Sample12 implements Sample11\r\n{\r\n\tpublic int add(int x, int y)\r\n\t{\r\n\t\tint z;\r\n\t\tz=x+y;\r\n\t\treturn z;\r\n\t}\r\n\t\r\n\tpublic int subtract(int x, int y)\r\n\t{\r\n\t\tint z;\r\n\t\tz=x-y;\r\n\t\treturn z;\r\n\t}\r\n\t\r\n\tpublic int multiply(int x, int y)\r\n\t{\r\n\t\tint z;\r\n\t\tz=x*y;\r\n\t\treturn z;\r\n\t}\r\n\t\r\n\tpublic int divide(int x, int y)\r\n\t{\r\n\t\tint z;\r\n\t\tz=x/y;\r\n\t\treturn z;\r\n\t}\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1395,"cells":{"blob_id":{"kind":"string","value":"6df7a16808c36b77ebcff95216d2e476710f3b3a"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"proyecto-adalid/adalid"},"path":{"kind":"string","value":"/source/adalid-alfa/src/main/java/adalid/core/annotations/OperationClass.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7418,"string":"7,418"},"score":{"kind":"number","value":2.40625,"string":"2.40625"},"int_score":{"kind":"number","value":2,"string":"2"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/*\r\n * Copyright 2017 Jorge Campins y David Uzcategui\r\n *\r\n * Este archivo forma parte de Adalid.\r\n *\r\n * Adalid es software libre; usted puede redistribuirlo y/o modificarlo bajo los terminos de la\r\n * licencia \"GNU General Public License\" publicada por la Fundacion \"Free Software Foundation\".\r\n * Adalid se distribuye con la esperanza de que pueda ser util, pero SIN NINGUNA GARANTIA; sin\r\n * siquiera las garantias implicitas de COMERCIALIZACION e IDONEIDAD PARA UN PROPOSITO PARTICULAR.\r\n *\r\n * Para mas detalles vea la licencia \"GNU General Public License\" en http://www.gnu.org/licenses\r\n */\r\npackage adalid.core.annotations;\r\n\r\nimport adalid.core.enums.*;\r\nimport java.lang.annotation.ElementType;\r\nimport java.lang.annotation.Retention;\r\nimport java.lang.annotation.RetentionPolicy;\r\nimport java.lang.annotation.Target;\r\n\r\n/**\r\n * La anotación OperationClass se utiliza para establecer atributos básicos de la operación. Es válida para cualquier clase de operación de negocio.\r\n *\r\n * @author Jorge Campins\r\n */\r\n@Retention(RetentionPolicy.RUNTIME)\r\n@Target(ElementType.TYPE)\r\npublic @interface OperationClass {\r\n\r\n /**\r\n * confirmation indica si las vistas (páginas) de procesamiento deben solicitar, o no, confirmación al ejecutar la operación. Su valor es uno de\r\n * los elementos de la enumeración Kleenean. Seleccione TRUE para solicitar confirmación; en caso contrario, seleccione FALSE. Alternativamente,\r\n * omita el elemento o seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es el\r\n * establecido con el método setBusinessOperationConfirmationRequired del proyecto maestro.\r\n *\r\n * @return confirmation\r\n */\r\n Kleenean confirmation() default Kleenean.UNSPECIFIED; // FALSE\r\n\r\n /**\r\n * access especifica el tipo de control de acceso de la operación. Su valor es uno de los elementos de la enumeración OperationAccess. Seleccione\r\n * PRIVATE, PUBLIC, PROTECTED o RESTRICTED si la operación es de acceso privado, público, protegido o restringido, respectivamente.\r\n * Alternativamente, omita el elemento o seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del\r\n * atributo es RESTRICTED. Las operaciones con acceso privado no pueden ser ejecutadas directamente por los usuarios del sistema. Son ejecutadas\r\n * solo por otras operaciones, a través de la Interfaz de Programación (API). Las operaciones con acceso público, protegido y restringido si\r\n * pueden ser ejecutadas directamente por los usuarios del sistema, a través de la Interfaz de Usuario (UI). Las operaciones con acceso público\r\n * pueden ser ejecutadas por todos los usuarios del sistema, aun cuando no tengan autorización explícita para ello. Las operaciones con acceso\r\n * protegido pueden ser ejecutadas por usuarios designados como súper-usuario o por usuarios explícitamente autorizados. Al igual que las\r\n * operaciones con acceso protegido, las operaciones con acceso restringido pueden ser ejecutadas por usuarios designados como súper-usuario o por\r\n * usuarios explícitamente autorizados. Además, a diferencia de las operaciones con acceso protegido, las operaciones personalizables con acceso\r\n * restringido, también pueden ser ejecutadas por usuarios que no tengan autorización explícita, pero solo sobre las instancias de la entidad que\r\n * sean propiedad del usuario.\r\n *\r\n * @return access\r\n */\r\n OperationAccess access() default OperationAccess.RESTRICTED;\r\n\r\n /**\r\n * asynchronous indica si la operación se debe ejecutar de manera síncrona o asíncrona. Su valor es uno de los elementos de la enumeración\r\n * Kleenean. Seleccione TRUE si se debe ejecutar de manera asíncrona; en caso contrario, seleccione FALSE. Alternativamente, omita el elemento o\r\n * seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es FALSE.\r\n *

\r\n * Este elemento no es relevante si la operación es un proceso de exportación (extensión de ExportOperation), un informe (extensión de\r\n * ReportOperation), o un procedimiento almacenado en la base de datos (extensión de ProcedureOperation) de tipo VOID, ya que tales operaciones\r\n * siempre se deben ejecutar de manera asíncrona.\r\n *\r\n * @return asynchronous\r\n */\r\n Kleenean asynchronous() default Kleenean.UNSPECIFIED; // FALSE\r\n\r\n /**\r\n * shell indica si la operación se debe ejecutar utilizando un proceso nativo del sistema operativo, cuando el uso de procesos nativos esté\r\n * permitido para la clase de operación (vea los métodos setExporterShellEnabled, setReporterShellEnabled y setSqlAgentShellEnabled). Solo aplica\r\n * si la operación es un proceso de exportación (extensión de ExportOperation), un informe (extensión de ReportOperation), u otra clase de\r\n * operación de negocio (extensión de ProcessOperation o ProcedureOperation) que esté implementada mediante una función o procedimiento almacenado\r\n * en la base de datos y que se ejecute asincrónicamente. Su valor es uno de los elementos de la enumeración Kleenean. Seleccione TRUE para\r\n * utilizar un proceso nativo; seleccione FALSE para utilizar un subproceso del servidor de aplicaciones. Alternativamente, omita el elemento o\r\n * seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es TRUE, si la operación es un\r\n * proceso de exportación, un informe o un procedimiento almacenado en la base de datos de tipo VOID; en los demás casos, FALSE.\r\n *

\r\n * Este elemento no es relevante si la operación es un procedimiento almacenado en la base de datos de tipo VOID, ya que tales operaciones siempre\r\n * se deben ejecutar utilizando un proceso nativo.\r\n *\r\n * @return shell\r\n */\r\n Kleenean shell() default Kleenean.UNSPECIFIED;\r\n\r\n /**\r\n * complex indica si la operación es, o no, una operación compleja. Su valor es uno de los elementos de la enumeración Kleenean. Seleccione TRUE\r\n * si la operación es compleja; en caso contrario, seleccione FALSE. Alternativamente, omita el elemento o seleccione UNSPECIFIED para utilizar el\r\n * valor predeterminado del atributo. El valor predeterminado del atributo es FALSE.\r\n *\r\n * @return complex\r\n */\r\n Kleenean complex() default Kleenean.UNSPECIFIED; // FALSE\r\n\r\n /**\r\n * logging especifica cuando se deben registrar pistas de auditoría de la ejecución de la operación. Su valor es uno de los elementos de la\r\n * enumeración OperationLogging. Seleccione SUCCESS, FAILURE o BOTH si las pistas se deben registrar cuando la operación se ejecute exitosamente,\r\n * cuando se produzca un error al ejecutar la operación, o en ambos casos, respectivamente. Alternativamente, omita el elemento o seleccione\r\n * UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es SUCCESS.\r\n *

\r\n * Este elemento no es relevante si el tipo de control de acceso de la operación es PRIVATE, ya que nunca se registran pistas de auditoría para\r\n * tales operaciones.\r\n *\r\n * @return logging\r\n */\r\n OperationLogging logging() default OperationLogging.UNSPECIFIED; // SUCCESS\r\n\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1396,"cells":{"blob_id":{"kind":"string","value":"6da4c98c12b91d45eb7bf30ec99bb0451f8c3c9a"},"language":{"kind":"string","value":"Java"},"repo_name":{"kind":"string","value":"Azam-Aminuddin/bool-func-repr"},"path":{"kind":"string","value":"/src/main/java/persons/azam_ami/learning/Learning_Algo_Tower.java"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1247,"string":"1,247"},"score":{"kind":"number","value":3.078125,"string":"3.078125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package persons.azam_ami.learning;\n\nimport persons.azam_ami.knowledge.repr.NeuralNet;\n\n/**\n * Implement Algorithm Tower.\n * \n * @author azam_ami@yahoo.com\n *\n */\npublic class Learning_Algo_Tower\n{\n public static NeuralNet.Node createNewNode( NeuralNet nn )\n {\n \n int[] weights = new int[1 + nn.getVarCount()]; \n int[] inputVars = new int[ nn.getVarCount() ]; \n int outputVar = nn.getVarCount();\n \n // Weights\n for( int i=0; i SimpleAnalysisResult(PromiseDrop about, IRNode location, int code, Object... args) {\r\n\t\tsuper(about, location);\r\n\t\tmessageCode = code;\r\n\t\tthis.args = new String[args.length];\r\n\t\tfor(int i=0; i

blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
30f69f536c35ad658b8aed36053c305b8cbb6231
Java
JoaoCarlosPires/feup-lpoo
/Practical Classes/designPatterns/src/main/java/RomulanClient.java
UTF-8
205
1.828125
2
[]
no_license
public class RomulanClient extends AlienClient { @Override protected OrderingStrategy createOrderingStrategy() { ImpatientStrategy is = new ImpatientStrategy(); return is; } }
true
4a469ad90af6f550578394f31272a8bf195bec73
Java
lvwe/News
/app/src/main/java/com/example/administrator/news/activity/TopActivity.java
UTF-8
4,501
2.09375
2
[]
no_license
package com.example.administrator.news.activity; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.TextView; import com.example.administrator.news.R; import com.example.administrator.news.fragment.JokeFragment; import com.example.administrator.news.fragment.MainFragment; import com.example.administrator.news.fragment.MyFragment; import com.example.administrator.news.fragment.WeatherFragment; import java.util.ArrayList; import java.util.List; public class TopActivity extends FragmentActivity implements View.OnClickListener { private static final String TAG = "TopActivity"; private ViewPager mTopViewPager; private TextView mTvNews, mTvJoke, mTvWeather, mTvMy; private List<Fragment> mFragmentList = new ArrayList<>(); private TopViewPagerAdapter mPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_top); initTabFragmentList(); initBottomView(); mPagerAdapter = new TopViewPagerAdapter(getSupportFragmentManager(), mFragmentList); mTopViewPager.setAdapter(mPagerAdapter); mTopViewPager.setOffscreenPageLimit(4); mTopViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 0: onChangeTextViewColor(position, mTvNews, mTvJoke, mTvWeather, mTvMy); break; case 1: onChangeTextViewColor(position, mTvJoke, mTvNews, mTvWeather, mTvMy); break; case 2: onChangeTextViewColor(position, mTvWeather, mTvNews, mTvJoke, mTvMy); break; case 3: onChangeTextViewColor(position, mTvMy, mTvNews, mTvWeather, mTvJoke); break; } } @Override public void onPageScrollStateChanged(int state) { } }); } private void initTabFragmentList() { mTopViewPager = (ViewPager) findViewById(R.id.id_top_viewPager); MainFragment mf = new MainFragment(); mFragmentList.add(mf); JokeFragment jf = new JokeFragment(); mFragmentList.add(jf); WeatherFragment wf = new WeatherFragment(); mFragmentList.add(wf); MyFragment myf = new MyFragment(); mFragmentList.add(myf); } private void initBottomView() { mTvNews = (TextView) findViewById(R.id.id_tob_tab_news); mTvJoke = (TextView) findViewById(R.id.id_tob_tab_joke); mTvWeather = (TextView) findViewById(R.id.id_tob_tab_weather); mTvMy = (TextView) findViewById(R.id.id_tob_tab_my); mTvNews.setBackgroundColor(Color.parseColor("#F0E68C")); mTvNews.setOnClickListener(this); mTvJoke.setOnClickListener(this); mTvWeather.setOnClickListener(this); mTvMy.setOnClickListener(this); } public void onChangeTextViewColor(int position, TextView tv0, TextView tv1, TextView tv2, TextView tv3) { mTopViewPager.setCurrentItem(position); tv0.setBackgroundColor(Color.parseColor("#F0E68C")); tv1.setBackgroundColor(Color.WHITE); tv2.setBackgroundColor(Color.WHITE); tv3.setBackgroundColor(Color.WHITE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.id_tob_tab_news: onChangeTextViewColor(0, mTvNews, mTvJoke, mTvWeather, mTvMy); break; case R.id.id_tob_tab_joke: onChangeTextViewColor(1, mTvJoke, mTvNews, mTvWeather, mTvMy); break; case R.id.id_tob_tab_weather: onChangeTextViewColor(2, mTvWeather, mTvNews, mTvJoke, mTvMy); break; case R.id.id_tob_tab_my: onChangeTextViewColor(3, mTvMy, mTvNews, mTvWeather, mTvJoke); break; } } }
true
661688d522866c8b6a827479109f37d6b0feaf5b
Java
ZHENGZX123/PCCramera
/Sample/Android/src/com/example/samplesep2p_appsdk/PlayBackActivity.java
UTF-8
7,201
2.0625
2
[]
no_license
package com.example.samplesep2p_appsdk; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.p2p.MSG_GET_REMOTE_REC_DAY_BY_MONTH_RESP; import com.p2p.MSG_GET_REMOTE_REC_FILE_BY_DAY_RESP; import com.p2p.MSG_START_PLAY_REC_FILE_RESP; import com.p2p.MSG_STOP_PLAY_REC_FILE_RESP; import com.p2p.REC_FILE_INFO; import com.p2p.SEP2P_Define; public class PlayBackActivity extends Activity implements IAVListener{ private EditText recDayEdit,recDateEdit,recFilesEdit; private Button RecDayBtn,RecordFilesBtn,PlaybackBtn; private Spinner recordTypeSpinner; private String strRecDay,strRecDate,strRecFiles; private String m_strFilePlayback=null; private boolean bStartPlayback=false; String [] record_spinner_list = null; ArrayAdapter<String> spinnerAdapter = null; private int PLAY_BACK_TYPE = SEP2P_Define.RECORD_TYPE_PLAN; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playback); init(); MainActivity.m_arrObjCam[0].regAVListener(PlayBackActivity.this); } public void init(){ record_spinner_list = new String[] {getResources().getString(R.string.plan_record), getResources().getString(R.string.alarm_record), getResources().getString(R.string.plan_alarm_record)}; recDayEdit = (EditText)findViewById(R.id.recorddayedit); recDateEdit = (EditText)findViewById(R.id.recorddateedit); recFilesEdit = (EditText)findViewById(R.id.recordfilesedit); RecDayBtn = (Button)findViewById(R.id.getrecdaybtn); RecordFilesBtn = (Button)findViewById(R.id.getrecordfilesbtn); PlaybackBtn = (Button)findViewById(R.id.startplaybackbtn); recordTypeSpinner = (Spinner)findViewById(R.id.recordtypespinner); spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,record_spinner_list); recordTypeSpinner.setAdapter(spinnerAdapter); recordTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) { if(arg2 == 0) PLAY_BACK_TYPE = SEP2P_Define.RECORD_TYPE_PLAN; if(arg2 == 1) PLAY_BACK_TYPE = SEP2P_Define.RECORD_TYPE_ALARM; if(arg2 == 2) PLAY_BACK_TYPE = SEP2P_Define.RECORD_TYPE_ALL; } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } public void onClick (View v){ switch(v.getId()){ /** * 返回 */ case R.id.back: finish(); break; /** * 通过年月获得下面有哪些天有录像文件 */ case R.id.getrecdaybtn: strRecDay = recDayEdit.getText().toString(); System.out.println("PlaybackActivity.java] request:"+strRecDay); if(!strRecDay.equals("")){ MainActivity.m_arrObjCam[0].getRemote_rec_day_by_yyyymm(Integer.parseInt(strRecDay),3); } break; /** * 通过年月日及录象类型获得所有的录像文件 */ case R.id.getrecordfilesbtn: strRecDate = recDateEdit.getText().toString(); System.out.println("PlaybackActivity.java] request: record files on "+strRecDate+",recordType="+PLAY_BACK_TYPE); if(!strRecDate.equals("")){ MainActivity.m_arrObjCam[0].getRemote_rec_file_by_yyyymmdd(Integer.parseInt(strRecDate),PLAY_BACK_TYPE, 0,0); } break; /** * 开始启动与停止录像回放 */ case R.id.startplaybackbtn: strRecFiles = recFilesEdit.getText().toString(); if(bStartPlayback){ bStartPlayback = false; PlaybackBtn.setText(getResources().getString(R.string.start_rec_play)); if(!strRecFiles.equals("")){ MainActivity.m_arrObjCam[0].stopPlayback(strRecFiles); } }else{ if(m_strFilePlayback==null) break; bStartPlayback=true; PlaybackBtn.setText(getResources().getString(R.string.stop_rec_play)); if(!strRecFiles.equals("")){ MainActivity.m_arrObjCam[0].startPlayback(0, 0, strRecFiles); } } break; } } Handler MsgPlaybackHandler = new Handler() { @SuppressLint("HandlerLeak") public void handleMessage(Message msg) { switch (msg.what) { case SEP2P_Define.SEP2P_MSG_GET_REMOTE_REC_DAY_BY_MONTH_RESP:{ if(msg.obj==null) break; byte[] byts=(byte[])msg.obj; MSG_GET_REMOTE_REC_DAY_BY_MONTH_RESP day_by_month = new MSG_GET_REMOTE_REC_DAY_BY_MONTH_RESP(byts); System.out.println("PlaybackActivity.java] response:"+day_by_month.getnChDay()+" of "+day_by_month.getnYearMon()); } break; case SEP2P_Define.SEP2P_MSG_GET_REMOTE_REC_FILE_BY_DAY_RESP:{ if(msg.obj==null) break; byte[] byts=(byte[])msg.obj; MSG_GET_REMOTE_REC_FILE_BY_DAY_RESP stResp=new MSG_GET_REMOTE_REC_FILE_BY_DAY_RESP(byts); stResp.getnResult(); stResp.getnFileTotalNum(); System.out.println("PlaybackActivity.java] response: result="+stResp.getnResult()+",TotalNum="+stResp.getnFileTotalNum()+ ", range of no=["+stResp.getnBeginNoOfThisTime()+","+stResp.getnEndNoOfThisTime()+"]"); REC_FILE_INFO stRecFileInfo=null; String str=null; int i=0, nFileNumOfThisTime=stResp.getnEndNoOfThisTime()-stResp.getnBeginNoOfThisTime()+1; for(i=0; i<nFileNumOfThisTime; i++){ stRecFileInfo=new REC_FILE_INFO(byts, MSG_GET_REMOTE_REC_FILE_BY_DAY_RESP.MY_LEN+i*REC_FILE_INFO.MY_LEN); str=String.format(" %d, type=%d %dsec %dKB, %s", i, stRecFileInfo.getchnRecType(), stRecFileInfo.getnTimeLen_sec(), stRecFileInfo.getnFileSize_KB(), stRecFileInfo.getchFilePath()); System.out.println(str); if(i==0) m_strFilePlayback=stRecFileInfo.getchFilePath();//for test } recFilesEdit.setText(m_strFilePlayback); }break; case SEP2P_Define.SEP2P_MSG_START_PLAY_REC_FILE_RESP:{ if(msg.obj==null) break; byte[] byts=(byte[])msg.obj; String str=null; MSG_START_PLAY_REC_FILE_RESP stResp=new MSG_START_PLAY_REC_FILE_RESP(byts); str=String.format("result=%d aparam=%d file=%s", stResp.getnResult(), stResp.getnAudioParam(), stResp.getchFilePath()); System.out.println("StartPlayback]"+str); }break; case SEP2P_Define.SEP2P_MSG_STOP_PLAY_REC_FILE_RESP:{ if(msg.obj==null) break; byte[] byts=(byte[])msg.obj; String str=null; MSG_STOP_PLAY_REC_FILE_RESP stResp = new MSG_STOP_PLAY_REC_FILE_RESP(byts); System.out.println("StopPlayback]"+ stResp.getnResult()); } break; default:; } } }; @Override public void updateFrameInfo(Object obj, int nWidth, int nHeigh) { } @Override public void updateBmpFrame(Object obj, byte[] rawVideoData, Bitmap bmp) { } @Override public void updateMsg(Object obj, int nMsgType, byte[] pMsg, int nMsgSize,int pUserData) { Message msg = MsgPlaybackHandler.obtainMessage(); msg.what= nMsgType; msg.obj = pMsg; MsgPlaybackHandler.sendMessage(msg); } }
true
667dc3905f8c44af2e481649dfaaa90eadc68fca
Java
cha63506/CompSecurity
/photo-grid-source/src/com/mopub/network/PlayServicesUrlRewriter.java
UTF-8
1,761
1.84375
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.mopub.network; import android.content.Context; import android.net.Uri; import com.mopub.common.GpsHelper; public class PlayServicesUrlRewriter implements com.mopub.volley.toolbox.HurlStack.UrlRewriter { public static final String DO_NOT_TRACK_TEMPLATE = "mp_tmpl_do_not_track"; public static final String UDID_TEMPLATE = "mp_tmpl_advertising_id"; private final String a; private final Context b; public PlayServicesUrlRewriter(String s, Context context) { a = s; b = context.getApplicationContext(); } public String rewriteUrl(String s) { Object obj1; if (!s.contains("mp_tmpl_advertising_id") && !s.contains("mp_tmpl_do_not_track")) { return s; } obj1 = new com.mopub.common.GpsHelper.AdvertisingInfo(a, false); if (!GpsHelper.isPlayServicesAvailable(b)) goto _L2; else goto _L1 _L1: Object obj = GpsHelper.fetchAdvertisingInfoSync(b); if (obj == null) goto _L2; else goto _L3 _L3: obj1 = "ifa:"; _L5: obj1 = s.replace("mp_tmpl_advertising_id", Uri.encode((new StringBuilder()).append(((String) (obj1))).append(((com.mopub.common.GpsHelper.AdvertisingInfo) (obj)).advertisingId).toString())); if (((com.mopub.common.GpsHelper.AdvertisingInfo) (obj)).limitAdTracking) { s = "1"; } else { s = "0"; } return ((String) (obj1)).replace("mp_tmpl_do_not_track", s); _L2: obj = obj1; obj1 = ""; if (true) goto _L5; else goto _L4 _L4: } }
true
3a0b4fe0874f3158d2de1bf163756fc1aa9efec3
Java
vshari/Ved
/E-Commerce/AMPLIFY/Version 2/amplify/src/main/java/com/niit/controller/ProductController.java
UTF-8
4,715
2.4375
2
[]
no_license
package com.niit.controller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.niit.model.Categories; import com.niit.model.Product; import com.niit.service.ProductService; @Controller public class ProductController { @Autowired ProductService productService; // setter + getter public ProductService getProductService() { return productService; } public void setProductService(ProductService productService) { this.productService = productService; } // browse all products including Angular JS @RequestMapping(value = "/getProductsList") public @ResponseBody List<Product> getProductsListInJSON() { return productService.getAllProducts(); } // To view the angularJS productList @RequestMapping("/productList") public String getProducts() { return "productList"; } /* * @RequestMapping("/productListAngular") public String getProducts() { * return "productListAngular"; } */ // displays all the products in the table @RequestMapping(value = "/getallproducts") public ModelAndView getAllProducts() { List<Product> allproducts = productService.getAllProducts(); ModelAndView mv = new ModelAndView("productList", "allproducts", allproducts); return mv; } // view product details if productId is clicked @RequestMapping(value = "/getProductsByProductId/{productId}") public ModelAndView getProductsByProductId(@PathVariable(value = "productId") int productId) { Product product = productService.getProductByProductId(productId); return new ModelAndView("productPage", "product", product); } // to delete a product @RequestMapping(value = "/admin/delete/{productId}") public String deleteProduct(@PathVariable(value = "productId") int productId) { productService.deleteProduct(productId); Path paths = Paths .get("F:\\Codes\\Eclipse\\Workspace_DT7_5\\amplify\\src\\main\\webapp\\WEB-INF\\resources\\images\\" + productId + ".png"); if (Files.exists(paths)) { try { Files.delete(paths); } catch (IOException e) { } } return "redirect:/getallproducts"; } // ADD PRODUCT // method 1 for add product @RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.GET) public String getProductForm(Model model) { Product product = new Product(); Categories categories = new Categories(); categories.setcId(1); product.setCategory(categories); model.addAttribute("productFormObj", product); return "productForm"; } // method 2 for addproduct @RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.POST) public String addProduct(@Valid @ModelAttribute(value = "productFormObj") Product product, BindingResult result) { if (result.hasErrors()) { return "productForm"; } else { productService.addProduct(product); MultipartFile productImage = product.getProductImage(); if (productImage != null && !productImage.isEmpty()) { Path paths = (Path) Paths .get("F:\\Codes\\Eclipse\\Workspace_DT7_5\\amplify\\src\\main\\webapp\\WEB-INF\\resources\\images\\" + product.getProductId() + ".png"); try { productImage.transferTo(new File(paths.toString())); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return "redirect:/getallproducts"; } } // EDIT PRODUCT // method 1 for edit product @RequestMapping("/admin/product/editProduct/{productId}") public ModelAndView getEditForm(@PathVariable(value = "productId") int productId) { Product product = this.productService.getProductByProductId(productId); return new ModelAndView("editProductForm", "editProductObj", product); } // method 2 for edit product @RequestMapping(value = "/admin/product/editProduct", method = RequestMethod.POST) public String editProduct(@ModelAttribute(value = "editProductObj") Product product) { productService.editProduct(product); return "redirect:/getallproducts"; } }
true
c235194679f85fdfc2c99d0891db7ee1a1f7aa24
Java
hldni/ny-cloud
/admin/src/main/java/com/nycloud/common/utils/ToStringDateSerializer.java
UTF-8
861
2.421875
2
[]
no_license
package com.nycloud.common.utils; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * @description: 毫秒转换成年月日时分秒字符串 * @author: super.wu * @date: Created in 2018/6/12 0012 * @modified By: * @version: 1.0 **/ public class ToStringDateSerializer extends JsonSerializer<Long> { @Override public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(aLong)).toString()); } }
true
2f72673a7a7955f65376f0206cf61c4e4d8054e0
Java
code-zhucj/rabbit-core
/src/main/java/core/view/ViewHandler.java
UTF-8
169
1.96875
2
[]
no_license
package core.view; public interface ViewHandler { void process(); default void throwable(Throwable throwable) { throwable.printStackTrace(); } }
true
555244b868d521eb60877df560f2b3e59c43bd16
Java
DrThundercat/SpanningTree
/src/Edge.java
UTF-8
656
3.28125
3
[]
no_license
import java.util.Random; public class Edge { Random rand = new Random(); int weight; Point source2,target2; boolean visited = false; public Edge(Point source2,Point target2,int weight){ this.source2 = source2; this.target2 = target2; this.weight = weight; } public Point getSource(){ return source2; } public Point getTarget(){ return target2; } public boolean visitedEdge(){ return visited; } public int getWeight(){ return weight; } public boolean getVisited(){ return visited; } public String toString(){ return "source point: "+ source2.title +" to target: " +target2.title+" distance: "+weight; } }
true
fec41373fe3bddce33bf4cebfe7689225aaebdb0
Java
ZhuoyuWei/KBCExperimentPlaform
/src/wzy/model/randwk/RandomExactly.java
UTF-8
3,901
2.234375
2
[]
no_license
package wzy.model.randwk; import java.util.ArrayList; import java.util.List; import java.util.Random; import wzy.meta.FormulaTreeNode; import wzy.meta.RPath; import wzy.model.RandomWalkModel; public class RandomExactly extends RandomWalkModel { //public int max_round=10; public double restart_rate=0.3; public double back_rate=0.5; public Random rand=new Random(); double[] fcounts; int t; @Override public void InitGradients() { super.InitGradients(); } @Override public void OneBranchTraining(int[][] train_triplets,int sindex,int eindex) { super.OneBranchTraining(train_triplets, sindex, eindex); } /* @Override public double[] RandomWalk(int[] triplet) { //int[] fcounts=new int[pathWeights[triplet[1]].length]; fcounts=super.RandomWalk(triplet); int state=triplet[0]; FormulaTreeNode ft_node=ff[triplet[1]].root; List<int[]> path_record=new ArrayList<int[]>(); for(int i=0;i<max_round;i++) { //restart if(rand.nextDouble()<restart_rate) { state=triplet[0]; ft_node=ff[triplet[1]].root; path_record=new ArrayList<int[]>(); } //back if(ft_node.next_map==null||(path_record.size()>2&&rand.nextDouble()<back_rate)) { if(path_record.size()<2) { //restart state=triplet[0]; ft_node=ff[triplet[1]].root; path_record=new ArrayList<int[]>(); continue; } state=path_record.get(path_record.size()-2)[1]; ft_node=ft_node.parent; path_record.remove(path_record.size()-1); } List<Integer> indexList=new ArrayList<Integer>(); for(int j=0;j<triplet_graph[state].length;j++) { if(ft_node.next_map[triplet_graph[state][j][0]]!=null) { indexList.add(j); } } if(indexList.size()<=0||ft_node.next_map==null) { //restart state=triplet[0]; ft_node=ff[triplet[1]].root; path_record=new ArrayList<int[]>(); continue; } //random exactly int rand_ind=Math.abs(rand.nextInt())%indexList.size(); while(rand_ind<0) rand_ind=Math.abs(rand.nextInt())%indexList.size(); //forward //System.out.println(triplet_graph[state][indexList.get(rand_ind)][0]); ft_node=ft_node.next_map[triplet_graph[state][indexList.get(rand_ind)][0]]; path_record.add(triplet_graph[state][indexList.get(rand_ind)]); state=triplet_graph[state][indexList.get(rand_ind)][1]; if(ft_node.leaf) { fcounts[ft_node.formula]++; } } if(nocount) super.NoCount(fcounts); return fcounts; } */ @Override public double[] RandomWalk(int[] triplet,boolean training) { fcounts=super.RandomWalk(triplet,training); t=triplet[2]; //List<int[]> path_record=new ArrayList<int[]>(); for(int r=0;r<max_round;r++) { int state=triplet[0]; FormulaTreeNode ft_node=ff[triplet[1]].root; DFS(state,ft_node); //int t=CheckRandomRes(fcounts); //System.err.println(r+" "+t); } return fcounts; } protected void DFS(int s,FormulaTreeNode fnode) { List<Integer> stateList=new ArrayList<Integer>(); List<FormulaTreeNode> formulaList=new ArrayList<FormulaTreeNode>(); for(int j=0;j<triplet_graph[s].length;j++) { if(fnode.next_map[triplet_graph[s][j][0]]!=null) { if(fnode.next_map[triplet_graph[s][j][0]].leaf&&triplet_graph[s][j][1]==t) { fcounts[fnode.next_map[triplet_graph[s][j][0]].formula]++; return; } else if(fnode.next_map[triplet_graph[s][j][0]].next_map!=null) { //DFS(triplet_graph[s][j][1],fnode.next_map[triplet_graph[s][j][0]]); stateList.add(triplet_graph[s][j][1]); formulaList.add(fnode.next_map[triplet_graph[s][j][0]]); } } } if(stateList.size()>0) { int index=rand.nextInt(stateList.size()); DFS(stateList.get(index),formulaList.get(index)); } } @Override public double Logistic_F_wx(int r,double[] fcounts) { return super.Logistic_F_wx(r, fcounts); } }
true
d694e0aa3692c4522a3f5d597ccd242dc84ad1e8
Java
joesilveira/Valkyrien-Skies
/src/main/java/org/valkyrienskies/mod/common/physmanagement/relocation/MoveBlocks.java
UTF-8
5,312
2.40625
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.valkyrienskies.mod.common.physmanagement.relocation; import java.util.Optional; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import org.valkyrienskies.addon.control.nodenetwork.IVSNodeProvider; import org.valkyrienskies.mod.common.coordinates.CoordinateSpaceType; import org.valkyrienskies.mod.common.coordinates.ShipTransform; import org.valkyrienskies.mod.common.physics.management.PhysicsObject; public class MoveBlocks { /** * @param world * @param oldPos * @param newPos * @param physicsObjectOptional Used when we're using this to copy from world to physics object; * should be empty when other way around. */ public static void copyBlockToPos(World world, BlockPos oldPos, BlockPos newPos, Optional<PhysicsObject> physicsObjectOptional) { // To avoid any updates crap, just edit the chunk data array directly. // These look switched, but trust me they aren't IBlockState oldState = world.getBlockState(newPos); IBlockState newState = world.getBlockState(oldPos); // A hacky way to set the block state within the chunk while avoiding any block updates. Chunk chunkToSet = world.getChunk(newPos); int storageIndex = newPos.getY() >> 4; // Check that we're placing the block in a valid position if (storageIndex < 0 || storageIndex >= chunkToSet.storageArrays.length) { // Invalid position, abort! return; } if (chunkToSet.storageArrays[storageIndex] == Chunk.NULL_BLOCK_STORAGE) { chunkToSet.storageArrays[storageIndex] = new ExtendedBlockStorage(storageIndex << 4, true); } chunkToSet.storageArrays[storageIndex] .set(newPos.getX() & 15, newPos.getY() & 15, newPos.getZ() & 15, newState); // Only want to send the update to clients and nothing else, so we use flag 2. world.notifyBlockUpdate(newPos, oldState, newState, 2); // Pretty messy to put this here but it works. Basically the ship keeps track of which of its chunks are // actually being used for performance reasons. if (physicsObjectOptional.isPresent()) { int minChunkX = physicsObjectOptional.get() .getOwnedChunks() .minX(); int minChunkZ = physicsObjectOptional.get() .getOwnedChunks() .minZ(); } // Now that we've copied the block to the position, copy the tile entity copyTileEntityToPos(world, oldPos, newPos, physicsObjectOptional); } private static void copyTileEntityToPos(World world, BlockPos oldPos, BlockPos newPos, Optional<PhysicsObject> physicsObjectOptional) { // Make a copy of the tile entity at oldPos to newPos TileEntity worldTile = world.getTileEntity(oldPos); if (worldTile != null) { NBTTagCompound tileEntNBT = new NBTTagCompound(); TileEntity newInstance; if (worldTile instanceof IRelocationAwareTile) { CoordinateSpaceType coordinateSpaceType = physicsObjectOptional.isPresent() ? CoordinateSpaceType.SUBSPACE_COORDINATES : CoordinateSpaceType.GLOBAL_COORDINATES; ShipTransform transform = new ShipTransform(newPos.getX() - oldPos.getX(), newPos.getY() - oldPos.getY(), newPos.getZ() - oldPos.getZ()); newInstance = ((IRelocationAwareTile) worldTile) .createRelocatedTile(newPos, transform, coordinateSpaceType); } else { tileEntNBT = worldTile.writeToNBT(tileEntNBT); // Change the block position to be inside of the Ship tileEntNBT.setInteger("x", newPos.getX()); tileEntNBT.setInteger("y", newPos.getY()); tileEntNBT.setInteger("z", newPos.getZ()); newInstance = TileEntity.create(world, tileEntNBT); } // Order the IVSNodeProvider to move by the given offset. if (newInstance instanceof IVSNodeProvider) { ((IVSNodeProvider) newInstance).shiftInternalData(newPos.subtract(oldPos)); if (physicsObjectOptional.isPresent()) { ((IVSNodeProvider) newInstance) .getNode() .setParentPhysicsObject(physicsObjectOptional.get()); } else { ((IVSNodeProvider) newInstance) .getNode() .setParentPhysicsObject(null); } } try { world.setTileEntity(newPos, newInstance); physicsObjectOptional .ifPresent(physicsObject -> physicsObject.onSetTileEntity(newPos, newInstance)); newInstance.markDirty(); } catch (Exception e) { e.printStackTrace(); } } } }
true
361d01e4c4fd41cab9a38ce473125669b7f41474
Java
praveenkumar41/HelloWorld
/app/src/main/java/com/example/project2/Friendrequest_Adapter.java
UTF-8
30,421
1.703125
2
[]
no_license
package com.example.project2; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.project2.Notification.Client; import com.example.project2.Notification.MyResponse; import com.example.project2.Notification1.Data1; import com.example.project2.Notification1.Sender1; import com.example.project2.Notification1.Token1; import com.example.project2.Notification2.APIService2; import com.example.project2.Notification2.Data2; import com.example.project2.Notification2.Sender2; import com.example.project2.Notification2.Token2; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton; import de.hdodenhof.circleimageview.CircleImageView; import retrofit2.Call; import retrofit2.Response; class FriendRequest_Adapter extends RecyclerView.Adapter<FriendRequest_Adapter.ViewHolder> { private Context mcontext; private List<Friends_request> mfriendrequest; DatabaseReference reference; String userid; DatabaseReference mref,mref1; DatabaseReference mref2,myrefry,ref; FirebaseUser firebaseUser; String username; String current; String currentstate; int count; APIService2 api2; boolean notify=false; public FriendRequest_Adapter(Context mcontext, List<Friends_request> mfriendrequest, String userid1, int count1) { this.mcontext=mcontext; this.mfriendrequest= mfriendrequest; // this.userid=userid1; this.count=count1; } @NonNull @Override public FriendRequest_Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mcontext).inflate(R.layout.request_cardlayout, parent, false); return new FriendRequest_Adapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { mref = FirebaseDatabase.getInstance().getReference().child("Friend_Request"); mref1 = FirebaseDatabase.getInstance().getReference().child("Friends"); mref.keepSynced(true); mref1.keepSynced(true); reference= FirebaseDatabase.getInstance().getReference("users").child(mfriendrequest.get(position).getSender()); reference.keepSynced(true); assert userid != null; ref= FirebaseDatabase.getInstance().getReference().child("Notifications"); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); final String user_id1 = mfriendrequest.get(position).getSender(); final String user_id = mfriendrequest.get(position).getId(); final Friends_request friends_request = mfriendrequest.get(position); mref2 = FirebaseDatabase.getInstance().getReference("users");//.child(user_id); mref2.child(user_id1).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String name = dataSnapshot.child("USERNAME").getValue(String.class); String image = dataSnapshot.child("IMAGEURL").getValue(String.class); holder.un.setText(name); holder.setUserimage(image, mcontext); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); api2= Client.getClient("https://fcm.googleapis.com/").create(APIService2.class); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mcontext, Alluserprofile.class); intent.putExtra("userid", user_id1); mcontext.startActivity(intent); } }); String countq = Integer.toString(count); DatabaseReference countref = FirebaseDatabase.getInstance().getReference().child("count_of_request").child(firebaseUser.getUid()); countref.child("count").setValue(countq).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { } }); String userid=friends_request.getId(); DatabaseReference mm = FirebaseDatabase.getInstance().getReference("users").child(user_id1); mm.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { username = dataSnapshot.child("USERNAME").getValue(String.class); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); mref.child(friends_request.getSender()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(friends_request.getReciever())) { String reqtype = dataSnapshot.child(friends_request.getReciever()).child("requested_type").getValue(String.class); if ("Recieved".equals(reqtype)) { currentstate = "reqrecieved"; current=currentstate; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); currentstate="reqrecieved"; holder.addrequestedfriend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { notify=true; if ("reqrecieved".equals(currentstate)) { holder.bar.setVisibility(View.VISIBLE); Calendar calendar = Calendar.getInstance(); final SimpleDateFormat currentdate1 = new SimpleDateFormat("MMM dd, YYYY"); final String currentdate = currentdate1.format(calendar.getTime()); final String sender = friends_request.getSender(); final String reciever = friends_request.getId(); mref1.child(sender).child(reciever).child("firstrequested").setValue(sender).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(sender).child(reciever).child("friendssince").setValue(currentdate).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(sender).child(reciever).child("accepted").setValue(reciever).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(sender).child(reciever).child("id").setValue(reciever).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(sender).child(reciever).child("acceptedname").setValue(username).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(sender).child(reciever).child("toggle").setValue("").addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("firstrequested").setValue(sender).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("friendssince").setValue(currentdate).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("accepted").setValue(reciever).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("id").setValue(sender).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("acceptedname").setValue(username).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref1.child(reciever).child(sender).child("toggle").setValue("").addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref.child(sender).child(reciever).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref.child(reciever).child(sender).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { DatabaseReference mref6 = FirebaseDatabase.getInstance().getReference().child("Typingstatus").child(sender).child(reciever); final HashMap typingstatus = new HashMap(); typingstatus.put("usertyping", "false"); mref6.setValue(typingstatus).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); mref6 = FirebaseDatabase.getInstance().getReference().child("Typingstatus").child(reciever).child(sender); final HashMap typingstatus1 = new HashMap(); typingstatus.put("usertyping", "false"); mref6.setValue(typingstatus1).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); DatabaseReference countref = FirebaseDatabase.getInstance().getReference().child("count_of_request").child(firebaseUser.getUid()); countref.child("count").setValue("0").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { } }); Toast.makeText(mcontext, "Accepted", Toast.LENGTH_SHORT).show(); currentstate = "friends"; holder.addrequestedfriend.setText("Added"); } }); } }); } }); } }); } }); } }); } }); } }); } }); } }); } }); } }); } }); } }); final String msg = "Accepted your Friend Request"; DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users").child(firebaseUser.getUid()); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Details details = dataSnapshot.getValue(Details.class); if (notify) { sendNotification1(sender, details.getUSERNAME(), msg, friends_request); } notify = false; } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); holder.bar.setVisibility(View.GONE); } } }); /* if(currentstate.equals("reqsend")) { mref.child(firebaseUser.getUid()).child(userid).child("requested_type").removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mref.child(userid).child(firebaseUser.getUid()).child("requested_type").removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(mcontext, "Request canceled...", Toast.LENGTH_SHORT).show(); currentstate ="Notfriends"; // addfriend.setText("Add Friend"); } }); } }); } } }); } }); */ } private void sendNotification1(final String reciever, final String username, final String message, Friends_request friends_request) { final String sender = friends_request.getSender(); userid = friends_request.getId(); DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens"); Query query = tokens.orderByKey().equalTo(reciever); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Token2 token = snapshot.getValue(Token2.class); Data2 data = new Data2(firebaseUser.getUid(), R.mipmap.ic_launcher, username + " " + message, "Friend Request", reciever); Sender2 sender2 = new Sender2(data, token.getToken()); api2.sendNotification(sender2) .enqueue(new retrofit2.Callback<MyResponse>() { @Override public void onResponse(Call<MyResponse> call, Response<MyResponse> response) { if (response.code() == 200) { if (response.body().success != 1) { Toast.makeText(mcontext, "Failed", Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<MyResponse> call, Throwable t) { } }); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return mfriendrequest.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView un; public CircleImageView imageenter1; Button addrequestedfriend; ProgressBar bar; public ViewHolder(View itemView) { super(itemView); un = itemView.findViewById(R.id.un); imageenter1 = itemView.findViewById(R.id.imageenter1); addrequestedfriend = itemView.findViewById(R.id.addrequestedfriend); bar=itemView.findViewById(R.id.bar); } public void setUserimage(String image, Context mcontext) { imageenter1 = itemView.findViewById(R.id.imageenter1); Picasso.with(mcontext).load(image).placeholder(R.drawable.pro).into(imageenter1); } } }
true
93a488014b1cced35cd9438670cbb9dedadbff28
Java
marlboroMedium/mad-sheep
/dukeshopFinal/src/casestudy/business/service/MemberServiceImpl.java
UHC
4,435
3.015625
3
[]
no_license
/** * ϸ : MemberServiceImpl.java * ۼ : 2014. 2. 13. * ϼ : */ package casestudy.business.service; import casestudy.business.domain.Member; /** * ȸ Ͻ Ŭ * ׼ ó MemberDao ü Ͽ Ѵ. * * @author ([email protected]) * */ public class MemberServiceImpl implements MemberService { private MemberDao memberDataAccess; /* * MemberDaoImpl ü Ͽ memberDataAccess νϽ ʱȭ */ public MemberServiceImpl() { memberDataAccess = new casestudy.dataaccess.MemberDaoImpl(); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#registerMember(casestudy.business.domain.Member) * * MemberDao ü ڷ ȸ Ѵ. * 1.1. ߺ memberID ȸ ʰ DataDuplicatedException ߻Ų. * (MemberDao memberIDExists() ޼ҵ Ȱ) * 1.2. ޼ҵ ο DataDuplicatedException ߻ ǥѴ.(throws DataDuplicatedException) */ @Override public void registerMember(Member member) throws DataDuplicatedException { if (memberDataAccess.memberIDExists(member.getMemberID())) { throw new DataDuplicatedException(" memberID ȸ ֽϴ.(" + member.getMemberID() + ")"); } memberDataAccess.insertMember(member); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#findMember(java.lang.String) * * MemberDao ü ڷ memberID شϴ ȸ ãƼ Ѵ. * 2.1. memberID شϴ ȸ DataNotFoundException ߻Ų. * (MemberDao memberIDExists() ޼ҵ Ȱ) * 2.2. ޼ҵ ο DataNotFoundException ߻ ǥѴ.(throws DataNotFoundException) */ @Override public Member findMember(String memberID) throws DataNotFoundException { if (!memberDataAccess.memberIDExists(memberID)) { throw new DataNotFoundException(" ʴ ȸԴϴ.(" + memberID + ")"); } return memberDataAccess.selectMember(memberID); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#updateMember(casestudy.business.domain.Member) * * MemberDao ü ڷ ȸ Ѵ. * 3. شϴ ȸ DataNotFoundException ߻Ų. */ @Override public void updateMember(Member member) throws DataNotFoundException { if (!memberDataAccess.memberIDExists(member.getMemberID())) { throw new DataNotFoundException(" ʴ ȸԴϴ.(" + member.getMemberID() + ")"); } memberDataAccess.updateMember(member); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#removeMember(casestudy.business.domain.Member) * * MemberDao ü ڷ ȸ Ѵ. * 4. شϴ ȸ DataNotFoundException ߻Ų. */ @Override public void removeMember(Member member) throws DataNotFoundException { if (!memberDataAccess.memberIDExists(member.getMemberID())) { throw new DataNotFoundException(" ʴ ȸԴϴ.(" + member.getMemberID() + ")"); } memberDataAccess.deleteMember(member); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#loginCheck(java.lang.String, java.lang.String) * * MemberDao ü ڷ memberID, password * α θ Ȯϰ, ش ȸ Ѵ. */ @Override public Member loginCheck(String memberID, String password) { return memberDataAccess.checkMember(memberID, password); } /* (non-Javadoc) * @see casestudy.business.service.MemberService#getAllMembers() * * MemberDao ü ȸ ؼ Ѵ. */ @Override public Member[] getAllMembers() { return memberDataAccess.selectAllMembers(); } }
true
ffecb80c062c4f8a90e00fc2389e39bb5893ee9b
Java
Mercies/projetB
/src/main/java/com/learning/service/CourService.java
UTF-8
541
2.046875
2
[]
no_license
package com.learning.service; import java.util.List; import com.learning.dto.CourDTO; import com.learning.model.Cour; public interface CourService extends CrudService<Cour, CourDTO> { Cour findEnitityById(Long id); List<CourDTO> findAll(); void deleteByModule(Long idModule); Cour convertDTOtoModelWithOutModule(CourDTO courDTO); CourDTO convertModelToDTOWithOutModule(final Cour cour); List<CourDTO> convertEntitiesToDtosWithOutModule(List<Cour> list); List<Cour> convertDtosToEntitiesWithOutModule(List<CourDTO> list); }
true
c4f2910cecad0215c1a9625ec3264a4516b8dfa3
Java
jhribal/bcplugin
/src/cz/vutbr/fit/xhriba01/bc/eclipse/algo/IClassFromJavaStrategy.java
UTF-8
266
1.53125
2
[]
no_license
package cz.vutbr.fit.xhriba01.bc.eclipse.algo; import org.eclipse.jdt.core.ICompilationUnit; import cz.vutbr.fit.xhriba01.bc.lib.IClassContainer; public interface IClassFromJavaStrategy { IClassContainer getClassFromJava(ICompilationUnit compilationUnit); }
true
7932dd77f428fabfc0e02b68762243b7e123df0d
Java
tgh-621/Linkis
/linkis-public-enhancements/linkis-datasource/metadatamanager/service/hive/src/main/java/org/apache/linkis/metadatamanager/service/HiveMetaService.java
UTF-8
9,063
1.710938
2
[ "Apache-2.0", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-unicode", "LGPL-2.0-or-later", "EPL-1.0", "Classpath-exception-2.0", "GPL-1.0-or-later", "CC-BY-SA-3.0", "CPL-1.0", "LicenseRef-scancode-generic-cla", "SAX-PD", "EPL-2.0", "LicenseRef-scancode-free-unknown", "CC-PDDC", "CDDL-1.0", "GPL-2.0-only", "GCC-exception-3.1", "xpp", "LGPL-2.1-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-export-compliance", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "NAIST-2003", "Apache-1.1", "CC0-1.0", "CDDL-1.1", "W3C", "MPL-1.1", "ICU", "WTFPL", "LGPL-2.1-or-later", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.linkis.metadatamanager.service; import org.apache.linkis.bml.client.BmlClient; import org.apache.linkis.bml.client.BmlClientFactory; import org.apache.linkis.bml.protocol.BmlDownloadResponse; import org.apache.linkis.common.conf.CommonVars; import org.apache.linkis.metadatamanager.common.domain.MetaColumnInfo; import org.apache.linkis.metadatamanager.common.domain.MetaPartitionInfo; import org.apache.linkis.metadatamanager.common.exception.MetaRuntimeException; import org.apache.linkis.metadatamanager.common.service.AbstractMetaService; import org.apache.linkis.metadatamanager.common.service.MetadataConnection; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; @Component public class HiveMetaService extends AbstractMetaService<HiveConnection> { private static final Logger LOG = LoggerFactory.getLogger(HiveMetaService.class); private static final CommonVars<String> TMP_FILE_STORE_LOCATION = CommonVars.apply("wds.linkis.server.mdm.service.temp.location", "classpath:/tmp"); private BmlClient client; @PostConstruct public void buildClient(){ client = BmlClientFactory.createBmlClient(); } @Override public MetadataConnection<HiveConnection> getConnection(String operator, Map<String, Object> params) throws Exception { Resource resource = new PathMatchingResourcePatternResolver().getResource(TMP_FILE_STORE_LOCATION.getValue()); String uris = String.valueOf(params.getOrDefault(HiveParamsMapper.PARAM_HIVE_URIS.getValue(), "")); String principle = String.valueOf(params.getOrDefault(HiveParamsMapper.PARAM_HIVE_PRINCIPLE.getValue(), "")); HiveConnection conn = null; if(StringUtils.isNotBlank(principle)){ LOG.info("Try to connect Hive MetaStore in kerberos with principle:[" + principle +"]"); String keytabResourceId = String.valueOf(params.getOrDefault(HiveParamsMapper.PARAM_HIVE_KEYTAB.getValue(), "")); if(StringUtils.isNotBlank(keytabResourceId)){ LOG.info("Start to download resource id:[" + keytabResourceId +"]"); String keytabFilePath = resource.getFile().getAbsolutePath() + "/" + UUID.randomUUID().toString().replace("-", ""); if(!downloadResource(keytabResourceId, operator, keytabFilePath)){ throw new MetaRuntimeException("Fail to download resource i:[" + keytabResourceId +"]"); } conn = new HiveConnection(uris, principle, keytabFilePath); }else{ throw new MetaRuntimeException("Cannot find the keytab file in connect parameters"); } }else{ conn = new HiveConnection(uris); } return new MetadataConnection<>(conn, true); } /** * Download resource to path by id * @param resourceId resource id * @param user user * @param absolutePath absolute path * @return * @throws IOException */ private boolean downloadResource(String resourceId, String user, String absolutePath) throws IOException { BmlDownloadResponse downloadResponse = client.downloadResource(user, resourceId, absolutePath); if(downloadResponse.isSuccess()){ IOUtils.copy(downloadResponse.inputStream(), new FileOutputStream(absolutePath)); return true; } return false; } @Override public List<String> queryDatabases(HiveConnection connection) { try { return connection.getClient().getAllDatabases(); } catch (HiveException e) { throw new RuntimeException("Fail to get Hive databases(获取数据库列表失败)", e); } } @Override public List<String> queryTables(HiveConnection connection, String database) { try { return connection.getClient().getAllTables(database); } catch (HiveException e) { throw new RuntimeException("Fail to get Hive tables(获取表列表失败)", e); } } @Override public MetaPartitionInfo queryPartitions(HiveConnection connection, String database, String table) { List<Partition> partitions; Table rawTable; try { rawTable = connection.getClient().getTable(database, table); partitions = connection.getClient().getPartitions(rawTable); } catch (HiveException e) { throw new RuntimeException("Fail to get Hive partitions(获取分区信息失败)", e); } MetaPartitionInfo info = new MetaPartitionInfo(); List<FieldSchema> partitionKeys = rawTable.getPartitionKeys(); List<String> partKeys = new ArrayList<>(); partitionKeys.forEach(e -> partKeys.add(e.getName())); info.setPartKeys(partKeys); //Static partitions Map<String, MetaPartitionInfo.PartitionNode> pMap = new HashMap<>(20); MetaPartitionInfo.PartitionNode root = new MetaPartitionInfo.PartitionNode(); info.setRoot(root); long t = System.currentTimeMillis(); for(Partition p : partitions){ try { List<String> values = p.getValues(); if(!partitionKeys.isEmpty()){ String parentNameValue = ""; for(int i = 0; i < values.size(); i++){ FieldSchema fieldSchema = partitionKeys.get(i); String name = fieldSchema.getName(); String value = values.get(i); String nameValue= name + "=" + value; MetaPartitionInfo.PartitionNode node = new MetaPartitionInfo.PartitionNode(); if(i > 0){ MetaPartitionInfo.PartitionNode parent = pMap.get(parentNameValue); parent.setName(name); parent.getPartitions().putIfAbsent(value, node); }else{ root.setName(name); root.getPartitions().putIfAbsent(value, node); } parentNameValue += "/" + nameValue; pMap.putIfAbsent(parentNameValue, node); } } }catch(Exception e){ LOG.warn(e.getMessage(), e); } } return info; } @Override public List<MetaColumnInfo> queryColumns(HiveConnection connection, String database, String table) { List<MetaColumnInfo> columns = new ArrayList<>(); Table tb; try { tb = connection.getClient().getTable(database, table); } catch (HiveException e) { throw new RuntimeException("Fail to get Hive columns(获得表字段信息失败)", e); } tb.getFields().forEach( field ->{ MetaColumnInfo metaColumnInfo = new MetaColumnInfo(); metaColumnInfo.setIndex(field.getFieldID()); metaColumnInfo.setName(field.getFieldName()); metaColumnInfo.setType(field.getFieldObjectInspector().getTypeName()); columns.add(metaColumnInfo); }); return columns; } @Override public Map<String, String> queryTableProps(HiveConnection connection, String database, String table) { try { Table rawTable = connection.getClient().getTable(database, table); return new HashMap<>((Map)rawTable.getMetadata()); }catch(Exception e){ throw new RuntimeException("Fail to get Hive table properties(获取表参数信息失败)", e); } } }
true
24023e535fced5ce971e030822347d0f5b572eda
Java
VoxMach/Tak-Ang
/app/src/main/java/com/example/tak_ang/tableget.java
UTF-8
987
2.28125
2
[]
no_license
package com.example.tak_ang; public class tableget { private int table_id; private String table_name; private int capacity; private int status; public tableget(int table_id, String table_name, int capacity, int status) { this.table_id = table_id; this.table_name = table_name; this.capacity = capacity; this.status = status; } public int getTable_id() { return table_id; } public void setTable_id(int table_id) { this.table_id = table_id; } public String getTable_name() { return table_name; } public void setTable_name(String table_name) { this.table_name = table_name; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
true
392c524aa18ba6acf5e82b72a335d963e92f9e08
Java
creator-krixus/StudentsApi
/src/main/java/com/studentSistem/service/StudentServiceImpl.java
UTF-8
598
2.28125
2
[]
no_license
package com.studentSistem.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.studentSistem.model.Student; import com.studentSistem.repository.StudentRepository; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Override public Student saveStudent(Student student) { return studentRepository.save(student); } @Override public List<Student> getAllStudents() { return studentRepository.findAll(); } }
true
75a6e8a2cdcb2c96865c7dab5d71550b35f83ee6
Java
cckmit/myproject-3
/crosswayembed/piano/src/main/java/com/klsw/piano/service/TbClassroomService.java
UTF-8
518
1.84375
2
[]
no_license
package com.klsw.piano.service; import com.klsw.pianoCommon.api.mapper.TbClassroomMapper; import com.klsw.pianoCommon.api.model.TbClassroom; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class TbClassroomService extends _BaseService<TbClassroom> { @Resource TbClassroomMapper tbClassroomMapper; public List<TbClassroom> selectClassroomList(Integer typeId) { return tbClassroomMapper.selectClassroomList(typeId); } }
true
54115a2d241a0ec3fec86f79e14a743327c7e2f3
Java
arraycto/cloudspring
/cloud-cms/src/main/java/com/ocean/cloudcms/config/FeignRequestInterceptor.java
UTF-8
1,930
2.328125
2
[]
no_license
package com.ocean.cloudcms.config; import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; /** * feign转发header参数 * @author langpf 2018/12/19 */ @Configuration public class FeignRequestInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String values = request.getHeader(name); template.header(name, values); } } } private HttpServletRequest getHttpServletRequest() { try { // 这种方式获取的HttpServletRequest是线程安全的 return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest(); } catch (Exception e) { return null; } } private Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enums = request.getHeaderNames(); while (enums.hasMoreElements()) { String key = enums.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
true
d8b5e20bd9f855e6ab8b848dc20422a5b98af8a8
Java
humber42/tyke-backends
/tyke-notifications/src/main/java/cu/edu/cujae/tykenotifications/api/notifications/NotificationsRestController.java
UTF-8
2,235
2.25
2
[]
no_license
package cu.edu.cujae.tykenotifications.api.notifications; import cu.edu.cujae.tykenotifications.constants.WebResourceKeyConstants; import cu.edu.cujae.tykenotifications.dto.Notifications; import cu.edu.cujae.tykenotifications.service.NotificationService; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping(WebResourceKeyConstants.BASE_API_NOTIFICATIONS) public class NotificationsRestController { @Autowired private NotificationService service; @Autowired private Mapper mapper; @GetMapping(WebResourceKeyConstants.NotificationsUrls.FIND_ALL_MY_NEW_NOTIFICATIONS) public List<NotificationsResponse> getAllMyNewNotifications(@PathVariable("id") long id) { return service.findAllNewNotificationsToMe(id) .stream() .map(this::mapping) .collect(Collectors.toList()); } @GetMapping(WebResourceKeyConstants.NotificationsUrls.FIND_ALL_MY_NOTIFICATIONS) public List<NotificationsResponse> getAllMyNotifications(@PathVariable("id") long id) { return service.findAllMyNotifications(id) .stream() .map(this::mapping) .collect(Collectors.toList()); } @PutMapping(WebResourceKeyConstants.NotificationsUrls.MARK_AS_READ) public NotificationsResponse markAsRead(@PathVariable("id") long id) { return mapping(service.markAsRead(id)); } @PostMapping(WebResourceKeyConstants.NotificationsUrls.NEW_NOTIFICATIONS) public NotificationsResponse sendNotification(@RequestBody NotificationsRequest request) { return mapping( service.newNotifications( mapper.map(request, Notifications.class)) ); } @DeleteMapping(WebResourceKeyConstants.NotificationsUrls.DELETE_NOTIFICATION) public void deleteNotification(@PathVariable("id") long id) { service.deleteNotification(id); } private NotificationsResponse mapping(Notifications notify) { return mapper.map(notify, NotificationsResponse.class); } }
true
d0083f728c92482e3c68dc744ef882f34bdcacec
Java
gnattyp/das-boot
/src/main/java/com/boot/App.java
UTF-8
646
2.4375
2
[]
no_license
package com.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * with spring boot we will run this app as a regular old java application * by adding @SpringBootApplication it will scan the app from spring annotations * and autowire most of the components we will want to use by enableing autoconfiguration */ @SpringBootApplication public class App { public static void main( String[] args ) { //fires up spring boot when our public static void main method is run as a pure java application SpringApplication.run(App.class, args); } }
true
8732cb48f3ae50613aded6deafedb16cee934511
Java
indeedeng/proctor
/proctor-webapp-library/src/test/java/com/indeed/proctor/webapp/db/GitProctorStoreFactoryTest.java
UTF-8
2,376
2.21875
2
[ "Apache-2.0" ]
permissive
package com.indeed.proctor.webapp.db; import com.indeed.proctor.store.ProctorStore; import com.indeed.proctor.store.cache.GlobalCachingProctorStore; import com.indeed.proctor.webapp.extensions.GlobalCacheStore; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class GitProctorStoreFactoryTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private GlobalCacheStore globalCacheStore; @Mock private ProctorStore proctorStore; private GitProctorStoreFactory gitProctorStoreFactory; @Before public void setUp() throws IOException { gitProctorStoreFactory = createGitProctorStoreFactory(globalCacheStore); } @Test public void testCreateStoreWithoutGlobalCache() throws IOException { final GitProctorStoreFactory gitProctorStoreFactoryWithoutGlobalCache = createGitProctorStoreFactory(null); final ProctorStore store = gitProctorStoreFactoryWithoutGlobalCache.createStoreWithGlobalCache( "trunk", proctorStore); assertThat(store).isNotInstanceOf(GlobalCachingProctorStore.class); } @Test public void testCreateStoreWithGlobalCache() { final ProctorStore store = gitProctorStoreFactory.createStoreWithGlobalCache("trunk", proctorStore); assertThat(store).isInstanceOf(GlobalCachingProctorStore.class); } @Test public void testCreateStoreWithInvalidBranch() { expectedException.expect(NullPointerException.class); gitProctorStoreFactory.createStoreWithGlobalCache("unknown", proctorStore); } private GitProctorStoreFactory createGitProctorStoreFactory( final GlobalCacheStore globalCacheStore) throws IOException { return new GitProctorStoreFactory( "test.git", "test-user", "password", "/definition/", "/", 20, 10, 10, true, globalCacheStore); } }
true
d3817f145a5cbcd68aefa7e1ca0784eaa7fc6d22
Java
enliktjioe/dataeng2020
/P07_Kafka_Streams/ksql/src/main/java/ee/ut/cs/dsg/dsg/exercise2/ObservationProducer.java
UTF-8
2,176
2.484375
2
[]
no_license
package ee.ut.cs.dsg.dsg.exercise2; import io.confluent.kafka.serializers.KafkaAvroDeserializerConfig; import io.confluent.kafka.serializers.KafkaAvroSerializer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Properties; import java.util.Random; public class ObservationProducer { public static String TOPIC = "temperature_avro2"; public void createProducer() throws InterruptedException { Random random = new Random(1); Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka1:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName()); // props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomPartitioner.class.getName()); // props.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, "mock://" + scope); props.put(KafkaAvroDeserializerConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://schema-registry:8081/"); KafkaProducer<String, Observation> termometer = new KafkaProducer<>(props); long ts = 0; try { while (true) { String key = "room" + random.nextInt(5); double temperature = random.nextDouble(); if (random.nextBoolean()) temperature = -1 * temperature; Observation value = new Observation(1L, temperature, TOPIC, ts += 2000); ProducerRecord<String, Observation> record = new ProducerRecord<>(TOPIC, key, value); termometer.send(record); Thread.sleep(10000); } } finally { termometer.close(); } } public static void main(String[] args) throws InterruptedException { ObservationProducer helloProducer = new ObservationProducer(); helloProducer.createProducer(); } }
true
249bb6f2035d6a9ac60c3ec47f0e996583790a9d
Java
spuppi/GitEclipse
/SENA_1/negocios/Sistema.java
ISO-8859-1
7,059
2.34375
2
[]
no_license
/** * */ package negocios; import persistencia.CadastroSistema; /** * @author Administrador * * Classe para validao de dados para cadastro do Sistema. * */ public class Sistema { private String nmInstituicao; private String endereco; private String numero; private String complemento; private String bairro; private String cidade; private String estado; private String cep; private String telefone; private String email; private String fax; private String nmResponsavel; private String cnpj; private String ie; private String nmSecretario; private String rgSecretario; private String nmDiretor; private String rgDiretor; private String caminhoLogo; /** * * Construtor * */ public Sistema(){ super(); } //---Ajusta dados para validao public void ajustaDados(String nmInstituicao, String endereco, String numero, String complemento, String bairro, String cidade, String estado, String cep, String telefone, String email, String fax, String nmResponsavel, String cnpj, String ie, String nmSecretario, String rgSecretario, String nmDiretor, String rgDiretor, String caminhoLogo){ this.nmInstituicao = nmInstituicao; this.endereco = endereco; this.numero = numero; this.complemento = complemento; this.bairro = bairro; this.cidade = cidade; this.estado = estado; this.cep = cep; this.telefone = telefone; this.email = email; this.fax = fax; this.nmResponsavel = nmResponsavel; this.cnpj = cnpj; this.ie = ie; this.nmSecretario = nmSecretario; this.rgSecretario = rgSecretario; this.nmDiretor = nmDiretor; this.rgDiretor = rgDiretor; this.caminhoLogo = caminhoLogo; } //----Mtodos que retornam valores respectivos public String getBairro() { return bairro; } public String getCaminhoLogo() { return caminhoLogo; } public String getCep() { return cep; } public String getCidade() { return cidade; } public String getCnpj() { return cnpj; } public String getComplemento() { return complemento; } public String getEmail() { return email; } public String getEndereco() { return endereco; } public String getEstado() { return estado; } public String getFax() { return fax; } public String getIe() { return ie; } public String getNmDiretor() { return nmDiretor; } public String getNmInstituicao() { return nmInstituicao; } public String getNmResponsavel() { return nmResponsavel; } public String getNmSecretario() { return nmSecretario; } public String getNumero() { return numero; } public String getRgDiretor() { return rgDiretor; } public String getRgSecretario() { return rgSecretario; } public String getTelefone() { return telefone; } //----------Validaa dos dados-----------------------------------------------// //---Atributo que armazenar status de validao private String status; //---Retorna status de validao public String getStatus(){ return this.status; } public int validar(){ int x = 0; this.status = ""; if(getNmInstituicao().equals("")){ this.status +="\nNome da Instituio de ensino invlido."; x+=1; } if(getEndereco().equals("")){ this.status +="\nEndereo da Instituio de ensino invlido."; x+=1; } if(getNumero().equals("")){ this.status +="\nNmero de endereo da Instituio de ensino invlido."; x+=1; } if(getBairro().equals("")){ this.status +="\nBairro do endereo da Instituio de ensino invlido."; x+=1; } if(getCidade().equals("")){ this.status +="\nCidade da Instituio de ensino invlido."; x+=1; } if(getEstado().equals("--")){ this.status +="\nEstado da Instituio de ensino invlido."; x+=1; } if(getCep().equals("__.___-___")){ this.status +="\nCEP da Instituio de ensino invlido."; x+=1; } if(getTelefone().equals("(__)____-____")){ this.status +="\nTelefone da Instituio de ensino invlido."; x+=1; } if(getNmResponsavel().equals("")){ this.status +="\nNome do responsvel pela Instituio de ensino invlido."; x+=1; } if(getNmSecretario().equals("")){ this.status +="\nNome do secretrio(a) da Instituio de ensino invlido."; x+=1; } if(getRgSecretario().equals("")){ this.status +="\nR.G. do secretrio(a) da Instituio de ensino invlido."; x+=1; } if(getNmDiretor().equals("")){ this.status +="\nNome do diretor(a) da Instituio de ensino invlido."; x+=1; } if(getRgDiretor().equals("")){ this.status +="\nR.G. do diretor(a) da Instituio de ensino invlido."; x+=1; } if(x==0){ this.status = ""; } return x; } //------------Comandos para a camada de persistncia---------------------------// //--Verifica se existe public int getExiste(){ CadastroSistema cadastrar = new CadastroSistema(); cadastrar.verificaExiste(); if(cadastrar.getExiste()==0){ return 0; }else{ return 1; } } //--Cadastrar public void cadastrar(){ CadastroSistema cadastrar = new CadastroSistema(); cadastrar.ajustaDados(getNmInstituicao(), getEndereco(), getNumero(), getComplemento(), getBairro(), getCidade(), getEstado(), getCep(), getTelefone(), getEmail(), getFax(), getNmResponsavel(), getCnpj(), getIe(), getNmSecretario(), getRgSecretario(), getNmDiretor(), getRgDiretor(), getCaminhoLogo()); cadastrar.cadastrar(); } //--Alterar public void alterar(){ CadastroSistema alterar = new CadastroSistema(); alterar.ajustaDados(getNmInstituicao(), getEndereco(), getNumero(), getComplemento(), getBairro(), getCidade(), getEstado(), getCep(), getTelefone(), getEmail(), getFax(), getNmResponsavel(), getCnpj(), getIe(), getNmSecretario(), getRgSecretario(), getNmDiretor(), getRgDiretor(), getCaminhoLogo()); alterar.alterar(); } //--Busca dados public void consultar(){ CadastroSistema consultar = new CadastroSistema(); consultar.consultar(); this.nmInstituicao = consultar.getNmInstituicao(); this.endereco = consultar.getEndereco(); this.numero = consultar.getNumero(); this.complemento = consultar.getComplemento(); this.bairro = consultar.getBairro(); this.cidade = consultar.getCidade(); this.estado = consultar.getEstado(); this.cep = consultar.getCep(); this.telefone = consultar.getTelefone(); this.email = consultar.getEmail(); this.fax = consultar.getFax(); this.nmResponsavel = consultar.getNmResponsavel(); this.cnpj = consultar.getCnpj(); this.ie = consultar.getIe(); this.nmSecretario = consultar.getNmSecretario(); this.rgSecretario = consultar.getRgSecretario(); this.nmDiretor = consultar.getNmDiretor(); this.rgDiretor = consultar.getRgDiretor(); this.caminhoLogo = consultar.getCaminhoLogo(); } }
true
1036306d6fdf1fd198ed923653099131372c65fa
Java
pranithashravani/java-pe1
/src/main/java/com/stackroute/junitdemo/Vowel.java
UTF-8
673
3.265625
3
[]
no_license
package com.stackroute.junitdemo; public class Vowel { public String isvowel(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') { result += "Vowel"; } else { result += "Consonant"; } } else { result += "Error"; } } return result; } }
true
d88d119076a11d427a974d38d171f48b4ff6f626
Java
jinshuaishuai/IdeaGitTest
/springboot-base/multithread/src/main/java/com/pattern/simplefactory/ReflectTest.java
UTF-8
421
2.75
3
[]
no_license
package com.pattern.simplefactory; import java.util.HashMap; /** * @author shuai.jin * @date 2020/11/10 11:54 */ public class ReflectTest { public static void main(String[] args) { HashMap<String, String> hashMap = new HashMap<String, String>(); for(int i = 0; i < Integer.MAX_VALUE; i++) { System.out.println("hello"); hashMap.put("" + i, i + ""); } } }
true
7239a8a49b14849cce903212f2f87aa23445fd40
Java
SyuuTou/wlspacecraft
/src/main/java/com/lhjl/tzzs/proxy/dto/SerchHistoryDto.java
UTF-8
1,082
2.046875
2
[]
no_license
package com.lhjl.tzzs.proxy.dto; import java.util.Date; public class SerchHistoryDto { private String search; private String date; private Integer id; private Integer user_id; private Date search_time; private Integer yn; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public Date getSearch_time() { return search_time; } public void setSearch_time(Date search_time) { this.search_time = search_time; } public Integer getYn() { return yn; } public void setYn(Integer yn) { this.yn = yn; } public String getSearch() { return search; } public void setSearch(String search) { this.search = search; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
true
5dc5289f7fe61f641e65ac7706ad895c661c921d
Java
bharat30156/Java-Whatsapp-Message-Sender-
/WhatsappSender.java
UTF-8
2,048
2.90625
3
[]
no_license
import java.io.BufferedReader; import java.io.OutputStream; import java.io.InputStreamReader; import java.net.*; /** * * @author Bharat * */ public class WhatsappSender { //TODO : put the Instance Id, Forever green client ID and Secret : private static final String INSTANCE_ID = "YOUR_INSTANCE_ID_HERE"; private static final String CLIENT_ID = "YOUR_CLIENT_ID_HERE"; private static final String CLIENT_SECRET = "YOUR_CLIENT_SECRET_HERE"; private static final String WA_GATEWAY_URL = "http://api.whatsmate.net/v3/whatsapp/single/text/message/" + INSTANCE_ID; /** * Entruy Point */ public static void main(String[] args) { } /** * Sends out a whatsapp message via whatsappMate WA Gateway */ public static void sendMessage(String number, String message) throws Exception { //TODO : should have a 3rd party library to make a JSON String from an object String jsonPayload = new StringBuilder() .append("{") .append("\"number\":\"") .append(number) .append("\",") .append("\"message\":\"") .append(message) .append("\"") .append("}") .toString(); URL url = new URL(WA_GATEWAY_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID); conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET); conn.setRequestProperty("Content-Type", "application/json"); OutputStream os = conn.getOutputStream(); os.write(jsonPayload.getBytes()); os.flush(); os.close(); int statusCode = conn.getResponseCode(); System.out.println("Response from WA Gateway: \n"); System.out.println("status code: " + statusCode); BufferedReader br = new BufferedReader(new InputStreamReader( (statusCode == 200) ? conn.getInputStream() : conn.getErrorStream() )); String output; while((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } }
true
c01851cc1716fd815f26ec19a0c41175a3e215cf
Java
inaabadjieva/SoftUni-Java
/Java-Fundamentals/10.Exams/src/Problem2_CubicRube.java
UTF-8
1,385
3.265625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Problem2_CubicRube { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); long[][][] cube = new long[n][n][n]; long count = (long)Math.pow(n, 3); long sum = 0L; String line = ""; while(!"Analyze".equals(line = reader.readLine())){ String[] tokens = line.split("\\s+"); int dimen1 = Integer.parseInt(tokens[0]); int dimen2 = Integer.parseInt(tokens[1]); int dimen3 = Integer.parseInt(tokens[2]); long value = Long.parseLong(tokens[3]); if(isInside(cube, dimen1, dimen2, dimen3)){ sum += value; if(value != 0){ count--; } } } System.out.println(sum); System.out.println(count); } private static boolean isInside(long[][][] cube, int dimen1, int dimen2, int dimen3) { if(dimen1 >= 0 && dimen1 < cube.length && dimen2 >= 0 && dimen2 < cube[0].length && dimen3 >= 0 && dimen3 < cube[0][0].length){ return true; } return false; } }
true
e25a0c02221f122b8da19eb6beed47a743438967
Java
xxbeam/service-master
/server/bill/src/main/java/com/platform/bill/dao/BillBookMapper.java
UTF-8
759
1.882813
2
[]
no_license
package com.platform.bill.dao; import com.platform.bill.bo.BillBook; import com.platform.bill.bo.BillBookExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BillBookMapper { int deleteByPrimaryKey(Integer id); int insert(BillBook record); int insertSelective(BillBook record); List<BillBook> selectByExample(BillBookExample example); BillBook selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") BillBook record, @Param("example") BillBookExample example); int updateByExample(@Param("record") BillBook record, @Param("example") BillBookExample example); int updateByPrimaryKeySelective(BillBook record); int updateByPrimaryKey(BillBook record); }
true
7c65f5300133dad19d4289c740eb36bd5757042b
Java
smsali97/Stuffies
/assignment/GuitarHeroVisualiser.java
UTF-8
1,883
3.015625
3
[]
no_license
package assignment; public class GuitarHeroVisualiser { public static void main(String[] args) { StdDraw.setCanvasSize(1024/4, 256); StdDraw.clear(StdDraw.BLACK); StdDraw.setPenColor(StdDraw.BOOK_BLUE); StdDraw.setXscale(0, StdAudio.SAMPLE_RATE/2); StdDraw.setYscale(-1, +1); StdDraw.show(); int N = 37; GuitarString[] gh = new GuitarString[N]; String keyboard = "q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/' "; for (int i = 0; i < gh.length; i++) { double freq = 440 * (Math.pow(1.05956, i - 24)); gh[i] = new GuitarString(freq); } int x = 0; while (true) { // Check if the user has typed a key /* nn//SS/ ..,,mmn //..,,m //..,,m nn//SS/ ..,,mmn w q q 8 u 7 y o p p i p z v b z p b n z p n d [ i d z p i p z p i u i i */ if (StdDraw.hasNextKeyTyped()) { char key = StdDraw.nextKeyTyped(); int no = keyboard.indexOf(key); // Check if character is valid if (!(no == -1)) { gh[no].pluck(); } } // Compute the super-position of the samples double sample = 0.5; for (int i = 0; i < 37; i++) { double old = sample; sample = old + gh[i].sample(); } // send the result to standard audio StdAudio.play(sample); // advance the simulation of each guitar string by one step for (int i = 0; i < 37; i++) { gh[i].tic(); } // Lets Draw! StdDraw.enableDoubleBuffering(); if (sample!=0) StdDraw.point((x) % StdAudio.SAMPLE_RATE/2, sample); // StdDraw.line(prev % StdAudio.SAMPLE_RATE, sample, // (x+1) % StdAudio.SAMPLE_RATE, sample); if (x == StdAudio.SAMPLE_RATE - 1) { StdDraw.show(); StdDraw.clear(StdDraw.BLACK); x = 0; } x += 1; } } }
true
a97d23068980197591f3f2aacb76f689a789cb77
Java
GcmWork/micro-wx-server1
/src/main/java/com/example/wx/domain/InputModel/GetAppealDetailInput.java
UTF-8
319
1.90625
2
[]
no_license
package com.example.wx.domain.InputModel; /** * Created by Administrator on 2018/4/21. */ public class GetAppealDetailInput { public long appealid=0L; public long getAppealid() { return appealid; } public void setAppealid(long appealid) { this.appealid = appealid; } }
true
c629ff59d31c884593b1a2576dbbc7a5cc24bfb6
Java
templario01/Adoptme
/app/src/main/java/com/example/adoptme/mapaMascota.java
UTF-8
7,532
2.1875
2
[]
no_license
package com.example.adoptme; import androidx.annotation.RequiresApi; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; public class mapaMascota extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; Button btnlisto,btnhelp; String lati; String longi; private Marker marcador; double lat = 0.0; double lng = 0.0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mapa_mascota); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); btnlisto = (Button)findViewById(R.id.btnListo); btnlisto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { enviarCoordenadas(); } }); btnhelp = (Button)findViewById(R.id.btnHelp); btnhelp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(mapaMascota.this); builder.setIcon(R.drawable.help) .setTitle("Añadir la ubicacion del perro") .setMessage("Manten presionado por 2 segundos en el lugar donde viste el animal") .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ public void enviarCoordenadas(){ try{ Intent intent = new Intent (mapaMascota.this, MainActivity.class); intent.putExtra("dato1",lati); intent.putExtra("dato2",longi); startActivity(intent); }catch (Exception e){ e.printStackTrace(); } } @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; miUbicacion(); /* Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/ //verificamos que solo genere un marcador try { if(TextUtils.isEmpty(lati) || TextUtils.isEmpty(longi)){ mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.dogmark)).anchor(0.0f,1.0f).position(latLng)); //rescatamos los valores de latlng y los almacenamos en lati y longi LatLng posicionmascota = latLng; lati = String.valueOf(posicionmascota.latitude); longi = String.valueOf(posicionmascota.longitude); } }); } }catch (Exception e){ e.printStackTrace(); } } private void agregarMarcador(double lat, double lng) { LatLng coordenadas = new LatLng(lat, lng); CameraUpdate miUbicacion = CameraUpdateFactory.newLatLngZoom(coordenadas, 13); if (marcador != null) marcador.remove(); marcador = mMap.addMarker(new MarkerOptions() .position(coordenadas).title("Posicion actual") .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_posicion))); mMap.animateCamera(miUbicacion); } private void actualizarUbicacion(Location location) { if (location != null) { lat = location.getLatitude(); lng = location.getLongitude(); agregarMarcador(lat, lng); } } LocationListener locListener = new LocationListener() { @Override public void onLocationChanged(Location location) { actualizarUbicacion(location); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; @RequiresApi(api = Build.VERSION_CODES.M) private void miUbicacion() { if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission .ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // Activity#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for Activity#requestPermissions for more details. return; } LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); actualizarUbicacion(location); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,15000,0,locListener); } }
true
79d17eae239111240d5e94db6a7a8cc68d55cc1d
Java
diogoleitao/pava-reprise
/GenericFunctions/src/ist/meic/pa/GenericFunctions/GenericFunction.java
UTF-8
3,676
3.171875
3
[ "MIT" ]
permissive
package ist.meic.pa.GenericFunctions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; /** * The GenericFunction class */ public class GenericFunction { /** The function's name. */ private String name; /** The exception message. */ private static String EXCEPTION_MESSAGE = "No methods for generic function %s with args %s of classes %s."; /** The main methods. */ private ArrayList<GFMethod> mainMethods = new ArrayList<>(); /** The before methods */ private ArrayList<GFMethod> befores = new ArrayList<>(); /** The after methods. */ private ArrayList<GFMethod> afters = new ArrayList<>(); public GenericFunction(String name) { this.name = name; } public String getName() { return this.name; } public void addMethod(GFMethod gfm) { this.mainMethods.add(gfm); } public void addAfterMethod(GFMethod gfm) { this.afters.add(gfm); } public void addBeforeMethod(GFMethod gfm) { this.befores.add(gfm); } /** * The call method will trigger the computation of the effective method. * Once it's done, it will invoke the before methods, then the primary * method, and finally it will invoke the after methods. All the methods are * invoked via Java reflection. If there aren't any applicable primary * methods to a particular set of arguments, an IllegalArgumentException is * thrown. * * The checked exceptions that Java reflection forces us to deal with are * not handled (given the absence of code in the catch block), since the * IllegalAccessException is prevented by making the accessed method public * and the InvocationTargetException is also avoided, since the receiver * object has always the same type (same class) and the arguments are * checked by the StandardCombination class. * * @param args: * the call arguments * @return the object */ public Object call(Object... args) { Object returnedObject = null; ArrayList<Class<?>> parameterTypes = new ArrayList<>(); for (Object arg : args) parameterTypes.add(arg.getClass()); EffectiveMethod effectiveMethod = new StandardCombination().computeEffectiveMethod(new ArrayList<>(this.befores), new ArrayList<>(this.mainMethods), new ArrayList<>(this.afters), new ArrayList<>(Arrays.asList(args))); if (effectiveMethod.getMainMethods().isEmpty()) throw new IllegalArgumentException(String.format(EXCEPTION_MESSAGE, getName(), Utils.listify(args), Utils.getTypesFromArgs(args))); for (GFMethod before : effectiveMethod.getBefores()) { Method[] declaredMethods = before.getClass().getDeclaredMethods(); for (Method method : declaredMethods) { method.setAccessible(true); if (method.getName().equals("call")) { try { method.invoke(before, args); } catch (IllegalAccessException | InvocationTargetException e) {} } } break; } Method mainMethod = effectiveMethod.getMainMethods().get(0).getClass().getDeclaredMethods()[0]; mainMethod.setAccessible(true); if (mainMethod.getName().equals("call")) { try { returnedObject = mainMethod.invoke(effectiveMethod.getMainMethods().get(0), args); } catch (IllegalAccessException |InvocationTargetException e) {} } for (GFMethod after : effectiveMethod.getAfters()) { Method[] declaredMethods = after.getClass().getDeclaredMethods(); for (Method method : declaredMethods) { method.setAccessible(true); if (method.getName().equals("call")) { try { method.invoke(after, args); } catch (IllegalAccessException | InvocationTargetException e) {} } } break; } return returnedObject; } }
true
a4f11fbe109258a70f0f0dbe2aa8c1616fd06c9f
Java
BenigiGarda/EzyFood
/main/java/com/example/ezyfood/DrinkAdapter.java
UTF-8
2,463
2.390625
2
[]
no_license
package com.example.ezyfood; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class DrinkAdapter extends RecyclerView.Adapter<DrinkAdapter.ViewHolder> { DrinkData[] drinkData; Context context; public DrinkAdapter(DrinkData[] drinkData, DrinksPage drinksPage) { this.drinkData = drinkData; this.context = drinksPage; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.drinks_menu, parent, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final DrinkData drinkDatalist = drinkData[position]; holder.imageView.setImageResource(drinkDatalist.getDrinkimage()); holder.textView1.setText(drinkDatalist.getDrinkname()); holder.textView2.setText("Rp." + drinkDatalist.getDrinkprice()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,Detail.class); intent.putExtra("image", drinkDatalist.getDrinkimage()); intent.putExtra("name", drinkDatalist.getDrinkname()); intent.putExtra("price",drinkDatalist.getDrinkprice()); context.startActivity(intent); } }); } @Override public int getItemCount() { return drinkData.length; } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView textView1, textView2; public ViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.imagedrink); textView1 = itemView.findViewById(R.id.drink_name); textView2 = itemView.findViewById(R.id.drink_price_menu); } } }
true
7ff3592bbb90ad9741efd2fc36caf74b12dc7de0
Java
b0erseun/csvlib
/src/com/cronjes/Main.java
UTF-8
1,021
2.890625
3
[]
no_license
package com.cronjes; import com.cronjes.csvlib.reader.CsvReader; import com.cronjes.csvlib.reader.CsvReaderBuilder; import java.io.FileNotFoundException; import java.io.IOException; import java.time.LocalDate; import java.util.List; public class Main { public static void main(String[] args) throws FileNotFoundException { // write your code here CsvReader<PersonM> peopleReader = new CsvReaderBuilder<>(PersonM.class) .withFilePath("c:/csvlibtest/people.txt") .withCustomDeserializer(new LocalDateDeserializer()) .withHasHeaderRow() .build(); try { List<PersonM> people = peopleReader.readCsvFile(); people.stream() .filter(p -> p.getDateOfBirth().isBefore(LocalDate.of(2001, 01, 01 ))) .forEach(p -> System.out.println(p.toString())); } catch (IOException ioex) { System.out.println("Could not read the file."); } } }
true
bafa0798a4148cfa3c9330993ba5b4486d6cbd6b
Java
tingley/globalsight
/main6/ling/com/globalsight/ling/tm3/core/MultilingualSharedTm.java
UTF-8
882
2.390625
2
[]
no_license
package com.globalsight.ling.tm3.core; class MultilingualSharedTm<T extends TM3Data> extends BaseTm<T> implements TM3SharedTm<T> { private long sharedStorageId; // Empty constructor for Hibernate MultilingualSharedTm() { } MultilingualSharedTm(long sharedStorageId, TM3DataFactory<T> factory) { super(factory); this.sharedStorageId = sharedStorageId; } @Override protected StorageInfo<T> createStorageInfo() { return new MultilingualSharedStorageInfo<T>(this); } @Override public TM3TmType getType() { return TM3TmType.MULTILINGUAL_SHARED; } @Override public long getSharedStorageId() { return sharedStorageId; } private void setSharedStorageId(long sharedStorageId) { this.sharedStorageId = sharedStorageId; } }
true
70786e2663e8d1a003c6463bbe37ba5c2e29d577
Java
michaelmernin/SkillsMatrixProto
/src/main/java/prototype_skills/prototypeskills/DAO/CategorySkillRepository.java
UTF-8
953
2.171875
2
[]
no_license
package prototype_skills.prototypeskills.DAO; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import prototype_skills.prototypeskills.Entities.CategorySkill; import prototype_skills.prototypeskills.Entities.Skill; import java.util.Collection; public interface CategorySkillRepository extends Neo4jRepository<CategorySkill, Long> { CategorySkill findByName(String name); //returns the category of a skill @Query("MATCH (:SKILL {name: {skillName}})-[r:SKILL_OF_CATEGORY]->(cs:CATEGORY) RETURN cs") CategorySkill findCategoryBySkill(@Param("skillName") String skillName); //returns list of category skills tree for a BU @Query("MATCH (cs:Category)<-[r:CATEGORY_BU_SKILL]-(e:BusinessUnit {name: {buName}}) RETURN s") Collection<CategorySkill> buSkillsList(@Param("buName") String buName); }
true
fc11aac7bee6a2ade8f0c2201c7628f56e4ec03e
Java
lilinsheng/p2p
/p2p-core/src/main/java/cn/wolfcode/p2p/business/query/TransferQueryObject.java
UTF-8
345
1.757813
2
[]
no_license
package cn.wolfcode.p2p.business.query; import cn.wolfcode.p2p.base.query.QueryObject; import lombok.Getter; import lombok.Setter; /** * 债权转让查询条件 */ @Setter @Getter public class TransferQueryObject extends QueryObject{ //转让人id private Long toLoginInfoId; //债权标状态 private Integer state = -1; }
true
530e395b08247b394b6cb4170d3b511a25020188
Java
cmrmain27/Assignment-4
/Program 4/src/Program4/MyList.java
UTF-8
2,087
3.625
4
[]
no_license
/* * INFO I-211/CSCI C-202 * MyList.java * Purpose: This program is designed to read in a dictionary as a Linked List * according the first letters of each word, read in a file, check to see if * each word in the file is found in the dictionary, and increments counters * depending on words found, words not found, comparisons found, and * comparisons not found. This program applies the use of LinkedLists to a * real world problem. * * Dr. Hettiarachchi * Cody Main * October 21-25, 2016 */ package Program4; /* DO NOT CHANGE THIS CODE */ public interface MyList<E> { /** Add a new element at the end of this list */ public void add(E e); /** Add a new element at the specified index in this list */ public void add(int index, E e); /** Clear the list */ public void clear(); /** Return true if this list contains the element */ public boolean contains(E e); /** Return true and increment count if this list contains the element */ public boolean contains(E e, int[] count); /** Return the element from this list at the specified index */ public E get(int index); /** Return the index of the first matching element in this list. * Return -1 if no match. */ public int indexOf(E e); /** Return true if this list contains no elements */ public boolean isEmpty(); /** Return the index of the last matching element in this list * Return -1 if no match. */ public int lastIndexOf(E e); /** Remove the first occurrence of the element o from this list. * Shift any subsequent elements to the left. * Return true if the element is removed. */ public boolean remove(E e); /** Remove the element at the specified position in this list * Shift any subsequent elements to the left. * Return the element that was removed from the list. */ public E remove(int index); /** Replace the element at the specified position in this list * with the specified element and returns the new set. */ public E set(int index, E e); /** Return the number of elements in this list */ public int size(); }
true
15e22e90ecdd9f1220789f6a2f80f5ebacf6b26e
Java
ty850454/S-S
/core/src/main/java/com/dreammakerteam/ss/core/dao/api/UserRepository.java
UTF-8
435
1.757813
2
[ "MIT" ]
permissive
package com.dreammakerteam.ss.core.dao.api; import com.dreammakerteam.ss.core.dao.entity.UserDO; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface UserRepository extends JpaRepository<UserDO, Long> { /** * 通过微信openId获取用户 * * @param openId 微信openId * @return 用户 */ Optional<UserDO> getByOpenId(String openId); }
true
f952765d338eb1de273d5d42563dc2f5d2eeab03
Java
nut-hatch/LOVBench
/lovbench-dataset/src/main/java/experiment/model/query/enums/TypeFilter.java
UTF-8
149
1.875
2
[ "Apache-2.0" ]
permissive
package experiment.model.query.enums; /** * Lists the possible type filter of term queries. */ public enum TypeFilter { CLASS, PROPERTY }
true
51adccbe6b4e41b3b1c17fd6bf007a1fcbcfeaec
Java
EmilianoBazanZapata/Segundo-Parcial-de-Laboratorio
/ParcialLaboratorioIV/src/java/Servlets/Socios/Actividad_x_Socio.java
UTF-8
1,652
2.34375
2
[]
no_license
/* * 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 Servlets.Socios; import Clases.Actividad; import Gestor.GestorActividad; import java.io.IOException; import java.io.PrintWriter; import static java.lang.System.out; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Emiliano */ @WebServlet(name = "Actividad_x_Socio", urlPatterns = {"/Actividad_x_Socio"}) public class Actividad_x_Socio extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.parseInt(request.getParameter("id")); GestorActividad g = new GestorActividad(); ArrayList<Actividad> lista = g.ObtenerActividades(); request.setAttribute("Actividades", lista); request.setAttribute("IdSocio", id); RequestDispatcher rd = getServletContext().getRequestDispatcher("/ActividadporSocio.jsp"); rd.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
a8748371ce64dc4df758b7e1f5a2d47718e00f8d
Java
tnyeanderson/heart-sms-android
/app/src/test/java/xyz/heart/sms/shared/util/SetUtilsTest.java
UTF-8
1,624
2.765625
3
[ "Apache-2.0" ]
permissive
package xyz.heart.sms.shared.util; import org.junit.Test; import java.util.HashSet; import java.util.Set; import xyz.heart.sms.MessengerSuite; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SetUtilsTest extends MessengerSuite { @Test public void shouldStringifyDoesntGiveOrder() { Set<String> set = new HashSet<>(); set.add("test 1"); set.add("test 2"); String result = SetUtils.INSTANCE.stringify(set); assertTrue(result.contains("test 1")); assertTrue(result.contains("test 2")); assertEquals("", result.replace("test 1", "").replace("test 2", "").replace(",", "")); } @Test public void shouldStringifyEmptySet() { Set<String> set = new HashSet<>(); assertEquals("", SetUtils.INSTANCE.stringify(set)); } @Test public void shouldStringifyNullSet() { Set<String> set = null; assertEquals("", SetUtils.INSTANCE.stringify(set)); } @Test public void shouldCreateSet() { String str = "test 1,test 2"; Set<String> set = SetUtils.INSTANCE.createSet(str); assertTrue(set.contains("test 1")); assertTrue(set.contains("test 2")); set.remove("test 1"); set.remove("test 2"); assertEquals(0, set.size()); } @Test public void shouldCreateSetFromEmptyString() { assertEquals(0, SetUtils.INSTANCE.createSet("").size()); } @Test public void shouldCreateSetFromNullString() { assertEquals(0, SetUtils.INSTANCE.createSet(null).size()); } }
true
2a3f79cd2527c3c07169133c9fc57cf5b62a3f24
Java
mmalashchonak/hospital-appointment-javafx
/src/com/stormnet/dentapp/client/controllers/registration/ClientRegistrationController.java
UTF-8
2,299
2.34375
2
[]
no_license
package com.stormnet.dentapp.client.controllers.registration; import com.stormnet.dentapp.client.common.AppWindows; import com.stormnet.dentapp.client.common.Controller; import com.stormnet.dentapp.client.common.WindowConfigs; import com.stormnet.dentapp.client.exceptions.LoginIsAlreadySetException; import com.stormnet.dentapp.bo.Client; import com.stormnet.dentapp.clientservice.PersonService; import com.stormnet.dentapp.clientservice.factory.ServiceFactory; import javafx.fxml.FXML; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import java.io.IOException; import java.util.List; public class ClientRegistrationController implements Controller { @FXML private TextField firstName; @FXML private TextField lastName; @FXML private TextField login; @FXML private PasswordField password; public void saveBtnPressed() throws IOException { if (firstName.getText().equals("") || lastName.getText().equals("") || login.getText().equals("") || password.getText().equals("")) { throw new RuntimeException("Please, fill all fields."); } PersonService<Client> clientService = ServiceFactory.getServiceFactory().getClientService(); List<Client> allClients = clientService.loadAll(); for (Client client : allClients) { String clientLogin = client.getLogin(); if (login.getText().equals(clientLogin)) { throw new LoginIsAlreadySetException(); } } Client client = new Client(); client.setFirstName(firstName.getText()); client.setLastName(lastName.getText()); client.setLogin(login.getText()); client.setPassword(password.getText()); clientService.save(client); AppWindows.getInstance().hideWindow(WindowConfigs.ClientRegistrationWindow); AppWindows.getInstance().showWindow(WindowConfigs.ClientLoginWindow); } public void cancelBtnPressed() { AppWindows.getInstance().hideWindow(WindowConfigs.ClientRegistrationWindow); AppWindows.getInstance().showWindow(WindowConfigs.ClientLoginWindow); } @Override public void reloadWindow() { } @Override public void setFormObject(Object object) { } }
true
eeffb0bf8ea24eeca57b587d2347e7868f264906
Java
castronovomartin/ClovinStore
/src/main/java/com/hulk/store/model/BrendCardRequest.java
UTF-8
726
2.078125
2
[]
no_license
package com.hulk.store.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; // TODO: Auto-generated Javadoc /** * Gets the brand card name. * * @return the brand card name */ @Getter /** * Sets the brand card name. * * @param brandCardName the new brand card name */ @Setter /** * To string. * * @return the java.lang. string */ @Builder /** * Instantiates a new brend card request. * * @param brandCardName the brand card name */ @AllArgsConstructor /** * Instantiates a new brend card request. */ @NoArgsConstructor public class BrendCardRequest { /** The brand card name. */ private String brandCardName; }
true
481fb178f536b7af7fd466cf85b7819dbd7ffafc
Java
apache/servicecomb-java-chassis
/core/src/main/java/org/apache/servicecomb/core/provider/consumer/MicroserviceReferenceConfig.java
UTF-8
2,537
1.625
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.core.provider.consumer; import org.apache.servicecomb.core.definition.ConsumerMicroserviceVersionsMeta; import org.apache.servicecomb.core.definition.MicroserviceMeta; import org.apache.servicecomb.core.definition.OperationMeta; /** * microservice meta data for consumer. */ public class MicroserviceReferenceConfig { private final String appId; private final String microserviceName; private final ConsumerMicroserviceVersionsMeta microserviceVersionsMeta; private final MicroserviceMeta microserviceMeta; public MicroserviceReferenceConfig( String appId, String microserviceName, ConsumerMicroserviceVersionsMeta microserviceVersionsMeta, MicroserviceMeta microserviceMeta) { this.appId = appId; this.microserviceName = microserviceName; this.microserviceVersionsMeta = microserviceVersionsMeta; this.microserviceMeta = microserviceMeta; } public MicroserviceMeta getMicroserviceMeta() { if (microserviceMeta == null) { throw new IllegalStateException( String.format( "Probably invoke a service before it is registered, or no instance found for it, appId=%s, name=%s.", appId, microserviceName)); } return microserviceMeta; } public ReferenceConfig createReferenceConfig(OperationMeta operationMeta) { return createReferenceConfig(null, operationMeta); } public ReferenceConfig createReferenceConfig(String transport, OperationMeta operationMeta) { if (transport == null) { transport = operationMeta.getConfig().getTransport(); } final ReferenceConfig referenceConfig = new ReferenceConfig(transport); return referenceConfig; } }
true
5d09021101d29d7c5539c0291a8c00a1bcdc0f1f
Java
igormzk/Avaliacao
/Avaliacao/src/br/com/avaliacao/controller/db/GradeDAO.java
ISO-8859-1
4,321
2.640625
3
[]
no_license
package br.com.avaliacao.controller.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import br.com.avaliacao.model.Course; import br.com.avaliacao.model.Grade; import br.com.avaliacao.model.Student; /** * Classe de Data Access Object (objeto de acesso a dados). * Utilizar para realizar as operaes no banco de dados. * @author Igor Muzeka * @version 1.0 */ public class GradeDAO implements DAO<Grade> { private Connection con; public GradeDAO() { con = ConnectionFactory.open(); } @Override public int save(Grade obj) { String sql = obj.getId() == null ? "INSERT INTO grade (id_student, grade_1, grade_2, grade_3, grade_4, id_course) VALUES (?, ?, ?, ?, ?, ?)" : "UPDATE grade SET id_student = ?, grade_1 = ?, grade_2 = ?, grade_3 = ?, grade_4 = ?, id_course = ? WHERE id = ?"; int result = -1; try { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setInt(1, obj.getStudent().getId()); ps.setBigDecimal(2, obj.getGrade1()); ps.setBigDecimal(3, obj.getGrade2()); ps.setBigDecimal(4, obj.getGrade3()); ps.setBigDecimal(5, obj.getGrade4()); ps.setInt(6, obj.getCourse().getId()); if (obj.getId() != null) { ps.setInt(7, obj.getId()); } ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { result = rs.getInt(1); } ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionFactory.close(); } return result; } @Override public int delete(int id) { String sql ="DELETE FROM grade WHERE id = ?"; int result = -1; try { PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, id); result = ps.executeUpdate(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionFactory.close(); } return result; } @Override public Grade load(int id) { Grade g = null; String sql = "SELECT g.*, s.name name_student, c.name name_course, c.credit FROM student s INNER JOIN grade g ON s.id = g.id_student LEFT JOIN course c ON c.id = g.id_course WHERE g.id = ?"; try { PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { g = new Grade(); g.setId(rs.getInt("id")); g.setGrade1(rs.getBigDecimal("grade_1")); g.setGrade2(rs.getBigDecimal("grade_2")); g.setGrade3(rs.getBigDecimal("grade_3")); g.setGrade4(rs.getBigDecimal("grade_4")); Student s = new Student(); s.setId(rs.getInt("s.id_student")); s.setName(rs.getString("name_student")); g.setStudent(s); Course c = new Course(); c.setId(rs.getInt("id_course")); c.setName(rs.getString("name_course")); c.setCredit(rs.getInt("credit")); g.setCourse(c); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionFactory.close(); } return g; } @Override public List<Grade> load() { List<Grade> list = new ArrayList<Grade>(); String sql = "SELECT g.*, s.name name_student, c.name name_course, c.credit FROM student s INNER JOIN grade g ON s.id = g.id_student LEFT JOIN course c ON c.id = g.id_course"; try { PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { Grade g = new Grade(); g.setId(rs.getInt("id")); g.setGrade1(rs.getBigDecimal("grade_1")); g.setGrade2(rs.getBigDecimal("grade_2")); g.setGrade3(rs.getBigDecimal("grade_3")); g.setGrade4(rs.getBigDecimal("grade_4")); Student s = new Student(); s.setId(rs.getInt("id_student")); s.setName(rs.getString("name_student")); g.setStudent(s); Course c = new Course(); c.setId(rs.getInt("id_course")); c.setName(rs.getString("name_course")); c.setCredit(rs.getInt("credit")); g.setCourse(c); list.add(g); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionFactory.close(); } return list; } }
true
ef0e9129ed4c7990efab212c70fcf65f1d440306
Java
thanhnh1806/MoMoTaxi
/User/src/main/java/bhtech/com/cabbytaxi/FavouriteDriver/FavouriteDriverAdapter.java
UTF-8
6,018
2.234375
2
[]
no_license
package bhtech.com.cabbytaxi.FavouriteDriver; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import com.daimajia.swipe.SimpleSwipeListener; import com.daimajia.swipe.SwipeLayout; import com.daimajia.swipe.adapters.BaseSwipeAdapter; import java.util.ArrayList; import bhtech.com.cabbytaxi.R; import bhtech.com.cabbytaxi.object.CarDriverObj; import bhtech.com.cabbytaxi.object.ContantValuesObject; import bhtech.com.cabbytaxi.services.NetworkServices; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by tuanla on 3/3/2016. */ public class FavouriteDriverAdapter extends BaseSwipeAdapter { private Context context; private ArrayList<CarDriverObj> list = new ArrayList<>(); private FavouriteDriverInterface.Listener listener; private FavouriteDriverInterface.Datasource datasource; public FavouriteDriverAdapter(Context context, ArrayList<CarDriverObj> list, FavouriteDriverInterface.Listener listener, FavouriteDriverInterface.Datasource datasource) { this.context = context; this.list = list; this.listener = listener; this.datasource = datasource; } @Override public int getSwipeLayoutResourceId(int position) { return R.id.swipe; } TextView tvNameDriver1, tvNameDriver2; TextView tvCarNumber1, tvCarNumber2; CircleImageView imgDriver; RatingBar rateBar; Button btnCall, btnMail, btnDel; LinearLayout layout_item_one, layout_item_two; @Override public View generateView(int position, ViewGroup parent) { View v = LayoutInflater.from(context).inflate(R.layout.favourite_driver_item, null); tvNameDriver1 = (TextView) v.findViewById(R.id.tv_nameDriver1); tvNameDriver2 = (TextView) v.findViewById(R.id.tv_nameDriver2); tvCarNumber1 = (TextView) v.findViewById(R.id.tv_carmuner1); tvCarNumber2 = (TextView) v.findViewById(R.id.tv_carmuner2); imgDriver = (CircleImageView) v.findViewById(R.id.img_driver); btnCall = (Button) v.findViewById(R.id.btn_phone_favourite_driver); btnMail = (Button) v.findViewById(R.id.btn_mail_favourite_driver); btnDel = (Button) v.findViewById(R.id.btn_del_favourite_driver); rateBar = (RatingBar) v.findViewById(R.id.rate_driver); layout_item_one = (LinearLayout) v.findViewById(R.id.layout_item_one); layout_item_two = (LinearLayout) v.findViewById(R.id.layout_item_two); SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position)); swipeLayout.addSwipeListener(new SimpleSwipeListener() { @Override public void onStartOpen(SwipeLayout layout) { super.onStartOpen(layout); } @Override public void onOpen(SwipeLayout layout) { } @Override public void onStartClose(SwipeLayout layout) { super.onStartClose(layout); } @Override public void onClose(SwipeLayout layout) { super.onClose(layout); } @Override public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) { super.onUpdate(layout, leftOffset, topOffset); } @Override public void onHandRelease(SwipeLayout layout, float xvel, float yvel) { super.onHandRelease(layout, xvel, yvel); } }); return v; } @Override public void fillValues(final int position, View convertView) { CarDriverObj obj = list.get(position); if (obj != null) { tvNameDriver1.setText(obj.getDriver().getFullName()); tvNameDriver2.setText(obj.getDriver().getFullName()); tvCarNumber1.setText("Taxi " + obj.getCar().getNumber()); tvCarNumber2.setText("Taxi " + obj.getCar().getNumber()); rateBar.setRating(obj.getDriver().getRate()); if (obj.getDriver().getPhoto() != null) { NetworkServices.imageRequest(context, ContantValuesObject.DOMAIN_IMAGE + obj.getDriver().getPhoto(), new NetworkServices.MakeImageRequestFinish() { @Override public void Success(Bitmap bitmap) { imgDriver.setImageBitmap(bitmap); } @Override public void Failure(bhtech.com.cabbytaxi.object.Error error) { } }); } } btnCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datasource.setListViewPositionClick(position); listener.onListViewIconPhoneClick(); } }); btnMail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datasource.setListViewPositionClick(position); listener.onListViewIconEmailClick(); } }); btnDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datasource.setListViewPositionClick(position); listener.onListViewButtonDeleteClick(); } }); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } }
true
0e27258a174dddd54358b71c3e77c3dae01164ae
Java
RollingSoftware/L2J_HighFive_Hardcore
/l2j_datapack/dist/game/data/scripts/quests/Q00423_TakeYourBestShot/Q00423_TakeYourBestShot.java
UTF-8
4,199
2.0625
2
[ "MIT" ]
permissive
/* * Copyright (C) 2004-2016 L2J DataPack * * This file is part of L2J DataPack. * * L2J DataPack is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J DataPack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q00423_TakeYourBestShot; import quests.Q00249_PoisonedPlainsOfTheLizardmen.Q00249_PoisonedPlainsOfTheLizardmen; import com.l2jserver.gameserver.model.actor.L2Npc; import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; import com.l2jserver.gameserver.model.quest.Quest; import com.l2jserver.gameserver.model.quest.QuestState; import com.l2jserver.gameserver.model.quest.State; /** * Take Your Best Shot (423) * @author Gnacik * @version 2010-06-26 Based on official server Franz */ public class Q00423_TakeYourBestShot extends Quest { // NPCs private static final int BATRACOS = 32740; private static final int JOHNNY = 32744; // Monster private static final int TANTA_GUARD = 18862; // Item private static final int SEER_UGOROS_PASS = 15496; // Misc private static final int MIN_LEVEL = 82; public Q00423_TakeYourBestShot() { super(423, Q00423_TakeYourBestShot.class.getSimpleName(), "Take Your Best Shot!"); addStartNpc(JOHNNY, BATRACOS); addTalkId(JOHNNY, BATRACOS); addFirstTalkId(BATRACOS); addKillId(TANTA_GUARD); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, false); if (st == null) { return null; } String htmltext = event; switch (event) { case "32740.html": case "32740-01.html": case "32744-02.html": case "32744-03.htm": break; case "32744-04.htm": st.startQuest(); break; case "32744-quit.html": st.exitQuest(true); break; default: htmltext = null; break; } return htmltext; } @Override public String onFirstTalk(L2Npc npc, L2PcInstance player) { if (npc.isInsideRadius(96782, 85918, 0, 100, false, true)) { return "32740-ugoros.html"; } return "32740.html"; } @Override public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon) { final QuestState st = getQuestState(killer, false); if ((st != null) && st.isCond(1)) { st.setCond(2, true); } return super.onKill(npc, killer, isSummon); } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, true); String htmltext = getNoQuestMsg(player); if (st == null) { return htmltext; } switch (npc.getId()) { case JOHNNY: switch (st.getState()) { case State.CREATED: final QuestState qs249 = player.getQuestState(Q00249_PoisonedPlainsOfTheLizardmen.class.getSimpleName()); if ((qs249 != null) && qs249.isCompleted() && (player.getLevel() >= MIN_LEVEL)) { htmltext = (st.hasQuestItems(SEER_UGOROS_PASS)) ? "32744-07.htm" : "32744-01.htm"; } else { htmltext = "32744-00.htm"; } break; case State.STARTED: if (st.isCond(1)) { htmltext = "32744-05.html"; } else if (st.isCond(2)) { htmltext = "32744-06.html"; } break; } break; case BATRACOS: switch (st.getState()) { case State.CREATED: htmltext = (st.hasQuestItems(SEER_UGOROS_PASS)) ? "32740-05.html" : "32740-00.html"; break; case State.STARTED: if (st.isCond(1)) { htmltext = "32740-02.html"; } else if (st.isCond(2)) { st.giveItems(SEER_UGOROS_PASS, 1); st.exitQuest(true, true); htmltext = "32740-04.html"; } break; } } return htmltext; } }
true
2dac84eb93c909ada9c5321fdfa58817531d5cba
Java
MiMiBill/zkyslauncher_huizhou
/app/src/main/java/com/muju/note/launcher/view/SpaceItemDecoration.java
UTF-8
1,697
2.53125
3
[]
no_license
package com.muju.note.launcher.view; import android.graphics.Canvas; import android.graphics.Rect; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; /** * 添加间距 */ public class SpaceItemDecoration extends RecyclerView.ItemDecoration { int left; int right; int top; int bottom; public SpaceItemDecoration(int left, int right, int top, int bottom) { this.left = left; this.right = right; this.top = top; this.bottom = bottom; } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.left = left; if (!isLastColum(parent, parent.getChildLayoutPosition(view))) { outRect.right = right; } outRect.top = top; outRect.bottom = bottom; } //判断是最后一列 private boolean isLastColum(RecyclerView parent, int pos) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { GridLayoutManager glm = (GridLayoutManager) layoutManager; if ((pos + 1) % glm.getSpanCount() == 0) { return true; } } return false; } }
true
0a8dcd588ba4fbcdbf7b7e269326ad5a1d01613f
Java
michaelmartak/gladiatorslounge
/JGladiator/framework/src/main/java/org/oaktownrpg/jgladiator/framework/mtg/MtgRarity.java
UTF-8
248
1.882813
2
[]
no_license
/** * */ package org.oaktownrpg.jgladiator.framework.mtg; /** * Card rarity, usually defined within a set (a card's rarity can change) * * @author michaelmartak * */ public enum MtgRarity { COMMON, UNCOMMON, RARE, MYTHIC, SPECIAL }
true
1441d9c79f0cca58e35e771a665eef445c54b374
Java
JAQUELINERT/UNIDAD1
/evaluacionprimera/src/giti7083jaquelinefutbol/Entrenador.java
UTF-8
235
1.65625
2
[]
no_license
/** * */ package giti7083jaquelinefutbol; public class Entrenador extends SeleccionFutbol{ private int idFederacion; public static void planificarEntrenamiento(){ } public Entrenador() { //CONSTRUCTOR DE LA CLASE } }
true
b38dcff8d8123b26ff68efa6a4084e8b559bf7c4
Java
bcdev/s3mpc-isin
/src/test/java/com/bc/s3mpc/isin/ProjectionParamFactoryTest.java
UTF-8
1,940
1.929688
2
[]
no_license
package com.bc.s3mpc.isin; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class ProjectionParamFactoryTest { @Test public void testGetISIN_K() { final ProjectionParam param = ProjectionParamFactory.get(ProjectionType.ISIN_K); assertNotNull(param); assertEquals(ProjectionType.ISIN_K, param.projection); assertISINParams(param); } @Test public void testGetISIN_H() { final ProjectionParam param = ProjectionParamFactory.get(ProjectionType.ISIN_H); assertNotNull(param); assertEquals(ProjectionType.ISIN_H, param.projection); assertISINParams(param); } @Test public void testGetISIN_Q() { final ProjectionParam param = ProjectionParamFactory.get(ProjectionType.ISIN_Q); assertNotNull(param); assertEquals(ProjectionType.ISIN_Q, param.projection); assertISINParams(param); } private void assertISINParams(ProjectionParam param) { assertEquals(-20015109.354, param.ul_xul, 1e-8); assertEquals(10007554.677, param.ul_yul, 1e-8); assertEquals(926.62543305, param.pixel_size, 1e-8); assertEquals(-1, param.sphere_code); assertEquals(6371007.181, param.sphere, 1e-8); assertEquals(1200, param.nl_tile); assertEquals(1200, param.ns_tile); assertEquals(18, param.ntile_line); assertEquals(36, param.ntile_samp); assertEquals(18 * 1200, param.nl_grid); assertEquals(36 * 1200, param.ns_grid); assertArrayEquals(new int[] {90, 540, 1080, 4320}, param.nl_global); assertArrayEquals(new int[] {180, 1080, 2160, 8640}, param.ns_global); assertArrayEquals(new int[] {0, 0, 0, 0}, param.nl_offset); assertArrayEquals(new int[] {0, 0, 0, 0}, param.ns_offset); } }
true
10d469b3a316dd431e678f45fe602793077c0174
Java
chrgu000/other-1
/pdm/src/main/java/com/anosi/asset/dao/jpa/RepairedDeviceDailyPerDao.java
UTF-8
361
1.75
2
[]
no_license
package com.anosi.asset.dao.jpa; import java.util.List; import org.springframework.data.domain.Pageable; import com.anosi.asset.model.jpa.RepairedDeviceDailyPer; public interface RepairedDeviceDailyPerDao extends BaseJPADao<RepairedDeviceDailyPer> { public List<RepairedDeviceDailyPer> findByDevCategoryIdEquals(Long devCategoryId, Pageable pageable); }
true
9b775b04d052757e035c830849643be36e7d0ea4
Java
cedricxs/JavaCode
/Pro/TestWrapAndUnwrap.java
GB18030
481
3.4375
3
[]
no_license
package Pro; /** * ԰ѻתΪദ * ԶװͲ * Object * @author * */ public class TestWrapAndUnwrap { public static void main(String[] args) { Integer i = 10; //Զװ System.out.println(i); Object obj = new Integer(100); int a = (int) obj; //Object->Integer->Զ System.out.println(a); System.out.println(new Integer(new String("979581491".getBytes()))); } }
true
ae3974d13f049e2c8e70f66bed39f1c804b4e0ab
Java
Sigma91/FootballApp
/FootballApp/src/businessService/SportsMetode.java
UTF-8
759
2.453125
2
[]
no_license
package businessService; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import model.Sports; public class SportsMetode { private SessionFactory sf = new Configuration().configure().buildSessionFactory(); private Session session = sf.openSession(); public boolean ubaciSport (String sportsName) { Sports sport = new Sports(); session.beginTransaction(); try { sport.setName(sportsName); session.save(sport); session.getTransaction().commit(); System.out.println("Uspesan unos"); return true; }catch (Exception e) { session.getTransaction().rollback(); System.out.println("Neuspesan unos"); return false; } finally { session.close(); } } }
true
20ac2db9cfc2082089226a3b7b325a2c6886b155
Java
huangsanm/UISample
/app/src/main/java/com/huashengmi/ui/android/ui/view/drag/DragViewActivity.java
UTF-8
3,168
2.296875
2
[]
no_license
package com.huashengmi.ui.android.ui.view.drag; import android.graphics.Rect; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.huashengmi.ui.android.R; import com.huashengmi.ui.android.utils.Globals; import roboguice.activity.RoboActivity; import roboguice.inject.InjectView; public class DragViewActivity extends RoboActivity { @InjectView(R.id.drag_logo) private ImageView mDragImageView; //设备分辨率 private int mScreenWidth; private int mScreenHeight; private int lastX, lastY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drag_view); buildComponent(); } private void buildComponent(){ //状态高度 Rect statusBar = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(statusBar); Globals.log("dddddddddddd:" + statusBar.top); DisplayMetrics dm = getResources().getDisplayMetrics(); mScreenWidth = dm.widthPixels; mScreenHeight = dm.heightPixels - 150; mDragImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE: int dx = (int) event.getRawX() - lastX; int dy = (int) event.getRawY() - lastY; int left = v.getLeft() + dx; int top = v.getTop() + dy; int right = v.getRight() + dx; int bottom = v.getBottom() + dy; // 设置不能出界 if (left < 0) { left = 0; right = left + v.getWidth(); } if (right > mScreenWidth) { right = mScreenWidth; left = right - v.getWidth(); } if (top < 0) { top = 0; bottom = top + v.getHeight(); } if (bottom > mScreenHeight) { bottom = mScreenHeight; top = bottom - v.getHeight(); } v.layout(left, top, right, bottom); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_UP: break; } return true; } }); } }
true
47c28370b4d23f84874400ce556e83f59b503a88
Java
singhakan2635/ImageMangementSystem
/src/main/java/sample/Controller.java
UTF-8
14,179
2.703125
3
[]
no_license
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.FileChooser; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; /** * Controller class implements all the operations which is performed on the Application. * We have to initialise all the FXML elements before we can use them in the method. */ public class Controller implements EditingProperties { @FXML private BorderPane borderPane; @FXML private ChoiceBox choiceBox; @FXML private TextField textWidth; @FXML private TextField textHeight; @FXML private GridPane gridpane; @FXML private Label label_Header; @FXML private Label imageSelected; @FXML private Button ButtonConvert; @FXML private Button ButtonUpload; @FXML private ImageView imageview; /** * All the variables which is required by the class has been initialize here * to have their scope for the entire class. SOme of these variables are being used by * more than one method. In some cases, some of these variables are getting their value * changed by different methods based on their requirements. */ private Image image; private Image imageOrg; private List<File> files; private boolean IsUploadDone; private boolean uploadCheck; private double newImageHeight; private double newImageWidth; private FileInputStream input; /** * Once the Choose the image button is clicked, imageProcessing method is called. * This method first clear the gridpane to make sure it has no previous data. * After that, once the image file is selected from the user computer, it checks for the * file validation by using FileChooser library. * Now based on our requirement, it sets the imageView and textArea to display the * image and the properties of the image. * For displaying the properties of the image it calls the class ExtractMetaData. * If file selection is cancelled then it will show "You have Cancelled the Selection of Image". */ @FXML public void imageProcessing() { String text; String sourcePath; String imageName; gridpane.getChildren().clear(); label_Header.setVisible(true); List<String> properties; int count = 0; FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("Image Files Types", "*.jpeg", "*.png", "*.gif", "*.jpg", "*.mp4") ); files = chooser.showOpenMultipleDialog(borderPane.getScene().getWindow()); if (files != null) { for (int i = 0; i < files.size(); i++) { try { Label textArea = new Label(); File file = files.get(i); int indexX = i % 5; int indexY = i / 5; count++; sourcePath = files.get(i).getPath(); System.out.println("SourcePath is " + sourcePath); imageName = file.getName(); ExtractMetaData extractMetaData = new ExtractMetaData(); properties = extractMetaData.getMataData(file); image = new Image(file.toURI().toString()); input = new FileInputStream(file); imageOrg = image; image = new Image(input); /** *One of the project requirement is to show the thumbnail of the image which has *a dimensions of 100*100 . */ newImageHeight = 100; newImageWidth = 100; imageview = new ImageView(image); imageview.setFitHeight(newImageHeight); imageview.setFitWidth(newImageWidth); /** * Setting up the TextArea with the Image Properties */ if (properties.size() > 0) { text = " Name: " + imageName + "\n" + " Height: " + image.getHeight() + "\n" + " Width: " + image.getWidth() + "\n" + " Longitude: " + properties.get(0) + "\n" + " Latitude: " + properties.get(1) + "\n" + " Date: " + properties.get(2); } else { text = " Name: " + imageName + "\n" + " Height: " + image.getHeight() + "\n" + " Width: " + image.getWidth(); } /** * Setting up the textarea properties of font and style */ textArea.setFont(Font.font("Serif", FontWeight.BOLD, 15)); textArea.setStyle("-fx-text-fill: white ;"); textArea.setText(text); if (count > 5) { indexY += 4; } if (count > 10) { break; } gridpane.add(imageview, indexX, indexY); gridpane.add(textArea, indexX, indexY + 1); uploadCheck = true; } catch (Exception e) { e.printStackTrace(); } } } else { System.out.println("You have Cancelled the Selection of Image"); } } /** * After the user clicks on the convert & save button - this method is invoked. * ConvertImages method take all the new width and new height specified by the * user, including the source path and destination path and convert the image * in the specified format. * @throws IOException */ @FXML public void ConvertImages() throws IOException { /** * Initializing properties i.e new height and new width and implementing convert operation * */ if (uploadCheck) { int width = 0; int height = 0; int newWidth; int newHeight; FileInputStream input; String filePath; String sourcePath; FileChooser chooser = new FileChooser(); File file = chooser.showSaveDialog(borderPane.getScene().getWindow()); for (int i = 0; i < files.size(); i++) { chooser.setInitialFileName(file.getName()); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("Image Files", "*." + choiceBox.getValue()) ); String destinationPath = ""; File imageFile = files.get(i); input = new FileInputStream(imageFile); image = new Image(input); sourcePath = files.get(i).getPath(); try { filePath = file.getPath(); if (files.size() > 1) { destinationPath = filePath.substring(0, filePath.lastIndexOf("/") + 1); destinationPath += imageFile.getName().substring(0, imageFile.getName().lastIndexOf(".")); destinationPath += ("." + choiceBox.getValue().toString()); } else { destinationPath = filePath; destinationPath += ("." + choiceBox.getValue()); } /** * For Converting the Image with new height and new width , also into new format - * We have called the class ConvertImage. We have Instantiated the class with * label and gridpane. Then we will call the method "convert" by passing the parameters * sourcePath, new Width, new Height and the destination path in the user system * to convert the image and save it in the system. * In case the User doesn't specify the new height and width, we will * use the original image width and height to convert the image. */ ConvertImage convertImg = new ConvertImage(label_Header, gridpane); if (textHeight.getText().equals("") && textWidth.getText().equals("")) { width = (int) image.getWidth(); height = (int) image.getWidth(); System.out.println("width: " + width); System.out.println("height: " + height); System.out.println("sourcePath: " + sourcePath); System.out.println("destinationPath: " + destinationPath); convertImg.convert(sourcePath, width, height, destinationPath); } else if ((textHeight.getText().equals("") && !textWidth.getText().equals("")) || (!textHeight.getText().equals("") && textWidth.getText().equals(""))) { IsUploadDone = true; break; } else if (Integer.parseInt(textHeight.getText()) > 10000 || Integer.parseInt(textWidth.getText()) > 10000) { IsUploadDone = true; break; } else { newWidth = Integer.parseInt(textWidth.getText()); newHeight = Integer.parseInt(textHeight.getText()); width = newWidth; height = newHeight; convertImg.convert(sourcePath, width, height, destinationPath); } } catch (Exception e) { System.out.println(e.toString()); } } uploadCheck = false; textWidth.clear(); textHeight.clear(); } else { imageSelected.setText("Please Select an Image to Convert"); imageSelected.setVisible(true); } } /** * ZoomIn Image is implemented from the Interface Editing Properties. * This method increase the image width and image height by 10% * everytime this method is invoked. */ @Override public void zoomInImage() { newImageWidth = newImageHeight * (1.1); newImageHeight = newImageHeight * (1.1); displayImage(); } /** * ZoomOut Image is implemented from the Interface Editing Properties. * This method decreases the image width and image height by 10% * everytime this method is invoked. */ @Override public void zoomOutImage() { newImageWidth = newImageHeight * (0.9); newImageHeight = newImageHeight * (0.9); displayImage(); } /** * Display image Method set the imageview with the new image width and height * based on the changes. */ private void displayImage() { //imageview = new imageview(image); imageview.setFitHeight(newImageWidth); imageview.setFitWidth(newImageHeight); } /** * This is FXML implementation of the method for the ZoomIn button. It calls the method * ZoominImnage, everytime its clicked. */ @FXML public void ZoomIn() { zoomInImage(); } /** * This is FXML implementation of the method for the ZoomOut button. It calls the method * zoomOutImage, everytime its clicked. */ @FXML public void ZoomOut() { zoomOutImage(); } /** * This is FXML implementation of the method for the Rotate button. It calls the method * rotateImage, everytime its clicked. */ public void Rotate(ActionEvent actionEvent) { rotateImage(); } /** * Rotate Image is implemented from the Interface Editing Properties. * This method method will rotate the image to 90 degree * everytime this method is invoked. */ @Override public void rotateImage() { imageview.setRotate(imageview.getRotate() + 90); } /** * Rotate Image is implemented from the Interface Editing Properties. * This method method will rotate the image to 90 degree * everytime this method is invoked. */ @Override public void changeToGrayScale() { ColorAdjust colorAdjust = new ColorAdjust(); colorAdjust.setSaturation(-1); imageview.setEffect(colorAdjust); } /** * This is FXML implementation of the method for the GrayScale button. It calls the method * changeToGrayScale, once its clicked. * @param actionEvent */ public void GreyScale(ActionEvent actionEvent) { changeToGrayScale(); } /** * This is FXML implementation of the method for the Revert button. It calls the method * revertChanges, once its clicked. * @param actionEvent */ public void Revert(ActionEvent actionEvent) { revertChanges(); } /** * Revert Changes is implemented from the Interface Editing Properties. * This method method will revert any changes done to the image * everytime this method is invoked. */ @Override public void revertChanges() { ColorAdjust colorAdjust = new ColorAdjust(); colorAdjust.setSaturation(0); imageview.setImage(imageOrg); imageview.setEffect(colorAdjust); imageview.setFitWidth(100); imageview.setFitHeight(100); } }
true
f99ee7f31728170fb9034ecdead4655d6eb624e6
Java
bellmit/claimcar2
/claimcar-claim/src/main/java/ins/sino/claimcar/interf/vo/DriverVo.java
UTF-8
2,630
2.25
2
[]
no_license
package ins.sino.claimcar.interf.vo; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("Driver") public class DriverVo { /*驾驶员单位或家庭地址*/ @XStreamAlias("Address") private String address; /*年龄*/ @XStreamAlias("DriverAge") private String driverAge; /*驾照类型*/ @XStreamAlias("DriverAllowedVehicleType") private String driverAllowedVehicleType; /*教育程度*/ @XStreamAlias("DriverEducation") private String driverEducation; /*性别*/ @XStreamAlias("DriverGender") private String driverGender; /*颁证机关*/ @XStreamAlias("DriverLicenseInstitution") private String driverLicenseInstitution; /*联系电话*/ @XStreamAlias("DriverTel") private String driverTel; /*初次领证日期*/ @XStreamAlias("DrivingLicenseDate") private String drivingLicenseDate; /*驾驶证号码*/ @XStreamAlias("DrivingLicenseNum") private String drivingLicenseNum; /*驾驶员姓名*/ @XStreamAlias("Name") private String name; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDriverAge() { return driverAge; } public void setDriverAge(String driverAge) { this.driverAge = driverAge; } public String getDriverAllowedVehicleType() { return driverAllowedVehicleType; } public void setDriverAllowedVehicleType(String driverAllowedVehicleType) { this.driverAllowedVehicleType = driverAllowedVehicleType; } public String getDriverEducation() { return driverEducation; } public void setDriverEducation(String driverEducation) { this.driverEducation = driverEducation; } public String getDriverGender() { return driverGender; } public void setDriverGender(String driverGender) { this.driverGender = driverGender; } public String getDriverLicenseInstitution() { return driverLicenseInstitution; } public void setDriverLicenseInstitution(String driverLicenseInstitution) { this.driverLicenseInstitution = driverLicenseInstitution; } public String getDriverTel() { return driverTel; } public void setDriverTel(String driverTel) { this.driverTel = driverTel; } public String getDrivingLicenseDate() { return drivingLicenseDate; } public void setDrivingLicenseDate(String drivingLicenseDate) { this.drivingLicenseDate = drivingLicenseDate; } public String getDrivingLicenseNum() { return drivingLicenseNum; } public void setDrivingLicenseNum(String drivingLicenseNum) { this.drivingLicenseNum = drivingLicenseNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
17fd37aa3ee1cecc15e49c27cb1977a8042e832b
Java
8lueFox/asos
/src/main/java/com/io/usos/services/DokumentyServiceImpl.java
UTF-8
3,214
2.203125
2
[]
no_license
package com.io.usos.services; import com.io.usos.exceptions.ObjectNotFoundException; import com.io.usos.models.Ankieta; import com.io.usos.models.AnkietaOdpowiedz; import com.io.usos.models.Odpowiedz; import com.io.usos.models.Stypendium; import com.io.usos.repositories.*; import javassist.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class DokumentyServiceImpl implements DokumentyService { @Autowired AnkietaRepository ankietaRepository; @Autowired AnkietaOdpowiedzRepository ankietaOdpowiedzRepository; @Autowired AnkietaPytanieRepository ankietaPytanieRepository; @Autowired OdpowiedzRepository odpowiedzRepository; @Autowired StypendiumRepository stypendiumRepository; @Override public Ankieta getAnkieta(int id) { Optional<Ankieta> optionalAnkieta = ankietaRepository.findById(id); Ankieta ankieta = optionalAnkieta.orElseThrow(() -> new ObjectNotFoundException("ankieta",id)); return ankieta; } @Override public List<Ankieta> getAllAnkieta() { return ankietaRepository.findAll(); } @Override public List<Odpowiedz> getAllOdpowiedz() { return odpowiedzRepository.findAll(); } @Override public List<AnkietaOdpowiedz> getAllOdpowiedzi() { return ankietaOdpowiedzRepository.findAll(); } @Override public List<AnkietaOdpowiedz> getAllOdpowiedzi(int id) { return ankietaOdpowiedzRepository.findAllByAnkietaId(id); } @Override public List<Ankieta> getAllMyAnkieta(int id) { return ankietaRepository.findDistinctByPrzedmiot_StudenciId(id); } @Override public void deleteAnkieta(int id) { if (ankietaRepository.existsById(id) == true) { ankietaRepository.deleteById(id); } } @Override public void saveAnkieta(Ankieta ankieta) { ankietaRepository.save(ankieta); } @Override public void saveAnkietaOdpowiedz(AnkietaOdpowiedz ankietaOdpowiedz) { ankietaOdpowiedzRepository.save(ankietaOdpowiedz); } @Override public Stypendium getStypendium(int id) { Optional<Stypendium> optionalStypendium = stypendiumRepository.findById(id); Stypendium stypendium = optionalStypendium.orElseThrow(() -> new ObjectNotFoundException("stypendium",id)); return stypendium; } @Override public List<Stypendium> getAllStypendium() { return stypendiumRepository.findAll(); } @Override public List<Stypendium> getAllStypendiumOld() { return stypendiumRepository.findAllByZatwierdzonyIsTrue(); } @Override public List<Stypendium> getAllMyStypendium(int id) { return stypendiumRepository.findAllByStudent_Id(id); } @Override public void deleteStypendium(int id) { if (stypendiumRepository.existsById(id) == true) { stypendiumRepository.deleteById(id); } } @Override public void saveStypendium(Stypendium stypendium) { stypendiumRepository.save(stypendium); } }
true
dec5997808ecb51e71b640db9dcf3aff138d728a
Java
isratreto4395/GitHubPractice
/src/eashasstuff/Manager.java
UTF-8
5,108
3.15625
3
[]
no_license
package eashasstuff; import java.sql.SQLException; import java.util.Scanner; public class Manager { static Scanner input = new Scanner(System.in); public static void mainMenu() throws SQLException { System.out.println("1- Add Employee"); System.out.println("2- Remove Employee"); System.out.println("3- Update Employee Profile"); int selection = input.nextInt(); switch(selection){ case 1 :{ System.out.println("Enter Employee ID : "); int employeeId = input.nextInt(); System.out.println("Enter First Name : "); String firstName =input.next(); System.out.println("Enter Last Name : "); String lastName =input.next(); System.out.println("Enter Password : "); String passwrd =input.next(); System.out.println("Enter Department : "); String dept =input.next(); System.out.println("Enter Salary : "); int sal= input.nextInt(); String quer = "INSERT INTO `employee` (employee_id, password, first_name, last_name, department, salary) VALUES ('" + employeeId + "','" + passwrd + "','" + firstName + "','" + lastName + "','" + dept + "' , '" + sal + "') "; Config.connect().createStatement().execute(quer); Config.connect().close(); break; } case 2 :{ System.out.println("Enter Employee ID "); int employeeId = input.nextInt(); String quer = "DELETE FROM employee WHERE employee_id = '" + employeeId + "'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is removed from our Database"); Config.connect().close(); break; } case 3 : { System.out.println("Update Employee Profile"); System.out.println("Enter Employee ID: "); int employeeId = input.nextInt(); System.out.println("1- Update First Name : "); System.out.println("2- Update Last Name : "); System.out.println("3- Update Password : "); System.out.println("4- Update Department : "); System.out.println("5- Update Salary : "); int selection1 = input.nextInt(); if (selection1 == 1) { System.out.println("Enter First Name : "); String firstName = input.next(); String quer = "UPDATE employee SET first_name = '" + firstName + "' WHERE employee_id='" + employeeId + "'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is successfully upated"); Config.connect().close(); break; } if (selection1 == 2) { System.out.println("Enter Last Name : "); String lastName = input.next(); String quer = "UPDATE employee SET last_name = '" + lastName + "' WHERE employee_id='" + employeeId +"'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is successfully updated"); Config.connect().close(); break; } if (selection1 == 3) { System.out.println("Enter Password : "); String passwrd = input.next(); String quer = "UPDATE employee SET password = '" + passwrd + "' WHERE employee_id='" + employeeId + "'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is successfully updated"); Config.connect().close(); break; } if (selection1 == 4){ System.out.println("Enter Department : "); String dept = input.next(); String quer = "UPDATE employee SET department = '" + dept + "' WHERE employee_id='" + employeeId + "'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is successfully updated"); Config.connect().close(); break; } if(selection1 ==5){ System.out.println("Enter salary : "); int sal = input.nextInt(); String quer = "UPDATE employee SET salary = '" + sal + "' WHERE employee_id='" + employeeId + "'"; Config.connect().createStatement().execute(quer); System.out.println("Employee is successfully updated"); Config.connect().close(); break; } } break; } } }
true
1cb1f3694e09ef3233bdfa7e800781584d79b8c4
Java
KTLeYing/springboot-learning-1
/springboot的消息队列(用RabbitMQ、ActiveMQ和Kafka)/RabbitMQ实现/模板2(rabbitmq-demo2项目用到)/rabbitmq-demo2/src/main/java/com/mzl/rabbitmqdemo2/entity/Book.java
UTF-8
501
1.898438
2
[]
no_license
package com.mzl.rabbitmqdemo2.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @ClassName : Book * @Description: 书本实体类 * @Author: mzl * @CreateDate: 2020/10/20 19:53 * @Version: 1.0 */ @Data @AllArgsConstructor @NoArgsConstructor public class Book implements Serializable { public static final long serialVersionUID = -2164058270260403154L; private Integer id; private String name; }
true
639916d82ad248189800fbc733f072e8b8b1fe7c
Java
ankushd85/hello-world-rest
/src/main/java/com/org/app/controller/RESTDemoInfoController.java
UTF-8
738
2.296875
2
[]
no_license
package com.org.app.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author pfe456 * Main Controller for root url to provide info */ @RestController public class RESTDemoInfoController { /** * This method provides info to user on root url * @return * String message */ @GetMapping("/") public ResponseEntity<String> getInfo(){ return new ResponseEntity<String>("<html><body><h2>" + "Please visit <a href='https://github.com/ankushd85/hello-world-rest'>Here</a> "+ " for more info </h2></body></html>", HttpStatus.OK); } }
true
0ba0ccd2d0ed28c05506d40a00c9c72ae5e2332d
Java
mikuluna/Design-patterns
/02-Structural Patterns/Decorator Pattern/src/com/luna/decorator/impl/Vest.java
UTF-8
331
2.375
2
[]
no_license
package com.luna.decorator.impl; import com.luna.decorator.Player; import com.luna.decorator.PlayerDecorator; /** * 防弹衣 */ public class Vest extends PlayerDecorator { public Vest(Player player) { super(player); } @Override public String equip(){ return super.equip()+"+防弹衣"; } }
true
997b79440eae9f86efa794ae6169e26512599dba
Java
if-050java/ATM_Locator
/src/main/java/com/ss/atmlocator/entity/AtmNetwork.java
UTF-8
927
2.3125
2
[]
no_license
package com.ss.atmlocator.entity; import org.codehaus.jackson.annotate.JsonIgnore; import javax.persistence.*; import java.util.Set; /** * Created by Olavin on 18.11.2014. */ @Entity @Table(name="atmnetworks") public class AtmNetwork { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column private String name; /* @JsonIgnore //Ignoring this field in JSON serializing @OneToMany(cascade = CascadeType.ALL, mappedBy = "network", fetch = FetchType.LAZY) private Set<Bank> Banks; */ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } /* public Set<Bank> getBanks() { return Banks; } public void setBanks(Set<Bank> banks) { Banks = banks; } */ }
true
019321f9ff3329f3c3e49fafb157c90276365c54
Java
Li-jiabing/JavaSE
/src/com/company/day01_02_03/OperatorTest01.java
UTF-8
1,905
4.46875
4
[]
no_license
package com.company.day01_02_03; /** * 关于java编程中运算符之:算数运算符 * + 加 * - 减 * * 乘 * / 除 * % 取模 * ++ 自加1 * -- 自减1 * * 注意:一个表达式中有多个运算符,运算符有优先级,不确定的加小括号,优先级得到提升 */ public class OperatorTest01 { public static void main(String[] args) { int i = 10; int j = 3; System.out.println(i+j);//13 System.out.println(i-j);//7 System.out.println(i*j);//30 System.out.println(i/j);//3 System.out.println(i%j);//1 //以下以++为例,--自学 //关于++运算符【自加1】 int k = 10; //++运算符可以出现在变量后面【单目运算符】 k++; System.out.println(k); int y = 10; //++运算副可以出现在变量前面[单目运算符] ++y; System.out.println(y);//11 /** * 小结:++运算符可以出现在变量前,也可以出现在变量后,无论是变量前还是变量后,只要++运算结束,该变量中的值一定会自加1 */ //++出现在变量后 int a = 100; int b = a++;//++出现在变量后面,先赋值再运算 System.out.println(a);//101 System.out.println(b);//100 //++出现在变量前 //规则:先进行自加1运算,然后再进行赋值操作 int c = 100; System.err.println(c); int d = ++c; System.err.println(c);//101 System.err.println(d);//101 int xx = 500; System.out.println(xx++);//500 System.out.println(xx);//501 int s = 100; System.out.println(++s);//101 System.out.println(s);//101 } }
true
c22d31e5722e76c21a2712c357abd39bfaff83b5
Java
jonathansantana19/projetos
/TesteJSFPRIMAFACES/src/GuicheController.java
UTF-8
1,657
2.25
2
[]
no_license
import java.io.Serializable; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ViewScoped @ManagedBean public class GuicheController implements Serializable { /** * */ private static final long serialVersionUID = 1L; private List<GuicheVO> lista; private GuicheVO guiche; private String dataHora; @PostConstruct public void init(){ System.out.println("iniciando"); GuicheVO obj = new GuicheVO(); lista = new ArrayList<GuicheVO>(); guiche = new GuicheVO(); obj.setNomePaciente("Anderson"); obj.setSala("Ambulatorio3"); lista.add(obj); obj.setNomePaciente("Carlos"); obj.setSala("Ambulatorio1"); lista.add(obj); obj.setNomePaciente("Fernando"); obj.setSala("Sala2"); lista.add(obj); LocalDateTime agora = LocalDateTime.now(); DateTimeFormatter formatador = DateTimeFormatter. ofLocalizedDateTime(FormatStyle.SHORT).withLocale(new Locale("pt", "br")); // agora.format(formatador); //08/04/14 10:02 dataHora = agora.format(formatador); } public List<GuicheVO> getLista() { return lista; } public void setLista(List<GuicheVO> lista) { this.lista = lista; } public GuicheVO getGuiche() { return guiche; } public void setGuiche(GuicheVO guiche) { this.guiche = guiche; } public String getDataHora() { return dataHora; } public void setDataHora(String dataHora) { this.dataHora = dataHora; } }
true
03bf313edf3d49f064c13283e10c287147e5b685
Java
tfisher1226/ARIES
/bookshop2/bookshop2-seller/bookshop2-seller-service/src/main/java/bookshop2/seller/SellerProcessMBean.java
UTF-8
197
1.601563
2
[ "Apache-2.0" ]
permissive
package bookshop2.seller; import javax.management.MXBean; @MXBean public interface SellerProcessMBean { public static final String MBEAN_NAME = "bookshop2.buyer:name=SellerProcessMBean"; }
true
53330a949020acbc4cd77de46b04f64a5c579fd7
Java
DeepaMalviya/OfficeProject
/app/src/main/java/com/daffodil/officeproject/SplashModule/SplashActivity.java
UTF-8
9,793
1.835938
2
[]
no_license
package com.daffodil.officeproject.SplashModule; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Handler; import android.support.annotation.NonNull; import androidx.core.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.TextView; import com.daffodil.officeproject.HomeModule.Main2Activity; import com.daffodil.officeproject.LoginModule.LoginnActivity; import com.daffodil.officeproject.R; public class SplashActivity extends AppCompatActivity { private static final String TAG = "SplashActivity"; /** * Duration of wait **/ private final int SPLASH_DISPLAY_LENGTH = 1000; private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0; private TextView loading_tv2; private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 999; private TelephonyManager mTelephonyManager; private String userid, imei; SharedPreferences sharedpref; int PERMISSION_ALL = 1; /* String[] PERMISSIONS = { android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA };*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.splashScreenTheme); setContentView(R.layout.activity_splash); // Log.e(TAG, "onCreate:-===== "+!hasPermissions(this, PERMISSIONS) ); /* if (!hasPermissions(this, PERMISSIONS)) { ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL); }*/ initView(); } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { /* if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) { // Received permission result for READ_PHONE_STATE permission.est."); // Check if the only required permission has been granted if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number //alertAlert(getString(R.string.permision_available_read_phone_state)); //doPermissionGrantedStuffs(); } else { alertAlert("permissions_not_granted_read_phone_state"); } } if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) { // Received permission result for READ_PHONE_STATE permission.est."); // Check if the only required permission has been granted if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number //alertAlert(getString(R.string.permision_available_read_phone_state)); //doPermissionGrantedStuffs(); } else { alertAlert("permissions_not_granted_read_phone_state"); } }*/ /* if (requestCode == PERMISSIONS_REQUEST_READ_PHONE_STATE && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getDeviceImei(); } *//*if (requestCode == PERMISSION_ALL && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getDeviceImei(); }*/ } public static boolean hasPermissions(Context context, String... permissions) { if (context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } private void alertAlert(String msg) { new AlertDialog.Builder(SplashActivity.this) .setTitle("Permission Request") .setMessage(msg) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do somthing here } }) // .setIcon(R.drawable.onlinlinew_warning_sign) .show(); } String mobile, time_in, time_out, user_id, otp, user_role, user_name, company_id, company_name; private void initView() { Log.e(TAG, "initView: "); sharedpref = getSharedPreferences("opark", Context.MODE_PRIVATE); mobile = sharedpref.getString("mobile", ""); user_id = sharedpref.getString("user_id", ""); otp = sharedpref.getString("otp", ""); user_role = sharedpref.getString("user_role", ""); user_name = sharedpref.getString("user_name", ""); company_id = sharedpref.getString("company_id", ""); company_name = sharedpref.getString("company_name", ""); Log.e(TAG, "initView:user_id" + user_id); time_in = sharedpref.getString("time_in", ""); time_out = sharedpref.getString("time_out", ""); Log.e(TAG, "initView:time_in " + time_in); Log.e(TAG, "initView:time_out " + time_out); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSIONS_REQUEST_READ_PHONE_STATE); Log.e(TAG, "initView: if permission"); } else { Log.e(TAG, "initView: else permission"); getDeviceImei(); } } new Handler().postDelayed(new Runnable() { @Override public void run() { try { if (user_id.equals("")) { Log.e(TAG, "run1" + user_id.equals("")); Intent intentSplash = new Intent(SplashActivity.this, LoginnActivity.class); startActivity(intentSplash); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } else if (user_name.equals("") && user_id.equals("") && company_name.equals("") && user_name.equals("")) { Log.e(TAG, "run2:user_name "); Intent intentSplash = new Intent(SplashActivity.this, LoginnActivity.class); startActivity(intentSplash); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } else if (!user_id.equals("")) { Log.e(TAG, "run7: else" + !user_id.equals("")); Log.e(TAG, "run7: else user_id" + user_id); Intent intentSplash = new Intent(SplashActivity.this, Main2Activity.class); startActivity(intentSplash); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } else { Log.e(TAG, "run: final else" ); } //} } catch (Exception err) { initView(); Intent mainIntent = new Intent(SplashActivity.this, LoginnActivity.class); startActivity(mainIntent); finish(); err.printStackTrace(); } } }, SPLASH_DISPLAY_LENGTH); } /* @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSIONS_REQUEST_READ_PHONE_STATE && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getDeviceImei(); } }*/ @SuppressLint("NewApi") private void getDeviceImei() { Log.e(TAG, "getDeviceImei: "); mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // Activity#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for Activity#requestPermissions for more details. return; } imei = mTelephonyManager.getDeviceId(); Log.e("msg", "DeviceImei " + imei); } }
true
f79343edcb02ef3ba732f37eeffcdfddda866ab2
Java
Pig-Everest/GoodsPromotion
/src/main/java/com/haut/promotion/service/impl/FullCouponServiceImpl.java
UTF-8
800
2.265625
2
[]
no_license
package com.haut.promotion.service.impl; import com.haut.promotion.domain.FullCoupon; import org.springframework.stereotype.Service; import javax.annotation.Resource; import com.haut.promotion.mapper.FullCouponMapper; import com.haut.promotion.service.FullCouponService; @Service public class FullCouponServiceImpl implements FullCouponService{ @Resource private FullCouponMapper fullCouponMapper; /** * 新建新的满减券 * * @param full 满多少 * @param reduction 减多少 */ @Override public void createFullCoupon(Integer full, Integer reduction) { FullCoupon fullCoupon = new FullCoupon(); fullCoupon.setFull(full); fullCoupon.setReduction(reduction); fullCouponMapper.insertSelective(fullCoupon); } }
true
7f427a48879fbbb13b202425face2d6a61f077d8
Java
chenhongbao/adminsys
/src/chb/client/Login.java
UTF-8
8,427
2.390625
2
[]
no_license
package chb.client; import chb.base.LoggingProxy; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.File; import java.io.IOException; import java.sql.*; public class Login extends AServlet{ protected File configFile = null; protected HttpServletRequest reqst = null; protected HttpServletResponse respos = null; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.reqst = req; this.respos =resp; String oper = req.getParameter("operation"); if(oper.equals("login")) { /** * If login succeeds, jump to the review.se, otherwise goes back to login.html. */ if(checkUserLogin(req.getParameter("identityNo"), req.getParameter("pwd"))) { RequestDispatcher dispatcher = req.getRequestDispatcher("/review.se"); dispatcher.forward(req, resp); }else { RequestDispatcher dispatcher = req.getRequestDispatcher("/index.html"); dispatcher.forward(req, resp); } } else if (oper.equals("register")) { /** * If the user clicks the register button, goes to register page. * <strong>NOTE:</strong> * Give top = 1, will show the top banner, other value will hid the banner. */ RequestDispatcher dispatcher = req.getRequestDispatcher("/register.jsp?top=1"); dispatcher.forward(req, resp); } else { /** * Bad incoming parameter. */ String lp = getInitParameterPath("path.login.error.log"); LoggingProxy logger = new LoggingProxy(lp); logger.log(LoggingProxy.ERROR, "["+getHash(req.getParameterMap())+"]Login abused, wrong field name."); req.setAttribute("info", "登陆参数错误,请联系管理员。"); RequestDispatcher dispatcher = req.getRequestDispatcher("/error.jsp"); dispatcher.forward(req, resp); } } /** * Check whether the user has registered. * @param idNo the identity number of the user. * @param pwd the password of the user * @return true if user exists. */ protected boolean checkUserLogin(String idNo, String pwd) { String p = getInitParameterPath("path.datasource.config"); /* in order to build the connection string, we need configuration file. */ this.configFile = new File(p); if(this.configFile.exists() == false || this.configFile.canRead() == false) { return false; } String url = buildConnectionString(); Connection conn = getConnection(url, "com.mysql.jdbc.Driver"); if(conn == null) { String lp = getInitParameterPath("path.login.error.log"); LoggingProxy logger = new LoggingProxy(lp); logger.log(LoggingProxy.ERROR, "["+getHash(reqst.getParameterMap())+"]Login error. Database connection error, return null."); return false; } try { Statement stat = conn.createStatement(); String query = "select 1 from register_info where pwd = \'" + pwd + "\' and identityNo = \'" + idNo +"\';"; ResultSet set = stat.executeQuery(query); return set.next(); } catch (SQLException e) { String lp = getInitParameterPath("path.login.error.log"); LoggingProxy logger = new LoggingProxy(lp); logger.log(LoggingProxy.ERROR, "["+getHash(reqst.getParameterMap())+"]Login error." + e.getMessage()); return false; } } /** * Build connection string from XML configuration file. * * @return connection string */ protected String buildConnectionString() { String conn = ""; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = null; Document doc = null; XPath xpath = null; try { builder = factory.newDocumentBuilder(); doc = builder.parse(this.configFile); xpath = XPathFactory.newInstance().newXPath(); } catch (Exception e) { return null; } conn += getSingleValueFromXML(xpath, "//datasource/header/@value", doc); conn += "//" + getSingleValueFromXML(xpath, "//datasource/address/@value", doc); conn += ":" + getSingleValueFromXML(xpath, "//datasource/port/@value", doc); conn += "/" + getSingleValueFromXML(xpath, "//datasource/database/@value", doc); conn += "?" + getPairValueFromXML(xpath, "//datasource/param", doc); return conn; } /** * Draw the value from XML by XPath. * * @param xpath instance of XPath * @param path XPath expression * @param doc Document instance * @return string value */ protected String getSingleValueFromXML(XPath xpath, String path, Document doc) { if (doc == null || xpath == null || path == null) { return ""; } try { XPathExpression expr = xpath.compile(path); Object res = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) res; if (nodes.getLength() < 1) { return null; } Node n = nodes.item(0); String v = n.getNodeValue(); return v; } catch (Exception e) { return ""; } } /** * Get key-value pairs in the form 'name1=value1&name2=value2'. * * @param xpath instance of XPath * @param path XPath expression * @param doc Document instance * @return string value */ protected String getPairValueFromXML(XPath xpath, String path, Document doc) { if (doc == null || xpath == null || path == null) { return ""; } try { XPathExpression expr = xpath.compile(path); Object res = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) res; if (nodes.getLength() < 1) { return null; } String v = ""; for (int i = 0; i < nodes.getLength(); ++i) { Node n = nodes.item(i); NamedNodeMap nnm = n.getAttributes(); Node n1 = nnm.getNamedItem("name"); Node n2 = nnm.getNamedItem("value"); if(n1 == null || n2 == null) { continue; } v += n1.getNodeValue(); v += "=" + n2.getNodeValue(); if (i != nodes.getLength() - 1) { v += "&"; } } return v; } catch (Exception e) { return ""; } } /** * Create JDBC connection. * @param url connection url * @param classname Class name used in Class.forName(). * @return connection instance */ public Connection getConnection(String url, String classname) { try { Class.forName(classname); Connection con = DriverManager.getConnection(url); return con; } catch (ClassNotFoundException e) { String lp = getInitParameterPath("path.login.error.log"); LoggingProxy logger = new LoggingProxy(lp); logger.log(LoggingProxy.ERROR, "["+getHash(reqst.getParameterMap())+"]" +"Login error.\t"+ e.getMessage()); return null; } catch (SQLException e) { String lp = getInitParameterPath("path.login.error.log"); LoggingProxy logger = new LoggingProxy(lp); logger.log(LoggingProxy.ERROR, "["+getHash(reqst.getParameterMap())+"]"+"Login error.\t"+e.getMessage()); return null; } } }
true
172c128e3344135d169beab00c5d4ba761ed8c26
Java
stbischof/bnd
/bndtools.m2e/src/bndtools/m2e/WorkspaceProjectPostProcessor.java
UTF-8
2,035
2
2
[ "EPL-2.0", "Apache-2.0" ]
permissive
package bndtools.m2e; import java.io.File; import java.nio.file.Paths; import org.apache.maven.model.Build; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.m2e.core.project.IMavenProjectFacade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.maven.lib.resolve.PostProcessor; class WorkspaceProjectPostProcessor implements MavenRunListenerHelper, PostProcessor { private static final Logger logger = LoggerFactory.getLogger(WorkspaceProjectPostProcessor.class); private final IProgressMonitor monitor; WorkspaceProjectPostProcessor(IProgressMonitor monitor) { this.monitor = monitor; } @Override public ArtifactResult postProcessResult(ArtifactResult resolvedArtifact) throws MojoExecutionException { Artifact artifact = resolvedArtifact.getArtifact(); IMavenProjectFacade projectFacade = mavenProjectRegistry.getMavenProject(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); if (projectFacade != null) { try { MavenProject mavenProject = projectFacade.getMavenProject(monitor); Build build = mavenProject.getBuild(); File file = Paths.get(build.getDirectory(), build.getFinalName() .concat(".") .concat(artifact.getExtension())) .toFile(); resolvedArtifact = new ArtifactResult(resolvedArtifact.getRequest()); resolvedArtifact.setArtifact( new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getExtension(), artifact.getVersion(), artifact.getProperties(), file)); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Could not obtain project artifact for {} due to: {}", resolvedArtifact, e.getMessage()); } } } return resolvedArtifact; } }
true
9d7f43e1a18b02126502677b1e7419c4f63d7606
Java
SuzyWu2014/coprhd-controller
/controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/discovery/smis/processor/detailedDiscovery/FastPolicyProcessor.java
UTF-8
2,762
1.921875
2
[]
no_license
/* * Copyright (c) 2014-2015 EMC Corporation * All Rights Reserved */ package com.emc.storageos.volumecontroller.impl.plugins.discovery.smis.processor.detailedDiscovery; import com.emc.storageos.plugins.BaseCollectionException; import com.emc.storageos.plugins.common.Constants; import com.emc.storageos.plugins.common.Processor; import com.emc.storageos.plugins.common.domainmodel.Operation; import com.emc.storageos.volumecontroller.impl.plugins.discovery.smis.processor.fast.FASTPolicyProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.cim.CIMObjectPath; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This processor is responsible for discovering VNX and VNAX fast policies. */ public class FastPolicyProcessor extends Processor { private Logger log = LoggerFactory.getLogger(FastPolicyProcessor.class); @Override public void processResult(Operation operation, Object resultObj, Map<String, Object> keyMap) throws BaseCollectionException { try { final Iterator<CIMObjectPath> it = (Iterator<CIMObjectPath>) resultObj; while (it.hasNext()) { final CIMObjectPath policyObjectPath = it.next(); String systemName = policyObjectPath.getKey(Constants.SYSTEMNAME).getValue().toString(); if (!systemName.contains((String) keyMap.get(Constants._serialID))) { continue; } String[] array = systemName.split(Constants.PATH_DELIMITER_REGEX); String policyRuleName = policyObjectPath.getKey(Constants.POLICYRULENAME) .getValue().toString(); log.info("Policy Name {}", policyRuleName); String policyKey = validateFastPolicy(array[0], policyRuleName); if (null != policyKey) { log.info("Adding Policy Object Path {}", policyObjectPath); addPath(keyMap, policyKey, policyObjectPath); } } } catch (Exception e) { log.error("Fast Policy discovery failed during UnManaged Volume discovery", e); } } public static String validateFastPolicy(String arrayType, String policyRuleName) { if (Constants.CLARIION.equalsIgnoreCase(arrayType)) { return Constants.VNXFASTPOLICIES; } if (Constants.SYMMETRIX.equalsIgnoreCase(arrayType) && !FASTPolicyProcessor.GlobalVMAXPolicies.contains(policyRuleName)) { return Constants.VMAXFASTPOLICIES; } return null; } @Override protected void setPrerequisiteObjects(List<Object> inputArgs) throws BaseCollectionException { } }
true
05f1629fd8dde6cea01556b35082bb7e46ce827f
Java
kaueelias/Geometria-Arq.Dev.Sis.Mult
/Tresde.java
UTF-8
96
1.828125
2
[]
no_license
package BR.USJT.OO; public abstract class Tresde { public abstract double volume(); }
true
3f23d7b97966ffafccf749add891b9d49a3e6e92
Java
muka-robusta/salon
/salon-data/src/main/java/io/github/onetwostory/salon/repositories/MasterRepo.java
UTF-8
337
1.820313
2
[]
no_license
package io.github.onetwostory.salon.repositories; import io.github.onetwostory.salon.domain.Master; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; public interface MasterRepo extends CrudRepository<Master, Long> { Optional<Master> findByLastName(String lastName); }
true
ebd8507045243626f1442949dd730e2366c88991
Java
mdsaleem1804/Android
/KalviSeithi_AadharConnections/app/src/main/java/nellaibill/aadharconnections/AadharMobile.java
UTF-8
4,071
2.109375
2
[]
no_license
package nellaibill.aadharconnections; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.kirianov.multisim.MultiSimTelephonyManager; public class AadharMobile extends AppCompatActivity { MultiSimTelephonyManager multiSimTelephonyManager; Button xBtn1, xBtn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aadhar_mobile); customBar(); try { xBtn1 = (Button) findViewById(R.id.btnsim1); xBtn2 = (Button) findViewById(R.id.btnsim2); multiSimTelephonyManager = new MultiSimTelephonyManager(this, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { useInfo(); } }); }catch(Exception e) { Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show(); } } public void refresh(View v) { Intent intent = getIntent(); finish(); startActivity(intent); } public void sim1(View v) { try { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:14546")); callIntent.putExtra("com.android.phone.extra.slot", 0); startActivity(callIntent); } catch (Exception e) { //TODO smth } } public void sim2(View v) { try { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.putExtra("com.android.phone.extra.slot",1); callIntent.setData(Uri.parse("tel:14546")); startActivity(callIntent); } catch (Exception e) { //TODO smth } } public void customBar(){ ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); LayoutInflater inflater = LayoutInflater.from(this); View customView = inflater.inflate(R.layout.custom_actionbar, null); ImageView menus =(ImageView) customView.findViewById(R.id.slidingmenu); actionBar.setCustomView(customView); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); Toolbar toolbar=(Toolbar)actionBar.getCustomView().getParent(); toolbar.setContentInsetsAbsolute(0, 0); toolbar.getContentInsetEnd(); toolbar.setPadding(0, 0, 0, 0); } public void useInfo() { // get number of slots: if (multiSimTelephonyManager != null) { multiSimTelephonyManager.sizeSlots(); } // get info from each slot: if (multiSimTelephonyManager != null) { for(int i = 0; i < multiSimTelephonyManager.sizeSlots(); i++) { if(i==0) { xBtn1.setText("Connect Aadhar -"+multiSimTelephonyManager.getSlot(i).getNetworkOperatorName().toString()); } else { xBtn2.setText("Connect Aadhar -"+multiSimTelephonyManager.getSlot(i).getNetworkOperatorName().toString()); } } } }public void updateInfo() { // for update UI runOnUiThread(new Runnable() { @Override public void run() { multiSimTelephonyManager.update(); useInfo(); } }); // for update background information multiSimTelephonyManager.update(); useInfo(); } }
true
6548614fc601c86e931807cb9417aed97a2c1b3c
Java
zh2333/LeetCode
/src/com/leetcode/p365/Solution.java
UTF-8
1,817
3.5
4
[]
no_license
package com.leetcode.p365; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; /** * 有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水? 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。 你允许: 装满任意一个水壶 清空任意一个水壶 从一个水壶向另外一个水壶倒水,直到装满或者倒空 示例 1: (From the famous "Die Hard" example) 输入: x = 3, y = 5, z = 4 输出: True 示例 2: 输入: x = 2, y = 6, z = 5 输出: False * @author 张恒 * gcd方法:如果z%(x和y的最大公约数)==0,表示可以 */ class Solution { public boolean canMeasureWater(int x, int y, int z) { if(z < 0 || x+y < z) return false; int big = Math.max(x, y); int small = Math.min(x, y); if(small ==0 ) return big == z; while(big % small != 0){ int tmp = small; small = big % small; big = tmp; } return small == z; } } class Solution2 { public boolean canMeasureWater(int x, int y, int z) { if(z < 0 || x+y < z) return false; Set<Integer> set = new HashSet<Integer>();//记录状态,防止重复计算 Queue<Integer> q = new LinkedList<>(); q.offer(0); while(!q.isEmpty()){ int n = q.poll(); if(n + x <= x+y && set.add(n+x)){ q.add(n+x); } if(n + y <= x+y && set.add(n+y)){ q.add(n+y); } if(n-x>=0 && set.add(n-x)){ q.add(n-x); } if(n-y >= 0 && set.add(n-y)){ q.add(n-y); } if(set.contains(z)){ return true; } } return false; } }
true
6464d107dd771e6b1402ad6bb25fa259620bcbd7
Java
JuliaKodosova/Mytasks
/Task5/src/core/Main.java
UTF-8
516
2.8125
3
[]
no_license
package core; public class Main { public static void main(String[] args) { Tester tester1 = new Tester("Julia", "Kodosova", 7, "advanced", 23); System.out.println(tester1.printInfo()); tester1.printInfo(tester1.getSalary()); tester1.printInfo(tester1.getName(), tester1.getSurname()); tester1.printInfo(tester1.getExpirienceInYears(), tester1.getEnglishLevel(), tester1.getSalary()); Tester.printSmth(); System.out.println(RegularExp.test("abcd")); System.out.print(RegularExp.test2("124")); } }
true
0ff17a17b7ca22dd54c219f7eda6da785ea8b2fb
Java
pabloscotto87/pro3.
/src/main/java/pro3maven/pro3/Main.java
UTF-8
2,397
2.828125
3
[]
no_license
/* * 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 pro3maven.pro3; import Factories.FactoryDao; import Factories.FactoryService; import IDao.UsuarioDao; import Modelos.Log; import Modelos.LogUsuario; import Modelos.Usuario; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import java.util.Properties; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author pabloscotto87 */ public class Main { public static String usuarioLogueado; public static Scanner s = new Scanner(System.in); public static void main(String[] arg) { Log.mapLog.clear(); boolean salir = false; while (!salir) { System.out.println("Seleccione Opción"); System.out.println("L-Login"); System.out.println("P-Imprime Log"); System.out.println("S-Salir"); switch (s.next()) { case "L": logueo(); break; case "P": Log.imprimeLog(); break; case "S": salir = true; break; } } } public static void logueo() { //Login FactoryService factory = new FactoryService(); UsuarioDao usuarioDao = factory.crearUsuarioServicio(); Usuario[] usuarios = usuarioDao.getAll(); String usuario; String pass; boolean logueado = false; while (!logueado) { System.out.println("Ingrese Usuario: "); usuario = s.next(); System.out.println("Ingrese Password: "); pass = s.next(); for (Usuario user : usuarios) { if (user.getNombre().equals(usuario) && user.getPass().equals(pass)) { usuarioLogueado = usuario; LogUsuario logUsuario = new LogUsuario(usuarioLogueado, "Logueo", new Date()); Log.mapLog.put(Log.mapLog.size(), logUsuario); logueado = true; break; } } } } public static void menu() { } }
true
b522fcf80f09e2e6e7a8d8f07345a1b0315bb744
Java
twewyttst777/2017-APCSA-Casino
/misc/BingoCard.java
UTF-8
907
3.265625
3
[]
no_license
import java.util.ArrayList; import java.util.Collections; public class BingoCard{ BingoNum[][] nums; public BingoCard(){ for(int j = 0; j < 5; j++){ ArrayList<Integer> num = new ArrayList<Integer>(); for(int k = 1; k <= 15; k++){ num.add(k); } Collections.shuffle(num); for(int r = 0; r < 5; r++){ if(j == 2 && r == 2){ nums[r][j] = new BingoNum(0); } else { nums[r][j] = new BingoNum(num.remove(0)); } } } } public void mark(int col, int row){ nums[col][row].mark(); } public BingoNum[][] showCard(){ return nums; } public BingoNum seeNumber(int col, int row){ return nums[col][row]; } }
true
102fbdbda097b92cf31e5b36aee872129798a407
Java
jaumevn/lipidianSoccer
/src/domain/Estadisticas.java
UTF-8
1,027
2.21875
2
[]
no_license
/* * Alexandre Vidal Obiols */ package domain; public abstract class Estadisticas { private Integer golesRecibidos; private Integer golesMarcados; private Integer tarjetasAmarillas; private Integer tarjetasRojas; public Estadisticas() { golesRecibidos = 0; golesMarcados = 0; tarjetasAmarillas = 0; tarjetasRojas = 0; } public Integer getGolesRecibidos() { return golesRecibidos; } public void setGolesRecibidos(Integer golesRecibidos) { this.golesRecibidos = golesRecibidos; } public Integer getGolesMarcados() { return golesMarcados; } public void setGolesMarcados(Integer golesMarcados) { this.golesMarcados = golesMarcados; } public Integer getTarjetasAmarillas() { return tarjetasAmarillas; } public void setTarjetasAmarillas(Integer tarjetasAmarillas) { this.tarjetasAmarillas = tarjetasAmarillas; } public Integer getTarjetasRojas() { return tarjetasRojas; } public void setTarjetasRojas(Integer tarjetasRojas) { this.tarjetasRojas = tarjetasRojas; } }
true
9300735b99ec75e8610f3431b29307c54fe0fd41
Java
zhanght86/HSBC20171018
/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/cbcheckgrp/ImpartToICDBL.java
UTF-8
5,927
2.03125
2
[]
no_license
package com.sinosoft.lis.cbcheckgrp; import org.apache.log4j.Logger; import com.sinosoft.lis.db.LCDiseaseResultDB; import com.sinosoft.lis.db.LDPersonDB; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.MMap; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.pubfun.PubSubmit; import com.sinosoft.lis.schema.LDPersonSchema; import com.sinosoft.lis.vschema.LCDiseaseResultSet; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.VData; /** * <p> * Title: * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2004 * </p> * <p> * Company: SinoSoft * </p> * * @author HYQ * @version 1.0 */ public class ImpartToICDBL { private static Logger logger = Logger.getLogger(ImpartToICDBL.class); // 错误处理类,每个需要错误处理的类中都放置该类 public CErrors mErrors = new CErrors(); /** 往界面传输数据的容器 */ private VData mResult = new VData(); private VData mInputData; private GlobalInput tGI = new GlobalInput(); /** 数据操作字符串 */ private String mOperate; private String mOperator; private String mManageCom; /** 业务操作类 */ private LCDiseaseResultSet mLCDiseaseResultSet = new LCDiseaseResultSet(); /** 业务数据 */ private String mName = ""; private String mDelSql = ""; public ImpartToICDBL() { } /** * 传输数据的公共方法 * * @param cInputData * VData * @param cOperate * String * @return boolean */ public boolean submitData(VData cInputData, String cOperate) { // 将操作数据拷贝到本类中 this.mOperate = cOperate; logger.debug("Operate==" + cOperate); // 得到外部传入的数据,将数据备份到本类中 if (!getInputData(cInputData)) { return false; } logger.debug("After getinputdata"); if (!checkData()) { return false; } // 进行业务处理 if (!dealData()) { return false; } logger.debug("After dealData!"); // 准备往后台的数据 if (!prepareOutputData()) { return false; } logger.debug("After prepareOutputData"); logger.debug("Start ImpartToICDBL Submit..."); PubSubmit tSubmit = new PubSubmit(); if (!tSubmit.submitData(mResult, "")) { // @@错误处理 this.mErrors.copyAllErrors(tSubmit.mErrors); CError tError = new CError(); tError.moduleName = "GrpUWAutoChkBL"; tError.functionName = "submitData"; tError.errorMessage = "数据提交失败!"; this.mErrors.addOneError(tError); return false; } logger.debug("ImpartToICDBL end"); return true; } /** * prepareOutputData * * @return boolean */ private boolean prepareOutputData() { mResult.clear(); MMap map = new MMap(); map.put(mLCDiseaseResultSet, "INSERT"); mResult.add(map); return true; } /** * dealData 业务逻辑处理 * * @return boolean */ private boolean dealData() { int tDisSerialNo; LCDiseaseResultDB tLCDiseaseResultDB = new LCDiseaseResultDB(); tLCDiseaseResultDB.setContNo(mLCDiseaseResultSet.get(1).getContNo()); tLCDiseaseResultDB.setCustomerNo(mLCDiseaseResultSet.get(1) .getCustomerNo()); LCDiseaseResultSet tLCDiseaseResultSet = tLCDiseaseResultDB.query(); if (tLCDiseaseResultSet.size() == 0) { tDisSerialNo = 0; } else { tDisSerialNo = tLCDiseaseResultSet.size() + 1; } for (int i = 1; i <= mLCDiseaseResultSet.size(); i++) { mLCDiseaseResultSet.get(i).setName(mName); mLCDiseaseResultSet.get(i).setSerialNo("" + tDisSerialNo); mLCDiseaseResultSet.get(i).setOperator(mOperator); mLCDiseaseResultSet.get(i).setMakeDate(PubFun.getCurrentDate()); mLCDiseaseResultSet.get(i).setMakeTime(PubFun.getCurrentTime()); mLCDiseaseResultSet.get(i).setModifyDate(PubFun.getCurrentDate()); mLCDiseaseResultSet.get(i).setModifyTime(PubFun.getCurrentTime()); tDisSerialNo++; } return true; } /** * checkData 数据校验 * * @return boolean */ private boolean checkData() { LDPersonDB tLDPersonDB = new LDPersonDB(); LDPersonSchema tLDPersonSchema = new LDPersonSchema(); tLDPersonDB.setCustomerNo(mLCDiseaseResultSet.get(1).getCustomerNo()); if (!tLDPersonDB.getInfo()) { // @@错误处理 // this.mErrors.copyAllErrors( tLCGrpContDB.mErrors ); CError tError = new CError(); tError.moduleName = "ImpartToICDBL"; tError.functionName = "checkData"; tError.errorMessage = "客户信息查询失败!"; this.mErrors.addOneError(tError); return false; } tLDPersonSchema = tLDPersonDB.getSchema(); mName = tLDPersonSchema.getName(); return true; } /** * getInputData * * @param cInputData * VData * @return boolean */ private boolean getInputData(VData cInputData) { // 公用变量 tGI = (GlobalInput) cInputData.getObjectByObjectName("GlobalInput", 0); mLCDiseaseResultSet = (LCDiseaseResultSet) cInputData .getObjectByObjectName("LCDiseaseResultSet", 0); mOperator = tGI.Operator; if (mOperator == null || mOperator.length() <= 0) { // @@错误处理 // this.mErrors.copyAllErrors( tLCGrpContDB.mErrors ); CError tError = new CError(); tError.moduleName = "ImpartToICDBL"; tError.functionName = "getInputData"; tError.errorMessage = "前台传输全局公共数据Operator失败!"; this.mErrors.addOneError(tError); return false; } // 取得疾病信息 if (mLCDiseaseResultSet == null || mLCDiseaseResultSet.size() <= 0) { // @@错误处理 // this.mErrors.copyAllErrors( tLCGrpContDB.mErrors ); CError tError = new CError(); tError.moduleName = "ImpartToICDBL"; tError.functionName = "getInputData"; tError.errorMessage = "前台传输数据LCDiseaseResultSet失败!"; this.mErrors.addOneError(tError); return false; } return true; } /** * 返回结果 * * @return VData */ public VData getResult() { return mResult; } }
true
20bd310fa2d6d2f9aa381f19c5b1fa396106dd6e
Java
boonto/landsofcinder
/core/src/de/loc/quest/QuestLog.java
UTF-8
1,301
2.453125
2
[ "MIT" ]
permissive
package de.loc.quest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import de.loc.event.Event; import de.loc.event.EventListener; import de.loc.event.EventSystem; import de.loc.event.Observable; public class QuestLog implements Observable, EventListener { private final List<EventListener> listeners; private final HashMap<String, Quest> activeQuests; public QuestLog(HashMap<String, Quest> questList) { this.listeners = new ArrayList<>(); this.activeQuests = questList; EventSystem.getInstance().addListener(this, EventSystem.EventType.QUEST_EVENT); } public HashMap<String, Quest> getActiveQuests() { return this.activeQuests; } public void addListener(EventListener listener) { this.listeners.add(listener); } public void removeListener(EventListener listener) { this.listeners.remove(listener); } @Override public void fire(EventSystem.EventType eventType, Object... args) { for ( EventListener listener : this.listeners ) { listener.update(new Event(eventType)); } } @Override public void update(Event e) { if ( e.eventType == EventSystem.EventType.QUEST_EVENT ) { this.fire(null); } } }
true
773ffc7aa4103efb57a496ce6d20885d01fe0f0c
Java
biadebeatriz/Trabalho1
/Interfaces/ITableReceptacle.java
UTF-8
154
1.71875
2
[]
no_license
package Interfaces; public interface ITableReceptacle { public void updateTable(String[][] instances); public void connect(ITableProducer producer); }
true
0cad164ea21c2c958466dad3b8bbac1f4ed6eb7d
Java
mihai9-lab/Document-handler
/src/gui/listeners/change/DocumentViewsSelectionListener.java
UTF-8
646
2.34375
2
[]
no_license
package gui.listeners.change; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import tree.model.Document; import view.DocumentView; public class DocumentViewsSelectionListener implements ChangeListener { public void stateChanged(ChangeEvent e) { JTabbedPane tabbedPane = (JTabbedPane) e.getSource(); int n = tabbedPane.getComponentCount(); if(n==0) return; int selectedIndex = tabbedPane.getSelectedIndex(); Document d = ((DocumentView)tabbedPane.getComponentAt(selectedIndex)).getDocument(); if(!d.isSelected()) d.select(); } }
true
c68375f0e089d64306bd0a4fa76dcb3406113c1c
Java
zjsyhjh/leetcode
/95.Unique Binary Search Trees II/Solution.java
UTF-8
887
3.421875
3
[]
no_license
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<TreeNode> generateTrees(int n) { if (n == 0) { return new ArrayList<>(); } return dfs(1, n); } private List<TreeNode> dfs(int st, int ed) { List<TreeNode > tree = new ArrayList<>(); if (st > ed) { tree.add(null); return tree; } for (int mid = st; mid <= ed; mid++) { List<TreeNode > ltree = dfs(st, mid - 1); List<TreeNode > rtree = dfs(mid + 1, ed); for (TreeNode lnode : ltree) { for (TreeNode rnode : rtree) { TreeNode rt = new TreeNode(mid); rt.left = lnode; rt.right = rnode; tree.add(rt); } } } return tree; } }
true
7d678b074c378d3337505f65e38fbbf0a00fb7c1
Java
JeffersonLab/clas12-offline-software
/common-tools/clas-io/src/main/java/org/jlab/utils/BoardDecoderVSCM.java
UTF-8
14,883
1.78125
2
[]
no_license
/* * 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 org.jlab.utils; import java.util.ArrayList; import org.jlab.io.evio.EvioDataBank; import org.jlab.io.evio.EvioDataDictionary; import org.jlab.io.evio.EvioDataEvent; import org.jlab.io.evio.EvioDataSync; import org.jlab.io.evio.EvioSource; /** * * @author gavalian */ public class BoardDecoderVSCM { //ArrayList< ArrayList<BoardRecordVSCM> > boardEvents = new ArrayList< ArrayList<BoardRecordVSCM> >(); ArrayList<BoardRecordVSCM> boardEvent = new ArrayList<BoardRecordVSCM>(); final static int DATA_TYPE_BLKHDR = 0x00; final static int DATA_TYPE_BLKTLR = 0x01; final static int DATA_TYPE_EVTHDR = 0x02; final static int DATA_TYPE_TRGTIME = 0x03; final static int DATA_TYPE_BCOTIME = 0x04; final static int DATA_TYPE_FSSREVT = 0x08; final static int DATA_TYPE_DNV = 0x0E; final static int DATA_TYPE_FILLER = 0x0F; final static int UNIX_TYPE_FILLER = 0x0D; public BoardDecoderVSCM(){ } public int getLayer(int slotid, int hfcbid,int chipid){ if(slotid==10&&hfcbid==0){ if(chipid==1||chipid==2){ return 5; } if(chipid==3||chipid==4){ return 6; } } if(slotid==9&&hfcbid==1){ if(chipid==1||chipid==2){ return 1; } if(chipid==3||chipid==4){ return 2; } } if(slotid==9&&hfcbid==0){ if(chipid==1||chipid==2){ return 1; } if(chipid==3||chipid==4){ return 2; } } if(slotid==8&&hfcbid==1){ if(chipid==1||chipid==2){ return 5; } if(chipid==3||chipid==4){ return 6; } } return 0; /* int ring = this.getRing(slotid,hfcbid); int locallayer = 2; if(chipid<=2) locallayer = 1; return (ring-1)*2 + locallayer;*/ } public int getStrip(int chipid, int chan){ if(chipid==1){ return chan+1; } if(chipid==2){ return chan + 129; } if(chipid==3){ return chan + 1; } if(chipid==4){ return chan + 129; } return 0; /* int coef = chipid; if(coef>2) coef = coef - 1; return chan*coef + 1;*/ } public int getRing(int slotid, int hfcbid){ int sector = (slotid-3)*2 + hfcbid + 1; if(sector>10 && sector <=24){ return 2; } if(sector>24 && sector <=42){ return 3; } if(sector > 42) return 4; return 1; } public int getSector(int slotid, int hfcbid){ if(slotid==10&&hfcbid==0){ return 1; } if(slotid==9&&hfcbid==1){ return 1; } if(slotid==9&&hfcbid==0){ return 6; } if(slotid==8&&hfcbid==1){ return 10; } return 0; /* int sector = (slotid-3)*2 + hfcbid + 1; if(sector>10 && sector <=24){ return sector-10; } if(sector>24 && sector <=42){ return sector-24; } if(sector > 42){ return sector - 42; } return sector;*/ } public ArrayList<BoardRecordVSCM> getRecords(){ return this.boardEvent;} public void decode(int[] array){ int unixtime = 0; int totalLength = array.length; int icount = 0; int ievent = 0; int bcostart = 0; int bcostop = 0; boardEvent.clear(); //ArrayList<BoardRecordVSCM> boardevent = null; int slotid = 0; while(icount<=totalLength){ if(icount>=totalLength) break; long word = this.getWord(array[icount]); if ((word & 0x80000000) != -1){ int type = (int) ((word >> 27) & 0xF); switch(type){ case DATA_TYPE_BLKHDR: int nevents = (int) ((word>>11) & 0x3FF); slotid = (int) ((word >> 22) & 0x1f); //System.err.println("-> BLOCK HEADER in position = " + icount //+ " N EVENTS = " + nevents + " SLOT = " + slotid); break; case DATA_TYPE_BLKTLR: int nwords = (int) ((word) & 0xFFFFF); /* if(boardevent!=null){ for(BoardRecordVSCM rec : boardevent){ rec.slotid = slotid; } }*/ //System.err.println("-> BLOCK TRAILER in position = " + icount //+ " N WORDS = " + nwords + " slot id = " + slotid); break; case DATA_TYPE_BCOTIME: //System.out.println("FOUND BCO TIME " + String.format("%X", word)); bcostop = (int) ((word>>16) & 0x00FF); bcostart = (int) ((word) & 0x00FF); break; case DATA_TYPE_EVTHDR: ievent = 0; //System.out.println("FOUND EVENT HEADER " + String.format("%X", word)); //System.err.println("---------> EVENT HEADER in position = " + icount); break; case DATA_TYPE_TRGTIME: //System.err.println("----> TRIGGER TIME found at position = " + icount); icount++; break; case DATA_TYPE_FSSREVT: { int chipID = (int) (word >> 19) & 0x7; // get chip id int channel = (int) (word >> 12) & 0x7F; // get channel int bco = (int) (word >> 4) & 0xFF; // get bco time int adc = (int) (word >> 0) & 0x7; // get adc -- value starts at 0 int hfcbID = (int) (word >> 22) & 0x1; BoardRecordVSCM record = new BoardRecordVSCM(); record.slotid = slotid; //if(record.slotid>=11) record.slotid = slotid - 2; record.adc = adc; record.channel = channel; record.bco = bco; record.chipid = chipID; record.hfcbid = hfcbID; record.bcostart = bcostart; record.bcostop = bcostop; if(boardEvent!=null) { //System.err.println(record); boardEvent.add(record); } //System.err.println("----------------> EVENT " + ievent + " slot = " + " chip = " + chipID + " chan = " + channel //+ " time = " + bco + " adc = " + adc + " hfcID = " //+ hfcbID); ievent++; } break; default: break; } } icount++; } } public EvioDataBank getConvertedBanks(EvioDataEvent event){ EvioDataBank bstBank = (EvioDataBank) event.getDictionary().createBank("BST::dgtz", boardEvent.size()); //System.err.println(" CREATE BST BANK with size = " + boardEvent.size()); int counter = 0; for(BoardRecordVSCM rec : boardEvent){ int sector = this.getSector(rec.slotid, rec.hfcbid); int layer = this.getLayer(rec.slotid, rec.hfcbid,rec.chipid); int strip = this.getStrip(rec.chipid,rec.channel); //System.err.println(" slot ID = " + rec.slotid + " HFCBID = " + rec.hfcbid // + " CHIPID = " + rec.chipid + " CHANNEL = " + rec.channel + " SECTOR = " + sector + // " LAYAR = " + layer + " STRIP = " + strip); //System.err.println("entry " + counter + " SLOT = " + //rec.slotid + " HFCBID = " + rec.hfcbid + " CHIP = " + rec.chipid + " CHANNEL = " + rec.channel //+ " SECTOR = " + sector + " LAYER = " + layer ); bstBank.setInt("layer",counter,layer); bstBank.setInt("strip",counter,strip); bstBank.setInt("sector",counter,sector); bstBank.setInt("ADC", counter,rec.adc); counter++; } return bstBank; //return null; } public void decodeold(int[] array){ int unixtime=0; for(int loop = 3; loop < array.length; loop++){ if(unixtime==1) { unixtime = 0; continue; } long word = getWord(array[loop]); if ((word & 0x80000000) != -1) { int type = (int) ((word >> 27) & 0xF); int slotID = 0; int hfcbID = 0; int chipID = 0; int channel = 0; int bco = 0; int adc = 0; /* HEADER */ if(type==DATA_TYPE_BLKHDR) { System.err.println("-------> block started here = " + loop); } if(type==DATA_TYPE_BLKTLR) { slotID = (int) ((word >> 22) & 0x1f); //System.err.println("-------> block ends here = " + loop); } if(type==DATA_TYPE_EVTHDR) { //System.err.println("-------> event started here = " + loop); } if(type==DATA_TYPE_TRGTIME) { //System.err.println("-------> TRIG TIME = " + loop); } if(type==UNIX_TYPE_FILLER ) { unixtime = 1; } if(type==DATA_TYPE_BCOTIME) { } if(type==DATA_TYPE_FSSREVT) { // // System.out.printf(" {FSSREVT}"); // // System.out.printf(" HFCBID: %1d", (word >> 22) & 0x1); // // System.out.printf(" CHIPID: %1d", (word >> 19) & 0x7); // // System.out.printf(" CH: %3d", (word >> 12) & 0x7F); // // System.out.printf(" BCO: %3d", (word >> 4) & 0xFF); // // System.out.printf(" \n"); //// System.out.printf(" ADC: %1d\n", (word >> 0) & 0x7); chipID = (int) (word >> 19) & 0x7; // get chip id channel = (int) (word >> 12) & 0x7F; // get channel bco = (int) (word >> 4) & 0xFF; // get bco time adc = (int) (word >> 0) & 0x7; // get adc -- value starts at 0 hfcbID = (int) (word >> 22) & 0x1; System.err.println("slot = " + slotID + " chip = " + chipID + " chan = " + channel + " time = " + bco + " adc = " + adc + " hfcID = " + hfcbID); } if(type==DATA_TYPE_DNV) { System.exit(0); } if(type==DATA_TYPE_FILLER) { } if(slotID==3 || slotID==4) { // // System.out.println(" stored hits " ); } } } } public long getWord(int value){ return (long) value; } public static void main(String[] args){ String inputFileName = args[0]; BoardDecoderVSCM decoder = new BoardDecoderVSCM(); EvioSource reader = new EvioSource(); //reader.open("/Users/gavalian/Work/DataSpace/svt2test.dat_000819.evio"); reader.open(inputFileName); EvioDataSync writer = new EvioDataSync(); writer.open("BST_decoded_data.evio"); int evcounter = 0; int writecounter = 0; while(reader.hasEvent()){ if(evcounter%400==0){ System.err.println("-----------> processed events = " + evcounter + " events written = " + writecounter); } EvioDataEvent event = (EvioDataEvent) reader.getNextEvent(); //event.getDictionary().show(); //event.showNodes(); //System.err.println("\n\n"); //System.err.println("***************************************************************"); //System.err.println("********************* EVENT START " + evcounter); //System.err.println("***************************************************************"); //System.err.println("\n\n"); int[] buffer = event.getInt(57604, 1); if(buffer!=null){ System.err.println(" BUFFER LENGTH = " + buffer.length); try { //System.err.println(" buffer length = " + buffer.length); decoder.decode(buffer); EvioDataEvent outevent = writer.createEvent((EvioDataDictionary) event.getDictionary()); EvioDataBank bstbank = decoder.getConvertedBanks(event); System.err.println(" writing event " + evcounter + " with " + bstbank.rows() + " banks"); EvioDataEvent evout = writer.createEvent((EvioDataDictionary) event.getDictionary()); if(bstbank.rows()>4){ evout.appendBank(bstbank); writer.writeEvent(evout); writecounter++; } } catch (Exception e){ System.err.println("********* ERROR : something went wrong with event # " + evcounter); } } evcounter++; } writer.close(); System.err.println("\n\n FINAL ------> processed events = " + evcounter + " events written = " + writecounter); System.err.println("\n\n Done...\n\n"); } }
true
6ccdeb239cb98aa27bb321d3f8cfd122c93cced3
Java
antonio90protom/myTimeMaster
/mytime-master/src/main/java/com/protom/mytime/controller/ControllerStatus.java
UTF-8
106
1.703125
2
[]
no_license
package com.protom.mytime.controller; public interface ControllerStatus { int OK = 0; int KO = -1; }
true
2536daa0ffc81fdd380bcec0ca4b3573f7acbc40
Java
joaomarccos/AirSoft-Association
/pos-airsoft-business-rules/src/main/java/io/github/joaomarccos/pos/airsoft/repositories/GameRepositoryImpl.java
UTF-8
1,528
2.4375
2
[]
no_license
package io.github.joaomarccos.pos.airsoft.repositories; import io.github.joaomarccos.pos.airsoft.dao.DaoJPAFactory; import io.github.joaomarccos.pos.airsoft.dao.GameDAO; import io.github.joaomarccos.pos.airsoft.enums.GameStatus; import io.github.joaomarccos.pos.airsoft.entitys.Game; import io.github.joaomarccos.pos.airsoft.repositories.interfaces.GameRepository; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author João Marcos <joaomarccos.github.io> */ public class GameRepositoryImpl implements GameRepository { private final GameDAO dao; public GameRepositoryImpl() { this.dao = DaoJPAFactory.createGameDao(); } @Override public void save(Game entity) { entity.setStatus(GameStatus.DEFAULT.name()); dao.save(entity); } @Override public void delete(Game entity) { dao.delete(entity); } @Override public void update(Game entity) { dao.update(entity); } @Override public List<Game> findAll() { List<Game> listQuery = dao.listQuery("games.all", null); return listQuery; } @Override public Game findById(long id) { Map<String, Object> params = new HashMap<>(); params.put("id", id); return dao.simpleQuery("games.findbyid", params); } @Override public long numberOfGames() { return dao.numberOfGames(); } @Override public List<Game> findPerPage(int page) { return dao.findPerPage(page); } }
true
01a869a23f153abd39322ad7eebde70adc50f3d6
Java
TarasFiliuk/calm_down
/src/main/java/com/epam/ua/trainingProject/error/ErrorUtils.java
UTF-8
915
2.484375
2
[]
no_license
package com.epam.ua.trainingProject.error; import lombok.AccessLevel; import lombok.NoArgsConstructor; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hibernate.validator.internal.metadata.core.ConstraintHelper.MESSAGE; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ErrorUtils { public static Error newError(String field, String message) { return new Error(field, message); } public static Errors newErrorsList(Error... phone) { return new Errors(asList(phone)); } public static Errors newSingletonErrors(String message) { return new Errors(singletonList(new Error(MESSAGE, message))); } public static Errors newSingletonErrors(String message, String exceptionMessage) { return new Errors(singletonList(new Error(MESSAGE, message + " " + exceptionMessage))); } }
true
98eb28d47667a2508ba75d4f71f17481e74745c1
Java
lixingluo/JAVA-Design-Pattern
/DesignPattern-13-Decorator/src/designpattern/component/Label.java
UTF-8
307
2.953125
3
[]
no_license
package designpattern.component; public class Label extends Decorator { public Label(Component component) { // TODO Auto-generated constructor stub super(component); } @Override public void show() { // TODO Auto-generated method stub System.out.println("Get the Label"); super.show(); } }
true
1354e9bcb7ae244a0b29018b4c1b18946c073c25
Java
FanBeginner/MVPDemo
/app/src/main/java/com/example/mvpdemo/adapter/NewsRecycleViewAdapter.java
UTF-8
2,446
2.265625
2
[]
no_license
package com.example.mvpdemo.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.mvpdemo.R; import com.example.mvpdemo.bean.TitleData; public class NewsRecycleViewAdapter extends RecyclerView.Adapter<NewsRecycleViewAdapter.ViewHolder> { private Context mContext; private TitleData titleData; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.adp_recycler_news,parent,false); ViewHolder holder=new ViewHolder(view); return holder; } public NewsRecycleViewAdapter(Context mContext, TitleData data) { this.mContext = mContext; this.titleData = data; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Glide.with(mContext) .load(titleData.getResult().getData().get(position).getThumbnail_pic_s()) .into(holder.imageView); holder.tv_title.setText(titleData.getResult().getData().get(position).getTitle()); holder.tv_author.setText(titleData.getResult().getData().get(position).getAuthor_name()); holder.tv_category.setText(titleData.getResult().getData().get(position).getCategory()); holder.tv_date.setText(titleData.getResult().getData().get(position).getDate()); } @Override public int getItemCount() { return titleData.getResult().getData().size(); } public class ViewHolder extends RecyclerView.ViewHolder { private ImageView imageView; private TextView tv_title; private TextView tv_author; private TextView tv_date; private TextView tv_category; public ViewHolder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.dap_news_image); tv_title=itemView.findViewById(R.id.adp_news_title); tv_author=itemView.findViewById(R.id.adp_news_author); tv_date=itemView.findViewById(R.id.adp_news_date); tv_category=itemView.findViewById(R.id.adp_news_category); } } }
true
26550f4d1d6f79ebf8d45d01ccc549b9963f9d81
Java
gitter-badger/decksy
/src/main/java/com/decksy/controller/DeckController.java
UTF-8
1,478
2.328125
2
[]
no_license
package com.decksy.controller; import com.decksy.model.Deck; import com.decksy.service.DeckService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.validation.Valid; import java.util.Optional; @Controller @RequestMapping("/deck") public class DeckController { @Autowired private DeckService deckService; @GetMapping(value = "/") public String index(Model model) { model.addAttribute("deck", new Deck()); return "deck/index"; } @GetMapping(value = "/{id}") public String show(@PathVariable long id, Model model) { Optional<Deck> deck = deckService.findById(id); if (!deck.isPresent()) { return "redirect:/deck/"; } model.addAttribute("deck", deck.get()); return "deck/deck"; } @PostMapping(value = "/") public String create(@Valid Deck deck, BindingResult result) { if (result.hasErrors()) { return "deck/index"; } return "redirect:/deck/" + deckService.save(deck).getId(); } }
true
858e6492504638c7753f338c501fe2807f5eec8f
Java
shwetha4praneeth/JavaOld
/src/test/java/javabasics/Sample12.java
UTF-8
382
3.109375
3
[]
no_license
package javabasics; public class Sample12 implements Sample11 { public int add(int x, int y) { int z; z=x+y; return z; } public int subtract(int x, int y) { int z; z=x-y; return z; } public int multiply(int x, int y) { int z; z=x*y; return z; } public int divide(int x, int y) { int z; z=x/y; return z; } }
true
6df7a16808c36b77ebcff95216d2e476710f3b3a
Java
proyecto-adalid/adalid
/source/adalid-alfa/src/main/java/adalid/core/annotations/OperationClass.java
UTF-8
7,418
2.40625
2
[]
no_license
/* * Copyright 2017 Jorge Campins y David Uzcategui * * Este archivo forma parte de Adalid. * * Adalid es software libre; usted puede redistribuirlo y/o modificarlo bajo los terminos de la * licencia "GNU General Public License" publicada por la Fundacion "Free Software Foundation". * Adalid se distribuye con la esperanza de que pueda ser util, pero SIN NINGUNA GARANTIA; sin * siquiera las garantias implicitas de COMERCIALIZACION e IDONEIDAD PARA UN PROPOSITO PARTICULAR. * * Para mas detalles vea la licencia "GNU General Public License" en http://www.gnu.org/licenses */ package adalid.core.annotations; import adalid.core.enums.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * La anotación OperationClass se utiliza para establecer atributos básicos de la operación. Es válida para cualquier clase de operación de negocio. * * @author Jorge Campins */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface OperationClass { /** * confirmation indica si las vistas (páginas) de procesamiento deben solicitar, o no, confirmación al ejecutar la operación. Su valor es uno de * los elementos de la enumeración Kleenean. Seleccione TRUE para solicitar confirmación; en caso contrario, seleccione FALSE. Alternativamente, * omita el elemento o seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es el * establecido con el método <b>setBusinessOperationConfirmationRequired</b> del proyecto maestro. * * @return confirmation */ Kleenean confirmation() default Kleenean.UNSPECIFIED; // FALSE /** * access especifica el tipo de control de acceso de la operación. Su valor es uno de los elementos de la enumeración OperationAccess. Seleccione * PRIVATE, PUBLIC, PROTECTED o RESTRICTED si la operación es de acceso privado, público, protegido o restringido, respectivamente. * Alternativamente, omita el elemento o seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del * atributo es RESTRICTED. Las operaciones con acceso privado no pueden ser ejecutadas directamente por los usuarios del sistema. Son ejecutadas * solo por otras operaciones, a través de la Interfaz de Programación (API). Las operaciones con acceso público, protegido y restringido si * pueden ser ejecutadas directamente por los usuarios del sistema, a través de la Interfaz de Usuario (UI). Las operaciones con acceso público * pueden ser ejecutadas por todos los usuarios del sistema, aun cuando no tengan autorización explícita para ello. Las operaciones con acceso * protegido pueden ser ejecutadas por usuarios designados como súper-usuario o por usuarios explícitamente autorizados. Al igual que las * operaciones con acceso protegido, las operaciones con acceso restringido pueden ser ejecutadas por usuarios designados como súper-usuario o por * usuarios explícitamente autorizados. Además, a diferencia de las operaciones con acceso protegido, las operaciones personalizables con acceso * restringido, también pueden ser ejecutadas por usuarios que no tengan autorización explícita, pero solo sobre las instancias de la entidad que * sean propiedad del usuario. * * @return access */ OperationAccess access() default OperationAccess.RESTRICTED; /** * asynchronous indica si la operación se debe ejecutar de manera síncrona o asíncrona. Su valor es uno de los elementos de la enumeración * Kleenean. Seleccione TRUE si se debe ejecutar de manera asíncrona; en caso contrario, seleccione FALSE. Alternativamente, omita el elemento o * seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es FALSE. * <p> * Este elemento no es relevante si la operación es un proceso de exportación (extensión de ExportOperation), un informe (extensión de * ReportOperation), o un procedimiento almacenado en la base de datos (extensión de ProcedureOperation) de tipo VOID, ya que tales operaciones * siempre se deben ejecutar de manera asíncrona. * * @return asynchronous */ Kleenean asynchronous() default Kleenean.UNSPECIFIED; // FALSE /** * shell indica si la operación se debe ejecutar utilizando un proceso nativo del sistema operativo, cuando el uso de procesos nativos esté * permitido para la clase de operación (vea los métodos setExporterShellEnabled, setReporterShellEnabled y setSqlAgentShellEnabled). Solo aplica * si la operación es un proceso de exportación (extensión de ExportOperation), un informe (extensión de ReportOperation), u otra clase de * operación de negocio (extensión de ProcessOperation o ProcedureOperation) que esté implementada mediante una función o procedimiento almacenado * en la base de datos y que se ejecute asincrónicamente. Su valor es uno de los elementos de la enumeración Kleenean. Seleccione TRUE para * utilizar un proceso nativo; seleccione FALSE para utilizar un subproceso del servidor de aplicaciones. Alternativamente, omita el elemento o * seleccione UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es TRUE, si la operación es un * proceso de exportación, un informe o un procedimiento almacenado en la base de datos de tipo VOID; en los demás casos, FALSE. * <p> * Este elemento no es relevante si la operación es un procedimiento almacenado en la base de datos de tipo VOID, ya que tales operaciones siempre * se deben ejecutar utilizando un proceso nativo. * * @return shell */ Kleenean shell() default Kleenean.UNSPECIFIED; /** * complex indica si la operación es, o no, una operación compleja. Su valor es uno de los elementos de la enumeración Kleenean. Seleccione TRUE * si la operación es compleja; en caso contrario, seleccione FALSE. Alternativamente, omita el elemento o seleccione UNSPECIFIED para utilizar el * valor predeterminado del atributo. El valor predeterminado del atributo es FALSE. * * @return complex */ Kleenean complex() default Kleenean.UNSPECIFIED; // FALSE /** * logging especifica cuando se deben registrar pistas de auditoría de la ejecución de la operación. Su valor es uno de los elementos de la * enumeración OperationLogging. Seleccione SUCCESS, FAILURE o BOTH si las pistas se deben registrar cuando la operación se ejecute exitosamente, * cuando se produzca un error al ejecutar la operación, o en ambos casos, respectivamente. Alternativamente, omita el elemento o seleccione * UNSPECIFIED para utilizar el valor predeterminado del atributo. El valor predeterminado del atributo es SUCCESS. * <p> * Este elemento no es relevante si el tipo de control de acceso de la operación es PRIVATE, ya que nunca se registran pistas de auditoría para * tales operaciones. * * @return logging */ OperationLogging logging() default OperationLogging.UNSPECIFIED; // SUCCESS }
true
6da4c98c12b91d45eb7bf30ec99bb0451f8c3c9a
Java
Azam-Aminuddin/bool-func-repr
/src/main/java/persons/azam_ami/learning/Learning_Algo_Tower.java
UTF-8
1,247
3.078125
3
[ "MIT" ]
permissive
package persons.azam_ami.learning; import persons.azam_ami.knowledge.repr.NeuralNet; /** * Implement Algorithm Tower. * * @author [email protected] * */ public class Learning_Algo_Tower { public static NeuralNet.Node createNewNode( NeuralNet nn ) { int[] weights = new int[1 + nn.getVarCount()]; int[] inputVars = new int[ nn.getVarCount() ]; int outputVar = nn.getVarCount(); // Weights for( int i=0; i<nn.getVarCount(); i++ ) { weights[i] = 0; } // Use previous output as it is. weights[nn.getVarCount()] = 1; // InputVars for( int i=0; i<nn.getVarCount(); i++ ) { inputVars[i] = i; } NeuralNet.Node ans = new NeuralNet.Node( weights, inputVars, outputVar ); return ans; } /** * Create new Neural-Net by add one new node and put on top previous nodes. * * @param nn * @return */ public static NeuralNet createNewNeuralNet( NeuralNet nn ) { NeuralNet.Node newNode = createNewNode( nn ); NeuralNet ans = new NeuralNet( nn ); ans.addNode( newNode ); return ans; } }
true
5f2c2a03e59cd34b6d8d7f8080b946e62305ba5f
Java
vikasyadavnsit/Java_Projects
/zz-microservice-old/src/main/java/org/api/utility/concurrency/ThreadLocalTask1.java
UTF-8
329
2.4375
2
[]
no_license
package org.api.utility.concurrency; public class ThreadLocalTask1 { public static void run() { UserThreadLocalContext.local.set(UserThreadLocalContext.local.get() + 1); System.out .println(Thread.currentThread().getName() + " : Initial Value - " + UserThreadLocalContext.local.get()); ThreadLocalTask2.run(); } }
true
2e37b5abe7c0e25851d7579871a2baa33e296a24
Java
surelogic/jsure
/jsure-analysis/src/com/surelogic/persistence/SimpleAnalysisResult.java
UTF-8
1,495
2.015625
2
[]
no_license
/*$Header: /cvs/fluid/fluid/.settings/org.eclipse.jdt.ui.prefs,v 1.2 2006/03/27 21:35:50 boyland Exp $*/ package com.surelogic.persistence; import com.surelogic.aast.IAASTRootNode; import com.surelogic.common.i18n.I18N; import com.surelogic.common.xml.XmlCreator; import com.surelogic.dropsea.ir.PromiseDrop; import edu.cmu.cs.fluid.ir.IRNode; public class SimpleAnalysisResult extends AbstractAnalysisResult { private final int messageCode; private final String[] args; public <T extends IAASTRootNode> SimpleAnalysisResult(PromiseDrop<T> about, IRNode location, int code, Object... args) { super(about, location); messageCode = code; this.args = new String[args.length]; for(int i=0; i<args.length; i++) { this.args[i] = args[i].toString(); } } @Override protected void attributesToXML(XmlCreator.Builder b) { //Entities.newLine(b, indent); b.addAttribute(PersistenceConstants.MESSAGE, I18N.res(messageCode, (Object[]) args)); b.addAttribute(PersistenceConstants.MESSAGE_CODE, messageCode); if (args.length == 0) { b.addAttribute(PersistenceConstants.MESSAGE_ARGS, ""); } else { StringBuilder argsB = new StringBuilder(); boolean first = true; for(String arg : args) { if (first) { first = false; } else { argsB.append(", "); // TODO what if the args contain a comma? } argsB.append(arg); } b.addAttribute(PersistenceConstants.MESSAGE_ARGS, argsB.toString()); } } }
true
271c8883af0335e58742bbf6918ba975072f3a8c
Java
ssilvestresilva/conexus
/src/main/java/br/pucminas/api/entities/Integracao.java
UTF-8
1,301
2.3125
2
[]
no_license
package br.pucminas.api.entities; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Integracao { private String cpf; private String nome; private String curso; private String instituicao; private String periodo; private BigDecimal resultado; public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCurso() { return curso; } public void setCurso(String curso) { this.curso = curso; } public String getInstituicao() { return instituicao; } public void setInstituicao(String instituicao) { this.instituicao = instituicao; } public String getPeriodo() { return periodo; } public void setPeriodo(String periodo) { this.periodo = periodo; } public BigDecimal getResultado() { return resultado; } public void setResultado(BigDecimal resultado) { this.resultado = resultado; } @Override public String toString() { return "Integracao [cpf=" + cpf + ", nome=" + nome + ", curso=" + curso + ", instituicao=" + instituicao + ", periodo=" + periodo + ", resultado=" + resultado + "]"; } }
true