hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e10f0e818ecf9054b1d24151489e4d0528899b3 | 2,289 | java | Java | common/src/main/java/com/sxjs/common/util/DialogUtil.java | syu2007/JD-Test | 97957a5e4b1d77caf164858c56e16b46af135ffb | [
"Apache-2.0"
] | 1,477 | 2017-04-15T06:09:45.000Z | 2022-03-31T22:37:29.000Z | common/src/main/java/com/sxjs/common/util/DialogUtil.java | syu2007/JD-Test | 97957a5e4b1d77caf164858c56e16b46af135ffb | [
"Apache-2.0"
] | 21 | 2017-04-16T11:25:21.000Z | 2021-03-22T07:31:41.000Z | common/src/main/java/com/sxjs/common/util/DialogUtil.java | syu2007/JD-Test | 97957a5e4b1d77caf164858c56e16b46af135ffb | [
"Apache-2.0"
] | 337 | 2017-04-15T14:52:18.000Z | 2021-11-01T02:43:23.000Z | 31.791667 | 119 | 0.663172 | 7,133 | package com.sxjs.common.util;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import com.sxjs.common.R;
/**
* Created by admin on 2017/3/13.
*/
public class DialogUtil {
/**
* 有取消回调的进度dialog
* @param context
* @param msg
* @return
*/
public static Dialog createLoadingDialog(Activity context, String msg, DialogInterface.OnCancelListener listener) {
final Dialog dialog = new Dialog(context , R.style.NoBackGroundDialog);
dialog.show();
dialog.setCanceledOnTouchOutside(false);
if(listener != null) dialog.setOnCancelListener(listener);
Window window = dialog.getWindow();
assert window != null;
window.setGravity(Gravity.CENTER);
int width = ScreenUtil.getWidth(context) * 2 / 3;
window.setLayout(width,
android.view.WindowManager.LayoutParams.WRAP_CONTENT);
View view = context.getLayoutInflater().inflate(
R.layout.loading_dialog, null);
TextView tipTextView = (TextView) view.findViewById(R.id.tipTextView);// 提示文字
if(!TextUtils.isEmpty(msg)){
tipTextView.setText(msg);// 设置加载信息
}
window.setContentView(view);//
return dialog;
}
/**
* gif动画进度
* @param context
*
* @return
*/
public static Dialog createJDLoadingDialog(Activity context, DialogInterface.OnCancelListener listener) {
final Dialog dialog = new Dialog(context , R.style.NoBackGroundDialog);
dialog.show();
dialog.setCanceledOnTouchOutside(false);
if(listener != null) dialog.setOnCancelListener(listener);
Window window = dialog.getWindow();
assert window != null;
window.setGravity(Gravity.CENTER);
window.setLayout(android.view.WindowManager.LayoutParams.WRAP_CONTENT,
android.view.WindowManager.LayoutParams.WRAP_CONTENT);
View view = context.getLayoutInflater().inflate(
R.layout.jd_loading_dialog, null);
window.setContentView(view);//
return dialog;
}
}
|
3e10f18041fcdb0eae8fd85ab3351f9e58dd6b52 | 428 | java | Java | src/main/java/com/ishan/dsalgo/recursion/NToOne.java | ishansoni22/ds-algo | 95bba17a91b27f527d0ee603c22894d05bc23467 | [
"MIT"
] | null | null | null | src/main/java/com/ishan/dsalgo/recursion/NToOne.java | ishansoni22/ds-algo | 95bba17a91b27f527d0ee603c22894d05bc23467 | [
"MIT"
] | null | null | null | src/main/java/com/ishan/dsalgo/recursion/NToOne.java | ishansoni22/ds-algo | 95bba17a91b27f527d0ee603c22894d05bc23467 | [
"MIT"
] | null | null | null | 13.375 | 42 | 0.577103 | 7,134 | package com.ishan.dsalgo.recursion;
//Tail recursive solution
public class NToOne {
private int n;
public NToOne(int n) {
this.n = Math.abs(n);
}
private void printIt(int i) {
if (i <= 0) {
return;
}
System.out.println(i);
printIt(i - 1);
}
void print() {
printIt(n);
}
public static void main(String[] args) {
NToOne nToOne = new NToOne(15);
nToOne.print();
}
}
|
3e10f1c232c14353a842a3abc66efb56fb0a4ae7 | 13,687 | java | Java | atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/manifest/Permission.java | iDev01/atlas | fdcd7357a46b618528c4b56e9cfcafb8941bf2f3 | [
"Apache-2.0"
] | 8,865 | 2017-03-13T03:27:32.000Z | 2022-03-31T12:57:44.000Z | atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/manifest/Permission.java | qxj006/atlas | c20c5b83f67b9a14fb597d59a287ec7a3e5bdbac | [
"Apache-2.0"
] | 359 | 2017-03-13T06:37:22.000Z | 2022-01-27T14:31:43.000Z | atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tools/manifest/Permission.java | qxj006/atlas | c20c5b83f67b9a14fb597d59a287ec7a3e5bdbac | [
"Apache-2.0"
] | 1,709 | 2017-03-13T02:29:13.000Z | 2022-03-31T12:57:48.000Z | 48.882143 | 81 | 0.675605 | 7,135 | /*
*
*
*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2016 Alibaba Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.taobao.android.builder.tools.manifest;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wuzhong on 2017/8/1.
*/
public class Permission {
private List<Item> permissions = new ArrayList<>();
private List<Item> uses_permissions = new ArrayList<>();
private List<Item> uses_features = new ArrayList<>();
public static Item query(List<Item> list, String name) {
for (Item item : list) {
if (item!=null &&name.equals(item.getName())) {
return item;
}
}
return null;
}
public List<Item> getPermissions() {
return permissions;
}
public void setPermissions(List<Item> permissions) {
this.permissions = permissions;
}
public List<Item> getUses_permissions() {
return uses_permissions;
}
public void setUses_permissions(List<Item> uses_permissions) {
this.uses_permissions = uses_permissions;
}
public List<Item> getUses_features() {
return uses_features;
}
public void setUses_features(List<Item> uses_features) {
this.uses_features = uses_features;
}
public static class Item {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
|
3e10f1c35fa5a8985099a9f9d9602499d946927f | 3,655 | java | Java | sling/core/commons/src/main/java/com/composum/sling/core/util/HttpUtil.java | raducotescu/composum | 8c1461a039f4fbab5f6344df8e8d49dfbf4aacdc | [
"MIT"
] | 56 | 2015-09-27T18:35:35.000Z | 2020-10-23T12:51:31.000Z | sling/core/commons/src/main/java/com/composum/sling/core/util/HttpUtil.java | raducotescu/composum | 8c1461a039f4fbab5f6344df8e8d49dfbf4aacdc | [
"MIT"
] | 80 | 2015-09-30T14:57:33.000Z | 2021-01-30T12:01:40.000Z | sling/core/commons/src/main/java/com/composum/sling/core/util/HttpUtil.java | raducotescu/composum | 8c1461a039f4fbab5f6344df8e8d49dfbf4aacdc | [
"MIT"
] | 34 | 2015-10-07T19:42:40.000Z | 2020-10-09T02:39:21.000Z | 42.011494 | 121 | 0.700137 | 7,136 | package com.composum.sling.core.util;
import org.apache.sling.api.servlets.HttpConstants;
import java.util.Calendar;
/**
* A basic class for all '/bin/{service}/path/to/resource' servlets.
*/
public class HttpUtil extends HttpConstants {
public static final String HEADER_LOCATION = "Location";
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String VALUE_NO_CACHE = "no-cache";
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
public static final String HEADER_VARY = "Vary";
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
/**
* Checks whether we can skip transmission of a resource because of a recent enough {@link #HEADER_IF_MODIFIED_SINCE}
* header.
* Returns true if the given lastModified date is after the {ifModifiedSince} or if there is no lastModified date,
* so that we don't know and have to transmit the resource, anyway.
*
* @param ifModifiedSince value of the {@link #HEADER_IF_MODIFIED_SINCE} header
* @param lastModified date of the resource to be submitted
* @return if the resource transmission can be skipped since the browser has the current version
*/
public static boolean notModifiedSince(long ifModifiedSince, Calendar lastModified) {
return lastModified != null && notModifiedSince(ifModifiedSince, lastModified.getTimeInMillis());
}
/**
* Checks whether we can skip transmission of a resource because of a recent enough {@link #HEADER_IF_MODIFIED_SINCE}
* header.
* Returns true if the given lastModified date is after the {ifModifiedSince} or if there is no lastModified date,
* so that we don't know and have to transmit the resource, anyway.
*
* @param ifModifiedSince value of the {@link #HEADER_IF_MODIFIED_SINCE} header
* @param lastModified date of the resource to be submitted
* @return if the resource transmission can be skipped since the browser has the current version
*/
public static boolean notModifiedSince(long ifModifiedSince, Long lastModified) {
if (ifModifiedSince != -1 && lastModified != null) {
// ignore millis because 'ifModifiedSince' comes often without millis
long lastModifiedTime = lastModified / 1000L * 1000L;
ifModifiedSince = ifModifiedSince / 1000L * 1000L;
return lastModifiedTime <= ifModifiedSince;
}
return false;
}
/**
* @deprecated please use {@link #notModifiedSince(long, Calendar)} since that's cleaner; this will be removed
* soon
*/
// FIXME(hps,15.11.19) remove this
@Deprecated
public static boolean isModifiedSince(long ifModifiedSince, Calendar lastModified) {
return !notModifiedSince(ifModifiedSince, lastModified);
}
/**
* @deprecated please use {@link #notModifiedSince(long, Long)} since that's cleaner; this will be removed
* soon
*/
// FIXME(hps,15.11.19) remove this
@Deprecated
public static boolean isModifiedSince(long ifModifiedSince, Long lastModified) {
if (ifModifiedSince != -1 && lastModified != null) {
// ignore millis because 'ifModifiedSince' comes often without millis
long lastModifiedTime = lastModified / 1000L * 1000L;
ifModifiedSince = ifModifiedSince / 1000L * 1000L;
return lastModifiedTime > ifModifiedSince;
}
return true;
}
}
|
3e10f26cf5cd09ab5f90ce90f6421bf5a8184e75 | 896 | java | Java | src/main/java/com/workable/matchmakers/web/validator/RegexValidator.java | antonakospanos/matchmakers | 4b2fe4ff2aba10dfd3c05309c60e91c764e509eb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/workable/matchmakers/web/validator/RegexValidator.java | antonakospanos/matchmakers | 4b2fe4ff2aba10dfd3c05309c60e91c764e509eb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/workable/matchmakers/web/validator/RegexValidator.java | antonakospanos/matchmakers | 4b2fe4ff2aba10dfd3c05309c60e91c764e509eb | [
"Apache-2.0"
] | 1 | 2019-05-28T08:49:23.000Z | 2019-05-28T08:49:23.000Z | 56 | 183 | 0.50558 | 7,137 | package com.workable.matchmakers.web.validator;
public class RegexValidator {
public static final String EMAIL_VALIDATOR = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";
public static final String URL_VALIDATOR = "^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(\\/.*)?$";
// "@(https?|http?|ftp)://(-\\.)?([^\\s/?\\.#-]+\\.?)+(/[^\\s]*)?$@iS";
//"^(https?|http?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
//"^(http:\\/\\/|https:\\/\\/)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?$";
public static final String FACEBOOK_URL_VALIDATOR = "((http|https)://)?(www[.])?facebook.com/.+";
public static final String LINKEDIN_URL_VALIDATOR = "((http|https)://)?(www[.])?linkedin.com/.+";
public static final String CV_URL_VALIDATOR = "((http|https)://).+";
}
|
3e10f2b4b1cd005d539a432c34cc0c28dafaa054 | 1,017 | java | Java | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/annotations/EventFactory.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 14 | 2019-10-09T23:59:32.000Z | 2022-03-01T08:34:56.000Z | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/annotations/EventFactory.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 1,549 | 2019-08-16T01:07:16.000Z | 2022-03-31T23:57:34.000Z | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/annotations/EventFactory.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 24 | 2019-09-05T00:09:35.000Z | 2021-10-19T05:10:39.000Z | 36.321429 | 79 | 0.767945 | 7,138 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.sections.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface EventFactory {
// Nothing
}
|
3e10f395e1890c52f3553032bd82fadd4a3d976f | 6,396 | java | Java | src/org/sosy_lab/cpachecker/core/waitlist/AbstractSortedWaitlist.java | gernst/cpachecker | 8cb25b44a385d7b7b6f903f77551c209f9b9ef11 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/core/waitlist/AbstractSortedWaitlist.java | gernst/cpachecker | 8cb25b44a385d7b7b6f903f77551c209f9b9ef11 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-05-23T19:41:59.000Z | 2019-05-23T19:41:59.000Z | src/org/sosy_lab/cpachecker/core/waitlist/AbstractSortedWaitlist.java | gernst/cpachecker | 8cb25b44a385d7b7b6f903f77551c209f9b9ef11 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 31.048544 | 96 | 0.703721 | 7,139 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.core.waitlist;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.errorprone.annotations.ForOverride;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.util.statistics.StatCounter;
import org.sosy_lab.cpachecker.util.statistics.StatInt;
import org.sosy_lab.cpachecker.util.statistics.StatKind;
/**
* Default implementation of a sorted waitlist.
* The key that is used for sorting is defined by sub-classes (it's type is
* the type parameter of this class).
*
* There may be several abstract states with the same key, so this class
* delegates the decision which of those should be chosen to a second waitlist
* implementation. A factory for this implementation needs to be given to the
* constructor.
*
* The iterators created by this class are unmodifiable.
*/
public abstract class AbstractSortedWaitlist<K extends Comparable<K>> implements Waitlist {
private final WaitlistFactory wrappedWaitlist;
// invariant: all entries in this map are non-empty
private final NavigableMap<K, Waitlist> waitlist = new TreeMap<>();
private int size = 0;
private final StatCounter popCount;
private final StatCounter delegationCount;
private final Map<String, StatInt> delegationCounts = new HashMap<>();
/**
* Constructor that needs a factory for the waitlist implementation that
* should be used to store states with the same sorting key.
*/
protected AbstractSortedWaitlist(WaitlistFactory pSecondaryStrategy) {
wrappedWaitlist = Preconditions.checkNotNull(pSecondaryStrategy);
popCount = new StatCounter("Pop requests to waitlist (" + getClass().getSimpleName() + ")");
delegationCount = new StatCounter(
"Pops delegated to wrapped waitlists (" + wrappedWaitlist.getClass().getSimpleName() +
")");
}
/**
* Method that generates the sorting key for any abstract state.
* States with largest key are considered first.
* This method may not return null.
* If this method throws an exception, no guarantees about the state of the
* current instance of this class are made.
*/
@ForOverride
protected abstract K getSortKey(AbstractState pState);
@Override
public void add(AbstractState pState) {
K key = getSortKey(pState);
Waitlist localWaitlist = waitlist.get(key);
if (localWaitlist == null) {
localWaitlist = wrappedWaitlist.createWaitlistInstance();
waitlist.put(key, localWaitlist);
} else {
assert !localWaitlist.isEmpty();
}
localWaitlist.add(pState);
size++;
}
@Override
public boolean contains(AbstractState pState) {
K key = getSortKey(pState);
Waitlist localWaitlist = waitlist.get(key);
if (localWaitlist == null) {
return false;
}
assert !localWaitlist.isEmpty();
return localWaitlist.contains(pState);
}
@Override
public void clear() {
waitlist.clear();
size = 0;
}
@Override
public boolean isEmpty() {
assert waitlist.isEmpty() == (size == 0);
return waitlist.isEmpty();
}
@Override
public Iterator<AbstractState> iterator() {
return Iterables.concat(waitlist.values()).iterator();
}
@Override
public final AbstractState pop() {
popCount.inc();
Entry<K, Waitlist> highestEntry = waitlist.lastEntry();
Waitlist localWaitlist = highestEntry.getValue();
assert !localWaitlist.isEmpty();
AbstractState result = localWaitlist.pop();
if (localWaitlist.isEmpty()) {
waitlist.remove(highestEntry.getKey());
addStatistics(localWaitlist);
} else {
delegationCount.inc();
}
size--;
return result;
}
private void addStatistics(Waitlist pWaitlist) {
if (pWaitlist instanceof AbstractSortedWaitlist) {
Map<String, StatInt> delegCount =
((AbstractSortedWaitlist<?>) pWaitlist).getDelegationCounts();
for (Entry<String, StatInt> e : delegCount.entrySet()) {
String key = e.getKey();
if (!delegationCounts.containsKey(key)) {
delegationCounts.put(key, e.getValue());
} else {
delegationCounts.get(key).add(e.getValue());
}
}
}
}
/**
* Returns a map of delegation counts for this waitlist and all waitlists delegated to.
* The keys of the returned Map are the names of the waitlists, the values
* are the existing delegations.
*/
public Map<String, StatInt> getDelegationCounts() {
String waitlistName = this.getClass().getSimpleName();
StatInt directDelegations = new StatInt(StatKind.AVG, waitlistName);
assert delegationCount.getValue() <= Integer.MAX_VALUE;
directDelegations.setNextValue((int) delegationCount.getValue());
delegationCounts.put(waitlistName, directDelegations);
return delegationCounts;
}
@Override
public boolean remove(AbstractState pState) {
K key = getSortKey(pState);
Waitlist localWaitlist = waitlist.get(key);
if (localWaitlist == null) {
return false;
}
assert !localWaitlist.isEmpty();
boolean result = localWaitlist.remove(pState);
if (result) {
if (localWaitlist.isEmpty()) {
waitlist.remove(key);
}
size--;
}
return result;
}
@Override
public int size() {
return size;
}
@Override
public String toString() {
return waitlist.toString();
}
}
|
3e10f45d05d3461a133044df84fe61436de6ee02 | 4,893 | java | Java | smarthome_app/app/src/main/java/com/hr/smarthome/ui/temphumi/TemphumiFragment.java | ldcowq/smartHome | 54372c6c049ebe6e620e0b760a34e302484e1a23 | [
"Apache-2.0"
] | 16 | 2021-02-28T08:01:05.000Z | 2022-03-27T05:38:09.000Z | smarthome_app/app/src/main/java/com/hr/smarthome/ui/temphumi/TemphumiFragment.java | efforter/smartHome | 50139678e43021bc556ad2db48cd0532e4672b4c | [
"Apache-2.0"
] | 1 | 2021-07-29T08:26:02.000Z | 2021-08-09T00:15:43.000Z | smarthome_app/app/src/main/java/com/hr/smarthome/ui/temphumi/TemphumiFragment.java | efforter/smartHome | 50139678e43021bc556ad2db48cd0532e4672b4c | [
"Apache-2.0"
] | 7 | 2021-02-28T12:08:36.000Z | 2021-12-23T17:00:45.000Z | 32.403974 | 148 | 0.573064 | 7,140 | package com.hr.smarthome.ui.temphumi;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hr.smarthome.R;
import com.hr.smarthome.okhttp.OkHttpUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class TemphumiFragment extends Fragment {
private List<TempHumiJavaBean> mTHdataList = new ArrayList<>();
private TempHumiAdapter adapter;
private SwipeRefreshLayout swipeRefresh;
RecyclerView recyclerView;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_temphumi, container, false);
recyclerView = view.findViewById(R.id.temp_recyclerview);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new TempHumiAdapter(mTHdataList);
recyclerView.setAdapter(adapter);
swipeRefresh = view.findViewById(R.id.temp_swipe_refresh);
swipeRefresh.setColorScheme(R.color.colorPrimary);
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//从数据库获取最新的温湿度数据
refresh();
}
});
System.out.println("oncreateview()________");
refresh();
return view;
}
private void refresh() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (isAdded()) {//判断fragment是否已经添加到activity中
requireActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
OkHttpUtil.sendHttpRequest("http://103.152.132.235:8080/smartHome/th?pagers=1", new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String responseData = response.body().string();
System.out.println(responseData);
Gson gson = new Gson();
List<TempHumiJavaBean> tempHumiJavaBeans = gson.fromJson(responseData, new TypeToken<List<TempHumiJavaBean>>() {
}.getType());
for (TempHumiJavaBean t : tempHumiJavaBeans) {
mTHdataList.add(new TempHumiJavaBean(t.getTemp(), t.getHumi()));
}
swipeRefresh.setRefreshing(false);
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
});
adapter.notifyDataSetChanged();
}
});
}
}
}).start();
}
@Override
public void onStart() {
super.onStart();
System.out.println("TH: start()________");
}
@Override
public void onResume() {
super.onResume();
System.out.println("TH: onresume()________");
}
@Override
public void onPause() {
super.onPause();
System.out.println("TH: onpause()________");
}
@Override
public void onStop() {
super.onStop();
System.out.println("TH: onstop()________");
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("TH: ondestroy()________");
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
|
3e10f4946bc3ee6c6470721aa4604f65b8a749cb | 901 | java | Java | iis-wf/iis-wf-referenceextraction/src/test/java/eu/dnetlib/iis/wf/referenceextraction/softwareurl/HttpServiceFacadeFactoryTest.java | johnfouf/iis | c27398cfa71a60af4932b4d6a12f8d21429578a2 | [
"Apache-2.0"
] | 20 | 2015-09-19T21:17:23.000Z | 2022-03-01T10:37:59.000Z | iis-wf/iis-wf-referenceextraction/src/test/java/eu/dnetlib/iis/wf/referenceextraction/softwareurl/HttpServiceFacadeFactoryTest.java | johnfouf/iis | c27398cfa71a60af4932b4d6a12f8d21429578a2 | [
"Apache-2.0"
] | 1,054 | 2015-09-11T06:51:27.000Z | 2022-03-30T09:46:54.000Z | iis-wf/iis-wf-referenceextraction/src/test/java/eu/dnetlib/iis/wf/referenceextraction/softwareurl/HttpServiceFacadeFactoryTest.java | LSmyrnaios/iis | 9a6a5e0eeafb1df0067b725d95fd36b1dc8c2e11 | [
"Apache-2.0"
] | 80 | 2015-12-09T12:41:52.000Z | 2022-02-16T11:46:42.000Z | 39.173913 | 108 | 0.804661 | 7,141 | package eu.dnetlib.iis.wf.referenceextraction.softwareurl;
import com.google.common.collect.Maps;
import eu.dnetlib.iis.wf.referenceextraction.FacadeContentRetriever;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class HttpServiceFacadeFactoryTest {
@Test
@DisplayName("Http service facade factory instantiates http service facade with default parameters")
public void givenHttpServiceFacadeFactory_whenInstantiated_thenServiceWithDefaultParametersIsCreated() {
HttpServiceFacadeFactory factory = new HttpServiceFacadeFactory();
FacadeContentRetriever<String, String> service = factory.instantiate(Maps.newHashMap());
assertNotNull(service);
assertTrue(service instanceof HttpServiceFacade);
}
} |
3e10f54fb7b60b620e83150740189b644f0a61ee | 3,784 | java | Java | src/main/java/com/github/hcsp/Crawler.java | GrumpyCitizenBear/zxh-crawler | 5d539715a72a517e7815803344ee527efa4f5b66 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/hcsp/Crawler.java | GrumpyCitizenBear/zxh-crawler | 5d539715a72a517e7815803344ee527efa4f5b66 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/hcsp/Crawler.java | GrumpyCitizenBear/zxh-crawler | 5d539715a72a517e7815803344ee527efa4f5b66 | [
"Apache-2.0"
] | null | null | null | 33.192982 | 163 | 0.642178 | 7,142 | package com.github.hcsp;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.sql.*;
import java.util.stream.Collectors;
public class Crawler {
private CrawlerDao dao = new MyBatisCrawlerDao();
public void run() throws SQLException, IOException {
String link;
//从数据库中加载下一个链接,如果能加载到,则进行循环
while ((link = dao.getNextLinkThenDelete()) != null) {
//Create a pool to hold links
if (dao.isLinkProcessed(link)) {
continue;
}
if (isInterestingLink(link)) {
System.out.println(link);
Document doc = httpGetAndParseHtml(link);
parseUrlsFromPageAndStoreIntoDatabase(doc);
storeIntoDatabaseIfItIsNewsPage(doc, link);
dao.insertProcessedLink(link);
}
}
}
@SuppressFBWarnings("DMI_CONSTANT_DB_PASSWORD")
public static void main(String[] args) throws SQLException, IOException {
new Crawler().run();
}
private void parseUrlsFromPageAndStoreIntoDatabase(Document doc) throws SQLException {
for (Element aTag : doc.select("a")) {
String href = aTag.attr("href");
if (href.startsWith("//")) {
href = "https:" + href;
}
if (!href.toLowerCase().startsWith("javascript")) {
dao.insertLinkToBeProcessed(href);
// dao.updateDatabase(href, "INSERT INTO LINKS_TO_BE_PROCESSED (link)values(?)");
}
}
}
private void storeIntoDatabaseIfItIsNewsPage(Document doc, String link) throws SQLException {
//假如这是一个新闻的详情页面,那么就存入数据库,否则什么都不做。
Elements articleTags = doc.select("article");
if (!articleTags.isEmpty()) {
for (Element articleTag : articleTags) {
String title = articleTags.get(0).child(0).text();
String content = articleTag.select("p").stream().map(Element::text).collect(Collectors.joining("\n"));
dao.insertNewsIntoDatabase(link, title, content);
System.out.println(title);
}
}
}
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE")
private static Document httpGetAndParseHtml(String link) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(link);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity);
return Jsoup.parse(html);
}
}
private static boolean isInterestingLink(String link) {
return (isNewsPage(link) || isIndexPage(link)) &&
isNotLoginPage(link);
}
private static boolean isIndexPage(String link) {
return "https://sina.cn".equals(link);
}
private static boolean isNewsPage(String link) {
return link.contains("news.sina.cn");
}
private static boolean isNotLoginPage(String link) {
return !link.contains("passport.sina.cn");
}
}
|
3e10f5998252cd1e9283bb80c0770fb2775a7bf7 | 2,469 | java | Java | pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/sunsecure/MethodReturnsInternalArrayRule.java | magnologan/pmd | 76af873708d4c8aecbfd5b1b7d8e9a7859ad54bd | [
"Apache-2.0"
] | null | null | null | pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/sunsecure/MethodReturnsInternalArrayRule.java | magnologan/pmd | 76af873708d4c8aecbfd5b1b7d8e9a7859ad54bd | [
"Apache-2.0"
] | null | null | null | pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/sunsecure/MethodReturnsInternalArrayRule.java | magnologan/pmd | 76af873708d4c8aecbfd5b1b7d8e9a7859ad54bd | [
"Apache-2.0"
] | null | null | null | 35.782609 | 101 | 0.638315 | 7,143 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.sunsecure;
import java.util.List;
import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.java.ast.ASTTypeDeclaration;
/**
* Implementation note: this rule currently ignores return types of y.x.z,
* currently it handles only local type fields.
* Created on Jan 17, 2005
*
* @author mgriffa
*/
public class MethodReturnsInternalArrayRule extends AbstractSunSecureRule {
@Override
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if (node.isInterface()) {
return data;
}
return super.visit(node, data);
}
@Override
public Object visit(ASTMethodDeclaration method, Object data) {
if (!method.getResultType().returnsArray()) {
return data;
}
List<ASTReturnStatement> returns = method.findDescendantsOfType(ASTReturnStatement.class);
ASTTypeDeclaration td = method.getFirstParentOfType(ASTTypeDeclaration.class);
for (ASTReturnStatement ret: returns) {
final String vn = getReturnedVariableName(ret);
if (!isField(vn, td)) {
continue;
}
if (ret.findDescendantsOfType(ASTPrimarySuffix.class).size() > 2) {
continue;
}
if (ret.hasDescendantOfType(ASTAllocationExpression.class)) {
continue;
}
if (!isLocalVariable(vn, method)) {
addViolation(data, ret, vn);
} else {
// This is to handle field hiding
final ASTPrimaryPrefix pp = ret.getFirstDescendantOfType(ASTPrimaryPrefix.class);
if (pp != null && pp.usesThisModifier()) {
final ASTPrimarySuffix ps = ret.getFirstDescendantOfType(ASTPrimarySuffix.class);
if (ps.hasImageEqualTo(vn)) {
addViolation(data, ret, vn);
}
}
}
}
return data;
}
}
|
3e10f5d2d22a9a90cadae8ad2ac885a7b9776d1d | 8,382 | java | Java | GediCore/src/gedi/util/math/stat/counting/Counter.java | erhard-lab/gedi | 4d045235873a720f12bd7799d136c2e1fa70af83 | [
"Apache-2.0"
] | 17 | 2018-03-13T11:02:02.000Z | 2021-12-31T06:30:39.000Z | GediCore/src/gedi/util/math/stat/counting/Counter.java | erhard-lab/gedi | 4d045235873a720f12bd7799d136c2e1fa70af83 | [
"Apache-2.0"
] | 67 | 2018-03-14T00:47:12.000Z | 2022-03-16T12:03:42.000Z | GediCore/src/gedi/util/math/stat/counting/Counter.java | erhard-lab/gedi | 4d045235873a720f12bd7799d136c2e1fa70af83 | [
"Apache-2.0"
] | 7 | 2018-07-28T15:39:10.000Z | 2021-12-04T01:32:21.000Z | 23.880342 | 112 | 0.642806 | 7,144 | /**
*
* Copyright 2017 Florian Erhard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package gedi.util.math.stat.counting;
import gedi.util.ArrayUtils;
import gedi.util.FunctorUtils;
import gedi.util.ReflectionUtils;
import gedi.util.StringUtils;
import gedi.util.datastructure.dataframe.DataColumn;
import gedi.util.datastructure.dataframe.DataFrame;
import gedi.util.datastructure.dataframe.DataFrameBuilder;
import gedi.util.datastructure.dataframe.IntegerDataColumn;
import gedi.util.functions.EI;
import gedi.util.functions.ExtendedIterator;
import gedi.util.math.stat.binning.IntegerBinning;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
public class Counter<T> {
private LinkedHashMap<T,int[]> map = new LinkedHashMap<T, int[]>();
private int[] total;
private int dim;
private String[] dimNames = null;
private String elementName;
public Counter() {
this("Element",1);
}
public Counter(String elementName, int dim) {
this.dim = dim;
this.elementName = elementName;
this.total = new int[dim];
}
public Counter(String elementName, String... dimNames) {
this.dimNames = dimNames;
this.elementName = elementName;
this.dim = dimNames.length;
this.total = new int[dim];
}
public void clear() {
Arrays.fill(total, 0);
for (int[] v : map.values())
Arrays.fill(v, 0);
}
/**
* Inits an element (i.e. its count is 0). Do this this if you want a specific reporting order!
* Does nothing if the element is already present!
* @param o
*/
public void init(T o) {
map.computeIfAbsent(o, k->new int[dim]);
}
/**
* Inits multiple elements (i.e. its count is 0). Do this this if you want a specific reporting order!
* Does nothing if the element is already present!
* @param o
*/
public void init(Iterator<T> o) {
while (o.hasNext())
init(o.next());
}
public String getName(int d) {
if (dimNames==null && dim==1) return "Count";
return dimNames==null?"Count "+d:dimNames[d];
}
public Counter<T> sortByCount() {
Comparator<int[]> ac = FunctorUtils.intArrayComparator();
return sort((a,b)->ac.compare(get(b), get(a)));
}
public Counter<T> sort() {
return sort((Comparator<T>)FunctorUtils.naturalComparator());
}
public Counter<T> sort(Comparator<T> comp) {
T[] keys = map.keySet().toArray((T[])new Object[0]);
Arrays.sort(keys,comp);
LinkedHashMap<T,int[]> map2 = new LinkedHashMap<T, int[]>();
for (T k : keys)
map2.put(k, map.get(k));
map = map2;
return this;
}
public void cum() {
int[] last = null;
for (int[] c : map.values()) {
if (last!=null)
ArrayUtils.add(c, last);
last = c;
}
}
public T getMaxElement(int d) {
int m = -1;
T re = null;
for (T k : map.keySet()) {
int[] v = map.get(k);
if (v[d]>m) {
m = v[d];
re = k;
}
}
return re;
}
public Set<T> elements() {
return map.keySet();
}
public T first() {
Map.Entry<T, int[]> head;
try {
head = ReflectionUtils.get(map, "head");
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("Cannot get head from map!");
}
return head.getKey();
}
public T last() {
Map.Entry<T, int[]> tail;
try {
tail = ReflectionUtils.get(map, "tail");
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("Cannot get tail from map!");
}
return tail.getKey();
}
/**
* Adds a new element to this bag in all dimensions
* @param o
*/
public boolean add(T o) {
int[] a = map.computeIfAbsent(o, k->new int[dim]);
for (int d = 0; d<dim; d++) {
a[d]++;
total[d]++;
}
return true;
}
/**
* Adds a new element to this bag in all dimensions greater or equal to d
* @param o
*/
public boolean addAtLeast(T o, int d) {
int[] a = map.computeIfAbsent(o, k->new int[dim]);
for (int d2 = d; d2<dim; d2++) {
a[d2]++;
total[d2]++;
}
return true;
}
/**
* Adds a new element to this bag in all dimensions less or equal to d
* @param o
*/
public boolean addAtMost(T o, int d) {
int[] a = map.computeIfAbsent(o, k->new int[dim]);
for (int d2 = 0; d2<=d; d2++) {
a[d2]++;
total[d2]++;
}
return true;
}
/**
* Adds a new element to this bag
* @param o
*/
public boolean add(T o, int d) {
map.computeIfAbsent(o, k->new int[dim])[d]++;
total[d]++;
return true;
}
/**
* Adds a new element to this bag
* @param o
*/
public boolean add(T o, int[] d) {
ArrayUtils.add(map.computeIfAbsent(o, k->new int[dim]),d);
ArrayUtils.add(total,d);
return true;
}
public int[] get(T o) {
int[] re = map.get(o);
if (re==null) return new int[dim];
return re;
}
public int[] total(T o) {
return total;
}
public int get(T o, int d) {
int[] re = map.get(o);
if (re==null) return 0;
return re[d];
}
public int getDimensions() {
return dim;
}
public Set<T> getObjects() {
return map.keySet();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((map == null) ? 0 : map.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Counter<T> other = (Counter<T>) obj;
if (map == null) {
if (other.map != null)
return false;
} else if (!map.equals(other.map))
return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(elementName);
for (int i=0; i<dim; i++)
sb.append("\t").append(getName(i));
sb.append("\n");
for (T e : map.keySet())
sb.append(e.toString()).append("\t").append(StringUtils.concat("\t",map.get(e))).append("\n");
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
public String toSingleLine() {
if (map.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
for (T e : map.keySet())
sb.append(e.toString()).append(":").append(StringUtils.concat(",",map.get(e))).append(" ");
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
public int[] total() {
return total;
}
public boolean contains(T o) {
return map.containsKey(o);
}
public ExtendedIterator<ItemCount<T>> iterator() {
ExtendedIterator<T> it = EI.wrap(map.keySet());
return it.map(item->new ItemCount<T>(item,map.get(item)));
}
public DataFrame toDataFrame() {
DataFrame re = new DataFrame();
re.add(DataColumn.fromCollectionAsFactor(elementName, EI.wrap(map.keySet()).map(a->StringUtils.toString(a))));
for (int i=0; i<dim; i++) {
int ui = i;
re.add(DataColumn.fromCollection(getName(i), EI.wrap(map.keySet()).mapToInt(a->map.get(a)[ui])));
}
return re;
}
public String getElementName() {
return elementName;
}
public <K> Counter<K> bin(Function<T,K> binner) {
Counter<K> re = new Counter<>(elementName, dim);
for (T k : map.keySet())
re.add(binner.apply(k), map.get(k));
return re;
}
public double entropy(int dim) {
double sum = 0;
for (int[] s : map.values()) {
if (s[dim]>0) {
double p = s[dim]/(double)total[dim];
sum+=p*Math.log(p);
}
}
return -sum/Math.log(2);
}
/**
* Just as for sequence logos (2 is max, 0 is no information)
* @param dim
* @return
*/
public double informationContent(int dim) {
double corr = 1/Math.log(2)*(map.values().size()-1)/(2*total[dim]);
return Math.log(map.values().size())/Math.log(2)-(entropy(dim)+corr);
}
public double uncorrectedInformationContent(int dim) {
return Math.log(map.values().size())/Math.log(2)-(entropy(dim));
}
}
|
3e10f752d6eaac93a577f19013200c9890264d8f | 1,479 | java | Java | src/main/java/com/baselogic/tutorials/domain/AuditableEntity.java | mickknutson/JavaExamples | c0a1060e6d2255ad73e320a8912aae6c2ea92979 | [
"Apache-2.0"
] | 1 | 2021-04-05T15:49:13.000Z | 2021-04-05T15:49:13.000Z | src/main/java/com/baselogic/tutorials/domain/AuditableEntity.java | mickknutson/JavaExamples | c0a1060e6d2255ad73e320a8912aae6c2ea92979 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/baselogic/tutorials/domain/AuditableEntity.java | mickknutson/JavaExamples | c0a1060e6d2255ad73e320a8912aae6c2ea92979 | [
"Apache-2.0"
] | 2 | 2019-09-16T09:46:37.000Z | 2021-07-05T20:54:48.000Z | 32.152174 | 142 | 0.706558 | 7,145 | package com.baselogic.tutorials.domain;
import java.util.Calendar;
/**
* BASE Entity Class
*
* @author Mick Knutson
* @see <a href="http://www.baselogic.com">Blog: http://baselogic.com</a>
* @see <a href="http://linkedin.com/in/mickknutson">LinkedIN: http://linkedin.com/in/mickknutson</a>
* @see <a href="http://twitter.com/mickknutson">Twitter: http://twitter.com/mickknutson</a>
* @see <a href="http://github.com/mickknutson">Git hub: http://github.com/mickknutson</a>
* @see <a href="http://www.packtpub.com/java-ee6-securing-tuning-extending-enterprise-applications-cookbook/book">JavaEE 6 Cookbook Packt</a>
* @see <a href="http://www.amazon.com/Cookbook-securing-extending-enterprise-applications/dp/1849683166">JavaEE 6 Cookbook Amazon</a>
* @since 2012
*/
public abstract class AuditableEntity extends AbstractValueObject {
public static ThreadLocal currentUser = new ThreadLocal();
private String auditUser;
private Calendar auditTimestamp;
public String getAuditUser() {
return auditUser;
}
public void setAuditUser(String auditUser) {
this.auditUser = auditUser;
}
public Calendar getAuditTimestamp() {
return auditTimestamp;
}
public void setAuditTimestamp(Calendar auditTimestamp) {
this.auditTimestamp = auditTimestamp;
}
public void updateAuditInfo() {
setAuditUser((String) currentUser.get());
setAuditTimestamp(Calendar.getInstance());
}
}
|
3e10f7836cc6337f927b4aa014f702ad6808c97f | 1,245 | java | Java | decompile/output/app/src/main/java/org/aspectj/internal/lang/reflect/PointcutBasedPerClauseImpl.java | mio4kon/AspectMahou | 4b33acb83801c88d918a854dd6831e2cce35f868 | [
"MIT"
] | null | null | null | decompile/output/app/src/main/java/org/aspectj/internal/lang/reflect/PointcutBasedPerClauseImpl.java | mio4kon/AspectMahou | 4b33acb83801c88d918a854dd6831e2cce35f868 | [
"MIT"
] | null | null | null | decompile/output/app/src/main/java/org/aspectj/internal/lang/reflect/PointcutBasedPerClauseImpl.java | mio4kon/AspectMahou | 4b33acb83801c88d918a854dd6831e2cce35f868 | [
"MIT"
] | null | null | null | 27.666667 | 89 | 0.738956 | 7,146 | package org.aspectj.internal.lang.reflect;
import org.aspectj.lang.reflect.PerClauseKind;
import org.aspectj.lang.reflect.PointcutBasedPerClause;
import org.aspectj.lang.reflect.PointcutExpression;
public class PointcutBasedPerClauseImpl
extends PerClauseImpl
implements PointcutBasedPerClause
{
private final PointcutExpression pointcutExpression;
public PointcutBasedPerClauseImpl(PerClauseKind paramPerClauseKind, String paramString)
{
super(paramPerClauseKind);
pointcutExpression = new PointcutExpressionImpl(paramString);
}
public PointcutExpression getPointcutExpression()
{
return pointcutExpression;
}
public String toString()
{
StringBuffer localStringBuffer = new StringBuffer();
switch (1.$SwitchMap$org$aspectj$lang$reflect$PerClauseKind[getKind().ordinal()])
{
}
for (;;)
{
localStringBuffer.append(pointcutExpression.asString());
localStringBuffer.append(")");
return localStringBuffer.toString();
localStringBuffer.append("percflow(");
continue;
localStringBuffer.append("percflowbelow(");
continue;
localStringBuffer.append("pertarget(");
continue;
localStringBuffer.append("perthis(");
}
}
}
|
3e10f7ebbd652a4253a5958e4e1738b0407ba809 | 323 | java | Java | ClientLib/src/main/java/Graphics/Components/Tasks/ElementalTask.java | HyperSphereStudio/HyperSphereEngine | e2dcd108ff4c35e215ef2545c0861ec8f8a716d5 | [
"MIT"
] | 1 | 2020-11-24T01:52:44.000Z | 2020-11-24T01:52:44.000Z | ClientLib/src/main/java/Graphics/Components/Tasks/ElementalTask.java | HyperSphereStudio/HyperSphereEngine | e2dcd108ff4c35e215ef2545c0861ec8f8a716d5 | [
"MIT"
] | null | null | null | ClientLib/src/main/java/Graphics/Components/Tasks/ElementalTask.java | HyperSphereStudio/HyperSphereEngine | e2dcd108ff4c35e215ef2545c0861ec8f8a716d5 | [
"MIT"
] | null | null | null | 17.944444 | 48 | 0.671827 | 7,147 | package Graphics.Components.Tasks;
import com.badlogic.gdx.math.Rectangle;
public abstract class ElementalTask<T> {
public T t;
public Rectangle bounds;
public ElementalTask(T t, Rectangle bounds){
this.t = t;
this.bounds = bounds;
}
public abstract void runTask(float... data);
}
|
3e10f82d811df68b360ebe7d3488a769855f7fd1 | 2,203 | java | Java | src/test/java/org/springframework/hateoas/mvc/HeaderLinksResponseEntityUnitTest.java | JamesTPF/spring-hateoas | f8216b58f51114cb538fb734e9ff54a62b5008d9 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/springframework/hateoas/mvc/HeaderLinksResponseEntityUnitTest.java | JamesTPF/spring-hateoas | f8216b58f51114cb538fb734e9ff54a62b5008d9 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/springframework/hateoas/mvc/HeaderLinksResponseEntityUnitTest.java | JamesTPF/spring-hateoas | f8216b58f51114cb538fb734e9ff54a62b5008d9 | [
"Apache-2.0"
] | 2 | 2020-11-26T13:27:14.000Z | 2022-03-20T02:12:55.000Z | 31.927536 | 105 | 0.758965 | 7,148 | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas.mvc;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Unit tests for {@link HeaderLinksResponseEntity}.
*
* @author Oliver Gierke
*/
public class HeaderLinksResponseEntityUnitTest {
static final Object CONTENT = new Object();
static final Link LINK = new Link("href", "rel");
Resource<Object> resource = new Resource<Object>(CONTENT, LINK);
ResponseEntity<Resource<Object>> entity = new ResponseEntity<Resource<Object>>(resource, HttpStatus.OK);
@Test
public void movesRootResourceLinksToHeader() {
HttpEntity<Resource<Object>> wrapper = HeaderLinksResponseEntity.wrap(entity);
// No links in resource anymore
assertThat(wrapper.getBody().getLinks(), is(Matchers.<Link> empty()));
// Link found in header
List<String> linkHeader = wrapper.getHeaders().get("Link");
assertThat(linkHeader, hasSize(1));
Link link = Link.valueOf(linkHeader.get(0));
assertThat(link, is(LINK));
}
@Test
public void defaultStatusCodeToOkForHttpEntities() {
HttpEntity<Resource<Object>> entity = new HttpEntity<Resource<Object>>(resource);
ResponseEntity<Resource<Object>> wrappedEntity = HeaderLinksResponseEntity.wrap(entity);
assertThat(wrappedEntity.getStatusCode(), is(HttpStatus.OK));
}
}
|
3e10f8a3c828561a2ce74c3c9c75979e57bed3e3 | 30,942 | java | Java | old/src/main/java/com/guider/healthring/b30/b30minefragment/B30MineFragment.java | 18271261642/RingmiiHX | 3f1f840a1727cdf3ee39bc1b8d8aca4d2c3ebfcb | [
"Apache-2.0"
] | null | null | null | old/src/main/java/com/guider/healthring/b30/b30minefragment/B30MineFragment.java | 18271261642/RingmiiHX | 3f1f840a1727cdf3ee39bc1b8d8aca4d2c3ebfcb | [
"Apache-2.0"
] | null | null | null | old/src/main/java/com/guider/healthring/b30/b30minefragment/B30MineFragment.java | 18271261642/RingmiiHX | 3f1f840a1727cdf3ee39bc1b8d8aca4d2c3ebfcb | [
"Apache-2.0"
] | 1 | 2021-05-13T03:02:35.000Z | 2021-05-13T03:02:35.000Z | 43.336134 | 132 | 0.591106 | 7,149 | package com.guider.healthring.b30.b30minefragment;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.aigestudio.wheelpicker.widgets.ProfessionPick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.guider.healthring.Commont;
import com.guider.healthring.MyApp;
import com.guider.healthring.R;
import com.guider.healthring.activity.LoginActivity;
import com.guider.healthring.activity.MyPersonalActivity;
import com.guider.healthring.b30.B30DeviceActivity;
import com.guider.healthring.b30.B30SysSettingActivity;
import com.guider.healthring.b30.bean.BaseResultVoNew;
import com.guider.healthring.b31.BemoSwitchActivity;
import com.guider.healthring.b31.bpoxy.ReadHRVSoDataForDevices;
import com.guider.healthring.bean.GuiderUserInfo;
import com.guider.healthring.bleutil.MyCommandManager;
import com.guider.healthring.siswatch.LazyFragment;
import com.guider.healthring.siswatch.NewSearchActivity;
import com.guider.healthring.siswatch.utils.WatchUtils;
import com.guider.healthring.util.LocalizeTool;
import com.guider.healthring.util.OkHttpTool;
import com.guider.healthring.util.SharedPreferencesUtils;
import com.guider.healthring.util.ToastUtil;
import com.guider.healthring.w30s.utils.httputils.RequestPressent;
import com.guider.healthring.w30s.utils.httputils.RequestView;
import com.veepoo.protocol.listener.base.IBleWriteResponse;
import com.veepoo.protocol.listener.data.ICustomSettingDataListener;
import com.veepoo.protocol.model.enums.EFunctionStatus;
import com.veepoo.protocol.model.settings.CustomSetting;
import com.veepoo.protocol.model.settings.CustomSettingData;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by Administrator on 2018/7/20.
*/
/**
* B30 我的界面
*/
public class B30MineFragment extends LazyFragment implements RequestView {
private static final String TAG = "B30MineFragment";
View b30MineView;
Unbinder unbinder;
@BindView(R.id.b30userImageHead)
ImageView b30UserImageHead;
@BindView(R.id.b30UserNameTv)
TextView b30UserNameTv;
@BindView(R.id.commentB30TitleTv)
TextView commentB30TitleTv;
@BindView(R.id.b30MineDeviceTv)
TextView b30MineDeviceTv;
/**
* 公制|英制
*/
@BindView(R.id.b30MineUnitTv)
TextView b30MineUnitTv;
@BindView(R.id.b30MineSportGoalTv)
TextView b30MineSportGoalTv;
@BindView(R.id.b30MineSleepGoalTv)
TextView b30MineSleepGoalTv;
private RequestPressent requestPressent;
private AlertDialog.Builder builder;
//运动目标
ArrayList<String> sportGoalList;
//睡眠目标
ArrayList<String> sleepGoalList;
/**
* 本地化工具
*/
private LocalizeTool mLocalTool;
/**
* 是否修改了个人中心的用户资料
*/
private boolean updatePersonalInfo;
private Gson gson = new Gson();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
b30MineView = inflater.inflate(R.layout.fragment_b30_mine_layout, container, false);
unbinder = ButterKnife.bind(this, b30MineView);
initViews();
initData();
return b30MineView;
}
private void initData() {
if (getActivity() != null) {
mLocalTool = new LocalizeTool(getActivity());
// readCustomSetting();// 读取手环的自定义配置(是否打开公制)
requestPressent = new RequestPressent();
requestPressent.attach(this);
sportGoalList = new ArrayList<>();
sleepGoalList = new ArrayList<>();
for (int i = 1000; i <= 64000; i += 1000) {
sportGoalList.add(i + "");
}
for (int i = 1; i < 48; i++) {
sleepGoalList.add(WatchUtils.mul(Double.valueOf(i), 0.5) + "");
}
//显示运动目标和睡眠目标
int b30SportGoal = (int) SharedPreferencesUtils.getParam(getActivity(), "b30Goal", 0);
b30MineSportGoalTv.setText(b30SportGoal + "");
//睡眠
String b30SleepGoal = (String) SharedPreferencesUtils.getParam(MyApp.getContext(), "b30SleepGoal", "");
if (!WatchUtils.isEmpty(b30SleepGoal)) {
b30MineSleepGoalTv.setText(b30SleepGoal + "");
}
}
}
//获取盖德的用户信息
private void getGadiDeUserInfoData() {
try {
long accountId = (long) SharedPreferencesUtils.getParam(getContext(),"accountIdGD",0L);
if(accountId == 0)
return;
String guiderUrl ="http://api.guiderhealth.com/api/v1/userinfo?accountId="+accountId;
if(requestPressent != null){
requestPressent.getRequestJSONObjectGet(11,guiderUrl,getContext(),11);
}
}catch (Exception e){
e.printStackTrace();
}
}
private void initViews() {
commentB30TitleTv.setText(getResources().getString(R.string.menu_settings));
}
@SuppressLint("SetTextI18n")
@Override
protected void onFragmentVisibleChange(boolean isVisible) {
if (isVisible) {
Log.e(TAG, "onFragmentVisibleChange----------执行");
readDevicesSwithStute();// 读取手环的自定义配置(是否打开公制)
if (getActivity() != null && !getActivity().isFinishing()) {
if (MyCommandManager.DEVICENAME != null) {
String bleMac = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC);
b30MineDeviceTv.setText(MyCommandManager.DEVICENAME + " " + bleMac);
} else {
b30MineDeviceTv.setText(getResources().getString(R.string.string_not_coon));//"未连接"
}
}
if (updatePersonalInfo) {
updatePersonalInfo = false;
}
}
}
@Override
public void onResume() {
super.onResume();
getGadiDeUserInfoData();
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
if (requestPressent != null) {
requestPressent.detach();
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@OnClick({R.id.b30userImageHead, R.id.b30MineDeviceRel, R.id.b30MineSportRel,
R.id.b30MineSleepRel, R.id.b30MineUnitRel, R.id.b30MineAboutRel,
R.id.b30LogoutBtn,R.id.bemoRel})
public void onClick(View view) {
switch (view.getId()) {
case R.id.b30userImageHead: //头像
startActivity(new Intent(getActivity(), MyPersonalActivity.class));
break;
case R.id.b30MineDeviceRel: //设备
if (!getActivity().isFinishing()) {
if (MyCommandManager.DEVICENAME != null) {
startActivity(new Intent(getActivity(), B30DeviceActivity.class));
} else {
startActivity(new Intent(getActivity(), NewSearchActivity.class));
getActivity().finish();
}
}
break;
case R.id.b30MineSportRel: //运动目标
if (!getActivity().isFinishing()) {
if (MyCommandManager.DEVICENAME != null) {
setSportGoal(); //设置运动目标
} else {
startActivity(new Intent(getActivity(), NewSearchActivity.class));
getActivity().finish();
}
}
break;
case R.id.b30MineSleepRel: //睡眠目标
if (!getActivity().isFinishing()) {
if (MyCommandManager.DEVICENAME != null) {
setSleepGoal(); //设置睡眠目标
} else {
startActivity(new Intent(getActivity(), NewSearchActivity.class));
getActivity().finish();
}
}
break;
case R.id.b30MineUnitRel: //单位设置
if (!getActivity().isFinishing()) {
if (MyCommandManager.DEVICENAME != null) {
showUnitDialog();
} else {
startActivity(new Intent(getActivity(), NewSearchActivity.class));
getActivity().finish();
}
}
break;
case R.id.b30MineAboutRel: //关于
startActivity(new Intent(getActivity(), B30SysSettingActivity.class));
break;
case R.id.b30LogoutBtn: //退出登录
longOutApp();
break;
case R.id.bemoRel:
startActivity(new Intent(getActivity(),BemoSwitchActivity.class));
break;
}
}
//运动过量提醒 B31不支持
EFunctionStatus isOpenSportRemain = EFunctionStatus.UNSUPPORT;
//血压/心率播报 B31不支持
EFunctionStatus isOpenVoiceBpHeart = EFunctionStatus.UNSUPPORT;
//查找手表 B31不支持
EFunctionStatus isOpenFindPhoneUI = EFunctionStatus.UNSUPPORT;
//秒表功能 支持
EFunctionStatus isOpenStopWatch;
//低压报警 支持
EFunctionStatus isOpenSpo2hLowRemind = EFunctionStatus.SUPPORT_OPEN;
//肤色功能 支持
EFunctionStatus isOpenWearDetectSkin = EFunctionStatus.SUPPORT_OPEN;
//自动接听来电 不支持
EFunctionStatus isOpenAutoInCall = EFunctionStatus.UNSUPPORT;
//自动检测HRV 支持
EFunctionStatus isOpenAutoHRV = EFunctionStatus.SUPPORT_OPEN;
//断连提醒 支持
EFunctionStatus isOpenDisconnectRemind;
//SOS 不支持
EFunctionStatus isOpenSOS = EFunctionStatus.UNSUPPORT;
//开关设置
private void setSwitchCheck() {
if(MyCommandManager.DEVICENAME == null)
return;
showLoadingDialog("loading...");
//保存的状态
boolean isSystem = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISSystem, true);//是否为公制
boolean is24Hour = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.IS24Hour, true);//是否为24小时制
boolean isAutomaticHeart = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISAutoHeart, true);//自动测量心率
boolean isAutomaticBoold = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISAutoBp, true);//自动测量血压
boolean isSecondwatch = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISSecondwatch, false);//秒表
boolean isWearCheck = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISWearcheck, true);//佩戴
boolean isFindPhone = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISFindPhone, false);//查找手机
boolean CallPhone = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISCallPhone, true);//来电
boolean isDisconn = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISDisAlert, false);//断开连接提醒
boolean isSos = (boolean) SharedPreferencesUtils.getParam(MyApp.getContext(), Commont.ISHelpe, false);//sos
//秒表功能
if (isSecondwatch) {
isOpenStopWatch = EFunctionStatus.SUPPORT_OPEN;
} else {
isOpenStopWatch = EFunctionStatus.SUPPORT_CLOSE;
}
//佩戴
if (isWearCheck) {
isOpenWearDetectSkin = EFunctionStatus.SUPPORT_OPEN;
} else {
isOpenWearDetectSkin = EFunctionStatus.SUPPORT_CLOSE;
}
//断连提醒
if (isDisconn) {
isOpenDisconnectRemind = EFunctionStatus.SUPPORT_OPEN;
} else {
isOpenDisconnectRemind = EFunctionStatus.SUPPORT_CLOSE;
}
Log.e(TAG, "----- SOSa啊 " + isSos);
//SOS
if (isSos) {
isOpenSOS = EFunctionStatus.SUPPORT_OPEN;
} else {
isOpenSOS = EFunctionStatus.SUPPORT_CLOSE;
}
Log.i("bbbbbbbbo" , "B31MineFragment");
CustomSetting customSetting = new CustomSetting(true, isSystem, is24Hour, isAutomaticHeart,
isAutomaticBoold, isOpenSportRemain, isOpenVoiceBpHeart, isOpenFindPhoneUI, isOpenStopWatch, isOpenSpo2hLowRemind,
isOpenWearDetectSkin, isOpenAutoInCall, isOpenAutoHRV, isOpenDisconnectRemind, isOpenSOS);
Log.e(TAG, "-----新设置的值啊---customSetting=" + customSetting.toString());
MyApp.getInstance().getVpOperateManager().changeCustomSetting(iBleWriteResponse, new ICustomSettingDataListener() {
@Override
public void OnSettingDataChange(CustomSettingData customSettingData) {
closeLoadingDialog();
Log.e(TAG, "--新设置的值结果--customSettingData=" + customSettingData.toString());
if (getActivity() != null && !getActivity().isFinishing()) {
if (customSettingData.getMetricSystem() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, true);//是否为公制
b30MineUnitTv.setText(R.string.setkm);
mLocalTool.putMetricSystem(true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, false);//是否为公制
b30MineUnitTv.setText(R.string.setmi);
mLocalTool.putMetricSystem(false);
}
Intent intent = new Intent();
intent.setAction("com.example.bozhilun.android.siswatch.run.UNIT");
getActivity().sendBroadcast(intent);
}
}
}, customSetting);
}
private IBleWriteResponse iBleWriteResponse = new IBleWriteResponse() {
@Override
public void onResponse(int i) {
}
};
private void longOutApp() {
new MaterialDialog.Builder(getActivity())
.title(getResources().getString(R.string.prompt))
.content(getResources().getString(R.string.exit_login))
.positiveText(getResources().getString(R.string.confirm))
.negativeText(getResources().getString(R.string.cancle))
.onPositive(new com.afollestad.materialdialogs.MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
unbindDevices();
if (MyCommandManager.DEVICENAME != null) {
MyApp.getInstance().getVpOperateManager().disconnectWatch(new IBleWriteResponse() {
@Override
public void onResponse(int state) {
if (state == -1) {
SharedPreferencesUtils.saveObject(MyApp.getContext(), "mylanya", "");
SharedPreferencesUtils.saveObject(MyApp.getContext(), Commont.BLEMAC, "");
MyApp.getInstance().setMacAddress(null);// 清空全局的
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userId", null);
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userInfo", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), "isFirst", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.DEVICESCODE, "0000");
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
}
});
}
else {
MyCommandManager.DEVICENAME = null;
MyCommandManager.ADDRESS = null;
SharedPreferencesUtils.saveObject(MyApp.getContext(), "mylanya", "");
SharedPreferencesUtils.saveObject(MyApp.getContext(), Commont.BLEMAC, "");
MyApp.getInstance().setMacAddress(null);// 清空全局的
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userId", null);
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userInfo", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), "isFirst", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.DEVICESCODE, "0000");
startActivity(new Intent(getActivity(), LoginActivity.class));
}
MyCommandManager.DEVICENAME = null;
MyCommandManager.ADDRESS = null;
SharedPreferencesUtils.saveObject(MyApp.getContext(), "mylanya", "");
SharedPreferencesUtils.saveObject(MyApp.getContext(), Commont.BLEMAC, "");
MyApp.getInstance().setMacAddress(null);// 清空全局的
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userId", null);
SharedPreferencesUtils.saveObject(MyApp.getContext(), "userInfo", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), "isFirst", "");
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.DEVICESCODE, "0000");
// startActivity(new Intent(getActivity(), LoginActivity.class));
// if (BemoServiceConnection.getInstance()!=null){
// getActivity().unbindService(BemoServiceConnection.getInstance());
// }
//SharedPreferences_status.save_IMEI(MyApplication.context, "");
SharedPreferencesUtils.setParam(getContext(), Commont.BATTERNUMBER, 0);//电池
SharedPreferencesUtils.setParam(getContext(), "personContent", "");//SOS 内容
SharedPreferencesUtils.setParam(getContext(), "personOne", "");//SOS 联系人 名字 1
SharedPreferencesUtils.setParam(getContext(), "personTwo", "");//SOS 联系人 名字 2
SharedPreferencesUtils.setParam(getContext(), "personThree", "");//SOS 联系人 名字 3
SharedPreferencesUtils.setParam(getContext(), "NameOne", "");//SOS 联系人 电话 1
SharedPreferencesUtils.setParam(getContext(), "NameTwo", "");//SOS 联系人 电话 2
SharedPreferencesUtils.setParam(getContext(), "NameThree", "");//SOS 联系人 电话 3
new LocalizeTool(MyApp.getContext()).putUpdateDate(WatchUtils
.obtainFormatDate(1));// 同时把数据更新时间清楚更新最后更新数据的时间
//getActivity().finish();
}
}).show();
}
/**
* 解绑设备
*/
private final String Base_Url = "http://47.92.218.150:8082/api/v1/";
void unbindDevices() {
Long l;
Integer i;
long accountIdGD = (long) SharedPreferencesUtils.getParam(MyApp.getInstance(), "accountIdGD", 0L);
if (accountIdGD == 0L) return;
String deviceCode = (String) SharedPreferencesUtils.readObject(MyApp.getInstance(), Commont.BLEMAC);
String upStepPatch = Base_Url + "user/" + accountIdGD + "/device/unbind?deviceCode=" + deviceCode;
//{accountId}/deviceandcompany/bind?deviceCode=
OkHttpTool.getInstance().doDelete(upStepPatch, "", this, new OkHttpTool.HttpResult() {
@Override
public void onResult(String result) {
if (!WatchUtils.isEmpty(result)) {
BaseResultVoNew baseResultVoNew = new Gson().fromJson(result, BaseResultVoNew.class);
if (baseResultVoNew.getCode() == 0 || baseResultVoNew.getMsg().equals("您已经绑定该设备")) {
Log.e(TAG, "=======解绑该设备= " + result);
}
}
}
});
}
//设置运动目标
private void setSportGoal() {
ProfessionPick dailyumberofstepsPopWin = new ProfessionPick.Builder(getActivity(),
new ProfessionPick.OnProCityPickedListener() {
@Override
public void onProCityPickCompleted(String profession) {
b30MineSportGoalTv.setText(profession);
SharedPreferencesUtils.setParam(getActivity(), "b30Goal", Integer.valueOf(profession.trim()));
}
}).textConfirm(getResources().getString(R.string.confirm)) //text of confirm button
.textCancel(getResources().getString(R.string.cancle)) //text of cancel button
.btnTextSize(16) // button text size
.viewTextSize(25) // pick view text size
.colorCancel(Color.parseColor("#999999")) //color of cancel button
.colorConfirm(Color.parseColor("#009900"))//color of confirm button
.setProvinceList(sportGoalList) //min year in loop
.dateChose("8000") // date chose when init popwindow
.build();
dailyumberofstepsPopWin.showPopWin(getActivity());
}
//设置睡眠目标
private void setSleepGoal() {
ProfessionPick dailyumberofstepsPopWin = new ProfessionPick.Builder(getActivity(),
new ProfessionPick.OnProCityPickedListener() {
@Override
public void onProCityPickCompleted(String profession) {
b30MineSleepGoalTv.setText(profession);
SharedPreferencesUtils.setParam(getActivity(), "b30SleepGoal", profession.trim());
}
}).textConfirm(getResources().getString(R.string.confirm)) //text of confirm button
.textCancel(getResources().getString(R.string.cancle)) //text of cancel button
.btnTextSize(16) // button text size
.viewTextSize(25) // pick view text size
.colorCancel(Color.parseColor("#999999")) //color of cancel button
.colorConfirm(Color.parseColor("#009900"))//color of confirm button
.setProvinceList(sleepGoalList) //min year in loop
.dateChose("8.0") // date chose when init popwindow
.build();
dailyumberofstepsPopWin.showPopWin(getActivity());
}
//展示公英制
private void showUnitDialog() {
String runTypeString[] = new String[]{getResources().getString(R.string.setkm),
getResources().getString(R.string.setmi)};
builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.select_running_mode))
.setItems(runTypeString, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (i == 0) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, true);//是否为公制
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, false);//是否为公制
}
setSwitchCheck();
// changeCustomSetting(i == 0);
}
}).setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
/**
* 读取设备开关
*/
void readDevicesSwithStute() {
Log.e(TAG, "HRV-----Spo同步状态 " + ReadHRVSoDataForDevices.isUpdataHRV() + " == " + ReadHRVSoDataForDevices.isUpdataO2O());
if(MyCommandManager.DEVICENAME == null)
return;
if (!WatchUtils.isEmpty(MyCommandManager.DEVICENAME)
&& MyCommandManager.DEVICENAME.equals("500S")
&& (ReadHRVSoDataForDevices.isUpdataHRV() || ReadHRVSoDataForDevices.isUpdataO2O())) {
ToastUtil.showShort(getContext(), "HRV 同步中");
return;
}
MyApp.getInstance().getVpOperateManager().readCustomSetting(new IBleWriteResponse() {
@Override
public void onResponse(int i) {
}
}, new ICustomSettingDataListener() {
@Override
public void OnSettingDataChange(CustomSettingData customSettingData) {
// Log.e(TAG, "---自定义设置--=" + customSettingData.toString());
//查找手机
if (customSettingData.getFindPhoneUi() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISFindPhone, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISFindPhone, false);
}
//公英制
if (customSettingData.getMetricSystem() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, true);//是否为公制
b30MineUnitTv.setText(R.string.setkm);
mLocalTool.putMetricSystem(true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSystem, false);//是否为公制
b30MineUnitTv.setText(R.string.setmi);
mLocalTool.putMetricSystem(false);
}
//秒表
if (customSettingData.getSecondsWatch() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSecondwatch, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISSecondwatch, false);
}
//读取心率自动检测功能是否开启
if (customSettingData.getAutoHeartDetect() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISAutoHeart, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISAutoHeart, false);
}
//读取血压自动检测功能是否开启
if (customSettingData.getAutoBpDetect() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISAutoBp, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISAutoBp, false);
}
//读取设备是否为24小时制
if (customSettingData.isIs24Hour()) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.IS24Hour, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.IS24Hour, false);
}
//是否开启断连提醒
if (customSettingData.getDisconnectRemind() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISDisAlert, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISDisAlert, false);
}
//判断是否开启SOS
if (customSettingData.getSOS() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISHelpe, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISHelpe, false);
}
//佩戴检测
if (customSettingData.getSkin() == EFunctionStatus.SUPPORT_OPEN) {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISWearcheck, true);
} else {
SharedPreferencesUtils.setParam(MyApp.getContext(), Commont.ISWearcheck, false);
}
// if(customSettingData.getFindPhoneUi() == EFunctionStatus.SUPPORT_OPEN){//判断是否开启查找手机UI
// b30SwitchFindPhoneToggleBtn.setChecked(true);
// }else {
// b30SwitchFindPhoneToggleBtn.setChecked(false);
// }
}
});
}
@Override
public void showLoadDialog(int what) {
}
@Override
public void successData(int what, Object object, int daystag) {
if(object == null)
return;
if(what == 11){
showGaideUserInfo(object.toString());
}
}
@Override
public void failedData(int what, Throwable e) {
}
@Override
public void closeLoadDialog(int what) {
}
private void showGaideUserInfo(String userStr){
if(WatchUtils.isNetRequestSuccess(userStr,0)){
try {
JSONObject jsonObject = new JSONObject(userStr);
String dataStr = jsonObject.getString("data");
GuiderUserInfo guiderUserInfo = gson.fromJson(dataStr, GuiderUserInfo.class);
if(guiderUserInfo == null)
return;
//头像
//mineLogoIv
String hearUrl = guiderUserInfo.getHeadUrl();
if(hearUrl != null){
RequestOptions mRequestOptions = RequestOptions.circleCropTransform().diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true);
Glide.with(this).load(hearUrl).apply(mRequestOptions).into(b30UserImageHead);//头像
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
|
3e10f934a5118b6bacd5930d4c6790dc406662de | 1,303 | java | Java | src/test/java/q183272/MonthlyConsumptionReportTest.java | gervaisb/stackexchange-codereview | 5a122435fb2a9a17138e0ebf8f53f22a546c7e2a | [
"MIT"
] | null | null | null | src/test/java/q183272/MonthlyConsumptionReportTest.java | gervaisb/stackexchange-codereview | 5a122435fb2a9a17138e0ebf8f53f22a546c7e2a | [
"MIT"
] | null | null | null | src/test/java/q183272/MonthlyConsumptionReportTest.java | gervaisb/stackexchange-codereview | 5a122435fb2a9a17138e0ebf8f53f22a546c7e2a | [
"MIT"
] | 2 | 2017-09-25T13:56:52.000Z | 2022-03-15T17:23:48.000Z | 27.145833 | 81 | 0.597084 | 7,150 | package q183272;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class MonthlyConsumptionReportTest {
private final ByteArrayOutputStream output = new ByteArrayOutputStream();
private final MonthlyConsumptionReport target = new MonthlyConsumptionReport(
Arrays.asList(
Consumption.of("2017-02-13", 1200.00),
Consumption.of("2017-02-19", 50.00),
Consumption.of("2017-04-10", 100.45)
));
@Test
public void must_group_by_month() {
target.writeTo(output);
assertThat(output.toString())
.containsOnlyOnce("February-2017")
.containsOnlyOnce("April-2017");
}
@Test
public void must_sort_month() {
target.writeTo(output);
assertThat(output.toString()).containsSequence(
"February-2017 | 1250.00",
"April-2017 | 100.45");
}
@Test
public void must_sum_consumption_by_month() {
target.writeTo(output);
assertThat(output.toString())
.contains("February-2017 | 1250.00")
.contains("April-2017 | 100.45");
}
} |
3e10f991f2fd63f5f441c59d584686711fd38491 | 4,244 | java | Java | time/src/main/java/com/dmdirc/addons/time/TimerManager.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | null | null | null | time/src/main/java/com/dmdirc/addons/time/TimerManager.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 61 | 2015-01-04T01:14:08.000Z | 2017-04-14T22:46:37.000Z | time/src/main/java/com/dmdirc/addons/time/TimerManager.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 4 | 2017-03-22T03:11:43.000Z | 2020-01-10T07:08:50.000Z | 32.899225 | 119 | 0.662818 | 7,151 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.addons.time;
import com.dmdirc.interfaces.WindowModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.inject.Inject;
/**
* Class to manage Timers.
*/
public class TimerManager {
/** Map of all the timers that are running. */
private final Map<Integer, TimedCommand> timerList = new HashMap<>();
/** The timer factory to create timers with. */
private final TimerFactory timerFactory;
@Inject
public TimerManager(final TimerFactory timerFactory) {
this.timerFactory = timerFactory;
}
/**
* Adds a timer to the internal list and starts the timer.
*
* @param repetitions Amount of times the timer repeats
* @param interval Interval between repetitions
* @param command Command to be run when the timer fires
* @param origin The frame container to use for the execution
*/
public void addTimer(final int repetitions, final int interval,
final String command, final WindowModel origin) {
synchronized (this) {
final int timerKey = findFreeKey();
final TimedCommand timedCommand = new TimedCommand(this, timerKey,
repetitions, interval, command, origin);
timerList.put(timerKey, timedCommand);
timedCommand.schedule(timerFactory);
}
}
/**
* Removes a timer from our internal list of active timers. This should only be called when a
* timer is cancelled.
*
* @param timerKey Key of the timer to remove
*/
public void removeTimer(final int timerKey) {
timerList.remove(timerKey);
}
/**
* Gets a list of all current active timers.
*
* @return Returns a set of keys for all active timers
*/
public Set<Entry<Integer, TimedCommand>> listTimers() {
return timerList.entrySet();
}
/**
* Returns a list of all known Timer IDs.
*
* @return returns an Integer Set of Timer IDs
*/
public Set<Integer> getTimerIDs() {
return timerList.keySet();
}
/**
* Locates a key in our list that is currently not being used by a timer.
*
* @return Returns a key that can be used for creating a new timer
*/
private int findFreeKey() {
int i = 0;
while (timerList.containsKey(i)) {
i++;
}
return i;
}
/**
* Matches a Timer ID to a Timer. This will return null if there is no Timer with the provided
* ID.
*
* @param id ID that we want the timer for
*
* @return Returns the Timer for the ID provided or null if none exist
*/
public TimedCommand getTimerByID(final int id) {
return timerList.get(id);
}
/**
* Checkes if there is a timer with the provided ID.
*
* @param id ID that we want to check if there is a timer for
*
* @return Returns True iif there is a timer with the ID
*/
public boolean hasTimerWithID(final int id) {
return timerList.containsKey(id);
}
}
|
3e10fa240da9eeff7aa8e662aa7796cea523523f | 422 | java | Java | guns-gateway/src/main/java/com/stylefeng/guns/rest/common/CurrentUser.java | hfzh618/guns-parent | 83e6a982c88ec330d89009f843c9eeb1ee6f05cb | [
"Apache-2.0"
] | null | null | null | guns-gateway/src/main/java/com/stylefeng/guns/rest/common/CurrentUser.java | hfzh618/guns-parent | 83e6a982c88ec330d89009f843c9eeb1ee6f05cb | [
"Apache-2.0"
] | 1 | 2021-04-22T17:01:03.000Z | 2021-04-22T17:01:03.000Z | guns-gateway/src/main/java/com/stylefeng/guns/rest/common/CurrentUser.java | hfzh618/guns-parent | 83e6a982c88ec330d89009f843c9eeb1ee6f05cb | [
"Apache-2.0"
] | null | null | null | 21.1 | 79 | 0.665877 | 7,152 | package com.stylefeng.guns.rest.common;
/**
* Created by hufangzhou on 2019/11/25.
*/
public class CurrentUser {
//线程绑定的存储空间
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
//将用户信息放入存储空间
public static void saveUserId(String userId){
threadLocal.set(userId);
}
//将用户信息取出
public static String getCurrentUser(){
return threadLocal.get();
}
}
|
3e10fa73dc1c349d5d6fb6d347ba69eb17ede6c0 | 636 | java | Java | src/main/character/Enemy.java | rayz2007/RayRPG | 692f5cde4f62a9f91594651af2708f65a29ffa52 | [
"MIT"
] | 1 | 2018-11-29T01:55:10.000Z | 2018-11-29T01:55:10.000Z | src/main/character/Enemy.java | matthiastz/TextRPG | 5bf925836550d4358fbbdb3e2729817c45960aba | [
"MIT"
] | null | null | null | src/main/character/Enemy.java | matthiastz/TextRPG | 5bf925836550d4358fbbdb3e2729817c45960aba | [
"MIT"
] | 1 | 2021-01-24T09:54:04.000Z | 2021-01-24T09:54:04.000Z | 22.714286 | 92 | 0.731132 | 7,153 | package main.character;
import java.util.concurrent.ThreadLocalRandom;
import main.data.Amount;
import main.data.Item;
public abstract class Enemy extends Character {
// random int in range of 1-10
protected final int randomNumItems = ThreadLocalRandom.current().nextInt(1, 10 + 1);
public Enemy(String name, int attack, int defense, int hp, int mana, int xp, float stamina)
throws Exception {
super(name, attack, defense, hp, mana, xp, stamina);
}
public Enemy(String name, int level) throws Exception {
setName(name);
setLevel(level);
}
public int getRandomNumItems() {
return this.randomNumItems;
}
}
|
3e10fb8599d1211affe395c6e34a3ef6971d67c5 | 1,866 | java | Java | software/cab2b/src/java/client/edu/wustl/cab2b/client/ui/pagination/PageElement.java | NCIP/cab2b | f4d8df98d0ccbf59dee026342096698053f25213 | [
"BSD-3-Clause"
] | 1 | 2021-04-28T22:08:40.000Z | 2021-04-28T22:08:40.000Z | software/cab2b/src/java/client/edu/wustl/cab2b/client/ui/pagination/PageElement.java | NCIP/cab2b | f4d8df98d0ccbf59dee026342096698053f25213 | [
"BSD-3-Clause"
] | null | null | null | software/cab2b/src/java/client/edu/wustl/cab2b/client/ui/pagination/PageElement.java | NCIP/cab2b | f4d8df98d0ccbf59dee026342096698053f25213 | [
"BSD-3-Clause"
] | 1 | 2018-03-27T00:53:31.000Z | 2018-03-27T00:53:31.000Z | 17.439252 | 61 | 0.623794 | 7,154 | /*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.wustl.cab2b.client.ui.pagination;
/**
*
* @author chetan_bh
* @author atul_jawale
*/
public interface PageElement {
/**
* Returns description
* @return
*/
public String getDescription();
/**
* Sets description
* @param description
*/
public void setDescription(String description);
/**
* Returns display name
* @return
*/
public String getDisplayName();
/**
* Sets display name
* @param displayName
*/
public void setDisplayName(String displayName);
/**
* Returns image Location.
* @return
*/
public String getImageLocation();
/**
* Sets image location
* @param imageLocation
*/
public void setImageLocation(String imageLocation);
/**
* Returns link URL
* @return
*/
public String getLinkURL();
/**
* Sets link URL.
* @param linkURL
*/
public void setLinkURL(String linkURL);
/**
* Returns User object
* @return
*/
public Object getUserObject();
/**
* Sets user object
* @param userObject
*/
public void setUserObject(Object userObject);
/**
* Returns whether this is selected or not
* @return
*/
public boolean isSelected();
/**
* Sets boolean for selection.
* @param value
*/
public void setSelected(boolean value);
/**
* Sets extra display text.
* @param extraDisplayText
*/
public void setExtraDisplayText(String extraDisplayText);
/**
* Returns extra display text.
* @return
*/
public String getExtraDisplayText();
/**
* Returns action command
* @return
*/
public String getActionCommand();
}
|
3e10fb8955509476892d1370ceb3f928a7844d3a | 9,936 | java | Java | bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/UpdateAttributeDetails.java | lovababug/oci-java-sdk | ffd711257beeb9f883af6cbaf1c619883ad721da | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/UpdateAttributeDetails.java | lovababug/oci-java-sdk | ffd711257beeb9f883af6cbaf1c619883ad721da | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | bmc-datacatalog/src/main/java/com/oracle/bmc/datacatalog/model/UpdateAttributeDetails.java | lovababug/oci-java-sdk | ffd711257beeb9f883af6cbaf1c619883ad721da | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 39.11811 | 246 | 0.6407 | 7,155 | /**
* Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.datacatalog.model;
/**
* Properties used in attribute update operations.
* <br/>
* Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields
* that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in
* the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called
* {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take
* {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__}
* (since the constructor cannot distinguish explicit {@code null} from unset {@code null}).
**/
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20190325")
@lombok.AllArgsConstructor(onConstructor = @__({@Deprecated}))
@lombok.Value
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(
builder = UpdateAttributeDetails.Builder.class
)
@com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME)
public class UpdateAttributeDetails {
@com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "")
@lombok.experimental.Accessors(fluent = true)
public static class Builder {
@com.fasterxml.jackson.annotation.JsonProperty("displayName")
private String displayName;
public Builder displayName(String displayName) {
this.displayName = displayName;
this.__explicitlySet__.add("displayName");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("description")
private String description;
public Builder description(String description) {
this.description = description;
this.__explicitlySet__.add("description");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("externalDataType")
private String externalDataType;
public Builder externalDataType(String externalDataType) {
this.externalDataType = externalDataType;
this.__explicitlySet__.add("externalDataType");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("isIncrementalData")
private Boolean isIncrementalData;
public Builder isIncrementalData(Boolean isIncrementalData) {
this.isIncrementalData = isIncrementalData;
this.__explicitlySet__.add("isIncrementalData");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("isNullable")
private Boolean isNullable;
public Builder isNullable(Boolean isNullable) {
this.isNullable = isNullable;
this.__explicitlySet__.add("isNullable");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("length")
private Long length;
public Builder length(Long length) {
this.length = length;
this.__explicitlySet__.add("length");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("position")
private Integer position;
public Builder position(Integer position) {
this.position = position;
this.__explicitlySet__.add("position");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("precision")
private Integer precision;
public Builder precision(Integer precision) {
this.precision = precision;
this.__explicitlySet__.add("precision");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("scale")
private Integer scale;
public Builder scale(Integer scale) {
this.scale = scale;
this.__explicitlySet__.add("scale");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("timeExternal")
private java.util.Date timeExternal;
public Builder timeExternal(java.util.Date timeExternal) {
this.timeExternal = timeExternal;
this.__explicitlySet__.add("timeExternal");
return this;
}
@com.fasterxml.jackson.annotation.JsonProperty("properties")
private java.util.Map<String, java.util.Map<String, String>> properties;
public Builder properties(java.util.Map<String, java.util.Map<String, String>> properties) {
this.properties = properties;
this.__explicitlySet__.add("properties");
return this;
}
@com.fasterxml.jackson.annotation.JsonIgnore
private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>();
public UpdateAttributeDetails build() {
UpdateAttributeDetails __instance__ =
new UpdateAttributeDetails(
displayName,
description,
externalDataType,
isIncrementalData,
isNullable,
length,
position,
precision,
scale,
timeExternal,
properties);
__instance__.__explicitlySet__.addAll(__explicitlySet__);
return __instance__;
}
@com.fasterxml.jackson.annotation.JsonIgnore
public Builder copy(UpdateAttributeDetails o) {
Builder copiedBuilder =
displayName(o.getDisplayName())
.description(o.getDescription())
.externalDataType(o.getExternalDataType())
.isIncrementalData(o.getIsIncrementalData())
.isNullable(o.getIsNullable())
.length(o.getLength())
.position(o.getPosition())
.precision(o.getPrecision())
.scale(o.getScale())
.timeExternal(o.getTimeExternal())
.properties(o.getProperties());
copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__);
return copiedBuilder;
}
}
/**
* Create a new builder.
*/
public static Builder builder() {
return new Builder();
}
/**
* A user-friendly display name. Does not have to be unique, and it's changeable.
* Avoid entering confidential information.
*
**/
@com.fasterxml.jackson.annotation.JsonProperty("displayName")
String displayName;
/**
* Detailed description of the attribute.
**/
@com.fasterxml.jackson.annotation.JsonProperty("description")
String description;
/**
* Data type of the attribute as defined in the external system.
**/
@com.fasterxml.jackson.annotation.JsonProperty("externalDataType")
String externalDataType;
/**
* Property that identifies if this attribute can be used as a watermark to extract incremental data.
**/
@com.fasterxml.jackson.annotation.JsonProperty("isIncrementalData")
Boolean isIncrementalData;
/**
* Property that identifies if this attribute can be assigned nullable values.
**/
@com.fasterxml.jackson.annotation.JsonProperty("isNullable")
Boolean isNullable;
/**
* Max allowed length of the attribute value.
**/
@com.fasterxml.jackson.annotation.JsonProperty("length")
Long length;
/**
* Position of the attribute in the record definition.
**/
@com.fasterxml.jackson.annotation.JsonProperty("position")
Integer position;
/**
* Precision of the attribute value usually applies to float data type.
**/
@com.fasterxml.jackson.annotation.JsonProperty("precision")
Integer precision;
/**
* Scale of the attribute value usually applies to float data type.
**/
@com.fasterxml.jackson.annotation.JsonProperty("scale")
Integer scale;
/**
* Last modified timestamp of this object in the external system.
**/
@com.fasterxml.jackson.annotation.JsonProperty("timeExternal")
java.util.Date timeExternal;
/**
* A map of maps that contains the properties which are specific to the attribute type. Each attribute type
* definition defines it's set of required and optional properties. The map keys are category names and the
* values are maps of property name to property value. Every property is contained inside of a category. Most
* attributes have required properties within the \"default\" category. To determine the set of required and
* optional properties for an Attribute type, a query can be done on '/types?type=attribute' which returns a
* collection of all attribute types. The appropriate attribute type, which will include definitions of all
* of it's properties, can be identified from this collection.
* Example: `{\"properties\": { \"default\": { \"key1\": \"value1\"}}}`
*
**/
@com.fasterxml.jackson.annotation.JsonProperty("properties")
java.util.Map<String, java.util.Map<String, String>> properties;
@com.fasterxml.jackson.annotation.JsonIgnore
private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>();
}
|
3e10fd06ab17e6caaddeffb1789fcbf8d7ffc219 | 1,538 | java | Java | authenticator-management/src/main/java/com/charlyghislain/authenticator/management/web/provider/AuthenticatorManagementValidationExceptionMapper.java | cghislai/authenticator | 1cd9318e352e1a2228d422bf9ac64c8b225618fe | [
"MIT"
] | 1 | 2018-09-07T14:12:06.000Z | 2018-09-07T14:12:06.000Z | authenticator-management/src/main/java/com/charlyghislain/authenticator/management/web/provider/AuthenticatorManagementValidationExceptionMapper.java | cghislai/authenticator | 1cd9318e352e1a2228d422bf9ac64c8b225618fe | [
"MIT"
] | null | null | null | authenticator-management/src/main/java/com/charlyghislain/authenticator/management/web/provider/AuthenticatorManagementValidationExceptionMapper.java | cghislai/authenticator | 1cd9318e352e1a2228d422bf9ac64c8b225618fe | [
"MIT"
] | null | null | null | 38.45 | 134 | 0.789987 | 7,156 | package com.charlyghislain.authenticator.management.web.provider;
import com.charlyghislain.authenticator.management.api.domain.WsError;
import com.charlyghislain.authenticator.management.api.domain.WsValidationError;
import com.charlyghislain.authenticator.management.api.error.AuthenticatorManagementValidationException;
import com.charlyghislain.authenticator.management.api.domain.WsViolationError;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.ArrayList;
@Provider
public class AuthenticatorManagementValidationExceptionMapper implements ExceptionMapper<AuthenticatorManagementValidationException> {
private static final Logger LOG = LoggerFactory.getLogger(AuthenticatorManagementValidationExceptionMapper.class);
@Override
public Response toResponse(@NonNull AuthenticatorManagementValidationException exception) {
ArrayList<WsViolationError> violations = new ArrayList<>(exception.getWsViolationErrors());
WsValidationError wsValidationError = new WsValidationError();
wsValidationError.setCode(exception.getCode());
wsValidationError.setViolations(violations);
return Response
.status(406)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(wsValidationError)
.build();
}
}
|
3e10fd1c1d22de122c78c48c7e96ab71216f466c | 95 | java | Java | src/main/java/com/cea/digitalworld/dwmicroservice2/web/rest/package-info.java | flefevre/jhipsterangularjsmd5 | 7920d786874047a3c93d828e53644845968f97e2 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cea/digitalworld/dwmicroservice2/web/rest/package-info.java | flefevre/jhipsterangularjsmd5 | 7920d786874047a3c93d828e53644845968f97e2 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cea/digitalworld/dwmicroservice2/web/rest/package-info.java | flefevre/jhipsterangularjsmd5 | 7920d786874047a3c93d828e53644845968f97e2 | [
"Apache-2.0"
] | null | null | null | 19 | 54 | 0.747368 | 7,157 | /**
* Spring MVC REST controllers.
*/
package com.cea.digitalworld.dwmicroservice2.web.rest;
|
3e10fd8b2d53894023d1d34b22fa8abafad02f4d | 7,448 | java | Java | app/src/main/java/com/mrserviceman/messenger/Fragments/AccountFragMent.java | Creative-Enterprises/Messenger | 887ab82eac025959b624464dc0eabdc6aa482e15 | [
"Unlicense"
] | null | null | null | app/src/main/java/com/mrserviceman/messenger/Fragments/AccountFragMent.java | Creative-Enterprises/Messenger | 887ab82eac025959b624464dc0eabdc6aa482e15 | [
"Unlicense"
] | null | null | null | app/src/main/java/com/mrserviceman/messenger/Fragments/AccountFragMent.java | Creative-Enterprises/Messenger | 887ab82eac025959b624464dc0eabdc6aa482e15 | [
"Unlicense"
] | null | null | null | 37.24 | 165 | 0.618555 | 7,158 | package com.mrserviceman.messenger.Fragments;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.mrserviceman.messenger.Activity.SettingsActivity;
import com.google.firebase.auth.FirebaseAuth;
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.ValueEventListener;
import com.mrserviceman.messenger.Activity.ProfieEditActivity;
import com.mrserviceman.messenger.Activity.SignUpActivity;
import com.mrserviceman.messenger.Activity.WebActivity;
import com.mrserviceman.messenger.Model.ChatFragmentsModels.User;
import com.mrserviceman.messenger.R;
public class AccountFragMent extends Fragment {
private Button sign_in,invite_friend;
private TextView user_name;
private ImageView edit,profile_pic;
private User user;
public AccountFragMent(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_account,container,false);
Toolbar myToolbar = view.findViewById(R.id.my_toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
myToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(new Intent(getContext(), SettingsActivity.class));
return true;
}
});
sign_in=view.findViewById(R.id.sign_in_button);
user_name=view.findViewById(R.id.user_name);
edit=view.findViewById(R.id.edit_info);
profile_pic=view.findViewById(R.id.profile_pic);
SharedPreferences sharedPref = getContext().getSharedPreferences(
"com.messenger.profile_name", Context.MODE_PRIVATE);
String username = sharedPref.getString("com.messenger.profile_name", "");
user_name.setText(username);
invite_friend=view.findViewById(R.id.invite_friends);
invite_friend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Heyy Try This All in One Messaging App I have Downloaded from uptodown Store");
startActivity(Intent.createChooser(sendIntent, "Share With"));
}
});
ImageView facebook=view.findViewById(R.id.facebook);
facebook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getContext(), WebActivity.class);
intent.putExtra("URL","https://www.facebook.com/");
startActivity(intent);
}
});
SearchView googleSearch=view.findViewById(R.id.google_search);
googleSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Intent intent=new Intent(getContext(), WebActivity.class);
intent.putExtra("URL", "https://www.google.com/search?q="+s.replace(" ","+"));
startActivity(intent);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
sharedPref = getContext().getSharedPreferences(
"com.messenger.profile_pic_uri", Context.MODE_PRIVATE);
final String profile_uri = sharedPref.getString("com.messenger.profile_pic_uri", "");
try {
if (!profile_uri.equals("")){
profile_pic.setImageURI(Uri.parse(profile_uri));
}
}
catch (Exception ex){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
user=dataSnapshot.getValue(User.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
profile_pic.setImageURI(Uri.parse(user.getImageUrl()));
}
if(!profile_uri.equals("")){
sign_in.setVisibility(View.GONE);
}
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!profile_uri.equals("")){
startActivity(new Intent(getContext(), ProfieEditActivity.class));
}
else{
if(isInternetOn()){
Intent intent=new Intent(getActivity(), SignUpActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else{
Toast.makeText(getContext(),"No Internet",Toast.LENGTH_SHORT).show();
}
}
}
});
sign_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getActivity(), SignUpActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chat, menu);
}
public final boolean isInternetOn() {
ConnectivityManager cm = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}
|
3e10fdc43552dc4acc480780d804dc52af2031c9 | 5,346 | java | Java | EventHandle.java | rosik22/Java-Library-Management-CLI | 852c6d7acab8e1244be42eb5aba8a41a8d51476b | [
"Apache-2.0"
] | null | null | null | EventHandle.java | rosik22/Java-Library-Management-CLI | 852c6d7acab8e1244be42eb5aba8a41a8d51476b | [
"Apache-2.0"
] | null | null | null | EventHandle.java | rosik22/Java-Library-Management-CLI | 852c6d7acab8e1244be42eb5aba8a41a8d51476b | [
"Apache-2.0"
] | null | null | null | 33.622642 | 118 | 0.533857 | 7,159 | import java.util.Scanner;
public class EventHandle {
private Scanner scan = new Scanner(System.in);
private DatabaseManager dbman = new DatabaseManager();
private boolean running = true;
public boolean Running() {
return running;
}
// Initializing tables
public void StartUp() {
dbman.createNewTable();
}
// prompt user to sign-un
public void promptSignUp() {
System.out.println("Sign-up");
System.out.print("Username(at least one character): ");
String username = scan.nextLine();
System.out.print("Password(at least five characters): ");
String password = scan.nextLine();
// check if the credentials are compatible
// and insert them in the User table
if (checkCredentials(username, password)) {
dbman.insertUser(username, password);
}
}
// prompt user to sign-in
public boolean promptSignIn() {
System.out.println("Sign-in");
System.out.print("Username: ");
String username = scan.nextLine();
System.out.print("Password: ");
String password = scan.nextLine();
// if the username and password are correct
// the user is signed in
if (dbman.login(username, password)) {
return true;
}
return false;
}
// checks whether the credentials are correct
public boolean checkCredentials(String username, String password) {
if (username.length() < 1 || password.length() < 5) {
System.out.println("Wrong length of username or password");
return false;
}
return true;
}
// prompts the user to either log-in or register
public String login_register() {
System.out.println("Choose (s) for sign-in | Choose (r) for registration");
String choice = scan.nextLine();
return choice;
}
// prompts the user to choose a command
public boolean menu_prompt() {
System.out.println("Choose a command:");
System.out.println(" a(add) - add a book in the library" + "\n l(loan) - loan a book to a person"
+ "\n t(take) - take back a book from a person" + "\n r(remove) - discard a book from the library"
+ "\n av(availability) - check if a book is available"
+ "\n w(who is loaning) - check who is loaning the book"
+ "\n s(search) - search for a book(s) by its name" + "\n u(unavailable) - show all unavailable books"
+ "\n c(catalogue) - show all the books in the library" + "\n e(exit) - log out");
String choice = scan.nextLine();
// log out if the exit command is chosen
if (choice.equals("e")) {
return false;
} else {
// handle every other choice
handleMenuChoice(choice);
}
return true;
}
// handles the command which the user
// chose to execute
public void handleMenuChoice(String choice) {
String input;
String strings[];
switch (choice) {
case "a":
System.out.println("Enter data in the order: title,author,date of issue(YYYY-MM-DD)");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.insertBook(strings[0], strings[1], strings[2]);
}
break;
case "l":
System.out.println("Enter data in the order: person,return date(optional),author,title");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.loanBook(strings);
}
break;
case "t":
System.out.println("Enter data in the order: author,title");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.receiveBook(strings[0], strings[1]);
}
break;
case "r":
System.out.println("Enter data in the order: author,title");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.removeBook(strings[0], strings[1]);
}
break;
case "av":
System.out.println("Enter data in the order: author,title");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.isBookAvailable(strings[0], strings[1]);
}
break;
case "w":
System.out.println("Enter data in the order: author,title");
input = scan.nextLine();
strings = input.split(",");
if (strings.length > 1) {
dbman.whoIsLoaning(strings[0], strings[1]);
}
break;
case "s":
System.out.println("Enter data as follows: title");
input = scan.nextLine();
if (input.length() > 0) {
dbman.findBook(input);
}
break;
case "u":
dbman.printLoanedBooks();
break;
case "c":
dbman.printBooks();
break;
}
}
}
|
3e10fdc48ae7d1d87677159dea70437b40ff877e | 882 | java | Java | src/main/java/jp/co/tis/s2n/jspConverter/convert/tag/html/TagHtmlImgConvert.java | oscana/oscana-s2n-jspconverter | df10be3a651eb5da1509f8d53e2f7583ac34b776 | [
"Apache-2.0"
] | null | null | null | src/main/java/jp/co/tis/s2n/jspConverter/convert/tag/html/TagHtmlImgConvert.java | oscana/oscana-s2n-jspconverter | df10be3a651eb5da1509f8d53e2f7583ac34b776 | [
"Apache-2.0"
] | null | null | null | src/main/java/jp/co/tis/s2n/jspConverter/convert/tag/html/TagHtmlImgConvert.java | oscana/oscana-s2n-jspconverter | df10be3a651eb5da1509f8d53e2f7583ac34b776 | [
"Apache-2.0"
] | null | null | null | 25.941176 | 87 | 0.656463 | 7,160 | package jp.co.tis.s2n.jspConverter.convert.tag.html;
import jp.co.tis.s2n.converterCommon.util.StringUtils;
import jp.co.tis.s2n.jspConverter.node.NodeWrapper;
/**
* HtmlImgタグ変換用クラス。
*
* @author Fumihiko Yamamoto
*
*/
public class TagHtmlImgConvert extends TagHtmlConvertBase {
@Override
protected void convertStartProc(NodeWrapper nw) {
String sAction = getAndDelParam(nw, "action");
String sPage = getAndDelParam(nw, "page");
String sSrc = getAndDelParam(nw, "src ");
nw.renameKeyString("styleId", "id");
nw.renameKeyString("altKey", "alt");
//パス書き換え
nw.addKeyValue("src", convertPath(sAction, sPage, null, sSrc, getCurModule()));
//必須属性のaltがなければ自動追加
if (StringUtils.isEmpty(nw.getValueAsString("alt"))) {
nw.addKeyValue("alt", nw.getValueAsString("src"));
}
}
}
|
3e10ff897113a6fb86b26b615f7bf1715b812ae2 | 2,829 | java | Java | spring-cloud-aws-context/src/test/java/org/springframework/cloud/aws/context/support/io/SimpleStorageProtocolResolverConfigurerIntegrationTest.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 613 | 2015-02-04T01:14:22.000Z | 2022-01-06T13:07:17.000Z | spring-cloud-aws-context/src/test/java/org/springframework/cloud/aws/context/support/io/SimpleStorageProtocolResolverConfigurerIntegrationTest.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 664 | 2015-01-02T03:56:29.000Z | 2022-01-16T08:47:41.000Z | spring-cloud-aws-context/src/test/java/org/springframework/cloud/aws/context/support/io/SimpleStorageProtocolResolverConfigurerIntegrationTest.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 461 | 2015-01-12T08:20:08.000Z | 2022-01-17T06:06:02.000Z | 33.282353 | 107 | 0.809473 | 7,161 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.cloud.aws.context.support.io;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.aws.context.config.annotation.EnableContextResourceLoader;
import org.springframework.cloud.aws.core.io.s3.SimpleStorageResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class SimpleStorageProtocolResolverConfigurerIntegrationTest {
@Autowired
@Qualifier("configurationLoadedResource")
private Resource resource;
@Value("s3://foo/bar.txt")
private Resource fieldResource;
@Autowired
private ResourceLoader resourceLoader;
@Test
public void configurationClassAnnotatedResourceResolvesToS3Resource() throws Exception {
assertThat(((Advised) resource).getTargetSource().getTarget()).isInstanceOf(SimpleStorageResource.class);
}
@Test
public void valueAnnotatedResourceResolvesToS3Resource() {
assertThat(fieldResource).isInstanceOf(SimpleStorageResource.class);
}
@Test
public void resourceLoadedResourceIsS3Resource() {
assertThat(resourceLoader.getResource("s3://foo/bar.txt")).isInstanceOf(SimpleStorageResource.class);
}
@Configuration
@EnableContextResourceLoader
static class Config {
@Value("s3://foo/bar.txt")
@Lazy
private Resource resource;
@Bean
public Resource configurationLoadedResource() {
return resource;
}
}
}
|
3e1100f82ee5eb0a54117d984278a4bf2e450dcc | 1,519 | java | Java | src/main/java/net/darktree/virus/codon/arg/CodonValueArg.java | magistermaks/virus-game | dc1b272b5c899614d27c6f8d54caeb2a2233ddb2 | [
"MIT"
] | 1 | 2021-02-22T10:40:31.000Z | 2021-02-22T10:40:31.000Z | src/main/java/net/darktree/virus/codon/arg/CodonValueArg.java | magistermaks/virus-game | dc1b272b5c899614d27c6f8d54caeb2a2233ddb2 | [
"MIT"
] | 1 | 2021-07-08T13:07:57.000Z | 2021-09-13T14:38:01.000Z | src/main/java/net/darktree/virus/codon/arg/CodonValueArg.java | magistermaks/virus-game | dc1b272b5c899614d27c6f8d54caeb2a2233ddb2 | [
"MIT"
] | null | null | null | 21.394366 | 87 | 0.57472 | 7,162 | package net.darktree.virus.codon.arg;
import net.darktree.virus.codon.CodonMetaInfo;
import net.darktree.virus.util.Helpers;
import net.darktree.virus.util.Utils;
public class CodonValueArg extends ComplexCodonArg {
public int value = 0;
public CodonValueArg(int id, CodonMetaInfo info) {
super(id, info);
}
@Override
public void setParam( String param ) {
value = Helpers.clamp( Integer.parseInt( param.substring(0, 2) ), 0, 40 ) - 20;
}
@Override
public String getParam() {
return serialize( value + 20, 2 );
}
@Override
public String getText() {
return super.getText() + " (" + value + ")";
}
@Override
public CodonArg clone() {
CodonValueArg arg = new CodonValueArg( code, info );
arg.value = value;
return arg;
}
@Override
public boolean is( CodonArg arg ) {
return arg instanceof CodonValueArg;
}
@Override
public String[] getOptions() {
return new String[] { "value" };
}
@Override
public void increment( int option ) {
value = Helpers.clamp( value + 1, -20, 20 );
}
@Override
public void decrement( int option ) {
value = Helpers.clamp( value - 1, -20, 20 );
}
@Override
public int get( int option ) {
return value;
}
@Override
public void mutate() {
if( Utils.random(1) == 0 ) {
decrement(0);
}else{
increment(0);
}
}
}
|
3e1100fb9fb8fb3ed27632b752e0dec1b562d317 | 429 | java | Java | octopus-server/src/main/java/org/metahut/octopus/server/converter/SampleInstanceFromDTOConverter.java | Moouna/octopus | 2fca86b14996840bb34717fea132cb3d98a324af | [
"Apache-2.0"
] | null | null | null | octopus-server/src/main/java/org/metahut/octopus/server/converter/SampleInstanceFromDTOConverter.java | Moouna/octopus | 2fca86b14996840bb34717fea132cb3d98a324af | [
"Apache-2.0"
] | null | null | null | octopus-server/src/main/java/org/metahut/octopus/server/converter/SampleInstanceFromDTOConverter.java | Moouna/octopus | 2fca86b14996840bb34717fea132cb3d98a324af | [
"Apache-2.0"
] | null | null | null | 35.75 | 123 | 0.857809 | 7,163 | package org.metahut.octopus.server.converter;
import org.metahut.octopus.api.dto.SampleInstanceCreateOrUpdateRequestDTO;
import org.metahut.octopus.dao.entity.SampleInstance;
import org.mapstruct.Mapper;
import org.springframework.core.convert.converter.Converter;
@Mapper(componentModel = "spring")
public interface SampleInstanceFromDTOConverter extends Converter<SampleInstanceCreateOrUpdateRequestDTO, SampleInstance> {
}
|
3e1100fe1a38f7ae51ac8e144c6aaf30ca48b6f5 | 931 | java | Java | spinaltap-common/src/test/java/com/airbnb/spinaltap/common/util/ChainedFilterTest.java | zuofei/SpinalTap | 9a80734b712ac5922f4a25fb2c9f02daa84f9716 | [
"Apache-2.0"
] | 366 | 2018-03-12T21:10:06.000Z | 2022-03-14T23:26:39.000Z | spinaltap-common/src/test/java/com/airbnb/spinaltap/common/util/ChainedFilterTest.java | ramch22/SpinalTap | e8def919c16a230d5138a24fdac24fe22a9bf437 | [
"Apache-2.0"
] | 7 | 2018-03-14T00:01:49.000Z | 2019-06-10T22:35:57.000Z | spinaltap-common/src/test/java/com/airbnb/spinaltap/common/util/ChainedFilterTest.java | ramch22/SpinalTap | e8def919c16a230d5138a24fdac24fe22a9bf437 | [
"Apache-2.0"
] | 60 | 2018-03-12T22:41:21.000Z | 2022-01-24T23:45:21.000Z | 25.861111 | 96 | 0.711063 | 7,164 | /**
* Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license
* information.
*/
package com.airbnb.spinaltap.common.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ChainedFilterTest {
@Test
public void testFailingFilter() throws Exception {
Filter<Integer> filter =
ChainedFilter.<Integer>builder().addFilter(num -> true).addFilter(num -> false).build();
assertFalse(filter.apply(1));
}
@Test
public void testPassingFilter() throws Exception {
Filter<Integer> filter =
ChainedFilter.<Integer>builder().addFilter(num -> true).addFilter(num -> true).build();
assertTrue(filter.apply(1));
}
@Test
public void testEmptyFilter() throws Exception {
Filter<Integer> filter = ChainedFilter.<Integer>builder().build();
assertTrue(filter.apply(1));
}
}
|
3e11014b14c6ef98efe7cbd571bc6a447e475b23 | 1,074 | java | Java | src/Polygons.java | simahero/Polygons | 61c596f31511e70deeca2a0801906e473849bac9 | [
"MIT"
] | null | null | null | src/Polygons.java | simahero/Polygons | 61c596f31511e70deeca2a0801906e473849bac9 | [
"MIT"
] | null | null | null | src/Polygons.java | simahero/Polygons | 61c596f31511e70deeca2a0801906e473849bac9 | [
"MIT"
] | null | null | null | 25.571429 | 91 | 0.527933 | 7,165 | import java.util.ArrayList;
public class Polygons {
static int radius = 300;
int sides;
double angle;
int [] x;
int [] y;
static ArrayList<Polygons> poligons = new ArrayList<>();
public Polygons(){}
public Polygons(int sides, double angle, int [] x, int [] y) {
this.sides = sides;
this.angle = angle;
this.x = x;
this.y = y;
}
public static void init(){
for (int i = 3; i < 360; i++){
poligons.add(new Polygons(i, (360f/i), new int[i], new int[i]));
}
}
public void countCoordinates(Polygons p, int rotate){
double anglecounter = 90 + rotate;
for (int i = 0; i < p.sides; i++){
//p.x[0] = 0;
//p.y[0] = radius;
p.x[i] = -1 * (int) Math.floor( Math.cos(Math.toRadians(anglecounter))*radius);
p.y[i] = -1 * (int) Math.floor( Math.sin(Math.toRadians(anglecounter))*radius);
anglecounter = anglecounter + p.angle;
//anglecounter = anglecounter + rotate;
}
}
}
|
3e1102566dbd9e1893cae8592ec8dd08947968e4 | 2,767 | java | Java | bundles/ru.capralow.dt.coverage.ui/src/ru/capralow/dt/coverage/internal/ui/handlers/MergeSessionsHandler.java | bia-technologies/ru.capralow.dt.unit.launcher | 6bc0abce169f5b59180dc4e2adf201ecc7a31db1 | [
"BSD-3-Clause"
] | 60 | 2019-04-24T14:10:03.000Z | 2021-03-16T19:46:32.000Z | bundles/ru.capralow.dt.coverage.ui/src/ru/capralow/dt/coverage/internal/ui/handlers/MergeSessionsHandler.java | bia-technologies/ru.capralow.dt.unit.launcher | 6bc0abce169f5b59180dc4e2adf201ecc7a31db1 | [
"BSD-3-Clause"
] | 22 | 2019-04-26T10:14:01.000Z | 2021-03-02T09:43:47.000Z | bundles/ru.capralow.dt.coverage.ui/src/ru/capralow/dt/coverage/internal/ui/handlers/MergeSessionsHandler.java | bia-technologies/ru.capralow.dt.unit.launcher | 6bc0abce169f5b59180dc4e2adf201ecc7a31db1 | [
"BSD-3-Clause"
] | 10 | 2019-05-16T09:02:57.000Z | 2021-03-02T06:02:16.000Z | 31.443182 | 103 | 0.684857 | 7,166 | /**
* Copyright (c) 2020, Alexander Kapralov
*/
package ru.capralow.dt.coverage.internal.ui.handlers;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import ru.capralow.dt.coverage.CoverageStatus;
import ru.capralow.dt.coverage.CoverageTools;
import ru.capralow.dt.coverage.ICoverageSession;
import ru.capralow.dt.coverage.ISessionManager;
import ru.capralow.dt.coverage.internal.ui.UiMessages;
import ru.capralow.dt.coverage.internal.ui.dialogs.MergeSessionsDialog;
/**
* Handler to merge session coverage session.
*/
public class MergeSessionsHandler
extends AbstractSessionManagerHandler
{
private static Job createJob(final ISessionManager sm, final Collection<ICoverageSession> sessions,
final String description)
{
final Job job = new Job(UiMessages.MergingSessions_task)
{
@Override
protected IStatus run(IProgressMonitor monitor)
{
try
{
sm.mergeSessions(sessions, description, monitor);
}
catch (CoreException e)
{
return CoverageStatus.MERGE_SESSIONS_ERROR.getStatus(e);
}
return Status.OK_STATUS;
}
};
job.setPriority(Job.SHORT);
return job;
}
public MergeSessionsHandler()
{
super(CoverageTools.getSessionManager());
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
final Shell parentShell = HandlerUtil.getActiveShell(event);
final ISessionManager sm = CoverageTools.getSessionManager();
List<ICoverageSession> sessions = sm.getSessions();
String descr = UiMessages.MergeSessionsDialogDescriptionDefault_value;
descr = MessageFormat.format(descr, new Object[] { new Date() });
final MergeSessionsDialog d = new MergeSessionsDialog(parentShell, sessions, descr);
if (d.open() == IDialogConstants.OK_ID)
{
createJob(sm, d.getSessions(), d.getDescription()).schedule();
}
return null;
}
@Override
public boolean isEnabled()
{
return sessionManager.getSessions().size() > 1;
}
}
|
3e11034e571d453a620a5f20b33380840179b585 | 6,389 | java | Java | lyj-core/src/org/lyj/commons/io/chunks/FileChunksController.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | 2 | 2018-12-12T21:13:33.000Z | 2019-03-18T14:20:14.000Z | lyj-core/src/org/lyj/commons/io/chunks/FileChunksController.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | null | null | null | lyj-core/src/org/lyj/commons/io/chunks/FileChunksController.java | botikasm/lyj-framework | a806711a5dbe73643f1659774d353def3ecaef24 | [
"MIT"
] | 1 | 2018-12-12T21:13:36.000Z | 2018-12-12T21:13:36.000Z | 32.267677 | 91 | 0.452496 | 7,167 | package org.lyj.commons.io.chunks;
import org.lyj.commons.cryptograph.MD5;
import org.lyj.commons.io.cache.filecache.CacheFiles;
import org.lyj.commons.tokenizers.files.FileTokenizer;
import org.lyj.commons.util.DateUtils;
import org.lyj.commons.util.FileUtils;
import org.lyj.commons.util.PathUtils;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class FileChunksController {
// ------------------------------------------------------------------------
// c o n s t
// ------------------------------------------------------------------------
private static final String DEF_ROOT = PathUtils.getTemporaryDirectory("tmp_chunks");
private static final long CACHE_DURATION_MS = DateUtils.ONE_HOUR_MS;
// ------------------------------------------------------------------------
// f i e l d s
// ------------------------------------------------------------------------
private final CacheFiles _cache;
private final Map<String, FileChunks> _chunks_map;
private final String _root;
// ------------------------------------------------------------------------
// c o n s t r u c t o r
// ------------------------------------------------------------------------
public FileChunksController() {
this(DEF_ROOT, CACHE_DURATION_MS);
}
public FileChunksController(final String root,
final long cache_timeout_ms) {
_root = PathUtils.getAbsolutePath(root);
FileUtils.tryMkdirs(_root);
_chunks_map = Collections.synchronizedMap(new HashMap<>());
_cache = new CacheFiles(_root, cache_timeout_ms);
}
// ------------------------------------------------------------------------
// p u b l i c
// ------------------------------------------------------------------------
public String root() {
return _root;
}
public FileChunksController open() {
if (!_cache.isRunning()) {
_cache.clear();
_cache.open();
this.init();
}
return this;
}
public void close() {
if (_cache.isRunning()) {
_cache.close();
}
}
public void add(final String uid,
final int index,
final int total,
final byte[] data) {
synchronized (_chunks_map) {
if (!_chunks_map.containsKey(uid)) {
_chunks_map.put(uid, new FileChunks(uid));
}
// add to cache
final String cache_key = cacheKey(uid, index);
_cache.put(cache_key, data);
// add to chunks
final FileChunks chunks = _chunks_map.get(uid);
chunks.add(cache_key, index, total);
}
}
public boolean has(final String uid,
final int index) {
synchronized (_chunks_map) {
if (!_chunks_map.containsKey(uid)) {
return false;
}
final FileChunks chunks = _chunks_map.get(uid);
final String cache_key = cacheKey(uid, index);
return chunks.contains(cache_key);
}
}
public void remove(final String uid) {
synchronized (_chunks_map) {
this.remove(_chunks_map.remove(uid));
}
}
public int count(final String uid) {
synchronized (_chunks_map) {
if (_chunks_map.containsKey(uid)) {
return _chunks_map.get(uid).count();
}
return 0;
}
}
public void compose(final String uid,
final String out_file_name) throws Exception {
this.compose(uid, new File(out_file_name));
}
public void compose(final String uid,
final File out) throws Exception {
synchronized (_chunks_map) {
if (_chunks_map.containsKey(uid)) {
this.compose(_chunks_map.get(uid), out);
}
}
}
// ------------------------------------------------------------------------
// p r i v a t e
// ------------------------------------------------------------------------
private void init() {
}
private void remove(final FileChunks chunks) {
if (null != chunks) {
// clear cache
final FileChunks.ChunkInfo[] data = chunks.data();
for (final FileChunks.ChunkInfo info : data) {
final String cache_key = info.cacheKey();
_cache.remove(cache_key);
}
// clear info
chunks.clear();
}
}
private void compose(final FileChunks chunks,
final File out) throws Exception {
if (null != chunks) {
final FileChunks.ChunkInfo[] data = chunks.sort();
for (final FileChunks.ChunkInfo info : data) {
final String cache_key = info.cacheKey();
final byte[] bytes = _cache.getBytes(cache_key);
FileTokenizer.append(bytes, out);
}
this.remove(chunks);
}
}
// ------------------------------------------------------------------------
// S T A T I C
// ------------------------------------------------------------------------
private static String cacheKey(final String uid, final int index) {
return MD5.encode(uid + index);
}
// ------------------------------------------------------------------------
// S I N G L E T O N
// ------------------------------------------------------------------------
private static FileChunksController __instance;
public static synchronized FileChunksController instance(final String root,
final long cache_timeout_ms) {
if (null == __instance) {
__instance = new FileChunksController(root, cache_timeout_ms);
}
return __instance;
}
public static synchronized FileChunksController instance() {
if (null == __instance) {
__instance = new FileChunksController();
}
return __instance;
}
}
|
3e11036998fd42471f149bb74e0fc99b14f31b70 | 7,820 | java | Java | src/test/java/com/zup/academy/eduardoribeiro/Proposta/carteira/AssociaCarteiraControllerTest.java | eduardorcury/orange-talents-03-template-proposta | 864b6416b0e8956a335499eca4b41d557b95757e | [
"Apache-2.0"
] | null | null | null | src/test/java/com/zup/academy/eduardoribeiro/Proposta/carteira/AssociaCarteiraControllerTest.java | eduardorcury/orange-talents-03-template-proposta | 864b6416b0e8956a335499eca4b41d557b95757e | [
"Apache-2.0"
] | null | null | null | src/test/java/com/zup/academy/eduardoribeiro/Proposta/carteira/AssociaCarteiraControllerTest.java | eduardorcury/orange-talents-03-template-proposta | 864b6416b0e8956a335499eca4b41d557b95757e | [
"Apache-2.0"
] | null | null | null | 39.40404 | 116 | 0.697129 | 7,168 | package com.zup.academy.eduardoribeiro.Proposta.carteira;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zup.academy.eduardoribeiro.Proposta.cartao.Cartao;
import com.zup.academy.eduardoribeiro.Proposta.cartao.CartaoClient;
import com.zup.academy.eduardoribeiro.Proposta.utils.TestUtils;
import feign.FeignException;
import feign.Request;
import feign.RequestTemplate;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
class AssociaCarteiraControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper mapper;
@Autowired
CarteiraRepository carteiraRepository;
@Autowired
TestUtils utils;
@MockBean
CartaoClient cartaoClient;
@ParameterizedTest
@ValueSource(strings = {"PAYPAL", "SAMSUNG_PAY"})
@DisplayName("Deve associar uma nova carteira a um cartão existente")
void deveAssociarCarteiraACartao(String tipo) throws Exception {
Cartao cartao = utils.salvaCartao();
AssociacaoCarteiraRequest request = new AssociacaoCarteiraRequest("envkt@example.com", tipo);
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"));
List<Carteira> list = carteiraRepository.findAll();
assertEquals(1, list.size());
assertEquals(cartao, list.get(0).getCartao());
}
@Test
@DisplayName("Deve associar duas carteiras diferentes a um cartão")
void deveAssociarDuasCarteirasDiferentesACartao() throws Exception {
Cartao cartao = utils.salvaCartao();
AssociacaoCarteiraRequest request1 =
new AssociacaoCarteiraRequest("envkt@example.com", "PAYPAL");
AssociacaoCarteiraRequest request2 =
new AssociacaoCarteiraRequest("envkt@example.com", "SAMSUNG_PAY");
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request1)))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"));
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request2)))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"));
List<Carteira> list = carteiraRepository.findAll();
assertEquals(2, list.size());
assertEquals(cartao, list.get(0).getCartao());
assertEquals(cartao, list.get(1).getCartao());
}
@ParameterizedTest
@MethodSource("criaRequestInvalidos")
@DisplayName("Deve retornar BAD_REQUEST para request inválido")
void naoDeveAssociarCarteiraParaRequestInvalido(String email, String tipo) throws Exception {
Cartao cartao = utils.salvaCartao();
AssociacaoCarteiraRequest request = new AssociacaoCarteiraRequest(email, tipo);
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isBadRequest());
assertTrue(carteiraRepository.findAll().isEmpty());
}
@Test
@DisplayName("Deve retornar NOT_FOUND para cartão não encontrado")
void deveRetornarNotFoundParaCartaoNaoEncontrado() throws Exception {
AssociacaoCarteiraRequest request = new AssociacaoCarteiraRequest("envkt@example.com", "PAYPAL");
mockMvc.perform(post("/cartoes/1/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isNotFound());
assertTrue(carteiraRepository.findAll().isEmpty());
}
@Test
@DisplayName("Deve retornar UNPROCESSABLE_ENTITY para carteira já associada")
void deveRetornarUnprocessableEntityParaCarteiraJaAssociada() throws Exception {
Cartao cartao = utils.salvaCartao();
carteiraRepository.save(new Carteira(cartao, "envkt@example.com", TipoDeCarteira.PAYPAL));
assertEquals(1, carteiraRepository.findAll().size());
AssociacaoCarteiraRequest request = new AssociacaoCarteiraRequest("envkt@example.com", "PAYPAL");
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isUnprocessableEntity());
assertEquals(1, carteiraRepository.findAll().size());
}
@Test
@DisplayName("Deve retornar INTERNAL_SERVER_ERROR se sistema retornar erro")
void deveRetornarInternalServerErrorSeSistemaRetornarErro() throws Exception {
Cartao cartao = utils.salvaCartao();
AssociacaoCarteiraRequest request = new AssociacaoCarteiraRequest("envkt@example.com", "PAYPAL");
FeignException.BadRequest exception =
new FeignException.BadRequest(
"Erro do sistema",
Request.create(Request.HttpMethod.POST, "url", Collections.emptyMap(),
mapper.writeValueAsBytes(request), Charset.defaultCharset(), new RequestTemplate()),
mapper.writeValueAsBytes("resposta"));
Mockito.when(cartaoClient.associaCarteira(cartao.getIdExterno(),
new NotificacaoCarteira(request))).thenThrow(exception);
mockMvc.perform(post("/cartoes/" + cartao.getId() + "/carteiras")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(request)))
.andExpect(status().isInternalServerError());
assertTrue(carteiraRepository.findAll().isEmpty());
}
private static Stream<Arguments> criaRequestInvalidos() {
return Stream.of(
Arguments.of(null, "PAYPAL"),
Arguments.of("envkt@example.com", null),
Arguments.of(" ", " "),
Arguments.of("email", "PAYPAL"),
Arguments.of("envkt@example.com", "qualquer")
);
}
} |
3e1103c48bf66f9cf25c555ad04e6674142c6e5b | 3,448 | java | Java | cdap-master/src/test/java/co/cask/cdap/data/runtime/main/ResourcesClassLoaderTest.java | Werselba/pipeline | 2821b1e4ecd640f614cc553bed963b854bb6a28e | [
"Apache-2.0"
] | 3 | 2018-03-22T23:25:54.000Z | 2018-03-22T23:36:44.000Z | cdap-master/src/test/java/co/cask/cdap/data/runtime/main/ResourcesClassLoaderTest.java | Werselba/pipeline | 2821b1e4ecd640f614cc553bed963b854bb6a28e | [
"Apache-2.0"
] | null | null | null | cdap-master/src/test/java/co/cask/cdap/data/runtime/main/ResourcesClassLoaderTest.java | Werselba/pipeline | 2821b1e4ecd640f614cc553bed963b854bb6a28e | [
"Apache-2.0"
] | null | null | null | 38.741573 | 116 | 0.734919 | 7,169 | /*
* Copyright © 2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.data.runtime.main;
import co.cask.cdap.common.lang.ClassLoaders;
import org.apache.hadoop.mapred.JobConf;
import org.junit.Assert;
import org.junit.Test;
import java.net.URI;
import java.net.URL;
/**
*
*/
public class ResourcesClassLoaderTest {
@SuppressWarnings("AccessStaticViaInstance")
@Test
public void testCustomResourceLoading() throws Exception {
// Using default classloader
JobConf jobConf = new JobConf();
// foo-loader is not defined in default classloader
Assert.assertNull(jobConf.get("foo-loader"));
// On first load, TestClass.init should be false
Assert.assertFalse(TestClass.init);
TestClass.init = true;
// Using ResourcesClassLoader with URL /test-conf
URL url = getClass().getResource("/test-conf/mapred-site.xml");
ClassLoader previousClassLoader = ClassLoaders.setContextClassLoader(
new ResourcesClassLoader(new URL[]{getParentUrl(url)}, getClass().getClassLoader()));
jobConf = new JobConf();
Assert.assertEquals("bar-loader", jobConf.get("foo-loader"));
// TestClass is already initialzed earlier, hence TestClass.init should be true
TestClass testClass =
(TestClass) Thread.currentThread().getContextClassLoader().loadClass(TestClass.class.getName()).newInstance();
Assert.assertTrue(testClass.init);
ClassLoaders.setContextClassLoader(previousClassLoader);
// Using ResourcesClassLoader with URL /test-app-conf
url = getClass().getResource("/test-app-conf/mapred-site.xml");
previousClassLoader = ClassLoaders.setContextClassLoader(
new ResourcesClassLoader(new URL[]{getParentUrl(url)}, getClass().getClassLoader()));
jobConf = new JobConf();
Assert.assertEquals("baz-app-loader", jobConf.get("foo-loader"));
// TestClass is already initialzed earlier, hence TestClass.init should be true
testClass =
(TestClass) Thread.currentThread().getContextClassLoader().loadClass(TestClass.class.getName()).newInstance();
Assert.assertTrue(testClass.init);
ClassLoaders.setContextClassLoader(previousClassLoader);
}
@SuppressWarnings("ConstantConditions")
@Test
public void testFirstNonNull() throws Exception {
Integer null1 = null;
Integer five = 5;
Assert.assertNull(ResourcesClassLoader.firstNonNull(null1, null1));
Assert.assertEquals((Integer) 5, ResourcesClassLoader.firstNonNull(null1, five));
Assert.assertEquals((Integer) 5, ResourcesClassLoader.firstNonNull(five, null1));
Assert.assertEquals((Integer) 5, ResourcesClassLoader.firstNonNull(five, five));
}
private URL getParentUrl(URL url) throws Exception {
URI uri = url.toURI();
return uri.getPath().endsWith("/") ? uri.resolve("..").toURL() : uri.resolve(".").toURL();
}
public static final class TestClass {
public static boolean init = false;
}
}
|
3e1104a161876443dc7e56810ddd9279737f159d | 6,446 | java | Java | src/top/totoro/plugin/action/NewActivityFileAction.java | totoro-dev/IDEA_Plugin | 1ab662006513d117f0cd2e5c463dc76acdd1d2e0 | [
"Apache-2.0"
] | null | null | null | src/top/totoro/plugin/action/NewActivityFileAction.java | totoro-dev/IDEA_Plugin | 1ab662006513d117f0cd2e5c463dc76acdd1d2e0 | [
"Apache-2.0"
] | null | null | null | src/top/totoro/plugin/action/NewActivityFileAction.java | totoro-dev/IDEA_Plugin | 1ab662006513d117f0cd2e5c463dc76acdd1d2e0 | [
"Apache-2.0"
] | null | null | null | 33.398964 | 128 | 0.56919 | 7,170 | package top.totoro.plugin.action;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import top.totoro.plugin.file.Log;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.nio.charset.StandardCharsets;
import static top.totoro.plugin.constant.Constants.NEW_SWING_FILE_CONTENT;
public class NewActivityFileAction extends AnAction {
private Project project;
private String path;
private VirtualFile chooseFile;
public NewActivityFileAction() {
super("新建Activity文件");
}
public void setChooseFile(VirtualFile chooseFile) {
this.chooseFile = chooseFile;
}
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
project = anActionEvent.getProject();
new NewActivityFileDialog().show();
}
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
e.getPresentation().setEnabled(false);
/* 处理新建Swing布局按钮是否可用 */
if (chooseFile.getPath().contains("/java")) {
if (chooseFile.getName().equals("java") || chooseFile.getPath().contains("/java/")) {
e.getPresentation().setEnabled(true);
}
}
}
public void setPath(String path) {
this.path = path;
}
/* 点击新建Swing布局的对话框 */
public class NewActivityFileDialog extends DialogWrapper {
public NewActivityFileDialog() {
super(true);
setTitle("新建Activity文件"); //设置会话框标题
setResizable(false);
init(); //触发一下init方法,否则swing样式将无法展示在会话框
}
private final JTextField nameContent = new JTextField(30);
public JPanel initNorth() {
//定义表单的标题部分,放置到IDEA会话框的顶部位置
return null;
}
public JPanel initCenter() {
JPanel center = new JPanel();
JLabel name = new JLabel("文件名:");
//定义表单的主体部分,放置到IDEA会话框的中央位置
center.setLayout(new BorderLayout());
//row1:文件名+文本框
center.add(name, BorderLayout.WEST);
center.add(nameContent, BorderLayout.CENTER);
return center;
}
public JPanel initSouth() {
JPanel south = new JPanel();
//定义表单的提交按钮,放置到IDEA会话框的底部位置
JButton submit = new JButton("创建");
submit.setHorizontalAlignment(SwingConstants.CENTER); //水平居中
submit.setVerticalAlignment(SwingConstants.CENTER); //垂直居中
south.add(submit);
//按钮事件绑定
submit.addActionListener(e -> {
createActivityFile();
});
nameContent.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER)
createActivityFile();
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
});
return south;
}
@SuppressWarnings({"DialogTitleCapitalization", "ResultOfMethodCallIgnored"})
private void createActivityFile() {
if (nameContent.getText() == null || nameContent.getText().isEmpty()) {
Messages.showMessageDialog(project, "文件名不能为空", "无法创建", Messages.getErrorIcon());
return;
}
String filename = nameContent.getText() + ".java";
String packagePath = "";
if (!path.endsWith("/java")) {
packagePath = path.substring(path.indexOf("/java/") + "/java/".length());
Log.d(this, "packagePath = " + packagePath);
}
File activityFile = new File(path + "/" + filename);
if (activityFile.exists()) {
Messages.showMessageDialog(project, filename + "已存在", "无法创建", Messages.getErrorIcon());
return;
}
if (!activityFile.getParentFile().exists()) {
activityFile.getParentFile().mkdirs();
}
if (activityFile.getParentFile().exists()) {
try {
activityFile.createNewFile();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(activityFile), StandardCharsets.UTF_8);
osw.write(getActivityContent(packagePath, nameContent.getText()));
osw.flush();
osw.close();
// 刷新目录
chooseFile.refresh(false, true);
close(1);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
@Override
protected JComponent createNorthPanel() {
return initNorth(); //返回位于会话框north位置的swing样式
}
// 特别说明:不需要展示SouthPanel要重写返回null,否则IDEA将展示默认的"Cancel"和"OK"按钮
@Override
protected JComponent createSouthPanel() {
return initSouth();
}
@Override
protected JComponent createCenterPanel() {
//定义表单的主题,放置到IDEA会话框的中央位置
return initCenter();
}
}
private String getActivityContent(String packagePath, String className) {
String packageHeader = "";
if (!packagePath.isEmpty()) {
packageHeader = "package " + packagePath + ";\n\n";
}
String importContent = "import swing.R;\n" +
"import top.totoro.swing.widget.context.Activity;\n\n";
String classHeader = "public class " + className + " extends Activity {\n";
String classBody = " @Override\n" +
" public void onCreate() {\n" +
" super.onCreate();\n" +
" setContentView(R.layout.activity_main);\n" +
" }\n";
String classTail = "}\n";
return packageHeader + importContent + classHeader + classBody + classTail;
}
}
|
3e1104cb908786f9a2ab77fb2ea83370d5b62a65 | 217 | java | Java | src/main/java/com/alexonxxx/dddshop/cashregister/CashRegisterEvent.java | alexonxxx/DDD-shop | d3a1ef87f5b18c44061b0b57f78f013fe71fa998 | [
"0BSD"
] | null | null | null | src/main/java/com/alexonxxx/dddshop/cashregister/CashRegisterEvent.java | alexonxxx/DDD-shop | d3a1ef87f5b18c44061b0b57f78f013fe71fa998 | [
"0BSD"
] | null | null | null | src/main/java/com/alexonxxx/dddshop/cashregister/CashRegisterEvent.java | alexonxxx/DDD-shop | d3a1ef87f5b18c44061b0b57f78f013fe71fa998 | [
"0BSD"
] | null | null | null | 21.7 | 55 | 0.746544 | 7,171 | package com.alexonxxx.dddshop.cashregister;
import com.alexonxxx.dddshop.events.Event;
public abstract class CashRegisterEvent extends Event {
public CashRegisterEvent() {
super("cashregister");
}
}
|
3e1104ecaa376a42aea241d467b04776bf937668 | 2,930 | java | Java | service/src/main/java/org/vandervj/cleanPath/control/CleanerControl.java | jvandervelden/clean-path | 5fa5cd25403709029c06240fee5856e5b6691aa1 | [
"Apache-2.0"
] | null | null | null | service/src/main/java/org/vandervj/cleanPath/control/CleanerControl.java | jvandervelden/clean-path | 5fa5cd25403709029c06240fee5856e5b6691aa1 | [
"Apache-2.0"
] | null | null | null | service/src/main/java/org/vandervj/cleanPath/control/CleanerControl.java | jvandervelden/clean-path | 5fa5cd25403709029c06240fee5856e5b6691aa1 | [
"Apache-2.0"
] | null | null | null | 27.383178 | 139 | 0.727986 | 7,172 | /**
* Copyright 2019, Kion Group All Rights Reserved.
* Created by vandervj on 2/28/2019.
*/
package org.vandervj.cleanPath.control;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.vandervj.cleanPath.boundary.dto.CleanerDto;
import org.vandervj.cleanPath.boundary.dto.MapDto;
import org.vandervj.cleanPath.entity.CleanerDirection;
import org.vandervj.cleanPath.net.CleanerTelemetry;
import org.vandervj.cleanPath.net.TelemetryDto;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Named
public class CleanerControl implements ApplicationListener<ApplicationReadyEvent> {
private static Logger logger = LoggerFactory.getLogger(CleanerControl.class);
@Inject
private MapControl mapControl;
@Inject
private CleanerTelemetry cleanerTelemetryRequest;
public static List<CleanerDto> cleaners = new ArrayList<>();
static {
cleaners.add(new CleanerDto());
}
public CleanerDto getCleaner(final int id) {
try {
return cleaners.get(id);
} catch (final IndexOutOfBoundsException e) {
return null;
}
}
public void updateCleaner(final int id, final CleanerDto cleaner) {
cleaners.add(id, cleaner);
cleanerTelemetryRequest.setCleanerPosition(id, new TelemetryDto(cleaner.getPositionX(), cleaner.getPositionY(), cleaner.getDirection()));
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
// Setup the initial cleaner on a random point in the map.
final MapDto map = mapControl.getMap(0);
final int maxY = map.size();
final int maxX = maxY > 0 ? map.get(0).size() : 0;
final Random rand = new Random();
final CleanerDirection direction =
CleanerDirection.values()[rand.nextInt(CleanerDirection.values().length)];
int x = 0;
int y = 0;
if (maxX > 0 && maxY > 0) {
int tries = 0;
do {
x = rand.nextInt(maxX);
y = rand.nextInt(maxY);
tries++;
} while (map.get(y).get(x).equals("#") && tries < maxX * maxY);
if (tries >= maxX * maxY) {
x = y = 0;
logger.error("Unable to find a suitable random x, y coordinate. Setting to 0,0");
}
}
cleaners.get(0).setPositionX(x);
cleaners.get(0).setPositionY(y);
cleaners.get(0).setDirection(direction);
cleaners.get(0).setMapId(0);
final TelemetryDto telemetryDto = new TelemetryDto(x, y, direction);
logger.info("Setting initial position of cleaner");
while(!cleanerTelemetryRequest.setCleanerPosition(0, telemetryDto)) {
logger.info("Failed to set initial position, sleeping 1 second and trying again.");
if (Thread.currentThread().isInterrupted()) {
Thread.currentThread().interrupt();
break;
}
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
break;
}
}
}
}
|
3e11052fb305ae50e4d7369446dce9df7ed99050 | 631 | java | Java | app/repository/EbeanRepository.java | MateusDantas/ufcgcarona | 8ad0eab1c0afcdf1d92f918f97d3cb4622a0c7e3 | [
"Apache-2.0"
] | null | null | null | app/repository/EbeanRepository.java | MateusDantas/ufcgcarona | 8ad0eab1c0afcdf1d92f918f97d3cb4622a0c7e3 | [
"Apache-2.0"
] | null | null | null | app/repository/EbeanRepository.java | MateusDantas/ufcgcarona | 8ad0eab1c0afcdf1d92f918f97d3cb4622a0c7e3 | [
"Apache-2.0"
] | null | null | null | 21.758621 | 84 | 0.727417 | 7,173 | package repository;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import models.Identity;
public abstract class EbeanRepository<T extends Identity> implements Repository<T> {
@Override
public Optional<T> get(String id) {
return get().stream().filter(entity -> entity.getId().equals(id)).findFirst();
}
@Override
public Set<T> query(Predicate<T> query) {
return get().stream().filter(query).collect(Collectors.toSet());
}
@Override
public boolean remove(String id) {
T entity = this.get(id).get();
return this.remove(entity);
}
}
|
3e11053ab588fde34e6337571b532bc57b983bb7 | 4,303 | java | Java | jOOQ/src/main/java/org/jooq/Template.java | Vertabelo/jOOQ | e65f62d833286ea0689748e3be47dabe94a9f511 | [
"Apache-2.0"
] | 1 | 2015-01-19T00:51:30.000Z | 2015-01-19T00:51:30.000Z | jOOQ/src/main/java/org/jooq/Template.java | Vertabelo/jOOQ | e65f62d833286ea0689748e3be47dabe94a9f511 | [
"Apache-2.0"
] | null | null | null | jOOQ/src/main/java/org/jooq/Template.java | Vertabelo/jOOQ | e65f62d833286ea0689748e3be47dabe94a9f511 | [
"Apache-2.0"
] | null | null | null | 33.88189 | 122 | 0.640716 | 7,174 | /**
* Copyright (c) 2009-2014, Data Geekery GmbH (http://www.datageekery.com)
* All rights reserved.
*
* This work is dual-licensed
* - under the Apache Software License 2.0 (the "ASL")
* - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
* =============================================================================
* You may choose which license applies to you:
*
* - If you're using this work with Open Source databases, you may choose
* either ASL or jOOQ License.
* - If you're using this work with at least one commercial database, you must
* choose jOOQ License
*
* For more information, please visit http://www.jooq.org/licenses
*
* Apache Software License 2.0:
* -----------------------------------------------------------------------------
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* jOOQ License and Maintenance Agreement:
* -----------------------------------------------------------------------------
* Data Geekery grants the Customer the non-exclusive, timely limited and
* non-transferable license to install and use the Software under the terms of
* the jOOQ License and Maintenance Agreement.
*
* This library is distributed with a LIMITED WARRANTY. See the jOOQ License
* and Maintenance Agreement for more details: http://www.jooq.org/licensing
*/
package org.jooq;
/**
* A functional interface to return custom {@link QueryPart} objects from input.
* <p>
* This interface is used for templating in jOOQ. Any type of
* <code>QueryPart</code> can be created through templating mechanisms.
* Depending on the template, some <code>input</code> data is needed - for
* example an array or a collection of bind values.
* <p>
* Simple examples of templates are plain SQL construction templates, which are
* used by jOOQ internally for all plain SQL factory methods. More sophisticated
* examples include XSL transformation templates, MyBatis templates, etc.
* <p>
* An example using Apache Velocity is given here:
* <p>
* <code><pre>
* class VelocityTemplate implements Template {
* private final String file;
*
* public VelocityTemplate(String file) {
* this.file = file;
* }
*
* public QueryPart transform(Object... input) {
* VelocityEngine ve = new VelocityEngine();
* ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
* ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, new File("authors-and-books.vm").getAbsolutePath());
* ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
* ve.init();
*
* VelocityContext context = new VelocityContext();
* context.put("p", input);
*
* StringWriter writer = new StringWriter();
* ve.getTemplate(file, "UTF-8").merge(context, writer);
* return DSL.queryPart(writer.toString(), input);
* }
* }
* </pre></code>
* <p>
* And then:
* <p>
* <code><pre>
* DSL.using(configuration)
* .resultQuery(new VelocityTemplate("authors-and-books.vm"), 1, 2, 3)
* .fetch();
* </pre></code>
* <p>
* With the contents of authors-and-books.vm being
* <p>
* <code><pre>
* SELECT
* a.first_name,
* a.last_name,
* count(*)
* FROM
* t_author a
* LEFT OUTER JOIN
* t_book b ON a.id = b.author_id
* WHERE
* 1 = 0
* #foreach ($param in $p)
* OR a.id = ?
* #end
* GROUP BY
* a.first_name,
* a.last_name
* ORDER BY
* a.id ASC
* </pre></code>
* <p>
*
* @deprecated - This type is still very experimental and not yet released to a
* broad public. Do not use this type yet.
* @author Lukas Eder
*/
@Deprecated
public interface Template {
/**
* Transform some input data into a {@link QueryPart}.
*/
QueryPart transform(Object... input);
}
|
3e1106375b5a0f2bd3c25cf8ac54e7839ca8017b | 9,567 | java | Java | luwak/src/main/java/uk/co/flax/luwak/QueryIndex.java | 28kayak/luwak | 87bdb2960847c1f886fd0407b81b9da231913e52 | [
"Apache-2.0"
] | 360 | 2015-01-04T14:58:28.000Z | 2022-02-25T09:41:00.000Z | luwak/src/main/java/uk/co/flax/luwak/QueryIndex.java | 28kayak/luwak | 87bdb2960847c1f886fd0407b81b9da231913e52 | [
"Apache-2.0"
] | 117 | 2015-04-23T08:05:42.000Z | 2020-01-10T08:29:10.000Z | luwak/src/main/java/uk/co/flax/luwak/QueryIndex.java | 28kayak/luwak | 87bdb2960847c1f886fd0407b81b9da231913e52 | [
"Apache-2.0"
] | 101 | 2015-02-16T16:17:34.000Z | 2022-02-25T09:43:07.000Z | 34.413669 | 126 | 0.603951 | 7,175 | package uk.co.flax.luwak;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
class QueryIndex {
private final IndexWriter writer;
private final SearcherManager manager;
/* Used to cache updates while a purge is ongoing */
private volatile Map<BytesRef, QueryCacheEntry> purgeCache = null;
/* Used to lock around the creation of the purgeCache */
private final ReadWriteLock purgeLock = new ReentrantReadWriteLock();
private final Object commitLock = new Object();
/* The current query cache */
private volatile ConcurrentMap<BytesRef, QueryCacheEntry> queries = new ConcurrentHashMap<>();
// NB this is not final because it can be replaced by purgeCache()
// package-private for testing
final Map<IndexReader.CacheKey, QueryTermFilter> termFilters = new HashMap<>();
QueryIndex(IndexWriter indexWriter) throws IOException {
this.writer = indexWriter;
this.manager = new SearcherManager(writer, true, true, new TermsHashBuilder());
}
QueryIndex() throws IOException {
this(Monitor.defaultIndexWriter(new RAMDirectory()));
}
private class TermsHashBuilder extends SearcherFactory {
@Override
public IndexSearcher newSearcher(IndexReader reader, IndexReader previousReader) throws IOException {
IndexSearcher searcher = super.newSearcher(reader, previousReader);
searcher.setQueryCache(null);
termFilters.put(reader.getReaderCacheHelper().getKey(), new QueryTermFilter(reader));
reader.getReaderCacheHelper().addClosedListener(termFilters::remove);
return searcher;
}
}
void commit(List<Indexable> updates) throws IOException {
synchronized (commitLock) {
purgeLock.readLock().lock();
try {
if (updates != null) {
Set<String> ids = new HashSet<>();
for (Indexable update : updates) {
ids.add(update.id);
}
for (String id : ids) {
writer.deleteDocuments(new Term(Monitor.FIELDS.del, id));
}
for (Indexable update : updates) {
this.queries.put(update.queryCacheEntry.hash, update.queryCacheEntry);
writer.addDocument(update.document);
if (purgeCache != null)
purgeCache.put(update.queryCacheEntry.hash, update.queryCacheEntry);
}
}
writer.commit();
manager.maybeRefresh();
} finally {
purgeLock.readLock().unlock();
}
}
}
interface QueryBuilder {
Query buildQuery(QueryTermFilter termFilter) throws IOException;
}
long scan(QueryCollector matcher) throws IOException {
return search(new MatchAllDocsQuery(), matcher);
}
long search(final Query query, QueryCollector matcher) throws IOException {
QueryBuilder builder = termFilter -> query;
return search(builder, matcher);
}
long search(QueryBuilder queryBuilder, QueryCollector matcher) throws IOException {
IndexSearcher searcher = null;
try {
Map<BytesRef, QueryCacheEntry> queries;
purgeLock.readLock().lock();
try {
searcher = manager.acquire();
queries = this.queries;
}
finally {
purgeLock.readLock().unlock();
}
MonitorQueryCollector collector = new MonitorQueryCollector(queries, matcher);
long buildTime = System.nanoTime();
Query query = queryBuilder.buildQuery(termFilters.get(searcher.getIndexReader().getReaderCacheHelper().getKey()));
buildTime = System.nanoTime() - buildTime;
searcher.search(query, collector);
return buildTime;
}
finally {
if (searcher != null) {
manager.release(searcher);
}
}
}
interface CachePopulator {
void populateCacheWithIndex(Map<BytesRef, QueryCacheEntry> newCache) throws IOException;
}
/**
* Remove unused queries from the query cache.
*
* This is normally called from a background thread at a rate set by configurePurgeFrequency().
*
* @throws IOException on IO errors
*/
synchronized void purgeCache(CachePopulator populator) throws IOException {
/*
Note on implementation
The purge works by scanning the query index and creating a new query cache populated
for each query in the index. When the scan is complete, the old query cache is swapped
for the new, allowing it to be garbage-collected.
In order to not drop cached queries that have been added while a purge is ongoing,
we use a ReadWriteLock to guard the creation and removal of an update log. Commits take
the read lock. If the update log has been created, then a purge is ongoing, and queries
are added to the update log within the read lock guard.
The purge takes the write lock when creating the update log, and then when swapping out
the old query cache. Within the second write lock guard, the contents of the update log
are added to the new query cache, and the update log itself is removed.
*/
final ConcurrentMap<BytesRef, QueryCacheEntry> newCache = new ConcurrentHashMap<>();
purgeLock.writeLock().lock();
try {
purgeCache = new ConcurrentHashMap<>();
}
finally {
purgeLock.writeLock().unlock();
}
populator.populateCacheWithIndex(newCache);
purgeLock.writeLock().lock();
try {
newCache.putAll(purgeCache);
purgeCache = null;
queries = newCache;
}
finally {
purgeLock.writeLock().unlock();
}
}
// ---------------------------------------------
// Proxy trivial operations...
// ---------------------------------------------
void closeWhileHandlingException() throws IOException {
IOUtils.closeWhileHandlingException(manager, writer, writer.getDirectory());
}
int numDocs() {
return writer.numDocs();
}
int numRamDocs() {
return writer.numRamDocs();
}
int cacheSize() {
return queries.size();
}
void deleteDocuments(Term term) throws IOException {
writer.deleteDocuments(term);
}
void deleteDocuments(Query query) throws IOException {
writer.deleteDocuments(query);
}
interface QueryCollector {
void matchQuery(String id, QueryCacheEntry query, DataValues dataValues) throws IOException;
default boolean needsScores() {
return false;
}
}
// ---------------------------------------------
// Helper classes...
// ---------------------------------------------
static final class DataValues {
public BinaryDocValues hash;
public SortedDocValues id;
public BinaryDocValues mq;
public Scorer scorer;
public int doc;
void advance(int doc) throws IOException {
this.doc = doc;
hash.advanceExact(doc);
id.advanceExact(doc);
if (mq != null) {
mq.advanceExact(doc);
}
}
}
/**
* A Collector that decodes the stored query for each document hit.
*/
static final class MonitorQueryCollector extends SimpleCollector {
private final Map<BytesRef, QueryCacheEntry> queries;
private final QueryCollector matcher;
private final DataValues dataValues = new DataValues();
public MonitorQueryCollector(Map<BytesRef, QueryCacheEntry> queries, QueryCollector matcher) {
this.queries = queries;
this.matcher = matcher;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.dataValues.scorer = scorer;
}
@Override
public void collect(int doc) throws IOException {
dataValues.advance(doc);
BytesRef hash = dataValues.hash.binaryValue();
BytesRef id = dataValues.id.binaryValue();
QueryCacheEntry query = queries.get(hash);
matcher.matchQuery(id.utf8ToString(), query, dataValues);
}
@Override
public void doSetNextReader(LeafReaderContext context) throws IOException {
this.dataValues.hash = context.reader().getBinaryDocValues(Monitor.FIELDS.hash);
this.dataValues.id = context.reader().getSortedDocValues(Monitor.FIELDS.id);
this.dataValues.mq = context.reader().getBinaryDocValues(Monitor.FIELDS.mq);
}
@Override
public boolean needsScores() {
return matcher.needsScores();
}
}
}
|
3e110694b2ab4769d0aff33d33f804b79f4f4e54 | 2,969 | java | Java | src/main/java/com/yapp/pet/web/account/model/MyPageResponse.java | YAPP-Github/20th-iOS-Team-1-BE | 3996eb2f73fde21fcf50512eafba6caef11ed21d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yapp/pet/web/account/model/MyPageResponse.java | YAPP-Github/20th-iOS-Team-1-BE | 3996eb2f73fde21fcf50512eafba6caef11ed21d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yapp/pet/web/account/model/MyPageResponse.java | YAPP-Github/20th-iOS-Team-1-BE | 3996eb2f73fde21fcf50512eafba6caef11ed21d | [
"Apache-2.0"
] | null | null | null | 26.274336 | 99 | 0.615359 | 7,176 | package com.yapp.pet.web.account.model;
import com.yapp.pet.domain.account.entity.Account;
import com.yapp.pet.domain.account.entity.AccountSex;
import com.yapp.pet.domain.common.Category;
import com.yapp.pet.domain.pet.entity.Pet;
import com.yapp.pet.domain.pet.entity.PetSex;
import com.yapp.pet.domain.pet_tag.PetTag;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
@NoArgsConstructor
public class MyPageResponse {
private AccountInfoResponse accountInfo;
private List<PetInfoResponse> petInfos;
public MyPageResponse(Account account, List<Pet> pets) {
this.accountInfo = new AccountInfoResponse(account);
this.petInfos = pets.stream()
.map(PetInfoResponse::new)
.collect(Collectors.toList());
}
public static MyPageResponse of(Account account, List<Pet> pets) {
return new MyPageResponse(account, pets);
}
@Getter
@Setter
@NoArgsConstructor
public static class AccountInfoResponse {
private String nickname;
private String address;
private String age;
private AccountSex sex;
private String selfIntroduction;
private List<Category> interestCategories = new ArrayList<>();
private String imageUrl;
public AccountInfoResponse(Account account) {
this.nickname = account.getNickname();
this.address = account.getAddress().getCity() + " " + account.getAddress().getDetail();
this.age = account.getAge() + "살";
this.sex = account.getSex();
this.selfIntroduction = account.getSelfIntroduction();
if (account.getInterestCategories() != null) {
this.interestCategories.addAll(account.getInterestCategories());
}
if (account.getAccountImage() != null) {
this.imageUrl = account.getAccountImage().getPath();
}
}
}
@Getter
@Setter
@NoArgsConstructor
public static class PetInfoResponse {
private String nickname;
private String breed;
private String age;
private PetSex sex;
private List<String> tags = new ArrayList<>();
private String imageUrl;
public PetInfoResponse(Pet pet) {
this.nickname = pet.getName();
this.breed = pet.getBreed();
this.age = pet.getAge().getAge();
this.sex = pet.getSex();
if (pet.getTags() != null && pet.getTags().size() != 0) {
this.tags.addAll(pet.getTags().stream()
.map(PetTag::getName)
.collect(Collectors.toList()));
}
if (pet.getPetImage() != null) {
this.imageUrl = pet.getPetImage().getPath();
}
}
}
}
|
3e1107077cdfba02e7a933d7c481cccb7bc15182 | 2,262 | java | Java | src/main/java/com/ruoyi/project/system/feetype/domain/Feetype.java | nanagirl0720/pinggu_yj | 8c4d261871bf8250b06118382e7b8b6504ed9a9b | [
"MIT"
] | 1 | 2019-07-30T16:07:56.000Z | 2019-07-30T16:07:56.000Z | src/main/java/com/ruoyi/project/system/feetype/domain/Feetype.java | nanagirl0720/pinggu_yj | 8c4d261871bf8250b06118382e7b8b6504ed9a9b | [
"MIT"
] | 1 | 2021-09-20T20:50:25.000Z | 2021-09-20T20:50:25.000Z | src/main/java/com/ruoyi/project/system/feetype/domain/Feetype.java | nanagirl0720/pinggu_yj | 8c4d261871bf8250b06118382e7b8b6504ed9a9b | [
"MIT"
] | null | null | null | 19.669565 | 72 | 0.646773 | 7,177 | package com.ruoyi.project.system.feetype.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.framework.aspectj.lang.annotation.Excel;
import com.ruoyi.framework.web.domain.BaseEntity;
import com.ruoyi.project.system.dict.domain.DictData;
import java.util.Date;
/**
* 费用类别表 sys_feetype
*
* @author panda
* @date 2018-12-18
*/
public class Feetype extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 费用类别表id */
@Excel(name="费用类别序号")
private Integer id;
/** 费用类别编码 */
@Excel(name="费用类别编码")
private String feecode;
/** 费用类别名称 */
@Excel(name="费用类别名称")
private String feename;
/** 数据来源 */
@Excel(name="数据来源")
private Integer datatype;
/** 创建时间 */
private Date createtime;
/** 修改时间 */
private Date updatetime;
/** 数据来源*/
private DictData dictdata;
public DictData getDictdata() {
return dictdata;
}
public void setDictdata(DictData dictdata) {
this.dictdata = dictdata;
}
public Integer getDatatype() {
return datatype;
}
public void setDatatype(Integer datatype) {
this.datatype = datatype;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return id;
}
public void setFeecode(String feecode)
{
this.feecode = feecode;
}
public String getFeecode()
{
return feecode;
}
public void setFeename(String feename)
{
this.feename = feename;
}
public String getFeename()
{
return feename;
}
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("feecode", getFeecode())
.append("feename", getFeename())
.append("createtime", getCreatetime())
.append("updatetime", getUpdatetime())
.toString();
}
}
|
3e110745830abd872eff009d6583b96b121b1f45 | 5,489 | java | Java | xxpay-shop/src/main/java/org/xxpay/shop/dao/plugin/DruidDataSourceConfig.java | digitalops-mall/mall-pay | a79f8684a616ce012a68c95bb425e1561037b0e1 | [
"MIT"
] | null | null | null | xxpay-shop/src/main/java/org/xxpay/shop/dao/plugin/DruidDataSourceConfig.java | digitalops-mall/mall-pay | a79f8684a616ce012a68c95bb425e1561037b0e1 | [
"MIT"
] | null | null | null | xxpay-shop/src/main/java/org/xxpay/shop/dao/plugin/DruidDataSourceConfig.java | digitalops-mall/mall-pay | a79f8684a616ce012a68c95bb425e1561037b0e1 | [
"MIT"
] | null | null | null | 54.346535 | 156 | 0.772272 | 7,178 | package org.xxpay.shop.dao.plugin;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
/**
*
*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "org.xxpay.shop.dao.mapper")
public class DruidDataSourceConfig implements EnvironmentAware {
private Environment environment;
private Properties properties;
public void setEnvironment(Environment environment) {
this.environment = environment;
Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
Binder binder = new Binder(sources);
BindResult<Properties> bindResult = binder.bind("spring.datasource", Properties.class);
this.properties = bindResult.get();
}
//注册dataSource
@Bean(initMethod = "init", destroyMethod = "close")
public DruidDataSource dataSource() throws SQLException {
if (StringUtils.isEmpty(properties.getProperty("url"))) {
System.out.println("Your database connection pool configuration is incorrect!"
+ " Please check your Spring profile, current profiles are:"
+ Arrays.toString(environment.getActiveProfiles()));
throw new ApplicationContextException(
"Database connection pool is not configured correctly");
}
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getProperty("driver-class-name"));
druidDataSource.setUrl(properties.getProperty("url"));
druidDataSource.setUsername(properties.getProperty("username"));
druidDataSource.setPassword(properties.getProperty("password"));
druidDataSource.setInitialSize(Integer.parseInt(properties.getProperty("initialSize")));
druidDataSource.setMinIdle(Integer.parseInt(properties.getProperty("minIdle")));
druidDataSource.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
druidDataSource.setMaxWait(Integer.parseInt(properties.getProperty("maxWait")));
druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(properties.getProperty("timeBetweenEvictionRunsMillis")));
druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(properties.getProperty("minEvictableIdleTimeMillis")));
druidDataSource.setValidationQuery(properties.getProperty("validationQuery"));
druidDataSource.setTestWhileIdle(Boolean.parseBoolean(properties.getProperty("testWhileIdle")));
druidDataSource.setTestOnBorrow(Boolean.parseBoolean(properties.getProperty("testOnBorrow")));
druidDataSource.setTestOnReturn(Boolean.parseBoolean(properties.getProperty("testOnReturn")));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(properties.getProperty("poolPreparedStatements")));
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(properties.getProperty("maxPoolPreparedStatementPerConnectionSize")));
druidDataSource.setFilters(properties.getProperty("filters"));
return druidDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
//mybatis分页
PageHelper pageHelper = new PageHelper();
Properties props = new Properties();
props.setProperty("dialect", "mysql");
props.setProperty("reasonable", "true");
props.setProperty("supportMethodsArguments", "true");
props.setProperty("returnPageInfo", "check");
props.setProperty("params", "count=countSql");
pageHelper.setProperties(props); //添加插件
sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:org/xxpay/shop/dao/mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
return new DataSourceTransactionManager(dataSource());
}
} |
3e110778a7f341b22f4c675ebda9c5bad0248e71 | 937 | java | Java | src/S0892SurfaceArea3DShapes.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 4 | 2021-11-30T20:28:14.000Z | 2022-01-04T04:01:32.000Z | src/S0892SurfaceArea3DShapes.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | null | null | null | src/S0892SurfaceArea3DShapes.java | camelcc/leetcode | 0ba37f7fd47ed3e893525988ce803ce805001ba7 | [
"CECILL-B"
] | 1 | 2021-11-30T23:33:51.000Z | 2021-11-30T23:33:51.000Z | 30.225806 | 64 | 0.310566 | 7,179 | public class S0892SurfaceArea3DShapes {
public int surfaceArea(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
int M = grid.length;
int N = grid[0].length;
int cnt = 0;
for (int x = 0; x < M; x++) {
for (int y = 0; y < N; y++) {
if (grid[x][y] > 0) {
cnt += (grid[x][y] * 4 + 2);
}
if (x > 0) {
cnt -= Math.min(grid[x][y], grid[x - 1][y]);
}
if (x < M-1) {
cnt -= Math.min(grid[x][y], grid[x+1][y]);
}
if (y > 0) {
cnt -= Math.min(grid[x][y], grid[x][y - 1]);
}
if (y < N-1) {
cnt -= Math.min(grid[x][y], grid[x][y+1]);
}
}
}
return cnt;
}
}
|
3e110840f8fc3f5061d7722e0b1058728b03b4f2 | 1,132 | java | Java | src/main/java/com/karl/debugger/ui/core/file/SystemBlobFileRender.java | kawhii/debugger-ui | 68b85857c627050a6a720bdd69e6cb13c88bafc5 | [
"Apache-2.0"
] | 5 | 2018-08-06T06:08:48.000Z | 2021-02-27T07:48:27.000Z | src/main/java/com/karl/debugger/ui/core/file/SystemBlobFileRender.java | kawhii/debugger-ui | 68b85857c627050a6a720bdd69e6cb13c88bafc5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/karl/debugger/ui/core/file/SystemBlobFileRender.java | kawhii/debugger-ui | 68b85857c627050a6a720bdd69e6cb13c88bafc5 | [
"Apache-2.0"
] | 4 | 2018-11-14T14:16:03.000Z | 2021-02-24T01:52:41.000Z | 25.155556 | 70 | 0.710247 | 7,180 | package com.karl.debugger.ui.core.file;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
/**
* 直接输出的文件渲染器
*
* @author karl
* @date 2018/7/22
*/
public class SystemBlobFileRender extends BaseFileRender<String> {
/**
* 这些后缀能够被处理
*/
@Autowired
@Qualifier("fileProcessSuffix")
private Set<String> fileProcessSuffix;
@Override
public String name() {
return "blob";
}
@Override
public boolean support(String suffix) {
return fileProcessSuffix.contains(suffix);
}
@Override
public String render(String filePath) throws IOException {
String basePath = rootDirectoryAware.getRootDir();
File file = new File(basePath, filePath);
String str = FileCopyUtils.copyToString(new FileReader(file));
return Base64Utils.encodeToString(str.getBytes("UTF-8"));
}
}
|
3e1108fb25bd2a6e005fc5f96651969936912055 | 24,657 | java | Java | classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/swing/plaf/basic/BasicHTML.java | Suyashtnt/Bytecoder | d957081d50f2d30b3206447b805b1ca9da69c8c2 | [
"Apache-2.0"
] | 543 | 2017-06-14T14:53:33.000Z | 2022-03-23T14:18:09.000Z | classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/swing/plaf/basic/BasicHTML.java | Suyashtnt/Bytecoder | d957081d50f2d30b3206447b805b1ca9da69c8c2 | [
"Apache-2.0"
] | 381 | 2017-10-31T14:29:54.000Z | 2022-03-25T15:27:27.000Z | classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/swing/plaf/basic/BasicHTML.java | Suyashtnt/Bytecoder | d957081d50f2d30b3206447b805b1ca9da69c8c2 | [
"Apache-2.0"
] | 50 | 2018-01-06T12:35:14.000Z | 2022-03-13T14:54:33.000Z | 35.631503 | 100 | 0.580646 | 7,181 | /*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.basic;
import java.io.*;
import java.awt.*;
import java.net.URL;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import sun.swing.SwingUtilities2;
/**
* Support for providing html views for the swing components.
* This translates a simple html string to a javax.swing.text.View
* implementation that can render the html and provide the necessary
* layout semantics.
*
* @author Timothy Prinzing
* @since 1.3
*/
public class BasicHTML {
/**
* Constructs a {@code BasicHTML}.
*/
public BasicHTML() {}
/**
* Create an html renderer for the given component and
* string of html.
*
* @param c a component
* @param html an HTML string
* @return an HTML renderer
*/
public static View createHTMLView(JComponent c, String html) {
BasicEditorKit kit = getFactory();
Document doc = kit.createDefaultDocument(c.getFont(),
c.getForeground());
Object base = c.getClientProperty(documentBaseKey);
if (base instanceof URL) {
((HTMLDocument)doc).setBase((URL)base);
}
Reader r = new StringReader(html);
try {
kit.read(r, doc, 0);
} catch (Throwable e) {
}
ViewFactory f = kit.getViewFactory();
View hview = f.create(doc.getDefaultRootElement());
View v = new Renderer(c, f, hview);
return v;
}
/**
* Returns the baseline for the html renderer.
*
* @param view the View to get the baseline for
* @param w the width to get the baseline for
* @param h the height to get the baseline for
* @throws IllegalArgumentException if width or height is < 0
* @return baseline or a value < 0 indicating there is no reasonable
* baseline
* @see java.awt.FontMetrics
* @see javax.swing.JComponent#getBaseline(int,int)
* @since 1.6
*/
public static int getHTMLBaseline(View view, int w, int h) {
if (w < 0 || h < 0) {
throw new IllegalArgumentException(
"Width and height must be >= 0");
}
if (view instanceof Renderer) {
return getBaseline(view.getView(0), w, h);
}
return -1;
}
/**
* Gets the baseline for the specified component. This digs out
* the View client property, and if non-null the baseline is calculated
* from it. Otherwise the baseline is the value <code>y + ascent</code>.
*/
static int getBaseline(JComponent c, int y, int ascent,
int w, int h) {
View view = (View)c.getClientProperty(BasicHTML.propertyKey);
if (view != null) {
int baseline = getHTMLBaseline(view, w, h);
if (baseline < 0) {
return baseline;
}
return y + baseline;
}
return y + ascent;
}
/**
* Gets the baseline for the specified View.
*/
static int getBaseline(View view, int w, int h) {
if (hasParagraph(view)) {
view.setSize(w, h);
return getBaseline(view, new Rectangle(0, 0, w, h));
}
return -1;
}
private static int getBaseline(View view, Shape bounds) {
if (view.getViewCount() == 0) {
return -1;
}
AttributeSet attributes = view.getElement().getAttributes();
Object name = null;
if (attributes != null) {
name = attributes.getAttribute(StyleConstants.NameAttribute);
}
int index = 0;
if (name == HTML.Tag.HTML && view.getViewCount() > 1) {
// For html on widgets the header is not visible, skip it.
index++;
}
bounds = view.getChildAllocation(index, bounds);
if (bounds == null) {
return -1;
}
View child = view.getView(index);
if (view instanceof javax.swing.text.ParagraphView) {
Rectangle rect;
if (bounds instanceof Rectangle) {
rect = (Rectangle)bounds;
}
else {
rect = bounds.getBounds();
}
return rect.y + (int)(rect.height *
child.getAlignment(View.Y_AXIS));
}
return getBaseline(child, bounds);
}
private static boolean hasParagraph(View view) {
if (view instanceof javax.swing.text.ParagraphView) {
return true;
}
if (view.getViewCount() == 0) {
return false;
}
AttributeSet attributes = view.getElement().getAttributes();
Object name = null;
if (attributes != null) {
name = attributes.getAttribute(StyleConstants.NameAttribute);
}
int index = 0;
if (name == HTML.Tag.HTML && view.getViewCount() > 1) {
// For html on widgets the header is not visible, skip it.
index = 1;
}
return hasParagraph(view.getView(index));
}
/**
* Check the given string to see if it should trigger the
* html rendering logic in a non-text component that supports
* html rendering.
*
* @param s a text
* @return {@code true} if the given string should trigger the
* html rendering logic in a non-text component
*/
public static boolean isHTMLString(String s) {
if (s != null) {
if ((s.length() >= 6) && (s.charAt(0) == '<') && (s.charAt(5) == '>')) {
String tag = s.substring(1,5);
return tag.equalsIgnoreCase(propertyKey);
}
}
return false;
}
/**
* Stash the HTML render for the given text into the client
* properties of the given JComponent. If the given text is
* <em>NOT HTML</em> the property will be cleared of any
* renderer.
* <p>
* This method is useful for ComponentUI implementations
* that are static (i.e. shared) and get their state
* entirely from the JComponent.
*
* @param c a component
* @param text a text
*/
public static void updateRenderer(JComponent c, String text) {
View value = null;
View oldValue = (View)c.getClientProperty(BasicHTML.propertyKey);
Boolean htmlDisabled = (Boolean) c.getClientProperty(htmlDisable);
if (htmlDisabled != Boolean.TRUE && BasicHTML.isHTMLString(text)) {
value = BasicHTML.createHTMLView(c, text);
}
if (value != oldValue && oldValue != null) {
for (int i = 0; i < oldValue.getViewCount(); i++) {
oldValue.getView(i).setParent(null);
}
}
c.putClientProperty(BasicHTML.propertyKey, value);
String currentAccessibleNameProperty =
(String) c.getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
String previousParsedText = null;
if (currentAccessibleNameProperty != null && oldValue != null) {
try {
previousParsedText =
(oldValue.getDocument().getText(0, oldValue.getDocument().getLength())).strip();
} catch (BadLocationException e) {
}
}
// AccessibleContext.ACCESSIBLE_NAME_PROPERTY should be set from here only if,
// 1. If AccessibleContext.ACCESSIBLE_NAME_PROPERTY was NOT set before
// i.e. currentAccessibleNameProperty is null. and,
// 2. If AccessibleContext.ACCESSIBLE_NAME_PROPERTY was previously set from this method
// using the value.getDocument().getText().
if (currentAccessibleNameProperty == null ||
currentAccessibleNameProperty.equals(previousParsedText)) {
String parsedText = null;
if (value != null) {
try {
parsedText =
(value.getDocument().getText(0, value.getDocument().getLength())).strip();
} catch (BadLocationException e) {
}
}
c.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, parsedText);
}
}
/**
* If this client property of a JComponent is set to Boolean.TRUE
* the component's 'text' property is never treated as HTML.
*/
private static final String htmlDisable = "html.disable";
/**
* Key to use for the html renderer when stored as a
* client property of a JComponent.
*/
public static final String propertyKey = "html";
/**
* Key stored as a client property to indicate the base that relative
* references are resolved against. For example, lets say you keep
* your images in the directory resources relative to the code path,
* you would use the following the set the base:
* <pre>
* jComponent.putClientProperty(documentBaseKey,
* xxx.class.getResource("resources/"));
* </pre>
*/
public static final String documentBaseKey = "html.base";
static BasicEditorKit getFactory() {
if (basicHTMLFactory == null) {
basicHTMLViewFactory = new BasicHTMLViewFactory();
basicHTMLFactory = new BasicEditorKit();
}
return basicHTMLFactory;
}
/**
* The source of the html renderers
*/
private static BasicEditorKit basicHTMLFactory;
/**
* Creates the Views that visually represent the model.
*/
private static ViewFactory basicHTMLViewFactory;
/**
* Overrides to the default stylesheet. Should consider
* just creating a completely fresh stylesheet.
*/
private static final String styleChanges =
"p { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }" +
"body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }";
/**
* The views produced for the ComponentUI implementations aren't
* going to be edited and don't need full html support. This kit
* alters the HTMLEditorKit to try and trim things down a bit.
* It does the following:
* <ul>
* <li>It doesn't produce Views for things like comments,
* head, title, unknown tags, etc.
* <li>It installs a different set of css settings from the default
* provided by HTMLEditorKit.
* </ul>
*/
@SuppressWarnings("serial") // JDK-implementation class
static class BasicEditorKit extends HTMLEditorKit {
/** Shared base style for all documents created by us use. */
private static StyleSheet defaultStyles;
/**
* Overriden to return our own slimmed down style sheet.
*/
public StyleSheet getStyleSheet() {
if (defaultStyles == null) {
defaultStyles = new StyleSheet();
StringReader r = new StringReader(styleChanges);
try {
defaultStyles.loadRules(r, null);
} catch (Throwable e) {
// don't want to die in static initialization...
// just display things wrong.
}
r.close();
defaultStyles.addStyleSheet(super.getStyleSheet());
}
return defaultStyles;
}
/**
* Sets the async policy to flush everything in one chunk, and
* to not display unknown tags.
*/
public Document createDefaultDocument(Font defaultFont,
Color foreground) {
StyleSheet styles = getStyleSheet();
StyleSheet ss = new StyleSheet();
ss.addStyleSheet(styles);
BasicDocument doc = new BasicDocument(ss, defaultFont, foreground);
doc.setAsynchronousLoadPriority(Integer.MAX_VALUE);
doc.setPreservesUnknownTags(false);
return doc;
}
/**
* Returns the ViewFactory that is used to make sure the Views don't
* load in the background.
*/
public ViewFactory getViewFactory() {
return basicHTMLViewFactory;
}
}
/**
* BasicHTMLViewFactory extends HTMLFactory to force images to be loaded
* synchronously.
*/
static class BasicHTMLViewFactory extends HTMLEditorKit.HTMLFactory {
public View create(Element elem) {
View view = super.create(elem);
if (view instanceof ImageView) {
((ImageView)view).setLoadsSynchronously(true);
}
return view;
}
}
/**
* The subclass of HTMLDocument that is used as the model. getForeground
* is overridden to return the foreground property from the Component this
* was created for.
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
static class BasicDocument extends HTMLDocument {
/** The host, that is where we are rendering. */
// private JComponent host;
BasicDocument(StyleSheet s, Font defaultFont, Color foreground) {
super(s);
setPreservesUnknownTags(false);
setFontAndColor(defaultFont, foreground);
}
/**
* Sets the default font and default color. These are set by
* adding a rule for the body that specifies the font and color.
* This allows the html to override these should it wish to have
* a custom font or color.
*/
private void setFontAndColor(Font font, Color fg) {
getStyleSheet().addRule(sun.swing.SwingUtilities2.
displayPropertiesToCSS(font,fg));
}
}
/**
* Root text view that acts as an HTML renderer.
*/
static class Renderer extends View {
Renderer(JComponent c, ViewFactory f, View v) {
super(null);
host = c;
factory = f;
view = v;
view.setParent(this);
// initially layout to the preferred size
setSize(view.getPreferredSpan(X_AXIS), view.getPreferredSpan(Y_AXIS));
}
/**
* Fetches the attributes to use when rendering. At the root
* level there are no attributes. If an attribute is resolved
* up the view hierarchy this is the end of the line.
*/
public AttributeSet getAttributes() {
return null;
}
/**
* Determines the preferred span for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getPreferredSpan(int axis) {
if (axis == X_AXIS) {
// width currently laid out to
return width;
}
return view.getPreferredSpan(axis);
}
/**
* Determines the minimum span for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getMinimumSpan(int axis) {
return view.getMinimumSpan(axis);
}
/**
* Determines the maximum span for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getMaximumSpan(int axis) {
return Integer.MAX_VALUE;
}
/**
* Specifies that a preference has changed.
* Child views can call this on the parent to indicate that
* the preference has changed. The root view routes this to
* invalidate on the hosting component.
* <p>
* This can be called on a different thread from the
* event dispatching thread and is basically unsafe to
* propagate into the component. To make this safe,
* the operation is transferred over to the event dispatching
* thread for completion. It is a design goal that all view
* methods be safe to call without concern for concurrency,
* and this behavior helps make that true.
*
* @param child the child view
* @param width true if the width preference has changed
* @param height true if the height preference has changed
*/
public void preferenceChanged(View child, boolean width, boolean height) {
host.revalidate();
host.repaint();
}
/**
* Determines the desired alignment for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the desired alignment, where 0.0 indicates the origin
* and 1.0 the full span away from the origin
*/
public float getAlignment(int axis) {
return view.getAlignment(axis);
}
/**
* Renders the view.
*
* @param g the graphics context
* @param allocation the region to render into
*/
public void paint(Graphics g, Shape allocation) {
Rectangle alloc = allocation.getBounds();
view.setSize(alloc.width, alloc.height);
view.paint(g, allocation);
}
/**
* Sets the view parent.
*
* @param parent the parent view
*/
public void setParent(View parent) {
throw new Error("Can't set parent on root view");
}
/**
* Returns the number of views in this view. Since
* this view simply wraps the root of the view hierarchy
* it has exactly one child.
*
* @return the number of views
* @see #getView
*/
public int getViewCount() {
return 1;
}
/**
* Gets the n-th view in this container.
*
* @param n the number of the view to get
* @return the view
*/
public View getView(int n) {
return view;
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @return the bounding box of the given position
*/
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
return view.modelToView(pos, a, b);
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param p0 the position to convert >= 0
* @param b0 the bias toward the previous character or the
* next character represented by p0, in case the
* position is a boundary of two views.
* @param p1 the position to convert >= 0
* @param b1 the bias toward the previous character or the
* next character represented by p1, in case the
* position is a boundary of two views.
* @param a the allocated region to render into
* @return the bounding box of the given position is returned
* @exception BadLocationException if the given position does
* not represent a valid location in the associated document
* @exception IllegalArgumentException for an invalid bias argument
* @see View#viewToModel
*/
public Shape modelToView(int p0, Position.Bias b0, int p1,
Position.Bias b1, Shape a) throws BadLocationException {
return view.modelToView(p0, b0, p1, b1, a);
}
/**
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param x x coordinate of the view location to convert
* @param y y coordinate of the view location to convert
* @param a the allocated region to render into
* @return the location within the model that best represents the
* given point in the view
*/
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
return view.viewToModel(x, y, a, bias);
}
/**
* Returns the document model underlying the view.
*
* @return the model
*/
public Document getDocument() {
return view.getDocument();
}
/**
* Returns the starting offset into the model for this view.
*
* @return the starting offset
*/
public int getStartOffset() {
return view.getStartOffset();
}
/**
* Returns the ending offset into the model for this view.
*
* @return the ending offset
*/
public int getEndOffset() {
return view.getEndOffset();
}
/**
* Gets the element that this view is mapped to.
*
* @return the view
*/
public Element getElement() {
return view.getElement();
}
/**
* Sets the view size.
*
* @param width the width
* @param height the height
*/
public void setSize(float width, float height) {
this.width = (int) width;
view.setSize(width, height);
}
/**
* Fetches the container hosting the view. This is useful for
* things like scheduling a repaint, finding out the host
* components font, etc. The default implementation
* of this is to forward the query to the parent view.
*
* @return the container
*/
public Container getContainer() {
return host;
}
/**
* Fetches the factory to be used for building the
* various view fragments that make up the view that
* represents the model. This is what determines
* how the model will be represented. This is implemented
* to fetch the factory provided by the associated
* EditorKit.
*
* @return the factory
*/
public ViewFactory getViewFactory() {
return factory;
}
private int width;
private View view;
private ViewFactory factory;
private JComponent host;
}
}
|
3e1109197d09ae01ec7ba3a4b51af0fc7603559a | 1,280 | java | Java | vertx/src/test/java/eu/internetofus/common/vertx/basic/PersistenceVerticle.java | InternetOfUs/common-models-java | b6312e66aed917fd7efc30bcfd1f1c6526fe8d89 | [
"Apache-2.0"
] | null | null | null | vertx/src/test/java/eu/internetofus/common/vertx/basic/PersistenceVerticle.java | InternetOfUs/common-models-java | b6312e66aed917fd7efc30bcfd1f1c6526fe8d89 | [
"Apache-2.0"
] | null | null | null | vertx/src/test/java/eu/internetofus/common/vertx/basic/PersistenceVerticle.java | InternetOfUs/common-models-java | b6312e66aed917fd7efc30bcfd1f1c6526fe8d89 | [
"Apache-2.0"
] | null | null | null | 30.47619 | 80 | 0.646094 | 7,182 | /*
* -----------------------------------------------------------------------------
*
* Copyright 2019 - 2022 UDT-IA, IIIA-CSIC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* -----------------------------------------------------------------------------
*/
package eu.internetofus.common.vertx.basic;
import eu.internetofus.common.vertx.AbstractPersistenceVerticle;
import io.vertx.core.Future;
/**
* The verticle with the persistence services.
*
* @author UDT-IA, IIIA-CSIC
*/
public class PersistenceVerticle extends AbstractPersistenceVerticle {
/**
* {@inheritDoc}
*/
@Override
protected Future<Void> registerRepositoriesFor(final String schemaVersion) {
return UsersRepository.register(this.vertx, this.pool, schemaVersion);
}
}
|
3e1109d031887cccc8891eb9f13c097091f86177 | 4,585 | java | Java | RoadSurfersMobile/app/src/main/java/com/roadsurfers/roadsurfers/MainActivity.java | raulamit/RoadTripPlanner | e0d2bc4da7424ea5d91abeabfefe51b92adee5b4 | [
"MIT"
] | null | null | null | RoadSurfersMobile/app/src/main/java/com/roadsurfers/roadsurfers/MainActivity.java | raulamit/RoadTripPlanner | e0d2bc4da7424ea5d91abeabfefe51b92adee5b4 | [
"MIT"
] | null | null | null | RoadSurfersMobile/app/src/main/java/com/roadsurfers/roadsurfers/MainActivity.java | raulamit/RoadTripPlanner | e0d2bc4da7424ea5d91abeabfefe51b92adee5b4 | [
"MIT"
] | null | null | null | 35 | 259 | 0.681352 | 7,183 | package com.roadsurfers.roadsurfers;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.roadsurfers.roadsurfers.utility.MyLocationManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
private GoogleApiClient googleApiClient;
public double lat;
public double lon;
private MyLocationManager myLocationManager;
private Integer distanceMiles;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
setContentView(R.layout.activity_main);
}
myLocationManager = new MyLocationManager(this);
}
public void onClick(View view) {
String jsonContent="";
EditText textValue= (EditText) findViewById(R.id.distRadius);
distanceMiles= Integer.getInteger(textValue.getText().toString());
lat= 42.3379;
lon= -71.0976;
Intent intent = new Intent(this, SuggestionActivity.class);
intent.putExtra("lon",lon);
intent.putExtra("lat", lat);
intent.putExtra("distance",distanceMiles);
startActivity(intent);
// new Activity
// jsonContent
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good!
} else {
Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
protected void onStop() {
if (googleApiClient!=null)
googleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
lat = lastLocation.getLatitude();
lon = lastLocation.getLongitude();
}
}
}
@Override
public void onConnectionSuspended(int i) {
System.out.println("location off");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
System.out.println("connection failed");
}
}
|
3e110a1ed3df6f5e9e76d64229cad5404576c9c3 | 427 | java | Java | src/main/java/com/chengxiaoxiao/MainApplication.java | iquanzhan/springboot-demo | 0c46fcd7729701e0d17962e5b5eeb137d0445842 | [
"MIT"
] | null | null | null | src/main/java/com/chengxiaoxiao/MainApplication.java | iquanzhan/springboot-demo | 0c46fcd7729701e0d17962e5b5eeb137d0445842 | [
"MIT"
] | null | null | null | src/main/java/com/chengxiaoxiao/MainApplication.java | iquanzhan/springboot-demo | 0c46fcd7729701e0d17962e5b5eeb137d0445842 | [
"MIT"
] | null | null | null | 23.722222 | 68 | 0.737705 | 7,184 | package com.chengxiaoxiao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @ClassName: MainApplication
* @description:
* @author: Cheng XiaoXiao (🍊 ^_^ ^_^)
* @Date: 2018-12-05
*/
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class);
}
}
|
3e110a5544b6991a7a65ecb1ce9d47b93a237d2f | 2,617 | java | Java | app/src/main/java/iop/gimbalbeacon/Activity/SettingsActivity.java | brunofmf/Smart-Clothing | b9a8be102e6949ff25a86c5a43a0fce8f9b65bb2 | [
"Apache-2.0"
] | 1 | 2020-07-28T16:28:21.000Z | 2020-07-28T16:28:21.000Z | app/src/main/java/iop/gimbalbeacon/Activity/SettingsActivity.java | brunofmf/Smart-Clothing | b9a8be102e6949ff25a86c5a43a0fce8f9b65bb2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/iop/gimbalbeacon/Activity/SettingsActivity.java | brunofmf/Smart-Clothing | b9a8be102e6949ff25a86c5a43a0fce8f9b65bb2 | [
"Apache-2.0"
] | 1 | 2020-07-28T16:28:23.000Z | 2020-07-28T16:28:23.000Z | 34.434211 | 103 | 0.721055 | 7,185 | package iop.gimbalbeacon.Activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.gimbal.android.Gimbal;
import com.gimbal.android.PlaceManager;
import iop.gimbalbeacon.Controller.GimbalIntegration;
import iop.gimbalbeacon.Controller.LocationPermissions;
import iop.gimbalbeacon.R;
public class SettingsActivity extends Activity {
private CheckBox gimbalMonitoringCheckBox;
LocationPermissions locationPermissions;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 100;
NumberPicker np;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
locationPermissions = new LocationPermissions(this);
gimbalMonitoringCheckBox = (CheckBox) findViewById(R.id.gimbal_monitoring_checkbox);
gimbalMonitoringCheckBox.setChecked(PlaceManager.getInstance().isMonitoring());
np = findViewById(R.id.numberPicker);
np.setMinValue(10);
np.setMaxValue(120);
np.setValue(GimbalIntegration.instance().sightingTimeFrame/1000);
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
GimbalIntegration.instance().sightingTimeFrame = numberPicker.getValue()*1000;
np.setValue(numberPicker.getValue());
}
});
}
public void onGimbalMonitoringClicked(View view) {
gimbalMonitoringCheckBox.setChecked(!gimbalMonitoringCheckBox.isChecked());
if (gimbalMonitoringCheckBox.isChecked()) {
locationPermissions = new LocationPermissions(this);
locationPermissions.checkAndRequestPermission();
}
else {
GimbalIntegration.instance().onTerminate();
}
}
public void onResetAppInstance(View view) {
Gimbal.resetApplicationInstanceIdentifier();
Toast.makeText(this, "App Instance ID reset successful", Toast.LENGTH_LONG).show();
}
@Override
public void onResume() {
super.onResume();
gimbalMonitoringCheckBox.setChecked(PlaceManager.getInstance().isMonitoring());
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
locationPermissions.onRequestPermissionResult(requestCode, permissions, grantResults);
}
}
|
3e110a60834a98232bbb3f3cc230cffd65aa546b | 696 | java | Java | app/src/main/java/com/prometrx/questionscresolver/Fragments/Model/ExploreModel.java | MetrXJavA/QuestionsCreSolver | 6e10fad4714994aa10be03118700fc8483e6ffef | [
"MIT"
] | null | null | null | app/src/main/java/com/prometrx/questionscresolver/Fragments/Model/ExploreModel.java | MetrXJavA/QuestionsCreSolver | 6e10fad4714994aa10be03118700fc8483e6ffef | [
"MIT"
] | null | null | null | app/src/main/java/com/prometrx/questionscresolver/Fragments/Model/ExploreModel.java | MetrXJavA/QuestionsCreSolver | 6e10fad4714994aa10be03118700fc8483e6ffef | [
"MIT"
] | null | null | null | 18.810811 | 67 | 0.597701 | 7,186 | package com.prometrx.questionscresolver.Fragments.Model;
public class ExploreModel {
private String qCount, qTitle, qId;
public ExploreModel(String qCount, String qTitle, String qId) {
this.qCount = qCount;
this.qTitle = qTitle;
this.qId = qId;
}
public String getqCount() {
return qCount;
}
public void setqCount(String qCount) {
this.qCount = qCount;
}
public String getqTitle() {
return qTitle;
}
public void setqTitle(String qTitle) {
this.qTitle = qTitle;
}
public String getqId() {
return qId;
}
public void setqId(String qId) {
this.qId = qId;
}
}
|
3e110aa18d97d6dc3c2baac0d2b5cb010835e460 | 2,679 | java | Java | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/chart/ApplicationMemoryChartGroup.java | caijianfang/pinpoint | b6873821d1fd66c15095a6e6ba2a697a47b4c422 | [
"Apache-2.0"
] | 2 | 2018-01-31T14:34:35.000Z | 2020-01-10T02:19:56.000Z | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/chart/ApplicationMemoryChartGroup.java | caijianfang/pinpoint | b6873821d1fd66c15095a6e6ba2a697a47b4c422 | [
"Apache-2.0"
] | null | null | null | web/src/main/java/com/navercorp/pinpoint/web/vo/stat/chart/ApplicationMemoryChartGroup.java | caijianfang/pinpoint | b6873821d1fd66c15095a6e6ba2a697a47b4c422 | [
"Apache-2.0"
] | 3 | 2018-04-22T14:38:04.000Z | 2018-12-18T11:57:58.000Z | 45.40678 | 277 | 0.77193 | 7,187 | /*
* Copyright 2017 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.vo.stat.chart;
import com.navercorp.pinpoint.web.util.TimeWindow;
import com.navercorp.pinpoint.web.vo.stat.AggreJoinMemoryBo;
import com.navercorp.pinpoint.web.vo.stat.chart.MemoryPoint.UncollectedMemoryPointCreater;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author minwoo.jung
*/
public class ApplicationMemoryChartGroup implements ApplicationStatChartGroup {
public static final UncollectedMemoryPointCreater UNCOLLECTED_MEMORY_POINT = new UncollectedMemoryPointCreater();
private final Map<ChartType, Chart> memoryChartMap;
public enum MemoryChartType implements ChartType {
MEMORY_HEAP,
MEMORY_NON_HEAP
}
public ApplicationMemoryChartGroup(TimeWindow timeWindow, List<AggreJoinMemoryBo> aggreJoinMemoryBoList) {
memoryChartMap = new HashMap<>();
List<Point> heapList = new ArrayList<>(aggreJoinMemoryBoList.size());
List<Point> nonHeapList = new ArrayList<>(aggreJoinMemoryBoList.size());
for (AggreJoinMemoryBo aggreJoinMemoryBo : aggreJoinMemoryBoList) {
heapList.add(new MemoryPoint(aggreJoinMemoryBo.getTimestamp(), aggreJoinMemoryBo.getMinHeapUsed(), aggreJoinMemoryBo.getMinHeapAgentId(), aggreJoinMemoryBo.getMaxHeapUsed(), aggreJoinMemoryBo.getMaxHeapAgentId(), aggreJoinMemoryBo.getHeapUsed()));
nonHeapList.add(new MemoryPoint(aggreJoinMemoryBo.getTimestamp(), aggreJoinMemoryBo.getMinNonHeapUsed(), aggreJoinMemoryBo.getMinNonHeapAgentId(), aggreJoinMemoryBo.getMaxNonHeapUsed(), aggreJoinMemoryBo.getMaxNonHeapAgentId(), aggreJoinMemoryBo.getNonHeapUsed()));
}
memoryChartMap.put(MemoryChartType.MEMORY_HEAP, new TimeSeriesChartBuilder(timeWindow, UNCOLLECTED_MEMORY_POINT).build(heapList));
memoryChartMap.put(MemoryChartType.MEMORY_NON_HEAP, new TimeSeriesChartBuilder(timeWindow, UNCOLLECTED_MEMORY_POINT).build(nonHeapList));
}
@Override
public Map<ChartType, Chart> getCharts() {
return this.memoryChartMap;
}
}
|
3e110adb6107d2e617e9f3f48fb51a5192402c37 | 12,399 | java | Java | app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/coordinatorlayout/R.java | MohamedWessam/no-internet-layout | 7445994ef72873043b3a73ba6e817859801c6a52 | [
"Apache-2.0"
] | 121 | 2019-12-19T19:49:16.000Z | 2022-01-03T17:39:47.000Z | app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/coordinatorlayout/R.java | MohamedWessam/no-internet-layout | 7445994ef72873043b3a73ba6e817859801c6a52 | [
"Apache-2.0"
] | 7 | 2019-12-23T12:13:42.000Z | 2021-05-19T11:13:57.000Z | app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/coordinatorlayout/R.java | MohamedWessam/no-internet-layout | 7445994ef72873043b3a73ba6e817859801c6a52 | [
"Apache-2.0"
] | 19 | 2019-12-19T11:01:07.000Z | 2022-03-14T17:17:35.000Z | 58.485849 | 185 | 0.74014 | 7,188 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.coordinatorlayout;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f020027;
public static final int coordinatorLayoutStyle = 0x7f020065;
public static final int font = 0x7f020083;
public static final int fontProviderAuthority = 0x7f020085;
public static final int fontProviderCerts = 0x7f020086;
public static final int fontProviderFetchStrategy = 0x7f020087;
public static final int fontProviderFetchTimeout = 0x7f020088;
public static final int fontProviderPackage = 0x7f020089;
public static final int fontProviderQuery = 0x7f02008a;
public static final int fontStyle = 0x7f02008b;
public static final int fontVariationSettings = 0x7f02008c;
public static final int fontWeight = 0x7f02008d;
public static final int keylines = 0x7f02009d;
public static final int layout_anchor = 0x7f0200a0;
public static final int layout_anchorGravity = 0x7f0200a1;
public static final int layout_behavior = 0x7f0200a2;
public static final int layout_dodgeInsetEdges = 0x7f0200cc;
public static final int layout_insetEdge = 0x7f0200d5;
public static final int layout_keyline = 0x7f0200d6;
public static final int statusBarBackground = 0x7f020117;
public static final int ttcIndex = 0x7f02014b;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f040042;
public static final int notification_icon_bg_color = 0x7f040043;
public static final int ripple_material_light = 0x7f04004e;
public static final int secondary_text_default_material_light = 0x7f040050;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f05004e;
public static final int compat_button_inset_vertical_material = 0x7f05004f;
public static final int compat_button_padding_horizontal_material = 0x7f050050;
public static final int compat_button_padding_vertical_material = 0x7f050051;
public static final int compat_control_corner_material = 0x7f050052;
public static final int compat_notification_large_icon_max_height = 0x7f050053;
public static final int compat_notification_large_icon_max_width = 0x7f050054;
public static final int notification_action_icon_size = 0x7f05005e;
public static final int notification_action_text_size = 0x7f05005f;
public static final int notification_big_circle_margin = 0x7f050060;
public static final int notification_content_margin_start = 0x7f050061;
public static final int notification_large_icon_height = 0x7f050062;
public static final int notification_large_icon_width = 0x7f050063;
public static final int notification_main_column_padding_top = 0x7f050064;
public static final int notification_media_narrow_margin = 0x7f050065;
public static final int notification_right_icon_size = 0x7f050066;
public static final int notification_right_side_padding_top = 0x7f050067;
public static final int notification_small_icon_background_padding = 0x7f050068;
public static final int notification_small_icon_size_as_large = 0x7f050069;
public static final int notification_subtext_size = 0x7f05006a;
public static final int notification_top_pad = 0x7f05006b;
public static final int notification_top_pad_large_text = 0x7f05006c;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f060066;
public static final int notification_bg = 0x7f060067;
public static final int notification_bg_low = 0x7f060068;
public static final int notification_bg_low_normal = 0x7f060069;
public static final int notification_bg_low_pressed = 0x7f06006a;
public static final int notification_bg_normal = 0x7f06006b;
public static final int notification_bg_normal_pressed = 0x7f06006c;
public static final int notification_icon_background = 0x7f06006d;
public static final int notification_template_icon_bg = 0x7f06006e;
public static final int notification_template_icon_low_bg = 0x7f06006f;
public static final int notification_tile_bg = 0x7f060070;
public static final int notify_panel_notification_icon_bg = 0x7f060071;
}
public static final class id {
private id() {}
public static final int action_container = 0x7f08002f;
public static final int action_divider = 0x7f080031;
public static final int action_image = 0x7f080032;
public static final int action_text = 0x7f080038;
public static final int actions = 0x7f080039;
public static final int async = 0x7f08003f;
public static final int blocking = 0x7f080042;
public static final int bottom = 0x7f080043;
public static final int chronometer = 0x7f08004c;
public static final int end = 0x7f08005b;
public static final int forever = 0x7f080062;
public static final int icon = 0x7f080068;
public static final int icon_group = 0x7f080069;
public static final int info = 0x7f08006c;
public static final int italic = 0x7f08006e;
public static final int left = 0x7f08006f;
public static final int line1 = 0x7f080070;
public static final int line3 = 0x7f080071;
public static final int none = 0x7f08007c;
public static final int normal = 0x7f08007d;
public static final int notification_background = 0x7f08007e;
public static final int notification_main_column = 0x7f08007f;
public static final int notification_main_column_container = 0x7f080080;
public static final int right = 0x7f08008b;
public static final int right_icon = 0x7f08008c;
public static final int right_side = 0x7f08008d;
public static final int start = 0x7f0800aa;
public static final int tag_transition_group = 0x7f0800b4;
public static final int tag_unhandled_key_event_manager = 0x7f0800b5;
public static final int tag_unhandled_key_listeners = 0x7f0800b6;
public static final int text = 0x7f0800b7;
public static final int text2 = 0x7f0800b8;
public static final int time = 0x7f0800bb;
public static final int title = 0x7f0800bc;
public static final int top = 0x7f0800bf;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f090004;
}
public static final class layout {
private layout() {}
public static final int notification_action = 0x7f0b0020;
public static final int notification_action_tombstone = 0x7f0b0021;
public static final int notification_template_custom_big = 0x7f0b0028;
public static final int notification_template_icon_group = 0x7f0b0029;
public static final int notification_template_part_chronometer = 0x7f0b002d;
public static final int notification_template_part_time = 0x7f0b002e;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0d0021;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0e00ed;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0e00ee;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0e00f0;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0e00f3;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0e00f5;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0e0161;
public static final int Widget_Compat_NotificationActionText = 0x7f0e0162;
public static final int Widget_Support_CoordinatorLayout = 0x7f0e0163;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f020027 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] CoordinatorLayout = { 0x7f02009d, 0x7f020117 };
public static final int CoordinatorLayout_keylines = 0;
public static final int CoordinatorLayout_statusBarBackground = 1;
public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f0200a0, 0x7f0200a1, 0x7f0200a2, 0x7f0200cc, 0x7f0200d5, 0x7f0200d6 };
public static final int CoordinatorLayout_Layout_android_layout_gravity = 0;
public static final int CoordinatorLayout_Layout_layout_anchor = 1;
public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2;
public static final int CoordinatorLayout_Layout_layout_behavior = 3;
public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4;
public static final int CoordinatorLayout_Layout_layout_insetEdge = 5;
public static final int CoordinatorLayout_Layout_layout_keyline = 6;
public static final int[] FontFamily = { 0x7f020085, 0x7f020086, 0x7f020087, 0x7f020088, 0x7f020089, 0x7f02008a };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f020083, 0x7f02008b, 0x7f02008c, 0x7f02008d, 0x7f02014b };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
|
3e110de257eccaec9d5d5ddf318aa05c4fd94fae | 3,132 | java | Java | core/Pipeline/src/pdf2xml/pdf2xml.java | acoli-repo/abi | 24480253f45c41c388de2095865ee1b3056abf62 | [
"Apache-2.0"
] | null | null | null | core/Pipeline/src/pdf2xml/pdf2xml.java | acoli-repo/abi | 24480253f45c41c388de2095865ee1b3056abf62 | [
"Apache-2.0"
] | null | null | null | core/Pipeline/src/pdf2xml/pdf2xml.java | acoli-repo/abi | 24480253f45c41c388de2095865ee1b3056abf62 | [
"Apache-2.0"
] | 5 | 2015-09-16T00:13:11.000Z | 2016-01-25T14:12:00.000Z | 26.1 | 82 | 0.582375 | 7,189 | /* **************************************************************
* Projekt : Text Analyse (java)
* --------------------------------------------------------------
* Autor(en) : Kathrin Donandt, Zhanhong Huang
* Beginn-Datum : 04.20.2016
* --------------------------------------------------------------
* copyright (c) 2016 Uni Frankfurt Informatik
* Alle Rechte vorbehalten.
* **************************************************************
*/
package pdf2xml;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import helper.listFiles;
import helper.readwriteFiles;
/**
*
* @author Kathrin Donandt, Zhanhong Huang
*
*/
public class pdf2xml {
/**
* Convertes pdf to xml using pdf2xml (https://sourceforge.net/projects/pdf2xml/)
*
* @param input_path
* : absolute path of pdf input file
* @param output_path
* : absolute path of xml output file
* @param locationProject
* : absolute path of this project (TextAnalse)
* @throws InterruptedException
*/
public void convertPdftoXML(String input_path, String output_path,
String locationProject) throws InterruptedException {
listFiles lf = new listFiles();
List<File> files = lf.listf(input_path);
for (File f : files) {
try {
String inputfile = f.getAbsolutePath();
String outputfile = output_path
+ f.getAbsolutePath().split("/pdf/")[1].split("pdf")[0]
+ "xml";
Runtime.getRuntime().exec(
locationProject
+ "src/pdf2xml/pdftoxml.linux64.exe.1.2_7"
+ " -noImage " + inputfile + " " + outputfile);
System.out.println("Conversion of "
+ inputfile.split("/pdf/")[1] + " into "
+ outputfile.split("/xml/")[1] + " done!");
} catch (IOException e) {
System.out.println("Exception happened :( ");
e.printStackTrace();
System.exit(-1);
}
}
}
/**
* Validates xml files using xmllint
*
* @param xmlDir: directory containing xml files
* @throws InterruptedException
*/
public void validateXML(String xmlDir) throws InterruptedException {
// validate XML
listFiles lf = new listFiles();
List<File> files = lf.listf(xmlDir);
for (File f : files) {
try {
String file = f.getAbsolutePath();
Process rec = Runtime.getRuntime().exec(
"xmllint --format --recover " + file);
List<String> lines = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(
rec.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
lines.add(line);
}
rec.waitFor();
System.err.println("ok!");
in.close();
readwriteFiles rwf = new readwriteFiles();
rwf.write(file, lines);
} catch (IOException e) {
System.out.println("Exception happened :( ");
e.printStackTrace();
System.exit(-1);
}
}
}
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
}
} |
3e110e323b2cbf1f30b78f795e3ee6a17d92056c | 1,562 | java | Java | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-yoo/src/main/java/com/lanking/cloud/domain/yoo/activity/imperialExamination/ImperialExaminationMessageTime.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 1 | 2019-01-20T06:19:53.000Z | 2019-01-20T06:19:53.000Z | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-yoo/src/main/java/com/lanking/cloud/domain/yoo/activity/imperialExamination/ImperialExaminationMessageTime.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | null | null | null | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-yoo/src/main/java/com/lanking/cloud/domain/yoo/activity/imperialExamination/ImperialExaminationMessageTime.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 2 | 2019-01-20T06:19:54.000Z | 2021-07-21T14:13:44.000Z | 18.458824 | 70 | 0.673678 | 7,190 | package com.lanking.cloud.domain.yoo.activity.imperialExamination;
import java.io.Serializable;
import java.util.Date;
import com.lanking.cloud.domain.base.message.api.MessageType;
/**
* 科举考试消息发送时间表.
*
* @author <a href="mailto:lyhxr@example.com">wanlong.che</a>
*
* @version 2017年4月7日
*/
public class ImperialExaminationMessageTime implements Serializable {
private static final long serialVersionUID = -6391040619871875287L;
/**
* 消息类型
*
* @see MessageType
*/
private MessageType messageType;
/**
* 消息模板代码
*/
private Integer messageTemplateCode;
/**
* 发送时间.
*/
private Date startTime;
/**
* 发送范围.
*
* <pre>
* 1: 未使用过APP的渠道初中教师
* 2: 未报名的渠道初中教师
* 3:所有渠道初中教师
* 4:已报名的渠道初中教师
* 5:所有初中用户
* 6:所有初中老师
* 7:所有初中学生
* 8:未提交作业的学生
* TODO 由实现者继续添加类型
* </pre>
*/
private Integer userScope = 1;
public MessageType getMessageType() {
return messageType;
}
public void setMessageType(MessageType messageType) {
this.messageType = messageType;
}
public Integer getMessageTemplateCode() {
return messageTemplateCode;
}
public void setMessageTemplateCode(Integer messageTemplateCode) {
this.messageTemplateCode = messageTemplateCode;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Integer getUserScope() {
return userScope;
}
public void setUserScope(Integer userScope) {
this.userScope = userScope;
}
}
|
3e11101443c7c2fa181eaa400a9862c179642bbd | 1,432 | java | Java | Assignment-III/Ques_6.java | laksh-2193/ISC_Assignments | 5845d3a0c08733b8a0afb7d54e2909de0be16603 | [
"BSD-3-Clause"
] | null | null | null | Assignment-III/Ques_6.java | laksh-2193/ISC_Assignments | 5845d3a0c08733b8a0afb7d54e2909de0be16603 | [
"BSD-3-Clause"
] | null | null | null | Assignment-III/Ques_6.java | laksh-2193/ISC_Assignments | 5845d3a0c08733b8a0afb7d54e2909de0be16603 | [
"BSD-3-Clause"
] | null | null | null | 30.468085 | 107 | 0.5 | 7,191 |
/**
* Program to find twin prime number
*/
import java.io.*;
public class Ques_6
{
public static boolean isPrime(int n)
{
// boolean value will return
boolean f = true;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
f = false;
break;
}
}
return f;
}
// main method begins
public static void main(String args[]) throws IOException
{
int number1, number2;
// InputStreamReader object
InputStreamReader in = new InputStreamReader(System.in);
// BufferedReader object
BufferedReader br = new BufferedReader(in);
System.out.print("Enter first number: ");
// First number
number1 = Integer.parseInt(br.readLine());
System.out.print("Enter second number: ");
// Second number
number2 = Integer.parseInt(br.readLine());
// Checking both the number is prime and the difference between two is 2
if (isPrime(number1) == true && isPrime(number2) == true && Math.abs(number2 - number1) == 2) {
System.out.println("Twin prime number");
} else {
System.out.println("Not twin prime numbers");
}
} // end method main
} // end clas |
3e1110730b842059c66def8fb0a4b31450a5aefc | 2,794 | java | Java | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/headers/CollectionHeader.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 2 | 2015-10-09T13:14:20.000Z | 2016-05-05T01:38:29.000Z | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/headers/CollectionHeader.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 9 | 2020-06-30T22:53:38.000Z | 2022-01-21T23:10:11.000Z | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/headers/CollectionHeader.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 1 | 2016-02-24T12:11:20.000Z | 2016-02-24T12:11:20.000Z | 31.393258 | 76 | 0.593057 | 7,192 | /**
* Copyright 2012 Universitat Pompeu Fabra.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.onexus.website.widget.tableviewer.headers;
import org.apache.wicket.Component;
import org.onexus.collection.api.Collection;
import org.onexus.collection.api.Field;
import org.onexus.website.api.utils.panels.HelpMark;
import org.onexus.website.widget.tableviewer.formaters.StringFormater;
public class CollectionHeader extends ElementHeader {
private Collection collection;
public CollectionHeader(Collection dataType) {
super(
dataType == null ? null : dataType,
dataType == null ? null : new StringHeader(null),
new StringFormater(30, false)
);
this.collection = dataType;
}
@Override
public Component getHeader(String componentId) {
if (collection.getProperty("HELP") != null) {
return new HelpMark(componentId, collection.getName(),
getFormatedLabel(), getHelpContent());
} else {
return super.getHeader(componentId);
}
}
@Override
public String getLabel() {
return (collection == null ? "" : collection.getTitle());
}
@Override
public String getTitle() {
return collection.getDescription();
}
private String getHelpContent() {
StringBuilder str = new StringBuilder();
str.append("<p>");
str.append(collection.getProperty("HELP"));
str.append("</p>");
str.append("<ul>");
for (Field field : collection.getFields()) {
if (field.getProperty("HELP") != null) {
str.append("<li>");
str.append("<strong>").append(field.getLabel())
.append(":</strong> ");
str.append(field.getProperty("HELP"));
if (field.getProperty("HELP-LINK") != null) {
str.append(" <a href=\"")
.append(field.getProperty("HELP-LINK"))
.append("\" target=\"_tab\">more...</a>");
}
str.append("</li>");
}
}
str.append("</ul>");
return str.toString();
}
}
|
3e111091854c6f0df4e159eec2047b7a13017124 | 11,242 | java | Java | src/test/java/eu/fasten/vulnerabilityproducer/mappers/PurlMapperTest.java | fasten-project/vulnerability-producer | f19766d3d1857a5164cbee5a4152f9ff20a89402 | [
"Apache-2.0"
] | 9 | 2020-10-26T10:48:22.000Z | 2022-02-16T22:40:43.000Z | src/test/java/eu/fasten/vulnerabilityproducer/mappers/PurlMapperTest.java | fasten-project/vulnerability-producer | f19766d3d1857a5164cbee5a4152f9ff20a89402 | [
"Apache-2.0"
] | 82 | 2020-09-22T08:44:05.000Z | 2022-03-30T12:36:45.000Z | src/test/java/eu/fasten/vulnerabilityproducer/mappers/PurlMapperTest.java | fasten-project/vulnerability-producer | f19766d3d1857a5164cbee5a4152f9ff20a89402 | [
"Apache-2.0"
] | 3 | 2020-10-07T14:18:19.000Z | 2022-02-10T00:28:26.000Z | 41.330882 | 121 | 0.662071 | 7,193 | /*
* 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 eu.fasten.vulnerabilityproducer.mappers;
import eu.fasten.vulnerabilityproducer.utils.*;
import eu.fasten.vulnerabilityproducer.utils.connections.*;
import eu.fasten.vulnerabilityproducer.utils.mappers.PurlMapper;
import eu.fasten.vulnerabilityproducer.utils.mappers.VersionRanger;
import org.junit.jupiter.api.*;
import org.mockito.Mockito;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
public class PurlMapperTest {
VersionRanger vrMock = Mockito.mock(VersionRanger.class);
PatchFinder pfMock = Mockito.mock(PatchFinder.class);
JavaHttpClient client = Mockito.mock(JavaHttpClient.class);
PurlMapper purlMapper;
@BeforeEach
public void init() {
var listUrl = "https://salsa.debian.org/security-tracker-team/security-tracker/-/raw/master/data/CPE/list";
var aliasesUrl = "https://salsa.debian.org/security-tracker-team/security-tracker/-/raw/master/data/CPE/aliases";
var cpeList = "" +
"a2ps;cpe:/a:gnu:a2ps\n" +
"abc2ps;cpe:/a:abc2ps:abc2ps\n" +
"asterisk;cpe:/a:digium:asterisk\n";
var aliasesList = "" +
"#\n" +
"# Comments\n" +
"#\n" +
"cpe:/a:asterisk:asterisk\n" +
"cpe:/a:asterisk:open_source\n" +
"cpe:/a:asterisk:p_b_x\n" +
"cpe:/a:digium:asterisk\n" +
"cpe:/a:asterisk:opensource\n" +
"\n" +
"# End comment\n";
when(client.sendGet(listUrl)).thenReturn(cpeList);
when(client.sendGet(aliasesUrl)).thenReturn(aliasesList);
purlMapper = new PurlMapper(vrMock, pfMock, "./src/test/resources/purl_maps/", "both", client);
}
@Test
public void getBasePurlTest() {
Vulnerability v = new Vulnerability();
v.addPurl("pkg:pypi/django@1.9");
v.addPurl("pkg:pypi/django@1.9.1");
v.addPurl("pkg:pypi/django@1.9.2");
assertEquals("pkg:pypi/django", purlMapper.getPurlBase(v));
}
@Test
public void creationCPE2PURLMap() {
assertTrue(purlMapper.cpe2purl.getMappings().containsKey("cpe:2.3:a:google:guava"));
assertEquals("pkg:maven/org.google.guava/guava", purlMapper.cpe2purl.getMostVoted("cpe:2.3:a:google:guava"));
}
@Test
public void importDebianCPE() {
assertTrue(purlMapper.cpe2purl.getMappings().containsKey("cpe:2.3:a:gnu:a2ps"));
assertEquals("pkg:deb/debian/a2ps", purlMapper.cpe2purl.getMostVoted("cpe:2.3:a:gnu:a2ps"));
assertTrue(purlMapper.cpe2purl.getMappings().containsKey("cpe:2.3:a:asterisk:opensource"));
assertEquals("pkg:deb/debian/asterisk", purlMapper.cpe2purl.getMostVoted("cpe:2.3:a:asterisk:opensource"));
}
// repo2purl
@Test
public void inferPurlPyPIMap() {
purlMapper.repo2purl.insertVote("https://github.com/python/django", "pkg:pypi/django");
var versions = new ArrayList<String>(); versions.add("pkg:pypi/django@1.9");
var v = new Vulnerability();
v.addPatchLink("https//github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
v.addPatch(new Patch("oof.py", null, null, null, "2018-05-30"));
when(vrMock.getPurlsBeforeDate(Mockito.anyString(), Mockito.any())).thenReturn(versions);
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/python/django");
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:pypi/django@1.9"));
}
@Test
public void inferPurlMavenMap() {
purlMapper.repo2purl.insertVote("https://github.com/apache/hive", "pkg:mvn/org.apache/hive");
var versions = new ArrayList<String>(); versions.add("pkg:maven/org.apache/hive@0.1");
var v = new Vulnerability();
v.addPatchLink("https//github.com/apache/hive/commit/5326bi6b5u53b1u5ob1b5i265");
v.addPatch(new Patch("foo.java", null, null, null, "2018-05-30"));
when(vrMock.getPurlsBeforeDate(Mockito.anyString(), Mockito.any())).thenReturn(versions);
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/apache/hive");
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:maven/org.apache/hive@0.1"));
}
@Test
public void storeRepo2PurlRepoInfo() {
var v = new Vulnerability();
v.addPurl("pkg:pypi/django@1.9");
v.addPatchLink("https://github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/python/django");
purlMapper.inferPurls(v);
assertEquals("pkg:pypi/django", purlMapper.repo2purl.getMostVoted("https://github.com/python/django"));
}
// cpe2purl
@Test
public void inferPurlCpe2Purl() {
purlMapper.cpe2purl.insertVote("cpe:2.3:a:apache:hive", "pkg:maven/org.apache.hive/hive");
var v = new Vulnerability("CVE-TEST");
v.setBaseCpe("cpe:2.3:a:apache:hive");
var cpe_versions = new HashMap<String, List<String>>();
cpe_versions.put("cpe:2.3:a:apache:hive", Arrays.asList("1.0"));
when(vrMock.getCPEVersions(v.getId())).thenReturn(cpe_versions);
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:maven/org.apache.hive/hive@1.0"));
}
@Test
public void inferPurlStoringCpe2Purl() {
var v = new Vulnerability("CVE-TEST-1");
v.addPurl("pkg:pypi/foo@1.0");
v.setBaseCpe("cpe:2.3:a:foo:foo");
purlMapper.inferPurls(v);
assertTrue(purlMapper.cpe2purl.getMappings().containsKey("cpe:2.3:a:foo:foo"));
assertEquals("pkg:pypi/foo", purlMapper.cpe2purl.getMostVoted("cpe:2.3:a:foo:foo"));
}
@Test
public void inferPurlStoringBoth() {
var v = new Vulnerability("CVE-TEST-1");
v.addPurl("pkg:pypi/foo@1.0");
v.setBaseCpe("cpe:2.3:a:foo:foo");
v.addPatchLink("https://github.com/foo/foo/commit/5326bi6b5u53b1u5ob1b5i265");
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/foo/foo");
purlMapper.inferPurls(v);
assertTrue(purlMapper.cpe2purl.getMappings().containsKey("cpe:2.3:a:foo:foo"));
assertEquals("pkg:pypi/foo", purlMapper.cpe2purl.getMostVoted("cpe:2.3:a:foo:foo"));
assertTrue(purlMapper.repo2purl.getMappings().containsKey("https://github.com/foo/foo"));
assertEquals("pkg:pypi/foo", purlMapper.repo2purl.getMostVoted("https://github.com/foo/foo"));
}
@Test
public void testStrategyNone() {
purlMapper.strategy = "none";
var v = new Vulnerability("TEST-1");
v.setBaseCpe("cpe:2.3:a:google:guava");
v.addPatchLink("https//github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
v.setPublishedDate("2018-05-30");
// inject repo2purl information
purlMapper.pypiMap.put("https://github.com/python/django", "pkg:pypi/django");
var versions = new ArrayList<String>(); versions.add("pkg:pypi/django@1.9");
when(vrMock.getPurlsBeforeDate(Mockito.anyString(), Mockito.any())).thenReturn(versions);
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/python/django");
// inject cpe2purl information
purlMapper.cpe2purl.insertVote("cpe:2.3:a:google:guava", "pkg:maven/org.google/guava");
purlMapper.inferPurls(v);
assertEquals(0, v.getPurls().size());
}
@Test
public void testStrategyRepo2Purl() {
purlMapper.strategy = "repo2purl";
var v = new Vulnerability("TEST-1");
v.addPatchLink("https//github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
v.setPublishedDate("2018-05-30");
// inject repo2purl information
purlMapper.repo2purl.insertVote("https://github.com/python/django", "pkg:pypi/django");
var versions = new ArrayList<String>(); versions.add("pkg:pypi/django@1.9");
when(vrMock.getPurlsBeforeDate(Mockito.anyString(), Mockito.any())).thenReturn(versions);
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/python/django");
// inject cpe2purl information
purlMapper.cpe2purl.insertVote("cpe:2.3:a:google:guava", "pkg:maven/org.google/guava");
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:pypi/django@1.9"));
}
@Test
public void testStrategyCpe2Purl() {
purlMapper.strategy = "cpe2purl";
var v = new Vulnerability("TEST-1");
v.setBaseCpe("cpe:2.3:a:google:guava");
v.addPatchLink("https//github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
v.setPublishedDate("2018-05-30");
// inject repo2purl information
purlMapper.repo2purl.insertVote("https://github.com/python/django", "pkg:pypi/django");
// inject cpe2purl information
purlMapper.cpe2purl.insertVote("cpe:2.3:a:google:guava", "pkg:maven/org.google.guava/guava");
var versions = new HashMap<String, List<String>>();
versions.put("cpe:2.3:a:google:guava", Collections.singletonList("1.0"));
when(vrMock.getCPEVersions(Mockito.anyString())).thenReturn(versions);
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:maven/org.google.guava/guava@1.0"));
}
@Test
public void testStrategyBoth() {
purlMapper.strategy = "both";
var v = new Vulnerability("TEST-1");
v.setBaseCpe("cpe:2.3:a:google:guava");
v.addPatchLink("https//github.com/python/django/commit/5326bi6b5u53b1u5ob1b5i265");
v.setPublishedDate("2018-05-30");
// inject repo2purl information
purlMapper.repo2purl.insertVote("https://github.com/python/django", "pkg:pypi/django");
var versions = new HashMap<String, List<String>>();
versions.put("cpe:2.3:a:google:guava", Collections.singletonList("1.9"));
when(vrMock.getCPEVersions(Mockito.anyString())).thenReturn(versions);
when(pfMock.getBaseRepo(v)).thenReturn("https://github.com/python/django");
// inject cpe2purl information
purlMapper.cpe2purl.insertVote("cpe:2.3:a:google:guava", "pkg:maven/org.google/guava");
purlMapper.inferPurls(v);
assertTrue(v.getPurls().contains("pkg:pypi/django@1.9"));
}
}
|
3e1111c1ee27cdee4ab85ac4cf6ee88cd5875237 | 2,128 | java | Java | src/main/java/com/aaa/project/tool/gen/domain/ColumnInfo.java | qy93-3/Henan-mobile-patrol-inspection | 46010537dfc6fa6ab3698ed1cf4fc9e2065d1066 | [
"MIT"
] | 4 | 2019-07-23T04:05:28.000Z | 2021-12-03T08:39:21.000Z | src/main/java/com/aaa/project/tool/gen/domain/ColumnInfo.java | qy93-3/Henan-mobile-patrol-inspection | 46010537dfc6fa6ab3698ed1cf4fc9e2065d1066 | [
"MIT"
] | 2 | 2021-04-22T16:53:22.000Z | 2021-09-20T20:50:40.000Z | src/main/java/com/aaa/project/tool/gen/domain/ColumnInfo.java | c90005471/SZ_DouDou | 5ed8bfcdbb68df21ce239a8dfd52fe01b55009ec | [
"MIT"
] | null | null | null | 18.831858 | 86 | 0.605733 | 7,194 | package com.aaa.project.tool.gen.domain;
import com.alibaba.fastjson.JSON;
import com.aaa.common.utils.StringUtils;
/**
* ry数据库表列信息
*
* @author teacherChen
*/
public class ColumnInfo
{
/** 字段名称 */
private String columnName;
/** 字段类型 */
private String dataType;
/** 列描述 */
private String columnComment;
/** 列配置 */
private ColumnConfigInfo configInfo;
/** Java属性类型 */
private String attrType;
/** Java属性名称(第一个字母大写),如:user_name => UserName */
private String attrName;
/** Java属性名称(第一个字母小写),如:user_name => userName */
private String attrname;
public String getColumnName()
{
return columnName;
}
public void setColumnName(String columnName)
{
this.columnName = columnName;
}
public String getDataType()
{
return dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public String getColumnComment()
{
return columnComment;
}
public void setColumnComment(String columnComment)
{
// 根据列描述解析列的配置信息
if (StringUtils.isNoneEmpty(columnComment) && columnComment.startsWith("{"))
{
this.configInfo = JSON.parseObject(columnComment, ColumnConfigInfo.class);
this.columnComment = configInfo.getTitle();
}
else
{
this.columnComment = columnComment;
}
}
public String getAttrName()
{
return attrName;
}
public void setAttrName(String attrName)
{
this.attrName = attrName;
}
public String getAttrname()
{
return attrname;
}
public void setAttrname(String attrname)
{
this.attrname = attrname;
}
public String getAttrType()
{
return attrType;
}
public void setAttrType(String attrType)
{
this.attrType = attrType;
}
public ColumnConfigInfo getConfigInfo()
{
return configInfo;
}
public void setConfigInfo(ColumnConfigInfo configInfo)
{
this.configInfo = configInfo;
}
}
|
3e1111ef0e263da6c2954a438df677aaa6809c0e | 2,204 | java | Java | core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0731LegacyRepoLayoutTest.java | cstamas/maven-integration-testing | 91a7aa7cc6b1254aad18e51883212733b5912474 | [
"Apache-2.0"
] | 19 | 2015-11-04T21:13:52.000Z | 2022-03-22T21:50:57.000Z | core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0731LegacyRepoLayoutTest.java | cstamas/maven-integration-testing | 91a7aa7cc6b1254aad18e51883212733b5912474 | [
"Apache-2.0"
] | 61 | 2016-01-07T11:55:14.000Z | 2022-03-11T19:02:37.000Z | core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0731LegacyRepoLayoutTest.java | cstamas/maven-integration-testing | 91a7aa7cc6b1254aad18e51883212733b5912474 | [
"Apache-2.0"
] | 68 | 2015-04-19T21:45:36.000Z | 2022-03-21T20:31:12.000Z | 34.4375 | 114 | 0.704628 | 7,195 | package org.apache.maven.it;
/*
* 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.
*/
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
/**
* This is a test set for <a href="https://issues.apache.org/jira/browse/MNG-731">MNG-731</a>.
*
* @author John Casey
*
*/
public class MavenITmng0731LegacyRepoLayoutTest
extends AbstractMavenIntegrationTestCase
{
public MavenITmng0731LegacyRepoLayoutTest()
{
// legacy layout no longer supported in Maven 3.x (see MNG-4204)
super( "[2.0,3.0-alpha-3)" );
}
/**
* Verify that deployment of artifacts to a legacy-layout repository
* results in a groupId directory of 'the.full.group.id' instead of
* 'the/full/group/id'.
*/
public void testitMNG731()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/mng-0731" );
Verifier verifier = newVerifier( testDir.getAbsolutePath() );
verifier.setAutoclean( false );
verifier.deleteDirectory( "target" );
verifier.executeGoal( "validate" );
verifier.assertFilePresent( "target/test-repo/org.apache.maven.its.it0061/jars/maven-it-it0061-1.0.jar" );
verifier.assertFilePresent( "target/test-repo/org.apache.maven.its.it0061/poms/maven-it-it0061-1.0.pom" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
}
}
|
3e1113d0be50a11bf43320deaac560fa197a3a5e | 1,170 | java | Java | bootstrap/src/main/java/br/com/trustsystems/gravity/system/BaseSystemHandler.java | leandroclf/gravity-ignite | 25471214b933091047675474691a445685cf7778 | [
"Apache-2.0"
] | null | null | null | bootstrap/src/main/java/br/com/trustsystems/gravity/system/BaseSystemHandler.java | leandroclf/gravity-ignite | 25471214b933091047675474691a445685cf7778 | [
"Apache-2.0"
] | null | null | null | bootstrap/src/main/java/br/com/trustsystems/gravity/system/BaseSystemHandler.java | leandroclf/gravity-ignite | 25471214b933091047675474691a445685cf7778 | [
"Apache-2.0"
] | null | null | null | 35.454545 | 95 | 0.733333 | 7,196 | package br.com.trustsystems.gravity.system;
import br.com.trustsystems.gravity.exceptions.UnRetriableException;
import org.apache.commons.configuration.Configuration;
import java.io.Serializable;
public interface BaseSystemHandler extends Comparable<BaseSystemHandler>, Serializable{
/**
* <code>configure</code> allows the base system to configure itself by getting
* all the settings it requires and storing them internally. The plugin is only expected to
* pick the settings it has registered on the configuration file for its particular use.
* @param configuration
* @throws UnRetriableException
*/
void configure(Configuration configuration) throws UnRetriableException;
/**
* <code>initiate</code> starts the operations of this system handler.
* All excecution code for the plugins is expected to begin at this point.
*
* @throws UnRetriableException
*/
void initiate() throws UnRetriableException;
/**
* <code>terminate</code> halts excecution of this plugin.
* This provides a clean way to exit /stop operations of this particular plugin.
*/
void terminate();
}
|
3e111664ede1021ae59cbfc45b8a0b492347cec0 | 2,486 | java | Java | Code Examples/Jaxrs/src/main/java/io/hashimati/graphqls/FruitQueryResolver.java | hashimati/MicroCli | 3db69b765115713f1ee25fd6a67f3a1c1c839e4c | [
"Apache-2.0"
] | 2 | 2022-02-07T03:53:13.000Z | 2022-02-15T22:48:54.000Z | Code Examples/Jaxrs/src/main/java/io/hashimati/graphqls/FruitQueryResolver.java | hashimati/MicroCli | 3db69b765115713f1ee25fd6a67f3a1c1c839e4c | [
"Apache-2.0"
] | null | null | null | Code Examples/Jaxrs/src/main/java/io/hashimati/graphqls/FruitQueryResolver.java | hashimati/MicroCli | 3db69b765115713f1ee25fd6a67f3a1c1c839e4c | [
"Apache-2.0"
] | null | null | null | 39.460317 | 199 | 0.726066 | 7,197 | package io.hashimati.graphqls;
import graphql.kickstart.tools.GraphQLMutationResolver;
import graphql.kickstart.tools.GraphQLQueryResolver;
import io.hashimati.domains.Fruit;
import io.hashimati.services.FruitService;
import io.micrometer.core.annotation.Timed;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
@Singleton
public class FruitQueryResolver implements GraphQLQueryResolver, GraphQLMutationResolver {
@Inject
private FruitService fruitService;
@Timed(value = "io.hashimati.graphqls.QueryResolver.save.findById", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for finding a fruit object by id")
public Fruit findFruitById(long id)
{
return fruitService.findById(id);
}
//@Timed(value = "io.hashimati.graphqls.FruitQueryResolver.findAll", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for finding all fruit objects")
public Iterable<Fruit> findAllFruit()
{
return fruitService.findAll();
}
@Timed(value = "io.hashimati.graphqls.FruitQueryResolver.save", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for saving fruit object")
public Fruit saveFruit(Fruit fruit){
return fruitService.save(fruit);
}
@Timed(value = "io.hashimati.graphqls.FruitQueryResolver.update", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for update a fruit object")
public Fruit updateFruit(Fruit fruit)
{
return fruitService.update(fruit);
}
@Timed(value = "io.hashimati.graphqls.FruitQueryResolver.deleteById", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for deleting a fruit object by id")
public boolean deleteFruit(long id){
return fruitService.deleteById(id);
}
@Timed(value = "io.hashimati.graphqls.QueryResolver.findByIdName", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for finding a fruit object by Name")
public Fruit findFruitByName(String query){
return fruitService.findByName(query);
}
//@Timed(value = "io.hashimati.graphqls.FruitQueryResolver.findAllLetter", percentiles = { 0.5, 0.95, 0.99 }, description = "Observing all service metric for finding all fruit objects by Letter")
public Iterable<Fruit> findAllFruitByLetter(String query){
return fruitService.findAllByLetter(query);
}
}
|
3e1116b0990088d36db72a2b350fd6089b2e7c78 | 4,675 | java | Java | data/raw/syncope/ext/flowable/client-enduser/src/main/java/org/apache/syncope/client/enduser/resources/UserRequestCancelResource.java | NelloCarotenuto/Weakness-Detector-for-Java | 5809e23d1b0f5d17a370d4dd841596973b34aa79 | [
"MIT"
] | 2 | 2019-10-22T18:13:23.000Z | 2019-10-27T16:41:35.000Z | data/raw/syncope/ext/flowable/client-enduser/src/main/java/org/apache/syncope/client/enduser/resources/UserRequestCancelResource.java | NelloCarotenuto/Weakness-Detector-for-Java | 5809e23d1b0f5d17a370d4dd841596973b34aa79 | [
"MIT"
] | null | null | null | data/raw/syncope/ext/flowable/client-enduser/src/main/java/org/apache/syncope/client/enduser/resources/UserRequestCancelResource.java | NelloCarotenuto/Weakness-Detector-for-Java | 5809e23d1b0f5d17a370d4dd841596973b34aa79 | [
"MIT"
] | null | null | null | 46.75 | 120 | 0.683636 | 7,198 | /*
* 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.syncope.client.enduser.resources;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.syncope.client.enduser.SyncopeEnduserSession;
import org.apache.syncope.client.enduser.annotations.Resource;
import org.apache.syncope.common.rest.api.service.UserRequestService;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.AbstractResource;
import org.apache.wicket.request.resource.IResource;
import org.apache.wicket.util.string.StringValue;
@Resource(key = "userRequestCancel", path = "/api/flowable/userRequests/${executionId}")
public class UserRequestCancelResource extends BaseResource {
private static final long serialVersionUID = 7273151109078469253L;
@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
ResourceResponse response = new AbstractResource.ResourceResponse();
response.setContentType(MediaType.APPLICATION_JSON);
StringValue executionId;
try {
HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
if (!xsrfCheck(request)) {
LOG.error("XSRF TOKEN does not match");
response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN does not match");
return response;
}
if (!HttpMethod.DELETE.equals(request.getMethod())) {
throw new UnsupportedOperationException("Unsupported operation, only DELETE allowed");
}
PageParameters parameters = attributes.getParameters();
executionId = parameters.get("executionId");
IRequestParameters requestParameters = attributes.getRequest().getQueryParameters();
StringValue reason = requestParameters.getParameterValue("reason");
LOG.debug("Cancel Flowable User Request with execution id [{}] for user [{}] with reason [{}]", executionId,
SyncopeEnduserSession.get().getSelfTO().getUsername(), reason);
if (executionId.isEmpty()) {
throw new IllegalArgumentException("Empty executionId, please provide a value");
}
SyncopeEnduserSession.get().getService(UserRequestService.class).cancel(executionId.toString(),
reason.toString());
final String outcomeMessage = String.format(
"User Request with execution id [%s] successfully canceled for User [%s]", executionId.
toString(), SyncopeEnduserSession.get().getSelfTO().getUsername());
response.setWriteCallback(new AbstractResource.WriteCallback() {
@Override
public void writeData(final IResource.Attributes attributes) throws IOException {
attributes.getResponse().write(outcomeMessage);
}
});
response.setContentType(MediaType.APPLICATION_JSON);
response.setTextEncoding(StandardCharsets.UTF_8.name());
response.setStatusCode(Response.Status.OK.getStatusCode());
} catch (Exception e) {
LOG.error("Error cancelling User Request for [{}]", SyncopeEnduserSession.get().getSelfTO().getUsername(),
e);
response.setError(Response.Status.BAD_REQUEST.getStatusCode(), new StringBuilder()
.append("ErrorMessage{{ ")
.append(e.getMessage())
.append(" }}")
.toString());
}
return response;
}
}
|
3e1117511360d7afc9b31fda73fc7c48b15ca53d | 733 | java | Java | 1/ParkJaemin/Lecture/210104/StartHomework.java | dkak49/GroupStudy | 9f452007bd4c323acb651c926b2dcfa03b1a1311 | [
"MIT"
] | 1 | 2021-02-01T17:32:00.000Z | 2021-02-01T17:32:00.000Z | 1/ParkJaemin/Lecture/210104/StartHomework.java | dkak49/GroupStudy | 9f452007bd4c323acb651c926b2dcfa03b1a1311 | [
"MIT"
] | null | null | null | 1/ParkJaemin/Lecture/210104/StartHomework.java | dkak49/GroupStudy | 9f452007bd4c323acb651c926b2dcfa03b1a1311 | [
"MIT"
] | null | null | null | 22.90625 | 67 | 0.496589 | 7,199 | import java.util.Scanner;
public class StartHomework {
public static void main(String[] args) {
//시작 값을 입력 받도록 하고
//끝나는 값을 입력 받도록 만들어서 시작 ~ 끝까지의 합을 출력해보자!
Scanner scanner = new Scanner(System.in);
System.out.println("시작하는 값은 = ");
int num = scanner.nextInt();
// int start = scan.NextInt();
System.out.println("끝나는 값은 = ");
int num2 = scanner.nextInt();
// int start2 = scan.NextInt();
int sum = 0;
for (int i = num; i <= num2; i++) {
sum = sum + i;
}
System.out.println("시작하는 값과 끝나는 값의 총합 = " + (sum));
// System.out.printf("%d ~%d까지의 합 = %d\n, " start,end,sum);
}
}
|
3e1117c954bb3878af58ce9246600338a8db43c8 | 5,377 | java | Java | VanillaPlus/src/fr/soreth/VanillaPlus/Icon/IconAchievement.java | dracnis/VanillaPlus | 6ae48d9141918099fbf709963ddecd07771885a4 | [
"MIT"
] | 1 | 2017-09-13T00:49:57.000Z | 2017-09-13T00:49:57.000Z | VanillaPlus/src/fr/soreth/VanillaPlus/Icon/IconAchievement.java | dracnis/VanillaPlus | 6ae48d9141918099fbf709963ddecd07771885a4 | [
"MIT"
] | 1 | 2017-12-23T19:22:41.000Z | 2020-04-05T20:03:24.000Z | VanillaPlus/src/fr/soreth/VanillaPlus/Icon/IconAchievement.java | dracnis/VanillaPlus | 6ae48d9141918099fbf709963ddecd07771885a4 | [
"MIT"
] | null | null | null | 37.340278 | 114 | 0.747629 | 7,200 | package fr.soreth.VanillaPlus.Icon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import fr.soreth.VanillaPlus.VanillaPlusCore;
import fr.soreth.VanillaPlus.Error;
import fr.soreth.VanillaPlus.ErrorLogger;
import fr.soreth.VanillaPlus.Localizer;
import fr.soreth.VanillaPlus.Node;
import fr.soreth.VanillaPlus.PlaceH;
import fr.soreth.VanillaPlus.Menu.MenuLink;
import fr.soreth.VanillaPlus.Message.MessageManager;
import fr.soreth.VanillaPlus.MComponent.MComponent;
import fr.soreth.VanillaPlus.Player.Achievement;
import fr.soreth.VanillaPlus.Player.VPPlayer;
import fr.soreth.VanillaPlus.Utils.LiteEntry;
public class IconAchievement extends Icon{
private Achievement achievement;
private LiteEntry<Icon, Icon> display;
private MComponent requirementMessage, rewardMessage;
private boolean showUnlockedRequirement, showUnlockedReward, showLockedRequirement, showLockedReward;
public IconAchievement(ConfigurationSection section, MessageManager manager) {
this.achievement = VanillaPlusCore.getAchievementManager().get((short) section.getInt(Node.ID.get(), 0));
if(achievement == null){
ErrorLogger.addError(Node.ID.get() + Error.INVALID.getMessage());
return;
}
this.display = VanillaPlusCore.getAchievementManager().getDisplay((byte) section.getInt(Node.DISPLAY.get(), 0));
if(display == null)
ErrorLogger.addError(Node.DISPLAY.get() + Error.INVALID.getMessage());
showLockedRequirement = section.getBoolean("SHOW_LOCKED_REQUIREMENT", true);
showLockedReward = section.getBoolean("SHOW_LOCKED_REWARD", true);
showUnlockedRequirement = section.getBoolean("SHOW_UNLOCKED_REQUIREMENT", false);
showUnlockedReward = section.getBoolean("SHOW_UNLOCKED_REWARD", false);
if((showLockedRequirement || showUnlockedRequirement) && achievement.getRequirement() == null){
ErrorLogger.addError("Can't show unset requirement !");
showLockedRequirement = false;
showUnlockedRequirement = false;
}else if(showLockedRequirement || showUnlockedRequirement){
if(section.contains("REQUIREMENT_MESSAGE"))
this.requirementMessage = manager.getComponentManager().get(section.getString("REQUIREMENT_MESSAGE"));
}
if((showLockedReward || showUnlockedReward) && achievement.getReward() == null){
ErrorLogger.addError("Can't show unset reward !");
showLockedReward = false;
showUnlockedReward = false;
}else if (showLockedReward || showUnlockedReward) {
if(section.contains("REWARD_MESSAGE"))
this.rewardMessage = manager.getComponentManager().get(section.getString("REWARD_MESSAGE"));
}
}
@Override
public boolean isStatic(){
return false;
}
@Override
public boolean closeOnClick() {
return false;
}
@Override
public boolean hasLore() {
return true;
}
@Override
public ItemStack getItemstack(VPPlayer player, Localizer loc){
Icon curent = null;
boolean has = false;
if(player.hasAchievement(achievement.getID())){
curent = display.getKey();
has = true;
}else{
curent = display.getValue();
}
MComponent base = curent.name;
if(base != null)
base.addReplacement(PlaceH.NAME.get(), achievement.getName().getMessage(player.getLanguage()));
if(curent.hasLore())
for(MComponent lore : curent.lore){
lore.addReplacement(PlaceH.DESCRIPTION.get(), achievement.getLore().getMessage(player.getLanguage()));
lore.setSplit(true);
}
ItemStack result = curent.getItemstack(player, loc);
if(has && (showUnlockedRequirement || showUnlockedReward)){
ItemMeta meta = result.getItemMeta();
List<String>lores = meta.getLore();
if(lores == null){
lores = new ArrayList<String>();
}
if(showLockedRequirement){
if(requirementMessage != null)
lores.addAll(Arrays.asList(requirementMessage.getMessage(player, loc).split("\n")));
lores.addAll(Arrays.asList(achievement.getRequirement().format(player, player.getLanguage()).split("\n")));
}
if(showLockedReward){
if(rewardMessage != null)
lores.addAll(Arrays.asList(rewardMessage.getMessage(player, loc).split("\n")));
lores.addAll(achievement.getReward().format(player.getLanguage()));
}
meta.setLore(lores);
result.setItemMeta(meta);
}else if(!has && (showLockedRequirement || showLockedReward)){
ItemMeta meta = result.getItemMeta();
List<String>lores = meta.getLore();
if(lores == null){
lores = new ArrayList<String>();
}
if(showLockedRequirement){
if(requirementMessage != null)
lores.addAll(Arrays.asList(requirementMessage.getMessage(player, loc).split("\n")));
lores.addAll(Arrays.asList(achievement.getRequirement().format(player, player.getLanguage()).split("\n")));
}
if(showLockedReward){
if(rewardMessage != null)
lores.addAll(Arrays.asList(rewardMessage.getMessage(player, loc).split("\n")));
lores.addAll(achievement.getReward().format(player.getLanguage()));
}
meta.setLore(lores);
result.setItemMeta(meta);
}
return result;
}
@Override
public boolean canMove(VPPlayer clicker) {
return false;
}
@Override
public Icon getIcon(VPPlayer player) {
return this;
}
@Override
public boolean onClick(VPPlayer viewer, ClickType type, MenuLink ml){
return false;
}
}
|
3e1117ddab51afcda682b4d156ee8766402e3ca4 | 2,660 | java | Java | FitSDKRelease_21.40.00/java/com/garmin/fit/UserLocalId.java | JoyKuan/ArchitecturalDesign_AI | 71442dcfdba20564a772a6807e43cbb86dafc14d | [
"Apache-2.0"
] | 1 | 2021-02-21T05:24:21.000Z | 2021-02-21T05:24:21.000Z | FitSDKRelease_21.40.00/java/com/garmin/fit/UserLocalId.java | JoyKuan/ArchitecturalDesign_AI | 71442dcfdba20564a772a6807e43cbb86dafc14d | [
"Apache-2.0"
] | null | null | null | FitSDKRelease_21.40.00/java/com/garmin/fit/UserLocalId.java | JoyKuan/ArchitecturalDesign_AI | 71442dcfdba20564a772a6807e43cbb86dafc14d | [
"Apache-2.0"
] | null | null | null | 36.944444 | 81 | 0.599624 | 7,201 | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2020 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 21.40Release
// Tag = production/akw/21.40.00-0-g813c158
////////////////////////////////////////////////////////////////////////////////
package com.garmin.fit;
import java.util.HashMap;
import java.util.Map;
public class UserLocalId {
public static final int LOCAL_MIN = 0x0000;
public static final int LOCAL_MAX = 0x000F;
public static final int STATIONARY_MIN = 0x0010;
public static final int STATIONARY_MAX = 0x00FF;
public static final int PORTABLE_MIN = 0x0100;
public static final int PORTABLE_MAX = 0xFFFE;
public static final int INVALID = Fit.UINT16_INVALID;
private static final Map<Integer, String> stringMap;
static {
stringMap = new HashMap<Integer, String>();
stringMap.put(LOCAL_MIN, "LOCAL_MIN");
stringMap.put(LOCAL_MAX, "LOCAL_MAX");
stringMap.put(STATIONARY_MIN, "STATIONARY_MIN");
stringMap.put(STATIONARY_MAX, "STATIONARY_MAX");
stringMap.put(PORTABLE_MIN, "PORTABLE_MIN");
stringMap.put(PORTABLE_MAX, "PORTABLE_MAX");
}
/**
* Retrieves the String Representation of the Value
* @return The string representation of the value, or empty if unknown
*/
public static String getStringFromValue( Integer value ) {
if( stringMap.containsKey( value ) ) {
return stringMap.get( value );
}
return "";
}
/**
* Retrieves a value given a string representation
* @return The value or INVALID if unkwown
*/
public static Integer getValueFromString( String value ) {
for( Map.Entry<Integer, String> entry : stringMap.entrySet() ) {
if( entry.getValue().equals( value ) ) {
return entry.getKey();
}
}
return INVALID;
}
}
|
3e1118e6dcb63535d001d67a532cf61dd5e3d6c9 | 7,271 | java | Java | dex-reader-api/src/main/java/com/googlecode/d2j/visitors/DexCodeVisitor.java | KoEnix/dex2jar | 1d64a8583370296321b62e988930cfe8a1f6f3a1 | [
"Apache-2.0"
] | 10,182 | 2015-03-22T04:27:47.000Z | 2022-03-31T19:58:26.000Z | dex-reader-api/src/main/java/com/googlecode/d2j/visitors/DexCodeVisitor.java | KoEnix/dex2jar | 1d64a8583370296321b62e988930cfe8a1f6f3a1 | [
"Apache-2.0"
] | 516 | 2015-04-10T03:38:42.000Z | 2022-03-30T21:04:50.000Z | dex-reader-api/src/main/java/com/googlecode/d2j/visitors/DexCodeVisitor.java | KoEnix/dex2jar | 1d64a8583370296321b62e988930cfe8a1f6f3a1 | [
"Apache-2.0"
] | 2,035 | 2015-04-09T16:07:53.000Z | 2022-03-30T16:29:41.000Z | 22.721875 | 116 | 0.499931 | 7,202 | /*
* Copyright (c) 2009-2012 Panxiaobo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.d2j.visitors;
import com.googlecode.d2j.*;
import com.googlecode.d2j.reader.Op;
/**
* @author <a href="mailto:upchh@example.com">Panxiaobo</a>
* @version $Rev$
*/
public class DexCodeVisitor {
protected DexCodeVisitor visitor;
public DexCodeVisitor() {
super();
}
public DexCodeVisitor(DexCodeVisitor visitor) {
super();
this.visitor = visitor;
}
public void visitRegister(int total) {
if (visitor != null) {
visitor.visitRegister(total);
}
}
/**
* <pre>
* OP_X_INT_LIT8
* </pre>
*
* @param op
* @param distReg
* @param srcReg
* @param content
*/
public void visitStmt2R1N(Op op, int distReg, int srcReg, int content) {
if (visitor != null) {
visitor.visitStmt2R1N(op, distReg, srcReg, content);
}
}
/**
* <pre>
*
* OP_ADD
* OP_SUB
* OP_MUL
* OP_DIV
* OP_REM
* OP_AND
* OP_OR
* OP_XOR
* OP_SHL
* OP_SHR
* OP_USHR
* OP_CMPL
* OP_CMPG
* OP_CMP
* OP_AGETX
* OP_APUTX
* </pre>
*
*/
public void visitStmt3R(Op op, int a, int b, int c) {
if (visitor != null) {
visitor.visitStmt3R(op, a, b, c);
}
}
/**
* <pre>
* OP_INSTANCE_OF
* OP_NEW_ARRAY
* OP_CHECK_CAST
* OP_NEW_INSTANCE
* </pre>
*
* @param op
* @param a
* @param b
* @param type
*/
public void visitTypeStmt(Op op, int a, int b, String type) {
if (visitor != null) {
visitor.visitTypeStmt(op, a, b, type);
}
}
/**
* <pre>
* CONST * CONST_WIDE * CONST_STRING * CONST_CLASS *
* </pre>
*
* @param op
* @param ra
* @param value
* int/long/type
*/
public void visitConstStmt(Op op, int ra, Object value) {
if (visitor != null) {
visitor.visitConstStmt(op, ra, value);
}
}
public void visitFillArrayDataStmt(Op op, int ra, Object array) {
if (visitor != null) {
visitor.visitFillArrayDataStmt(op, ra, array);
}
}
public void visitEnd() {
if (visitor != null) {
visitor.visitEnd();
}
}
/**
* <pre>
* OP_IGETX a,b field
* OP_IPUTX a,b field
* OP_SGETX a field
* OP_SPUTX a field
* </pre>
*
* @param op
* @param a
* @param b
* @param field
*/
public void visitFieldStmt(Op op, int a, int b, Field field) {
if (visitor != null) {
visitor.visitFieldStmt(op, a, b, field);
}
}
/**
* <pre>
* OP_FILLED_NEW_ARRAY
* </pre>
*
* @param op
* @param args
* @param type
*/
public void visitFilledNewArrayStmt(Op op, int[] args, String type) {
if (visitor != null) {
visitor.visitFilledNewArrayStmt(op, args, type);
}
}
/**
* <pre>
* OP_IF_EQ
* OP_IF_NE
* OP_IF_LT
* OP_IF_GE
* OP_IF_GT
* OP_IF_LE
* OP_GOTO
* OP_IF_EQZ
* OP_IF_NEZ
* OP_IF_LTZ
* OP_IF_GEZ
* OP_IF_GTZ
* OP_IF_LEZ
* </pre>
*
* @param op
* @param a
* @param b
* @param label
*/
public void visitJumpStmt(Op op, int a, int b, DexLabel label) {
if (visitor != null) {
visitor.visitJumpStmt(op, a, b, label);
}
}
public void visitLabel(DexLabel label) {
if (visitor != null) {
visitor.visitLabel(label);
}
}
public void visitSparseSwitchStmt(Op op, int ra, int[] cases, DexLabel[] labels) {
if (visitor != null) {
visitor.visitSparseSwitchStmt(op, ra, cases, labels);
}
}
/**
* <pre>
* OP_INVOKE_VIRTUAL
* OP_INVOKE_SUPER
* OP_INVOKE_DIRECT
* OP_INVOKE_STATIC
* OP_INVOKE_INTERFACE
* </pre>
*
* @param op
* @param args
* @param method
*/
public void visitMethodStmt(Op op, int[] args, Method method) {
if (visitor != null) {
visitor.visitMethodStmt(op, args, method);
}
}
/**
* <pre>
* OP_INVOKE_CUSTOM
* </pre>
*/
public void visitMethodStmt(Op op, int[] args, String name, Proto proto, MethodHandle bsm, Object... bsmArgs) {
if (visitor != null) {
visitor.visitMethodStmt(op, args, name, proto, bsm, bsmArgs);
}
}
/**
* <pre>
* OP_INVOKE_POLYMORPHIC
* </pre>
*
*/
public void visitMethodStmt(Op op, int[] args, Method bsm, Proto proto) {
if (visitor != null) {
visitor.visitMethodStmt(op, args, bsm, proto);
}
}
/**
* <pre>
* OP_MOVE*
* a = a X b
* OP_ARRAY_LENGTH
* a=Xb
* X_TO_Y
* </pre>
*
* @param op
* @param a
* @param b
*/
public void visitStmt2R(Op op, int a, int b) {
if (visitor != null) {
visitor.visitStmt2R(op, a, b);
}
}
/**
*
* {@link Op#RETURN_VOID} {@link Op#NOP} {@link Op#BAD_OP}
*
* @param op
*/
public void visitStmt0R(Op op) {
if (visitor != null) {
visitor.visitStmt0R(op);
}
}
/**
* <pre>
* OP_RETURN_X
* OP_THROW_X
* OP_MONITOR_ENTER
* OP_MONITOR_EXIT
* OP_MOVE_RESULT_X
* OP_MOVE_EXCEPTION_X
* </pre>
*
* @param op
* @param reg
*/
public void visitStmt1R(Op op, int reg) {
if (visitor != null) {
visitor.visitStmt1R(op, reg);
}
}
public void visitPackedSwitchStmt(Op op, int aA, int first_case, DexLabel[] labels) {
if (visitor != null) {
visitor.visitPackedSwitchStmt(op, aA, first_case, labels);
}
}
public void visitTryCatch(DexLabel start, DexLabel end, DexLabel handler[], String type[]) {
if (visitor != null) {
visitor.visitTryCatch(start, end, handler, type);
}
}
public DexDebugVisitor visitDebug() {
if (visitor != null) {
return visitor.visitDebug();
}
return null;
}
}
|
3e1118f2670dc7bc4b3b657e2a1f140f38336536 | 1,296 | java | Java | hutool-core/src/main/java/cn/hutool/core/io/resource/BytesResource.java | 769786651/hutool | 03c7c7e48fd2b4708f9f7af5b8771345f06b9b67 | [
"Apache-2.0"
] | 3 | 2018-07-10T08:41:20.000Z | 2018-07-10T08:41:26.000Z | hutool-core/src/main/java/cn/hutool/core/io/resource/BytesResource.java | catkins10/hutool | 03c7c7e48fd2b4708f9f7af5b8771345f06b9b67 | [
"Apache-2.0"
] | null | null | null | hutool-core/src/main/java/cn/hutool/core/io/resource/BytesResource.java | catkins10/hutool | 03c7c7e48fd2b4708f9f7af5b8771345f06b9b67 | [
"Apache-2.0"
] | null | null | null | 19.938462 | 68 | 0.702932 | 7,203 | package cn.hutool.core.io.resource;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.nio.charset.Charset;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
/**
* 基于byte[]的资源获取器<br>
* 注意:此对象中getUrl方法始终返回null
*
* @author looly
* @since 4.0.9
*/
public class BytesResource implements Resource {
private byte[] bytes;
/**
* 构造
*
* @param bytes 字节数组
*/
public BytesResource(byte[] bytes) {
this.bytes = bytes;
}
@Override
public URL getUrl() {
return null;
}
@Override
public InputStream getStream() {
return new ByteArrayInputStream(this.bytes);
}
@Override
public BufferedReader getReader(Charset charset) {
return new BufferedReader(new StringReader(readStr(charset)));
}
@Override
public String readStr(Charset charset) throws IORuntimeException {
return StrUtil.str(this.bytes, charset);
}
@Override
public String readUtf8Str() throws IORuntimeException {
return readStr(CharsetUtil.CHARSET_UTF_8);
}
@Override
public byte[] readBytes() throws IORuntimeException {
return this.bytes;
}
}
|
3e111996fdcd4d4af238b93c601a5554da3c1ba5 | 4,282 | java | Java | src/main/java/zmaster587/advancedRocketry/client/render/ClientDynamicTexture.java | chilla55/AdvancedRocketry | 6075a7820f8d983630e961852df17fe275709b17 | [
"MIT"
] | 167 | 2015-06-20T13:55:21.000Z | 2021-03-24T08:12:57.000Z | src/main/java/zmaster587/advancedRocketry/client/render/ClientDynamicTexture.java | chilla55/AdvancedRocketry | 6075a7820f8d983630e961852df17fe275709b17 | [
"MIT"
] | 1,952 | 2015-09-30T05:28:39.000Z | 2021-04-03T03:45:35.000Z | src/main/java/zmaster587/advancedRocketry/client/render/ClientDynamicTexture.java | chilla55/AdvancedRocketry | 6075a7820f8d983630e961852df17fe275709b17 | [
"MIT"
] | 290 | 2021-04-13T18:06:28.000Z | 2022-03-31T05:46:50.000Z | 31.955224 | 145 | 0.730967 | 7,204 | package zmaster587.advancedRocketry.client.render;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import zmaster587.advancedRocketry.AdvancedRocketry;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class ClientDynamicTexture {
private BufferedImage image;
private static final byte BYTES_PER_PIXEL = 4;
int textureId;
/**
* Creates a texture with the default 512x512 pixels
*/
public ClientDynamicTexture() {
this(512,512);
}
/**
*
* @param x x size of the image
* @param y y size of the image
*/
public ClientDynamicTexture(int x, int y) {
image = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
textureId = -1;
init();
}
/**
* @return this buffered image
*/
public BufferedImage getImage() {
return image;
}
/**
*
* @param x x location of the pixel
* @param y y location of the pixel
* @param color color in RGBA8
*/
public void setPixel(int x, int y, int color) {
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getHeight() * image.getWidth() * BYTES_PER_PIXEL);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, getTextureId());
GL11.glGetTexImage(GL11.GL_TEXTURE_2D,0 , GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
buffer.putInt(x + (y * image.getHeight()), color);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
}
/**
* @return IntBuffer containing the pixels for the image
*/
public IntBuffer getByteBuffer() {
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getHeight() * image.getWidth() * BYTES_PER_PIXEL);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, getTextureId());
//GL11.glGetTexImage(GL11.GL_TEXTURE_2D,0 , GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
IntBuffer ret = buffer.asIntBuffer();
ret.put(pixels);
return ret;
}
public void setByteBuffer(IntBuffer buffer) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, getTextureId());
//Just clamp to edge
//GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
//GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
//Scale linearly
//GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
//GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
//GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
//GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
try {
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, image.getWidth(), image.getHeight(), GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
} catch(IllegalArgumentException e) {
e.printStackTrace();
AdvancedRocketry.logger.warn("Planet image generation FX failed!");
}
}
private void init() {
//create array, every single pixel
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getHeight() * image.getWidth() * BYTES_PER_PIXEL);
for(int i = 0; i < image.getHeight() * image.getWidth(); i++) {
buffer.putInt(0x00000000);
}
buffer.flip();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, getTextureId());
//Just clamp to edge
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
//Scale linearly
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
}
/**
* Returns the GL texture ID of this image, if it doesnt exist, then creates it
* @return the GL texture ID of this image
*/
public int getTextureId() {
if(textureId != -1)
return textureId;
textureId = GL11.glGenTextures();
return textureId;
}
}
|
3e111aca408e832840ff638aa5245ad3785c9e0e | 465 | java | Java | src/main/java/com/melonbar/exchange/coinbase/authentication/NoAuthentication.java | melon-bar/MelonBarExchange-CoinbasePro | 0920d01311f13379ef3338c44048c2256e8d378c | [
"Apache-2.0"
] | 3 | 2021-05-13T21:05:13.000Z | 2021-05-19T01:19:16.000Z | src/main/java/com/melonbar/exchange/coinbase/authentication/NoAuthentication.java | melon-bar/MelonBarExchange-CoinbasePro | 0920d01311f13379ef3338c44048c2256e8d378c | [
"Apache-2.0"
] | 1 | 2021-05-08T04:15:27.000Z | 2021-05-08T04:15:27.000Z | src/main/java/com/melonbar/exchange/coinbase/authentication/NoAuthentication.java | coryjk/MelonBarExchange-CoinbasePro | c53b8bfb8d6a74094927590cfd06a5c8f4bde9b3 | [
"Apache-2.0"
] | 2 | 2021-05-13T21:03:05.000Z | 2021-05-13T23:33:55.000Z | 31 | 81 | 0.606452 | 7,205 | package com.melonbar.exchange.coinbase.authentication;
import java.net.http.HttpRequest;
public class NoAuthentication implements Authentication {
@Override
public HttpRequest.Builder sign(final HttpRequest.Builder httpRequestBuilder,
final String method,
final String requestPath,
final String body) {
return httpRequestBuilder;
}
}
|
3e111bc54ca2a75dd358838f6817fc7664a8b56b | 506 | java | Java | references/bcb_chosen_clones/selected#1434359#219#232.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 23 | 2018-10-03T15:02:53.000Z | 2021-09-16T11:07:36.000Z | references/bcb_chosen_clones/selected#1434359#219#232.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 18 | 2019-02-10T04:52:54.000Z | 2022-01-25T02:14:40.000Z | references/bcb_chosen_clones/selected#1434359#219#232.java | cragkhit/Siamese | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 19 | 2018-11-16T13:39:05.000Z | 2021-09-05T23:59:30.000Z | 33.733333 | 73 | 0.523715 | 7,206 | public static void copyFile(File from, File to) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
byte[] bytes = new byte[1024 * 4];
int len = 0;
while ((len = in.read(bytes)) >= 0) out.write(bytes, 0, len);
} finally {
Streams.closeQuietly(in);
Streams.closeQuietly(out);
}
}
|
3e111be119596decfb0f3c08897946535dab81e0 | 1,236 | java | Java | components/dotnet-vendor/src/main/java/npanday/vendor/SettingsRepository.java | octavian-h/npanday | 02a0fa919534fc4afee4ae407f8e597fd7f5e6a7 | [
"Apache-2.0"
] | 6 | 2016-06-06T05:04:19.000Z | 2021-11-10T13:36:47.000Z | components/dotnet-vendor/src/main/java/npanday/vendor/SettingsRepository.java | octavian-h/npanday | 02a0fa919534fc4afee4ae407f8e597fd7f5e6a7 | [
"Apache-2.0"
] | 3 | 2017-10-28T14:08:53.000Z | 2019-02-25T13:24:27.000Z | components/dotnet-vendor/src/main/java/npanday/vendor/SettingsRepository.java | octavian-h/npanday | 02a0fa919534fc4afee4ae407f8e597fd7f5e6a7 | [
"Apache-2.0"
] | 12 | 2015-01-15T14:29:50.000Z | 2021-11-10T13:36:36.000Z | 31.075 | 74 | 0.750603 | 7,207 | package npanday.vendor;
/*
* 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.
*/
import npanday.model.settings.DefaultSetup;
import npanday.model.settings.Vendor;
import npanday.registry.Repository;
import java.util.List;
/**
* @author <a href="mailto:nnheo@example.com">Lars Corneliussen</a>
*/
public interface SettingsRepository
extends Repository
{
List<Vendor> getVendors();
DefaultSetup getDefaultSetup();
boolean isEmpty();
int getContentVersion();
}
|
3e111cb9d754db59b02be88e8e15549097088615 | 10,529 | java | Java | TlosSW_V1.0/src/com/likya/tlossw/core/cpc/Cpc.java | likyateknoloji/TlossWGroup | a0fa0415a3b478bd594b4b9df534fc7c287f5b9e | [
"Apache-2.0"
] | null | null | null | TlosSW_V1.0/src/com/likya/tlossw/core/cpc/Cpc.java | likyateknoloji/TlossWGroup | a0fa0415a3b478bd594b4b9df534fc7c287f5b9e | [
"Apache-2.0"
] | null | null | null | TlosSW_V1.0/src/com/likya/tlossw/core/cpc/Cpc.java | likyateknoloji/TlossWGroup | a0fa0415a3b478bd594b4b9df534fc7c287f5b9e | [
"Apache-2.0"
] | null | null | null | 34.634868 | 146 | 0.713458 | 7,208 | package com.likya.tlossw.core.cpc;
import java.util.HashMap;
import org.apache.log4j.Logger;
import com.likya.tlos.model.xmlbeans.data.TlosProcessDataDocument.TlosProcessData;
import com.likya.tlos.model.xmlbeans.state.LiveStateInfoDocument.LiveStateInfo;
import com.likya.tlos.model.xmlbeans.state.StateNameDocument.StateName;
import com.likya.tlos.model.xmlbeans.state.StatusNameDocument.StatusName;
import com.likya.tlos.model.xmlbeans.state.SubstateNameDocument.SubstateName;
import com.likya.tlossw.TlosSpaceWide;
import com.likya.tlossw.core.cpc.helper.ConcurrencyAnalyzer;
import com.likya.tlossw.core.cpc.helper.Consolidator;
import com.likya.tlossw.core.cpc.model.AppState;
import com.likya.tlossw.core.cpc.model.RunInfoType;
import com.likya.tlossw.core.cpc.model.SpcInfoType;
import com.likya.tlossw.core.spc.Spc;
import com.likya.tlossw.exceptions.TlosException;
import com.likya.tlossw.exceptions.TlosFatalException;
import com.likya.tlossw.model.SpcLookupTable;
import com.likya.tlossw.model.path.TlosSWPathType;
import com.likya.tlossw.utils.CpcUtils;
import com.likya.tlossw.utils.PersistenceUtils;
import com.likya.tlossw.utils.SpaceWideRegistry;
/**
* @author Serkan Taş
*
*/
public class Cpc extends CpcBase {
public boolean isUserSelectedRecover = false;
private Logger logger = SpaceWideRegistry.getGlobalLogger();
// private boolean isRegular = true;
public Cpc(SpaceWideRegistry spaceWideRegistry) {
super(spaceWideRegistry);
this.isUserSelectedRecover = spaceWideRegistry.isUserSelectedRecover();
}
public void run() {
Thread.currentThread().setName("Cpc");
while (isExecutionPermission()) {
try {
logger.info("");
logger.info(" 2 - Recover işlemi gerekli mi?");
if (isUserSelectedRecover) {
logger.info(" > Evet, recover işlemi gerekli !");
handleRecoverdExecution();
} else {
logger.info(" > Hayır, recover işlemi gerekli değil !");
handleDailyExecution();
}
// Her bir run icin senaryolari aktive et !
for (String runId : getSpaceWideRegistry().getRunLookupTable().keySet()) {
RunInfoType runInfoType = getSpaceWideRegistry().getRunLookupTable().get(runId);
HashMap<String, SpcInfoType> spcLookupTable = runInfoType.getSpcLookupTable().getTable();
if (spcLookupTable == null) {
logger.warn(" >>> UYARI : Senaryo isleme agaci SPC bos !!");
logger.debug(" DEBUG : spcLookupTable is null, check getSpaceWideRegistry().getPlanLookupTable().get(" + runId + ")! ");
break;
}
logger.info("");
logger.info(" 10 - Butun senaryolar calismaya hazir, islem baslasin !");
for (String spcId : spcLookupTable.keySet()) {
SpcInfoType mySpcInfoType = spcLookupTable.get(spcId);
Spc spc = mySpcInfoType.getSpcReferance();
if (spc == null) {
// No spc defined for this scenario, it is NOT a BUG !
continue;
}
logger.info(" > Senaryo " + spcId + " calistiriliyor !");
CpcUtils.startSpc(mySpcInfoType, logger);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Cpc failed, terminating !");
break;
}
logger.info("");
logger.info(" > CPC nin durumu : " + getSpaceWideRegistry().getCpcReference().getExecuterThread().getState());
try {
if (TlosSpaceWide.isPersistent()) {
if (!PersistenceUtils.persistSWRegistry()) {
logger.error("Cpc persist failed, terminating !");
break;
}
}
TlosSpaceWide.changeApplicationState(AppState.INT_RUNNING);
// Cpc.dumpSpcLookupTables(getSpaceWideRegistry());
logger.info(" > CPC nin durumu : getExecuterThread().wait() : " + getSpaceWideRegistry().getCpcReference().getExecuterThread().getState());
synchronized (this.getExecuterThread()) {
this.getExecuterThread().wait();
}
logger.info(" >> Cpc notified !");
} catch (InterruptedException e) {
logger.error("Cpc failed, terminating !");
break;
}
}
TlosSpaceWide.changeApplicationState(AppState.INT_STOPPING);
terminateAllJobs(Cpc.FORCED);
logger.info("Exited Cpc notified !");
}
private void freshDataLoad(TlosProcessData tlosProcessData) throws TlosException {
logger.info(" > Hayır, ilk eleman olacak !");
/**
* Senaryo ve isler spcLookUpTable a yani senaryo agacina
* yerlestirilecek. Bunun icin islerin validasyonu da
* gerceklestirilecek.
*
**/
SpcLookupTable spcLookUpTable = prepareSpcLookupTable(tlosProcessData, logger);
/*
* scpLookUpTable olusturuldu. Olusan bu tablo PlanID ile
* iliskilendirilecek.
*/
logger.info("");
logger.info(" 9 - SPC (spcLookUpTable) senaryo ağacı, PlanID = " + tlosProcessData.getRunId() + " ile ilişkilendirilecek.");
RunInfoType runInfoType = new RunInfoType();
runInfoType.setRunId(tlosProcessData.getRunId());
runInfoType.setSpcLookupTable(spcLookUpTable);
getSpaceWideRegistry().getRunLookupTable().put(runInfoType.getRunId(), runInfoType);
logger.info(" > OK ilişkilendirildi.");
if (spcLookUpTable == null) {
logger.warn(" >>> SPC (spcLookUpTable) senaryo agaci BOS !!");
logger.info(" >>> SPC (spcLookUpTable) senaryo agaci BOS !!");
}
}
private void loadOnLiveSystem(TlosProcessData tlosProcessData) throws TlosException {
SpcLookupTable spcLookupTableNew = prepareSpcLookupTable(tlosProcessData, logger);
if(getSpaceWideRegistry().getRunLookupTable().size() < -1 || getSpaceWideRegistry().getRunLookupTable().size() > 1) {
// Ne yapmalı ??
return;
}
RunInfoType runInfoType = (RunInfoType) getSpaceWideRegistry().getRunLookupTable().values().toArray()[0];
HashMap<String, SpcInfoType> spcLookupTableOld = runInfoType.getSpcLookupTable().getTable();
runInfoType.setSpcLookupTable(null);
String oldRunId = runInfoType.getRunId();
String newRunId = tlosProcessData.getRunId();
Consolidator.compareAndConsolidateTwoTables(oldRunId, spcLookupTableNew.getTable(), spcLookupTableOld);
logger.info("");
logger.info(" 9 - SPC (spcLookUpTable) senaryo agaci, RunID = " + newRunId + " ile iliskilendirilecek.");
logger.info(" > RunID = " + newRunId + " olarak belirlendi.");
runInfoType.setRunId(newRunId);
runInfoType.setSpcLookupTable(spcLookupTableNew);
getSpaceWideRegistry().getRunLookupTable().clear();
getSpaceWideRegistry().getRunLookupTable().put(runInfoType.getRunId(), runInfoType);
logger.info(" > OK iliskilendirildi.");
TlosSpaceWide.changeApplicationState(AppState.INT_RUNNING);
}
public void loadOnLiveSystemOld(TlosProcessData tlosProcessData) throws TlosException {
ConcurrencyAnalyzer.checkAndCleanSpcLookUpTables(getSpaceWideRegistry().getRunLookupTable(), logger);
logger.info(" > Evet, " + getSpaceWideRegistry().getRunLookupTable().size() + ". eleman olacak !");
SpcLookupTable spcLookupTableNew = prepareSpcLookupTable(tlosProcessData, logger);
for (String runId : getSpaceWideRegistry().getRunLookupTable().keySet()) {
RunInfoType runInfoType = getSpaceWideRegistry().getRunLookupTable().get(runId);
HashMap<String, SpcInfoType> spcLookupTableOld = runInfoType.getSpcLookupTable().getTable();
ConcurrencyAnalyzer.checkConcurrency(runId, spcLookupTableNew.getTable(), spcLookupTableOld);
}
logger.info("");
logger.info(" 9 - SPC (spcLookUpTable) senaryo agaci, PlanID = " + tlosProcessData.getRunId() + " ile iliskilendirilecek.");
RunInfoType runInfoType = new RunInfoType();
logger.info(" > Instance ID = " + tlosProcessData.getRunId() + " olarak belirlendi.");
runInfoType.setRunId(tlosProcessData.getRunId());
runInfoType.setSpcLookupTable(spcLookupTableNew);
getSpaceWideRegistry().getRunLookupTable().put(runInfoType.getRunId(), runInfoType);
logger.info(" > OK iliskilendirildi.");
}
private void handleDailyExecution() throws TlosException {
TlosProcessData tlosProcessData = getSpaceWideRegistry().getTlosProcessData();
initParameters();
if (getSpaceWideRegistry().getRunLookupTable().size() == 0) {
freshDataLoad(tlosProcessData);
} else {
loadOnLiveSystem(tlosProcessData);
}
return;
}
private void handleRecoverdExecution() throws TlosFatalException {
for (String runId : getSpaceWideRegistry().getRunLookupTable().keySet()) {
RunInfoType runInfoType = getSpaceWideRegistry().getRunLookupTable().get(runId);
HashMap<String, SpcInfoType> spcLookupTable = runInfoType.getSpcLookupTable().getTable();
for (String spcId : spcLookupTable.keySet()) {
TlosSWPathType tlosSWPathType = new TlosSWPathType(spcId);
Spc spc = new Spc(tlosSWPathType.getRunId(), tlosSWPathType.getAbsolutePath(), getSpaceWideRegistry(), null, isUserSelectedRecover, false);
LiveStateInfo myLiveStateInfo = LiveStateInfo.Factory.newInstance();
myLiveStateInfo.setStateName(StateName.PENDING);
myLiveStateInfo.setSubstateName(SubstateName.IDLED);
myLiveStateInfo.setStatusName(StatusName.BYTIME);
spc.setLiveStateInfo(myLiveStateInfo);
Thread thread = new Thread(spc);
spc.setExecuterThread(thread);
SpcInfoType spcInfoType = spcLookupTable.get(spcId);
spcInfoType.getScenario().getManagement().getConcurrencyManagement().setRunningId(runInfoType.getRunId());
spc.setBaseScenarioInfos(spcInfoType.getScenario().getBaseScenarioInfos());
spc.setDependencyList(spcInfoType.getScenario().getDependencyList());
spc.setScenarioStatusList(spcInfoType.getScenario().getScenarioStatusList());
spc.setAlarmPreference(spcInfoType.getScenario().getAlarmPreference());
spc.setManagement(spcInfoType.getScenario().getManagement());
spc.setAdvancedScenarioInfos(spcInfoType.getScenario().getAdvancedScenarioInfos());
spc.setLocalParameters(spcInfoType.getScenario().getLocalParameters());
spc.setJsName(spcInfoType.getJsName());
spc.setConcurrent(spcInfoType.isConcurrent());
spc.setComment(spcInfoType.getComment());
spc.setUserId(spcInfoType.getUserId());
spcInfoType.setSpcReferance(spc);
spcLookupTable.put(spcId, spcInfoType);
}
}
return;
}
// public boolean isRegular() {
// return isRegular;
// }
//
// public void setRegular(boolean isRegular) {
// this.isRegular = isRegular;
// }
}
|
3e111cd9c7cf6e9e5afda349597c414c877880bf | 670 | java | Java | dagger-comparison/src/main/java/motif/daggercomparison/motif/RootView.java | runningcode/motif | a18c9ebbea7b12f2feeee843bfe2370aac63884e | [
"Apache-2.0"
] | null | null | null | dagger-comparison/src/main/java/motif/daggercomparison/motif/RootView.java | runningcode/motif | a18c9ebbea7b12f2feeee843bfe2370aac63884e | [
"Apache-2.0"
] | null | null | null | dagger-comparison/src/main/java/motif/daggercomparison/motif/RootView.java | runningcode/motif | a18c9ebbea7b12f2feeee843bfe2370aac63884e | [
"Apache-2.0"
] | null | null | null | 27.916667 | 105 | 0.746269 | 7,209 | package motif.daggercomparison.motif;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import motif.sample.R;
public class RootView extends FrameLayout {
public RootView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RootView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public static RootView create(ViewGroup parent) {
return (RootView) LayoutInflater.from(parent.getContext()).inflate(R.layout.root, parent, false);
}
}
|
3e111d42684986f6e09d5cf21de5f0d3f7b838cc | 2,340 | java | Java | 2 Hands-on Bounded Contexts/src/accounting/AccountManagementService.java | alperhankendi/ddd-banking-example | 406bf8fe7deb4da73651b0906ddffa657d26e725 | [
"MIT"
] | null | null | null | 2 Hands-on Bounded Contexts/src/accounting/AccountManagementService.java | alperhankendi/ddd-banking-example | 406bf8fe7deb4da73651b0906ddffa657d26e725 | [
"MIT"
] | null | null | null | 2 Hands-on Bounded Contexts/src/accounting/AccountManagementService.java | alperhankendi/ddd-banking-example | 406bf8fe7deb4da73651b0906ddffa657d26e725 | [
"MIT"
] | 1 | 2021-11-26T16:47:10.000Z | 2021-11-26T16:47:10.000Z | 32.5 | 106 | 0.757692 | 7,210 | package accounting;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import credit.CreditService;
public class AccountManagementService {
private Map<Integer, Customer> customerList = new HashMap<Integer, Customer>();
private int customerNumberCounter = 0;
private Map<Integer, Account> accountList = new HashMap<Integer, Account>();
private int accountNumberCounter = 0;
private CreditService creditService = null;
public AccountManagementService(CreditService creditService) {
this.creditService = creditService;
}
public Customer newCustomer(String firstName, String familyName, LocalDate dateOfBirth) {
Customer customer = new Customer(firstName, familyName, dateOfBirth, customerNumberCounter++);
customerList.put(customer.getCustomerNumber(), customer);
creditService.newCustomer(customer.getFirstName(), customer.getFamilyName(), customer.getDateOfBirth(),
customer.getCustomerNumber());
return customer;
}
public Account newAccount(float balance, Customer customer) {
Account account = new Account(accountNumberCounter++, customer);
account.setBalance(balance);
accountList.put(account.getAccountnumber(), account);
customer.getAccountList().add(account);
return account;
}
public List<Account> getAccountList() {
return new ArrayList<Account>(accountList.values());
}
public List<Customer> getCustomerList() {
return new ArrayList<Customer>(customerList.values());
}
public void transferMoney(float amount, int debitorAccountNumber, int creditorAccountNumber) {
float balance = accountList.get(debitorAccountNumber).getBalance();
balance = balance - amount;
accountList.get(debitorAccountNumber).setBalance(balance);
balance = accountList.get(creditorAccountNumber).getBalance();
balance = balance + amount;
accountList.get(creditorAccountNumber).setBalance(balance);
}
public Set<Integer> getAccountNumberList() {
return accountList.keySet();
}
public Account getAccount(int accountNumber) {
return accountList.get(accountNumber);
}
public Customer getCustomer(int accountNumber) {
Customer customer = accountList.get(accountNumber).getAccountowner();
return customer;
}
}
|
3e111d69c835b9d5f0851273104e62d3ec9f6763 | 3,058 | java | Java | core/src/main/java/com/opensymphony/xwork2/interceptor/WithLazyParams.java | melanj/struts | f0b24d17da4751666f12bc498c73c20d91e29558 | [
"Apache-2.0"
] | 1,330 | 2015-01-01T12:04:11.000Z | 2022-03-31T06:18:36.000Z | core/src/main/java/com/opensymphony/xwork2/interceptor/WithLazyParams.java | melanj/struts | f0b24d17da4751666f12bc498c73c20d91e29558 | [
"Apache-2.0"
] | 447 | 2015-01-20T04:00:10.000Z | 2022-03-15T13:32:57.000Z | core/src/main/java/com/opensymphony/xwork2/interceptor/WithLazyParams.java | melanj/struts | f0b24d17da4751666f12bc498c73c20d91e29558 | [
"Apache-2.0"
] | 955 | 2015-01-05T09:07:43.000Z | 2022-03-27T06:00:27.000Z | 37.292683 | 140 | 0.706998 | 7,211 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.opensymphony.xwork2.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.ognl.OgnlUtil;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.TextParser;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import java.util.Map;
/**
* Interceptors marked with this interface won't be fully initialised during initialisation.
* Appropriated params will be injected just before usage of the interceptor.
*
* Please be aware that in such case {@link Interceptor#init()} method must be prepared for this.
*
* @since 2.5.9
*/
public interface WithLazyParams {
class LazyParamInjector {
protected OgnlUtil ognlUtil;
protected TextParser textParser;
protected ReflectionProvider reflectionProvider;
private final TextParseUtil.ParsedValueEvaluator valueEvaluator;
public LazyParamInjector(final ValueStack valueStack) {
valueEvaluator = new TextParseUtil.ParsedValueEvaluator() {
public Object evaluate(String parsedValue) {
return valueStack.findValue(parsedValue); // no asType !!!
}
};
}
@Inject
public void setTextParser(TextParser textParser) {
this.textParser = textParser;
}
@Inject
public void setReflectionProvider(ReflectionProvider reflectionProvider) {
this.reflectionProvider = reflectionProvider;
}
@Inject
public void setOgnlUtil(OgnlUtil ognlUtil) {
this.ognlUtil = ognlUtil;
}
public Interceptor injectParams(Interceptor interceptor, Map<String, String> params, ActionContext invocationContext) {
for (Map.Entry<String, String> entry : params.entrySet()) {
Object paramValue = textParser.evaluate(new char[]{ '$' }, entry.getValue(), valueEvaluator, TextParser.DEFAULT_LOOP_COUNT);
ognlUtil.setProperty(entry.getKey(), paramValue, interceptor, invocationContext.getContextMap());
}
return interceptor;
}
}
}
|
3e111e1a59a7ad722c53170af794329f45a57b70 | 3,331 | java | Java | src/main/java/digitalTrafficLightControlSimulationPlugin/Pedestrian.java | dload22/TrafficLightControl | 6b382d7023530297a8fb65592379fb57130c1adb | [
"MIT"
] | null | null | null | src/main/java/digitalTrafficLightControlSimulationPlugin/Pedestrian.java | dload22/TrafficLightControl | 6b382d7023530297a8fb65592379fb57130c1adb | [
"MIT"
] | null | null | null | src/main/java/digitalTrafficLightControlSimulationPlugin/Pedestrian.java | dload22/TrafficLightControl | 6b382d7023530297a8fb65592379fb57130c1adb | [
"MIT"
] | null | null | null | 23.293706 | 102 | 0.667968 | 7,212 | package digitalTrafficLightControlSimulationPlugin;
import java.util.*;
import java.awt.geom.*;
import java.awt.*;
public class Pedestrian {
private PedestrianState pedestrianState;
private PedestrianType pedestrianType;
private GeneralPath pedestrianShape;
public int posX = 0;
public int posY = 0;
public boolean colision = false;
private static final Random random = new Random();
/**
* Creates a new pedestrian instance
*/
public Pedestrian () {
this.pedestrianState = PedestrianState.WAITING;
this.pedestrianType = randomEnum(PedestrianType.class);
this.pedestrianShape = GeneratePedestrian(getWidth(), getHeight(), this.pedestrianType);
updatePosition(550 - getWidth()/2, 2000);
}
public PedestrianState getPedestrianState() {
return pedestrianState;
}
public void setPedestrianState(PedestrianState pedestrianState) {
this.pedestrianState = pedestrianState;
}
public PedestrianType getPedestrianType() {
return pedestrianType;
}
public Shape getPedestrianShape() {
return pedestrianShape;
}
public void updatePosition(int dX, int dY) {
this.posX += dX;
this.posY += dY;
AffineTransform at = new AffineTransform();
at.setToTranslation(dX, dY);
this.pedestrianShape.transform(at);
}
//returns a random state from given enum
public static <T extends Enum<?>> T randomEnum(Class<T> clazz){
int x = random.nextInt(clazz.getEnumConstants().length);
return clazz.getEnumConstants()[x];
}
public int getWidth() {
switch (pedestrianType) {
case NORMAL:
return 50;
case MEXICAN:
return 80;
case BASEBALLCAP:
return 50;
default:
return 0;
}
}
public int getHeight() {
switch (pedestrianType) {
case NORMAL:
return 50;
case MEXICAN:
return 80;
case BASEBALLCAP:
return 50;
default:
return 0;
}
}
public int getSpeed() {
switch (pedestrianType) {
case NORMAL:
return 10;
case MEXICAN:
return 10;
case BASEBALLCAP:
return 10;
default:
return 0;
}
}
//paint pedestrians
private GeneralPath GeneratePedestrian(double width, double height, PedestrianType pedestrianType) {
GeneralPath p = new GeneralPath();
Ellipse2D ellipse = new Ellipse2D.Double();
Arc2D arc = new Arc2D.Double();
switch (pedestrianType) {
case NORMAL:
ellipse.setFrame(0, 0, width, height/2);
p.append(ellipse, false);
ellipse.setFrame(0.3*width, 0, 0.4*width, 0.4*height);
p.append(ellipse, false);
break;
case MEXICAN:
// generate path for pedestrian with sombrero
ellipse.setFrame(0, 0, width, height);
p.append(ellipse, false);
break;
case BASEBALLCAP:
// generate path for pedestrian with baseball cap
ellipse.setFrame(0, 0, width, height/2);
p.append(ellipse, false);
ellipse.setFrame(0.3*width, 0, 0.4*width, 0.4*height);
p.append(ellipse, false);
arc.setArc(0.3*width, -0.3*height, 0.4*width, 0.6*height, 0, 180, Arc2D.OPEN);
p.append(arc, false);
break;
default:
break;
}
return p;
}
}
enum PedestrianState {
WAITING, ENTER_CROSSING, BEFORE_PEDESTRIAN_LIGHT, WALK_IN, DELETE;
}
enum PedestrianType {
NORMAL, MEXICAN, BASEBALLCAP;
} |
3e111e3ddddbb85874b92a34dafd96fc946a3954 | 11,859 | java | Java | fordel-web/src/test/java/no/nav/foreldrepenger/fordel/web/app/konfig/RestApiInputValideringDtoTest.java | navikt/fpfordel | a4870890d15f72d402e0eac566ce1afaf6d127b1 | [
"MIT"
] | 2 | 2021-09-02T11:37:03.000Z | 2021-09-23T21:38:19.000Z | fordel-web/src/test/java/no/nav/foreldrepenger/fordel/web/app/konfig/RestApiInputValideringDtoTest.java | navikt/fpfordel | a4870890d15f72d402e0eac566ce1afaf6d127b1 | [
"MIT"
] | 1,342 | 2019-12-15T10:42:34.000Z | 2022-03-25T08:48:16.000Z | fordel-web/src/test/java/no/nav/foreldrepenger/fordel/web/app/konfig/RestApiInputValideringDtoTest.java | navikt/fpfordel | a4870890d15f72d402e0eac566ce1afaf6d127b1 | [
"MIT"
] | 1 | 2020-02-19T11:58:01.000Z | 2020-02-19T11:58:01.000Z | 41.95053 | 150 | 0.642941 | 7,213 | package no.nav.foreldrepenger.fordel.web.app.konfig;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.json.JsonValue;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import javax.validation.Valid;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import no.nav.foreldrepenger.fordel.IndexClasses;
import no.nav.vedtak.isso.config.ServerInfo;
lyhxr@example.com)
@Disabled
public class RestApiInputValideringDtoTest extends RestApiTester {
private Class<?> dto;
// @Parameterized.Parameters(name = "Validerer Dto - {0}")
public static Collection<Object[]> getDtos() {
String prevLBUrl = System.setProperty(ServerInfo.PROPERTY_KEY_LOADBALANCER_URL, "http://localhost:8090");
Set<Object[]> alleDtoTyper = finnAlleDtoTyper().stream().map(c -> new Object[] { c.getName(), c }).collect(Collectors.toSet());
if (prevLBUrl != null) {
System.setProperty(ServerInfo.PROPERTY_KEY_LOADBALANCER_URL, prevLBUrl);
}
return alleDtoTyper;
}
public RestApiInputValideringDtoTest(@SuppressWarnings("unused") String name, Class<?> dto) {
this.dto = dto;
}
/**
* IKKE ignorer eller fjern denne testen, den sørger for at inputvalidering er i
* orden for REST-grensesnittene
* <p>
* Kontakt Team Humle hvis du trenger hjelp til å endre koden din slik at den
* går igjennom her
*/
@Test
public void alle_felter_i_objekter_som_brukes_som_inputDTO_skal_enten_ha_valideringsannotering_eller_være_av_godkjent_type() throws Exception {
Set<Class<?>> validerteKlasser = new HashSet<>(); // trengs for å unngå løkker og unngå å validere samme klasse flere ganger
// dobbelt
validerRekursivt(validerteKlasser, dto, null);
}
private static final List<Class<? extends Object>> ALLOWED_ENUM_ANNOTATIONS = Arrays.asList(JsonProperty.class, JsonValue.class, JsonIgnore.class,
Valid.class, Null.class, NotNull.class);
@SuppressWarnings("rawtypes")
private static final Map<Class, List<List<Class<? extends Annotation>>>> UNNTATT_FRA_VALIDERING = new HashMap<>() {
{
put(boolean.class, singletonList(emptyList()));
put(Boolean.class, singletonList(emptyList()));
// LocalDate og LocalDateTime har egne deserializers
put(LocalDate.class, singletonList(emptyList()));
put(LocalDateTime.class, singletonList(emptyList()));
// Enforces av UUID selv
put(UUID.class, singletonList(emptyList()));
}
};
@SuppressWarnings("rawtypes")
private static final Map<Class, List<List<Class<? extends Annotation>>>> VALIDERINGSALTERNATIVER = new HashMap<>() {
{
put(String.class, asList(
asList(Pattern.class, Size.class),
asList(Pattern.class),
singletonList(Digits.class)));
put(Long.class, asList(
asList(Min.class, Max.class),
asList(Digits.class)));
put(long.class, asList(
asList(Min.class, Max.class),
asList(Digits.class)));
put(Integer.class, singletonList(
asList(Min.class, Max.class)));
put(int.class, singletonList(
asList(Min.class, Max.class)));
put(BigDecimal.class, asList(
asList(Min.class, Max.class, Digits.class),
asList(DecimalMin.class, DecimalMax.class, Digits.class)));
putAll(UNNTATT_FRA_VALIDERING);
}
};
private static List<List<Class<? extends Annotation>>> getVurderingsalternativer(Field field) {
Class<?> type = field.getType();
if (field.getType().isEnum()) {
return Collections.singletonList(Collections.singletonList(Valid.class));
} else if (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) {
if (brukerGenerics(field)) {
Type[] args = ((ParameterizedType) field.getGenericType()).getActualTypeArguments();
if (Arrays.asList(args).stream().allMatch(t -> UNNTATT_FRA_VALIDERING.containsKey(t))) {
return Collections.singletonList(Arrays.asList(Size.class));
}
}
return singletonList(Arrays.asList(Valid.class, Size.class));
}
return VALIDERINGSALTERNATIVER.get(type);
}
private static Set<Class<?>> finnAlleDtoTyper() {
Set<Class<?>> parametre = new TreeSet<>(Comparator.comparing(Class::getName));
for (Method method : finnAlleRestMetoder()) {
parametre.addAll(Arrays.asList(method.getParameterTypes()));
for (Type type : method.getGenericParameterTypes()) {
if (type instanceof ParameterizedType) {
ParameterizedType genericTypes = (ParameterizedType) type;
for (Type gen : genericTypes.getActualTypeArguments()) {
parametre.add((Class<?>) gen);
}
}
}
}
Set<Class<?>> filtreteParametre = new TreeSet<>(Comparator.comparing(Class::getName));
for (Class<?> klasse : parametre) {
if (klasse.getName().startsWith("java")) {
// ikke sjekk nedover i innebygde klasser, det skal brukes annoteringer på
// tidligere tidspunkt
continue;
}
filtreteParametre.add(klasse);
}
return filtreteParametre;
}
private static void validerRekursivt(Set<Class<?>> besøkteKlasser, Class<?> klasse, Class<?> forrigeKlasse) throws URISyntaxException {
if (besøkteKlasser.contains(klasse)) {
return;
}
ProtectionDomain protectionDomain = klasse.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource == null) {
// system klasse
return;
}
besøkteKlasser.add(klasse);
if ((klasse.getAnnotation(Entity.class) != null) || (klasse.getAnnotation(MappedSuperclass.class) != null)) {
throw new AssertionError("Klassen " + klasse + " er en entitet, kan ikke brukes som DTO. Brukes i " + forrigeKlasse);
}
URL klasseLocation = codeSource.getLocation();
for (Class<?> subklasse : IndexClasses.getIndexFor(klasseLocation.toURI()).getSubClassesWithAnnotation(klasse, JsonTypeName.class)) {
validerRekursivt(besøkteKlasser, subklasse, forrigeKlasse);
}
for (Field field : getRelevantFields(klasse)) {
if (field.getAnnotation(JsonIgnore.class) != null) {
continue; // feltet blir hverken serialisert elle deserialisert, unntas fra sjekk
}
if (field.getType().isEnum()) {
validerEnum(field);
continue; // enum er OK
}
if (getVurderingsalternativer(field) != null) {
validerRiktigAnnotert(field); // har konfigurert opp spesifikk validering
} else if (field.getType().getName().startsWith("java")) {
throw new AssertionError(
"Feltet " + field + " har ikke påkrevde annoteringer. Trenger evt. utvidelse av denne testen for å akseptere denne typen.");
} else {
validerHarValidAnnotering(field);
validerRekursivt(besøkteKlasser, field.getType(), forrigeKlasse);
}
if (brukerGenerics(field)) {
validerRekursivt(besøkteKlasser, field.getType(), forrigeKlasse);
for (Class<?> klazz : genericTypes(field)) {
validerRekursivt(besøkteKlasser, klazz, forrigeKlasse);
}
}
}
}
private static void validerEnum(Field field) {
validerRiktigAnnotert(field);
List<Annotation> illegal = Arrays.asList(field.getAnnotations()).stream().filter(a -> !ALLOWED_ENUM_ANNOTATIONS.contains(a.annotationType()))
.collect(Collectors.toList());
if (!illegal.isEmpty()) {
throw new AssertionError("Ugyldige annotasjoner funnet på [" + field + "]: " + illegal);
}
}
private static void validerHarValidAnnotering(Field field) {
if (field.getAnnotation(Valid.class) == null) {
throw new AssertionError("Feltet " + field + " må ha @Valid-annotering.");
}
}
private static Set<Class<?>> genericTypes(Field field) {
Set<Class<?>> klasser = new HashSet<>();
ParameterizedType type = (ParameterizedType) field.getGenericType();
for (Type t : type.getActualTypeArguments()) {
klasser.add((Class<?>) t);
}
return klasser;
}
private static boolean brukerGenerics(Field field) {
return field.getGenericType() instanceof ParameterizedType;
}
private static Set<Field> getRelevantFields(Class<?> klasse) {
Set<Field> fields = new LinkedHashSet<>();
while (!klasse.isPrimitive() && !klasse.getName().startsWith("java")) {
fields.addAll(fjernStaticFields(Arrays.asList(klasse.getDeclaredFields())));
klasse = klasse.getSuperclass();
}
return fields;
}
private static Collection<Field> fjernStaticFields(List<Field> fields) {
return fields.stream().filter(f -> !Modifier.isStatic(f.getModifiers())).collect(Collectors.toList());
}
private static void validerRiktigAnnotert(Field field) {
List<List<Class<? extends Annotation>>> alternativer = getVurderingsalternativer(field);
for (List<Class<? extends Annotation>> alternativ : alternativer) {
boolean harAlleAnnoteringerForAlternativet = true;
for (Class<? extends Annotation> annotering : alternativ) {
if (field.getAnnotation(annotering) == null) {
harAlleAnnoteringerForAlternativet = false;
}
}
if (harAlleAnnoteringerForAlternativet) {
return;
}
}
throw new IllegalArgumentException("Feltet " + field + " har ikke påkrevde annoteringer: " + alternativer);
}
}
|
3e111e7533fcc07fc7d83b20091a3f62289b0b72 | 151 | java | Java | complex-service/src/test/java/com/liumapp/archetype/separation/service/package-info.java | liumapp/mybatis-with-complex-source | 6ca476471368a7977c4a5f3eb9e5026dc834b2b7 | [
"Apache-2.0"
] | null | null | null | complex-service/src/test/java/com/liumapp/archetype/separation/service/package-info.java | liumapp/mybatis-with-complex-source | 6ca476471368a7977c4a5f3eb9e5026dc834b2b7 | [
"Apache-2.0"
] | null | null | null | complex-service/src/test/java/com/liumapp/archetype/separation/service/package-info.java | liumapp/mybatis-with-complex-source | 6ca476471368a7977c4a5f3eb9e5026dc834b2b7 | [
"Apache-2.0"
] | 1 | 2019-03-04T20:36:12.000Z | 2019-03-04T20:36:12.000Z | 25.833333 | 45 | 0.703226 | 7,214 | /**
* Created by liumapp on 9/28/17.
* E-mail:dycjh@example.com
* home-page:http://www.liumapp.com
*/
package com.liumapp.demo.mybatis.complex.api; |
3e111f64365ecf5f33dd6af639d1c8d27696edfa | 227 | java | Java | tb/b9/b9.m5.rl29/src/test/java/d/rl/tst/sui/s1.java | yuanyuanli66/jgrovelib | 5af18ab154701f5e061b20b82fab679691768db7 | [
"Apache-2.0"
] | null | null | null | tb/b9/b9.m5.rl29/src/test/java/d/rl/tst/sui/s1.java | yuanyuanli66/jgrovelib | 5af18ab154701f5e061b20b82fab679691768db7 | [
"Apache-2.0"
] | null | null | null | tb/b9/b9.m5.rl29/src/test/java/d/rl/tst/sui/s1.java | yuanyuanli66/jgrovelib | 5af18ab154701f5e061b20b82fab679691768db7 | [
"Apache-2.0"
] | null | null | null | 14.1875 | 32 | 0.713656 | 7,215 | package d.rl.tst.sui;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import d.rl.tst.t1a;
import d.rl.tst.t1c;
@RunWith(Suite.class)
@Suite.SuiteClasses({
t1a.class,
t1c.class
})
public class s1 {}
|
3e11210d75f70f9bb566431ba7a7bd3be627745b | 2,030 | java | Java | src/com/fit/testdatagen/testdataexec/TestdriverGenerationforC.java | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null | src/com/fit/testdatagen/testdataexec/TestdriverGenerationforC.java | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null | src/com/fit/testdatagen/testdataexec/TestdriverGenerationforC.java | ducanhnguyen/cft4cpp-for-dummy | d7599f95e688943f52f6a9a0b729f16011997eb8 | [
"Apache-2.0"
] | null | null | null | 30.757576 | 103 | 0.731527 | 7,216 | package com.fit.testdatagen.testdataexec;
import com.fit.config.ISettingv2;
import com.fit.config.Paths;
import com.fit.tree.object.INode;
import com.fit.utils.Utils;
public class TestdriverGenerationforC extends TestdriverGeneration {
@Override
public void generate() throws Exception {
String oldContent = Utils.readFileContent(Utils.getSourcecodeFile(functionNode).getAbsolutePath());
String include = generateIncludes();
String instrumentedFunction = generateInstrumentedFunction();
instrumentedFunction = removeStaticInFunctionDefinition(instrumentedFunction);
/**
* is this function in unname(annonymous) namespace ?
*/
if (getFunction().isChildrenOfUnnameNamespace()) {
instrumentedFunction = "namespace {" + instrumentedFunction + "}";
}
String main = generateMain(initialization, functionNode);
String testDriver = "writeContentToFile(\"" + Paths.CURRENT_PROJECT.CURRENT_TESTDRIVER_EXECUTION_PATH
+ "\", build);";
String append = include + "\r" + ITestdriverGeneration.C.WRITTER + "\r" + "\r"
+ ITestdriverGeneration.C.MARK_BEGIN + testDriver + ITestdriverGeneration.C.MARK_END + "\r" + "\r"
+ instrumentedFunction + "\r" + main;
this.testDriver = oldContent + append;
}
private String generateMain(String randomValues, INode testedFunction) {
return "int main(){" + randomValues + functionCall + "return 0;}";
}
private String generateIncludes() {
String include = "";
switch (Paths.CURRENT_PROJECT.TYPE_OF_PROJECT) {
case ISettingv2.PROJECT_DEV_CPP:
case ISettingv2.PROJECT_ECLIPSE: {
final String[] INCLUDE_FOR_DEVC_C = new String[] { "#include <stdio.h>", "#include <memory.h>",
"#include <stdlib.h>", "#include <string.h>" };
for (String item : INCLUDE_FOR_DEVC_C)
include += item + "\r";
break;
}
case ISettingv2.PROJECT_VISUALSTUDIO:
break;
case ISettingv2.PROJECT_CODEBLOCK:
break;
case ISettingv2.PROJECT_UNKNOWN_TYPE:
break;
case ISettingv2.PROJECT_CUSTOMMAKEFILE:
break;
}
return include;
}
}
|
3e112120b9f3588e5f33d54721e3a81b42279d3a | 11,793 | java | Java | src/de/l3s/eventkg/evaluation/TimeFusionEvaluationResults.java | rpatil524/eventkg | d27a6262f9ade9a727b83d6f121615580166c1ae | [
"MIT"
] | 30 | 2017-06-19T13:21:49.000Z | 2022-03-18T09:07:52.000Z | src/de/l3s/eventkg/evaluation/TimeFusionEvaluationResults.java | rpatil524/eventkg | d27a6262f9ade9a727b83d6f121615580166c1ae | [
"MIT"
] | 7 | 2018-11-14T20:51:04.000Z | 2022-03-04T10:56:01.000Z | src/de/l3s/eventkg/evaluation/TimeFusionEvaluationResults.java | rpatil524/eventkg | d27a6262f9ade9a727b83d6f121615580166c1ae | [
"MIT"
] | 7 | 2018-07-13T06:55:28.000Z | 2021-03-11T07:57:46.000Z | 33.126404 | 111 | 0.671076 | 7,217 | package de.l3s.eventkg.evaluation;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import de.l3s.eventkg.integration.model.DateGranularity;
import de.l3s.eventkg.integration.model.DateWithGranularity;
import de.l3s.eventkg.integration.model.Event;
import de.l3s.eventkg.integration.model.relation.DataSet;
import de.l3s.eventkg.meta.Source;
import de.l3s.eventkg.util.MapUtil;
public class TimeFusionEvaluationResults {
private Map<String, DataSet> dataSets = new HashMap<String, DataSet>();
private Map<String, Event> events = new HashMap<String, Event>();
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) {
TimeFusionEvaluationResults tfer = new TimeFusionEvaluationResults();
String dataFileName = "/home/simon/Documents/EventKB/time_evaluation_data/time_fusion_all.tsv";
String evaluationDataFolderName = "/home/simon/Documents/EventKB/time_evaluation_data/results/";
tfer.loadData(dataFileName);
tfer.loadEvaluationData(evaluationDataFolderName);
tfer.evaluate();
}
private void loadData(String dataFileName) {
LineIterator it = null;
try {
it = FileUtils.lineIterator(new File(dataFileName), "UTF-8");
while (it.hasNext()) {
String line = it.nextLine();
String[] parts = line.split("\t");
Event event = new Event();
event.setId(parts[0]);
for (int i = 1; i < parts.length; i++) {
String[] parts2 = parts[i].split(";");
String sources = parts2[0];
DateWithGranularity startDate = null;
DateWithGranularity endDate = null;
try {
if (!parts2[1].equals("-"))
startDate = new DateWithGranularity(TimeFusionEvaluation.dateFormat.parse(parts2[1]),
DateGranularity.DAY);
if (!parts2[2].equals("-"))
endDate = new DateWithGranularity(TimeFusionEvaluation.dateFormat.parse(parts2[2]),
DateGranularity.DAY);
} catch (ParseException e) {
e.printStackTrace();
}
for (String source : sources.split(", ")) {
event.addStartTime(startDate, getDataSet(source));
event.addEndTime(endDate, getDataSet(source));
}
events.put(event.getId(), event);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
it.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadEvaluationData(String evaluationDataFolderName) {
File dir = new File(evaluationDataFolderName);
File[] directoryListing = dir.listFiles();
Map<String, Integer> sources = new HashMap<String, Integer>();
int sum = 0;
for (File file : directoryListing) {
LineIterator it = null;
try {
it = FileUtils.lineIterator(file, "UTF-8");
boolean firstLine = true;
while (it.hasNext()) {
String line = it.nextLine();
if (firstLine) {
firstLine = false;
continue;
}
String[] parts = line.split("\t");
Event event = events.get(parts[0]);
String source1 = getSource(parts[2]);
String source2 = getSource(parts[4]);
if (!sources.containsKey(source1))
sources.put(source1, 0);
if (!sources.containsKey(source2))
sources.put(source2, 0);
sources.put(source1, sources.get(source1) + 1);
sources.put(source2, sources.get(source2) + 1);
sum += 2;
DateWithGranularity startDate = null;
DateWithGranularity endDate = null;
try {
startDate = new DateWithGranularity(dateFormat.parse(parts[1]), DateGranularity.DAY);
} catch (ParseException e) {
System.err.println("Unparsebale date: " + parts[1]);
continue;
}
try {
endDate = new DateWithGranularity(dateFormat.parse(parts[3]), DateGranularity.DAY);
} catch (ParseException e) {
System.err.println("Unparsebale date: " + parts[3]);
continue;
}
event.addStartTime(startDate, getDataSet("user"));
event.addEndTime(endDate, getDataSet("user"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
it.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(sum);
System.out.println("--- Sources ---");
for (String source : MapUtil.sortByValueDescending(sources).keySet()) {
System.out.println(source + "\t" + sources.get(source) + "\t" + (double) sources.get(source) / sum);
}
System.out.println("");
}
public static String getSource(String source) {
URL url;
try {
url = new URL(source);
return url.getHost();
} catch (MalformedURLException e) {
}
return "-";
}
private void evaluate() {
// filter s.t. only events with user annotation remain
for (Iterator<String> it = events.keySet().iterator(); it.hasNext();) {
String label = it.next();
for (Set<DataSet> dss : events.get(label).getStartTimesWithDataSets().values()) {
if (dss.contains(getDataSet("user")))
continue;
}
it.remove();
}
System.out.println("#Events with annotations: " + events.size());
Map<DataSet, Integer> correctDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> correctStartDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> correctEndDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> wrongDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> wrongStartDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> wrongEndDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> missingDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> missingStartDates = new HashMap<DataSet, Integer>();
Map<DataSet, Integer> missingEndDates = new HashMap<DataSet, Integer>();
for (DataSet dataSet : this.dataSets.values()) {
correctStartDates.put(dataSet, 0);
correctDates.put(dataSet, 0);
correctEndDates.put(dataSet, 0);
wrongDates.put(dataSet, 0);
wrongStartDates.put(dataSet, 0);
wrongEndDates.put(dataSet, 0);
missingDates.put(dataSet, 0);
missingStartDates.put(dataSet, 0);
missingEndDates.put(dataSet, 0);
}
Map<Event, Map<DataSet, Boolean>> correctInDataSet = new HashMap<Event, Map<DataSet, Boolean>>();
for (Event event : events.values()) {
correctInDataSet.put(event, new HashMap<DataSet, Boolean>());
for (DataSet dataSet : this.dataSets.values()) {
DateWithGranularity userStartDate = null;
DateWithGranularity dataStartDate = null;
for (DateWithGranularity date : event.getStartTimesWithDataSets().keySet()) {
if (event.getStartTimesWithDataSets().get(date) == getDataSet("user"))
userStartDate = date;
if (event.getStartTimesWithDataSets().get(date) == dataSet)
dataStartDate = date;
}
if (userStartDate != null && dataStartDate != null && userStartDate.equals(dataStartDate)) {
correctStartDates.put(dataSet, correctStartDates.get(dataSet) + 1);
correctDates.put(dataSet, correctDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, true);
} else if (dataStartDate == null) {
missingStartDates.put(dataSet, missingStartDates.get(dataSet) + 1);
missingDates.put(dataSet, missingDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, false);
} else {
wrongStartDates.put(dataSet, wrongStartDates.get(dataSet) + 1);
wrongDates.put(dataSet, wrongDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, false);
}
DateWithGranularity userEndDate = null;
DateWithGranularity dataEndDate = null;
for (DateWithGranularity date : event.getEndTimesWithDataSets().keySet()) {
if (event.getEndTimesWithDataSets().get(date) == getDataSet("user"))
userEndDate = date;
if (event.getEndTimesWithDataSets().get(date) == dataSet)
dataEndDate = date;
}
if (userEndDate != null && dataEndDate != null && userEndDate.equals(dataEndDate)) {
correctEndDates.put(dataSet, correctEndDates.get(dataSet) + 1);
correctDates.put(dataSet, correctDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, true);
} else if (dataEndDate == null) {
missingEndDates.put(dataSet, missingEndDates.get(dataSet) + 1);
missingDates.put(dataSet, missingDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, false);
} else {
wrongEndDates.put(dataSet, wrongEndDates.get(dataSet) + 1);
wrongDates.put(dataSet, wrongDates.get(dataSet) + 1);
correctInDataSet.get(event).put(dataSet, false);
}
}
}
System.out.println("correct\twrong\tmissing");
System.out.println("--- Start Dates ---");
for (DataSet dataSet : this.dataSets.values()) {
System.out.println(dataSet.getId() + "\t" + correctStartDates.get(dataSet) + "\t"
+ wrongStartDates.get(dataSet) + "\t" + missingStartDates.get(dataSet));
}
System.out.println("");
System.out.println("--- End Dates ---");
for (DataSet dataSet : this.dataSets.values()) {
System.out.println(dataSet.getId() + "\t" + correctEndDates.get(dataSet) + "\t" + wrongEndDates.get(dataSet)
+ "\t" + missingEndDates.get(dataSet));
}
System.out.println("");
System.out.println("--- Dates ---");
for (DataSet dataSet : this.dataSets.values()) {
System.out.println(dataSet.getId() + "\t" + correctDates.get(dataSet) + "\t" + wrongDates.get(dataSet)
+ "\t" + missingDates.get(dataSet));
}
System.out.println("--- Alll ---");
for (DataSet dataSet : this.dataSets.values()) {
System.out.println("\\multicolumn{1}{|l||}{" + dataSet.getId() + "} & " + +correctStartDates.get(dataSet)
+ " & " + wrongStartDates.get(dataSet) + " & " + missingStartDates.get(dataSet) + " & "
+ correctEndDates.get(dataSet) + " & " + wrongEndDates.get(dataSet) + " & "
+ missingEndDates.get(dataSet) + " & " + correctDates.get(dataSet) + " & " + wrongDates.get(dataSet)
+ " & " + missingDates.get(dataSet) + " \\\\ \\hline");
}
int d1Cd2C = 0;
int d1Cd2W = 0;
int d1Wd2C = 0;
int d1Wd2W = 0;
DataSet dataSet1 = this.dataSets.get("wikidata");
DataSet dataSet2 = this.dataSets.get("event_kg");
for (Event event : events.values()) {
if (correctInDataSet.get(event).get(dataSet1) && correctInDataSet.get(event).get(dataSet2))
d1Cd2C += 1;
else if (correctInDataSet.get(event).get(dataSet1) && !correctInDataSet.get(event).get(dataSet2))
d1Cd2W += 1;
else if (!correctInDataSet.get(event).get(dataSet1) && correctInDataSet.get(event).get(dataSet2))
d1Wd2C += 1;
else if (!correctInDataSet.get(event).get(dataSet1) && !correctInDataSet.get(event).get(dataSet2))
d1Wd2W += 1;
}
System.out.println("McNemar's test:");
System.out.println("\t" + dataSet2.getId() + ":correct\t" + dataSet2.getId() + ":wrong");
System.out.println(dataSet1.getId() + ":correct\t" + d1Cd2C + "\t" + d1Cd2W);
System.out.println(dataSet1.getId() + ":wrong\t" + d1Wd2C + "\t" + d1Wd2W);
}
private DataSet getDataSet(String sourceId) {
sourceId = sourceId.replace("eventKG-g:", "");
DataSet dataSet = this.dataSets.get(sourceId);
if (dataSet != null)
return dataSet;
Source source = null;
// switch (sourceId) {
// case "event_kg":
// source=Source.EVENT_KG;
// break;
// case "yago":
// source=Source.YAGO;
// break;
// case "event_kg":
// source=Source.EVENT_KG;
// break;
// case "event_kg":
// source=Source.EVENT_KG;
// break;
//
// default:
// break;
// }
dataSet = new DataSet(source, sourceId, null);
dataSets.put(sourceId, dataSet);
return dataSet;
}
}
|
3e112157b0fd4e08c1a97a4db4455e70ce72d89d | 1,080 | java | Java | library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/testdoubles/stub/HeadedSectionStub.java | Philipp91/SectionedRecyclerViewAdapter | 1ce72f69b66b0adc7fd7d338257d85a4e28c79de | [
"MIT"
] | 1 | 2019-09-05T19:10:51.000Z | 2019-09-05T19:10:51.000Z | library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/testdoubles/stub/HeadedSectionStub.java | Philipp91/SectionedRecyclerViewAdapter | 1ce72f69b66b0adc7fd7d338257d85a4e28c79de | [
"MIT"
] | null | null | null | library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/testdoubles/stub/HeadedSectionStub.java | Philipp91/SectionedRecyclerViewAdapter | 1ce72f69b66b0adc7fd7d338257d85a4e28c79de | [
"MIT"
] | null | null | null | 25.714286 | 84 | 0.694444 | 7,218 | package io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import io.github.luizgrp.sectionedrecyclerviewadapter.Section;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;
/**
* A stub of StatelessSection with header.
*/
public class HeadedSectionStub extends Section {
private final int contentItemsTotal;
public HeadedSectionStub(int contentItemsTotal) {
super(new SectionParameters.Builder(-1)
.headerResourceId(-1)
.failedResourceId(-1)
.loadingResourceId(-1)
.emptyResourceId(-1)
.build());
this.contentItemsTotal = contentItemsTotal;
}
@Override
public int getContentItemsTotal() {
return contentItemsTotal;
}
@Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return null;
}
@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
}
}
|
3e112161ee4615202c2449fb5bfdd4f76081e29e | 1,816 | java | Java | app/src/main/java/com/example/y/xhschedule/beans/Course.java | yforyoung/XHSchedule | 2975cdc894b769c87be256fac9308a4634463bbf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/y/xhschedule/beans/Course.java | yforyoung/XHSchedule | 2975cdc894b769c87be256fac9308a4634463bbf | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/y/xhschedule/beans/Course.java | yforyoung/XHSchedule | 2975cdc894b769c87be256fac9308a4634463bbf | [
"Apache-2.0"
] | null | null | null | 17.980198 | 61 | 0.601872 | 7,219 | package com.example.y.xhschedule.beans;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Course implements Serializable{
private String name;
@SerializedName("week_index")
private int week;
@SerializedName("course_index")
private int time[];
@SerializedName("week_start")
private int weekStart;
@SerializedName("week_end")
private int weekEnd;
private String teacher;
private String location;
private String zhou;
public Course() {
}
public Course(String name, String location,int weekEnd) {
this.name = name;
this.location = location;
this.weekEnd=weekEnd;
}
public String getZhou() {
return zhou;
}
public void setZhou(String zhou) {
this.zhou = zhou;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public int[] getTime() {
return time;
}
public void setTime(int[] time) {
this.time = time;
}
public int getWeekStart() {
return weekStart;
}
public void setWeekStart(int weekStart) {
this.weekStart = weekStart;
}
public int getWeekEnd() {
return weekEnd;
}
public void setWeekEnd(int weekEnd) {
this.weekEnd = weekEnd;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
|
3e112238b905fea473ec5b9474e34f0c29033977 | 3,206 | java | Java | dataprep-backend-service/src/main/java/org/talend/dataprep/exception/error/PreparationErrorCodes.java | mockstar/data-prep | eebd961dbfbab9f16f37cdb26f4ae7157fd04236 | [
"Apache-2.0"
] | 60 | 2016-02-12T18:47:00.000Z | 2021-03-21T04:35:27.000Z | dataprep-backend-service/src/main/java/org/talend/dataprep/exception/error/PreparationErrorCodes.java | mockstar/data-prep | eebd961dbfbab9f16f37cdb26f4ae7157fd04236 | [
"Apache-2.0"
] | 739 | 2016-02-15T06:14:06.000Z | 2020-04-13T09:44:43.000Z | dataprep-backend-service/src/main/java/org/talend/dataprep/exception/error/PreparationErrorCodes.java | mockstar/data-prep | eebd961dbfbab9f16f37cdb26f4ae7157fd04236 | [
"Apache-2.0"
] | 47 | 2016-02-11T18:33:14.000Z | 2021-07-31T06:49:21.000Z | 32.383838 | 88 | 0.682158 | 7,220 | // ============================================================================
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataprep.exception.error;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.talend.daikon.exception.error.ErrorCode;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CONFLICT;
import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
/**
* Preparation error codes.
*/
public enum PreparationErrorCodes implements ErrorCode {
PREPARATION_DOES_NOT_EXIST(NOT_FOUND, "id"),
PREPARATION_STEP_DOES_NOT_EXIST(NOT_FOUND, "id", "stepId"),
PREPARATION_STEP_CANNOT_BE_DELETED_IN_SINGLE_MODE(FORBIDDEN, "id", "stepId"),
PREPARATION_STEP_CANNOT_BE_REORDERED(CONFLICT),
PREPARATION_ROOT_STEP_CANNOT_BE_DELETED(FORBIDDEN, "id", "stepId"),
UNABLE_TO_SERVE_PREPARATION_CONTENT(BAD_REQUEST, "id", "version"),
UNABLE_TO_READ_PREPARATION(INTERNAL_SERVER_ERROR, "id", "version"),
PREPARATION_NAME_ALREADY_USED(CONFLICT, "id", "name", "folder"),
PREPARATION_NOT_EMPTY(CONFLICT, "id"),
FORBIDDEN_PREPARATION_CREATION(FORBIDDEN),
PREPARATION_VERSION_DOES_NOT_EXIST(NOT_FOUND, "id", "stepId"),
EXPORTED_PREPARATION_VERSION_NOT_SUPPORTED(BAD_REQUEST),
UNABLE_TO_READ_PREPARATIONS_EXPORT(BAD_REQUEST, "importVersion", "dataPrepVersion"),
PREPARATION_ALREADY_EXIST(CONFLICT, "preparationName"),
INVALID_PREPARATION(BAD_REQUEST, "message");
/** The http status to use. */
private int httpStatus;
/** Expected entries to be in the context. */
private List<String> expectedContextEntries;
/**
* default constructor.
*
* @param httpStatus the http status to use.
* @param contextEntries expected context entries.
*/
PreparationErrorCodes(HttpStatus httpStatus, String... contextEntries) {
this.httpStatus = httpStatus.value();
this.expectedContextEntries = Arrays.asList(contextEntries);
}
/**
* @return the product.
*/
@Override
public String getProduct() {
return "TDP"; //$NON-NLS-1$
}
@Override
public String getGroup() {
return "PS"; //$NON-NLS-1$
}
/**
* @return the http status.
*/
@Override
public int getHttpStatus() {
return httpStatus;
}
/**
* @return the expected context entries.
*/
@Override
public Collection<String> getExpectedContextEntries() {
return expectedContextEntries;
}
@Override
public String getCode() {
return this.toString();
}
}
|
3e1122cdeebdf2bf79347db66056c672837eb140 | 13,718 | java | Java | TankWarDemo/src/com/itwn/view/MainViewPan.java | 930614591/java.ieda | f6a3ed50322d923b71c0ecf1f9caaae02a2752dc | [
"MulanPSL-1.0"
] | null | null | null | TankWarDemo/src/com/itwn/view/MainViewPan.java | 930614591/java.ieda | f6a3ed50322d923b71c0ecf1f9caaae02a2752dc | [
"MulanPSL-1.0"
] | null | null | null | TankWarDemo/src/com/itwn/view/MainViewPan.java | 930614591/java.ieda | f6a3ed50322d923b71c0ecf1f9caaae02a2752dc | [
"MulanPSL-1.0"
] | null | null | null | 27.882114 | 114 | 0.53951 | 7,221 | package com.itwn.view;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;
import java.util.Map;
import java.util.Vector;
import javax.swing.JPanel;
import com.itwn.pojo.Boom;
import com.itwn.pojo.Bullet;
import com.itwn.pojo.hero;
public class MainViewPan extends JPanel implements KeyListener {// 键盘监听事件
private int[][] map = new int[20][20];
{
map[0] = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
map[1] = new int[] { 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0 };
map[2] = new int[] { 0, 3, 3, 3, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 3, 3, 3, 0 };
map[3] = new int[] { 0, 3, 3, 3, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 3, 3, 3, 0 };
map[4] = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
map[5] = new int[] { 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1 };
map[6] = new int[] { 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1 };
map[7] = new int[] { 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 };
map[8] = new int[] { 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0 };
map[9] = new int[] { 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0 };
map[10] = new int[] { 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0 };
map[11] = new int[] { 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 };
map[12] = new int[] { 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 };
map[13] = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
map[14] = new int[] { 4, 4, 4, 4, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 4, 4, 4, 4 };
map[15] = new int[] { 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4 };
map[16] = new int[] { 4, 4, 4, 4, 0, 0, 0, 1, 1, 1, 1, 1, 0, 2, 2, 0, 4, 4, 4, 4 };
map[17] = new int[] { 4, 4, 4, 4, 0, 2, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 4, 4, 4, 4 };
map[18] = new int[] { 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
map[19] = new int[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
}
private Image ngImgImage = Toolkit.getDefaultToolkit().getImage("image/地面.jpg");// 背景图片
// 显示背景,重写绘图的方法,打印组件
// 砖头1
private Image wallImgImage = Toolkit.getDefaultToolkit().getImage("image/砖墙.jpg");
// 铁块2
private Image stelsImage = Toolkit.getDefaultToolkit().getImage("image/铁块.jpg");
// 水
private Image warter1Img = Toolkit.getDefaultToolkit().getImage("image/水池.jpg");
// 草4
private Image grassImage = Toolkit.getDefaultToolkit().getImage("image/草地.jpg");
// 英雄
private Image heroImage = Toolkit.getDefaultToolkit().getImage("image/英雄.png");
// Boss
private Image bossImage = Toolkit.getDefaultToolkit().getImage("image/boss.png");
// 炮弹
private Image bulletImage = Toolkit.getDefaultToolkit().getImage("image/star.png");
// 爆炸效果
private Image boomImgImage;
public MainViewPan() {
// 构造方法
// 加载英雄动图线程
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
heroCount++;// 英雄动图序号
// boosCount++;//boss动图序号
if (heroCount == heroValues.length) {
heroCount = 0;// 英雄动图循环
}
// if (boosCount==bossValues.length) {
// boosCount=0;//boss动图循环
// }
repaint();// 重绘
}
};
}.start();
// boss动图线程
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// heroCount++;//英雄动图序号
boosCount++;// boss动图序号
// if (heroCount==heroValues.length) {
// heroCount=0;//英雄动图循环
// }
if (boosCount == bossValues.length) {
boosCount = 0;// boss动图循环
}
repaint();// 重绘
}
};
}.start();
// 子弹动图线程
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// heroCount++;//英雄动图序号
bullteCount++;// boss动图序号
// if (heroCount==heroValues.length) {
// heroCount=0;//英雄动图循环
// }
if (bullteCount == bulletValues.length) {
bullteCount = 0;// boss动图循环
}
repaint();// 重绘
}
};
}.start();
// 爆炸效果动图
/*
* new Thread() { public void run() { while (true) {
* boomImgImage=Toolkit.getDefaultToolkit().getImage("image/1.png");//+boomCount
* +".png" //boomCount++;
*
* if(boomCount==10){ boomCount=0; }
*
* } } }.start();
*/
}
// 初始化英雄信息
hero hero = new hero(18, 6, 1);// 初始化位置
// 英雄动态加载
private int heroCount = 0;
private int[] heroValues = { 0, 32, 64, 96 }; // 四个动作
// BOSS坐标
private int boosx = 18;
private int boosy = 9;
private int boosCount = 0;
private int[] bossValues = { 0, 34, 68, 102, 136, 170, 204, 238, 272, 306, 340, 374 };
// 炮弹
// 子弹容器
private Vector<Bullet> bListBullets = new Vector<Bullet>();
// 子弹动图
private int bullteCount = 0;
private int[] bulletValues = { 0, 192, 192 * 2, 192 * 3, 192 * 4, 192 * 5, 192 * 6, 192 * 7, 192 * 8, 192 * 9 };
// 爆炸效果集合
private Vector<Boom> boomlistBooms = new Vector<Boom>();
private int boomCount = 0;
// 绘制地图
public void drawMap(Graphics g) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == 1) {
g.drawImage(wallImgImage, j << 5, i << 5, 32, 32, this);
} else if (map[i][j] == 2) {
g.drawImage(stelsImage, j << 5, i << 5, 32, 32, this);
} else if (map[i][j] == 3) {
g.drawImage(warter1Img, j << 5, i << 5, 32, 32, this);
} else if (map[i][j] == 4) {
g.drawImage(grassImage, j << 5, i << 5, 32, 32, this);
}
}
}
}
// 绘制背景图片
public void drawBgImg(Graphics g) {
g.drawImage(ngImgImage, 0, 0, this.getWidth(), this.getHeight(), this);
}
// 绘制英雄
public void drawHero(Graphics g) {
switch (hero.getDirect()) {
case 0: {// 向上
g.drawImage(heroImage, hero.getY() << 5, hero.getX() << 5, (hero.getY() + 1) << 5, (hero.getX() + 1) << 5,
heroValues[heroCount], 64, heroValues[heroCount] + 32, 96, this);
}
break;
case 1: {// 向下
g.drawImage(heroImage, hero.getY() << 5, hero.getX() << 5, (hero.getY() + 1) << 5, (hero.getX() + 1) << 5,
heroValues[heroCount], 0, heroValues[heroCount] + 32, 32, this);
}
break;
case 2: {
// 向左
g.drawImage(heroImage, hero.getY() << 5, hero.getX() << 5, (hero.getY() + 1) << 5, (hero.getX() + 1) << 5,
heroValues[heroCount], 96, heroValues[heroCount] + 32, 128, this);
}
break;
case 3: {
// 向右
g.drawImage(heroImage, hero.getY() << 5, hero.getX() << 5, (hero.getY() + 1) << 5, (hero.getX() + 1) << 5,
heroValues[heroCount], 32, heroValues[heroCount] + 32, 64, this);
}
break;
}
}
// 绘制boss
public void drawBoss(Graphics g) {
g.drawImage(bossImage, boosy << 5, boosx << 5, (boosy + 1) << 5, (boosx + 1) << 5, 0, bossValues[boosCount], 41,
bossValues[boosCount] + 34, this);
}
// 绘制子弹
public void drawBullet(Graphics g) {
for (Bullet bullet : bListBullets) {
g.drawImage(bulletImage, bullet.getY() << 5, bullet.getX() << 5, (bullet.getY() + 1) << 5,
(bullet.getX() + 1) << 5, bulletValues[bullteCount], 0, bulletValues[bullteCount] + 192, 192, this);
}
}
// 绘制爆炸效果
public void drawBoom(Graphics g) {
for (Boom boom : boomlistBooms) {
g.drawImage(boomImgImage, boom.getY() << 5, boom.getX(), (boom.getY() + 1) << 5, (boom.getX() + 1) << 5, 0,
0, 80, 80, this);
}
}
// 重写绘图方法
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
drawBgImg(g);// 背景
drawMap(g);// 地图
drawHero(g);// 英雄
drawBoss(g);// Boss
drawBullet(g);// 子弹
drawBoom(g);// 爆炸
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// 键盘释放时事件
// 先调方向后移动
if (e.getKeyCode() == KeyEvent.VK_W) {// 向上
if (hero.getDirect() == 0) {
// int xx=hero.getX();
// int yy=hero.getY();碰撞检测and边界检测
if ((hero.getX() - 1 >= 0)
&& (map[hero.getX() - 1][hero.getY()] == 0 || map[hero.getX() - 1][hero.getY()] == 4))
hero.setX(hero.getX() - 1);// 如果本来就是向上,就直接移动
} else {
// 如果不是就先转向,下一步才能移动
hero.setDirect(0);
}
}
if (e.getKeyCode() == KeyEvent.VK_S) {// 向下
if (hero.getDirect() == 1) {// 碰撞检测and边界检测
if ((hero.getX() + 1 < map.length)
&& (map[hero.getX() + 1][hero.getY()] == 0 || map[hero.getX() + 1][hero.getY()] == 4))
hero.setX(hero.getX() + 1);// 如果本来就是向上,就直接移动
} else {
// 如果不是就先转向,下一步才能移动
hero.setDirect(1);
}
}
if (e.getKeyCode() == KeyEvent.VK_A) {// 向左
if (hero.getDirect() == 2) {// 碰撞检测and边界检测
if ((hero.getY() - 1 >= 0)
&& (map[hero.getX()][hero.getY() - 1] == 0 || map[hero.getX()][hero.getY() - 1] == 4))
hero.setY(hero.getY() - 1);// 如果本来就是向上,就直接移动
} else {
// 如果不是就先转向,下一步才能移动
hero.setDirect(2);
}
}
if (e.getKeyCode() == KeyEvent.VK_D) {// 向右
if (hero.getDirect() == 3) {// fuck teh 碰撞检测and边界检测
if ((hero.getY() + 1 < map[hero.getX()].length)
&& (map[hero.getX()][hero.getY() + 1] == 0 || map[hero.getX()][hero.getY() + 1] == 4))
hero.setY(hero.getY() + 1);// 如果本来就是向上,就直接移动
} else {
// 如果不是就先转向,下一步才能移动
hero.setDirect(3);
}
}
// 产生子弹
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
bListBullets.add(new Bullet(hero.getX(), hero.getY(), hero.getDirect()));
runBullet();
}
repaint();// 重绘界面
}
// 子弹四个方向的移动
public void runBullet() {
Bullet bullet = bListBullets.get(bListBullets.size() - 1);
switch (bullet.getDirect()) {
case 0: {
Runnable ra0Runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
if (bullet.getX() <= 0 || map[bullet.getX()][bullet.getY()] == 1
|| map[bullet.getX() - 1][bullet.getY()] == 2) {
if (map[bullet.getX()][bullet.getY()] == 1) {
map[bullet.getX()][bullet.getY()] = 0;
repaint();
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bListBullets.remove(bullet);
break;
}
bullet.setX(bullet.getX() - 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
};
new Thread(ra0Runnable).start();
break;
}
case 1: {
Runnable ra1Runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
if (bullet.getX() == 19 || map[bullet.getX()][bullet.getY()] == 1
|| map[bullet.getX() + 1][bullet.getY()] == 2) {
// boomlistBooms.add(new Boom(bullet.getX(), bullet.getY()));
if (map[bullet.getX()][bullet.getY()] == 1) {
map[bullet.getX()][bullet.getY()] = 0;
repaint();
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bListBullets.remove(bullet);
break;
}
bullet.setX(bullet.getX() + 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
};
new Thread(ra1Runnable).start();
break;
}
case 2: {
Runnable ra2Runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
if (bullet.getY() == 0 || map[bullet.getX()][bullet.getY()] == 1
|| map[bullet.getX()][bullet.getY() - 1] == 2) {
if (map[bullet.getX()][bullet.getY()] == 1) {
map[bullet.getX()][bullet.getY()] = 0;
repaint();
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bListBullets.remove(bullet);
break;
}
bullet.setY(bullet.getY() - 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
};
new Thread(ra2Runnable).start();
break;
}
case 3: {
Runnable ra3Runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
if (bullet.getY() == 19 || map[bullet.getX()][bullet.getY()] == 1
|| map[bullet.getX()][bullet.getY() + 1] == 2) {
if (map[bullet.getX()][bullet.getY()] == 1) {
map[bullet.getX()][bullet.getY()] = 0;
repaint();
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bListBullets.remove(bullet);
break;
}
bullet.setY(bullet.getY() + 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
};
new Thread(ra3Runnable).start();
break;
}
}
}
}
|
3e1122e9fdec52258cd0b1a62665a1697c594b32 | 1,073 | java | Java | src/test/java/com/example/briefing/service/PostServiceTest.java | taoweicn/briefing-api | 3bb2a7a7e66711caaef0bce564478fcc969900b9 | [
"MIT"
] | null | null | null | src/test/java/com/example/briefing/service/PostServiceTest.java | taoweicn/briefing-api | 3bb2a7a7e66711caaef0bce564478fcc969900b9 | [
"MIT"
] | null | null | null | src/test/java/com/example/briefing/service/PostServiceTest.java | taoweicn/briefing-api | 3bb2a7a7e66711caaef0bce564478fcc969900b9 | [
"MIT"
] | null | null | null | 29 | 64 | 0.756757 | 7,222 | package com.example.briefing.service;
import com.example.briefing.model.domain.Post;
import com.example.briefing.model.domain.User;
import com.example.briefing.model.vo.PostVo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PostServiceTest {
@Autowired private PostService postService;
@Test
public void getPost() {
PostVo postVo = postService.getPost(1);
Assert.assertEquals(postVo.getTotalIssue(), 1);
}
@Test
@Transactional // 使用这条注解可自动回滚数据
public void updatePost() {
Post post = new Post();
User user = new User();
user.setUsername("tester");
post.setTotalIssue(999);
post.setIssue(999);
post.setContent("{\"hello\": \"world\"}");
postService.updatePost(post, user);
}
}
|
3e112399bae2d9a0c34d07117afea822f0554a7a | 520 | java | Java | witkey-shop/src/main/java/co/zhenxi/modules/shop/domain/ZbEmployLocal.java | guoxinming-droid/witkey | 4b32d0c4c321bc56483851d0444c03d66aa8be0d | [
"Apache-2.0"
] | 1 | 2020-08-19T09:13:40.000Z | 2020-08-19T09:13:40.000Z | witkey-shop/src/main/java/co/zhenxi/modules/shop/domain/ZbEmployLocal.java | guoxinming-droid/witkey | 4b32d0c4c321bc56483851d0444c03d66aa8be0d | [
"Apache-2.0"
] | null | null | null | witkey-shop/src/main/java/co/zhenxi/modules/shop/domain/ZbEmployLocal.java | guoxinming-droid/witkey | 4b32d0c4c321bc56483851d0444c03d66aa8be0d | [
"Apache-2.0"
] | 1 | 2021-02-09T07:47:08.000Z | 2021-02-09T07:47:08.000Z | 20.8 | 53 | 0.746154 | 7,223 | package co.zhenxi.modules.shop.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @Author: Jia Hao Hao
* @Date: 2020-09-11 16:11
* @Description: ZbEmployLocal
**/
@Data
@TableName("zb_employ_local")
public class ZbEmployLocal {
@TableId(type = IdType.AUTO)
private Integer id;
private Integer employId;
private Integer uid;
private Integer localId;
}
|
3e1123f2b3fb384fed727654fe6b15ac86fe9138 | 21,800 | java | Java | android/src/main/java/com/wonderpush/sdk/flutter/WonderPushPlugin.java | wonderpush/wonderpush-flutter-sdk | 62012c5953398310ae7d100677665f3eec10c083 | [
"Apache-2.0"
] | 5 | 2020-05-15T09:38:18.000Z | 2021-12-03T00:14:23.000Z | android/src/main/java/com/wonderpush/sdk/flutter/WonderPushPlugin.java | wonderpush/wonderpush-flutter-sdk | 62012c5953398310ae7d100677665f3eec10c083 | [
"Apache-2.0"
] | 2 | 2020-05-26T09:43:05.000Z | 2021-06-04T06:43:00.000Z | android/src/main/java/com/wonderpush/sdk/flutter/WonderPushPlugin.java | wonderpush/wonderpush-flutter-sdk | 62012c5953398310ae7d100677665f3eec10c083 | [
"Apache-2.0"
] | null | null | null | 34.493671 | 134 | 0.551101 | 7,224 | package com.wonderpush.sdk.flutter;
import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import android.location.Location;
import com.wonderpush.sdk.DeepLinkEvent;
import com.wonderpush.sdk.WonderPush;
import com.wonderpush.sdk.WonderPushAbstractDelegate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* WonderPushPlugin
*/
public class WonderPushPlugin implements FlutterPlugin, MethodCallHandler {
MethodChannel eventChannel = null;
private static WonderPushPlugin instance;
public WonderPushPlugin() {
instance = this;
}
public static WonderPushPlugin getInstance() {
if (instance == null) {
instance = new WonderPushPlugin();
}
return instance;
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
this.onAttachedToEngine(
flutterPluginBinding.getApplicationContext(),
flutterPluginBinding.getBinaryMessenger());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
}
private void onAttachedToEngine(Context applicationContext, BinaryMessenger binaryMessenger) {
// Integrator
WonderPush.setIntegrator("wonderpush_flutter-2.1.3");
// Method channel
final MethodChannel channel = new MethodChannel(binaryMessenger, "wonderpush_flutter");
eventChannel = channel;
channel.setMethodCallHandler(this);
// Listen to notification clicks
LocalBroadcastManager.getInstance(applicationContext).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
WonderPushPlugin.this.onReceiveNotificationWillOpen(intent);
}
}, new IntentFilter(WonderPush.INTENT_NOTIFICATION_WILL_OPEN));
}
private void onReceiveNotificationWillOpen(Intent intent) {
// No push data
if (WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_NOTIFICATION_TYPE_DATA.equals(
intent.getStringExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_NOTIFICATION_TYPE))) {
return;
}
// Get the push notif
final Intent pushNotif = intent.getParcelableExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_RECEIVED_PUSH_NOTIFICATION);
Bundle bundle = pushNotif.getExtras();
if (bundle == null) {
return;
}
// Turn the bundle into a Map
final Map<String, Object> notificationData = new HashMap<>();
Set<String> keys = bundle.keySet();
for (String key : keys) {
if (key.equals("_wp")) {
String jsonString = bundle.getString("_wp");
try {
JSONObject jsonObject = new JSONObject(jsonString);
notificationData.put("_wp", jsonToMap(jsonObject));
} catch (JSONException e) {
}
continue;
}
notificationData.put(key, bundle.get(key));
}
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
if (eventChannel != null) {
eventChannel.invokeMethod("wonderPushReceivedPushNotification", notificationData);
}
}
}, 100);
}
public static void setupWonderPushDelegate() {
WonderPush.setDelegate(new WonderPushAbstractDelegate() {
@Override
public String urlForDeepLink(DeepLinkEvent event) {
final DeepLinkEvent e = event;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
if (getInstance().eventChannel != null) {
getInstance().eventChannel.invokeMethod("wonderPushWillOpenURL", e.getUrl());
}
}
}, 100);
return event.getUrl();
}
});
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
try {
switch (call.method) {
case "subscribeToNotifications":
subscribeToNotifications();
result.success(null);
break;
case "unsubscribeFromNotifications":
unsubscribeFromNotifications();
result.success(null);
break;
case "isSubscribedToNotifications":
result.success(isSubscribedToNotifications());
break;
case "trackEvent":
String type = call.argument("type");
Map<String, Object> attributes = call.argument("attributes");
trackEvent(type, attributes);
result.success(null);
break;
case "addTag":
ArrayList tagsToAdd = call.argument("tags");
addTag(tagsToAdd);
result.success(null);
break;
case "removeTag":
ArrayList tagsToRemove = call.argument("tags");
removeTag(tagsToRemove);
result.success(null);
break;
case "removeAllTags":
removeAllTags();
result.success(null);
break;
case "hasTag":
String tag = call.argument("tag");
result.success(hasTag(tag));
break;
case "getTags":
result.success(getTags());
break;
case "getPropertyValue":
String propertyValueToGet = call.argument("property");
result.success(getPropertyValue(propertyValueToGet));
break;
case "getPropertyValues":
String propertyValuesToGet = call.argument("property");
result.success(getPropertyValues(propertyValuesToGet));
break;
case "addProperty":
String propertyToAdd = call.argument("property");
Object propertiesToAdd = call.argument("properties");
addProperty(propertyToAdd, propertiesToAdd);
result.success(null);
break;
case "removeProperty":
String propertyToRemove = call.argument("property");
Object propertiesToRemove = call.argument("properties");
removeProperty(propertyToRemove, propertiesToRemove);
result.success(null);
break;
case "setProperty":
String propertyToSet = call.argument("property");
Object propertiesToSet = call.argument("properties");
setProperty(propertyToSet, propertiesToSet);
result.success(null);
break;
case "unsetProperty":
String property = call.argument("property");
unsetProperty(property);
result.success(null);
break;
case "putProperties":
Map<String, Object> propertiesToPut = call.argument("properties");
putProperties(propertiesToPut);
result.success(null);
break;
case "getProperties":
result.success(getProperties());
break;
case "setCountry":
String country = call.argument("country");
setCountry(country);
result.success(null);
break;
case "getCountry":
result.success(getCountry());
break;
case "setCurrency":
String currency = call.argument("currency");
setCurrency(currency);
result.success(null);
break;
case "getCurrency":
result.success(getCurrency());
break;
case "setLocale":
String locale = call.argument("locale");
setLocale(locale);
result.success(null);
break;
case "getLocale":
result.success(getLocale());
break;
case "setTimeZone":
String timeZone = call.argument("timeZone");
setTimeZone(timeZone);
result.success(null);
break;
case "getTimeZone":
result.success(getTimeZone());
break;
case "setUserId":
String userId = call.argument("userId");
setUserId(userId);
result.success(null);
break;
case "getUserId":
result.success(getUserId());
break;
case "getInstallationId":
result.success(getInstallationId());
break;
case "getPushToken":
result.success(getPushToken());
break;
case "setRequiresUserConsent":
boolean isRequiresUserConsent = call.argument("isConsent");
setRequiresUserConsent(isRequiresUserConsent);
result.success(null);
break;
case "setUserConsent":
boolean userConsent = call.argument("isConsent");
setUserConsent(userConsent);
result.success(null);
break;
case "disableGeolocation":
disableGeolocation();
result.success(null);
break;
case "enableGeolocation":
enableGeolocation();
result.success(null);
break;
case "setGeolocation":
double lat = call.argument("lat");
double lon = call.argument("lon");
setGeolocation(lat, lon);
result.success(null);
break;
case "clearEventsHistory":
clearEventsHistory();
result.success(null);
break;
case "clearPreferences":
clearPreferences();
result.success(null);
break;
case "clearAllData":
clearAllData();
result.success(null);
break;
case "downloadAllData":
downloadAllData();
result.success(null);
break;
case "setLogging":
boolean enable = call.argument("enable");
setLogging(enable);
result.success(null);
break;
default:
result.notImplemented();
break;
}
} catch (Exception e) {
result.error("0", e.getLocalizedMessage(), null);
}
}
// Subscribing users
public void subscribeToNotifications() {
WonderPush.subscribeToNotifications();
}
public void unsubscribeFromNotifications() {
WonderPush.unsubscribeFromNotifications();
}
public boolean isSubscribedToNotifications() {
boolean status = WonderPush.isSubscribedToNotifications();
return status;
}
// Segmentation
public void trackEvent(String type, Map<String, Object> properties) throws JSONException {
if (properties != null) {
JSONObject jsonObject = toJsonObject(properties);
WonderPush.trackEvent(type, jsonObject);
} else {
WonderPush.trackEvent(type);
}
}
public void addTag(ArrayList tags) {
String[] arrTags = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
if (tags.get(i) instanceof String) {
arrTags[i] = (String) tags.get(i);
}
}
WonderPush.addTag(arrTags);
}
public void removeTag(ArrayList tags) {
String[] arrTags = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
if (tags.get(i) instanceof String) {
arrTags[i] = (String) tags.get(i);
}
}
WonderPush.removeTag(arrTags);
}
public void removeAllTags() {
WonderPush.removeAllTags();
}
public boolean hasTag(String tag) {
boolean status = WonderPush.hasTag(tag);
return status;
}
public ArrayList getTags() {
Set<String> tags = WonderPush.getTags();
ArrayList<String> list = new ArrayList<>();
for (String tag : tags)
list.add(tag);
return list;
}
public void addProperty(String property, Object properties) throws JSONException {
WonderPush.addProperty(property, properties);
}
public void removeProperty(String property, Object properties) throws JSONException {
WonderPush.removeProperty(property, properties);
}
public void setProperty(String property, Object properties) throws JSONException {
WonderPush.setProperty(property, properties);
}
public void unsetProperty(String property) {
WonderPush.unsetProperty(property);
}
public void putProperties(Map<String, Object> properties) throws JSONException {
JSONObject jsonObject = toJsonObject(properties);
WonderPush.putProperties(jsonObject);
}
public Object getPropertyValue(String property) throws JSONException {
Object value = WonderPush.getPropertyValue(property);
if (value instanceof JSONObject) {
return (jsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
return (jsonToList((JSONArray) value));
} else if (value == null || value == JSONObject.NULL) {
return null;
} else {
return value;
}
}
public List getPropertyValues(String property) throws JSONException {
List<Object> values = WonderPush.getPropertyValues(property);
List<Object> properties = WonderPush.getPropertyValues(property);
for (Object obj : values) {
if (obj instanceof JSONObject) {
properties.add(jsonToMap((JSONObject) obj));
} else if (obj instanceof JSONArray) {
properties.add(jsonToList((JSONArray) obj));
} else if (obj == null || obj == JSONObject.NULL) {
properties.add(obj);
} else {
properties.add(obj);
}
}
return properties;
}
public Map getProperties() throws JSONException {
JSONObject jsonObject = WonderPush.getProperties();
Map map = jsonToMap(jsonObject);
return map;
}
public String getCountry() {
String country = WonderPush.getCountry();
return country;
}
public void setCountry(String country) {
WonderPush.setCountry(country);
}
public String getCurrency() {
String currency = WonderPush.getCurrency();
return currency;
}
public void setCurrency(String currency) {
WonderPush.setCurrency(currency);
}
public String getLocale() {
String locale = WonderPush.getLocale();
return locale;
}
public void setLocale(String locale) {
WonderPush.setLocale(locale);
}
public String getTimeZone() {
String timeZone = WonderPush.getTimeZone();
return timeZone;
}
public void setTimeZone(String timeZone) {
WonderPush.setTimeZone(timeZone);
}
// User IDs
public void setUserId(String userId) {
WonderPush.setUserId(userId);
}
public String getUserId() {
String userId = WonderPush.getUserId();
return userId;
}
// Installation info
public String getInstallationId() {
String installationId = WonderPush.getInstallationId();
return installationId;
}
public String getPushToken() {
String pushToken = WonderPush.getPushToken();
return pushToken;
}
// Privacy
public void setRequiresUserConsent(Boolean isConsent) {
WonderPush.setRequiresUserConsent(isConsent);
}
public void setUserConsent(Boolean isConsent) {
WonderPush.setUserConsent(isConsent);
}
public void disableGeolocation() {
WonderPush.disableGeolocation();
}
public void enableGeolocation() {
WonderPush.enableGeolocation();
}
public void setGeolocation(double lat, double lon) {
Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);
WonderPush.setGeolocation(location);
}
public void clearEventsHistory() {
WonderPush.clearEventsHistory();
}
public void clearPreferences() {
WonderPush.clearPreferences();
}
public void clearAllData() {
WonderPush.clearAllData();
}
public void downloadAllData() {
WonderPush.downloadAllData();
}
// Debug
public void setLogging(boolean enable) {
WonderPush.setLogging(enable);
}
// Custom methods
private static List<Object> jsonToList(JSONArray jsonArray) throws JSONException {
List<Object> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
list.add(jsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
list.add(jsonToList((JSONArray) value));
} else if (value == JSONObject.NULL) {
list.add(null);
} else {
list.add(value);
}
}
return list;
}
private static Map<String, Object> jsonToMap(JSONObject jsonObject) throws JSONException {
Map<String, Object> map = new HashMap<>();
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
map.put(key, jsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
map.put(key, jsonToList((JSONArray) value));
} else if (value == null || value == JSONObject.NULL) {
map.put(key, null);
} else {
map.put(key, value);
}
}
return map;
}
@SuppressWarnings("unchecked")
private JSONObject toJsonObject(Map<String, Object> map) throws JSONException {
JSONObject object = new JSONObject();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
Object value = map.get(key);
if (value instanceof Map) {
object.put(key, toJsonObject((Map<String, Object>) value));
} else if (value instanceof List) {
object.put(key, toJsonArray((List<Object>) value));
} else if (value == null || value == JSONObject.NULL) {
object.put(key, null);
} else {
object.put(key, value);
}
}
return object;
}
@SuppressWarnings("unchecked")
private JSONArray toJsonArray(List<Object> list) throws JSONException {
JSONArray array = new JSONArray();
for (int idx = 0; idx < list.size(); idx++) {
Object value = list.get(idx);
if (value instanceof Map) {
array.put(toJsonObject((Map<String, Object>) value));
} else if (value instanceof List) {
array.put(toJsonArray((List<Object>) value));
} else if (value == null || value == JSONObject.NULL) {
array.put(null);
} else {
array.put(value);
}
}
return array;
}
}
|
3e1124cae3c9ee488d0d263d97d9acba61e87f43 | 425 | java | Java | extensions/robospice-retrofit2-parent/robospice-retrofit2/src/main/java/com/octo/android/robospice/persistence/retrofit2/converter/RetrofitResponseConverter.java | mykolaj/robospice-returns | 52c1ff7dfe0dce122bd5db3b5d77ec261e779963 | [
"Apache-2.0"
] | null | null | null | extensions/robospice-retrofit2-parent/robospice-retrofit2/src/main/java/com/octo/android/robospice/persistence/retrofit2/converter/RetrofitResponseConverter.java | mykolaj/robospice-returns | 52c1ff7dfe0dce122bd5db3b5d77ec261e779963 | [
"Apache-2.0"
] | null | null | null | extensions/robospice-retrofit2-parent/robospice-retrofit2/src/main/java/com/octo/android/robospice/persistence/retrofit2/converter/RetrofitResponseConverter.java | mykolaj/robospice-returns | 52c1ff7dfe0dce122bd5db3b5d77ec261e779963 | [
"Apache-2.0"
] | null | null | null | 30.357143 | 85 | 0.785882 | 7,225 | package com.octo.android.robospice.persistence.retrofit2.converter;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
public interface RetrofitResponseConverter {
Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
void saveObject(Object object, Class<?> clzz, OutputStream out) throws Exception;
Object restoreObject(InputStream in, Class<?> clzz) throws Exception;
}
|
3e11253917790d0e8cf4ba66f788843b4355924a | 4,534 | java | Java | office/src/main/java/com/wxiwei/office/fc/hslf/record/MainMaster.java | sonnguyenxcii/PdfViewer | cd4f7a82a7118adff663079b1b9e976cca37b9ba | [
"MIT"
] | null | null | null | office/src/main/java/com/wxiwei/office/fc/hslf/record/MainMaster.java | sonnguyenxcii/PdfViewer | cd4f7a82a7118adff663079b1b9e976cca37b9ba | [
"MIT"
] | null | null | null | office/src/main/java/com/wxiwei/office/fc/hslf/record/MainMaster.java | sonnguyenxcii/PdfViewer | cd4f7a82a7118adff663079b1b9e976cca37b9ba | [
"MIT"
] | null | null | null | 27.313253 | 77 | 0.561094 | 7,226 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package com.wxiwei.office.fc.hslf.record;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
/**
* Master slide
*
* @author Yegor Kozlov
*/
public final class MainMaster extends SheetContainer
{
private byte[] _header;
private static long _type = 1016;
/**
* Returns the SlideAtom of this Slide
*/
public SlideAtom getSlideAtom()
{
return slideAtom;
}
/**
* Returns the PPDrawing of this Slide, which has all the
* interesting data in it
*/
public PPDrawing getPPDrawing()
{
return ppDrawing;
}
public TxMasterStyleAtom[] getTxMasterStyleAtoms()
{
return txmasters;
}
public ColorSchemeAtom[] getColorSchemeAtoms()
{
return clrscheme;
}
/**
* Set things up, and find our more interesting children
*/
protected MainMaster(byte[] source, int start, int len)
{
// Grab the header
_header = new byte[8];
System.arraycopy(source, start, _header, 0, 8);
// Find our children
_children = Record.findChildRecords(source, start + 8, len - 8);
ArrayList<TxMasterStyleAtom> tx = new ArrayList<TxMasterStyleAtom>();
ArrayList<ColorSchemeAtom> clr = new ArrayList<ColorSchemeAtom>();
// Find the interesting ones in there
for (int i = 0; i < _children.length; i++)
{
if (_children[i] instanceof SlideAtom)
{
slideAtom = (SlideAtom)_children[i];
}
else if (_children[i] instanceof PPDrawing)
{
ppDrawing = (PPDrawing)_children[i];
}
else if (_children[i] instanceof TxMasterStyleAtom)
{
tx.add((TxMasterStyleAtom)_children[i]);
}
else if (_children[i] instanceof ColorSchemeAtom)
{
clr.add((ColorSchemeAtom)_children[i]);
}
if (ppDrawing != null && _children[i] instanceof ColorSchemeAtom)
{
_colorScheme = (ColorSchemeAtom)_children[i];
}
}
txmasters = tx.toArray(new TxMasterStyleAtom[tx.size()]);
clrscheme = clr.toArray(new ColorSchemeAtom[clr.size()]);
}
/**
* We are of type 1016
*/
public long getRecordType()
{
return _type;
}
public ColorSchemeAtom getColorScheme()
{
return _colorScheme;
}
/**
*
*/
public void dispose()
{
super.dispose();
_header = null;
if (slideAtom != null)
{
slideAtom.dispose();
slideAtom = null;
}
if (ppDrawing != null)
{
ppDrawing.dispose();
ppDrawing = null;
}
if (txmasters != null)
{
for (TxMasterStyleAtom tms : txmasters)
{
tms.dispose();
}
txmasters = null;
}
if (clrscheme != null)
{
for (ColorSchemeAtom csa : clrscheme)
{
csa.dispose();
}
clrscheme = null;
}
if (_colorScheme != null)
{
_colorScheme.dispose();
_colorScheme = null;
}
}
// Links to our more interesting children
private SlideAtom slideAtom;
private PPDrawing ppDrawing;
private TxMasterStyleAtom[] txmasters;
private ColorSchemeAtom[] clrscheme;
private ColorSchemeAtom _colorScheme;
}
|
3e1125e1e404695d4ed1a1291ae27dfd26f062e3 | 513 | java | Java | src/main/java/org/max/crafting/interpreter/jlox/ast/VarStmt.java | mstepan/jlox | c4af64216a9dffaef40cc0554532f5ed9b431edf | [
"MIT"
] | null | null | null | src/main/java/org/max/crafting/interpreter/jlox/ast/VarStmt.java | mstepan/jlox | c4af64216a9dffaef40cc0554532f5ed9b431edf | [
"MIT"
] | null | null | null | src/main/java/org/max/crafting/interpreter/jlox/ast/VarStmt.java | mstepan/jlox | c4af64216a9dffaef40cc0554532f5ed9b431edf | [
"MIT"
] | null | null | null | 24.428571 | 65 | 0.709552 | 7,227 | package org.max.crafting.interpreter.jlox.ast;
import org.max.crafting.interpreter.jlox.interpreter.StmtVisitor;
import org.max.crafting.interpreter.jlox.model.Token;
public class VarStmt implements Stmt {
public final Token name;
public final Expression initExpr;
public VarStmt(Token name, Expression initExpr) {
this.name = name;
this.initExpr = initExpr;
}
@Override
public <T> T accept(StmtVisitor<T> visitor) {
return visitor.visitVarStmt(this);
}
}
|
3e1126a87c5337946ee76cfc23921e018c2a83c6 | 2,320 | java | Java | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question7.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | null | null | null | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question7.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | 1 | 2021-12-14T21:15:32.000Z | 2021-12-14T21:15:32.000Z | Java/java-snippet/src/main/java/com/sununiq/snippet/jianzhioffer/Question7.java | Sitrone/coding-notes | 121f32be35281b857e8a9082644013d0d19d74d9 | [
"MIT"
] | null | null | null | 20.714286 | 94 | 0.534483 | 7,228 | package com.sununiq.snippet.jianzhioffer;
import java.util.LinkedList;
import java.util.Stack;
/**
* 两个栈实现一个队列 两个队列实现一个栈
*/
public class Question7 {
public static void main(String[] args) {
// testSQueue();
testQStack();
}
private static void testQStack() {
QStack<Integer> stack = new QStack<>();
for (int i = 0; i < 5; i++) {
stack.push(i);
}
for (int i = 0; i < 5; i++) {
System.out.println(stack.pop());
}
}
private static void testSQueue() {
SQueue<Integer> queue = new SQueue<>();
for (int i = 0; i < 10; i++) {
queue.enqueue(i);
}
for (int i = 0; i < 10; i++) {
System.out.println(queue.dequeue());
}
}
static class SQueue<T> {
private Stack<T> stack1 = new Stack<>();
private Stack<T> stack2 = new Stack<>();
private int size;
public void enqueue(T t) {
stack1.push(t);
size++;
}
public T dequeue() {
if (stack2.isEmpty() && stack1.isEmpty()) {
throw new IllegalStateException("Queue is empty, cannot dequeue anymore.");
}
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
T value = stack2.pop();
size--;
return value;
}
private boolean isEmpty() {
return size == 0;
}
}
/**
* 另一个版本可以参考 ref:https://stackoverflow.com/questions/688276/implement-stack-using-two-queues
*
* @param <T>
*/
static class QStack<T> {
private LinkedList<T> queue1 = new LinkedList<>();
private LinkedList<T> queue2 = new LinkedList<>();
private int size;
private boolean isEmpty() {
return size == 0;
}
public T pop() {
if (queue2.isEmpty() && queue1.isEmpty()) {
throw new IllegalStateException("Stack is empty, cannot pop element anymore.");
}
if (queue1.isEmpty()) {
while (queue2.size() != 1) {
queue1.offer(queue2.poll());
}
return queue2.pop();
} else {
while (queue1.size() != 1) {
queue2.offer(queue1.pop());
}
return queue1.pop();
}
}
public void push(T t) {
if (!queue1.isEmpty()) {
queue1.offer(t);
} else {
queue2.offer(t);
}
size++;
}
}
}
|
3e11279d989c7ac006aadd6f3274d2aaa1ec5854 | 6,047 | java | Java | maven-compiler-plugin/src/main/java/org/apache/maven/plugin/compiler/CompilerMojo.java | NunoEdgarGFlowHub/maven-plugins | 91f90b8075a363e4c592da285cf8324c63a66ffa | [
"Apache-2.0"
] | 1 | 2018-06-06T13:56:44.000Z | 2018-06-06T13:56:44.000Z | maven-compiler-plugin/src/main/java/org/apache/maven/plugin/compiler/CompilerMojo.java | NunoEdgarGFlowHub/maven-plugins | 91f90b8075a363e4c592da285cf8324c63a66ffa | [
"Apache-2.0"
] | 3 | 2021-05-18T20:53:35.000Z | 2022-02-01T01:12:21.000Z | maven-compiler-plugin/src/main/java/org/apache/maven/plugin/compiler/CompilerMojo.java | NunoEdgarGFlowHub/maven-plugins | 91f90b8075a363e4c592da285cf8324c63a66ffa | [
"Apache-2.0"
] | 1 | 2021-03-16T10:31:51.000Z | 2021-03-16T10:31:51.000Z | 29.202899 | 119 | 0.651282 | 7,229 | package org.apache.maven.plugin.compiler;
/*
* 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.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Compiles application sources
*
* @author <a href="mailto:envkt@example.com">Jason van Zyl </a>
* @version $Id$
* @since 2.0
*/
@org.apache.maven.plugins.annotations.Mojo( name = "compile", defaultPhase = LifecyclePhase.COMPILE, threadSafe = true,
requiresDependencyResolution = ResolutionScope.COMPILE )
public class CompilerMojo
extends AbstractCompilerMojo
{
/**
* The source directories containing the sources to be compiled.
*/
@Parameter( defaultValue = "${project.compileSourceRoots}", readonly = true, required = true )
private List<String> compileSourceRoots;
/**
* Project classpath.
*/
@Parameter( defaultValue = "${project.compileClasspathElements}", readonly = true, required = true )
private List<String> classpathElements;
/**
* The directory for compiled classes.
*/
@Parameter( defaultValue = "${project.build.outputDirectory}", required = true, readonly = true )
private File outputDirectory;
/**
* Projects main artifact.
*
* @todo this is an export variable, really
*/
@Parameter( defaultValue = "${project.artifact}", readonly = true, required = true )
private Artifact projectArtifact;
/**
* A list of inclusion filters for the compiler.
*/
@Parameter
private Set<String> includes = new HashSet<String>();
/**
* A list of exclusion filters for the compiler.
*/
@Parameter
private Set<String> excludes = new HashSet<String>();
/**
* <p>
* Specify where to place generated source files created by annotation processing.
* Only applies to JDK 1.6+
* </p>
*
* @since 2.2
*/
@Parameter( defaultValue = "${project.build.directory}/generated-sources/annotations" )
private File generatedSourcesDirectory;
/**
* Set this to 'true' to bypass compilation of main sources.
* Its use is NOT RECOMMENDED, but quite convenient on occasion.
*/
@Parameter ( property = "maven.main.skip" )
private boolean skipMain;
protected List<String> getCompileSourceRoots()
{
return compileSourceRoots;
}
protected List<String> getClasspathElements()
{
return classpathElements;
}
protected File getOutputDirectory()
{
return outputDirectory;
}
public void execute()
throws MojoExecutionException, CompilationFailureException
{
if ( skipMain )
{
getLog().info( "Not compiling main sources" );
return;
}
super.execute();
if ( outputDirectory.isDirectory() )
{
projectArtifact.setFile( outputDirectory );
}
}
protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis )
{
SourceInclusionScanner scanner;
if ( includes.isEmpty() && excludes.isEmpty() )
{
scanner = new StaleSourceScanner( staleMillis );
}
else
{
if ( includes.isEmpty() )
{
includes.add( "**/*.java" );
}
scanner = new StaleSourceScanner( staleMillis, includes, excludes );
}
return scanner;
}
protected SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding )
{
SourceInclusionScanner scanner;
// it's not defined if we get the ending with or without the dot '.'
String defaultIncludePattern = "**/*" + ( inputFileEnding.startsWith( "." ) ? "" : "." ) + inputFileEnding;
if ( includes.isEmpty() && excludes.isEmpty() )
{
includes = Collections.singleton( defaultIncludePattern );
scanner = new SimpleSourceInclusionScanner( includes, Collections.<String>emptySet() );
}
else
{
if ( includes.isEmpty() )
{
includes.add( defaultIncludePattern );
}
scanner = new SimpleSourceInclusionScanner( includes, excludes );
}
return scanner;
}
protected String getSource()
{
return source;
}
protected String getTarget()
{
return target;
}
protected String getCompilerArgument()
{
return compilerArgument;
}
protected Map<String, String> getCompilerArguments()
{
return compilerArguments;
}
protected File getGeneratedSourcesDirectory()
{
return generatedSourcesDirectory;
}
}
|
3e11285f045b2f7185596ea76bf158523a92562d | 3,814 | java | Java | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/ShadowTableRule.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 4,372 | 2019-01-16T03:07:05.000Z | 2020-04-17T11:16:15.000Z | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/ShadowTableRule.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 3,040 | 2019-01-16T01:18:40.000Z | 2020-04-17T12:53:05.000Z | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/ShadowTableRule.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 1,515 | 2019-01-16T08:44:17.000Z | 2020-04-17T09:07:53.000Z | 50.853333 | 196 | 0.771631 | 7,230 | /*
* 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.shardingsphere.shadow.rule;
import com.google.common.base.Preconditions;
import lombok.Getter;
import org.apache.shardingsphere.shadow.api.shadow.ShadowOperationType;
import org.apache.shardingsphere.shadow.api.shadow.column.ColumnShadowAlgorithm;
import org.apache.shardingsphere.shadow.api.shadow.hint.HintShadowAlgorithm;
import org.apache.shardingsphere.shadow.spi.ShadowAlgorithm;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Shadow table rule.
*/
@Getter
public final class ShadowTableRule {
private final String tableName;
private final Collection<String> shadowDataSources;
private final Collection<String> hintShadowAlgorithmNames;
private final Map<ShadowOperationType, Collection<String>> columnShadowAlgorithmNames;
public ShadowTableRule(final String tableName, final Collection<String> shadowDataSources, final Collection<String> shadowAlgorithmNames, final Map<String, ShadowAlgorithm> shadowAlgorithms) {
this.tableName = tableName;
this.shadowDataSources = shadowDataSources;
this.hintShadowAlgorithmNames = initHintShadowAlgorithmNames(shadowAlgorithmNames, shadowAlgorithms);
this.columnShadowAlgorithmNames = initColumnShadowAlgorithmNames(shadowAlgorithmNames, shadowAlgorithms);
}
private Collection<String> initHintShadowAlgorithmNames(final Collection<String> shadowAlgorithmNames, final Map<String, ShadowAlgorithm> shadowAlgorithms) {
return shadowAlgorithmNames.stream().filter(each -> shadowAlgorithms.get(each) instanceof HintShadowAlgorithm).collect(Collectors.toList());
}
private Map<ShadowOperationType, Collection<String>> initColumnShadowAlgorithmNames(final Collection<String> shadowAlgorithmNames, final Map<String, ShadowAlgorithm> shadowAlgorithms) {
Map<ShadowOperationType, Collection<String>> result = new EnumMap<>(ShadowOperationType.class);
shadowAlgorithmNames.forEach(each -> {
ShadowAlgorithm shadowAlgorithm = shadowAlgorithms.get(each);
if (shadowAlgorithm instanceof ColumnShadowAlgorithm) {
ShadowOperationType.contains(shadowAlgorithm.getProps().getProperty("operation")).ifPresent(optional -> initShadowAlgorithmNames(result, each, optional));
}
});
return result;
}
private void initShadowAlgorithmNames(final Map<ShadowOperationType, Collection<String>> columnShadowAlgorithmNames, final String algorithmName, final ShadowOperationType operationType) {
Collection<String> names = columnShadowAlgorithmNames.get(operationType);
Preconditions.checkState(null == names, "Column shadow algorithm `%s` operation only supports one column mapping in shadow table `%s`.", operationType.name(), tableName);
columnShadowAlgorithmNames.put(operationType, Collections.singletonList(algorithmName));
}
}
|
3e1128d5c7dc0a3ef40ffc90501e9f13a24093ab | 3,055 | java | Java | app/controllers/Admin.java | mvanlaar/gtfs-editor | 2ec42691b9080cd18885e6da495e475bb9475d45 | [
"MIT"
] | 103 | 2015-01-07T15:12:06.000Z | 2022-03-11T02:55:35.000Z | app/controllers/Admin.java | mvanlaar/gtfs-editor | 2ec42691b9080cd18885e6da495e475bb9475d45 | [
"MIT"
] | 146 | 2015-01-13T11:59:38.000Z | 2018-03-22T14:58:50.000Z | app/controllers/Admin.java | mvanlaar/gtfs-editor | 2ec42691b9080cd18885e6da495e475bb9475d45 | [
"MIT"
] | 56 | 2015-01-03T10:17:45.000Z | 2021-09-24T10:44:54.000Z | 22.463235 | 141 | 0.6982 | 7,231 | package controllers;
import play.*;
import play.db.jpa.JPA;
import play.mvc.*;
import java.awt.Color;
import java.io.File;
import java.math.BigInteger;
import java.util.*;
import javax.persistence.Query;
import org.apache.commons.lang.StringUtils;
import org.geotools.geometry.jts.JTS;
import org.opengis.referencing.operation.MathTransform;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import datastore.VersionedDataStore;
import datastore.GlobalTx;
import models.*;
import models.transit.Agency;
@With(Secure.class)
public class Admin extends Controller {
@Before
static void setConnectedUser() {
if(Security.isConnected() && Security.check("admin")) {
renderArgs.put("user", Security.connected());
}
else
Application.index();
}
public static void accounts() {
GlobalTx tx = VersionedDataStore.getGlobalTx();
try {
Collection<Account> accounts = tx.accounts.values();
Collection<Agency> agencies = tx.agencies.values();
render(accounts, agencies);
} finally {
tx.rollback();
}
}
public static void createAccount(String username, String password, String email, Boolean admin, String agencyId)
{
GlobalTx tx = VersionedDataStore.getGlobalTx();
if(!username.isEmpty() && !password.isEmpty() && !email.isEmpty() && !tx.accounts.containsKey(username)) {
Account acct = new Account(username, password, email, admin, agencyId);
tx.accounts.put(acct.id, acct);
tx.commit();
}
else {
tx.rollback();
}
Admin.accounts();
}
public static void updateAccount(String username, String email, Boolean active, Boolean admin, Boolean taxi, Boolean citom, String agencyId)
{
GlobalTx tx = VersionedDataStore.getGlobalTx();
if (!tx.accounts.containsKey(username)) {
badRequest();
return;
}
Account acct = tx.accounts.get(username).clone();
acct.email = email;
acct.active = active;
acct.admin = admin;
acct.agencyId = agencyId;
tx.accounts.put(acct.id, acct);
tx.commit();
Admin.accounts();
}
public static void getAccount(String username) {
GlobalTx tx = VersionedDataStore.getGlobalTx();
Account account = tx.accounts.get(username);
tx.rollback();
if (account == null)
notFound();
else
renderJSON(account);
}
public static void checkUsername(String username) {
GlobalTx tx = VersionedDataStore.getGlobalTx();
boolean exists = tx.accounts.containsKey(username);
tx.rollback();
if (exists)
badRequest();
else
ok();
}
public static void resetPassword(String username, String newPassword)
{
GlobalTx tx = VersionedDataStore.getGlobalTx();
if (!tx.accounts.containsKey(username)) {
tx.rollback();
notFound();
return;
}
Account acct = tx.accounts.get(username).clone();
acct.updatePassword(newPassword);
tx.accounts.put(acct.id, acct);
tx.commit();
ok();
}
} |
3e1128ebbecc5d73cfdbcc2839190afe56f07dbc | 372 | java | Java | algorithm/src/main/java/org/wuxinshui/boosters/designPatterns/facade/Light.java | wuxinshui/wsdlutils | f238c92a27b0b8002094d2ca3ddd59ccf1a142da | [
"Apache-2.0"
] | 2 | 2017-06-16T03:35:28.000Z | 2017-06-16T09:14:55.000Z | algorithm/src/main/java/org/wuxinshui/boosters/designPatterns/facade/Light.java | wuxinshui/wsdlutils | f238c92a27b0b8002094d2ca3ddd59ccf1a142da | [
"Apache-2.0"
] | 4 | 2020-05-11T02:06:09.000Z | 2022-03-31T18:35:14.000Z | algorithm/src/main/java/org/wuxinshui/boosters/designPatterns/facade/Light.java | wuxinshui/wsdlutils | f238c92a27b0b8002094d2ca3ddd59ccf1a142da | [
"Apache-2.0"
] | 1 | 2019-01-13T00:37:20.000Z | 2019-01-13T00:37:20.000Z | 19.578947 | 64 | 0.61828 | 7,232 | package org.wuxinshui.boosters.designPatterns.facade;
/**
* Created with IntelliJ IDEA.
* User: FujiRen
* Date: 2016/11/16
* Time: 17:08
* To change this template use File | Settings | File Templates.
*/
public class Light {
public void on() {
System.out.println("正在开灯。。。");
}
public void off() {
System.out.println("正在关灯。。。");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.