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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9238386ab6ec9f2472405d36fcf56127fedfb3aa | 341 | java | Java | src/main/java/com/hissummer/mockserver/mock/service/jpa/MockRuleMongoRepository.java | hissummer-mockserver/mockserver | 8a6b952cb1699aaee605d75df437f4256d6bb8c9 | [
"BSD-2-Clause"
] | 1 | 2020-05-21T09:32:17.000Z | 2020-05-21T09:32:17.000Z | src/main/java/com/hissummer/mockserver/mock/service/jpa/MockRuleMongoRepository.java | hissummer-mockserver/mockserver | 8a6b952cb1699aaee605d75df437f4256d6bb8c9 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/hissummer/mockserver/mock/service/jpa/MockRuleMongoRepository.java | hissummer-mockserver/mockserver | 8a6b952cb1699aaee605d75df437f4256d6bb8c9 | [
"BSD-2-Clause"
] | null | null | null | 28.416667 | 89 | 0.815249 | 998,358 | package com.hissummer.mockserver.mock.service.jpa;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.hissummer.mockserver.mgmt.entity.HttpMockRule;
public interface MockRuleMongoRepository extends MongoRepository<HttpMockRule, String> {
HttpMockRule findByHostAndUri(String host, String uri);
}
|
923838e6b30452c70aa356ba78173045a64ce829 | 2,639 | java | Java | src/test/java/freemarker/manual/GettingStartedExample.java | rototor/freemarker | eb1343fc43bed24f5eb2ffcd9971bc2aeb0caf6a | [
"Apache-2.0"
] | 536 | 2018-03-30T08:35:24.000Z | 2022-03-31T08:53:43.000Z | src/test/java/freemarker/manual/GettingStartedExample.java | Seanpm2001-FreeMarker-lang/freemarker | 5821339c3188e8083af1fc72e17b34d09af09fcb | [
"Apache-2.0"
] | 20 | 2015-10-12T06:45:37.000Z | 2018-01-25T09:51:04.000Z | src/test/java/freemarker/manual/GettingStartedExample.java | Seanpm2001-FreeMarker-lang/freemarker | 5821339c3188e8083af1fc72e17b34d09af09fcb | [
"Apache-2.0"
] | 167 | 2018-04-02T19:32:53.000Z | 2022-03-16T09:27:02.000Z | 38.808824 | 90 | 0.650246 | 998,359 | /*
* 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 freemarker.manual;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
public class GettingStartedExample {
@Test
public void main() throws Exception {
/* ------------------------------------------------------------------------ */
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
cfg.setClassForTemplateLoading(GettingStartedExample.class, "");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
/* ------------------------------------------------------------------------ */
/* You usually do these for MULTIPLE TIMES in the application life-cycle: */
/* Create a data-model */
Map root = new HashMap();
root.put("user", "Big Joe");
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
root.put("latestProduct", latest);
/* Get the template (uses cache internally) */
Template temp = cfg.getTemplate("test.ftlh");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
// Note: Depending on what `out` is, you may need to call `out.close()`.
// This is usually the case for file output, but not for servlet output.
}
}
|
92383983957e9d88b3adef3971cc23639fb6a7c1 | 1,298 | java | Java | RegularExpressionClientWork/Main.java | hazratali-bit/30-lines-code.java | b5080bb3f9c70f78e3cea94b23b12f7c6574cd25 | [
"MIT"
] | null | null | null | RegularExpressionClientWork/Main.java | hazratali-bit/30-lines-code.java | b5080bb3f9c70f78e3cea94b23b12f7c6574cd25 | [
"MIT"
] | null | null | null | RegularExpressionClientWork/Main.java | hazratali-bit/30-lines-code.java | b5080bb3f9c70f78e3cea94b23b12f7c6574cd25 | [
"MIT"
] | null | null | null | 23.6 | 57 | 0.477658 | 998,360 | package RegularExpressionClientWork;
public class Main {
public static void main(String[] args) {
System.out.println(substEscapes(""));
// write your code here
}
private static String substEscapes(String s){
/*
replaces some of the \s whitespace characters with
the escape sequences used for them and adds single quotes
around the string to make white space visible in
the display.
It also replaces null with the empty string, which will
NOT have the single quotes around it.
*/
if (s == null)
return "";
StringBuilder b = new StringBuilder();
char[] A = s.toCharArray();
char c;
int
i,
len = A.length;
b.append('\'');
for (i = 0; i < len; i++){
c = A[i];
if (c == '\t')
b.append("\\t");
else if (c == '\r')
b.append("\\r");
else if (c == '\n')
b.append("\\n");
else if (c == '\f')
b.append("\\f");
else if (c == '\b')
b.append("\\b");
else
b.append(c);
}
// add the final \' to mark the end of the string
b.append('\'');
return b.toString();
}
}
|
923839f07ebff177f5ae0dd56b7a07645656c7c1 | 1,236 | java | Java | orientacao_a_objetos/orientacao_a_objetos_parte1/acessando_atributos_de_objetos/exercicio01/Petshop.java | gladsonsimoes/ExemplosDeAlgoritmos | 49ef3ee447e15ebb106fcd2adc691daaf38c682c | [
"MIT"
] | null | null | null | orientacao_a_objetos/orientacao_a_objetos_parte1/acessando_atributos_de_objetos/exercicio01/Petshop.java | gladsonsimoes/ExemplosDeAlgoritmos | 49ef3ee447e15ebb106fcd2adc691daaf38c682c | [
"MIT"
] | null | null | null | orientacao_a_objetos/orientacao_a_objetos_parte1/acessando_atributos_de_objetos/exercicio01/Petshop.java | gladsonsimoes/ExemplosDeAlgoritmos | 49ef3ee447e15ebb106fcd2adc691daaf38c682c | [
"MIT"
] | null | null | null | 36.352941 | 124 | 0.567961 | 998,361 | package com.company.acessando_atributos_de_objetos.exercicio01;
public class Petshop {
public static void main(String[] args) {
Cachorro cachorro = new Cachorro(); //acessando o objeto da classe Cachorro e definindo um objeto chamado cachorro
cachorro.nome = "Bidu"; //usando o objeto cachorro e para acessar o atributo nome da Classe Cachorro
cachorro.idade = 2;
cachorro.raca = "Boxer";
cachorro.sexo = 'M';
System.out.println("\n===============================");
System.out.println("Nome: " + cachorro.nome);
System.out.println("Idade: " + cachorro.idade);
System.out.println("Raça: " + cachorro.raca);
System.out.println("Sexo: " + cachorro.sexo);
cachorro = new Cachorro();
cachorro.nome = "Kadu";
cachorro.idade = 4;
cachorro.raca = "Husky-Siberiano";
cachorro.sexo = 'M';
System.out.println("\n==============================");
System.out.println("Nome: " + cachorro.nome);
System.out.println("Idade: " + cachorro.idade);
System.out.println("Raça: " + cachorro.raca);
System.out.println("Sexo: " + cachorro.sexo);
}
}
|
92383a6cf99d6b4996b0821470bdb576576982ab | 648 | java | Java | javafx-d3/main/java/org/treez/javafxd3/d3/wrapper/canvas/CanvasElement.java | saschapojot/javafx-d3 | db31187e92ea12f74fe43cb18e5314ec4fc4763d | [
"BSD-3-Clause"
] | 104 | 2015-11-17T17:44:14.000Z | 2022-03-25T06:26:22.000Z | javafx-d3/main/java/org/treez/javafxd3/d3/wrapper/canvas/CanvasElement.java | saschapojot/javafx-d3 | db31187e92ea12f74fe43cb18e5314ec4fc4763d | [
"BSD-3-Clause"
] | 12 | 2015-10-15T17:42:50.000Z | 2019-07-12T07:38:02.000Z | javafx-d3/main/java/org/treez/javafxd3/d3/wrapper/canvas/CanvasElement.java | saschapojot/javafx-d3 | db31187e92ea12f74fe43cb18e5314ec4fc4763d | [
"BSD-3-Clause"
] | 32 | 2015-11-30T15:42:44.000Z | 2021-05-31T16:17:17.000Z | 19.058824 | 66 | 0.742284 | 998,362 | package org.treez.javafxd3.d3.wrapper.canvas;
import org.treez.javafxd3.d3.wrapper.JavaScriptObject;
import org.treez.javafxd3.d3.core.JsEngine;
import org.treez.javafxd3.d3.core.JsObject;
public class CanvasElement extends JavaScriptObject {
//#region CONSTRUCTORS
public CanvasElement(JsEngine engine, JsObject wrappedJsObject) {
super(engine, wrappedJsObject);
}
//#end region
//#region ACCESSORS
public Context2d getContext2d() {
String command = "this.getContext('2d')";
JsObject result = evalForJsObject(command);
if (result == null) {
return null;
}
return new Context2d(engine, result);
}
//#end region
}
|
92383ba7656d44c1a51a071deb12a328b6812f9d | 1,071 | java | Java | calims2-model/src/java/gov/nih/nci/calims2/domain/workflow/enumeration/MethodStatus.java | NCIP/calims | 8d76ec56361b1af7332ca19fb2801c73aa2be7b8 | [
"BSD-3-Clause"
] | 1 | 2018-10-30T20:43:20.000Z | 2018-10-30T20:43:20.000Z | calims2-model/src/java/gov/nih/nci/calims2/domain/workflow/enumeration/MethodStatus.java | NCIP/calims | 8d76ec56361b1af7332ca19fb2801c73aa2be7b8 | [
"BSD-3-Clause"
] | null | null | null | calims2-model/src/java/gov/nih/nci/calims2/domain/workflow/enumeration/MethodStatus.java | NCIP/calims | 8d76ec56361b1af7332ca19fb2801c73aa2be7b8 | [
"BSD-3-Clause"
] | null | null | null | 15.710145 | 132 | 0.698339 | 998,363 | /*L
* Copyright Moxie Informatics.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/calims/LICENSE.txt for details.
*/
package gov.nih.nci.calims2.domain.workflow.enumeration;
import java.util.Locale;
import gov.nih.nci.calims2.util.enumeration.I18nEnumeration;
/**
* @author lyhxr@example.com
*
*/
public enum MethodStatus implements I18nEnumeration {
/**
* APPROVALPENDING status name.
*/
APPROVALPENDING,
/**
* APPROVED status name.
*/
APPROVED,
/**
* NOTAPPROVED status name.
*/
NOTAPPROVED,
/**
* INPROGRESS status name.
*/
INPROGRESS,
/**
* COMPLETED status name.
*/
COMPLETED,
/**
* INREVIEW status name.
*/
INREVIEW,
/**
* REVIEWED status name.
*/
REVIEWED,
/**
* PUBLISHED status name.
*/
PUBLISHED;
/**
* {@inheritDoc}
*/
public String getLocalizedValue(Locale locale) {
return I18nEnumerationHelper.getLocalizedValue(gov.nih.nci.calims2.domain.workflow.l10n.MethodStatusBundle.class, locale, this);
}
/**
* {@inheritDoc}
*/
public String getName() {
return name();
}
} |
92383c5ec117a13267962359d6fa6fc5e214a479 | 490 | java | Java | learn-goods/src/main/java/com/wwjswly/learn/service/impl/MessageServiceImpl.java | javaDer/learn-qingyun | d615286398fce8434d19c94639d6a613ae02ed1a | [
"Apache-2.0"
] | 1 | 2019-04-10T16:49:34.000Z | 2019-04-10T16:49:34.000Z | learn-goods/src/main/java/com/wwjswly/learn/service/impl/MessageServiceImpl.java | javaDer/learn-qingyun | d615286398fce8434d19c94639d6a613ae02ed1a | [
"Apache-2.0"
] | 1 | 2021-08-03T09:53:40.000Z | 2021-08-03T09:53:40.000Z | learn-goods/src/main/java/com/wwjswly/learn/service/impl/MessageServiceImpl.java | javaDer/learn-qingyun | d615286398fce8434d19c94639d6a613ae02ed1a | [
"Apache-2.0"
] | null | null | null | 23.333333 | 103 | 0.783673 | 998,364 | package com.wwjswly.learn.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwjswly.entity.goods.Message;
import com.wwjswly.learn.mapper.MessageMapper;
import com.wwjswly.learn.service.MessageService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author zhangzhaofa
* @since 2019-05-15
*/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
}
|
92383d098e80215904c1241315d88ad0969bacce | 1,212 | java | Java | dopaas-ucm/dopaas-ucm-core/src/main/java/com/wl4g/dopaas/scm/config/StandardScmAutoConfiguration.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 72 | 2018-12-04T13:48:25.000Z | 2020-05-06T06:51:02.000Z | dopaas-ucm/dopaas-ucm-core/src/main/java/com/wl4g/dopaas/scm/config/StandardScmAutoConfiguration.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 7 | 2019-04-24T03:30:04.000Z | 2020-04-18T12:16:36.000Z | dopaas-ucm/dopaas-ucm-core/src/main/java/com/wl4g/dopaas/scm/config/StandardScmAutoConfiguration.java | wl4g/nops-cloud | 1d094d15b35ab6e8ea9710ffaa8aa2df2addafe9 | [
"Apache-2.0"
] | 24 | 2018-12-04T13:48:31.000Z | 2020-04-15T07:36:08.000Z | 32.756757 | 95 | 0.779703 | 998,365 | /*
* Copyright 2017 ~ 2050 the original author or authors <upchh@example.com, kenaa@example.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.dopaas.scm.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.wl4g.dopaas.scm.StandardConfigServerHandler;
import com.wl4g.dopaas.scm.handler.CentralConfigServerHandler;
@Configuration
public class StandardScmAutoConfiguration {
@Bean
public CentralConfigServerHandler configContextHandler() {
return new StandardConfigServerHandler();
}
@Bean
public StandardScmProperties scmServerProperties() {
return new StandardScmProperties();
}
} |
92383dc3e6eff1a9a7f680c3d8062f04408c3335 | 340 | java | Java | src/main/java/com/easyyu/api/buildings/food/FoodBuildingRepository.java | jackehuynh/EasyYU-API | fe624443711e1c8a8fcb9bed22a27f9c336c801c | [
"MIT"
] | null | null | null | src/main/java/com/easyyu/api/buildings/food/FoodBuildingRepository.java | jackehuynh/EasyYU-API | fe624443711e1c8a8fcb9bed22a27f9c336c801c | [
"MIT"
] | 9 | 2021-07-31T14:08:40.000Z | 2022-02-27T09:24:47.000Z | src/main/java/com/easyyu/api/buildings/food/FoodBuildingRepository.java | jackehuynh/EasyYU-API | fe624443711e1c8a8fcb9bed22a27f9c336c801c | [
"MIT"
] | null | null | null | 28.333333 | 85 | 0.832353 | 998,366 | package com.easyyu.api.buildings.food;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface FoodBuildingRepository extends JpaRepository<FoodBuilding, String> {
List<FoodBuilding> findByCampusIgnoreCase(String campus);
}
|
92383e9a04f53a0dc5b1fa3d737a3b222a0f4208 | 6,761 | java | Java | Android/GradeIt/app/src/main/java/io/github/stevenalbert/gradeit/ui/activity/MainActivity.java | stevenalbert/grade-it | 2fc8d48265f16e9807fc05b172598e274885e624 | [
"MIT"
] | null | null | null | Android/GradeIt/app/src/main/java/io/github/stevenalbert/gradeit/ui/activity/MainActivity.java | stevenalbert/grade-it | 2fc8d48265f16e9807fc05b172598e274885e624 | [
"MIT"
] | null | null | null | Android/GradeIt/app/src/main/java/io/github/stevenalbert/gradeit/ui/activity/MainActivity.java | stevenalbert/grade-it | 2fc8d48265f16e9807fc05b172598e274885e624 | [
"MIT"
] | null | null | null | 37.353591 | 155 | 0.694572 | 998,367 | package io.github.stevenalbert.gradeit.ui.activity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.github.stevenalbert.gradeit.R;
import io.github.stevenalbert.gradeit.model.AnswerKeyCode;
import io.github.stevenalbert.gradeit.model.AnswerSheetCode;
import io.github.stevenalbert.gradeit.ui.fragment.AnalysisFragment;
import io.github.stevenalbert.gradeit.ui.fragment.GetMarkFragment;
import io.github.stevenalbert.gradeit.ui.fragment.ViewMarksFragment;
import io.github.stevenalbert.gradeit.util.AppSharedPreference;
import io.github.stevenalbert.gradeit.util.FileUtils;
import io.github.stevenalbert.gradeit.util.MetadataUtils;
public class MainActivity extends TabActivity implements
GetMarkFragment.GetMarkListener,
ViewMarksFragment.OnSelectListener,
AnalysisFragment.OnSelectItemMCodeListener {
// TAG
private static final String TAG = MainActivity.class.getSimpleName();
private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_CODE = 1100;
// Parent Layout
private CoordinatorLayout parentLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initApps();
}
private void initApps() {
if(!AppSharedPreference.isInit(this)) {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, WRITE_EXTERNAL_STORAGE_PERMISSION_CODE);
return;
}
File metadataDirectory = MetadataUtils.getMetadataDirectory();
Log.d(TAG, metadataDirectory.getAbsolutePath());
metadataDirectory.mkdirs();
try {
final String directory = getString(R.string.metadata_directory_name);
String[] filenames = getAssets().list(directory);
for(String filename : filenames) {
File file = new File(metadataDirectory, filename);
FileUtils.copyFromAsset(this, directory + "/" + filename, file);
}
AppSharedPreference.saveMetadataString(this, filenames[0]);
} catch (IOException e) {
e.printStackTrace();
}
AppSharedPreference.setInit(this);
}
setContentView(R.layout.activity_main);
// Setup Toolbar
setupToolbar();
// Setup Tab Layout and View
setupTabActivity(getAllTabFragments());
parentLayout = findViewById(R.id.parent_layout);
}
@Override
protected void onResume() {
super.onResume();
setTitle(R.string.app_name);
}
private ArrayList<TabFragment> getAllTabFragments() {
final List<TabFragment> TAB_FRAGMENTS = Arrays.asList(
new TabFragment(new GetMarkFragment(), this.getString(R.string.mark_answer_title)),
new TabFragment(new ViewMarksFragment(), this.getString(R.string.view_marks_title)),
new TabFragment(new AnalysisFragment(), this.getString(R.string.answer_analysis_title))
);
return new ArrayList<>(TAB_FRAGMENTS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.popupmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.help) {
return true;
}
/*
else if (id == R.id.about_us) {
return true;
}
*/
return super.onOptionsItemSelected(item);
}
@Override
public void onProcessImageTaken(Uri uri) {
Intent processIntent = new Intent(this, ProcessActivity.class);
processIntent.setData(uri);
startActivity(processIntent);
}
@Override
public void onFinishDownloadAnswerSheet(File downloadFolder) {
Snackbar snackbar = Snackbar.make(parentLayout, getString(R.string.success_download_answer_sheet, downloadFolder.getPath()), Snackbar.LENGTH_LONG);
snackbar.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onSelectAnswerSheet(AnswerSheetCode answerSheetCode) {
Intent answerSheetDetailIntent = new Intent(this, AnswerSheetDetailActivity.class);
answerSheetDetailIntent.putExtra(AnswerSheetDetailActivity.ANSWER_SHEET_CODE_INTENT_KEY, answerSheetCode);
startActivity(answerSheetDetailIntent);
}
@Override
public void onSelectAnswerKey(AnswerKeyCode answerKeyCode) {
Intent answerKeyDetailIntent = new Intent(this, AnswerKeyDetailActivity.class);
answerKeyDetailIntent.putExtra(AnswerKeyDetailActivity.ANSWER_KEY_INTENT_KEY, answerKeyCode);
startActivity(answerKeyDetailIntent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_CODE) {
if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initApps();
} else {
finish();
}
}
}
@Override
public void onSelectItemMCode(int mCode) {
Intent analysisProcessIntent = new Intent(this, AnalysisProcessActivity.class);
analysisProcessIntent.putExtra(AnalysisProcessActivity.M_CODE_KEY, mCode);
startActivity(analysisProcessIntent);
}
}
|
92384035de1e296ef9f3a0b84ffb09ec79e470e1 | 308 | java | Java | src/Tuturialpoint/ExceptionLearn/FilenotFound_Demo.java | pritamkhose/PritamJava | fd20cc60bfa2c18907a5f8829c5acab870655259 | [
"Apache-2.0"
] | null | null | null | src/Tuturialpoint/ExceptionLearn/FilenotFound_Demo.java | pritamkhose/PritamJava | fd20cc60bfa2c18907a5f8829c5acab870655259 | [
"Apache-2.0"
] | null | null | null | src/Tuturialpoint/ExceptionLearn/FilenotFound_Demo.java | pritamkhose/PritamJava | fd20cc60bfa2c18907a5f8829c5acab870655259 | [
"Apache-2.0"
] | null | null | null | 19.25 | 70 | 0.743506 | 998,368 | package ExceptionLearn;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
|
9238404869e37ce3cb596a988618dfde169225d7 | 3,916 | java | Java | src/org/janeth/jennynet/core/ObjectAgglomeration.java | JanetHunt/jennynet | 353e3d0f02397dbe2019de4659cf09c670edb64b | [
"BSD-2-Clause"
] | null | null | null | src/org/janeth/jennynet/core/ObjectAgglomeration.java | JanetHunt/jennynet | 353e3d0f02397dbe2019de4659cf09c670edb64b | [
"BSD-2-Clause"
] | null | null | null | src/org/janeth/jennynet/core/ObjectAgglomeration.java | JanetHunt/jennynet | 353e3d0f02397dbe2019de4659cf09c670edb64b | [
"BSD-2-Clause"
] | null | null | null | 35.926606 | 120 | 0.64811 | 998,369 | package org.janeth.jennynet.core;
import org.janeth.jennynet.intfa.Serialization;
class ObjectAgglomeration {
private ConnectionImpl connection;
private long objectID;
private int serialSize, bufferPos;
private int numberOfParcels;
private SendPriority priority;
private Object object;
private byte[] byteStore;
private int nextParcelNr;
public ObjectAgglomeration (ConnectionImpl connection, long objectID, SendPriority priority) {
this.connection = connection;
this.objectID = objectID;
this.priority = priority;
}
public boolean objectReady () {
return object != null;
}
/** Returns the de-serialised transmission object.
*
* @return Object object or null if unavailable
*/
public Object getObject () {
return object;
}
/** Returns the priority class by which the contained object was
* or is being sent.
*
* @return SendPriority
*/
public SendPriority getPriority () {
return priority;
}
/** Digest a single data parcel into the agglomeration.
*
* @param parcel <code>TransmissionParcel</code>
* @throws IllegalStateException if parcel is malformed, out of sequence,
* or object serialisation size overflows maximum
*/
public void digestParcel (TransmissionParcel parcel) {
// verify fitting
if (parcel.getChannel() != TransmissionChannel.OBJECT)
throw new IllegalArgumentException("illegal parcel channel; must be OBJECT");
if (parcel.getObjectID() != objectID)
throw new IllegalStateException("mismatching object-ID in agglomeration parcel");
if (parcel.getParcelSequencelNr() != nextParcelNr) {
String hstr = objectReady() ? " (object completed)" : "";
throw new IllegalStateException("PARCEL SERIAL NUMBER out of sequence (object agglomeration); " +
" expected: " + nextParcelNr + hstr + ", received: " + parcel.getParcelSequencelNr());
}
// initialise on parcel number 0 (HEADER PARCEL)
if (parcel.getParcelSequencelNr() == 0) {
ObjectHeader header = parcel.getObjectHeader();
numberOfParcels = header.getNumberOfParcels();
serialSize = header.getTransmissionSize();
// check correctness of indicated object data size
if (numberOfParcels < 0 | serialSize < 0) {
throw new IllegalStateException("negative parcel amount or data length detected");
}
// check serialisation method consistency
if (header.getSerialisationMethod() != connection.getReceiveSerialization().getMethodID()) {
throw new IllegalStateException("mismatching serialisation method on RECEIVE OBJECT parcel: "
+ header.getSerialisationMethod());
}
// check feasibility of serialisation buffer length
if (serialSize > connection.getParameters().getMaxSerialisationSize()) {
throw new IllegalStateException("received oversized object serialisation: ID=" + objectID +
", serial-size=" + serialSize);
}
byteStore = new byte[serialSize];
}
// add parcel data to byte stream
try {
System.arraycopy(parcel.getData(), 0, byteStore, bufferPos, parcel.getLength());
bufferPos += parcel.getLength();
} catch (Throwable e) {
e.printStackTrace();
throw new IllegalStateException("unable to store parcel BYTE BUFFER in object agglomeration; current size == "
+ bufferPos);
}
// if last parcel arrived, perform object de-serialisation
if (nextParcelNr+1 == numberOfParcels) {
Serialization ser = connection.getReceiveSerialization();
object = ser.deserialiseObject(byteStore);
} else {
nextParcelNr++;
}
}
}
|
9238408334d385f00a45f5f217f0b63308aa7e0a | 22,495 | java | Java | rt/ws/rm/src/test/java/org/apache/cxf/ws/rm/ManagedRMManagerTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 839 | 2015-01-01T15:33:21.000Z | 2022-03-31T02:40:34.000Z | rt/ws/rm/src/test/java/org/apache/cxf/ws/rm/ManagedRMManagerTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 399 | 2015-01-07T19:59:38.000Z | 2022-03-30T21:56:27.000Z | rt/ws/rm/src/test/java/org/apache/cxf/ws/rm/ManagedRMManagerTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 1,581 | 2015-01-01T02:22:05.000Z | 2022-03-31T13:29:27.000Z | 38.191851 | 114 | 0.643165 | 998,370 | /**
* 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.cxf.ws.rm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.xml.namespace.QName;
import org.apache.cxf.Bus;
import org.apache.cxf.binding.soap.model.SoapBindingInfo;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.endpoint.EndpointImpl;
import org.apache.cxf.management.InstrumentationManager;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.ServiceImpl;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.ws.rm.v200702.Identifier;
import org.apache.cxf.ws.rm.v200702.SequenceAcknowledgement;
import org.apache.cxf.wsdl.WSDLConstants;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ManagedRMManagerTest {
private static final String TEST_URI = "http://nowhere.com/bar/foo";
private IMocksControl control;
private Bus bus;
private InstrumentationManager im;
private RMManager manager;
private Endpoint endpoint;
@Before
public void setUp() {
control = EasyMock.createNiceControl();
}
@After
public void tearDown() throws Exception {
if (bus != null) {
bus.shutdown(true);
}
control.verify();
}
@Test
public void testManagedRMManager() throws Exception {
final SpringBusFactory factory = new SpringBusFactory();
bus = factory.createBus("org/apache/cxf/ws/rm/managed-manager-bean.xml");
im = bus.getExtension(InstrumentationManager.class);
manager = bus.getExtension(RMManager.class);
endpoint = createTestEndpoint();
assertNotNull("Instrumentation Manager should not be null", im);
assertNotNull("RMManager should not be null", manager);
MBeanServer mbs = im.getMBeanServer();
assertNotNull("MBeanServer should be available.", mbs);
ObjectName managerName = RMUtils.getManagedObjectName(manager);
Set<ObjectInstance> mbset = mbs.queryMBeans(managerName, null);
assertEquals("ManagedRMManager should be found", 1, mbset.size());
Object o;
o = mbs.getAttribute(managerName, "UsingStore");
assertTrue(o instanceof Boolean);
assertFalse("Store attribute is false", (Boolean)o);
o = mbs.invoke(managerName, "getEndpointIdentifiers", null, null);
assertTrue(o instanceof String[]);
assertEquals("No Endpoint", 0, ((String[])o).length);
RMEndpoint rme = createTestRMEndpoint();
ObjectName endpointName = RMUtils.getManagedObjectName(rme);
mbset = mbs.queryMBeans(endpointName, null);
assertEquals("ManagedRMEndpoint should be found", 1, mbset.size());
o = mbs.invoke(managerName, "getEndpointIdentifiers", null, null);
assertEquals("One Endpoint", 1, ((String[])o).length);
assertEquals("Endpoint identifier must match",
RMUtils.getEndpointIdentifier(endpoint, bus), ((String[])o)[0]);
// test some endpoint methods
o = mbs.getAttribute(endpointName, "Address");
assertTrue(o instanceof String);
assertEquals("Endpoint address must match", TEST_URI, o);
o = mbs.getAttribute(endpointName, "LastApplicationMessage");
assertNull(o);
o = mbs.getAttribute(endpointName, "LastControlMessage");
assertNull(o);
o = mbs.invoke(endpointName, "getDestinationSequenceIds", null, null);
assertTrue(o instanceof String[]);
assertEquals("No sequence", 0, ((String[])o).length);
o = mbs.invoke(endpointName, "getDestinationSequences", null, null);
assertTrue(o instanceof CompositeData[]);
assertEquals("No sequence", 0, ((CompositeData[])o).length);
o = mbs.invoke(endpointName, "getSourceSequenceIds", new Object[]{true}, new String[]{"boolean"});
assertTrue(o instanceof String[]);
assertEquals("No sequence", 0, ((String[])o).length);
o = mbs.invoke(endpointName, "getSourceSequences", new Object[]{true}, new String[]{"boolean"});
assertTrue(o instanceof CompositeData[]);
assertEquals("No sequence", 0, ((CompositeData[])o).length);
o = mbs.invoke(endpointName, "getDeferredAcknowledgementTotalCount", null, null);
assertTrue(o instanceof Integer);
assertEquals("No deferred acks", 0, o);
o = mbs.invoke(endpointName, "getQueuedMessageTotalCount",
new Object[]{true}, new String[]{"boolean"});
assertTrue(o instanceof Integer);
assertEquals("No queued messages", 0, o);
}
@Test
public void testManagedRMEndpointGetQueuedCount() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
int n = managedEndpoint.getQueuedMessageTotalCount(true);
assertEquals(3, n);
n = managedEndpoint.getQueuedMessageCount("seq1", true);
assertEquals(2, n);
}
@Test
public void testGetUnAcknowledgedMessageIdentifiers() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
Long[] numbers = managedEndpoint.getUnAcknowledgedMessageIdentifiers("seq1");
assertEquals(2, numbers.length);
assertTrue(2L == numbers[0] && 4L == numbers[1]);
}
@Test
public void testRemoveSequence() throws Exception {
manager = new RMManager();
RMEndpoint rme = control.createMock(RMEndpoint.class);
EndpointReferenceType ref = RMUtils.createReference(TEST_URI);
Source source = new Source(rme);
Destination destination = new Destination(rme);
RetransmissionQueue rq = new TestRetransmissionQueue();
manager.setRetransmissionQueue(rq);
manager.initialise();
SourceSequence ss1 = createTestSourceSequence(source, "seq1", ref,
ProtocolVariation.RM10WSA200408, new long[]{1L, 1L, 3L, 3L});
SourceSequence ss3 = createTestSourceSequence(source, "seq3", ref,
ProtocolVariation.RM10WSA200408, new long[]{1L, 5L});
EasyMock.expect(rme.getManager()).andReturn(manager).anyTimes();
EasyMock.expect(rme.getSource()).andReturn(source).anyTimes();
EasyMock.expect(rme.getDestination()).andReturn(destination).anyTimes();
control.replay();
setCurrentMessageNumber(ss1, 5L);
setCurrentMessageNumber(ss3, 5L);
source.addSequence(ss1);
source.addSequence(ss3);
source.setCurrent(ss3);
ManagedRMEndpoint managedEndpoint = new ManagedRMEndpoint(rme);
// for those sequences without any unacknowledged messages
CompositeData cd = managedEndpoint.getSourceSequence("seq3");
assertNotNull(cd);
managedEndpoint.removeSourceSequence("seq3");
try {
managedEndpoint.getSourceSequence("seq3");
fail("sequnce not removed");
} catch (Exception e) {
// ok
}
// for those sequences with some unacknowledged messages
cd = managedEndpoint.getSourceSequence("seq1");
assertNotNull(cd);
try {
managedEndpoint.removeSourceSequence("seq1");
fail("sequnce may not be removed");
} catch (Exception e) {
// ok
}
cd = managedEndpoint.getSourceSequence("seq1");
assertNotNull(cd);
managedEndpoint.purgeUnAcknowledgedMessages("seq1");
managedEndpoint.removeSourceSequence("seq1");
try {
managedEndpoint.getSourceSequence("seq1");
fail("sequnce not removed");
} catch (Exception e) {
// ok
}
}
@Test
public void testGetSourceSequenceAcknowledgedRange() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
Long[] ranges = managedEndpoint.getSourceSequenceAcknowledgedRange("seq1");
assertEquals(4, ranges.length);
assertTrue(1L == ranges[0] && 1L == ranges[1] && 3L == ranges[2] && 3L == ranges[3]);
}
@Test
public void testGetSourceSequences() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
String[] sids = managedEndpoint.getSourceSequenceIds(true);
assertEquals(2, sids.length);
assertTrue(("seq1".equals(sids[0]) || "seq1".equals(sids[1]))
&& ("seq2".equals(sids[0]) || "seq2".equals(sids[1])));
String sid = managedEndpoint.getCurrentSourceSequenceId();
assertEquals("seq2", sid);
CompositeData[] sequences = managedEndpoint.getSourceSequences(true);
assertEquals(2, sequences.length);
verifySourceSequence(sequences[0]);
verifySourceSequence(sequences[1]);
}
@Test
public void testGetDestinationSequences() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
String[] sids = managedEndpoint.getDestinationSequenceIds();
assertEquals(2, sids.length);
assertTrue(("seq3".equals(sids[0]) || "seq3".equals(sids[1]))
&& ("seq4".equals(sids[0]) || "seq4".equals(sids[1])));
CompositeData[] sequences = managedEndpoint.getDestinationSequences();
assertEquals(2, sequences.length);
verifyDestinationSequence(sequences[0]);
verifyDestinationSequence(sequences[1]);
}
@Test
public void testGetRetransmissionStatus() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
TestRetransmissionQueue rq = (TestRetransmissionQueue)manager.getRetransmissionQueue();
CompositeData status = managedEndpoint.getRetransmissionStatus("seq1", 3L);
assertNull(status);
status = managedEndpoint.getRetransmissionStatus("seq1", 2L);
assertNotNull(status);
verifyRetransmissionStatus(status, 2L, rq.getRetransmissionStatus());
}
@Test
public void testSuspendAndResumeSourceQueue() throws Exception {
ManagedRMEndpoint managedEndpoint = createTestManagedRMEndpoint();
TestRetransmissionQueue rq = (TestRetransmissionQueue)manager.getRetransmissionQueue();
assertFalse(rq.isSuspended("seq1"));
managedEndpoint.suspendSourceQueue("seq1");
assertTrue(rq.isSuspended("seq1"));
managedEndpoint.resumeSourceQueue("seq1");
assertFalse(rq.isSuspended("seq1"));
}
private void verifySourceSequence(CompositeData cd) {
Object key = cd.get("sequenceId");
if ("seq1".equals(key)) {
verifySourceSequence(cd, "seq1", 5L, 2);
} else if ("seq2".equals(key)) {
verifySourceSequence(cd, "seq2", 4L, 1);
} else {
fail("Unexpected sequence: " + key);
}
}
private void verifySourceSequence(CompositeData cd, String sid, long num, int qsize) {
assertTrue(sid.equals(cd.get("sequenceId"))
&& num == ((Long)cd.get("currentMessageNumber")).longValue()
&& qsize == ((Integer)cd.get("queuedMessageCount")).intValue());
}
private void verifyDestinationSequence(CompositeData cd) {
Object key = cd.get("sequenceId");
assertTrue("seq3".equals(key) || "seq4".equals(key));
}
private void verifyRetransmissionStatus(CompositeData cd, long num, RetryStatus status) {
assertEquals(num, cd.get("messageNumber"));
assertEquals(status.getRetries(), cd.get("retries"));
assertEquals(status.getNext(), cd.get("next"));
assertEquals(status.getPrevious(), cd.get("previous"));
assertEquals(status.getNextInterval(), cd.get("nextInterval"));
assertEquals(status.getBackoff(), cd.get("backOff"));
}
private ManagedRMEndpoint createTestManagedRMEndpoint() {
manager = new RMManager();
RMEndpoint rme = control.createMock(RMEndpoint.class);
EndpointReferenceType ref = RMUtils.createReference(TEST_URI);
Source source = new Source(rme);
Destination destination = new Destination(rme);
RetransmissionQueue rq = new TestRetransmissionQueue();
manager.setRetransmissionQueue(rq);
manager.initialise();
List<SourceSequence> sss = createTestSourceSequences(source, ref);
List<DestinationSequence> dss = createTestDestinationSequences(destination, ref);
EasyMock.expect(rme.getManager()).andReturn(manager).anyTimes();
EasyMock.expect(rme.getSource()).andReturn(source).anyTimes();
EasyMock.expect(rme.getDestination()).andReturn(destination).anyTimes();
control.replay();
setCurrentMessageNumber(sss.get(0), 5L);
setCurrentMessageNumber(sss.get(1), 4L);
source.addSequence(sss.get(0));
source.addSequence(sss.get(1));
source.setCurrent(sss.get(1));
destination.addSequence(dss.get(0));
destination.addSequence(dss.get(1));
return new ManagedRMEndpoint(rme);
}
private void setCurrentMessageNumber(SourceSequence ss, long num) {
for (int i = 0; i < num; i++) {
ss.nextMessageNumber();
}
}
private List<SourceSequence> createTestSourceSequences(Source source,
EndpointReferenceType to) {
List<SourceSequence> sss = new ArrayList<>();
sss.add(createTestSourceSequence(source, "seq1", to,
ProtocolVariation.RM10WSA200408, new long[]{1L, 1L, 3L, 3L}));
sss.add(createTestSourceSequence(source, "seq2", to,
ProtocolVariation.RM11WSA200508, new long[]{1L, 1L, 3L, 3L}));
return sss;
}
private List<DestinationSequence> createTestDestinationSequences(Destination destination,
EndpointReferenceType to) {
List<DestinationSequence> dss = new ArrayList<>();
dss.add(createTestDestinationSequence(destination, "seq3", to,
ProtocolVariation.RM10WSA200408, new long[]{1L, 1L, 3L, 3L}));
dss.add(createTestDestinationSequence(destination, "seq4", to,
ProtocolVariation.RM11WSA200508, new long[]{1L, 1L, 3L, 3L}));
return dss;
}
private SourceSequence createTestSourceSequence(Source source, String sid,
EndpointReferenceType to,
ProtocolVariation protocol, long[] acked) {
Identifier identifier = RMUtils.getWSRMFactory().createIdentifier();
identifier.setValue(sid);
SourceSequence ss = new SourceSequence(identifier, protocol);
ss.setSource(source);
ss.setTarget(to);
List<SequenceAcknowledgement.AcknowledgementRange> ranges =
ss.getAcknowledgement().getAcknowledgementRange();
for (int i = 0; i < acked.length; i += 2) {
ranges.add(createAcknowledgementRange(acked[i], acked[i + 1]));
}
return ss;
}
private DestinationSequence createTestDestinationSequence(Destination destination, String sid,
EndpointReferenceType to,
ProtocolVariation protocol, long[] acked) {
Identifier identifier = RMUtils.getWSRMFactory().createIdentifier();
identifier.setValue(sid);
DestinationSequence ds = new DestinationSequence(identifier, to, null, protocol);
ds.setDestination(destination);
List<SequenceAcknowledgement.AcknowledgementRange> ranges =
ds.getAcknowledgment().getAcknowledgementRange();
for (int i = 0; i < acked.length; i += 2) {
ranges.add(createAcknowledgementRange(acked[i], acked[i + 1]));
}
return ds;
}
private SequenceAcknowledgement.AcknowledgementRange createAcknowledgementRange(long l, long u) {
SequenceAcknowledgement.AcknowledgementRange range =
new SequenceAcknowledgement.AcknowledgementRange();
range.setLower(l);
range.setUpper(u);
return range;
}
private Endpoint createTestEndpoint() throws Exception {
ServiceInfo svci = new ServiceInfo();
svci.setName(new QName(TEST_URI, "testService"));
Service svc = new ServiceImpl(svci);
SoapBindingInfo binding = new SoapBindingInfo(svci, WSDLConstants.NS_SOAP11);
binding.setTransportURI(WSDLConstants.NS_SOAP_HTTP_TRANSPORT);
EndpointInfo ei = new EndpointInfo();
ei.setAddress(TEST_URI);
ei.setName(new QName(TEST_URI, "testPort"));
ei.setBinding(binding);
ei.setService(svci);
return new EndpointImpl(bus, svc, ei);
}
private RMEndpoint createTestRMEndpoint() throws Exception {
Message message = control.createMock(Message.class);
Exchange exchange = control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getEndpoint()).andReturn(endpoint);
control.replay();
return manager.getReliableEndpoint(message);
}
private class TestRetransmissionQueue implements RetransmissionQueue {
private Set<String> suspended = new HashSet<>();
private RetryStatus status = new TestRetransmissionStatus();
private Map<String, List<Long>> numlists = new HashMap<>();
TestRetransmissionQueue() {
numlists.put("seq1", new ArrayList<>());
numlists.put("seq2", new ArrayList<>());
Collections.addAll(numlists.get("seq1"), 2L, 4L);
Collections.addAll(numlists.get("seq2"), 3L);
}
public int countUnacknowledged(SourceSequence seq) {
final String key = seq.getIdentifier().getValue();
List<Long> list = numlists.get(key);
return list != null ? list.size() : 0;
}
public boolean isEmpty() {
return false;
}
public void addUnacknowledged(Message message) {
}
public void purgeAcknowledged(SourceSequence seq) {
}
public void purgeAll(SourceSequence seq) {
final String key = seq.getIdentifier().getValue();
List<Long> list = numlists.get(key);
if (list != null) {
list.clear();
}
}
public List<Long> getUnacknowledgedMessageNumbers(SourceSequence seq) {
final String key = seq.getIdentifier().getValue();
List<Long> list = numlists.get(key);
return list != null ? list : new ArrayList<>();
}
public RetryStatus getRetransmissionStatus(SourceSequence seq, long num) {
final String key = seq.getIdentifier().getValue();
List<Long> list = numlists.get(key);
return list.contains(num) ? status : null;
}
public Map<Long, RetryStatus> getRetransmissionStatuses(SourceSequence seq) {
return null;
}
public void start() {
}
public void stop(SourceSequence seq) {
}
public void suspend(SourceSequence seq) {
suspended.add(seq.getIdentifier().getValue());
}
public void resume(SourceSequence seq) {
suspended.remove(seq.getIdentifier().getValue());
}
boolean isSuspended(String sid) {
return suspended.contains(sid);
}
RetryStatus getRetransmissionStatus() {
return status;
}
public int countUnacknowledged() {
return numlists.get("seq1").size() + numlists.get("seq2").size();
}
}
private static class TestRetransmissionStatus implements RetryStatus {
private long interval = 300000L;
private Date next = new Date(System.currentTimeMillis() + interval / 2);
private Date previous = new Date(next.getTime() - interval);
public Date getNext() {
return next;
}
public Date getPrevious() {
return previous;
}
public int getRetries() {
return 2;
}
public int getMaxRetries() {
return -1;
}
public long getNextInterval() {
return interval;
}
public long getBackoff() {
return 1L;
}
public boolean isPending() {
return false;
}
public boolean isSuspended() {
return false;
}
}
} |
9238419796b86625318f2852e63e0c37a371754f | 616 | java | Java | src/main/java/org/alliancegenome/agr_submission/entities/log/LogApiDTO.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 1 | 2021-03-15T17:54:23.000Z | 2021-03-15T17:54:23.000Z | src/main/java/org/alliancegenome/agr_submission/entities/log/LogApiDTO.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 4 | 2021-12-14T21:18:36.000Z | 2022-02-28T01:33:04.000Z | src/main/java/org/alliancegenome/agr_submission/entities/log/LogApiDTO.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 5 | 2020-05-13T11:32:02.000Z | 2021-05-21T04:08:49.000Z | 22.814815 | 57 | 0.797078 | 998,371 | package org.alliancegenome.agr_submission.entities.log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.alliancegenome.agr_submission.entities.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter @Setter @ToString
public class LogApiDTO {
public String requestMethod;
public String headersString;
public String address;
public List<String> userAgent = new ArrayList<String>();
public HashMap<String, List<String>> queryParameters;
public HashMap<String, List<String>> pathParameters;
public String requestUri;
public User user;
}
|
92384380308ba37aee0359ac3d78665352fabc10 | 6,482 | java | Java | scimono-compliance-tests/src/main/java/com/sap/scimono/scim/system/tests/extensions/GroupClientScimResponseExtension.java | thenewpyjiang/scimono | f51ac85b4e40e6df7700eb07aa884b126133c932 | [
"Apache-2.0"
] | 24 | 2019-04-16T10:50:20.000Z | 2022-03-23T09:44:44.000Z | scimono-compliance-tests/src/main/java/com/sap/scimono/scim/system/tests/extensions/GroupClientScimResponseExtension.java | thenewpyjiang/scimono | f51ac85b4e40e6df7700eb07aa884b126133c932 | [
"Apache-2.0"
] | 91 | 2019-04-16T11:38:09.000Z | 2022-03-23T09:19:44.000Z | scimono-compliance-tests/src/main/java/com/sap/scimono/scim/system/tests/extensions/GroupClientScimResponseExtension.java | thenewpyjiang/scimono | f51ac85b4e40e6df7700eb07aa884b126133c932 | [
"Apache-2.0"
] | 39 | 2019-04-16T11:05:23.000Z | 2022-03-29T11:57:27.000Z | 34.849462 | 142 | 0.789725 | 998,372 | package com.sap.scimono.scim.system.tests.extensions;
import com.sap.scimono.client.GroupRequest;
import com.sap.scimono.client.SCIMResponse;
import com.sap.scimono.client.query.IdentityPageQuery;
import com.sap.scimono.client.query.IndexPageQuery;
import com.sap.scimono.entity.Group;
import com.sap.scimono.entity.paging.PagedByIdentitySearchResult;
import com.sap.scimono.entity.paging.PagedByIndexSearchResult;
import com.sap.scimono.entity.patch.PatchBody;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public abstract class GroupClientScimResponseExtension implements BeforeEachCallback, AfterEachCallback, BeforeAllCallback, AfterAllCallback {
private static final Logger logger = LoggerFactory.getLogger(GroupClientScimResponseExtension.class);
private final Map<String, Group> managedResources = new HashMap<>();
private final GroupRequest groupRequest;
private final GroupFailSafeClient groupFailSafeClient;
public GroupClientScimResponseExtension(GroupRequest groupRequest) {
this.groupRequest = groupRequest;
this.groupFailSafeClient = new GroupFailSafeClient(this);
}
public void after(ExtensionContext extensionContext) {
logger.info("Deleting managed resources by test: {}", extensionContext.getDisplayName());
clearManagedResources();
}
public void before(ExtensionContext extensionContext) {
}
public void clearManagedResources() {
new HashSet<>(managedResources.keySet()).forEach(groupFailSafeClient::delete);
managedResources.clear();
}
public GroupFailSafeClient getFailSafeClient() {
return groupFailSafeClient;
}
public SCIMResponse<Group> createGroup(Group group) {
SCIMResponse<Group> createGroupResponse = groupRequest.createGroup(group);
if (createGroupResponse.isSuccess()) {
Group createdGroup = createGroupResponse.get();
managedResources.put(createdGroup.getId(), createdGroup);
}
return createGroupResponse;
}
public SCIMResponse<Void> deleteGroup(String groupId) {
SCIMResponse<Void> scimResponse = groupRequest.deleteGroup(groupId);
if(scimResponse.isSuccess()) {
managedResources.remove(groupId);
}
return scimResponse;
}
public SCIMResponse<Group> readSingleGroup(String id) {
return groupRequest.readSingleGroup(id);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readAllGroups() {
return groupRequest.readAllGroups();
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readAllGroups(String filter) {
return groupRequest.readAllGroups(filter);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroups() {
return groupRequest.readMultipleGroups();
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroups(String filter) {
return groupRequest.readMultipleGroups(filter);
}
public SCIMResponse<PagedByIdentitySearchResult<Group>> readMultipleGroups(IdentityPageQuery identityPageQuery) {
return groupRequest.readMultipleGroups(identityPageQuery);
}
public SCIMResponse<PagedByIdentitySearchResult<Group>> readMultipleGroups(IdentityPageQuery identityPageQuery, String filter) {
return groupRequest.readMultipleGroups(identityPageQuery, filter);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroups(IndexPageQuery indexPageQuery) {
return groupRequest.readMultipleGroups(indexPageQuery);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroups(IndexPageQuery indexPageQuery, String filter) {
return groupRequest.readMultipleGroups(indexPageQuery, filter);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroupsWithoutPaging() {
return groupRequest.readMultipleGroupsWithoutPaging();
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroupsWithoutPaging(String filter) {
return groupRequest.readMultipleGroupsWithoutPaging(filter);
}
public SCIMResponse<PagedByIndexSearchResult<Group>> readMultipleGroupsIndexed(Response response) {
return groupRequest.readMultipleGroupsIndexed(response);
}
public SCIMResponse<Group> updateGroup(Group group) {
return groupRequest.updateGroup(group);
}
public SCIMResponse<Void> patchGroup(PatchBody patchBody, String groupId) {
return groupRequest.patchGroup(patchBody, groupId);
}
public static GroupClientScimResponseExtension forClearingAfterAllExecutions(GroupRequest groupRequest) {
return new GroupClientScimResponseExtensionAroundAll(groupRequest);
}
public static GroupClientScimResponseExtension forClearingAfterEachExecutions(GroupRequest groupRequest) {
return new GroupClientScimResponseExtensionAroundEach(groupRequest);
}
public static class GroupClientScimResponseExtensionAroundEach extends GroupClientScimResponseExtension {
private GroupClientScimResponseExtensionAroundEach(GroupRequest groupRequest) {
super(groupRequest);
}
@Override
public void beforeAll(ExtensionContext extensionContext) {
// Not implemented
}
@Override
public void afterAll(ExtensionContext extensionContext) {
// Not implemented
}
@Override
public void beforeEach(ExtensionContext extensionContext) {
super.before(extensionContext);
}
@Override
public void afterEach(ExtensionContext extensionContext) {
super.after(extensionContext);
}
}
public static class GroupClientScimResponseExtensionAroundAll extends GroupClientScimResponseExtension {
private GroupClientScimResponseExtensionAroundAll(GroupRequest groupRequest) {
super(groupRequest);
}
@Override
public void beforeAll(ExtensionContext extensionContext) {
super.before(extensionContext);
}
@Override public void afterAll(ExtensionContext extensionContext) {
super.after(extensionContext);
}
@Override
public void beforeEach(ExtensionContext extensionContext) {
// Not implemented
}
@Override
public void afterEach(ExtensionContext extensionContext) {
// Not implemented
}
}
}
|
9238447e2a2ade0c859be6bad0c1ef9c251509a0 | 465 | java | Java | common/src/test/java/cn/edu/cug/cs/gtl/geom/DEMGridTest.java | ZhenwenHe/gtl-java | 01edf4814240ef5aaa3cc4fc5df590de2228d0c1 | [
"MIT"
] | 2 | 2019-10-11T09:02:29.000Z | 2019-11-19T13:26:28.000Z | common/src/test/java/cn/edu/cug/cs/gtl/geom/DEMGridTest.java | zhaohhit/gtl-java | 63581c2bfca3ea989a4ba1497dca5e3c36190d46 | [
"MIT"
] | 2 | 2021-12-10T01:25:16.000Z | 2021-12-14T21:35:12.000Z | common/src/test/java/cn/edu/cug/cs/gtl/geom/DEMGridTest.java | zhaohhit/gtl-java | 63581c2bfca3ea989a4ba1497dca5e3c36190d46 | [
"MIT"
] | 1 | 2019-10-11T09:00:29.000Z | 2019-10-11T09:00:29.000Z | 12.916667 | 39 | 0.574194 | 998,373 | package cn.edu.cug.cs.gtl.geom;
import org.junit.Test;
import static org.junit.Assert.*;
public class DEMGridTest {
@Test
public void isEmpty() {
}
@Test
public void cloneTest() {
}
@Test
public void load() {
}
@Test
public void store() {
}
@Test
public void getByteArraySize() {
}
@Test
public void getTextureParameter() {
}
@Test
public void setTextureParameter() {
}
} |
923845836f4ab92ddf180d61775480d498ca8be6 | 727 | java | Java | app/src/main/java/com/rxjava2/android/samples/ui/rxbus/RxBus.java | AnandTraveller/RxJava2-Android-Samples-master | c95135202b9cacb4a1dfb6fa8dc9fac8eb29f2fd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rxjava2/android/samples/ui/rxbus/RxBus.java | AnandTraveller/RxJava2-Android-Samples-master | c95135202b9cacb4a1dfb6fa8dc9fac8eb29f2fd | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rxjava2/android/samples/ui/rxbus/RxBus.java | AnandTraveller/RxJava2-Android-Samples-master | c95135202b9cacb4a1dfb6fa8dc9fac8eb29f2fd | [
"Apache-2.0"
] | null | null | null | 19.131579 | 69 | 0.647868 | 998,374 | package com.rxjava2.android.samples.ui.rxbus;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
/**
* Created by amitshekhar on 06/02/17.
*/
public class RxBus {
public RxBus() {
}
private PublishSubject<Object> bus = PublishSubject.create();
private PublishSubject<Object> bus_two = PublishSubject.create();
public void send(Object o) {
bus.onNext(o);
}
public void sendTwo(Object o) {
bus_two.onNext(o);
}
public Observable<Object> toObservable() {
return bus;
}
public Observable<Object> toObservableTwo() {
return bus_two;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}
|
923846435fb8cd33b25462832763593df0ace10a | 1,170 | java | Java | platform/platform-impl/src/com/intellij/remote/PathMappingProvider.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | platform/platform-impl/src/com/intellij/remote/PathMappingProvider.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | platform/platform-impl/src/com/intellij/remote/PathMappingProvider.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:06.000Z | 2018-10-03T12:35:06.000Z | 35.454545 | 135 | 0.818803 | 998,375 | package com.intellij.remote;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.util.PathMappingSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* @author traff
*/
public abstract class PathMappingProvider {
public static ExtensionPointName<PathMappingProvider> EP_NAME = ExtensionPointName.create("com.intellij.remote.pathMappingProvider");
public static List<PathMappingProvider> getSuitableMappingProviders(final RemoteSdkAdditionalData data) {
return Lists
.newArrayList(Iterables.filter(Arrays.asList(EP_NAME.getExtensions()), provider -> provider.accepts(data)));
}
@NotNull
public abstract String getProviderPresentableName(@NotNull RemoteSdkAdditionalData data);
public abstract boolean accepts(@Nullable RemoteSdkAdditionalData data);
@NotNull
public abstract PathMappingSettings getPathMappingSettings(@NotNull Project project, @NotNull RemoteSdkAdditionalData data);
}
|
9238466657e7c9dc96ea6e3df02fae70a2d3889b | 133 | java | Java | app/src/main/java/com/examen/pablo/jm_xml/Estacion.java | JMedinilla/acdat_ev1_XML | 9004cd090e2223847ba4761b9d8737b19c13e0a4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/examen/pablo/jm_xml/Estacion.java | JMedinilla/acdat_ev1_XML | 9004cd090e2223847ba4761b9d8737b19c13e0a4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/examen/pablo/jm_xml/Estacion.java | JMedinilla/acdat_ev1_XML | 9004cd090e2223847ba4761b9d8737b19c13e0a4 | [
"Apache-2.0"
] | null | null | null | 14.777778 | 32 | 0.684211 | 998,376 | package com.examen.pablo.jm_xml;
public class Estacion {
String titulo;
String estado;
String bicisD;
String url;
}
|
9238471b0deb990745067836f19d7c6c3d8a324a | 6,079 | java | Java | src/main/java/tv/mapper/embellishcraft/furniture/world/level/block/PlateBlock.java | KillerMapper/EmbellishCraft | ebb412c74ed258831a3d209236b3beb1f00ca0d4 | [
"MIT"
] | null | null | null | src/main/java/tv/mapper/embellishcraft/furniture/world/level/block/PlateBlock.java | KillerMapper/EmbellishCraft | ebb412c74ed258831a3d209236b3beb1f00ca0d4 | [
"MIT"
] | 1 | 2019-07-16T02:36:47.000Z | 2019-07-17T01:38:14.000Z | src/main/java/tv/mapper/embellishcraft/furniture/world/level/block/PlateBlock.java | KillerMapper/EmbellishCraft | ebb412c74ed258831a3d209236b3beb1f00ca0d4 | [
"MIT"
] | null | null | null | 42.215278 | 159 | 0.686626 | 998,377 | package tv.mapper.embellishcraft.furniture.world.level.block;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SimpleWaterloggedBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import tv.mapper.embellishcraft.furniture.world.item.InitFurnitureItems;
import tv.mapper.mapperbase.world.level.block.CustomBlock;
import tv.mapper.mapperbase.world.level.block.ToolTiers;
import tv.mapper.mapperbase.world.level.block.ToolTypes;
public class PlateBlock extends CustomBlock implements SimpleWaterloggedBlock
{
public static final IntegerProperty PLATES = IntegerProperty.create("plates", 1, 8);
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
VoxelShape plate_1 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 2.0D, 14.0D);
VoxelShape plate_2 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 4.0D, 14.0D);
VoxelShape plate_3 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 6.0D, 14.0D);
VoxelShape plate_4 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 8.0D, 14.0D);
VoxelShape plate_5 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 10.0D, 14.0D);
VoxelShape plate_6 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 12.0D, 14.0D);
VoxelShape plate_7 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 14.0D, 14.0D);
VoxelShape plate_8 = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D);
public PlateBlock(Properties properties, ToolTypes tool)
{
super(properties, tool);
this.registerDefaultState(this.stateDefinition.any().setValue(PLATES, 1).setValue(WATERLOGGED, Boolean.valueOf(false)));
}
public PlateBlock(Properties properties, ToolTypes tool, ToolTiers tier)
{
super(properties, tool, tier);
this.registerDefaultState(this.stateDefinition.any().setValue(PLATES, 1).setValue(WATERLOGGED, Boolean.valueOf(false)));
}
public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context)
{
switch(state.getValue(PLATES))
{
case 1:
return plate_1;
case 2:
return plate_2;
case 3:
return plate_3;
case 4:
return plate_4;
case 5:
return plate_5;
case 6:
return plate_6;
case 7:
return plate_7;
case 8:
return plate_8;
default:
return plate_1;
}
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit)
{
if(!player.isShiftKeyDown() && state.getValue(PLATES) < 8)
{
ItemStack stack = ItemStack.EMPTY;
if(player.getMainHandItem().getItem() == InitFurnitureItems.PLATE_ITEM.get())
stack = player.getMainHandItem();
else if(player.getOffhandItem().getItem() == InitFurnitureItems.PLATE_ITEM.get())
stack = player.getOffhandItem();
if(stack.getItem() == InitFurnitureItems.PLATE_ITEM.get())
{
worldIn.setBlockAndUpdate(pos, state.setValue(PLATES, state.getValue(PLATES) + 1));
if(!worldIn.isClientSide)
worldIn.playSound(null, pos, SoundEvents.GLASS_PLACE, SoundSource.BLOCKS, 1.0F, 1.0F);
if(!player.isCreative())
stack.setCount(stack.getCount() - 1);
return InteractionResult.SUCCESS;
}
}
return InteractionResult.FAIL;
}
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
{
builder.add(PLATES, WATERLOGGED);
}
public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos)
{
BlockPos blockpos = pos.below();
BlockState blockstate = worldIn.getBlockState(blockpos);
if(blockstate.getBlock() instanceof PlateBlock && blockstate.getValue(PLATES) == 8)
return true;
else
return canSupportCenter(worldIn, pos.below(), Direction.UP);
}
@SuppressWarnings("deprecation")
public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos)
{
if(stateIn.getValue(WATERLOGGED))
{
worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn));
}
if(facing == Direction.DOWN && !this.canSurvive(stateIn, worldIn, currentPos))
return Blocks.AIR.defaultBlockState();
return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos);
}
@SuppressWarnings("deprecation")
public FluidState getFluidState(BlockState state)
{
return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
}
} |
923847cfb8920477630819d9de94d05f7484bf36 | 173 | java | Java | src/main/java/com/example/demo/service/UserFeedService.java | panwar21/witter | d2090725aef11ec2d96fcecf48b43a1abc791dbf | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/service/UserFeedService.java | panwar21/witter | d2090725aef11ec2d96fcecf48b43a1abc791dbf | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/service/UserFeedService.java | panwar21/witter | d2090725aef11ec2d96fcecf48b43a1abc791dbf | [
"MIT"
] | null | null | null | 14.416667 | 37 | 0.774566 | 998,378 | package com.example.demo.service;
import java.util.List;
import com.example.demo.model.Post;
public interface UserFeedService {
List<Post> getFeed(String userName);
} |
92384819a64468e6c6c223689ea9bd03d3c8115b | 2,245 | java | Java | src/test/java/hu/ibello/data/TestDataToolsTest.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | 1 | 2021-04-21T15:06:43.000Z | 2021-04-21T15:06:43.000Z | src/test/java/hu/ibello/data/TestDataToolsTest.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | null | null | null | src/test/java/hu/ibello/data/TestDataToolsTest.java | kokog78/ibello-api | a0245662f3824dfbe0d0a39a24b002f90d080293 | [
"Apache-2.0"
] | null | null | null | 28.417722 | 84 | 0.776837 | 998,379 | package hu.ibello.data;
import static org.assertj.core.api.Assertions.assertThat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import hu.ibello.core.Name;
public class TestDataToolsTest {
@Test(expected = NullPointerException.class)
public void getEnumName_should_throw_NPE_if_parameter_is_null() throws Exception {
TestDataTools.getEnumName(null);
}
@Test
public void getEnumName_should_read_name_annotation() throws Exception {
String result = TestDataTools.getEnumName(TestEnum.X);
assertThat(result).isEqualTo("X name");
}
@Test
public void getEnumName_should_return_original_name() throws Exception {
String result = TestDataTools.getEnumName(TestEnum.Y);
assertThat(result).isEqualTo("Y");
}
@Test(expected = NullPointerException.class)
public void getClassName_should_throw_NPE_if_parameter_is_null() throws Exception {
TestDataTools.getClassName(null);
}
@Test
public void getClassName_should_read_name_annotation() throws Exception {
String result = TestDataTools.getClassName(TestEnum.class);
assertThat(result).isEqualTo("Name of enum");
}
@Test
public void getClassName_should_result_simple_name() throws Exception {
String result = TestDataTools.getClassName(TestDataToolsTest.class);
assertThat(result).isEqualTo("TestDataToolsTest");
}
@Test
public void getTimestamp_should_return_the_current_date() throws Exception {
String expected = new SimpleDateFormat("yyyyMMdd").format(new Date());
String result = TestDataTools.getTimestamp(8);
assertThat(result).isEqualTo(expected);
}
@Test
public void getTimestamp_should_return_the_whole_timestamp() throws Exception {
String expected = new SimpleDateFormat("yyyyMMdd").format(new Date());
String result1 = TestDataTools.getTimestamp(20);
String result2 = TestDataTools.getTimestamp(20);
assertThat(result1).startsWith(expected).hasSize(17).isEqualTo(result2);
}
@Test
public void getUUID_should_return_the_uuid() throws Exception {
String expected = TestDataTools.getUUID();
String result = TestDataTools.getUUID();
assertThat(result).isNotNull().isEqualTo(expected);
}
@Name("Name of enum")
public enum TestEnum {
@Name("X name")
X,
Y;
}
}
|
92384a5984dbe10dd9cf2d761fe7996d36a8980d | 913 | java | Java | src/frangel/model/statement/Statement.java | automenta/FrAngel | a6ba45eabfd96cfd619dbe4de222334dd2e86468 | [
"Apache-2.0"
] | 20 | 2018-10-30T19:21:00.000Z | 2022-03-08T10:26:40.000Z | src/frangel/model/statement/Statement.java | automenta/FrAngel | a6ba45eabfd96cfd619dbe4de222334dd2e86468 | [
"Apache-2.0"
] | null | null | null | src/frangel/model/statement/Statement.java | automenta/FrAngel | a6ba45eabfd96cfd619dbe4de222334dd2e86468 | [
"Apache-2.0"
] | 9 | 2019-01-04T14:55:41.000Z | 2021-12-13T11:38:39.000Z | 26.085714 | 87 | 0.624315 | 998,380 | package frangel.model.statement;
public abstract class Statement {
private int indent;
// Includes terminating newline
public String toJava(boolean indent) {
StringBuilder sb = new StringBuilder();
toJava(sb, false);
return sb.toString();
}
public String toJava() {
return toJava(true);
}
public abstract void toJava(StringBuilder sb, boolean indent);
public void toJava(StringBuilder sb) {
toJava(sb, true);
}
public abstract void encode(StringBuilder sb); // See comment for Program.encode()
@Override
public abstract boolean equals(Object obj);
@Override
public abstract int hashCode();
@Override
public abstract Statement clone();
public int getIndent() {
return indent;
}
public void setIndent(int indent) {
this.indent = indent;
}
}
|
92384a8c6ccd5f73c92f96d9669a0036173b896a | 6,154 | java | Java | config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java | ankeway/nacos | 489efb3292b68929ed0c60b4e9c65d9ba8a705d8 | [
"Apache-2.0"
] | 407 | 2022-03-16T08:09:38.000Z | 2022-03-31T12:27:10.000Z | config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java | ankeway/nacos | 489efb3292b68929ed0c60b4e9c65d9ba8a705d8 | [
"Apache-2.0"
] | 25 | 2022-03-22T04:27:31.000Z | 2022-03-30T08:47:28.000Z | config/src/main/java/com/alibaba/nacos/config/server/service/ClientTrackService.java | ankeway/nacos | 489efb3292b68929ed0c60b4e9c65d9ba8a705d8 | [
"Apache-2.0"
] | 109 | 2022-03-21T17:30:44.000Z | 2022-03-31T09:36:28.000Z | 33.445652 | 118 | 0.654046 | 998,381 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.model.SubscriberStatus;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 跟踪客户端md5的服务。 一段时间没有比较md5后,就删除IP对应的记录。
*
* @author Nacos
*/
public class ClientTrackService {
/**
* 跟踪客户端md5.
*/
static public void trackClientMd5(String ip, Map<String, String> clientMd5Map) {
ClientRecord record = getClientRecord(ip);
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.putAll(clientMd5Map);
}
static public void trackClientMd5(String ip, Map<String, String> clientMd5Map,
Map<String, Long> clientlastPollingTSMap) {
ClientRecord record = getClientRecord(ip);
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.putAll(clientMd5Map);
record.groupKey2pollingTsMap.putAll(clientlastPollingTSMap);
}
static public void trackClientMd5(String ip, String groupKey, String clientMd5) {
ClientRecord record = getClientRecord(ip);
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.put(groupKey, clientMd5);
record.groupKey2pollingTsMap.put(groupKey, record.lastTime);
}
/**
* 返回订阅者客户端个数
*/
static public int subscribeClientCount() {
return clientRecords.size();
}
/**
* 返回所有订阅者个数
*/
static public long subscriberCount() {
long count = 0;
for (ClientRecord record : clientRecords.values()) {
count += record.groupKey2md5Map.size();
}
return count;
}
/**
* groupkey -> SubscriberStatus
*/
static public Map<String, SubscriberStatus> listSubStatus(String ip) {
Map<String, SubscriberStatus> status = new HashMap<String, SubscriberStatus>(100);
ClientRecord record = getClientRecord(ip);
if (record == null) {
return status;
}
for (Map.Entry<String, String> entry : record.groupKey2md5Map.entrySet()) {
String groupKey = entry.getKey();
String clientMd5 = entry.getValue();
long lastPollingTs = record.groupKey2pollingTsMap.get(groupKey);
boolean isUpdate = ConfigService.isUptodate(groupKey, clientMd5);
status.put(groupKey, new SubscriberStatus(groupKey, isUpdate, clientMd5, lastPollingTs));
}
return status;
}
/**
* ip -> SubscriberStatus
*/
static public Map<String, SubscriberStatus> listSubsByGroup(String groupKey) {
Map<String, SubscriberStatus> subs = new HashMap<String, SubscriberStatus>(100);
for (ClientRecord clientRec : clientRecords.values()) {
String clientMd5 = clientRec.groupKey2md5Map.get(groupKey);
Long lastPollingTs = clientRec.groupKey2pollingTsMap.get(groupKey);
if (null != clientMd5 && lastPollingTs != null) {
Boolean isUpdate = ConfigService.isUptodate(groupKey, clientMd5);
subs.put(clientRec.ip, new SubscriberStatus(groupKey, isUpdate, clientMd5, lastPollingTs));
}
}
return subs;
}
/**
* 指定订阅者IP,查找数据是否最新。 groupKey -> isUptodate
*/
static public Map<String, Boolean> isClientUptodate(String ip) {
Map<String, Boolean> result = new HashMap<String, Boolean>(100);
for (Map.Entry<String, String> entry : getClientRecord(ip).groupKey2md5Map.entrySet()) {
String groupKey = entry.getKey();
String clientMd5 = entry.getValue();
Boolean isuptodate = ConfigService.isUptodate(groupKey, clientMd5);
result.put(groupKey, isuptodate);
}
return result;
}
/**
* 指定groupKey,查找所有订阅者以及数据是否最新。 IP -> isUptodate
*/
static public Map<String, Boolean> listSubscriberByGroup(String groupKey) {
Map<String, Boolean> subs = new HashMap<String, Boolean>(100);
for (ClientRecord clientRec : clientRecords.values()) {
String clientMd5 = clientRec.groupKey2md5Map.get(groupKey);
if (null != clientMd5) {
Boolean isuptodate = ConfigService.isUptodate(groupKey, clientMd5);
subs.put(clientRec.ip, isuptodate);
}
}
return subs;
}
/**
* 找到指定clientIp对应的记录。
*/
static private ClientRecord getClientRecord(String clientIp) {
ClientRecord record = clientRecords.get(clientIp);
if (null != record) {
return record;
}
clientRecords.putIfAbsent(clientIp, new ClientRecord(clientIp));
return clientRecords.get(clientIp);
}
static public void refreshClientRecord() {
clientRecords = new ConcurrentHashMap<String, ClientRecord>(50);
}
/**
* 所有客户端记录。遍历 >> 新增/删除
*/
static volatile ConcurrentMap<String, ClientRecord> clientRecords = new ConcurrentHashMap<String, ClientRecord>();
}
/**
* 保存客户端拉数据的记录。
*/
class ClientRecord {
final String ip;
volatile long lastTime;
final ConcurrentMap<String, String> groupKey2md5Map;
final ConcurrentMap<String, Long> groupKey2pollingTsMap;
ClientRecord(String clientIp) {
ip = clientIp;
groupKey2md5Map = new ConcurrentHashMap<String, String>(20, 0.75f, 1);
groupKey2pollingTsMap = new ConcurrentHashMap<String, Long>(20, 0.75f, 1);
}
}
|
92384c852a8e008f9acb4211a8ab846ef31aa5f0 | 1,964 | java | Java | spring-boot-jpa/src/main/java/br/com/regissanme/springbootjpa/controller/EventoController.java | regissanme/spring-boot-estudos | 8fbee1aee0a09375545ce3f3974558556bd78683 | [
"MIT"
] | null | null | null | spring-boot-jpa/src/main/java/br/com/regissanme/springbootjpa/controller/EventoController.java | regissanme/spring-boot-estudos | 8fbee1aee0a09375545ce3f3974558556bd78683 | [
"MIT"
] | null | null | null | spring-boot-jpa/src/main/java/br/com/regissanme/springbootjpa/controller/EventoController.java | regissanme/spring-boot-estudos | 8fbee1aee0a09375545ce3f3974558556bd78683 | [
"MIT"
] | null | null | null | 32.196721 | 136 | 0.734216 | 998,382 | package br.com.regissanme.springbootjpa.controller;
import br.com.regissanme.springbootjpa.entity.Evento;
import br.com.regissanme.springbootjpa.exceptions.EventoNaoEncontradoException;
import br.com.regissanme.springbootjpa.service.EventoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* Projeto: spring-boot-estudos-jpa
* Desenvolvedor: Reginaldo Santos de Medeiros (regissanme)
* Data: 15/01/2022
* Hora: 13:32
*/
@RestController
@RequestMapping("/api/v1/evento")
public class EventoController {
@Autowired
public EventoService eventoService;
@GetMapping
public ResponseEntity<List<Evento>> findAll() {
return ResponseEntity.status(HttpStatus.OK)
.body(eventoService.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<Evento> findById(@PathVariable Long id) throws EventoNaoEncontradoException {
return ResponseEntity.status(HttpStatus.OK)
.body(eventoService.findById(id));
}
@PostMapping
public ResponseEntity<Evento> save(@RequestBody @Valid Evento evento) throws EventoNaoEncontradoException {
return ResponseEntity.status(HttpStatus.CREATED)
.body(eventoService.save(evento));
}
@PutMapping("/{id}")
public ResponseEntity<Evento> update(@PathVariable Long id, @RequestBody @Valid Evento evento) throws EventoNaoEncontradoException {
return ResponseEntity.status(HttpStatus.OK)
.body(eventoService.update(id, evento));
}
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable Long id) throws EventoNaoEncontradoException {
eventoService.delete(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}
|
92384c967960b5da304b04545c5acbc65923e025 | 13,296 | java | Java | gua-core/src/main/java/com/github/dandelion/gua/core/generator/GuaJavascriptContentGenerator.java | dandelion/dandelion-gua | 9b51d01ee969d8d77a97b406adfa5bbb8422f9b8 | [
"BSD-3-Clause"
] | 1 | 2015-08-08T09:59:19.000Z | 2015-08-08T09:59:19.000Z | gua-core/src/main/java/com/github/dandelion/gua/core/generator/GuaJavascriptContentGenerator.java | dandelion/dandelion-gua | 9b51d01ee969d8d77a97b406adfa5bbb8422f9b8 | [
"BSD-3-Clause"
] | null | null | null | gua-core/src/main/java/com/github/dandelion/gua/core/generator/GuaJavascriptContentGenerator.java | dandelion/dandelion-gua | 9b51d01ee969d8d77a97b406adfa5bbb8422f9b8 | [
"BSD-3-Clause"
] | 2 | 2017-04-07T01:58:40.000Z | 2020-01-07T16:37:55.000Z | 41.164087 | 363 | 0.598601 | 998,383 | package com.github.dandelion.gua.core.generator;
import com.github.dandelion.core.asset.generator.js.AbstractJsContentGenerator;
import com.github.dandelion.gua.core.*;
import com.github.dandelion.gua.core.field.AnalyticsCreateField;
import com.github.dandelion.gua.core.field.AnalyticsField;
import com.github.dandelion.gua.core.field.ControlHolder;
import com.github.dandelion.gua.core.field.TimingField;
import com.github.dandelion.gua.core.tracker.*;
import com.github.dandelion.gua.core.tracker.send.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class GuaJavascriptContentGenerator extends AbstractJsContentGenerator {
private StringBuilder gua = new StringBuilder("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');");
private boolean needListenerFunction = false;
@Override
public String getAssetContent(HttpServletRequest request) {
return gua.append("\n").append(super.getAssetContent(request)).toString();
}
@Override
protected String getJavascriptContent(HttpServletRequest httpServletRequest) {
GoogleAnalytics analytics = GoogleAnalytics.class.cast(httpServletRequest.getAttribute(GoogleAnalytics.class.getCanonicalName()));
return treatAnalytics(analytics);
}
public String treatAnalytics(GoogleAnalytics analytics) {
StringBuilder builder = new StringBuilder();
for (Tracker tracker : analytics.getAll()) {
createTracker(builder, tracker);
setOnTracker(builder, tracker);
sendOnTracker(builder, tracker);
}
if (needListenerFunction) {
listenerFunction(builder);
}
return builder.toString();
}
private void listenerFunction(StringBuilder builder) {
builder.append("function addListener(element, type, callback) {");
builder.append("if (element.addEventListener) element.addEventListener(type, callback);");
builder.append("else if (element.attachEvent) element.attachEvent('on' + type, callback);");
builder.append("}");
}
private void createTracker(StringBuilder builder, Tracker tracker) {
builder.append("ga('create', '");
builder.append(tracker.getTrackingId());
builder.append("', ");
if (tracker.create().getAll().size() == 0 && tracker.getTrackerName() == null) {
builder.append("'auto'");
} else {
builder.append("{");
boolean firstField = true;
if(tracker.getTrackerName() != null) {
firstField = false;
builder.append("'name': '");
builder.append(tracker.getTrackerName());
builder.append("'");
}
for (Map.Entry<AnalyticsCreateField, String> entry : tracker.create().getAll().entrySet()) {
if(!firstField) {
builder.append(",");
}
firstField = false;
builder.append("'");
builder.append(entry.getKey());
builder.append("': ");
builder.append(ControlHolder.toString(entry.getKey(), entry.getValue()));
}
builder.append("}");
}
builder.append(");");
}
private void setOnTracker(StringBuilder builder, Tracker tracker) {
for (Map.Entry<AnalyticsField, String> entry : tracker.getAll().entrySet()) {
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("set', '");
builder.append(entry.getKey());
builder.append("', ");
builder.append(ControlHolder.toString(entry.getKey(), entry.getValue()));
builder.append(");");
}
}
private void sendOnTracker(StringBuilder builder, Tracker tracker) {
for (Map.Entry<String, SendSection> entry : tracker.sendAll().entrySet()) {
sendPageview(builder, tracker, entry.getValue().accessPageview());
sendEvent(builder, tracker, entry.getValue().accessEvent());
sendException(builder, tracker, entry.getValue().accessException());
sendScreenView(builder, tracker, entry.getValue().accessScreenView());
sendSocial(builder, tracker, entry.getValue().accessSocial());
sendTiming(builder, tracker, entry.getValue().accessTiming());
}
}
private void sendTiming(StringBuilder builder, Tracker tracker,
TimingSection section) {
if(section == null) {
return;
}
if (section.getWrapValueFunction() != null) {
builder.append("function ");
builder.append(section.getWrapValueFunction());
builder.append("(");
builder.append(TimingField.timingValue.name());
builder.append(") {");
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'timing'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
if (section.getWrapValueFunction() != null) {
callbackFunction.generateCriticalTimeout(builder, "");
builder.append("}");
}
callbackFunction.generateCriticalFunction(builder, "");
}
private void sendSocial(StringBuilder builder, Tracker tracker,
SocialSection section) {
if(section == null) {
return;
}
if (section.getWrappingFunctionName() != null) {
builder.append("function ");
builder.append(section.getWrappingFunctionName());
builder.append("() {");
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'social'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
if (section.getWrappingFunctionName() != null) {
callbackFunction.generateCriticalTimeout(builder, "");
builder.append("}");
}
callbackFunction.generateCriticalFunction(builder, "");
}
private void sendScreenView(StringBuilder builder, Tracker tracker, ScreenviewSection section) {
if(section == null) {
return;
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'screenview'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
callbackFunction.generateCriticalTimeout(builder, "");
callbackFunction.generateCriticalFunction(builder, "");
}
private void sendPageview(StringBuilder builder, Tracker tracker, PageviewSection section) {
if(section == null) {
return;
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'pageview'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
callbackFunction.generateCriticalTimeout(builder, "");
callbackFunction.generateCriticalFunction(builder, "");
}
private void sendException(StringBuilder builder, Tracker tracker, ExceptionSection section) {
if(section == null) {
return;
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'exception'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
callbackFunction.generateCriticalTimeout(builder, "");
callbackFunction.generateCriticalFunction(builder, "");
}
private void sendEvent(StringBuilder builder, Tracker tracker, EventSection section) {
if(section == null) {
return;
}
if (section.getElementId() != null) {
needListenerFunction = true;
builder.append("addListener(document.getElementById('");
builder.append(section.getElementId());
builder.append("'), '");
builder.append(section.getAction());
builder.append("', function() {");
}
builder.append("ga('");
if(tracker.getTrackerName() != null) {
builder.append(tracker.getTrackerName());
builder.append(".");
}
builder.append("send', 'event'");
CallbackFunction callbackFunction = new CallbackFunction(section.getCallbackFunction(), section.isCriticalCallbackFunction());
fieldArray(builder, section.getAll(), section, callbackFunction);
builder.append(");");
if (section.getElementId() != null) {
callbackFunction.generateCriticalTimeout(builder, "");
builder.append("});");
}
callbackFunction.generateCriticalFunction(builder, "");
}
@SuppressWarnings("unchecked")
private void fieldArray(StringBuilder builder, Map<AnalyticsField, String> fields,
MainSection section, CallbackFunction callbackFunction) {
boolean firstField = true;
builder.append(", {");
for (Map.Entry<AnalyticsField, String> entry : fields.entrySet()) {
if(!firstField) {
builder.append(",");
}
firstField = false;
builder.append("'");
builder.append(entry.getKey());
builder.append("': ");
if (section.isFieldForced(entry.getKey())) {
builder.append(entry.getValue());
} else {
builder.append(ControlHolder.toString(entry.getKey(), entry.getValue()));
}
}
if (callbackFunction.getFunction() != null) {
if(!firstField) {
builder.append(",");
}
builder.append("'hitCallback': ");
builder.append(callbackFunction.getFunction());
}
builder.append("}");
}
private class CallbackFunction {
private String function;
private boolean critical;
public CallbackFunction(String function, boolean critical) {
this.function = function;
this.critical = critical;
}
public String getFunction() {
return critical?function + "Critical":function;
}
public void generateCriticalTimeout(StringBuilder builder, String indent) {
if(function != null) {
builder.append(indent);
builder.append("setTimeout(");
builder.append(function);
builder.append("Critical, 2000);");
}
}
public void generateCriticalFunction(StringBuilder builder, String indent) {
if(function != null) {
builder.append(indent);
builder.append("var ");
builder.append(function);
builder.append("CriticalAlreadyCalled = false;");
builder.append(indent);
builder.append("function ");
builder.append(function);
builder.append("Critical() {");
builder.append(indent);
builder.append("if (");
builder.append(function);
builder.append("CriticalAlreadyCalled) return;");
builder.append(indent);
builder.append(function);
builder.append("CriticalAlreadyCalled = true;");
builder.append(function);
builder.append("();");
builder.append(indent);
builder.append("}");
}
}
}
}
|
92384d97e1bbb42791ebb1302410107a30cf273d | 751 | java | Java | ms-core/src/main/java/pl/a2s/ms/core/ie/FitnessExtractor.java | jswk/ms | 90a6f4ddc7bcaf1d72c7492c410054a5b7a132d4 | [
"Apache-2.0"
] | null | null | null | ms-core/src/main/java/pl/a2s/ms/core/ie/FitnessExtractor.java | jswk/ms | 90a6f4ddc7bcaf1d72c7492c410054a5b7a132d4 | [
"Apache-2.0"
] | null | null | null | ms-core/src/main/java/pl/a2s/ms/core/ie/FitnessExtractor.java | jswk/ms | 90a6f4ddc7bcaf1d72c7492c410054a5b7a132d4 | [
"Apache-2.0"
] | 2 | 2021-03-07T16:46:39.000Z | 2021-03-08T19:50:53.000Z | 27.814815 | 75 | 0.737683 | 998,384 | /*
* Copyright 2021 A2S
*
* 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 pl.a2s.ms.core.ie;
import pl.a2s.ms.core.ind.Population;
public interface FitnessExtractor {
double[] extractFitness(Population population);
}
|
92384d9edb8405a1ec156397320394b53bc2934f | 3,495 | java | Java | src/main/java/trademate/TradeMate.java | Teletha/CoinToss | 886bff19af69c1419f107768ef00bbcf260b066f | [
"MIT"
] | null | null | null | src/main/java/trademate/TradeMate.java | Teletha/CoinToss | 886bff19af69c1419f107768ef00bbcf260b066f | [
"MIT"
] | 4 | 2022-02-04T01:03:36.000Z | 2022-03-29T11:03:47.000Z | src/main/java/trademate/TradeMate.java | teletha/cointoss | 886bff19af69c1419f107768ef00bbcf260b066f | [
"MIT"
] | null | null | null | 32.06422 | 135 | 0.566524 | 998,385 | /*
* Copyright (C) 2021 cointoss Development Team
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*/
package trademate;
import java.util.List;
import java.util.Random;
import cointoss.Market;
import cointoss.MarketService;
import cointoss.market.MarketServiceProvider;
import cointoss.util.Chrono;
import cointoss.util.EfficientWebSocket;
import kiss.I;
import kiss.Managed;
import kiss.Signal;
import kiss.Singleton;
import psychopath.Locator;
import trademate.order.OrderView;
import trademate.setting.SettingView;
import trademate.verify.BackTestView;
import viewtify.Theme;
import viewtify.Viewtify;
import viewtify.ui.UITab;
import viewtify.ui.View;
import viewtify.ui.ViewDSL;
import viewtify.ui.dock.DockSystem;
@Managed(value = Singleton.class)
public class TradeMate extends View {
/**
* {@inheritDoc}
*/
@Override
protected ViewDSL declareUI() {
return new ViewDSL() {
{
$(DockSystem.UI);
}
};
}
/**
* {@inheritDoc}
*/
@Override
protected void initialize() {
DockSystem.register("Setting").contents(SettingView.class).closable(false);
DockSystem.register("BackTest").contents(BackTestView.class).closable(false);
DockSystem.register("Global Volume").contents(GlobalVolumeView.class).closable(false);
DockSystem.register("Order").contents(OrderView.class).closable(false);
// ========================================================
// Create Tab for each Markets
// ========================================================
MarketServiceProvider.availableMarketServices().take(MarketService::supportHistoricalTrade).to(service -> {
UITab tab = DockSystem.register(service.id).closable(false).text(service.id).contents(ui -> new TradingView(ui, service));
TradingViewCoordinator.requestLoading(service, tab);
});
DockSystem.validate();
// ========================================================
// Clock in Title bar
// ========================================================
Chrono.seconds().map(Chrono.DateDayTime::format).combineLatest(Wisdom.random()).on(Viewtify.UIThread).to(v -> {
stage().v.setTitle(v.ⅰ.substring(5) + " " + v.ⅱ);
});
}
/**
* Managing words of widsom.
*/
private static class Wisdom {
private static final List<String> words = Locator.file("wisdom.txt").lines().toList();
private static final Random random = new Random();
private static Signal<String> random() {
return Chrono.minutes().map(v -> words.get(random.nextInt(words.size())));
}
}
/**
* Entry point.
*/
public static void main(String[] args) {
I.load(Market.class);
// activate application
Viewtify.application() //
.logging((msg, error) -> {
I.error(msg);
I.error(error);
})
.use(Theme.Dark)
.icon("icon/app.png")
.onTerminating(EfficientWebSocket::shutdownNow)
.activate(TradeMate.class);
}
} |
92384dfd1235768e688c41c82b407f3561dfd93c | 4,340 | java | Java | src/test/java/br/com/zupacademy/saulo/mercadolivre/pagamento/transacao/CadastroTransacaoTest.java | SauloFregotte/orange-talents-06-template-ecommerce | bf6ad89105afa8d9cff105757731e198733ae2c7 | [
"Apache-2.0"
] | null | null | null | src/test/java/br/com/zupacademy/saulo/mercadolivre/pagamento/transacao/CadastroTransacaoTest.java | SauloFregotte/orange-talents-06-template-ecommerce | bf6ad89105afa8d9cff105757731e198733ae2c7 | [
"Apache-2.0"
] | null | null | null | src/test/java/br/com/zupacademy/saulo/mercadolivre/pagamento/transacao/CadastroTransacaoTest.java | SauloFregotte/orange-talents-06-template-ecommerce | bf6ad89105afa8d9cff105757731e198733ae2c7 | [
"Apache-2.0"
] | null | null | null | 47.692308 | 163 | 0.634793 | 998,386 | package br.com.zupacademy.saulo.mercadolivre.pagamento.transacao;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@SpringBootTest
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class CadastroTransacaoTest {
private static final String PAYPAL = "/pay-pal/1";
private static final String PAGSEGURO = "/pag-seguro/1";
@Autowired
private MockMvc mockMvc;
private String bearerToken;
@BeforeEach
void autenticacao() throws Exception {
String endpoint = "/auth-login";
String content = "{\"email\":\"lulo123@gmail.com\",\"senha\":\"123456\"}";
bearerToken = JsonPath.read(mockMvc.perform(
MockMvcRequestBuilders
.post(endpoint)
.contentType(MediaType.APPLICATION_JSON)
.content(content)
).andDo(MockMvcResultHandlers.print())
.andReturn()
.getResponse()
.getContentAsString(), "$.token");
}
private String json(String status){
return "{\n" +
" \"idPagamento\":\"hvebyrebrnv\",\n" +
" \"status\":\"" + status + "\"\n" +
"}";
}
@Test
@Sql(statements = {"Insert into usuario Values (1,'upchh@example.com', '2017-01-16 00:00:00', '$2a$10$mCxKN/mh2ootRbx0PVnqye3mQhacpUebaQHm01YuIivKsug3ox7BS')",
"Insert into categoria values (1, 'testeCategoria', null)",
"Insert into produto values (1, 'descricao produto', '2017-01-16 00:00:00', 'nomeProduto', 23, 50.00, 1, 1)",
"Insert into caracteristicas Values (1, 'Teste descricao1', 'nome1',1)",
"Insert into caracteristicas Values (2, 'Teste descricao2', 'nome2',1)",
"Insert into caracteristicas Values (3, 'Teste descricao3', 'nome3',1)",
"Insert into compra Values (1, \"PAG_SEGURO\", 3, \"INICIADA\", 1, 1)"})
void compraCadastradaPagseguroComSucesso() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders
.post(PAGSEGURO)
.contentType( MediaType.APPLICATION_JSON )
.header("Authorization", "Bearer " + bearerToken )
.content(json("SUCESSO"))
).andDo( MockMvcResultHandlers.print() )
.andExpect( MockMvcResultMatchers.status().isOk() );
}
@Test
@Sql(statements = {"Insert into usuario Values (1,'upchh@example.com', '2017-01-16 00:00:00', '$2a$10$mCxKN/mh2ootRbx0PVnqye3mQhacpUebaQHm01YuIivKsug3ox7BS')",
"Insert into categoria values (1, 'testeCategoria', null)",
"Insert into produto values (1, 'descricao produto', '2017-01-16 00:00:00', 'nomeProduto', 23, 50.00, 1, 1)",
"Insert into caracteristicas Values (1, 'Teste descricao1', 'nome1',1)",
"Insert into caracteristicas Values (2, 'Teste descricao2', 'nome2',1)",
"Insert into caracteristicas Values (3, 'Teste descricao3', 'nome3',1)",
"Insert into compra Values (1, \"PAY_PAL\", 3, \"INICIADA\", 1, 1)"})
void compraCadastradaPaypalComSucesso() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders
.post(PAYPAL)
.contentType( MediaType.APPLICATION_JSON )
.header("Authorization", "Bearer " + bearerToken )
.content(json("1"))
).andDo( MockMvcResultHandlers.print() )
.andExpect( MockMvcResultMatchers.status().isOk() );
}
} |
92384e4879227bcf10b7c929dd4edc092a2ee014 | 1,130 | java | Java | src/main/java/com/ean/client/v3/domain/ValueAdds.java | ExpediaInc/ean-hotel-api-v3-r29-java-client | dce86d086a74aa1e71e257dffbe5adcc9c385dbe | [
"MIT"
] | 3 | 2016-04-28T07:19:35.000Z | 2018-12-21T23:31:02.000Z | src/main/java/com/ean/client/v3/domain/ValueAdds.java | ExpediaInc/ean-hotel-api-v3-r29-java-client | dce86d086a74aa1e71e257dffbe5adcc9c385dbe | [
"MIT"
] | null | null | null | src/main/java/com/ean/client/v3/domain/ValueAdds.java | ExpediaInc/ean-hotel-api-v3-r29-java-client | dce86d086a74aa1e71e257dffbe5adcc9c385dbe | [
"MIT"
] | null | null | null | 22.156863 | 70 | 0.670796 | 998,387 | package com.ean.client.v3.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Contains all value adds details for a hotel reservation.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ValueAdds implements Serializable {
private static final long serialVersionUID = -408467012550249566L;
@JsonProperty("@size")
private int size;
@JsonProperty("ValueAdd")
private List<ValueAdd> valueAddList = new ArrayList<ValueAdd>();
/**
* Returns the size for the valueAdds
*
* @return int for the size
*/
public int getSize() {
return size;
}
/**
* Returns the value add list for hotel reservation
*
* @return List<ValueAdd> for the valueAdds
*/
public List<ValueAdd> getValueAddList() {
return valueAddList;
}
/**
* Set value add list
*
*/
public void setValueAdds(List<ValueAdd> valueAdd) {
this.valueAddList = valueAdd;
}
}
|
92384ecdc45f0c1c2e8cefd2fb90754fea5843eb | 1,191 | java | Java | leyou-order/leyou-order-service/src/main/java/com/leyou/order/config/SwaggerConfig.java | java-fkd/leyou | dd35415f47a1690540f230237be1e4a6aee01fb6 | [
"Apache-2.0"
] | 697 | 2018-11-01T15:55:14.000Z | 2022-03-11T01:21:47.000Z | leyou-order/leyou-order-service/src/main/java/com/leyou/order/config/SwaggerConfig.java | java-fkd/leyou | dd35415f47a1690540f230237be1e4a6aee01fb6 | [
"Apache-2.0"
] | 27 | 2018-12-01T01:30:35.000Z | 2022-03-31T21:04:13.000Z | leyou-order/leyou-order-service/src/main/java/com/leyou/order/config/SwaggerConfig.java | huhua1990/leyou | 98868d12ffe4688ff6a14e3033c234d269a5d805 | [
"Apache-2.0"
] | 519 | 2018-10-26T05:59:54.000Z | 2022-03-21T00:37:04.000Z | 34.028571 | 88 | 0.680101 | 998,389 | package com.leyou.order.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author 98050
*/
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8089")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.leyou.order.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("乐优商城订单系统")
.description("乐优商城订单系统接口文档")
.version("1.0")
.build();
}
} |
92385013c8945d3218358e7cd6cb61310c885f81 | 6,845 | java | Java | squidCore/src/main/java/org/cirdles/squid/parameters/parameterModels/referenceMaterialModels/ReferenceMaterialModelXMLConverter.java | bowring/Squid | 50775ecdf46388b75d06cddb70ab4357ccceda5d | [
"Apache-2.0"
] | 9 | 2017-05-08T15:02:48.000Z | 2022-03-05T02:21:05.000Z | squidCore/src/main/java/org/cirdles/squid/parameters/parameterModels/referenceMaterialModels/ReferenceMaterialModelXMLConverter.java | tejddaniel/Squid | 6e17a8abd89f7db7689a51fb978d7d4a692f4cec | [
"Apache-2.0"
] | 383 | 2017-05-10T23:32:00.000Z | 2022-03-31T00:57:52.000Z | squidCore/src/main/java/org/cirdles/squid/parameters/parameterModels/referenceMaterialModels/ReferenceMaterialModelXMLConverter.java | tejddaniel/Squid | 6e17a8abd89f7db7689a51fb978d7d4a692f4cec | [
"Apache-2.0"
] | 32 | 2017-03-19T20:47:27.000Z | 2022-01-13T15:57:19.000Z | 35.102564 | 172 | 0.633309 | 998,390 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.cirdles.squid.parameters.parameterModels.referenceMaterialModels;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.cirdles.squid.parameters.parameterModels.ParametersModel;
import org.cirdles.squid.parameters.valueModels.ValueModel;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
/**
* @author ryanb
*/
public class ReferenceMaterialModelXMLConverter implements Converter {
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
ParametersModel model = (ReferenceMaterialModel) o;
writer.startNode("modelName");
writer.setValue(model.getModelName());
writer.endNode();
writer.startNode("referenceDates");
writer.setValue(Boolean.toString(((ReferenceMaterialModel) model).isReferenceDates()));
writer.endNode();
writer.startNode("labName");
writer.setValue(model.getLabName());
writer.endNode();
writer.startNode("version");
writer.setValue(model.getVersion());
writer.endNode();
writer.startNode("dateCertified");
writer.setValue(model.getDateCertified());
writer.endNode();
writer.startNode("comments");
writer.setValue(model.getComments());
writer.endNode();
writer.startNode("references");
writer.setValue(model.getReferences());
writer.endNode();
writer.startNode("values");
context.convertAnother(model.getValues());
writer.endNode();
writer.startNode("rhos");
context.convertAnother(model.getRhos());
writer.endNode();
writer.startNode("isEditable");
writer.setValue(Boolean.toString(model.isEditable()));
writer.endNode();
writer.startNode("concentrations");
context.convertAnother(((ReferenceMaterialModel) model).getConcentrations());
writer.endNode();
writer.startNode("dates");
context.convertAnother((ValueModel[]) ((ReferenceMaterialModel) model).getDates());
writer.endNode();
writer.startNode("dataMeasured");
context.convertAnother(((ReferenceMaterialModel) model).getDataMeasured());
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
ParametersModel model = new ReferenceMaterialModel();
reader.moveDown();
model.setModelName(reader.getValue());
reader.moveUp();
reader.moveDown();
if (reader.getNodeName().equals("referenceDates")) {
((ReferenceMaterialModel) model).setReferenceDates(Boolean.parseBoolean(reader.getValue()));
reader.moveUp();
reader.moveDown();
model.setLabName(reader.getValue());
reader.moveUp();
} else {
model.setLabName(reader.getValue());
reader.moveUp();
}
reader.moveDown();
model.setVersion(reader.getValue());
reader.moveUp();
reader.moveDown();
model.setDateCertified(reader.getValue());
reader.moveUp();
reader.moveDown();
model.setComments(reader.getValue());
reader.moveUp();
reader.moveDown();
model.setReferences(reader.getValue());
reader.moveUp();
reader.moveDown();
model.setValues(new ValueModel[0]);
model.setValues((ValueModel[]) context.convertAnother(model.getValues(), ValueModel[].class));
reader.moveUp();
Map<String, BigDecimal> rhos = new HashMap<>();
reader.moveDown();
while (reader.hasMoreChildren()) {
reader.moveDown();
reader.moveDown();
String key = reader.getValue();
reader.moveUp();
reader.moveDown();
String currBigDec = reader.getValue();
BigDecimal value;
if (Double.parseDouble(currBigDec) == 0.0) {
value = BigDecimal.ZERO;
} else {
value = new BigDecimal(currBigDec);
}
reader.moveUp();
reader.moveUp();
rhos.put(key, value);
}
reader.moveUp();
model.setRhos(rhos);
reader.moveDown();
model.setIsEditable(Boolean.parseBoolean(reader.getValue()));
reader.moveUp();
reader.moveDown();
((ReferenceMaterialModel) model).setConcentrations(new ValueModel[0]);
((ReferenceMaterialModel) model).setConcentrations((ValueModel[]) context.convertAnother(((ReferenceMaterialModel) model).getConcentrations(), ValueModel[].class));
reader.moveUp();
reader.moveDown();
if (reader.getNodeName().equals("dates")) {
((ReferenceMaterialModel) model).setDates(new ValueModel[0]);
((ReferenceMaterialModel) model).setDates((ValueModel[]) context.convertAnother(((ReferenceMaterialModel) model).getDates(), ValueModel[].class));
reader.moveUp();
reader.moveDown();
((ReferenceMaterialModel) model).setDataMeasured(new boolean[0]);
((ReferenceMaterialModel) model).setDataMeasured((boolean[]) context.convertAnother(((ReferenceMaterialModel) model).getDataMeasured(), boolean[].class));
reader.moveUp();
} else {
((ReferenceMaterialModel) model).setDataMeasured(new boolean[0]);
((ReferenceMaterialModel) model).setDataMeasured((boolean[]) context.convertAnother(((ReferenceMaterialModel) model).getDataMeasured(), boolean[].class));
reader.moveUp();
boolean valuesAllZero = true;
for (int i = 0; valuesAllZero && i < model.getValues().length; i++) {
if (model.getValues()[i].getValue().doubleValue() > 0.000000000001) {
valuesAllZero = false;
}
}
if (valuesAllZero) {
((ReferenceMaterialModel) model).setReferenceDates(true);
((ReferenceMaterialModel) model).generateBaseDates();
} else {
((ReferenceMaterialModel) model).calculateApparentDates();
}
}
return model;
}
@Override
public boolean canConvert(Class type) {
return type.equals(ReferenceMaterialModel.class);
}
} |
92385071f9feaa11eaae6e0f56bdce00aa8eb6f7 | 1,264 | java | Java | src/main/java/cryptophasia/networking/transmission/ServerNotificationMessage.java | mes32/EoC-Cryptophasia | 931596e41527094120e5036fae49ec09e7adaedd | [
"MIT"
] | null | null | null | src/main/java/cryptophasia/networking/transmission/ServerNotificationMessage.java | mes32/EoC-Cryptophasia | 931596e41527094120e5036fae49ec09e7adaedd | [
"MIT"
] | null | null | null | src/main/java/cryptophasia/networking/transmission/ServerNotificationMessage.java | mes32/EoC-Cryptophasia | 931596e41527094120e5036fae49ec09e7adaedd | [
"MIT"
] | null | null | null | 25.28 | 110 | 0.655063 | 998,391 | /*
ServerNotificationMessage.java
A notification relating to the server ChatServer
*/
package cryptophasia.networking.transmission;
import cryptophasia.exception.*;
public class ServerNotificationMessage extends AbstractMessage {
private static final String HEADER = AbstractMessage.SERVER_NOTE;
private String body;
public ServerNotificationMessage(String message) {
body = message;
}
public static ServerNotificationMessage parse(String transmission) throws MalformedTransmissionException {
try {
int index = HEADER.length();
String message = transmission.substring(index);
return new ServerNotificationMessage(message);
} catch (IndexOutOfBoundsException e) {
throw new MalformedTransmissionException("Could not parse ServerNotificationMessage.", e);
}
}
public static boolean indicated(String transmission) {
if (transmission.startsWith(HEADER)) {
return true;
} else {
return false;
}
}
public String getBody() {
return body;
}
public String transmit() {
return HEADER + body;
}
public String toString() {
return " + " + body;
}
} |
9238510f454cc1005a8cad2e9b90ced15aae7a31 | 4,172 | java | Java | ntsiot-jt808-server/src/main/java/com/nts/iot/util/RedisUtil.java | luolxb/tracker-server | 74f81cc9e511c0bc75a98440d1fad2a25a827ce3 | [
"Apache-2.0"
] | null | null | null | ntsiot-jt808-server/src/main/java/com/nts/iot/util/RedisUtil.java | luolxb/tracker-server | 74f81cc9e511c0bc75a98440d1fad2a25a827ce3 | [
"Apache-2.0"
] | null | null | null | ntsiot-jt808-server/src/main/java/com/nts/iot/util/RedisUtil.java | luolxb/tracker-server | 74f81cc9e511c0bc75a98440d1fad2a25a827ce3 | [
"Apache-2.0"
] | 1 | 2021-12-20T07:54:15.000Z | 2021-12-20T07:54:15.000Z | 23.049724 | 91 | 0.541707 | 998,392 | package com.nts.iot.util;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redis 增删改查模板
*/
@Component
public class RedisUtil {
/**
* redisTemplate
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 添加缓存
*
* @param key
* @return
*/
public Boolean addRedis(String key, String value) {
Boolean flag = true;
ValueOperations<String, String> operations = redisTemplate.opsForValue();
try {
operations.set(key, value);
} catch (Exception e) {
flag = false;
e.printStackTrace();
System.out.println("添加redis失败!");
}
return flag;
}
/**
* 添加缓存(加上有效期)
*
* @param key
* @return
*/
public Boolean addRedis(String key, String value, long time) {
Boolean flag = true;
ValueOperations<String, String> operations = redisTemplate.opsForValue();
try {
operations.set(key, value,time,TimeUnit.SECONDS);
} catch (Exception e) {
flag = false;
e.printStackTrace();
System.out.println("添加redis失败!");
}
return flag;
}
/**
* 根据key,删除缓存
*
* @param key 主键
*/
public Boolean deleteByKey(String key) {
Boolean flag = true;
try {
redisTemplate.delete(key);
} catch (Exception e) {
flag = false;
e.printStackTrace();
System.out.println("根据redisKey,删除redis失败!");
}
return flag;
}
/**
* 修改缓存
*
* @param key
* @return
*/
public Boolean updateRedis(String key, String value) {
Boolean flag = true;
ValueOperations<String, String> operations = redisTemplate.opsForValue();
try {
operations.set(key, value);
} catch (Exception e) {
flag = false;
e.printStackTrace();
System.out.println("修改redis失败!");
}
return flag;
}
/**
* 修改缓存(加有效期)
*
* @param key
* @return
*/
public Boolean updateRedis(String key, String value,long time) {
Boolean flag = true;
ValueOperations<String, String> operations = redisTemplate.opsForValue();
try {
operations.set(key, value,time,TimeUnit.SECONDS);
} catch (Exception e) {
flag = false;
e.printStackTrace();
System.out.println("修改redis失败!");
}
return flag;
}
/**
* 获得缓存中的数据
*
* @param key
* @return
*/
public String getData(String key) {
String data = "";
try {
//根据接口名称去缓存中查询
data = redisTemplate.opsForValue().get(key);
} catch (Exception e) {
e.printStackTrace();
System.out.println("redis获取数据失败!");
}
return data;
}
/**
* 获得缓存中的数据
*
* @param key
* @return
*/
public Object getObject(String key) {
return key == null ? null : JSON.parseObject(redisTemplate.opsForValue().get(key));
}
/**
* 模糊查询key
* @param prefix
* @return
*/
public Set<String> keys(String prefix){
Set sets = redisTemplate.keys(prefix + "*");
return sets;
}
/**
* 通过keys查找
* @param keys
* @return
*/
public Set<Object> getObjectsByKeys(Set<String> keys){
Set<Object> sets = new HashSet<>();
for (String key : keys) {
Object obj = JSON.parseObject(redisTemplate.opsForValue().get(key));
sets.add(obj);
}
return sets;
}
/**
* 查询是否有key
* @param prefix
* @return
*/
public boolean hasKey(String prefix){
return redisTemplate.hasKey(prefix);
}
}
|
923851f67ac59804afa273d148bb20d94a6dddf3 | 5,926 | java | Java | src/uoa/are/dm/UserManager.java | buptliuhs/ARE | e5d9471d6dcb3229c0fbc121de32f418cb96eb41 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-11-11T02:23:47.000Z | 2015-11-11T02:23:47.000Z | src/uoa/are/dm/UserManager.java | buptliuhs/ARE | e5d9471d6dcb3229c0fbc121de32f418cb96eb41 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/uoa/are/dm/UserManager.java | buptliuhs/ARE | e5d9471d6dcb3229c0fbc121de32f418cb96eb41 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 32.740331 | 198 | 0.5297 | 998,393 | // Copyright 2015 Tony (Huansheng) Liu
//
// 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 uoa.are.dm;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import uoa.are.common.Code;
import uoa.are.common.Const;
import uoa.are.database.ConnectionEx;
import uoa.are.database.SC;
/**
* Utility class to manage users in database
*
* @author hliu482
*
*/
public class UserManager {
static Logger logger = Logger.getLogger(UserManager.class);
static public List<User> getAllUsers() {
List<User> list = new LinkedList<User>();
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "SELECT u.id as id, u.username as userName, u.password as password, u.enabled as enabled, u.role as role, r.role as roleName FROM sys_user u, sys_role r WHERE u.role = r.id"
+ " ORDER BY u.id";
sc.execute(sql);
logger.debug(sql);
while (sc.next()) {
User user = new User();
user.setId(sc.getInt("id"));
user.setName(sc.getString("userName"));
user.setRole(sc.getInt("role"));
user.setRoleName(sc.getString("roleName"));
user.setPassword(sc.getString("password"));
user.setEnabled(sc.getInt("enabled"));
list.add(user);
}
return list;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (sc != null)
sc.closeAll();
}
return list;
}
static public int getNumberOfUsers() {
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "select count(*) as d from sys_user";
sc.execute(sql);
sc.next();
return sc.getInt("d");
} catch (Exception e) {
logger.error("doTask failed", e);
} finally {
try {
sc.closeAll();
} catch (Exception e) {
logger.error("doTask failed", e);
}
}
return 0;
}
static public User getUserByName(String userName) {
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "SELECT count(*) AS count" + ", id" + ", role" + ", password" + ", enabled"
+ " FROM sys_user WHERE username = '" + userName + "'";
logger.debug(sql);
sc.execute(sql);
sc.next();
int count = sc.getInt("count");
if (count == 0)
return null;
User user = new User();
user.setId(sc.getInt("id"));
user.setName(userName);
user.setRole(sc.getInt("role"));
user.setPassword(sc.getString("password"));
user.setEnabled(sc.getInt("enabled"));
return user;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (sc != null)
sc.closeAll();
}
return null;
}
static public User addUser(String userName, String password) {
User user = null;
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "INSERT INTO sys_user (username, password) VALUES ('" + userName + "', '" + password + "')";
sc.execute(sql);
logger.debug(sql);
sc.next();
int new_user_id = sc.getInt(1);
logger.info("New User ID: " + new_user_id);
user = new User();
user.setId(new_user_id);
user.setName(userName);
// New Settings for the user
SettingManager.newSettings(new_user_id);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (sc != null)
sc.closeAll();
}
return user;
}
static public int editUser(String userName, String password) {
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "UPDATE sys_user SET password = '" + password + "'" + " WHERE username = '" + userName + "'";
sc.execute(sql);
logger.debug(sql);
return Code.SUCCESSFUL;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (sc != null)
sc.closeAll();
}
return Code.FAILED;
}
static private int changeUserStatus(String userName, int s) {
SC sc = null;
try {
sc = new SC(new ConnectionEx(Const.ARE));
String sql = "UPDATE sys_user SET enabled = " + s + "" + " WHERE username = '" + userName + "'";
sc.execute(sql);
logger.debug(sql);
return Code.SUCCESSFUL;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (sc != null)
sc.closeAll();
}
return Code.FAILED;
}
static public int enableUser(String userName) {
return changeUserStatus(userName, 1);
}
static public int disableUser(String userName) {
return changeUserStatus(userName, 0);
}
} |
92385437c4462c994b983f616e9d2cd59b8ce4fc | 3,302 | java | Java | spring-modular-core/src/main/java/com/griddynamics/banshun/config/xml/ImportBeanDefinitionParser.java | jirutka/spring-modular | 20ecc032c42f5f178f5428ff1e8d93686e1555f5 | [
"Apache-2.0"
] | 2 | 2016-05-03T15:54:23.000Z | 2019-08-16T17:31:30.000Z | spring-modular-core/src/main/java/com/griddynamics/banshun/config/xml/ImportBeanDefinitionParser.java | jirutka/spring-modular | 20ecc032c42f5f178f5428ff1e8d93686e1555f5 | [
"Apache-2.0"
] | null | null | null | spring-modular-core/src/main/java/com/griddynamics/banshun/config/xml/ImportBeanDefinitionParser.java | jirutka/spring-modular | 20ecc032c42f5f178f5428ff1e8d93686e1555f5 | [
"Apache-2.0"
] | null | null | null | 41.78481 | 119 | 0.764011 | 998,394 | /*
* Copyright 2012 Grid Dynamics Consulting Services, Inc.
* http://www.griddynamics.com
*
* Copyright 2013 Jakub Jirutka <envkt@example.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.griddynamics.banshun.config.xml;
import com.griddynamics.banshun.BeanReferenceInfo;
import com.griddynamics.banshun.Registry;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.io.Resource;
import org.w3c.dom.Element;
import static com.griddynamics.banshun.config.xml.ParserUtils.*;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON;
public class ImportBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected String getBeanClassName(Element el) {
return el.getAttribute(INTERFACE_ATTR);
}
@Override
protected void doParse(Element el, ParserContext parserContext, BeanDefinitionBuilder builder) {
Resource resource = parserContext.getReaderContext().getResource();
String rootName = defaultIfBlank(el.getAttribute(ROOT_ATTR), DEFAULT_ROOT_FACTORY_NAME);
String serviceIfaceName = el.getAttribute(INTERFACE_ATTR);
String serviceName = el.getAttribute(ID_ATTR);
Class<?> serviceIface = ParserUtils.findClassByName(serviceIfaceName, el.getAttribute(ID_ATTR), parserContext);
AbstractBeanDefinition beanDef = builder.getRawBeanDefinition();
beanDef.setFactoryBeanName(rootName);
beanDef.setFactoryMethodName(Registry.LOOKUP_METHOD_NAME);
beanDef.setConstructorArgumentValues(
defineLookupMethodArgs(serviceName, serviceIface));
beanDef.setLazyInit(true);
beanDef.setScope(SCOPE_SINGLETON);
beanDef.setResource(resource);
beanDef.setAttribute(IMPORT_BEAN_DEF_ATTR_NAME,
new BeanReferenceInfo(serviceName, serviceIface, extractResourcePath(resource)));
}
/**
* Creates arguments definition for the {@link Registry#lookup(String, Class) lookup()} method
* of the registry bean.
*/
private ConstructorArgumentValues defineLookupMethodArgs(String serviceName, Class<?> serviceIface) {
ConstructorArgumentValues holder = new ConstructorArgumentValues();
holder.addIndexedArgumentValue(0, serviceName);
holder.addIndexedArgumentValue(1, serviceIface);
return holder;
}
}
|
9238569ade7debecc402ff691cd45c06f267e8ac | 842 | java | Java | app/src/main/java/com/example/applock/utils/DataUtil.java | IronMastiff/AppLock | 5baf3e977664190f35ff0c31ae950cc69aaf57a2 | [
"Apache-2.0"
] | 1 | 2018-02-22T03:10:20.000Z | 2018-02-22T03:10:20.000Z | app/src/main/java/com/example/applock/utils/DataUtil.java | IronMastiff/AppLock | 5baf3e977664190f35ff0c31ae950cc69aaf57a2 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/applock/utils/DataUtil.java | IronMastiff/AppLock | 5baf3e977664190f35ff0c31ae950cc69aaf57a2 | [
"Apache-2.0"
] | null | null | null | 28.066667 | 93 | 0.644893 | 998,395 | package com.example.applock.utils;
import com.example.applock.bean.CommLockInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by 我的 on 2017/8/12.
*/
public class DataUtil {
public static List<CommLockInfo> clearRepeatCommLockInfo( List<CommLockInfo> lockInfos ){
HashMap<String, CommLockInfo > hashMap = new HashMap<>();
for ( CommLockInfo lockInfo : lockInfos ) {
if ( !hashMap.containsKey( lockInfo.getPackageName() ) ){
hashMap.put( lockInfo.getPackageName(), lockInfo );
}
}
List<CommLockInfo> commLockInfos = new ArrayList<>();
for ( HashMap.Entry<String, CommLockInfo> entry : hashMap.entrySet() ){
commLockInfos.add( entry.getValue() );
}
return commLockInfos;
}
}
|
923856a93cbb8218c5fcc2e5595bd6de1d0bed63 | 13,205 | java | Java | deps/kb_meme/meme-5.0.1/website/src/au/edu/uq/imb/memesuite/db/MotifDBList.java | kbasecollaborations/MotifFinderSampler | d4dc67aef5fb52990310c3811535bde405afae93 | [
"MIT"
] | 1 | 2019-07-19T04:33:41.000Z | 2019-07-19T04:33:41.000Z | deps/kb_meme/meme-5.0.1/website/src/au/edu/uq/imb/memesuite/db/MotifDBList.java | man4ish/MotifFinderMdscan | 2cf60b028963be22389717329a7ed28e0a489274 | [
"MIT"
] | 1 | 2019-07-08T17:54:26.000Z | 2019-07-08T17:54:26.000Z | deps/kb_meme/meme-5.0.1/website/src/au/edu/uq/imb/memesuite/db/MotifDBList.java | man4ish/MotifFinderMdscan | 2cf60b028963be22389717329a7ed28e0a489274 | [
"MIT"
] | 1 | 2021-03-13T15:12:52.000Z | 2021-03-13T15:12:52.000Z | 40.382263 | 160 | 0.616888 | 998,396 | package au.edu.uq.imb.memesuite.db;
import java.io.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;
import java.sql.*;
import au.edu.uq.imb.memesuite.data.AlphStd;
import au.edu.uq.imb.memesuite.data.MotifStats;
import au.edu.uq.imb.memesuite.servlet.util.MotifValidator;
import au.edu.uq.imb.memesuite.util.GlobFilter;
import org.sqlite.*;
import static au.edu.uq.imb.memesuite.db.SQL.SELECT_MOTIF_LISTINGS_OF_CATEGORY;
public class MotifDBList extends DBList {
private File csv;
protected static Logger logger = Logger.getLogger("au.edu.uq.imb.memesuite.motifdb");
public MotifDBList(File csv, File motifsDir) throws ClassNotFoundException, IOException, SQLException {
super(loadMotifCSV(csv, motifsDir), true);
this.csv = csv;
}
/**
* Get the source file that the database was created from.
* @return the csv file that was loaded to create the database.
*/
public File getCSV() {
return csv;
}
@Override
protected PreparedStatement prepareListingsQuery(Connection conn, long categoryId, boolean shortOnly, EnumSet<AlphStd> allowedAlphabets) throws SQLException {
PreparedStatement ps = conn.prepareStatement(SELECT_MOTIF_LISTINGS_OF_CATEGORY);
ps.setLong(1, categoryId);
ps.setInt(2, SQL.enumsToInt(allowedAlphabets));
return ps;
}
private MotifDBFile loadMotifFile(ResultSet rset) throws SQLException {
long id = rset.getLong(1);
String fileName = rset.getString(2);
AlphStd alphabet = AlphStd.fromInt(rset.getInt(3));
int motifCount = rset.getInt(4);
int totalCols = rset.getInt(5);
int minCols = rset.getInt(6);
int maxCols = rset.getInt(7);
double avgCols = rset.getDouble(8);
double stdDCols = rset.getDouble(9);
return new MotifDBFile(id, fileName, alphabet, motifCount, totalCols,
minCols, maxCols, avgCols, stdDCols);
}
public MotifDB getMotifListing(long listingId) throws SQLException {
MotifDB motifList;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rset = null;
try {
// create a database connection
conn = ds.getConnection();
// get the name and description
stmt = conn.prepareStatement(SQL.SELECT_LISTING);
stmt.setLong(1, listingId);
rset = stmt.executeQuery();
if (!rset.next()) throw new SQLException("No listing by that ID");
final String name = rset.getString(1);
final String description = rset.getString(2);
rset.close(); rset = null;
stmt.close(); stmt = null;
// get the motif files
stmt = conn.prepareStatement(SQL.SELECT_MOTIFS_OF_LISTING);
stmt.setLong(1, listingId);
rset = stmt.executeQuery();
ArrayList<MotifDBFile> files = new ArrayList<MotifDBFile>();
while (rset.next()) {
files.add(loadMotifFile(rset));
}
rset.close(); rset = null;
stmt.close(); stmt = null;
conn.close(); conn = null;
motifList = new MotifDB(name, description, files);
} finally {
if (rset != null) {
try {
rset.close();
} catch (SQLException e) { /* ignore */ }
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) { /* ignore */ }
}
if (conn != null) {
try {
conn.close();
} catch(SQLException e) {
logger.log(Level.SEVERE, "Cleanup (after error) failed to close the DB connection", e);
}
}
}
return motifList;
}
private static File loadMotifCSV(File csv, File motifsDir) throws ClassNotFoundException, IOException, SQLException {
// load the JDBC needed
Class.forName("org.sqlite.JDBC");
// create the file to contain the database
File db = File.createTempFile("motif_db_", ".sqlite");
db.deleteOnExit();
// configure the database
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
SQLiteDataSource ds = new SQLiteDataSource(config);
ds.setUrl("jdbc:sqlite:" + db);
// open a connection
Connection connection = null;
try {
connection = ds.getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate(SQL.CREATE_TBL_CATEGORY);
statement.executeUpdate(SQL.CREATE_TBL_LISTING);
statement.executeUpdate(SQL.CREATE_TBL_MOTIF_FILE);
statement.executeUpdate(SQL.CREATE_TBL_LISTING_MOTIF);
connection.setAutoCommit(false);
importMotifCSV(csv, motifsDir, connection);
connection.commit();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) { /* ignore */ }
}
}
if (!db.setLastModified(csv.lastModified())) {
logger.log(Level.WARNING, "Failed to set last modified date on " + db);
}
logger.log(Level.INFO, "Loaded Motif CSV \"" + csv + "\" into \"" + db + "\"");
return db;
}
protected static void importMotifCSV(File csv, File motifsDir, Connection connection) throws IOException, SQLException {
Path motifsPath = motifsDir.toPath();
logger.log(Level.INFO, "Importing motif csv from \"" + csv +
"\" expecting motifs to be in \"" + motifsDir + "\"");
String line;
Long categoryId = null;
Pattern emptyLine = Pattern.compile("^\\s*$");
Pattern commentLine = Pattern.compile("^#");
Pattern dashedName = Pattern.compile("^-*([^-](?:.*[^-])?)-*$");
BufferedReader in = null;
try {
ResultSet rs;
// open the csv file for reading
in = new BufferedReader(new InputStreamReader(new FileInputStream(csv), "UTF-8"));
// create the prepared statements
PreparedStatement pstmtCategory = connection.prepareStatement(
SQL.INSERT_CATEGORY, Statement.RETURN_GENERATED_KEYS);
PreparedStatement pstmtListing = connection.prepareStatement(
SQL.INSERT_LISTING, Statement.RETURN_GENERATED_KEYS);
PreparedStatement pstmtMotifFile = connection.prepareStatement(
SQL.INSERT_MOTIF_FILE, Statement.RETURN_GENERATED_KEYS);
PreparedStatement pstmtListingMotif = connection.prepareStatement(
SQL.INSERT_LISTING_MOTIF);
PreparedStatement pstmtFindMotifFileId = connection.prepareStatement(
SQL.SELECT_MOTIF_FILE_ID);
// now read the csv file
while ((line = in.readLine()) != null) {
// skip any empty lines or comments
if (emptyLine.matcher(line).find()) continue;
if (commentLine.matcher(line).find()) continue;
line = line.trim();
// check we have enough items on the line to do something
String[] values = line.split("\\s*,\\s*");
if (values.length < 5) {
logger.log(Level.WARNING,"CSV line has " + values.length + " values but expected at least 5.");
continue;
}
// check that a name was supplied
if (emptyLine.matcher(values[4]).find()) {
logger.log(Level.WARNING, "CSV line has no entry for name column.");
continue;
}
// test to see if we have a category or a selectable listing
if (emptyLine.matcher(values[0]).find()) {
// category
String name = values[4].trim();
// remove dashes from around name
Matcher matcher = dashedName.matcher(name);
if (matcher.matches()) {
name = matcher.group(1);
}
pstmtCategory.setString(1, name);
pstmtCategory.executeUpdate();
// now get the category Id
rs = pstmtCategory.getGeneratedKeys();
if (!rs.next()) throw new SQLException("Failed to get Category Id.\n");
categoryId = rs.getLong(1);
rs.close();
logger.log(Level.FINE, "Loaded Motif Category: " + name);
} else {
// listing
// check we have a category to store the listing under
if (categoryId == null) {
// create a dummy category with an empty name
pstmtCategory.setString(1, "");
pstmtCategory.executeUpdate();
// now get the category Id
rs = pstmtCategory.getGeneratedKeys();
if (!rs.next()) throw new SQLException("Failed to get Category Id.\n");
categoryId = rs.getLong(1);
rs.close();
}
// now create the listing
String filesPattern = values[0];
String name = values[4];
String description = (values.length > 5 ? values[5] : "");
pstmtListing.setLong(1, categoryId);
pstmtListing.setString(2, name);
pstmtListing.setString(3, description);
pstmtListing.executeUpdate();
// now get the listing Id
rs = pstmtListing.getGeneratedKeys();
if (!rs.next()) throw new SQLException("Failed to get Listing Id.\n");
long listingId = rs.getLong(1);
pstmtListingMotif.setLong(1, listingId);
rs.close();
logger.log(Level.FINE, "Loaded Motif Listing: " + name);
// get the list of files that match
File[] motifFiles = GlobFilter.find(motifsDir, filesPattern);
if (motifFiles.length == 0) {
logger.log(Level.WARNING, "No motif files found for pattern:\n" + filesPattern);
} else if (motifFiles.length < filesPattern.trim().split("(?:^|[^\\\\])\\s+", -1).length) {
StringBuilder fileListStr = new StringBuilder();
for (File motifFile : motifFiles) {
fileListStr.append("\n");
fileListStr.append(motifFile.toString());
}
logger.log(Level.WARNING, "Less motif files found than pattern implied. " +
"Pattern:\n" + filesPattern + "\nFiles found:" + fileListStr);
}
// add each file to the database
for (File motifFile : motifFiles) {
Path motifPath = motifFile.toPath();
Path relMotifPath = motifsPath.relativize(motifPath);
// see if the file was already added
pstmtFindMotifFileId.setString(1, relMotifPath.toString());
rs = pstmtFindMotifFileId.executeQuery();
Long motifFileId = null;
if (rs.next()) {
motifFileId = rs.getLong(1);
}
rs.close();
if (motifFileId == null) {
//get details about the motif
MotifStats stats = null;
try {
stats = MotifValidator.validate(motifFile, null);
} catch (IOException ignored) { }
if (stats == null) {
logger.log(Level.WARNING, "Failed to validate motifs in file: " + motifFile);
continue;
}
AlphStd alphStd = AlphStd.fromAlph(stats.getAlphabet());
if (alphStd == null) {
logger.log(Level.WARNING, "Non-standard alphabet used by motifs in file: " + motifFile);
continue;
}
// store details about the motif file
pstmtMotifFile.setString(1, relMotifPath.toString());
pstmtMotifFile.setInt(2, alphStd.toInt());
pstmtMotifFile.setInt(3, stats.getMotifCount());
pstmtMotifFile.setInt(4, stats.getTotalCols());
pstmtMotifFile.setInt(5, stats.getMinCols());
pstmtMotifFile.setInt(6, stats.getMaxCols());
pstmtMotifFile.setDouble(7, stats.getAverageCols());
pstmtMotifFile.setDouble(8, stats.getStandardDeviationCols());
pstmtMotifFile.executeUpdate();
// now get the motif file id
rs = pstmtListing.getGeneratedKeys();
if (!rs.next()) throw new SQLException("Failed to get Motif File Id.\n");
motifFileId = rs.getLong(1);
rs.close();
logger.log(Level.FINE, "Loaded Motif File: " + relMotifPath.toString());
}
// now link the listing to the motif file
pstmtListingMotif.setLong(2, motifFileId);
pstmtListingMotif.executeUpdate();
}
}
}
// close the prepared statements
pstmtCategory.close();
pstmtListing.close();
pstmtMotifFile.close();
pstmtListingMotif.close();
pstmtFindMotifFileId.close();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) { /* ignore */ }
}
}
}
public static void main(String[] args) throws Exception{
MotifDBList db = new MotifDBList(new File("/opt/meme/db/motif_databases/motif_db.csv"), new File("/opt/meme/db/motif_databases"));
List<Category> categories = db.getCategories(false, EnumSet.allOf(AlphStd.class));
for (Category category : categories) {
List<Listing> listings = db.getListings(category.getID(), false, EnumSet.allOf(AlphStd.class));
for (Listing listing : listings) {
MotifDB motifDB = db.getMotifListing(listing.getID());
System.out.println(motifDB.getName());
}
}
}
}
|
923856c57fb079c8e68137951ff44e0699f14344 | 303 | java | Java | dataTypes/DataTypes.java | Rashmidimpi/DS-JAVA-Algo | 420f3e3a5f0fe9e742c86292e490d91be08daeca | [
"Apache-2.0"
] | 1 | 2020-07-15T10:39:01.000Z | 2020-07-15T10:39:01.000Z | dataTypes/DataTypes.java | Rashmidimpi/DS-JAVA-Algo | 420f3e3a5f0fe9e742c86292e490d91be08daeca | [
"Apache-2.0"
] | null | null | null | dataTypes/DataTypes.java | Rashmidimpi/DS-JAVA-Algo | 420f3e3a5f0fe9e742c86292e490d91be08daeca | [
"Apache-2.0"
] | null | null | null | 16.833333 | 41 | 0.686469 | 998,397 | package dataTypes;
public class DataTypes {
public static void main(String[] args) {
// TODO Auto-generated method stub
int age = 10;
float rateOfInterest = 2.3f;
double rate = 3.145454;
System.out.println(rateOfInterest);
boolean isThisRashmi = true;
char myCharacter = '@';
}
}
|
9238570c96e1d228c604f4a1106b668adbfcf37b | 2,780 | java | Java | src/main/java/it/linksmt/cts2/plugin/sti/db/model/TempImportazione.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/linksmt/cts2/plugin/sti/db/model/TempImportazione.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/linksmt/cts2/plugin/sti/db/model/TempImportazione.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | 22.975207 | 87 | 0.721583 | 998,398 | package it.linksmt.cts2.plugin.sti.db.model;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
/**
* "temp_importazione" table model.
*
* @author Davide Pastore
*
*/
public class TempImportazione {
private Long codTempImportazione;
private Timestamp startTimeStamp;
private String nameCodeSystem;
private String versionCodeSystem;
private Date effectiveDate;
private String status;
private String statusMessage;
private String oid;
private String description;
public TempImportazione() {
}
/**
* Construct a {@link TempImportazione} object by the given {@link ResultSet} object.
* @param rs The {@link ResultSet} from which retrieve the data.
* @throws SQLException
*/
public TempImportazione(ResultSet rs) throws SQLException{
codTempImportazione = rs.getLong("cod_temp_importazione");
startTimeStamp = rs.getTimestamp("start_time_stamp");
nameCodeSystem = rs.getString("name_code_system");
versionCodeSystem = rs.getString("version_code_system");
effectiveDate = rs.getDate("effective_date");
status = rs.getString("status");
statusMessage = rs.getString("status_message");
oid = rs.getString("oid");
description = rs.getString("description");
}
public Long getCodTempImportazione() {
return codTempImportazione;
}
public void setCodTempImportazione(Long codTempImportazione) {
this.codTempImportazione = codTempImportazione;
}
public Timestamp getStartTimeStamp() {
return startTimeStamp;
}
public void setStartTimeStamp(Timestamp startTimeStamp) {
this.startTimeStamp = startTimeStamp;
}
public String getNameCodeSystem() {
return nameCodeSystem;
}
public void setNameCodeSystem(String nameCodeSystem) {
this.nameCodeSystem = nameCodeSystem;
}
public String getVersionCodeSystem() {
return versionCodeSystem;
}
public void setVersionCodeSystem(String versionCodeSystem) {
this.versionCodeSystem = versionCodeSystem;
}
public Date getEffectiveDate() {
return effectiveDate;
}
public void setEffectiveDate(Date effectiveDate) {
this.effectiveDate = effectiveDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
}
|
923859ae1bbb8d15f112c7ecd3db79d777bdd8fd | 2,064 | java | Java | src/test/java/com/artofarc/esb/action/ConfigServiceTest.java | karalus/esb0 | 935dcb21778a5f57fea29fb2afb6e0dd9fff6046 | [
"Apache-2.0"
] | 9 | 2018-03-12T10:05:50.000Z | 2022-01-07T17:40:01.000Z | src/test/java/com/artofarc/esb/action/ConfigServiceTest.java | karalus/esb0 | 935dcb21778a5f57fea29fb2afb6e0dd9fff6046 | [
"Apache-2.0"
] | 4 | 2019-08-14T08:45:43.000Z | 2022-03-28T09:48:56.000Z | src/test/java/com/artofarc/esb/action/ConfigServiceTest.java | karalus/esb0 | 935dcb21778a5f57fea29fb2afb6e0dd9fff6046 | [
"Apache-2.0"
] | 4 | 2018-03-16T20:51:05.000Z | 2021-08-20T02:51:22.000Z | 34.983051 | 167 | 0.731105 | 998,399 | package com.artofarc.esb.action;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.soap.SOAPConstants;
import javax.xml.ws.Endpoint;
import org.junit.Test;
import com.artofarc.esb.AbstractESBTest;
import com.artofarc.esb.ConsumerPort;
import com.artofarc.esb.artifact.ServiceArtifact;
import com.artofarc.esb.http.HttpConstants;
import com.artofarc.esb.message.BodyType;
import com.artofarc.esb.message.ESBMessage;
import com.artofarc.esb.message.ESBConstants;
public class ConfigServiceTest extends AbstractESBTest {
@WebService
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT)
public static class Echo {
public String checkAlive(String text) throws Exception {
Thread.sleep(500L);
return text;
}
}
@WebService
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT)
public static class Echo2 {
public String other(String text) throws Exception {
Thread.sleep(500L);
return text;
}
}
@Test
public void testHTTPService() throws Exception {
ServiceArtifact serviceArtifact = new ServiceArtifact(getGlobalContext().getFileSystem(), getGlobalContext().getFileSystem().getRoot(), "HttpService4.xservice");
serviceArtifact.setContent(readFile("src/test/resources/HttpService4.xservice"));
serviceArtifact.validate(getGlobalContext());
ConsumerPort consumerPort = serviceArtifact.getConsumerPort();
String url = "http://localhost:1212/echo";
Endpoint endpoint = Endpoint.publish(url, new Echo());
System.out.println("Service started @ " + url);
//
ESBMessage message = new ESBMessage(BodyType.BYTES, readFile("src/test/resources/SOAPRequest2.xml"));
message.getVariables().put(ESBConstants.HttpMethod, "POST");
message.putHeader(HttpConstants.HTTP_HEADER_CONTENT_TYPE, SOAPConstants.SOAP_1_1_CONTENT_TYPE);
//message.getHeaders().put(HttpAction.HTTP_HEADER_SOAP_ACTION, "\"\"");
consumerPort.processInternal(context, message);
endpoint.stop();
}
}
|
92385bccd3358eed5d97f426b290be75f73ddbe4 | 1,950 | java | Java | app/src/main/java/canvasolutions/kreemcabs/drivers/controller/AppController.java | UsamaHaf/K-Kareem | 475ae1c958b5fdf5b99e0dde084465f00bfe12c9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/canvasolutions/kreemcabs/drivers/controller/AppController.java | UsamaHaf/K-Kareem | 475ae1c958b5fdf5b99e0dde084465f00bfe12c9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/canvasolutions/kreemcabs/drivers/controller/AppController.java | UsamaHaf/K-Kareem | 475ae1c958b5fdf5b99e0dde084465f00bfe12c9 | [
"Apache-2.0"
] | null | null | null | 26.351351 | 76 | 0.657436 | 998,400 | package canvasolutions.kreemcabs.drivers.controller;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import androidx.multidex.MultiDex;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
/** Resolve multiplex problem **/
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
/*public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}*/
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
|
92385d4ed91f62202159c98bcef25edd13903045 | 265 | java | Java | backend/n2o/n2o-api/src/main/java/net/n2oapp/framework/api/metadata/meta/widget/chart/ChartType.java | osidorkin85/nno | cba91724beb63868d12a58d03953d2f3b30332b4 | [
"Apache-2.0"
] | 40 | 2018-12-20T08:21:48.000Z | 2021-08-15T01:13:35.000Z | backend/n2o/n2o-api/src/main/java/net/n2oapp/framework/api/metadata/meta/widget/chart/ChartType.java | osidorkin85/nno | cba91724beb63868d12a58d03953d2f3b30332b4 | [
"Apache-2.0"
] | 11 | 2020-01-10T10:29:15.000Z | 2022-03-29T05:21:59.000Z | backend/n2o/n2o-api/src/main/java/net/n2oapp/framework/api/metadata/meta/widget/chart/ChartType.java | osidorkin85/nno | cba91724beb63868d12a58d03953d2f3b30332b4 | [
"Apache-2.0"
] | 15 | 2018-12-28T08:47:37.000Z | 2022-02-04T08:53:35.000Z | 22.083333 | 60 | 0.611321 | 998,401 | package net.n2oapp.framework.api.metadata.meta.widget.chart;
/**
* Виды графиков / диаграмм
*/
public enum ChartType {
area, // диаграмма-область
bar, // гистограмма
line, // линейный график
pie // круговая диаграмма
}
|
92385f17380863b2177ece0b7c9f6c070e81368f | 940 | java | Java | src/main/java/chapter5/T5_8_RejectedExcecutionHanlderTest/Run.java | langkemaoxin/JavaConcurrentProgramming | 9f5927a0e60ec2bcb5c98aa87ff746e4874ae8a1 | [
"Apache-2.0"
] | null | null | null | src/main/java/chapter5/T5_8_RejectedExcecutionHanlderTest/Run.java | langkemaoxin/JavaConcurrentProgramming | 9f5927a0e60ec2bcb5c98aa87ff746e4874ae8a1 | [
"Apache-2.0"
] | null | null | null | src/main/java/chapter5/T5_8_RejectedExcecutionHanlderTest/Run.java | langkemaoxin/JavaConcurrentProgramming | 9f5927a0e60ec2bcb5c98aa87ff746e4874ae8a1 | [
"Apache-2.0"
] | null | null | null | 27.647059 | 113 | 0.652128 | 998,402 | package chapter5.T5_8_RejectedExcecutionHanlderTest;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @ClassName Run
* @Description TODO
* @Author GY.C
* @Date 2020/3/22 22:38
* @Version 1.0
*
* setRejectedExecutionHandler 当线程池关闭了之后,还强行添加任务,则会报错
*/
public class Run {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
pool.setRejectedExecutionHandler((a,b)->{
System.out.println(a.toString()+"拒绝了");
});
pool.execute(()-> System.out.println("A"));
pool.execute(()-> System.out.println("A"));
pool.execute(()-> System.out.println("A"));
pool.execute(()-> System.out.println("A"));
pool.shutdown();
pool.execute(()-> System.out.println("A"));
}
}
|
923861ee42f3fc1cd123ed58cd84678afc1bc621 | 900 | java | Java | src/main/java/com/perye/dokit/entity/Picture.java | perye/dok | 70cdfb0886564008a51247f33c94025dd4a302b6 | [
"RSA-MD"
] | 1 | 2021-06-29T14:02:53.000Z | 2021-06-29T14:02:53.000Z | src/main/java/com/perye/dokit/entity/Picture.java | xieguishui/dokit | dba458e471e1391811e17907e8d0861cead0de59 | [
"RSA-MD"
] | null | null | null | src/main/java/com/perye/dokit/entity/Picture.java | xieguishui/dokit | dba458e471e1391811e17907e8d0861cead0de59 | [
"RSA-MD"
] | null | null | null | 17.647059 | 55 | 0.654444 | 998,403 | package com.perye.dokit.entity;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* sm.ms图床
*/
@Data
@Entity
@Table(name = "picture")
public class Picture implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String filename;
private String url;
private String size;
private String height;
private String width;
@Column(name = "delete_url")
private String delete;
private String username;
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;
// 用于检测文件是否重复
private String md5Code;
@Override
public String toString() {
return "Picture{" +
"filename='" + filename + '\'' +
'}';
}
}
|
923862e5379763fdbddfc4387d3c2124e4812a55 | 4,364 | java | Java | jsyntaxpane/src/main/java/jsyntaxpane/Token.java | jbfaden/jsyntaxpane | d11a698689f92d6b8ce1a7a8f85d2a304219149a | [
"Apache-1.1"
] | 28 | 2015-07-14T22:41:58.000Z | 2022-02-23T02:21:04.000Z | jsyntaxpane/src/main/java/jsyntaxpane/Token.java | jbfaden/jsyntaxpane | d11a698689f92d6b8ce1a7a8f85d2a304219149a | [
"Apache-1.1"
] | 56 | 2015-05-02T22:40:25.000Z | 2021-07-08T10:20:29.000Z | jsyntaxpane/src/main/java/jsyntaxpane/Token.java | jbfaden/jsyntaxpane | d11a698689f92d6b8ce1a7a8f85d2a304219149a | [
"Apache-1.1"
] | 29 | 2015-07-15T08:52:50.000Z | 2022-02-25T01:59:43.000Z | 30.151724 | 85 | 0.613907 | 998,404 | /*
* Copyright 2008 Ayman Al-Sairafi anpch@example.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License
* at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsyntaxpane;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Segment;
/**
* A Token in a Document. Tokens do NOT store a reference to the
* underlying SyntaxDocument, and must generally be obtained from
* the SyntaxDocument methods. The reason for not storing the
* SyntaxDocument is simply for memory, as the number of Tokens
* per document can be large, you may end up with twice the memory
* in a SyntaxDocument with Tokens than a simple PlainDocument.
*
* @author Ayman Al-Sairafi
*/
public class Token implements Serializable, Comparable {
public final TokenType type;
public final int start;
public final int length;
/**
* the pair value to use if this token is one of a pair:
* This is how it is used:
* The opening part will have a positive number X
* The closing part will have a negative number X
* X should be unique for a pair:
* e.g. for [ pairValue = +1
* for ] pairValue = -1
*/
public final byte pairValue;
/**
* The kind of the Document. This is only needed if proper Parsing
* of a document is needed and it makes certain operations faster.
* You can use any of the supplied Generic Values, or create your
* language specific uses by using USER_FIRST + x;
*/
public final short kind = 0;
/**
* Constructs a new token
*/
public Token(TokenType type, int start, int length) {
this.type = type;
this.start = start;
this.length = length;
this.pairValue = 0;
}
/**
* Construct a new part of pair token
*/
public Token(TokenType type, int start, int length, byte pairValue) {
this.type = type;
this.start = start;
this.length = length;
this.pairValue = pairValue;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Token) {
Token token = (Token) obj;
return ((this.start == token.start) &&
(this.length == token.length) &&
(this.type.equals(token.type)));
} else {
return false;
}
}
@Override
public int hashCode() {
return start;
}
@Override
public String toString() {
if (pairValue == 0) {
return String.format("%s (%d, %d)", type, start, length);
} else {
return String.format("%s (%d, %d) (%d)", type, start, length, pairValue);
}
}
@Override
public int compareTo(Object o) {
Token t = (Token) o;
if (this.start != t.start) {
return (this.start - t.start);
} else if (this.length != t.length) {
return (this.length - t.length);
} else {
return this.type.compareTo(t.type);
}
}
/**
* return the end position of the token.
* @return start + length
*/
public int end() {
return start + length;
}
/**
* Get the text of the token from this document
*/
public CharSequence getText(Document doc) {
Segment text = new Segment();
try {
doc.getText(start, length, text);
} catch (BadLocationException ex) {
Logger.getLogger(Token.class.getName()).log(Level.SEVERE, null, ex);
}
return text;
}
public String getString(Document doc) {
try {
return doc.getText(start, length);
} catch (BadLocationException ex) {
Logger.getLogger(Token.class.getName()).log(Level.SEVERE, null, ex);
return "";
}
}
}
|
9238635e18aa84c1c49da7f8d54a3dbcb71d8d0a | 5,666 | java | Java | src/imop/lib/transform/simplify/OldFunctionStyleRemover.java | amannougrahiya/imop-compiler | a0f0c9aaea00c6e5d37a17172c5db2967822ba9b | [
"MIT"
] | 10 | 2020-02-24T20:39:06.000Z | 2021-11-01T03:33:22.000Z | src/imop/lib/transform/simplify/OldFunctionStyleRemover.java | anonymousoopsla21/homeostasis | e56c5c2f8392027ad5a49a45d7ac49a139c33674 | [
"MIT"
] | 2 | 2020-02-25T20:30:46.000Z | 2020-07-18T19:05:27.000Z | src/imop/lib/transform/simplify/OldFunctionStyleRemover.java | anonymousoopsla21/homeostasis | e56c5c2f8392027ad5a49a45d7ac49a139c33674 | [
"MIT"
] | 2 | 2020-03-11T11:53:47.000Z | 2021-08-23T06:49:57.000Z | 37.03268 | 110 | 0.68461 | 998,405 | /*
* Copyright (c) 2019 Aman Nougrahiya, V Krishna Nandivada, IIT Madras.
* This file is a part of the project IMOP, licensed under the MIT license.
* See LICENSE.md for the full text of the license.
*
* The above notice shall be included in all copies or substantial
* portions of this file.
*/
package imop.lib.transform.simplify;
import imop.ast.node.external.*;
import imop.baseVisitor.DepthFirstProcess;
import imop.parser.FrontEnd;
/**
* This class takes all the FunctionDefintions and replaces old-style parameter
* declarations with the new style ones.
*/
public class OldFunctionStyleRemover extends DepthFirstProcess {
/**
* f0 ::= ( DeclarationSpecifiers() )?
* f1 ::= Declarator()
* f2 ::= ( DeclarationList() )?
* f3 ::= CompoundStatement()
*/
@Override
public void visit(FunctionDefinition n) {
// If f0's node is null, then replace it with "int"
if (n.getF0().getNode() == null) {
DeclarationSpecifiers declSpec = FrontEnd.parseAlone("int", DeclarationSpecifiers.class);
declSpec.setParent(n.getF0());
n.getF0().setNode(declSpec);
}
ADeclaratorOp firstDeclOpChoice = (ADeclaratorOp) n.getF1().getF1().getF1().getF0().getNodes().get(0);
Node firstDeclOp = firstDeclOpChoice.getF0().getChoice();
if (firstDeclOp instanceof ParameterTypeListClosed) {
// This is a new-style parameter list
// Do nothing. No visit to parts required as C doesn't support nested function
// definitions.
return;
} else if (firstDeclOp instanceof OldParameterListClosed) {
// This is an old-style parameter list.
// Change this to a new-style parameter list
if (((OldParameterListClosed) firstDeclOp).getF1().getNode() == null) {
// Do nothing and return
return;
}
OldParameterList oldParaList = (OldParameterList) ((OldParameterListClosed) firstDeclOp).getF1().getNode();
/*
* Algorithm:
* For all the identifiers in the old-style parameter list,
* obtain the corresponding declaration and declarator.
* If no such information is found, use int for declaration.
* else, create the new parameter's string.
* Complete the string and add it to the FunctionDefinition
* at the appropriate place.
*/
String newDeclaratorString = new String();
newDeclaratorString = n.getF1().getF0().getInfo().getString(); // Add (pointer)?
newDeclaratorString += n.getF1().getF1().getF0().getInfo().getString(); // From DirectDeclarator, add
// IdentifierOrDeclarator
newDeclaratorString += "("; // Start the new-style parameter list
/*
* From firstDeclOpChoice, get all the identifiers one-by-one and
* after finding their appropriate declarations add them
*/
// Process the first identifier
String idName = oldParaList.getF0().getTokenImage();
Declaration declForParam = getDeclarationFromList(n.getF2(), idName);
if (declForParam == null) {
// This parameter is of type "int"
newDeclaratorString += "int " + idName;
} else {
// This parameter is defined in declForParam
// Get the appropriate string in newDeclarator
Declarator declaratorForParam = declForParam.getInfo().getDeclarator(idName);
if (declaratorForParam == null) {
// Some error
System.out.println(
"Can't find declarator for " + idName + " in " + declForParam.getInfo().getString());
Thread.dumpStack();
System.exit(0);
}
newDeclaratorString += declForParam.getF0().getInfo().getString() + " "
+ declaratorForParam.getInfo().getString();
}
// Process the remaining identifier
for (Node seq : oldParaList.getF1().getNodes()) {
newDeclaratorString += ", ";
assert seq instanceof NodeSequence;
idName = ((NodeToken) ((NodeSequence) seq).getNodes().get(1)).getTokenImage();
declForParam = getDeclarationFromList(n.getF2(), idName);
if (declForParam == null) {
// This parameter is of type "int"
newDeclaratorString += "int " + idName;
} else {
// This parameter is defined in declForParam
// Get the appropriate string in newDeclarator
Declarator declaratorForParam = declForParam.getInfo().getDeclarator(idName);
if (declaratorForParam == null) {
// Some error
System.out.println(
"Can't find declarator for " + idName + " in " + declForParam.getInfo().getString());
Thread.dumpStack();
System.exit(0);
}
newDeclaratorString += declForParam.getF0().getInfo().getString() + " "
+ declaratorForParam.getInfo().getString();
}
}
newDeclaratorString += ")"; // End the new-style parameter list
// Create the new declarator and make proper adjustments to replace
// the old-style parameter list with the new style parameter list
// 1.) Removing (DeclarationList)?
n.getF2().setNode(null);
// 2.) Replacing Declarator with newDeclarator obtained from newDeclaratorString
n.setF1(FrontEnd.parseAlone(newDeclaratorString, Declarator.class));
n.getF1().setParent(n);
}
}
/**
* @param declList:
* A NodeOptional of DeclarationList to be checked
* @param idName:
* An identifier name
* @return The declaration which contains idName
*/
public Declaration getDeclarationFromList(NodeOptional declListOption, String idName) {
if (declListOption.getNode() == null) {
return null;
}
DeclarationList declList = (DeclarationList) declListOption.getNode();
for (Node seq : declList.getF0().getNodes()) {
Declaration decl = (Declaration) seq;
for (String idElem : decl.getInfo().getIDNameList()) {
if (idElem.equals(idName)) {
return decl;
}
}
}
return null;
}
}
|
923863c52e397216c9a9eafcf01a564c74be234b | 3,428 | java | Java | src/main/java/com/weshare/wesharespring/service/AppointmentService.java | chenfanggm/steven-spring-boot-starter-kit | 06e6c1aabef9e3bf7ee1d164c3c194bbf567f434 | [
"MIT"
] | 4 | 2016-09-25T02:15:02.000Z | 2017-12-05T07:10:55.000Z | src/main/java/com/weshare/wesharespring/service/AppointmentService.java | chenfanggm/steven-spring-boot-starter-kit | 06e6c1aabef9e3bf7ee1d164c3c194bbf567f434 | [
"MIT"
] | null | null | null | src/main/java/com/weshare/wesharespring/service/AppointmentService.java | chenfanggm/steven-spring-boot-starter-kit | 06e6c1aabef9e3bf7ee1d164c3c194bbf567f434 | [
"MIT"
] | null | null | null | 38.088889 | 123 | 0.705076 | 998,406 | package com.weshare.wesharespring.service;
import com.weshare.wesharespring.common.constant.Constant;
import com.weshare.wesharespring.common.exception.DuplicateItemException;
import com.weshare.wesharespring.common.exception.ItemNotFoundException;
import com.weshare.wesharespring.common.exception.StorageServiceException;
import com.weshare.wesharespring.common.utils.Utils;
import com.weshare.wesharespring.entity.Appointment;
import com.weshare.wesharespring.entity.Profile;
import com.weshare.wesharespring.jdbi.dao.AppointmentDao;
import org.skife.jdbi.v2.exceptions.DBIException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class AppointmentService {
private final AppointmentDao appointmentDao;
private final ProfileService profileService;
@Autowired
public AppointmentService(final AppointmentDao appointmentDao,
final ProfileService profileService) {
this.appointmentDao = appointmentDao;
this.profileService = profileService;
}
public Appointment getAppointmentById(final Long appointmentId)
throws ItemNotFoundException, StorageServiceException {
try {
final Appointment appointment = appointmentDao.getById(appointmentId);
if (appointment == null) {
throw new ItemNotFoundException();
}
return appointment;
} catch (final DBIException dbiException) {
throw new StorageServiceException(dbiException);
}
}
public List<Appointment> getAppointmentByUserId(final Long userId)
throws ItemNotFoundException, StorageServiceException {
try {
final List<Appointment> appointmentList = appointmentDao.getAppointmentByUserId(userId);
if (appointmentList == null || appointmentList.isEmpty()) {
throw new ItemNotFoundException();
}
return appointmentList;
} catch (final DBIException dbiException) {
throw new StorageServiceException(dbiException);
}
}
public Appointment createAppointment(final Appointment appointment)
throws DuplicateItemException, ItemNotFoundException, StorageServiceException {
try {
final Long timeNow = Utils.getCurrentTimeStamp();
final Long appointmentId = appointmentDao.create(appointment.getUserId(), appointment.getAppointmentType(),
appointment.getTopicId(), appointment.getSummary(), appointment.getQuestion(), appointment.getMeetupTime(),
appointment.getMeetupAddress(),Constant.APPOINTMENT_STATUS_ACTIVE, timeNow);
// update profile
final Profile profile = Profile.builder()
.userId(appointment.getUserId())
.contactWechat(appointment.getContactWechat())
.build();
profileService.updateProfile(profile);
return getAppointmentById(appointmentId);
} catch (final DBIException dbiException) {
if (Utils.isDuplicateEntryException(dbiException)) {
throw new DuplicateItemException(dbiException);
}
throw new StorageServiceException(dbiException);
}
}
}
|
923865762870c4318f4ec62b353bc27fd22115f3 | 1,551 | java | Java | app/src/CET/java/com/qingyun/mvpretrofitrx/mvp/adapter/AssetHistoryAdapter.java | qykjsz/eta | 4e4af2529ed52e599adab19703edebdec9a5bd70 | [
"Apache-2.0"
] | 1 | 2020-09-14T01:03:36.000Z | 2020-09-14T01:03:36.000Z | app/src/CET/java/com/qingyun/mvpretrofitrx/mvp/adapter/AssetHistoryAdapter.java | qykjsz/eta | 4e4af2529ed52e599adab19703edebdec9a5bd70 | [
"Apache-2.0"
] | null | null | null | app/src/CET/java/com/qingyun/mvpretrofitrx/mvp/adapter/AssetHistoryAdapter.java | qykjsz/eta | 4e4af2529ed52e599adab19703edebdec9a5bd70 | [
"Apache-2.0"
] | null | null | null | 26.288136 | 112 | 0.732431 | 998,407 | package com.qingyun.mvpretrofitrx.mvp.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.qingyun.mvpretrofitrx.mvp.base.BaseAdapter;
import com.qingyun.mvpretrofitrx.mvp.base.BaseViewHolder;
import com.qingyun.mvpretrofitrx.mvp.entity.AssetHistory;
import com.senon.mvpretrofitrx.R;
import java.util.List;
import butterknife.BindView;
public class AssetHistoryAdapter extends BaseAdapter<AssetHistory, AssetHistoryAdapter.AssetHistoryViewHolder> {
public AssetHistoryAdapter(Context context, List<AssetHistory> list) {
super(context, list);
}
@Override
protected AssetHistoryViewHolder getViewHolder(ViewGroup parent, int viewType) {
return new AssetHistoryViewHolder(getView(R.layout.item_asset_history, parent));
}
@Override
protected void onItemReset(AssetHistoryViewHolder holder) {
}
@Override
protected void onItemSelect(AssetHistoryViewHolder holder) {
}
@Override
protected void viewHolderBind(AssetHistoryViewHolder holder, int position) {
}
class AssetHistoryViewHolder extends BaseViewHolder {
@BindView(R.id.iv)
ImageView iv;
@BindView(R.id.tv_address)
TextView tvAddress;
@BindView(R.id.tv_time)
TextView tvTime;
@BindView(R.id.tv_amount)
TextView tvAmount;
public AssetHistoryViewHolder(View itemView) {
super(itemView);
}
}
}
|
923865898468f0467d9b12df83eea367e06099f3 | 9,255 | java | Java | src/main/java/at/ac/ait/ariadne/routeformat/RoutingResponse.java | dts-ait/sproute-json-route-format | dd740590ec64da981320e5492a041a29e329bf6c | [
"CC0-1.0"
] | 6 | 2016-11-14T20:25:55.000Z | 2017-07-19T15:41:40.000Z | src/main/java/at/ac/ait/ariadne/routeformat/RoutingResponse.java | dts-ait/sproute-json-route-format | dd740590ec64da981320e5492a041a29e329bf6c | [
"CC0-1.0"
] | null | null | null | src/main/java/at/ac/ait/ariadne/routeformat/RoutingResponse.java | dts-ait/sproute-json-route-format | dd740590ec64da981320e5492a041a29e329bf6c | [
"CC0-1.0"
] | null | null | null | 34.793233 | 116 | 0.647758 | 998,408 | package at.ac.ait.ariadne.routeformat;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import at.ac.ait.ariadne.routeformat.Constants.Status;
import at.ac.ait.ariadne.routeformat.util.Utils;
/**
* A {@link RoutingResponse} encapsulates the response of routing services. It
* contains, amongst others, an optional {@link RoutingRequest}, a status, and
* of course one or more {@link Route}(s).
* <p>
* Since most attributes are mandatory no <code>createMinimal</code> method is
* offered.
* <p>
* The coordinate reference system is not directly set in the GeoJSON elements
* (as the specification would allow) because this would lead to unnecessarily
* big file sizes. Instead the CRS can optionally be set with the attribute
* {@link RoutingResponse#getCoordinateReferenceSystem()}.
*
* @author AIT Austrian Institute of Technology GmbH
*/
@JsonInclude(Include.NON_ABSENT)
public class RoutingResponse implements Validatable {
private String routeFormatVersion;
private String requestId;
private ZonedDateTime processedTime;
private Status status;
private Optional<String> debugMessage = Optional.empty();
private String coordinateReferenceSystem;
private Optional<RoutingRequest> request = Optional.empty();
private List<Route> routes = new ArrayList<>();
private Map<String, Object> additionalInfo = new TreeMap<>();
// -- getters
@JsonProperty(required = true)
public String getRouteFormatVersion() {
return routeFormatVersion;
}
@JsonProperty(required = true)
public String getRequestId() {
return requestId;
}
/**
* Time when request / calculations were finished or deemed not possible in
* case of an error.
*/
@JsonProperty(required = true)
public String getProcessedTime() {
return Utils.getDateTimeString(processedTime);
}
@JsonIgnore
public ZonedDateTime getProcessedTimeAsZonedDateTime() {
return processedTime;
}
@JsonProperty(required = true)
public Status getStatus() {
return status;
}
/** debug message explaining errors */
public Optional<String> getDebugMessage() {
return debugMessage;
}
/** in the form of EPSG:*, e.g. EPSG:4326 */
@JsonProperty(required = true)
public String getCoordinateReferenceSystem() {
return coordinateReferenceSystem;
}
/**
* @return The original request used to calculate the route(s). It is
* guaranteed that if at least one route is returned there is also a
* request here. The request will only be omitted if the request
* itself could not be created due to invalid request parameters.
*/
public Optional<RoutingRequest> getRequest() {
return request;
}
public Map<String, Object> getAdditionalInfo() {
return additionalInfo;
}
@JsonProperty(required = true)
public List<Route> getRoutes() {
return routes;
}
// -- setters
public RoutingResponse setRouteFormatVersion(String routeFormatVersion) {
this.routeFormatVersion = routeFormatVersion;
return this;
}
public RoutingResponse setRequestId(String requestId) {
this.requestId = requestId;
return this;
}
public RoutingResponse setProcessedTimeNow() {
this.processedTime = ZonedDateTime.now();
return this;
}
@JsonIgnore
public RoutingResponse setProcessedTime(ZonedDateTime processedTime) {
this.processedTime = processedTime;
return this;
}
@JsonProperty
public RoutingResponse setProcessedTime(String processedTime) {
this.processedTime = Utils.parseDateTime(processedTime, "processedTime");
return this;
}
public RoutingResponse setStatus(Status status) {
this.status = status;
return this;
}
public RoutingResponse setDebugMessage(String debugMessage) {
this.debugMessage = Optional.ofNullable(debugMessage);
return this;
}
public RoutingResponse setCoordinateReferenceSystem(String coordinateReferenceSystem) {
this.coordinateReferenceSystem = coordinateReferenceSystem;
return this;
}
public RoutingResponse setDefaultCoordinateReferenceSystem() {
this.coordinateReferenceSystem = "EPSG:4326";
return this;
}
public RoutingResponse setRequest(RoutingRequest request) {
this.request = Optional.ofNullable(request);
return this;
}
public RoutingResponse setRoutes(List<Route> routes) {
this.routes = new ArrayList<>(routes);
return this;
}
public RoutingResponse setAdditionalInfo(Map<String, Object> additionalInfo) {
this.additionalInfo = new TreeMap<>(additionalInfo);
return this;
}
// --
// no createMinimal! see javadoc for explanation.
@Override
public void validate() {
Preconditions.checkArgument(routeFormatVersion != null, "routeFormatVersion is mandatory but missing");
Preconditions.checkArgument(requestId != null, "requestId is mandatory but missing");
Preconditions.checkArgument(processedTime != null, "processedTime is mandatory but missing");
Preconditions.checkArgument(status != null, "status is mandatory but missing");
Preconditions.checkArgument(coordinateReferenceSystem != null,
"coordinateReferenceSystem is mandatory but missing");
Preconditions.checkArgument(coordinateReferenceSystem.startsWith("EPSG:"),
"coordinateReferenceSystem must start with EPSG:");
request.ifPresent(r -> r.validate());
routes.forEach(r -> r.validate());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((coordinateReferenceSystem == null) ? 0 : coordinateReferenceSystem.hashCode());
result = prime * result + ((debugMessage == null) ? 0 : debugMessage.hashCode());
result = prime * result + ((processedTime == null) ? 0 : processedTime.hashCode());
result = prime * result + ((request == null) ? 0 : request.hashCode());
result = prime * result + ((requestId == null) ? 0 : requestId.hashCode());
result = prime * result + ((routeFormatVersion == null) ? 0 : routeFormatVersion.hashCode());
result = prime * result + ((routes == null) ? 0 : routes.hashCode());
result = prime * result + ((status == null) ? 0 : status.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;
RoutingResponse other = (RoutingResponse) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (coordinateReferenceSystem == null) {
if (other.coordinateReferenceSystem != null)
return false;
} else if (!coordinateReferenceSystem.equals(other.coordinateReferenceSystem))
return false;
if (debugMessage == null) {
if (other.debugMessage != null)
return false;
} else if (!debugMessage.equals(other.debugMessage))
return false;
if (processedTime == null) {
if (other.processedTime != null)
return false;
} else if (!processedTime.equals(other.processedTime))
return false;
if (request == null) {
if (other.request != null)
return false;
} else if (!request.equals(other.request))
return false;
if (requestId == null) {
if (other.requestId != null)
return false;
} else if (!requestId.equals(other.requestId))
return false;
if (routeFormatVersion == null) {
if (other.routeFormatVersion != null)
return false;
} else if (!routeFormatVersion.equals(other.routeFormatVersion))
return false;
if (routes == null) {
if (other.routes != null)
return false;
} else if (!routes.equals(other.routes))
return false;
if (status != other.status)
return false;
return true;
}
@Override
public String toString() {
return "RoutingResponse [requestId=" + requestId + ", processedTime=" + processedTime + ", status=" + status
+ ", routes=" + routes.size() + "]";
}
}
|
923865a2a17e5ef11419bcc251e3b34cfa045683 | 6,437 | java | Java | gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/SetMembersCommand.java | hdost/gerrit | 75129a2d533450530465afc4145f2083b3dc196f | [
"Apache-2.0"
] | 1 | 2019-02-09T00:22:48.000Z | 2019-02-09T00:22:48.000Z | gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/SetMembersCommand.java | hdost/gerrit | 75129a2d533450530465afc4145f2083b3dc196f | [
"Apache-2.0"
] | 1 | 2021-02-23T22:02:25.000Z | 2021-02-23T23:13:26.000Z | gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/SetMembersCommand.java | hdost/gerrit | 75129a2d533450530465afc4145f2083b3dc196f | [
"Apache-2.0"
] | 1 | 2020-12-09T11:06:59.000Z | 2020-12-09T11:06:59.000Z | 39.012121 | 123 | 0.697685 | 998,409 | // Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.sshd.commands;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.TopLevelResource;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.GroupCache;
import com.google.gerrit.server.group.AddIncludedGroups;
import com.google.gerrit.server.group.AddMembers;
import com.google.gerrit.server.group.DeleteIncludedGroups;
import com.google.gerrit.server.group.DeleteMembers;
import com.google.gerrit.server.group.GroupResource;
import com.google.gerrit.server.group.GroupsCollection;
import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
@CommandMetaData(name = "set-members", description = "Modify members of specific group or number of groups")
public class SetMembersCommand extends SshCommand {
@Option(name = "--add", aliases = {"-a"}, metaVar = "USER", usage = "users that should be added as group member")
private List<Account.Id> accountsToAdd = Lists.newArrayList();
@Option(name = "--remove", aliases = {"-r"}, metaVar = "USER", usage = "users that should be removed from the group")
private List<Account.Id> accountsToRemove = Lists.newArrayList();
@Option(name = "--include", aliases = {"-i"}, metaVar = "GROUP", usage = "group that should be included as group member")
private List<AccountGroup.UUID> groupsToInclude = Lists.newArrayList();
@Option(name = "--exclude", aliases = {"-e"}, metaVar = "GROUP", usage = "group that should be excluded from the group")
private List<AccountGroup.UUID> groupsToRemove = Lists.newArrayList();
@Argument(index = 0, required = true, multiValued = true, metaVar = "GROUP", usage = "groups to modify")
private List<AccountGroup.UUID> groups = Lists.newArrayList();
@Inject
private Provider<AddMembers> addMembers;
@Inject
private Provider<DeleteMembers> deleteMembers;
@Inject
private Provider<AddIncludedGroups> addIncludedGroups;
@Inject
private Provider<DeleteIncludedGroups> deleteIncludedGroups;
@Inject
private GroupsCollection groupsCollection;
@Inject
private GroupCache groupCache;
@Inject
private AccountCache accountCache;
@Override
protected void run() throws UnloggedFailure, Failure, Exception {
for (AccountGroup.UUID groupUuid : groups) {
GroupResource resource =
groupsCollection.parse(TopLevelResource.INSTANCE,
IdString.fromUrl(groupUuid.get()));
if (!accountsToRemove.isEmpty()) {
deleteMembers.get().apply(resource, fromMembers(accountsToRemove));
reportMembersAction("removed from", resource, accountsToRemove);
}
if (!groupsToRemove.isEmpty()) {
deleteIncludedGroups.get().apply(resource, fromGroups(groupsToRemove));
reportGroupsAction("excluded from", resource, groupsToRemove);
}
if (!accountsToAdd.isEmpty()) {
addMembers.get().apply(resource, fromMembers(accountsToAdd));
reportMembersAction("added to", resource, accountsToAdd);
}
if (!groupsToInclude.isEmpty()) {
addIncludedGroups.get().apply(resource, fromGroups(groupsToInclude));
reportGroupsAction("included to", resource, groupsToInclude);
}
}
}
private void reportMembersAction(String action, GroupResource group,
List<Account.Id> accountIdList) throws UnsupportedEncodingException,
IOException {
out.write(String.format(
"Members %s group %s: %s\n",
action,
group.getName(),
Joiner.on(", ").join(
Iterables.transform(accountIdList,
new Function<Account.Id, String>() {
@Override
public String apply(Account.Id accountId) {
return MoreObjects.firstNonNull(accountCache.get(accountId)
.getAccount().getPreferredEmail(), "n/a");
}
}))).getBytes(ENC));
}
private void reportGroupsAction(String action, GroupResource group,
List<AccountGroup.UUID> groupUuidList)
throws UnsupportedEncodingException, IOException {
out.write(String.format(
"Groups %s group %s: %s\n",
action,
group.getName(),
Joiner.on(", ").join(
Iterables.transform(groupUuidList,
new Function<AccountGroup.UUID, String>() {
@Override
public String apply(AccountGroup.UUID uuid) {
return groupCache.get(uuid).getName();
}
}))).getBytes(ENC));
}
private AddIncludedGroups.Input fromGroups(List<AccountGroup.UUID> accounts) {
return AddIncludedGroups.Input.fromGroups(Lists.newArrayList(Iterables
.transform(accounts, new Function<AccountGroup.UUID, String>() {
@Override
public String apply(AccountGroup.UUID uuid) {
return uuid.toString();
}
})));
}
private AddMembers.Input fromMembers(List<Account.Id> accounts) {
return AddMembers.Input.fromMembers(Lists.newArrayList(Iterables.transform(
accounts, new Function<Account.Id, String>() {
@Override
public String apply(Account.Id id) {
return id.toString();
}
})));
}
}
|
923866716fc18607a2e9bcb8e9390c39d828e550 | 1,008 | java | Java | AL-Game/src/com/aionemu/gameserver/utils/TimeUtil.java | karllgiovany/Aion-Lightning-4.9-SRC | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2019-04-05T22:44:56.000Z | 2019-04-05T22:44:56.000Z | AL-Game/src/com/aionemu/gameserver/utils/TimeUtil.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | null | null | null | AL-Game/src/com/aionemu/gameserver/utils/TimeUtil.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2017-12-28T16:59:47.000Z | 2017-12-28T16:59:47.000Z | 32.516129 | 74 | 0.706349 | 998,410 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.utils;
/**
* @author ATracer
*/
public class TimeUtil {
/**
* Check whether supplied time in ms is expired
*/
public static final boolean isExpired(long time) {
return time < System.currentTimeMillis();
}
}
|
92386753e8563267bd00506a0293066a96f3dc90 | 1,394 | java | Java | subprojects/build-cache/src/main/java/org/gradle/caching/internal/NoOpBuildCacheService.java | stefanleh/gradle | c48e1c7bc796f7f3f6d207b7f635f0783965ab3d | [
"Apache-2.0"
] | 2 | 2018-09-29T05:42:34.000Z | 2018-12-12T05:15:10.000Z | subprojects/build-cache/src/main/java/org/gradle/caching/internal/NoOpBuildCacheService.java | stefanleh/gradle | c48e1c7bc796f7f3f6d207b7f635f0783965ab3d | [
"Apache-2.0"
] | 8 | 2018-04-17T21:57:28.000Z | 2018-08-10T08:06:58.000Z | subprojects/build-cache/src/main/java/org/gradle/caching/internal/NoOpBuildCacheService.java | stefanleh/gradle | c48e1c7bc796f7f3f6d207b7f635f0783965ab3d | [
"Apache-2.0"
] | 4 | 2016-12-30T06:18:52.000Z | 2021-01-13T10:39:29.000Z | 32.418605 | 101 | 0.75825 | 998,411 | /*
* Copyright 2017 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.gradle.caching.internal;
import org.gradle.caching.BuildCacheEntryReader;
import org.gradle.caching.BuildCacheEntryWriter;
import org.gradle.caching.BuildCacheException;
import org.gradle.caching.BuildCacheKey;
import org.gradle.caching.BuildCacheService;
import java.io.IOException;
@SuppressWarnings("unused") // used in integration tests
public class NoOpBuildCacheService implements BuildCacheService {
@Override
public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
return false;
}
@Override
public void store(BuildCacheKey key, BuildCacheEntryWriter writer) throws BuildCacheException {
}
@Override
public void close() throws IOException {
// Do nothing
}
}
|
923867714e0520e56a637b04a7a0fca0fabdef81 | 236 | java | Java | src/main/java/top/vetoer/comm/aop/LoggerManage.java | comTg/movie-axis | 37efca6be11fcf26e5f3f22010c468da9fcc32da | [
"Apache-2.0"
] | 1 | 2018-09-10T15:08:13.000Z | 2018-09-10T15:08:13.000Z | src/main/java/top/vetoer/comm/aop/LoggerManage.java | comTg/note-axis | 79161af383d042d5f97fdf2619012756ef2d79ef | [
"Apache-2.0"
] | null | null | null | src/main/java/top/vetoer/comm/aop/LoggerManage.java | comTg/note-axis | 79161af383d042d5f97fdf2619012756ef2d79ef | [
"Apache-2.0"
] | null | null | null | 16.857143 | 35 | 0.745763 | 998,412 | package top.vetoer.comm.aop;
import java.lang.annotation.*;
/**
* @Description: 日志注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoggerManage {
public String description();
}
|
92386970e3574c9912d73aa94b2efb7259e3aaa1 | 1,983 | java | Java | security-oauth2/src/main/java/io/micronaut/security/oauth2/endpoint/authorization/response/AuthorizationErrorResponseException.java | jleweb/micronaut-security | c4b90a527e5e69c11a19a266881e149931fc45c9 | [
"Apache-2.0"
] | 138 | 2019-04-17T15:56:03.000Z | 2022-03-21T19:31:53.000Z | security-oauth2/src/main/java/io/micronaut/security/oauth2/endpoint/authorization/response/AuthorizationErrorResponseException.java | jleweb/micronaut-security | c4b90a527e5e69c11a19a266881e149931fc45c9 | [
"Apache-2.0"
] | 463 | 2019-04-18T01:58:34.000Z | 2022-03-31T17:20:52.000Z | security-oauth2/src/main/java/io/micronaut/security/oauth2/endpoint/authorization/response/AuthorizationErrorResponseException.java | jleweb/micronaut-security | c4b90a527e5e69c11a19a266881e149931fc45c9 | [
"Apache-2.0"
] | 105 | 2019-04-25T12:58:28.000Z | 2022-03-28T11:32:25.000Z | 34.789474 | 105 | 0.689864 | 998,413 | /*
* Copyright 2017-2020 original 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 io.micronaut.security.oauth2.endpoint.authorization.response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A runtime exception thrown when a Oauth 2. Error code is received from the authorization endpoint.
*
* @author Sergio del Amo
* @since 1.2.0
*/
public class AuthorizationErrorResponseException extends RuntimeException {
private static final Logger LOG = LoggerFactory.getLogger(AuthorizationErrorResponseException.class);
private final AuthorizationErrorResponse authorizationErrorResponse;
/**
* Constructor.
*
* @param error OAuth 2.0 Authentication Error Response.
*/
public AuthorizationErrorResponseException(AuthorizationErrorResponse error) {
if (LOG.isDebugEnabled()) {
LOG.debug("error: {} error_description: {}, state: {} error_uri {}",
error.getError(),
error.getErrorDescription() != null ? error.getErrorDescription() : "",
error.getErrorUri() != null ? error.getErrorUri() : "",
error.getState() != null ? error.getState() : "");
}
this.authorizationErrorResponse = error;
}
/**
*
* @return Authentication Error Response.
*/
public AuthorizationErrorResponse getAuthorizationErrorResponse() {
return authorizationErrorResponse;
}
}
|
923869d23168c3726f6b60124fe47241db18ff52 | 1,320 | java | Java | src/main/java/org/trebol/operation/controllers/DataBillingTypesController.java | erickcernarequejo/spring-boot-backend | 9ce47aef365fbeb670bd0b83ee281e7015b5ea61 | [
"MIT"
] | null | null | null | src/main/java/org/trebol/operation/controllers/DataBillingTypesController.java | erickcernarequejo/spring-boot-backend | 9ce47aef365fbeb670bd0b83ee281e7015b5ea61 | [
"MIT"
] | 18 | 2020-12-25T14:59:40.000Z | 2021-09-20T20:14:26.000Z | src/main/java/org/trebol/operation/controllers/DataBillingTypesController.java | trebol-ecommerce/trebol-jee | 421dfd8a7dd66ae4819db573cf842ca3c7ee2ccc | [
"MIT"
] | null | null | null | 33.846154 | 101 | 0.790909 | 998,414 | package org.trebol.operation.controllers;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.trebol.operation.GenericDataController;
import org.trebol.pojo.DataPagePojo;
import org.trebol.pojo.BillingTypePojo;
import org.trebol.config.OperationProperties;
import org.trebol.jpa.GenericJpaService;
import org.trebol.jpa.entities.BillingType;
/**
* API point of entry for ProductCategory entities
*
* @author Benjamin La Madrid <bg.lamadrid at gmail.com>
*/
@RestController
@RequestMapping("/data/billing_types")
public class DataBillingTypesController
extends GenericDataController<BillingTypePojo, BillingType> {
@Autowired
public DataBillingTypesController(OperationProperties globals,
GenericJpaService<BillingTypePojo, BillingType> crudService) {
super(globals, crudService);
}
@GetMapping({"", "/"})
public DataPagePojo<BillingTypePojo> readMany(@RequestParam Map<String, String> allRequestParams) {
return super.readMany(null, null, allRequestParams);
}
}
|
92386c38f94a9ec64d06828188ac86131ee9fcb5 | 1,155 | java | Java | src/main/java/kernbeisser/CustomComponents/SearchBox/SearchBoxModel.java | julikiller98/Kernbeisser-Gradle- | 93b7032591adbdbb845351f0420d59eb87721f61 | [
"MIT"
] | 6 | 2020-01-17T22:22:24.000Z | 2021-12-14T21:21:55.000Z | src/main/java/kernbeisser/CustomComponents/SearchBox/SearchBoxModel.java | julikiller98/Kernbeisser-Gradle- | 93b7032591adbdbb845351f0420d59eb87721f61 | [
"MIT"
] | 254 | 2019-11-09T11:52:39.000Z | 2022-03-13T22:55:53.000Z | src/main/java/kernbeisser/CustomComponents/SearchBox/SearchBoxModel.java | julikiller98/Kernbeisser-Gradle- | 93b7032591adbdbb845351f0420d59eb87721f61 | [
"MIT"
] | 4 | 2019-12-14T14:05:41.000Z | 2021-11-18T19:54:20.000Z | 26.860465 | 78 | 0.766234 | 998,415 | package kernbeisser.CustomComponents.SearchBox;
import java.util.ArrayList;
import java.util.Collection;
import kernbeisser.CustomComponents.ObjectTable.Column;
import kernbeisser.Enums.Setting;
import kernbeisser.Windows.MVC.IModel;
import kernbeisser.Windows.Searchable;
public class SearchBoxModel<T> implements IModel<SearchBoxController<T>> {
private final Searchable<T> searchable;
private final Column<T>[] columns;
private T lastSelectedObject = null;
private final ArrayList<Runnable> lostSelectionListener = new ArrayList<>();
SearchBoxModel(Searchable<T> searchable, Column<T>[] columns) {
this.searchable = searchable;
this.columns = columns;
}
Collection<T> getSearchResults(String s) {
return searchable.search(s, Setting.DEFAULT_MAX_SEARCH.getIntValue());
}
public ArrayList<Runnable> getLostSelectionListener() {
return lostSelectionListener;
}
public T getLastSelectedObject() {
return lastSelectedObject;
}
public void setLastSelectedObject(T lastSelectedObject) {
this.lastSelectedObject = lastSelectedObject;
}
public Column<T>[] getColumns() {
return columns;
}
}
|
92386f0920de5524bd946c6c26fb0ed83373eb1b | 3,253 | java | Java | kubernetes-model-generator/kubernetes-model-rbac/src/test/java/io/fabric8/kubernetes/api/model/rbac/RoleBindingTest.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 2,460 | 2015-08-26T08:44:49.000Z | 2022-03-31T09:52:23.000Z | kubernetes-model-generator/kubernetes-model-rbac/src/test/java/io/fabric8/kubernetes/api/model/rbac/RoleBindingTest.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 3,934 | 2015-07-16T14:51:50.000Z | 2022-03-31T20:14:44.000Z | kubernetes-model-generator/kubernetes-model-rbac/src/test/java/io/fabric8/kubernetes/api/model/rbac/RoleBindingTest.java | see-quick/kubernetes-client | 34f37509a37cbc156ed1a458cf7e03ec55d2639b | [
"Apache-2.0"
] | 1,259 | 2015-07-16T14:36:46.000Z | 2022-03-31T09:52:26.000Z | 38.72619 | 113 | 0.664002 | 998,416 | /**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.api.model.rbac;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.rbac.RoleBinding;
import io.fabric8.kubernetes.api.model.rbac.SubjectBuilder;
import io.fabric8.kubernetes.api.model.rbac.RoleRefBuilder;
import io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder;
import io.fabric8.kubernetes.model.util.Helper;
import org.junit.jupiter.api.Test;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS;
import static net.javacrumbs.jsonunit.core.Option.TREATING_NULL_AS_ABSENT;
import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson;
public class RoleBindingTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void kubernetesRoleBindingTest() throws Exception {
// given
final String originalJson = Helper.loadJson("/valid-roleBinding.json");
// when
final RoleBinding kubernetesRoleBinding = mapper.readValue(originalJson, RoleBinding.class);
final String serializedJson = mapper.writeValueAsString(kubernetesRoleBinding);
// then
assertThatJson(serializedJson).when(IGNORING_ARRAY_ORDER, TREATING_NULL_AS_ABSENT, IGNORING_EXTRA_FIELDS)
.isEqualTo(originalJson);
}
@Test
public void kubernetesRoleBuilderTest() throws Exception {
// given
final String originalJson = Helper.loadJson("/valid-roleBinding.json");
// when
RoleBinding kubernetesRoleBinding = new RoleBindingBuilder()
.withNewMetadata()
.withName("read-jobs")
.withNamespace("default")
.endMetadata()
.addToSubjects(0, new SubjectBuilder()
.withApiGroup("rbac.authorization.k8s.io")
.withKind("User")
.withName("jane")
.withNamespace("default")
.build()
)
.withRoleRef(new RoleRefBuilder()
.withApiGroup("rbac.authorization.k8s.io")
.withKind("Role")
.withName("job-reader")
.build()
)
.build();
final String serializedJson = mapper.writeValueAsString(kubernetesRoleBinding);
// then
assertThatJson(serializedJson).when(IGNORING_ARRAY_ORDER, TREATING_NULL_AS_ABSENT, IGNORING_EXTRA_FIELDS)
.isEqualTo(originalJson);
}
}
|
92386f12f40601a8e4fe66939cb0fade6cfa371f | 722 | java | Java | frontend/UpnBank/app/src/main/java/com/apps/carlos/upnbank/Model/TipoOperacion.java | CarlosDevlp/banca-movil-plataforma | 7ef91f168e29be13b15187151b760d051afb5258 | [
"MIT"
] | null | null | null | frontend/UpnBank/app/src/main/java/com/apps/carlos/upnbank/Model/TipoOperacion.java | CarlosDevlp/banca-movil-plataforma | 7ef91f168e29be13b15187151b760d051afb5258 | [
"MIT"
] | null | null | null | frontend/UpnBank/app/src/main/java/com/apps/carlos/upnbank/Model/TipoOperacion.java | CarlosDevlp/banca-movil-plataforma | 7ef91f168e29be13b15187151b760d051afb5258 | [
"MIT"
] | null | null | null | 18.05 | 52 | 0.648199 | 998,417 | package com.apps.carlos.upnbank.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Carlos on 30/06/2017.
*/
public class TipoOperacion {
@SerializedName("idTipoOperacion")
@Expose
private int mId;
@SerializedName("descripcion")
@Expose
private String mDescripcion;
//constructor
public TipoOperacion() {
}
//setters and getters
public int getId() {
return mId;
}
public void setId(int id) {
mId = id;
}
public String getDescripcion() {
return mDescripcion;
}
public void setDescripcion(String descripcion) {
mDescripcion = descripcion;
}
}
|
92386f468c2155daabfac820783343d4ff0682f5 | 3,530 | java | Java | ef-sdk-java/src/main/java/mx/emite/sdk/enums/sat/TiposDeduccion.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | ef-sdk-java/src/main/java/mx/emite/sdk/enums/sat/TiposDeduccion.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | ef-sdk-java/src/main/java/mx/emite/sdk/enums/sat/TiposDeduccion.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | 28.467742 | 159 | 0.743909 | 998,418 | package mx.emite.sdk.enums.sat;
import org.apache.commons.lang3.StringUtils;
import org.beanio.types.TypeConversionException;
import lombok.Getter;
import mx.emite.sdk.errores.ApiException;
import mx.emite.sdk.errores.I_Api_Errores;
import mx.emite.sdk.utils.Utilerias;
@Getter
public enum TiposDeduccion implements Sat<String>{
IMSS("001","Seguridad social"),
ISR("002","ISR"),
APORTACIONESARETIROCESANTIAYVEJEZ("003","Aportaciones a retiro, cesantía en edad avanzada y vejez."),
OTROS("004","Otros"),
APORTACIONESAFONDODEVIVIENDA("005","Aportaciones a Fondo de vivienda"),
DESCUENTOPORINCAPACIDAD("006","Descuento por incapacidad"),
PENSIONALIMENTICIA("007","Pensión alimenticia"),
RENTA("008","Renta"),
PRESTAMOSINFONAVIT("009","Préstamos provenientes del Fondo Nacional de la Vivienda para los Trabajadores"),
PAGOPORCREDITODEVIVIENDA("010","Pago por crédito de vivienda"),
PAGODEABONOSINFONACOT("011","Pago de abonos INFONACOT"),
ANTICIPODESALARIOS("012","Anticipo de salarios"),
PAGOSHECHOSCONEXCESOALTRABAJADOR("013","Pagos hechos con exceso al trabajador"),
ERRORES("014","Errores"),
PERDIDAS("015","Pérdidas"),
AVERIAS("016","Averías"),
ADQUISICIONDEARTICULOSPRODUCIDOSPORLAEMPRESA("017","Adquisición de artículos producidos por la empresa o establecimiento"),
CUOTASDECAJASDEAHORRO("018","Cuotas para la constitución y fomento de sociedades cooperativas y de cajas de ahorro"),
CUOTASSINDICALES("019","Cuotas sindicales"),
AUSENCIA("020","Ausencia (Ausentismo)"),
CUOTASOBREROPATRONALES("021","Cuotas obrero patronales"),
IMPUESTOSLOCALES("022","Impuestos Locales"),
APORTACIONESVOLUNTARIAS("023","Aportaciones voluntarias"),
;
final String idSat;
final String descripcion;
final String[] sinonimos;
TiposDeduccion(String idSat,String descripcion){
this(idSat,descripcion,null);
}
TiposDeduccion(String idSat,String descripcion,String[] sinonimos){
this.idSat=idSat;
this.descripcion=descripcion;
this.sinonimos=sinonimos;
}
public static TiposDeduccion busca(String metodo) {
if(StringUtils.isEmpty(metodo))
return null;
for(TiposDeduccion m:values()){
if(Utilerias.compara(m.descripcion,metodo))
return m;
else if(Utilerias.compara(m.idSat.toString(),metodo))
return m;
else if(m.sinonimos!=null){
for(String s:m.sinonimos){
if(Utilerias.compara(s,metodo))
return m;
}
}
}
return null;
}
public static TiposDeduccion unmarshall(String metodo) throws ApiException{
if(StringUtils.isEmpty(metodo))
return null;
final TiposDeduccion estado = TiposDeduccion.busca(metodo);
if(estado==null)
throw new ApiException(I_Api_Errores.CLIENTE_XML_INVALIDO,"El tipo de deducción "+metodo+" no se encuentra en el catálogo de Tipos de Deducciones del SAT");
else
return estado;
}
public static String marshall(TiposDeduccion v) throws Exception {
if(v==null)
return null;
return v.getIdSat();
}
public static Object parse(String text) throws TypeConversionException, ApiException {
return unmarshall(text);
}
public boolean in(TiposDeduccion... tipos){
for(TiposDeduccion t:tipos){
if(this.equals(t)){
return true;
}
}
return false;
}
public boolean notin(TiposDeduccion... tipos){
return !in(tipos);
}
public String getClave() {
return idSat;
}
public String getConcepto() {
return descripcion;
}
public boolean esIsr(){
return this.equals(ISR);
}
public boolean esIncapacidad() {
return this.equals(DESCUENTOPORINCAPACIDAD);
}
}
|
92386f8184a91d0ec70c1487aa1289077631ba60 | 8,963 | java | Java | app/src/main/java/com/example/lsgo14/coolweather/WeatherActivity.java | DavidZXY/coolweather | a8faf7dffea1ce4f804384d6c702928efbca7f6c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/lsgo14/coolweather/WeatherActivity.java | DavidZXY/coolweather | a8faf7dffea1ce4f804384d6c702928efbca7f6c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/lsgo14/coolweather/WeatherActivity.java | DavidZXY/coolweather | a8faf7dffea1ce4f804384d6c702928efbca7f6c | [
"Apache-2.0"
] | null | null | null | 34.209924 | 137 | 0.637733 | 998,419 | package com.example.lsgo14.coolweather;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.lsgo14.coolweather.gson.Forecast;
import com.example.lsgo14.coolweather.gson.Weather;
import com.example.lsgo14.coolweather.service.AutoUpdateService;
import com.example.lsgo14.coolweather.util.HttpUtil;
import com.example.lsgo14.coolweather.util.Utility;
import org.w3c.dom.Text;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
public DrawerLayout mDrawerLayout;
private Button mNavButton;
public SwipeRefreshLayout mSwipeRefresh;
private ScrollView mWeatherLayout;
private TextView mTitleCity;
private TextView mTitleUpdateTime;
private TextView mDegreeText;
private TextView mWeatherInfoText;
private LinearLayout mForecastLayout;
private TextView mAqiText;
private TextView mPM25Text;
private TextView mComfortText;
private TextView mCarWashText;
private TextView mSportText;
private ImageView mBingPicImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
mBingPicImg = findViewById(R.id.bing_pic_img);
mWeatherLayout = findViewById(R.id.weather_layout);
mTitleCity = findViewById(R.id.title_city);
mTitleUpdateTime = findViewById(R.id.title_update_time);
mDegreeText = findViewById(R.id.degree_text);
mWeatherInfoText = findViewById(R.id.weather_info_text);
mForecastLayout = findViewById(R.id.forecast_layout);
mAqiText = findViewById(R.id.aqi_text);
mPM25Text = findViewById(R.id.pm25_text);
mComfortText = findViewById(R.id.comfort_text);
mCarWashText = findViewById(R.id.car_wash_text);
mSportText = findViewById(R.id.sport_text);
mSwipeRefresh = findViewById(R.id.swipe_refresh);
mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary);
mDrawerLayout = findViewById(R.id.drawer_layout);
mNavButton = findViewById(R.id.nav_button);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
final String weatherId;
if (weatherString != null) {
Weather weather = Utility.handleWeatherResponse(weatherString);
weatherId = weather.mBasic.mWeatherId;
showWeatherInfo(weather);
} else {
weatherId = getIntent().getStringExtra("weather_id");
mWeatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(weatherId);
}
});
mNavButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null) {
Glide.with(this).load(bingPic).into(mBingPicImg);
} else {
loadBingPic();
}
}
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=d55480611c5640eeadd4dfe0e9a84f99";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.mStatus)) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
mSwipeRefresh.setRefreshing(false);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
mSwipeRefresh.setRefreshing(false);
}
});
}
});
loadBingPic();
}
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(mBingPicImg);
}
});
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
}
private void showWeatherInfo(Weather weather) {
String cityName = weather.mBasic.mCityName;
String updateTime = weather.mBasic.mUpdate.mUpdateTime.split(" ")[1];
String degree = weather.mNow.mTemperature + "℃";
String weatherInfo = weather.mNow.mMore.mInfo;
mTitleCity.setText(cityName);
mTitleUpdateTime.setText(updateTime);
mDegreeText.setText(degree);
mWeatherInfoText.setText(weatherInfo);
mForecastLayout.removeAllViews();
for (Forecast forecast : weather.mForecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, mForecastLayout, false);
TextView dateText = view.findViewById(R.id.date_text);
TextView infoText = view.findViewById(R.id.info_text);
TextView maxText = view.findViewById(R.id.max_text);
TextView minText = view.findViewById(R.id.min_text);
dateText.setText(forecast.mDate);
infoText.setText(forecast.mMore.mInfo);
maxText.setText(forecast.mTemperature.mMax);
minText.setText(forecast.mTemperature.mMin);
mForecastLayout.addView(view);
}
if (weather.mAQI != null) {
mAqiText.setText(weather.mAQI.mCity.aqi);
mPM25Text.setText(weather.mAQI.mCity.pm25);
}
String comfort = "舒适度:" + weather.mSuggestion.mComfort.mInfo;
String carWash = "洗车指数" + weather.mSuggestion.mCarWash.mInfo;
String sport = "运动建议" + weather.mSuggestion.mSport.mInfo;
mComfortText.setText(comfort);
mCarWashText.setText(carWash);
mSportText.setText(sport);
mWeatherLayout.setVisibility(View.VISIBLE);
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
}
}
|
92386f8f6c3885ec5489e54ccc1fb42996c4a3cb | 4,369 | java | Java | src/main/java/net/minecraft/tileentity/TileEntityEnderChest.java | Akarin-project/Paper2Srg | 55798e89ed822e8d59dc55dfc6aa70cef1e47751 | [
"MIT"
] | 3 | 2018-06-22T14:09:27.000Z | 2021-09-15T02:27:45.000Z | src/main/java/net/minecraft/tileentity/TileEntityEnderChest.java | Akarin-project/AkarinModEdition | 55798e89ed822e8d59dc55dfc6aa70cef1e47751 | [
"MIT"
] | null | null | null | src/main/java/net/minecraft/tileentity/TileEntityEnderChest.java | Akarin-project/AkarinModEdition | 55798e89ed822e8d59dc55dfc6aa70cef1e47751 | [
"MIT"
] | 4 | 2018-06-21T09:44:06.000Z | 2021-09-15T02:27:50.000Z | 36.408333 | 281 | 0.586404 | 998,420 | package net.minecraft.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.SoundCategory;
public class TileEntityEnderChest extends TileEntity { // Paper - Remove ITickable
public float field_145972_a; // Paper - lid angle
public float field_145975_i;
public int field_145973_j; // Paper - Number of viewers
private int field_145974_k;
public TileEntityEnderChest() {}
public void func_73660_a() {
// Paper start - Disable all of this, just in case this does get ticked
/*
if (++this.h % 20 * 4 == 0) {
this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.g);
}
this.f = this.a;
int i = this.position.getX();
int j = this.position.getY();
int k = this.position.getZ();
float f = 0.1F;
double d0;
if (this.g > 0 && this.a == 0.0F) {
double d1 = (double) i + 0.5D;
d0 = (double) k + 0.5D;
this.world.a((EntityHuman) null, d1, (double) j + 0.5D, d0, SoundEffects.aT, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F);
}
if (this.g == 0 && this.a > 0.0F || this.g > 0 && this.a < 1.0F) {
float f1 = this.a;
if (this.g > 0) {
this.a += 0.1F;
} else {
this.a -= 0.1F;
}
if (this.a > 1.0F) {
this.a = 1.0F;
}
float f2 = 0.5F;
if (this.a < 0.5F && f1 >= 0.5F) {
d0 = (double) i + 0.5D;
double d2 = (double) k + 0.5D;
this.world.a((EntityHuman) null, d0, (double) j + 0.5D, d2, SoundEffects.aS, SoundCategory.BLOCKS, 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F);
}
if (this.a < 0.0F) {
this.a = 0.0F;
}
}
*/
// Paper end
}
public boolean func_145842_c(int i, int j) {
if (i == 1) {
this.field_145973_j = j;
return true;
} else {
return super.func_145842_c(i, j);
}
}
public void func_145843_s() {
this.func_145836_u();
super.func_145843_s();
}
public void func_145969_a() {
++this.field_145973_j;
// Paper start - Move enderchest open sounds out of the tick loop
if (this.field_145973_j > 0 && this.field_145972_a == 0.0F) {
this.field_145972_a = 0.7F;
double d1 = (double) this.func_174877_v().func_177958_n() + 0.5D;
double d0 = (double) this.func_174877_v().func_177952_p() + 0.5D;
this.field_145850_b.func_184148_a((EntityPlayer) null, d1, (double) this.func_174877_v().func_177956_o() + 0.5D, d0, SoundEvents.field_187520_aJ, SoundCategory.BLOCKS, 0.5F, this.field_145850_b.field_73012_v.nextFloat() * 0.1F + 0.9F);
}
// Paper end
this.field_145850_b.func_175641_c(this.field_174879_c, Blocks.field_150477_bB, 1, this.field_145973_j);
}
public void func_145970_b() {
--this.field_145973_j;
// Paper start - Move enderchest close sounds out of the tick loop
if (this.field_145973_j == 0 && this.field_145972_a > 0.0F || this.field_145973_j > 0 && this.field_145972_a < 1.0F) {
double d0 = (double) this.func_174877_v().func_177958_n() + 0.5D;
double d2 = (double) this.func_174877_v().func_177952_p() + 0.5D;
this.field_145850_b.func_184148_a((EntityPlayer) null, d0, (double) this.func_174877_v().func_177956_o() + 0.5D, d2, SoundEvents.field_187519_aI, SoundCategory.BLOCKS, 0.5F, this.field_145850_b.field_73012_v.nextFloat() * 0.1F + 0.9F);
this.field_145972_a = 0.0F;
}
// Paper end
this.field_145850_b.func_175641_c(this.field_174879_c, Blocks.field_150477_bB, 1, this.field_145973_j);
}
public boolean func_145971_a(EntityPlayer entityhuman) {
return this.field_145850_b.func_175625_s(this.field_174879_c) != this ? false : entityhuman.func_70092_e((double) this.field_174879_c.func_177958_n() + 0.5D, (double) this.field_174879_c.func_177956_o() + 0.5D, (double) this.field_174879_c.func_177952_p() + 0.5D) <= 64.0D;
}
}
|
9238708bcd2c45b83bf2ba2ee8226819169e9f4b | 1,415 | java | Java | src/main/java/com/spring/microservice/web/RatingDto.java | UkrainianCitizen/spring-microservice | 42d6e86d85ce324552f3a0c8e59c4106506382fb | [
"MIT"
] | 2 | 2018-05-30T18:06:58.000Z | 2018-10-20T13:36:22.000Z | src/main/java/com/spring/microservice/web/RatingDto.java | UkrainianCitizen/spring-microservice | 42d6e86d85ce324552f3a0c8e59c4106506382fb | [
"MIT"
] | null | null | null | src/main/java/com/spring/microservice/web/RatingDto.java | UkrainianCitizen/spring-microservice | 42d6e86d85ce324552f3a0c8e59c4106506382fb | [
"MIT"
] | null | null | null | 21.439394 | 65 | 0.65371 | 998,421 | package com.spring.microservice.web;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.hateoas.ResourceSupport;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Data Transfer Object for Rating a Tour.
*/
public class RatingDto extends ResourceSupport {
@Min(0)
@Max(5)
private int score;
@Size(max = 255)
private String comment;
@NotNull
@JsonProperty("customer_id")
private int customerId;
/**
* Constructor to fully initialize the RatingDto
*
* @param score score
* @param comment comment
* @param customerId customer id
*/
public RatingDto(int score, String comment, int customerId) {
this.score = score;
this.comment = comment;
this.customerId = customerId;
}
public RatingDto() {
}
public int getScore() {
return score;
}
public String getComment() {
return comment;
}
public int getCustomerId() {
return customerId;
}
public void setScore(Integer score) {
this.score = score;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
} |
923870e0ae6d46d19e50dc624b9b7ed19d139445 | 5,566 | java | Java | src/com/rosty/maze/controller/MenuBarController.java | MartiniDry/Mazette | b832f6ed5e1bf5e6c79af98f507daee799407aee | [
"MIT"
] | null | null | null | src/com/rosty/maze/controller/MenuBarController.java | MartiniDry/Mazette | b832f6ed5e1bf5e6c79af98f507daee799407aee | [
"MIT"
] | null | null | null | src/com/rosty/maze/controller/MenuBarController.java | MartiniDry/Mazette | b832f6ed5e1bf5e6c79af98f507daee799407aee | [
"MIT"
] | null | null | null | 31.805714 | 114 | 0.783507 | 998,422 | package com.rosty.maze.controller;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import com.rosty.maze.Mazette;
import com.rosty.maze.application.AppLauncher;
import com.rosty.maze.application.labels.LocaleManager;
import com.rosty.maze.dialog.DialogUtility;
import com.rosty.maze.model.algorithm.generation.AldousBroderAlgorithm;
import com.rosty.maze.model.algorithm.generation.BinaryTreeAlgorithm;
import com.rosty.maze.model.algorithm.generation.EllerAlgorithm;
import com.rosty.maze.model.algorithm.generation.GrowingTreeAlgorithm;
import com.rosty.maze.model.algorithm.generation.HuntAndKillAlgorithm;
import com.rosty.maze.model.algorithm.generation.KruskalAlgorithm;
import com.rosty.maze.model.algorithm.generation.Personal2Algorithm;
import com.rosty.maze.model.algorithm.generation.PersonalAlgorithm;
import com.rosty.maze.model.algorithm.generation.PrimAlgorithm;
import com.rosty.maze.model.algorithm.generation.RecursiveBacktrackingAlgorithm;
import com.rosty.maze.model.algorithm.generation.RecursiveDivisionAlgorithm;
import com.rosty.maze.model.algorithm.generation.ShuffledKruskalAlgorithm;
import com.rosty.maze.model.algorithm.generation.SidewinderAlgorithm;
import com.rosty.maze.model.algorithm.generation.WilsonAlgorithm;
import com.rosty.maze.view.box.MessageBox;
import javafx.fxml.FXML;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class MenuBarController {
@FXML
private void saveDataAs() {
Mazette.LOGGER.info("Sauvegarde des données");
}
@FXML
private void exportData() {
Mazette.LOGGER.info("Exportation des données");
FileChooser chooser = new FileChooser();
chooser.setTitle("Enregistrer le labyrinthe sous...");
chooser.getExtensionFilters().addAll(new ExtensionFilter("Images JPEG", "*.jpg *.jpeg"),
new ExtensionFilter("Images PNG", "*.png"), new ExtensionFilter("Images gif", "*.gif"));
chooser.setSelectedExtensionFilter(chooser.getExtensionFilters().get(1));
try {
File file = chooser.showSaveDialog(AppLauncher.getPrimaryStage().getOwner());
AppLauncher.getMainController().mazePanel.save(file);
} catch (IOException e) {
MessageBox box = new MessageBox(AlertType.ERROR, "Sauvegarde de l'image");
box.setContentText(e.getLocalizedMessage());
box.show();
} catch (IllegalArgumentException e) {
MessageBox box = new MessageBox(AlertType.ERROR, "Sauvegarde de l'image");
box.setContentText(e.getLocalizedMessage());
box.show();
}
}
@FXML
private void quitApplication() {
Mazette.shutDown();
}
@FXML
private void generateKruskal() {
AppLauncher.getMainController().regenerate(new KruskalAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateShuffledKruskal() {
AppLauncher.getMainController()
.regenerate(new ShuffledKruskalAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateRecursiveBacktracker() {
AppLauncher.getMainController()
.regenerate(new RecursiveBacktrackingAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateRecursiveDivision() {
AppLauncher.getMainController()
.regenerate(new RecursiveDivisionAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generatePrim() {
AppLauncher.getMainController().regenerate(new PrimAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateHuntAndKill() {
AppLauncher.getMainController().regenerate(new HuntAndKillAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateAldousBroder() {
AppLauncher.getMainController()
.regenerate(new AldousBroderAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateWilson() {
AppLauncher.getMainController().regenerate(new WilsonAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateBinaryTree() {
AppLauncher.getMainController().regenerate(new BinaryTreeAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateSidewinder() {
AppLauncher.getMainController().regenerate(new SidewinderAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateEller() {
AppLauncher.getMainController().regenerate(new EllerAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generatePersonal() {
AppLauncher.getMainController().regenerate(new PersonalAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generatePersonal2() {
AppLauncher.getMainController().regenerate(new Personal2Algorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void generateGrowingTree() {
AppLauncher.getMainController().regenerate(new GrowingTreeAlgorithm(AppLauncher.getMainController().mazePanel));
}
@FXML
private void changeColors() {
;
}
@FXML
private void preferences() {
;
}
@FXML
private void switchToFrench() {
LocaleManager.set(Locale.FRENCH);
AppLauncher.reloadView();
}
@FXML
private void switchToEnglish() {
LocaleManager.set(Locale.ENGLISH);
AppLauncher.reloadView();
}
@FXML
private void about() {
try {
DialogUtility.openAboutDialog();
} catch (IOException e) {
Mazette.LOGGER.error(e.getMessage(), e);
MessageBox box = new MessageBox(AlertType.ERROR, "A propos du logiciel");
box.setContentText("L'ouverture de la fenêtre a échoué ; veuillez recommencer.");
box.showAndWait();
}
}
} |
9238715fb10ebbae29bb293ed2453cd427da6d6d | 1,057 | java | Java | xcmailr-webapp/src/main/java/controllers/restapi/util/AbstractApiController.java | Xceptance/XCMailr | f8e4f2d831a693e8ac170479ab991de422da221f | [
"Apache-2.0"
] | 8 | 2016-04-21T23:00:39.000Z | 2020-12-04T13:55:00.000Z | xcmailr-webapp/src/main/java/controllers/restapi/util/AbstractApiController.java | Xceptance/XCMailr | f8e4f2d831a693e8ac170479ab991de422da221f | [
"Apache-2.0"
] | 60 | 2015-03-06T16:48:44.000Z | 2022-01-21T23:17:15.000Z | xcmailr-webapp/src/main/java/controllers/restapi/util/AbstractApiController.java | Xceptance/XCMailr | f8e4f2d831a693e8ac170479ab991de422da221f | [
"Apache-2.0"
] | 9 | 2015-10-08T12:50:39.000Z | 2019-06-07T08:16:38.000Z | 29.361111 | 83 | 0.733207 | 998,423 | /*
* Copyright 2020 by 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 controllers.restapi.util;
import com.google.inject.Singleton;
import filters.AcceptJsonFilter;
import filters.ApiTokenFilter;
import ninja.FilterWith;
/**
* Base class of all REST API controllers.
*/
@Singleton
@FilterWith(
{
ApiTokenFilter.class, // checks the API token
AcceptJsonFilter.class // checks that JSON is sent and accepted by the client
})
public class AbstractApiController
{
}
|
9238717e054ee1f0976bcb24221ac818aef12166 | 9,312 | java | Java | plugins/android-extensions/android-extensions-compiler/test/org/jetbrains/kotlin/android/synthetic/test/AndroidBytecodeShapeTestGenerated.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 45,293 | 2015-01-01T06:23:46.000Z | 2022-03-31T21:55:51.000Z | plugins/android-extensions/android-extensions-compiler/test/org/jetbrains/kotlin/android/synthetic/test/AndroidBytecodeShapeTestGenerated.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 3,386 | 2015-01-12T13:28:50.000Z | 2022-03-31T17:48:15.000Z | plugins/android-extensions/android-extensions-compiler/test/org/jetbrains/kotlin/android/synthetic/test/AndroidBytecodeShapeTestGenerated.java | Dimat112/kotlin | 0c463d3260bb78afd8da308849e430162aab6cd9 | [
"ECL-2.0",
"Apache-2.0"
] | 6,351 | 2015-01-03T12:30:09.000Z | 2022-03-31T20:46:54.000Z | 47.269036 | 224 | 0.776954 | 998,424 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.android.synthetic.test;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class AndroidBytecodeShapeTestGenerated extends AbstractAndroidBytecodeShapeTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
@TestMetadata("activityWithEntityOptionsNoCache")
public void testActivityWithEntityOptionsNoCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/activityWithEntityOptionsNoCache/");
}
public void testAllFilesPresentInBytecodeShape() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape"), Pattern.compile("^([^\\.]+)$"), null, false);
}
@TestMetadata("baseClass")
public void testBaseClass() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/baseClass/");
}
@TestMetadata("baseClassFragment")
public void testBaseClassFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/baseClassFragment/");
}
@TestMetadata("clearCache")
public void testClearCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/clearCache/");
}
@TestMetadata("clearCacheBaseClass")
public void testClearCacheBaseClass() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/clearCacheBaseClass/");
}
@TestMetadata("dialog")
public void testDialog() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/dialog/");
}
@TestMetadata("extensionFunctions")
public void testExtensionFunctions() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/extensionFunctions/");
}
@TestMetadata("extensionFunctionsFragment")
public void testExtensionFunctionsFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/extensionFunctionsFragment/");
}
@TestMetadata("extensionFunctionsView")
public void testExtensionFunctionsView() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/extensionFunctionsView/");
}
@TestMetadata("fqNameInAttr")
public void testFqNameInAttr() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/fqNameInAttr/");
}
@TestMetadata("fqNameInAttrFragment")
public void testFqNameInAttrFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/fqNameInAttrFragment/");
}
@TestMetadata("fqNameInTag")
public void testFqNameInTag() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/fqNameInTag/");
}
@TestMetadata("fqNameInTagFragment")
public void testFqNameInTagFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/fqNameInTagFragment/");
}
@TestMetadata("fragmentWithEntityOptionsNoCache")
public void testFragmentWithEntityOptionsNoCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/fragmentWithEntityOptionsNoCache/");
}
@TestMetadata("kt18545")
public void testKt18545() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/kt18545/");
}
@TestMetadata("multiFile")
public void testMultiFile() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/multiFile/");
}
@TestMetadata("multiFileFragment")
public void testMultiFileFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/multiFileFragment/");
}
@TestMetadata("onDestroyFragment")
public void testOnDestroyFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/onDestroyFragment/");
}
@TestMetadata("simple")
public void testSimple() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/simple/");
}
@TestMetadata("simpleFragment")
public void testSimpleFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/simpleFragment/");
}
@TestMetadata("simpleFragmentProperty")
public void testSimpleFragmentProperty() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/simpleFragmentProperty/");
}
@TestMetadata("simpleHashMapCacheImplementation")
public void testSimpleHashMapCacheImplementation() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/simpleHashMapCacheImplementation/");
}
@TestMetadata("simpleView")
public void testSimpleView() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/simpleView/");
}
@TestMetadata("supportExtensionFunctionsFragment")
public void testSupportExtensionFunctionsFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportExtensionFunctionsFragment/");
}
@TestMetadata("supportExtensionFunctionsFragmentAndroidx")
public void testSupportExtensionFunctionsFragmentAndroidx() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportExtensionFunctionsFragmentAndroidx/");
}
@TestMetadata("supportSimpleFragment")
public void testSupportSimpleFragment() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportSimpleFragment/");
}
@TestMetadata("supportSimpleFragmentAndroidx")
public void testSupportSimpleFragmentAndroidx() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportSimpleFragmentAndroidx/");
}
@TestMetadata("supportSimpleFragmentProperty")
public void testSupportSimpleFragmentProperty() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportSimpleFragmentProperty/");
}
@TestMetadata("supportSimpleFragmentPropertyAndroidx")
public void testSupportSimpleFragmentPropertyAndroidx() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/supportSimpleFragmentPropertyAndroidx/");
}
@TestMetadata("viewStub")
public void testViewStub() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/viewStub/");
}
@TestMetadata("viewWithCache")
public void testViewWithCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/viewWithCache/");
}
@TestMetadata("viewWithDefaultNoCache")
public void testViewWithDefaultNoCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/viewWithDefaultNoCache/");
}
@TestMetadata("viewWithEntityOptionsNoCache")
public void testViewWithEntityOptionsNoCache() throws Exception {
runTest("plugins/android-extensions/android-extensions-compiler/testData/codegen/bytecodeShape/viewWithEntityOptionsNoCache/");
}
}
|
923871e9a55a1cf02bd4f2b69e75b2bb2ea2166b | 784 | java | Java | app/src/main/java/com/allever/lose/weight/ui/adapter/LanguageAdapter.java | Peter-w9/LoseWeight | 02a63fb26952bc017b91cdeb9f9c4a192ff9bad1 | [
"Apache-2.0"
] | 12 | 2020-02-26T12:07:00.000Z | 2021-12-22T14:03:11.000Z | app/src/main/java/com/allever/lose/weight/ui/adapter/LanguageAdapter.java | Peter-w9/LoseWeight | 02a63fb26952bc017b91cdeb9f9c4a192ff9bad1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/allever/lose/weight/ui/adapter/LanguageAdapter.java | Peter-w9/LoseWeight | 02a63fb26952bc017b91cdeb9f9c4a192ff9bad1 | [
"Apache-2.0"
] | 7 | 2020-04-05T16:15:39.000Z | 2022-03-22T08:17:45.000Z | 26.133333 | 85 | 0.725765 | 998,425 | package com.allever.lose.weight.ui.adapter;
import android.content.Context;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.allever.lose.weight.R;
import com.allever.lose.weight.bean.LanguageItem;
import java.util.List;
/**
* Created by Mac on 18/3/14.
*/
public class LanguageAdapter extends BaseQuickAdapter<LanguageItem, BaseViewHolder> {
public LanguageAdapter(Context context, List<LanguageItem> languageItems) {
super(R.layout.item_language, languageItems);
}
@Override
protected void convert(BaseViewHolder holder, LanguageItem item) {
if (item == null) {
return;
}
holder.setText(R.id.id_item_language_tv_name, item.getName());
}
}
|
9238720d3e035f33d41f08871a3f0b623148cdf2 | 18,476 | java | Java | third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/proto/Client.java | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/proto/Client.java | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/proto/Client.java | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | 38.173554 | 168 | 0.695334 | 998,426 | /*
* Copyright 2011 Google 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.
*/
// Generated by j/c/g/ipc/invalidation/common/proto_wrapper_generator
package com.google.ipc.invalidation.ticl.proto;
import com.google.ipc.invalidation.util.Bytes;
import com.google.ipc.invalidation.util.ProtoWrapper;
import com.google.ipc.invalidation.util.ProtoWrapper.ValidationException;
import com.google.ipc.invalidation.util.TextBuilder;
import com.google.protobuf.nano.MessageNano;
import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public interface Client {
public static final class AckHandleP extends ProtoWrapper {
public static AckHandleP create(com.google.ipc.invalidation.ticl.proto.ClientProtocol.InvalidationP invalidation) {
return new AckHandleP(invalidation);
}
public static final AckHandleP DEFAULT_INSTANCE = new AckHandleP(null);
private final com.google.ipc.invalidation.ticl.proto.ClientProtocol.InvalidationP invalidation;
private AckHandleP(com.google.ipc.invalidation.ticl.proto.ClientProtocol.InvalidationP invalidation) {
this.invalidation = invalidation;
}
public com.google.ipc.invalidation.ticl.proto.ClientProtocol.InvalidationP getNullableInvalidation() { return invalidation; }
@Override public final boolean equals(Object obj) {
if (this == obj) { return true; }
if (!(obj instanceof AckHandleP)) { return false; }
AckHandleP other = (AckHandleP) obj;
return equals(invalidation, other.invalidation);
}
@Override protected int computeHashCode() {
int result = 1;
if (invalidation != null) {
result = result * 31 + invalidation.hashCode();
}
return result;
}
@Override public void toCompactString(TextBuilder builder) {
builder.append("<AckHandleP:");
if (invalidation != null) {
builder.append(" invalidation=").append(invalidation);
}
builder.append('>');
}
public static AckHandleP parseFrom(byte[] data) throws ValidationException {
try {
return fromMessageNano(MessageNano.mergeFrom(new com.google.protos.ipc.invalidation.nano.NanoClient.AckHandleP(), data));
} catch (InvalidProtocolBufferNanoException exception) {
throw new ValidationException(exception);
} catch (ValidationArgumentException exception) {
throw new ValidationException(exception.getMessage());
}
}
static AckHandleP fromMessageNano(com.google.protos.ipc.invalidation.nano.NanoClient.AckHandleP message) {
if (message == null) { return null; }
return new AckHandleP(com.google.ipc.invalidation.ticl.proto.ClientProtocol.InvalidationP.fromMessageNano(message.invalidation));
}
public byte[] toByteArray() {
return MessageNano.toByteArray(toMessageNano());
}
com.google.protos.ipc.invalidation.nano.NanoClient.AckHandleP toMessageNano() {
com.google.protos.ipc.invalidation.nano.NanoClient.AckHandleP msg = new com.google.protos.ipc.invalidation.nano.NanoClient.AckHandleP();
msg.invalidation = this.invalidation != null ? invalidation.toMessageNano() : null;
return msg;
}
}
public static final class PersistentTiclState extends ProtoWrapper {
public static final class Builder {
public Bytes clientToken;
public Long lastMessageSendTimeMs;
public Builder() {
}
public PersistentTiclState build() {
return new PersistentTiclState(clientToken, lastMessageSendTimeMs);
}
}
public static PersistentTiclState create(Bytes clientToken,
Long lastMessageSendTimeMs) {
return new PersistentTiclState(clientToken, lastMessageSendTimeMs);
}
public static final PersistentTiclState DEFAULT_INSTANCE = new PersistentTiclState(null, null);
private final long __hazzerBits;
private final Bytes clientToken;
private final long lastMessageSendTimeMs;
private PersistentTiclState(Bytes clientToken,
Long lastMessageSendTimeMs) {
int hazzerBits = 0;
if (clientToken != null) {
hazzerBits |= 0x1;
this.clientToken = clientToken;
} else {
this.clientToken = Bytes.EMPTY_BYTES;
}
if (lastMessageSendTimeMs != null) {
hazzerBits |= 0x2;
this.lastMessageSendTimeMs = lastMessageSendTimeMs;
} else {
this.lastMessageSendTimeMs = 0;
}
this.__hazzerBits = hazzerBits;
}
public Bytes getClientToken() { return clientToken; }
public boolean hasClientToken() { return (0x1 & __hazzerBits) != 0; }
public long getLastMessageSendTimeMs() { return lastMessageSendTimeMs; }
public boolean hasLastMessageSendTimeMs() { return (0x2 & __hazzerBits) != 0; }
public Builder toBuilder() {
Builder builder = new Builder();
if (hasClientToken()) {
builder.clientToken = clientToken;
}
if (hasLastMessageSendTimeMs()) {
builder.lastMessageSendTimeMs = lastMessageSendTimeMs;
}
return builder;
}
@Override public final boolean equals(Object obj) {
if (this == obj) { return true; }
if (!(obj instanceof PersistentTiclState)) { return false; }
PersistentTiclState other = (PersistentTiclState) obj;
return __hazzerBits == other.__hazzerBits
&& (!hasClientToken() || equals(clientToken, other.clientToken))
&& (!hasLastMessageSendTimeMs() || lastMessageSendTimeMs == other.lastMessageSendTimeMs);
}
@Override protected int computeHashCode() {
int result = hash(__hazzerBits);
if (hasClientToken()) {
result = result * 31 + clientToken.hashCode();
}
if (hasLastMessageSendTimeMs()) {
result = result * 31 + hash(lastMessageSendTimeMs);
}
return result;
}
@Override public void toCompactString(TextBuilder builder) {
builder.append("<PersistentTiclState:");
if (hasClientToken()) {
builder.append(" client_token=").append(clientToken);
}
if (hasLastMessageSendTimeMs()) {
builder.append(" last_message_send_time_ms=").append(lastMessageSendTimeMs);
}
builder.append('>');
}
public static PersistentTiclState parseFrom(byte[] data) throws ValidationException {
try {
return fromMessageNano(MessageNano.mergeFrom(new com.google.protos.ipc.invalidation.nano.NanoClient.PersistentTiclState(), data));
} catch (InvalidProtocolBufferNanoException exception) {
throw new ValidationException(exception);
} catch (ValidationArgumentException exception) {
throw new ValidationException(exception.getMessage());
}
}
static PersistentTiclState fromMessageNano(com.google.protos.ipc.invalidation.nano.NanoClient.PersistentTiclState message) {
if (message == null) { return null; }
return new PersistentTiclState(Bytes.fromByteArray(message.clientToken),
message.lastMessageSendTimeMs);
}
public byte[] toByteArray() {
return MessageNano.toByteArray(toMessageNano());
}
com.google.protos.ipc.invalidation.nano.NanoClient.PersistentTiclState toMessageNano() {
com.google.protos.ipc.invalidation.nano.NanoClient.PersistentTiclState msg = new com.google.protos.ipc.invalidation.nano.NanoClient.PersistentTiclState();
msg.clientToken = hasClientToken() ? clientToken.getByteArray() : null;
msg.lastMessageSendTimeMs = hasLastMessageSendTimeMs() ? lastMessageSendTimeMs : null;
return msg;
}
}
public static final class PersistentStateBlob extends ProtoWrapper {
public static PersistentStateBlob create(com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState ticlState,
Bytes authenticationCode) {
return new PersistentStateBlob(ticlState, authenticationCode);
}
public static final PersistentStateBlob DEFAULT_INSTANCE = new PersistentStateBlob(null, null);
private final long __hazzerBits;
private final com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState ticlState;
private final Bytes authenticationCode;
private PersistentStateBlob(com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState ticlState,
Bytes authenticationCode) {
int hazzerBits = 0;
if (ticlState != null) {
hazzerBits |= 0x1;
this.ticlState = ticlState;
} else {
this.ticlState = com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState.DEFAULT_INSTANCE;
}
if (authenticationCode != null) {
hazzerBits |= 0x2;
this.authenticationCode = authenticationCode;
} else {
this.authenticationCode = Bytes.EMPTY_BYTES;
}
this.__hazzerBits = hazzerBits;
}
public com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState getTiclState() { return ticlState; }
public boolean hasTiclState() { return (0x1 & __hazzerBits) != 0; }
public Bytes getAuthenticationCode() { return authenticationCode; }
public boolean hasAuthenticationCode() { return (0x2 & __hazzerBits) != 0; }
@Override public final boolean equals(Object obj) {
if (this == obj) { return true; }
if (!(obj instanceof PersistentStateBlob)) { return false; }
PersistentStateBlob other = (PersistentStateBlob) obj;
return __hazzerBits == other.__hazzerBits
&& (!hasTiclState() || equals(ticlState, other.ticlState))
&& (!hasAuthenticationCode() || equals(authenticationCode, other.authenticationCode));
}
@Override protected int computeHashCode() {
int result = hash(__hazzerBits);
if (hasTiclState()) {
result = result * 31 + ticlState.hashCode();
}
if (hasAuthenticationCode()) {
result = result * 31 + authenticationCode.hashCode();
}
return result;
}
@Override public void toCompactString(TextBuilder builder) {
builder.append("<PersistentStateBlob:");
if (hasTiclState()) {
builder.append(" ticl_state=").append(ticlState);
}
if (hasAuthenticationCode()) {
builder.append(" authentication_code=").append(authenticationCode);
}
builder.append('>');
}
public static PersistentStateBlob parseFrom(byte[] data) throws ValidationException {
try {
return fromMessageNano(MessageNano.mergeFrom(new com.google.protos.ipc.invalidation.nano.NanoClient.PersistentStateBlob(), data));
} catch (InvalidProtocolBufferNanoException exception) {
throw new ValidationException(exception);
} catch (ValidationArgumentException exception) {
throw new ValidationException(exception.getMessage());
}
}
static PersistentStateBlob fromMessageNano(com.google.protos.ipc.invalidation.nano.NanoClient.PersistentStateBlob message) {
if (message == null) { return null; }
return new PersistentStateBlob(com.google.ipc.invalidation.ticl.proto.Client.PersistentTiclState.fromMessageNano(message.ticlState),
Bytes.fromByteArray(message.authenticationCode));
}
public byte[] toByteArray() {
return MessageNano.toByteArray(toMessageNano());
}
com.google.protos.ipc.invalidation.nano.NanoClient.PersistentStateBlob toMessageNano() {
com.google.protos.ipc.invalidation.nano.NanoClient.PersistentStateBlob msg = new com.google.protos.ipc.invalidation.nano.NanoClient.PersistentStateBlob();
msg.ticlState = hasTiclState() ? ticlState.toMessageNano() : null;
msg.authenticationCode = hasAuthenticationCode() ? authenticationCode.getByteArray() : null;
return msg;
}
}
public static final class RunStateP extends ProtoWrapper {
public interface State {
public static final int NOT_STARTED = 1;
public static final int STARTED = 2;
public static final int STOPPED = 3;
}
public static RunStateP create(Integer state) {
return new RunStateP(state);
}
public static final RunStateP DEFAULT_INSTANCE = new RunStateP(null);
private final long __hazzerBits;
private final int state;
private RunStateP(Integer state) {
int hazzerBits = 0;
if (state != null) {
hazzerBits |= 0x1;
this.state = state;
} else {
this.state = 1;
}
this.__hazzerBits = hazzerBits;
}
public int getState() { return state; }
public boolean hasState() { return (0x1 & __hazzerBits) != 0; }
@Override public final boolean equals(Object obj) {
if (this == obj) { return true; }
if (!(obj instanceof RunStateP)) { return false; }
RunStateP other = (RunStateP) obj;
return __hazzerBits == other.__hazzerBits
&& (!hasState() || state == other.state);
}
@Override protected int computeHashCode() {
int result = hash(__hazzerBits);
if (hasState()) {
result = result * 31 + hash(state);
}
return result;
}
@Override public void toCompactString(TextBuilder builder) {
builder.append("<RunStateP:");
if (hasState()) {
builder.append(" state=").append(state);
}
builder.append('>');
}
public static RunStateP parseFrom(byte[] data) throws ValidationException {
try {
return fromMessageNano(MessageNano.mergeFrom(new com.google.protos.ipc.invalidation.nano.NanoClient.RunStateP(), data));
} catch (InvalidProtocolBufferNanoException exception) {
throw new ValidationException(exception);
} catch (ValidationArgumentException exception) {
throw new ValidationException(exception.getMessage());
}
}
static RunStateP fromMessageNano(com.google.protos.ipc.invalidation.nano.NanoClient.RunStateP message) {
if (message == null) { return null; }
return new RunStateP(message.state);
}
public byte[] toByteArray() {
return MessageNano.toByteArray(toMessageNano());
}
com.google.protos.ipc.invalidation.nano.NanoClient.RunStateP toMessageNano() {
com.google.protos.ipc.invalidation.nano.NanoClient.RunStateP msg = new com.google.protos.ipc.invalidation.nano.NanoClient.RunStateP();
msg.state = hasState() ? state : null;
return msg;
}
}
public static final class ExponentialBackoffState extends ProtoWrapper {
public static ExponentialBackoffState create(Integer currentMaxDelay,
Boolean inRetryMode) {
return new ExponentialBackoffState(currentMaxDelay, inRetryMode);
}
public static final ExponentialBackoffState DEFAULT_INSTANCE = new ExponentialBackoffState(null, null);
private final long __hazzerBits;
private final int currentMaxDelay;
private final boolean inRetryMode;
private ExponentialBackoffState(Integer currentMaxDelay,
Boolean inRetryMode) {
int hazzerBits = 0;
if (currentMaxDelay != null) {
hazzerBits |= 0x1;
this.currentMaxDelay = currentMaxDelay;
} else {
this.currentMaxDelay = 0;
}
if (inRetryMode != null) {
hazzerBits |= 0x2;
this.inRetryMode = inRetryMode;
} else {
this.inRetryMode = false;
}
this.__hazzerBits = hazzerBits;
}
public int getCurrentMaxDelay() { return currentMaxDelay; }
public boolean hasCurrentMaxDelay() { return (0x1 & __hazzerBits) != 0; }
public boolean getInRetryMode() { return inRetryMode; }
public boolean hasInRetryMode() { return (0x2 & __hazzerBits) != 0; }
@Override public final boolean equals(Object obj) {
if (this == obj) { return true; }
if (!(obj instanceof ExponentialBackoffState)) { return false; }
ExponentialBackoffState other = (ExponentialBackoffState) obj;
return __hazzerBits == other.__hazzerBits
&& (!hasCurrentMaxDelay() || currentMaxDelay == other.currentMaxDelay)
&& (!hasInRetryMode() || inRetryMode == other.inRetryMode);
}
@Override protected int computeHashCode() {
int result = hash(__hazzerBits);
if (hasCurrentMaxDelay()) {
result = result * 31 + hash(currentMaxDelay);
}
if (hasInRetryMode()) {
result = result * 31 + hash(inRetryMode);
}
return result;
}
@Override public void toCompactString(TextBuilder builder) {
builder.append("<ExponentialBackoffState:");
if (hasCurrentMaxDelay()) {
builder.append(" current_max_delay=").append(currentMaxDelay);
}
if (hasInRetryMode()) {
builder.append(" in_retry_mode=").append(inRetryMode);
}
builder.append('>');
}
public static ExponentialBackoffState parseFrom(byte[] data) throws ValidationException {
try {
return fromMessageNano(MessageNano.mergeFrom(new com.google.protos.ipc.invalidation.nano.NanoClient.ExponentialBackoffState(), data));
} catch (InvalidProtocolBufferNanoException exception) {
throw new ValidationException(exception);
} catch (ValidationArgumentException exception) {
throw new ValidationException(exception.getMessage());
}
}
static ExponentialBackoffState fromMessageNano(com.google.protos.ipc.invalidation.nano.NanoClient.ExponentialBackoffState message) {
if (message == null) { return null; }
return new ExponentialBackoffState(message.currentMaxDelay,
message.inRetryMode);
}
public byte[] toByteArray() {
return MessageNano.toByteArray(toMessageNano());
}
com.google.protos.ipc.invalidation.nano.NanoClient.ExponentialBackoffState toMessageNano() {
com.google.protos.ipc.invalidation.nano.NanoClient.ExponentialBackoffState msg = new com.google.protos.ipc.invalidation.nano.NanoClient.ExponentialBackoffState();
msg.currentMaxDelay = hasCurrentMaxDelay() ? currentMaxDelay : null;
msg.inRetryMode = hasInRetryMode() ? inRetryMode : null;
return msg;
}
}
}
|
9238724618730eafa229f1a1a585be497a86323f | 2,315 | java | Java | app/src/main/java/com/csz/app/base/download/DownloadActivity.java | zsgfrtttt/HttpUtil | eed49abc8659f918bbf3e4ce457c56e612e544aa | [
"Apache-2.0"
] | 5 | 2020-09-02T17:50:35.000Z | 2022-01-18T13:51:43.000Z | app/src/main/java/com/csz/app/base/download/DownloadActivity.java | zsgfrtttt/httpUtil | eed49abc8659f918bbf3e4ce457c56e612e544aa | [
"Apache-2.0"
] | 1 | 2022-01-18T09:00:20.000Z | 2022-01-18T17:06:28.000Z | app/src/main/java/com/csz/app/base/download/DownloadActivity.java | zsgfrtttt/httpUtil | eed49abc8659f918bbf3e4ce457c56e612e544aa | [
"Apache-2.0"
] | 1 | 2022-01-18T09:41:39.000Z | 2022-01-18T09:41:39.000Z | 30.866667 | 106 | 0.667819 | 998,427 | package com.csz.app.base.download;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import com.csz.app.R;
import com.csz.okhttp.http.DownloadCallback;
import com.csz.okhttp.http.DownloadManager;
import com.csz.okhttp.util.MD5Util;
import java.io.File;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
//http://hot.m.shouji.360tpcdn.com/191206/e01002387a835bbe3aa8c21ade9f3d3a/com.qihoo360.mobilesafe_266.apk
//https://data.photo-ac.com/data/thumbnails/62/6285acd688ee0eac57c5034f5218a192_w.jpeg
//https://big1.vqs.com/zqw/20191121/A17AFDD0DFBA14BC53F80A6A06185C95.apk
/**
* @author caishuzhan
*/
public class DownloadActivity extends AppCompatActivity {
private ImageView iv;
private SeekBar seekBar;
private String url = "https://oss-miaoyin.looyu.vip/android/4.0.2app-miaoyin-release.apk";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
iv = findViewById(R.id.iv);
seekBar = findViewById(R.id.progress);
DownloadManager.getInstance().download(url, new DownloadCallback() {
@Override
public void onSuccess(final File file) {
Log.i("csz","onSuccess "+ file.length()); //225461208 cb3f257daa7187b892f857d858539213
Toast.makeText(DownloadActivity.this, "download succ", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int code, String msg) {
Log.e("csz", "e : " + msg);
}
@Override
public void onProgress(final int progress) {
Log.i("csz","onProgress " +progress);
seekBar.setMax(100);
seekBar.setProgress(progress);
}
});
}
public void pause(View view) {
DownloadManager.getInstance().pause(url);
}
public void start(View view) {
DownloadManager.getInstance().resume(url);
}
@Override
protected void onDestroy() {
super.onDestroy();
DownloadManager.getInstance().finish(url);
}
}
|
923872921f0b5a6c4c5ebb2830a02613b2ba2586 | 637 | java | Java | src/main/java/com/midgetontoes/todolist/jpa/LocalDateTimePersistenceConverter.java | sunytonyli/spring-hateoas | 93d680995f73a078d984322192205d93bb5d9f6e | [
"MIT"
] | null | null | null | src/main/java/com/midgetontoes/todolist/jpa/LocalDateTimePersistenceConverter.java | sunytonyli/spring-hateoas | 93d680995f73a078d984322192205d93bb5d9f6e | [
"MIT"
] | 1 | 2018-04-01T06:27:14.000Z | 2018-04-01T06:27:14.000Z | src/main/java/com/midgetontoes/todolist/jpa/LocalDateTimePersistenceConverter.java | sunytonyli/spring-hateoas | 93d680995f73a078d984322192205d93bb5d9f6e | [
"MIT"
] | null | null | null | 31.85 | 104 | 0.77237 | 998,428 | package com.midgetontoes.todolist.jpa;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
import java.time.LocalDateTime;
@Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime attribute) {
return attribute != null ? Timestamp.valueOf(attribute) : null;
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp dbData) {
return dbData != null ? dbData.toLocalDateTime() : null;
}
}
|
923873301cd532e864a41906abd69d680a06f32a | 1,585 | java | Java | src/main/java/walkingkooka/spreadsheet/format/pattern/SpreadsheetNumberParsePatternsComponentThousandsSeparator.java | mP1/walkingkooka-spreadsheet | 70b0649b1595e4a64af203ab9523f20fb3490913 | [
"Apache-2.0"
] | 2 | 2020-04-15T07:39:28.000Z | 2020-11-29T19:23:00.000Z | src/main/java/walkingkooka/spreadsheet/format/pattern/SpreadsheetNumberParsePatternsComponentThousandsSeparator.java | mP1/walkingkooka-spreadsheet | 70b0649b1595e4a64af203ab9523f20fb3490913 | [
"Apache-2.0"
] | 252 | 2019-08-30T09:24:29.000Z | 2022-03-30T11:00:09.000Z | src/main/java/walkingkooka/spreadsheet/format/pattern/SpreadsheetNumberParsePatternsComponentThousandsSeparator.java | mP1/walkingkooka-spreadsheet | 70b0649b1595e4a64af203ab9523f20fb3490913 | [
"Apache-2.0"
] | null | null | null | 30.480769 | 150 | 0.736278 | 998,429 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.spreadsheet.format.pattern;
import walkingkooka.text.cursor.TextCursor;
/**
* A {@link SpreadsheetNumberParsePatternsComponent} that does not actually expect or consume the grouping character.
*/
final class SpreadsheetNumberParsePatternsComponentThousandsSeparator extends SpreadsheetNumberParsePatternsComponent2 {
/**
* Singleton
*/
final static SpreadsheetNumberParsePatternsComponentThousandsSeparator INSTANCE = new SpreadsheetNumberParsePatternsComponentThousandsSeparator();
private SpreadsheetNumberParsePatternsComponentThousandsSeparator() {
super();
}
@Override
boolean isExpressionCompatible() {
return false;
}
@Override
boolean parse(final TextCursor cursor,
final SpreadsheetNumberParsePatternsRequest request) {
return request.nextComponent(cursor);
}
@Override
public String toString() {
return ",";
}
}
|
923873b9001573bf28b57729616ca55b90b62271 | 9,060 | java | Java | port-system-stage02/src/main/java/com/foxthere/controller/Controller2.java | NekoSilverFox/Port-Simulation-System | c3313c375f415b18cb343ee8cc9c629b28511a57 | [
"Apache-2.0"
] | null | null | null | port-system-stage02/src/main/java/com/foxthere/controller/Controller2.java | NekoSilverFox/Port-Simulation-System | c3313c375f415b18cb343ee8cc9c629b28511a57 | [
"Apache-2.0"
] | null | null | null | port-system-stage02/src/main/java/com/foxthere/controller/Controller2.java | NekoSilverFox/Port-Simulation-System | c3313c375f415b18cb343ee8cc9c629b28511a57 | [
"Apache-2.0"
] | null | null | null | 40.266667 | 171 | 0.707064 | 998,430 | /**
* -*- coding: utf-8 -*-
*
* @Time : 2021/4/26 13:42
* @Author : NekoSilverfox
* @FileName: Controller2
* @Software: IntelliJ IDEA
* @Versions: v1.0
* @Github :https://github.com/NekoSilverFox
*/
package com.foxthere.controller;
import com.foxthere.config.JavaConfig;
import com.foxthere.model.ConstantsTable;
import com.foxthere.model.Freighter;
import com.foxthere.model.StatisticalResults;
import com.foxthere.service.service1.FreighterTimetable;
import com.foxthere.service.service2.JsonManager;
import com.foxthere.unit.ErrorHandle;
import com.foxthere.unit.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* 用于从 Json 文件中获取船舶的时间表:<br/>
*
* - 按照默认路径获取<b><i><big>所有船舶</big></i></b>的时间表:<br/>
* http://localhost:8080/controller2/getFreighterTimetable<br/>
*<br/>
* - 按照默认路径获取<b><i><big>集装箱货船</big></i></b>的时间表:<br/>
* http://localhost:8080/controller2/getContainershipTimetable<br/>
*<br/>
* - 按照默认路径获取<b><i><big>液货船</big></i></b>的时间表:<br/>
* http://localhost:8080/controller2/getBulkCarrierTimetable<br/>
*<br/>
* - 按照默认路径获取<b><i><big>散货船</big></i></b>的时间表:<br/>
* http://localhost:8080/controller2/getBulkCarrierTimetable<br/>
*<br/>
* <hr>
*<br/>
* - 按照文件路径获取<b><i><big>所有船舶</big></i></b>的时间表:<br/>
* http://localhost:8080/controller2/getFreighterTimetableByPath/{jsonFileName}<br/>
*/
@Controller
@RequestMapping("/controller2")
public class Controller2 {
@Autowired
RestTemplate restTemplate;
/** http://localhost:8080/controller2/getFreighterTimetable
* @return 按照Json文件的默认路径,返回一个所有船舶的时刻表
* @return возвращает расписание всех кораблей в соответствии с путем по умолчанию к Json-файлу.
*/
@GetMapping("/getFreighterTimetable")
@ResponseBody
public FreighterTimetable getFreighterTimetable() {
System.out.println("[INFO] Getting Freighter Timetable from the URL `http://localhost:8080/controller2/getFreighterTimetable`");
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
FreighterTimetable freighterTimetable = context.getBean("freighterTimetable", FreighterTimetable.class);
try {
freighterTimetable.setFreighterList(JsonManager.jsonReader(ConstantsTable.JSON_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
// ArrayList<Freighter> freighterList = freighterTimetable.getFreighterList();
// System.out.println("[INFO] The freighterList: \n" + freighterList.toString());
return freighterTimetable;
}
/** http://localhost:8080/controller2/getFreighterTimetableByPath
* @return 按照用户给定Json文件路径,返回一个所有船舶的时刻表
* @return возвращает расписание всех судов в соответствии с путем к Json-файлу, указанному пользователем.
*/
@GetMapping("/getFreighterTimetableByPath/{jsonFileName}")
@ResponseBody
public FreighterTimetable getFreighterTimetableByPath(@PathVariable String jsonFileName) throws IOException {
System.out.println("[INFO] Getting Freighter Timetable by path from the URL `http://localhost:8080/controller2/getFreighterTimetableByPath/" + jsonFileName + "`");
if (jsonFileName.isEmpty() || !jsonFileName.toLowerCase().endsWith(".json")) {
System.out.println("[ERROR] " + jsonFileName + " file is empty or is not a Json file");
/* Throw except */
throw new ResourceNotFoundException();
}
String jsonFilePath = ConstantsTable.JSON_FILE_SAVE_PATH + jsonFileName;
System.out.println("[INFO] Json file path `" + jsonFilePath + "`");
if (!(new File(jsonFilePath).exists())) {
System.out.println("[ERROR] File does not exist " + jsonFilePath);
/* Throw except */
throw new ResourceNotFoundException();
}
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
FreighterTimetable freighterTimetable = context.getBean("freighterTimetable", FreighterTimetable.class);
try {
freighterTimetable.setFreighterList(JsonManager.jsonReader(jsonFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// ArrayList<Freighter> freighterList = freighterTimetable.getFreighterList();
// System.out.println("[INFO] The freighterList: \n" + freighterList.toString());
return freighterTimetable;
}
/** http://localhost:8080/controller2/getContainershipTimetable
* @return 按照Json文件的默认路径,返回一个 集装箱船 的时刻表
* @return возвращает расписание движения контейнеровозов в соответствии со стандартным путем к Json-файлу.
*/
@GetMapping("/getContainershipTimetable")
@ResponseBody
public ArrayList<Freighter> getContainershipTimetable() {
System.out.println("[INFO] Getting Freighter Timetable from the URL `http://localhost:8080/controller2/getContainershipTimetable`");
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
FreighterTimetable freighterTimetable = context.getBean("freighterTimetable", FreighterTimetable.class);
try {
freighterTimetable.setFreighterList(JsonManager.jsonReader(ConstantsTable.JSON_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Freighter> containershipList = freighterTimetable.getContainershipList();
System.out.println("[INFO] The containershipList: \n" + containershipList.toString());
return containershipList;
}
/** http://localhost:8080/controller2/getBulkCarrierTimetable
* @return 按照Json文件的默认路径,返回一个 液体船 的时刻表
* @return возвращает расписание для жидкого судна, следуя пути по умолчанию к Json-файлу.
*/
@GetMapping("/getBulkCarrierTimetable")
@ResponseBody
public ArrayList<Freighter> getBulkCarrierTimetable() {
System.out.println("[INFO] Getting Freighter Timetable from the URL `http://localhost:8080/controller2/getBulkCarrierTimetable`");
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
FreighterTimetable freighterTimetable = context.getBean("freighterTimetable", FreighterTimetable.class);
try {
freighterTimetable.setFreighterList(JsonManager.jsonReader(ConstantsTable.JSON_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Freighter> bulkCarrierList = freighterTimetable.getBulkCarrierList();
System.out.println("[INFO] The bulkCarrierList: \n" + bulkCarrierList.toString());
return bulkCarrierList;
}
/** http://localhost:8080/controller2/getTankerTimetable
* @return 按照Json文件的默认路径,返回一个 散货船 的时刻表
* @return возвращает расписание для балкера, следуя пути по умолчанию к Json-файлу.
*/
@GetMapping("/getTankerTimetable")
@ResponseBody
public ArrayList<Freighter> getTankerTimetable() {
System.out.println("[INFO] Getting Freighter Timetable from the URL `http://localhost:8080/controller2/getTankerTimetable`");
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
FreighterTimetable freighterTimetable = context.getBean("freighterTimetable", FreighterTimetable.class);
try {
freighterTimetable.setFreighterList(JsonManager.jsonReader(ConstantsTable.JSON_FILE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Freighter> tankerList = freighterTimetable.getTankerList();
System.out.println("[INFO] The tankerList: \n" + tankerList.toString());
return tankerList;
}
/** 【通过POST】http://localhost:8080/controller2/postStatisticalResultsToJsonFile
* 将 post 过来的数据保存在json文件中
* Сохраните опубликованные данные в json-файле
*
* @param resultsArrayList 要保存的数据 Данные для сохранения
* @return
*/
@PostMapping("postStatisticalResultsToJsonFile")
// @RequestMapping("/postStatisticalResultsToJsonFile")
@ResponseBody
public ArrayList<StatisticalResults> postStatisticalResultsToJsonFile(@RequestBody ArrayList<StatisticalResults> resultsArrayList) {
try {
JsonManager.jsonStatisticalResultsWriter(resultsArrayList, ConstantsTable.RESULT_FILE_PATH);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("---------------------------- postStatisticalResultsToJsonFile ----------------------------");
System.out.println(resultsArrayList);
return resultsArrayList;
}
}
|
923876c2f1f346d153dd64603568e4b07be0ddd0 | 1,717 | java | Java | websphere-mq/src/test/java/org/mule/examples/WebsphereMQIT.java | mulesoft-consulting/anypoint-examples | 20f17b2f162c7a81787aafddd54b0ba196edd8d7 | [
"Apache-2.0"
] | 1 | 2019-03-08T16:08:23.000Z | 2019-03-08T16:08:23.000Z | websphere-mq/src/test/java/org/mule/examples/WebsphereMQIT.java | mulesoft-consulting/anypoint-examples | 20f17b2f162c7a81787aafddd54b0ba196edd8d7 | [
"Apache-2.0"
] | null | null | null | websphere-mq/src/test/java/org/mule/examples/WebsphereMQIT.java | mulesoft-consulting/anypoint-examples | 20f17b2f162c7a81787aafddd54b0ba196edd8d7 | [
"Apache-2.0"
] | 1 | 2019-03-08T16:08:28.000Z | 2019-03-08T16:08:28.000Z | 29.603448 | 124 | 0.679091 | 998,431 | /**
* MuleSoft Examples
* Copyright 2014 MuleSoft, Inc.
*
* This product includes software developed at
* MuleSoft, Inc. (http://www.mulesoft.com/).
*/
package org.mule.examples;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mule.DefaultMuleMessage;
import org.mule.api.MuleEvent;
import org.mule.munit.runner.functional.FunctionalMunitSuite;
public class WebsphereMQIT extends FunctionalMunitSuite
{
private String MESSAGE = "test";
@Override
protected String getConfigResources()
{
return "websphere-mq.xml";
}
@BeforeClass
public static void init(){
System.setProperty("wmq.host", "");
System.setProperty("wmq.password", "");
System.setProperty("wmq.port", "1414");
System.setProperty("wmq.channel", "");
System.setProperty("wmq.username", "");
System.setProperty("wmq.queue", "");
}
@Before
public void setUp(){
whenMessageProcessor("outbound-endpoint").ofNamespace("wmq").thenReturn(new DefaultMuleMessage(MESSAGE, muleContext));
whenMessageProcessor("outbound-endpoint").ofNamespace("ajax").thenReturn(new DefaultMuleMessage(MESSAGE, muleContext));
}
@Test
public void testWMQ() throws Exception
{
MuleEvent res = runFlow("Input", testEvent(""));
Assert.assertEquals(MESSAGE, res.getMessage().getPayloadAsString());
res = runFlow("MessageProcessor", testEvent(""));
Assert.assertEquals(MESSAGE, res.getMessage().getPayloadAsString());
res = runFlow("Output", testEvent(""));
Assert.assertEquals(MESSAGE, res.getMessage().getPayloadAsString());
}
}
|
92387702ec8fb757bb626a92887998048758d77b | 1,281 | java | Java | src/main/java/br/com/entelgy/liferay/dxp/pages/LoginPage.java | entelgy-brasil/zucchini-liferay-dxp | cfb3db75203c105455b120955f8469f455021c09 | [
"Apache-2.0"
] | 1 | 2017-04-13T10:34:18.000Z | 2017-04-13T10:34:18.000Z | src/main/java/br/com/entelgy/liferay/dxp/pages/LoginPage.java | entelgy-brasil/zucchini-liferay-dxp | cfb3db75203c105455b120955f8469f455021c09 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/entelgy/liferay/dxp/pages/LoginPage.java | entelgy-brasil/zucchini-liferay-dxp | cfb3db75203c105455b120955f8469f455021c09 | [
"Apache-2.0"
] | null | null | null | 26.6875 | 137 | 0.781421 | 998,432 | package br.com.entelgy.liferay.dxp.pages;
import br.com.entelgy.liferay.dxp.constants.Wait;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage {
private WebDriver driver;
@FindBy(how = How.ID, using = "_com_liferay_login_web_portlet_LoginPortlet_login")
private WebElement username;
@FindBy(how = How.ID, using = "_com_liferay_login_web_portlet_LoginPortlet_password")
private WebElement password;
@FindBy(how = How.CLASS_NAME, using = "btn-lg")
private WebElement btn;
public void login(String username, String password) {
WebElement usernameElement = new WebDriverWait(driver, Wait.TEN_SECONDS).until(ExpectedConditions.elementToBeClickable(this.username));
usernameElement.clear();
usernameElement.sendKeys(username);
this.password.sendKeys(password);
this.btn.click();
}
public WebElement getUsername() {
return username;
}
public WebElement getPassword() {
return password;
}
public WebElement getBtn() {
return btn;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
}
|
92387717e5a3200e87a30d8b6bc9d94ad0a0f301 | 12,626 | java | Java | app/src/main/java/net/xxtime/activity/JobSearchActivity.java | vvvpic/xxtime | 8512b8a7a74f4b245a106b429e85c3aaf65e56e3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/net/xxtime/activity/JobSearchActivity.java | vvvpic/xxtime | 8512b8a7a74f4b245a106b429e85c3aaf65e56e3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/net/xxtime/activity/JobSearchActivity.java | vvvpic/xxtime | 8512b8a7a74f4b245a106b429e85c3aaf65e56e3 | [
"Apache-2.0"
] | null | null | null | 34.686813 | 124 | 0.585696 | 998,433 | package net.xxtime.activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.longtu.base.data.ChakesheData;
import com.longtu.base.data.DatafieldBean;
import com.longtu.base.util.StringUtils;
import com.longtu.base.util.ToastUtils;
import com.loopj.android.http.RequestParams;
import net.xxtime.R;
import net.xxtime.adapter.BannerAdapter;
import net.xxtime.adapter.HistoryAdapter;
import net.xxtime.adapter.JobAdapter;
import net.xxtime.base.activity.BaseActivity;
import net.xxtime.bean.GetHomeLbtBean;
import net.xxtime.bean.JobByConditionBean;
import net.xxtime.utils.Contact;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JobSearchActivity extends BaseActivity implements AbsListView.OnScrollListener,AdapterView.OnItemClickListener{
private EditText et_search;
private ListView lvHistorys, lvJobs;
private ChakesheData historydata;
private DatafieldBean datafieldBean;
private View historyHeadView;
private View historyFooterView;
private TextView tvHostoryClear,tvHostoryClose;
private List<Map<String,Object>> listHistorys;
private List<Map<String,Object>> listseaHistorys;
private Map<String ,Object> maphis;
private HistoryAdapter historyAdapter;
private int indexPage=1;
private String CityCode;
private View FooterView;
private ImageView ivLoading ;
private TextView tvLoading;
private Message msg;
private JobAdapter jobAdapter;
private JobByConditionBean jobByConditionBean;
private List<JobByConditionBean.DefaultAListBean> listDefaults;
private String search;
private RelativeLayout rlEmpty;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
if (indexPage==1){
listDefaults.clear();
}
jobByConditionBean=JSONObject.parseObject(msg.obj.toString(),JobByConditionBean.class);
if (jobByConditionBean!=null&&jobByConditionBean.getBflag().equals("1")){
if (jobByConditionBean.getDefaultAList()!=null&&jobByConditionBean.getDefaultAList().size()>0) {
listDefaults.addAll(jobByConditionBean.getDefaultAList());
if (jobByConditionBean.getDefaultAList().size()==10){
ivLoading.setVisibility(View.VISIBLE);
tvLoading.setText("加载中...");
}else {
ivLoading.setVisibility(View.GONE);
tvLoading.setText("加载完毕");
}
lvJobs.setVisibility(View.VISIBLE);
lvHistorys.setVisibility(View.GONE);
rlEmpty.setVisibility(View.GONE);
}else {
ivLoading.setVisibility(View.GONE);
tvLoading.setText("加载完毕");
if (indexPage==1){
lvJobs.setVisibility(View.GONE);
lvHistorys.setVisibility(View.GONE);
rlEmpty.setVisibility(View.VISIBLE);
}
}
}else {
ivLoading.setVisibility(View.GONE);
tvLoading.setText("加载完毕");
if (indexPage==1){
lvJobs.setVisibility(View.GONE);
lvHistorys.setVisibility(View.GONE);
rlEmpty.setVisibility(View.VISIBLE);
}
}
jobAdapter.notifyDataSetChanged();
break;
}
}
};
@Override
public void setContentView() {
setContentView(R.layout.activity_job_search);
}
@Override
public void initViews() {
et_search =(EditText)findViewById(R.id.et_search);
lvHistorys =(ListView) findViewById(R.id.lvHistorys);
lvJobs =(ListView) findViewById(R.id.lvJobs);
rlEmpty=(RelativeLayout)findViewById(R.id.rlEmpty);
historyHeadView= LayoutInflater.from(this).inflate(R.layout.history_header,null);
lvHistorys.addHeaderView(historyHeadView);
historyFooterView=LayoutInflater.from(this).inflate(R.layout.history_footer,null);
tvHostoryClear =(TextView)historyFooterView.findViewById(R.id.tvHostoryClear);
tvHostoryClose =(TextView)historyFooterView.findViewById(R.id.tvHostoryClose);
lvHistorys.addFooterView(historyFooterView);
FooterView= LayoutInflater.from(this).inflate(R.layout.list_footer,null);
ivLoading =(ImageView) FooterView.findViewById(R.id.ivLoading);
tvLoading=(TextView)FooterView.findViewById(R.id.tvLoading);
lvJobs.addFooterView(FooterView);
loading(ivLoading);
}
@Override
public void initDatas() {
datafieldBean=new DatafieldBean();
datafieldBean.table="histoty";
datafieldBean.listfield.add("jobname");
historydata=new ChakesheData(this,datafieldBean);
historydata.onSetup();
setHistory();
if (!StringUtils.isEmpty(Contact.ChooseCityCode)){
CityCode=Contact.ChooseCityCode;
}else {
if (!StringUtils.isEmpty(Contact.CityCode)){
CityCode=Contact.CityCode;
}
}
listDefaults=new ArrayList<>();
jobAdapter=new JobAdapter(listDefaults,this);
lvJobs.setAdapter(jobAdapter);
}
private void setHistory(){
listHistorys=historydata.ReadAll();
historyAdapter=new HistoryAdapter(listHistorys,this);
lvHistorys.setAdapter(historyAdapter);
lvHistorys.setVisibility(View.VISIBLE);
lvJobs.setVisibility(View.GONE);
rlEmpty.setVisibility(View.GONE);
}
@Override
public void setDatas() {
}
private void addHistory(String jobname){
maphis=new HashMap<>();
maphis.put("jobname",jobname);
listseaHistorys=historydata.SearchAll(maphis,"jobname",null,null,false);
if (listseaHistorys==null||listseaHistorys.size()==0){
historydata.Add(maphis);
}
}
@Override
public void setListener() {
et_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
et_search.setInputType(EditorInfo.TYPE_CLASS_TEXT);
et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND
|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
if (!StringUtils.isEmpty(et_search.getText().toString())) {
indexPage = 1;
addHistory(et_search.getText().toString());
search=et_search.getText().toString();
getgetJobByCondition(search);
et_search.setText("");
hideSoftInput(et_search);
}else {
ToastUtils.show(JobSearchActivity.this,"请输入搜索内容");
}
return false;
}
return false;
}
});
// et_search.addTextChangedListener(new EditTextWatcher(R.id.et_search));
et_search.setOnClickListener(this);
lvJobs.setOnScrollListener(this);
lvJobs.setOnItemClickListener(this);
lvHistorys.setOnItemClickListener(this);
tvHostoryClear.setOnClickListener(this);
tvHostoryClose.setOnClickListener(this);
}
private void getgetJobByCondition(String jobname){
if (StringUtils.isEmpty(jobname)){
lvJobs.setVisibility(View.GONE);
lvHistorys.setVisibility(View.GONE);
rlEmpty.setVisibility(View.VISIBLE);
return;
}
params=new RequestParams();
params.put("reqCode","getJobByCondition");
params.put("indexPage",indexPage);
params.put("city",CityCode);
params.put("jobname",jobname);
Log.e("param==>",params.toString());
pullpost("job",params,"getJobByCondition");
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
// 判断是否滚动到底部
if (view.getLastVisiblePosition() == view.getCount() - 1&&ivLoading.getVisibility()==View.VISIBLE) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
indexPage++;
getgetJobByCondition(search);
}
}, 500);
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void OnReceive(String requestname, String response) {
msg=new Message();
if (requestname.equals("getJobByCondition")){
msg.what=1;
}
msg.obj=response;
handler.sendMessage(msg);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.lvJobs:
if (listDefaults.size()==position){
return;
}
intent=new Intent(this,JobDetailsActivity.class);
intent.putExtra("jobcode",listDefaults.get(position).getJobcode());
Jump(intent);
break;
case R.id.lvHistorys:
if (listHistorys==null&&listHistorys.size()==0){
return;
}
if (position==0||position==listHistorys.size()+1
){
return;
}
search=listHistorys.get(position-1).get("jobname").toString();
indexPage=1;
getgetJobByCondition(search);
hideSoftInput(et_search);
break;
}
}
public class EditTextWatcher implements TextWatcher {
int code;
public EditTextWatcher(int i) {
code = i;
}
@Override
public void afterTextChanged(Editable arg0) {
Log.e("afterTextChanged==>","afterTextChanged");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.e("beforeTextChanged==>","beforeTextChanged");
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO 自动生成的方法存根
Log.e("onTextChanged==>","onTextChanged");
}
}
@Override
public void ResumeDatas() {
}
@Override
public void onClick(View v) {
Log.e("v==>",v.getId()+"");
switch (v.getId()){
case R.id.et_search:
setHistory();
break;
case R.id.tvHostoryClear:
clear();
setHistory();
break;
case R.id.tvHostoryClose:
getgetJobByCondition(search);
hideSoftInput(et_search);
break;
}
}
private void clear(){
if (listHistorys!=null){
for (int i=0;i<listHistorys.size();i++){
historydata.Delete(listHistorys.get(i),"_id");
}
}
}
}
|
92387721dd10a82d059b1e195eddadff9d702a5d | 1,815 | java | Java | core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyNegativeCase1.java | chubbymaggie/error-prone | c5950dc5fd45c9f47472a93897425a9dcd949ac3 | [
"Apache-2.0"
] | 6 | 2020-07-26T18:24:07.000Z | 2022-01-21T07:17:42.000Z | core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyNegativeCase1.java | chubbymaggie/error-prone | c5950dc5fd45c9f47472a93897425a9dcd949ac3 | [
"Apache-2.0"
] | 44 | 2022-01-13T23:27:31.000Z | 2022-03-21T16:15:56.000Z | core/src/test/java/com/google/errorprone/bugpatterns/testdata/FinallyNegativeCase1.java | chubbymaggie/error-prone | c5950dc5fd45c9f47472a93897425a9dcd949ac3 | [
"Apache-2.0"
] | 1 | 2021-11-25T18:35:50.000Z | 2021-11-25T18:35:50.000Z | 19.105263 | 75 | 0.553168 | 998,434 | /*
* Copyright 2013 The Error Prone 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 com.google.errorprone.bugpatterns.testdata;
/** @author anpch@example.com (Eddie Aftandilian) */
public class FinallyNegativeCase1 {
public static void test1() {
while (true) {
try {
break;
} finally {
}
}
}
public static void test2() {
while (true) {
try {
continue;
} finally {
}
}
}
public static void test3() {
try {
return;
} finally {
}
}
public static void test4() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
} finally {
}
}
/** break inner loop. */
public void test5() {
label:
while (true) {
try {
} finally {
while (true) {
break;
}
}
}
}
/** continue statement jumps out of inner for. */
public void test6() {
label:
for (; ; ) {
try {
} finally {
for (; ; ) {
continue;
}
}
}
}
/** break statement jumps out of switch. */
public void test7() {
int i = 10;
while (true) {
try {
} finally {
switch (i) {
case 10:
break;
}
}
}
}
}
|
92387761ad7a311d7510c0e62f63f43b20d61ea7 | 1,379 | java | Java | acgist-conan/src/test/java/com/acgist/test/TaskTest.java | acgist/demo | 7dfc5d6cb967dafec4d5707e2f395d3e3d354d80 | [
"BSD-3-Clause"
] | 3 | 2019-07-06T02:31:44.000Z | 2020-07-31T08:04:55.000Z | acgist-conan/src/test/java/com/acgist/test/TaskTest.java | acgist/demo | 7dfc5d6cb967dafec4d5707e2f395d3e3d354d80 | [
"BSD-3-Clause"
] | 24 | 2020-07-31T07:21:58.000Z | 2021-12-19T08:43:42.000Z | acgist-conan/src/test/java/com/acgist/test/TaskTest.java | acgist/demo | 7dfc5d6cb967dafec4d5707e2f395d3e3d354d80 | [
"BSD-3-Clause"
] | null | null | null | 39.4 | 264 | 0.712835 | 998,435 | package com.acgist.test;
import java.io.IOException;
import org.junit.Test;
import com.acgist.bean.Task;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TaskTest {
@Test
public void json() throws JsonParseException, JsonMappingException, IOException {
String json = "{\"id\":\"73e122df-235f-4873-8713-e4c72dc800df\",\"name\":\"测试\",\"match\":\"all\",\"state\":\"over\",\"page\":1,\"processed\":11,\"totalPage\":11,\"keys\":[\"碧螺萧萧\",\"\"],\"sources\":[\"baidu\"],\"taskFollows\":[{\"value\":\"百度\",\"times\":7}]}";
ObjectMapper mapper = new ObjectMapper();
// JavaType inner = mapper.getTypeFactory().constructParametricType(TaskFollow.class);
// JavaType javaType = mapper.getTypeFactory().constructParametricType(Task.class, TaskFollow.class);
Task task = mapper.readValue(json, Task.class);
System.out.println(task.getId());
System.out.println(task.getName());
System.out.println(task.getState());
System.out.println(task.getPage());
System.out.println(task.getProcessed());
System.out.println(task.getTotalPage());
System.out.println(task.getMatch());
System.out.println(task.getSources());
task.getTaskFollows().forEach(value -> {
System.out.println(value.getValue() + "-" + value.getTimes());
});
}
}
|
9238776cb4ad72a9dead865faff212bb56ef8d57 | 3,802 | java | Java | src/main/java/com/intuit/graphql/orchestrator/xtext/XtextScalars.java | LaudateCorpus1/graphql-orchestrator-java | 87c7be61c0009aa4e0bc70ddc8861c6d516a71ff | [
"Apache-2.0"
] | 13 | 2021-06-22T02:49:47.000Z | 2022-03-28T02:52:38.000Z | src/main/java/com/intuit/graphql/orchestrator/xtext/XtextScalars.java | intuit/graphql-orchestrator-java | f09f91f572758b28f451c97b14c1f701cf3019d3 | [
"Apache-2.0"
] | 3 | 2021-12-21T17:34:11.000Z | 2022-03-30T23:35:19.000Z | src/main/java/com/intuit/graphql/orchestrator/xtext/XtextScalars.java | LaudateCorpus1/graphql-orchestrator-java | 87c7be61c0009aa4e0bc70ddc8861c6d516a71ff | [
"Apache-2.0"
] | 2 | 2021-09-12T03:37:24.000Z | 2021-11-08T15:44:13.000Z | 37.643564 | 117 | 0.792741 | 998,436 | package com.intuit.graphql.orchestrator.xtext;
import static com.intuit.graphql.orchestrator.xtext.GraphQLFactoryDelegate.createScalarTypeDefinition;
import static org.eclipse.xtext.EcoreUtil2.copy;
import com.intuit.graphql.graphQL.ScalarTypeDefinition;
import java.util.HashSet;
import java.util.Set;
/**
* Provides all supported standard scalars in the GraphQL specification and extended scalars in GraphQL-Java as Xtext
* ScalarTypeDefinitions. All methods return <b>new instances</b> for the respective scalar type.
*/
public class XtextScalars {
public static Set<ScalarTypeDefinition> STANDARD_SCALARS = new HashSet<>(11);
private static final ScalarTypeDefinition INT_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition STRING_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition FLOAT_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition BOOLEAN_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition ID_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition LONG_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition BIG_INT_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition BIG_DECIMAL_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition SHORT_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition CHAR_TYPE_DEFINITION = createScalarTypeDefinition();
private static final ScalarTypeDefinition BYTE_TYPE_DEFINITION = createScalarTypeDefinition();
static {
INT_TYPE_DEFINITION.setName("Int");
STRING_TYPE_DEFINITION.setName("String");
FLOAT_TYPE_DEFINITION.setName("Float");
BOOLEAN_TYPE_DEFINITION.setName("Boolean");
ID_TYPE_DEFINITION.setName("ID");
LONG_TYPE_DEFINITION.setName("Long");
BIG_INT_TYPE_DEFINITION.setName("BigInteger");
BIG_DECIMAL_TYPE_DEFINITION.setName("BigDecimal");
SHORT_TYPE_DEFINITION.setName("Short");
CHAR_TYPE_DEFINITION.setName("Char");
BYTE_TYPE_DEFINITION.setName("Byte");
}
static {
STANDARD_SCALARS.add(newIntType());
STANDARD_SCALARS.add(newStringType());
STANDARD_SCALARS.add(newFloatType());
STANDARD_SCALARS.add(newBooleanType());
STANDARD_SCALARS.add(newIdType());
STANDARD_SCALARS.add(newLongType());
STANDARD_SCALARS.add(newBigIntType());
STANDARD_SCALARS.add(newBigDecimalType());
STANDARD_SCALARS.add(newShortType());
STANDARD_SCALARS.add(newCharType());
STANDARD_SCALARS.add(newByteType());
}
public static ScalarTypeDefinition newStringType() {
return copy(STRING_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newFloatType() {
return copy(FLOAT_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newBooleanType() {
return copy(BOOLEAN_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newIdType() {
return copy(ID_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newLongType() {
return copy(LONG_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newBigIntType() {
return copy(BIG_INT_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newBigDecimalType() {
return copy(BIG_DECIMAL_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newShortType() {
return copy(SHORT_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newCharType() {
return copy(CHAR_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newByteType() {
return copy(BYTE_TYPE_DEFINITION);
}
public static ScalarTypeDefinition newIntType() {
return copy(INT_TYPE_DEFINITION);
}
} |
923877a6b533e2aac4aaa88f8289566174e4d633 | 4,219 | java | Java | src/srcmlolol/XMLListener.java | cscorley/srcmlolol | 722ddf82b92d4e601d4f649cabdc69b6fdfdcc39 | [
"MIT"
] | 5 | 2016-11-07T00:26:58.000Z | 2021-12-25T02:47:39.000Z | src/srcmlolol/XMLListener.java | cscorley/srcmlolol | 722ddf82b92d4e601d4f649cabdc69b6fdfdcc39 | [
"MIT"
] | 1 | 2021-08-07T02:24:41.000Z | 2021-08-25T01:52:01.000Z | src/srcmlolol/XMLListener.java | cscorley/srcmlolol | 722ddf82b92d4e601d4f649cabdc69b6fdfdcc39 | [
"MIT"
] | 3 | 2016-06-09T20:29:46.000Z | 2020-02-26T10:12:32.000Z | 39.064815 | 107 | 0.676227 | 998,437 | package srcmlolol;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLListener implements ParseTreeListener {
private Map<Integer, String> token2name;
private Map<String, Integer> name2token;
private DocumentBuilderFactory factory;
private DocumentBuilder builder;
private Stack<Element> stack;
public Document doc;
public XMLListener(String filename, Map<String, Integer> tokenMap) throws ParserConfigurationException{
stack = new Stack<Element>();
token2name = new HashMap<Integer, String>();
name2token = tokenMap;
for (String key : name2token.keySet()){
token2name.put(name2token.get(key), key);
}
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element unit = doc.createElement("unit");
unit.setAttribute("filename", filename);
doc.appendChild(unit);
stack.add(unit);
}
@Override
public void enterEveryRule(ParserRuleContext ctx) {
String name = ctx.getClass().getSimpleName().replace("Context", "");
Element rule = doc.createElement(name);
rule.setAttribute("start_line", Integer.toString(ctx.start.getLine()));
rule.setAttribute("start_line_char", Integer.toString(ctx.start.getCharPositionInLine()));
rule.setAttribute("start_char", Integer.toString(ctx.start.getStartIndex()));
// occasionally stop isn't set. prefer start token instead.
if (ctx.stop == null){
rule.setAttribute("end_line", Integer.toString(ctx.start.getLine()));
rule.setAttribute("end_line_char", Integer.toString(
(ctx.start.getCharPositionInLine() + ctx.start.getText().length())));
rule.setAttribute("end_char", Integer.toString(ctx.start.getStopIndex()));
}
else{
rule.setAttribute("end_line", Integer.toString(ctx.stop.getLine()));
rule.setAttribute("end_line_char", Integer.toString(
(ctx.stop.getCharPositionInLine() + ctx.stop.getText().length())));
rule.setAttribute("end_char", Integer.toString(ctx.stop.getStopIndex()));
}
// attaching to last elem on stack
stack.peek().appendChild(rule);
stack.add(rule);
}
@Override
public void exitEveryRule(ParserRuleContext ctx) {
// oh no!!
stack.pop();
}
@Override
public void visitErrorNode(ErrorNode node) {
}
@Override
public void visitTerminal(TerminalNode node) {
String text = node.getText();
if (text.equals("<EOF>")) {
return;
}
Token token = node.getSymbol();
Element tokenelem = doc.createElement(token.getClass().getSimpleName());
int type = token.getType();
tokenelem.setAttribute("type", Integer.toString(type));
tokenelem.setAttribute("name", token2name.get(type));
tokenelem.appendChild(doc.createTextNode(StringEscapeUtils.escapeXml10(text)));
tokenelem.setAttribute("start_line", Integer.toString(token.getLine()));
tokenelem.setAttribute("end_line", Integer.toString(token.getLine()));
tokenelem.setAttribute("start_line_char", Integer.toString(token.getCharPositionInLine()));
tokenelem.setAttribute("end_line_char", Integer.toString(
(token.getCharPositionInLine() + token.getText().length())));
tokenelem.setAttribute("start_char", Integer.toString(token.getStartIndex()));
tokenelem.setAttribute("end_char", Integer.toString(token.getStopIndex()));
stack.peek().appendChild(tokenelem);
}
}
|
923877e0fa40b3b83668b4fa43b4365f07c233bb | 8,276 | java | Java | src/com/smartisanos/sidebar/view/RecentPhotoAdapter.java | fenghuan1994/onestep-learning | a7715ccc2d72f0f2e411031d1deeb8ab51119b02 | [
"Apache-2.0"
] | 503 | 2016-12-20T07:35:22.000Z | 2022-03-12T09:44:41.000Z | src/com/smartisanos/sidebar/view/RecentPhotoAdapter.java | Shenglin-Lee/packages_apps_OneStep | 860c58e383c903ce0b5bbdb6ce41440fc7d0b195 | [
"Apache-2.0"
] | 8 | 2016-12-21T15:44:11.000Z | 2019-11-13T06:55:08.000Z | src/com/smartisanos/sidebar/view/RecentPhotoAdapter.java | Shenglin-Lee/packages_apps_OneStep | 860c58e383c903ce0b5bbdb6ce41440fc7d0b195 | [
"Apache-2.0"
] | 126 | 2016-12-20T13:24:35.000Z | 2022-02-16T02:38:56.000Z | 32.711462 | 129 | 0.581078 | 998,438 | package com.smartisanos.sidebar.view;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.smartisanos.sidebar.R;
import com.smartisanos.sidebar.util.DataManager.RecentUpdateListener;
import com.smartisanos.sidebar.util.IEmpty;
import com.smartisanos.sidebar.util.ImageInfo;
import com.smartisanos.sidebar.util.ImageLoader;
import com.smartisanos.sidebar.util.LOG;
import com.smartisanos.sidebar.util.RecentPhotoManager;
import com.smartisanos.sidebar.util.Utils;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class RecentPhotoAdapter extends BaseAdapter {
private static final LOG log = LOG.getInstance(RecentPhotoAdapter.class);
private static final int[] sNeedExpandNumber = new int[] { 30, 30, 60, 60,
60 };
private Context mContext;
private RecentPhotoManager mPhotoManager;
private List<ImageInfo> mImageInfoList = new ArrayList<ImageInfo>();
private boolean[] mExpand = new boolean[Utils.Interval.DAY_INTERVAL.length];
private Map<Integer, List<ImageInfo>> mIntervals = new HashMap<Integer, List<ImageInfo>>();
private int mFirstInterval;
private ImageLoader mImageLoader;
private Handler mHandler;
private IEmpty mEmpty;
public RecentPhotoAdapter(Context context, IEmpty empty) {
mContext = context;
mEmpty = empty;
mHandler = new Handler(Looper.getMainLooper());
mPhotoManager = RecentPhotoManager.getInstance(mContext);
int maxPhotoSize = mContext.getResources().getDimensionPixelSize(R.dimen.recent_photo_size);
mImageLoader = new ImageLoader(maxPhotoSize);
mImageInfoList = mPhotoManager.getImageList();
updateDataList();
mPhotoManager.addListener(new RecentUpdateListener() {
@Override
public void onUpdate() {
mHandler.post(new Runnable(){
@Override
public void run() {
mImageInfoList = mPhotoManager.getImageList();
updateDataList();
notifyDataSetChanged();
}
});
}
});
notifyEmpty();
}
public void shrink() {
Arrays.fill(mExpand, false);
notifyDataSetChanged();
}
private void updateDataList() {
mIntervals.clear();
mFirstInterval = Integer.MAX_VALUE;
long now = System.currentTimeMillis();
for (int i = 0; i < mImageInfoList.size(); i++) {
ImageInfo info = mImageInfoList.get(i);
int interval = Utils.Interval.getInterval(now, info.time);
List<ImageInfo> list = mIntervals.get(interval);
if (list == null) {
list = new ArrayList<ImageInfo>();
mIntervals.put(interval, list);
mFirstInterval = Math.min(mFirstInterval, interval);
}
list.add(info);
}
}
private void notifyEmpty() {
if (mEmpty != null) {
mEmpty.setEmpty(getCount() == 0);
}
}
@Override
public void notifyDataSetChanged() {
notifyEmpty();
super.notifyDataSetChanged();
}
@Override
public int getCount() {
int total = 0;
for(int i = 0; i < Utils.Interval.DAY_INTERVAL.length; ++ i) {
total += getIntervalCount(i);
}
return total;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder vh = null;
if(view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.photo_line, null);
vh = new ViewHolder();
vh.dateView = (TextView)view.findViewById(R.id.date);
vh.subView[0] = (PhotoLineSubView)view.findViewById(R.id.photo_line_sub_view_1);
vh.subView[1] = (PhotoLineSubView)view.findViewById(R.id.photo_line_sub_view_2);
vh.subView[2] = (PhotoLineSubView)view.findViewById(R.id.photo_line_sub_view_3);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
vh.reset();
int now = 0;
int our_interval = 0;
int interval_line = 0;
for(int i = 0; i < Utils.Interval.DAY_INTERVAL.length; ++ i) {
if(now + getIntervalCount(i) > position) {
our_interval = i;
interval_line = position - now;
break;
}
now += getIntervalCount(i);
}
if(interval_line == 0) {
// show date
vh.dateView.setText(Utils.Interval.LABEL_INTERVAL[our_interval]);
vh.dateView.setVisibility(View.VISIBLE);
}
List<ImageInfo> intervalInfos = mIntervals.get(our_interval);
boolean expand = mExpand[our_interval];
int startIndex = interval_line * 3;
int needExpandNumber = sNeedExpandNumber[our_interval];
if(our_interval == mFirstInterval) {
startIndex -= 1;
needExpandNumber -- ;
}
int starti = 0;
if(position == 0) {
vh.subView[0].showOpenGallery();
starti ++ ;
}
int size = intervalInfos.size();
if (!expand) {
size = Math.min(needExpandNumber, intervalInfos.size());
}
for(int i = starti; i < 3; ++ i) {
int index = startIndex + i;
if(index < size) {
if(interval_line * 3 + i == sNeedExpandNumber[our_interval] - 1) {
if(intervalInfos.size() > needExpandNumber && !expand) {
// show expand button;
vh.subView[i].showMorePhoto(new showMoreListener(our_interval, vh.subView[i], intervalInfos.get(index)));
continue;
}
}
// set Image
vh.subView[i].setImageLoader(mImageLoader);
vh.subView[i].showPhoto(intervalInfos.get(index));
} else {
// NA;
}
}
return view;
}
public void clearCache() {
if (mImageLoader != null) {
mImageLoader.clearCache();
}
}
private int getIntervalCount(int i) {
List<ImageInfo> list = mIntervals.get(i);
if(list != null) {
// consider expand later ..
int line = (list.size() + (i == mFirstInterval ? 1 : 0) + 2) / 3;
if(mExpand[i]) {
return line;
} else {
return Math.min(line, (sNeedExpandNumber[i] + 2) / 3);
}
}
return 0;
}
class ViewHolder {
public TextView dateView;
public PhotoLineSubView[] subView;
public ViewHolder() {
subView = new PhotoLineSubView[3];
}
public void reset() {
dateView.setVisibility(View.GONE);
for(PhotoLineSubView view : subView) {
view.reset();
}
}
}
class showMoreListener implements View.OnClickListener {
private int mInterval;
private PhotoLineSubView mView;
private ImageInfo mInfo;
public showMoreListener(int interval, PhotoLineSubView view, ImageInfo imageinfo) {
mInterval = interval;
mView = view;
mInfo = imageinfo;
}
@Override
public void onClick(View v) {
mExpand[mInterval] = true;
notifyDataSetChanged();
mView.reset();
mView.setImageLoader(mImageLoader);
mView.showPhoto(mInfo);
}
}
} |
923877f60f175aff27aa5d78ed6157f5e550dfa1 | 309 | java | Java | org.crap.jrain/org.crap.jrain.core/src/main/java/org/crap/jrain/core/validate/BarScreenFactory.java | craping/crap-all | bc8cccafbd1bd07a24e5d7366d59ca58ad1bdd72 | [
"Apache-2.0"
] | null | null | null | org.crap.jrain/org.crap.jrain.core/src/main/java/org/crap/jrain/core/validate/BarScreenFactory.java | craping/crap-all | bc8cccafbd1bd07a24e5d7366d59ca58ad1bdd72 | [
"Apache-2.0"
] | 9 | 2020-11-16T20:30:31.000Z | 2021-08-25T15:31:40.000Z | org.crap.jrain/org.crap.jrain.core/src/main/java/org/crap/jrain/core/validate/BarScreenFactory.java | craping/crap-all | bc8cccafbd1bd07a24e5d7366d59ca58ad1bdd72 | [
"Apache-2.0"
] | 2 | 2019-07-14T15:28:47.000Z | 2020-06-23T01:29:33.000Z | 17.166667 | 58 | 0.66343 | 998,439 | package org.crap.jrain.core.validate;
/**
* @ClassName: BarScreenFactory
* @Description: 数据屏障工厂接口
* @author Crap
* @date 2017年11月10日
*
*/
public interface BarScreenFactory {
@SuppressWarnings("rawtypes")
public DataBarScreen createDataBarScreen(DataType type);
}
|
9238786640545123b6f2529dfc284cdaa4041265 | 275 | java | Java | src/com/googlecode/totallylazy/io/Destination.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 317 | 2015-01-09T04:59:17.000Z | 2021-11-20T17:34:30.000Z | src/com/googlecode/totallylazy/io/Destination.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 19 | 2015-02-20T13:39:32.000Z | 2021-03-24T21:28:12.000Z | src/com/googlecode/totallylazy/io/Destination.java | danjpgriffin/totallylazy | 0194e4d51c2717f28d34fb7657ef9b29eb189af8 | [
"Apache-2.0"
] | 50 | 2015-01-19T13:00:06.000Z | 2022-02-25T09:43:15.000Z | 25 | 76 | 0.810909 | 998,440 | package com.googlecode.totallylazy.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
public interface Destination extends Closeable {
OutputStream destination(String name, Date modified) throws IOException;
}
|
9238788b4eb1c8db83c00f4ba27760d2b9537be4 | 888 | java | Java | src/main/java/com/google/codeu/servlets/SeeAroundSevlet.java | nanda-thant-sin/team35-codeu | ae6aebbb386e2b128dcfdedfe68259a8d29da0c5 | [
"Apache-2.0"
] | 1 | 2019-06-01T15:20:52.000Z | 2019-06-01T15:20:52.000Z | src/main/java/com/google/codeu/servlets/SeeAroundSevlet.java | nanda-thant-sin/team35-codeu | ae6aebbb386e2b128dcfdedfe68259a8d29da0c5 | [
"Apache-2.0"
] | 22 | 2019-05-24T02:59:53.000Z | 2019-07-28T03:33:34.000Z | src/main/java/com/google/codeu/servlets/SeeAroundSevlet.java | nanda-thant-sin/team35-codeu | ae6aebbb386e2b128dcfdedfe68259a8d29da0c5 | [
"Apache-2.0"
] | 2 | 2019-09-05T22:31:16.000Z | 2019-09-10T10:37:52.000Z | 26.117647 | 97 | 0.780405 | 998,441 | package com.google.codeu.servlets;
import com.google.codeu.data.Datastore;
import com.google.codeu.data.Message;
import com.google.gson.Gson;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/all-messages")
public class SeeAroundSevlet extends HttpServlet {
private Datastore datastore;
@Override
public void init() {
datastore = new Datastore();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
List<Message> m = datastore.getAllMessages();
System.out.println(m);
Gson gson = new Gson();
String json = gson.toJson(m);
response.getOutputStream().println(json);
}
}
|
9238789436d1454cd2568e4a639d3100432a827c | 658 | java | Java | thrift/compiler/test/fixtures/basic-annotations/gen-java/test/fixtures/basicannotations/Constants.java | killight98/fbthrift | c28d5036f96f7eab67c30abadc5ddbe627a11ee3 | [
"Apache-2.0"
] | 2,112 | 2015-01-02T11:34:27.000Z | 2022-03-31T16:30:42.000Z | thrift/compiler/test/fixtures/basic-annotations/gen-java/test/fixtures/basicannotations/Constants.java | killight98/fbthrift | c28d5036f96f7eab67c30abadc5ddbe627a11ee3 | [
"Apache-2.0"
] | 372 | 2015-01-05T10:40:09.000Z | 2022-03-31T20:45:11.000Z | thrift/compiler/test/fixtures/basic-annotations/gen-java/test/fixtures/basicannotations/Constants.java | killight98/fbthrift | c28d5036f96f7eab67c30abadc5ddbe627a11ee3 | [
"Apache-2.0"
] | 582 | 2015-01-03T01:51:56.000Z | 2022-03-31T02:01:09.000Z | 22.689655 | 70 | 0.74772 | 998,442 | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package test.fixtures.basicannotations;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
@SuppressWarnings({ "unused" })
public class Constants {
public static final MyStruct myStruct = new MyStruct();
static {
myStruct.setMajor(42L);
myStruct.setPackage("package");
myStruct.setMy_enum(test.fixtures.basicannotations.MyEnum.DOMAIN);
}
}
|
923878c1fe3103695ac4b314161d423e07bb2c96 | 574 | java | Java | src/main/java/it/fvaleri/clrs3/algorithm/basic/ha/DeterministicHA.java | fvaleri/clrs3 | f3b96458a593971a0806ea322881f1a6b767f40a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/fvaleri/clrs3/algorithm/basic/ha/DeterministicHA.java | fvaleri/clrs3 | f3b96458a593971a0806ea322881f1a6b767f40a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/fvaleri/clrs3/algorithm/basic/ha/DeterministicHA.java | fvaleri/clrs3 | f3b96458a593971a0806ea322881f1a6b767f40a | [
"Apache-2.0"
] | null | null | null | 24.956522 | 57 | 0.543554 | 998,443 | package it.fvaleri.clrs3.algorithm.basic.ha;
/**
* We assume an uniform probability ditribution of input.
* Same inputs lead always to the same results.
* Average-case cost: O(cost*ln(n))
* Worst-case cost: O(cost*n)
*/
public class DeterministicHA implements HAProblem {
@Override
public int execute(int[] a) {
int best = 0;
int hires = 0; // random variable
for (int i = 0; i < a.length; i++) {
if (a[i] > best) {
best = a[i];
hires++;
}
}
return hires;
}
}
|
923879d852a2618ca90f7b59ee731dd94f04ebfb | 3,189 | java | Java | src/main/java/com/alipay/api/request/AlipayCommerceEducateFacefeatureDeleteRequest.java | wongoo/alipay-sdk-java-all | b3c2dd14a8ffba03a2b96a3dd98e4c4a2a11754b | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/request/AlipayCommerceEducateFacefeatureDeleteRequest.java | wongoo/alipay-sdk-java-all | b3c2dd14a8ffba03a2b96a3dd98e4c4a2a11754b | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/request/AlipayCommerceEducateFacefeatureDeleteRequest.java | antopen/alipay-sdk-java-all | 790dea41169e764e3f2e08330800246b4aba1b29 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 23.108696 | 134 | 0.707432 | 998,444 | package com.alipay.api.request;
import com.alipay.api.domain.AlipayCommerceEducateFacefeatureDeleteModel;
import java.util.Map;
import com.alipay.api.AlipayRequest;
import com.alipay.api.internal.util.AlipayHashMap;
import com.alipay.api.response.AlipayCommerceEducateFacefeatureDeleteResponse;
import com.alipay.api.AlipayObject;
/**
* ALIPAY API: alipay.commerce.educate.facefeature.delete request
*
* @author auto create
* @since 1.0, 2021-07-23 15:19:41
*/
public class AlipayCommerceEducateFacefeatureDeleteRequest implements AlipayRequest<AlipayCommerceEducateFacefeatureDeleteResponse> {
private AlipayHashMap udfParams; // add user-defined text parameters
private String apiVersion="1.0";
/**
* 人脸出库接口
*/
private String bizContent;
public void setBizContent(String bizContent) {
this.bizContent = bizContent;
}
public String getBizContent() {
return this.bizContent;
}
private String terminalType;
private String terminalInfo;
private String prodCode;
private String notifyUrl;
private String returnUrl;
private boolean needEncrypt=false;
private AlipayObject bizModel=null;
public String getNotifyUrl() {
return this.notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getReturnUrl() {
return this.returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public void setTerminalType(String terminalType){
this.terminalType=terminalType;
}
public String getTerminalType(){
return this.terminalType;
}
public void setTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public String getTerminalInfo(){
return this.terminalInfo;
}
public void setProdCode(String prodCode) {
this.prodCode=prodCode;
}
public String getProdCode() {
return this.prodCode;
}
public String getApiMethodName() {
return "alipay.commerce.educate.facefeature.delete";
}
public Map<String, String> getTextParams() {
AlipayHashMap txtParams = new AlipayHashMap();
txtParams.put("biz_content", this.bizContent);
if(udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
public void putOtherTextParam(String key, String value) {
if(this.udfParams == null) {
this.udfParams = new AlipayHashMap();
}
this.udfParams.put(key, value);
}
public Class<AlipayCommerceEducateFacefeatureDeleteResponse> getResponseClass() {
return AlipayCommerceEducateFacefeatureDeleteResponse.class;
}
public boolean isNeedEncrypt() {
return this.needEncrypt;
}
public void setNeedEncrypt(boolean needEncrypt) {
this.needEncrypt=needEncrypt;
}
public AlipayObject getBizModel() {
return this.bizModel;
}
public void setBizModel(AlipayObject bizModel) {
this.bizModel=bizModel;
}
}
|
92387a2803a38bea7a91aa0129691b13396cb2b7 | 4,115 | java | Java | modules/core/src/test/java/org/apache/ignite/internal/GridProjectionSelfTest.java | DirectXceriD/apache-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 36 | 2015-11-05T04:46:27.000Z | 2021-12-29T08:26:02.000Z | modules/core/src/test/java/org/apache/ignite/internal/GridProjectionSelfTest.java | gridgain/incubator-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 13 | 2016-08-29T11:54:08.000Z | 2020-12-08T08:47:04.000Z | modules/core/src/test/java/org/apache/ignite/internal/GridProjectionSelfTest.java | gridgain/incubator-ignite | 7972da93f7ca851642fe1fb52723b661e3c3933b | [
"Apache-2.0"
] | 15 | 2016-03-18T09:25:39.000Z | 2021-10-01T05:49:39.000Z | 28.184932 | 91 | 0.608991 | 998,445 | /*
* 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.ignite.internal;
import org.apache.ignite.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.testframework.junits.common.*;
import java.util.*;
/**
* Test for {@link org.apache.ignite.cluster.ClusterGroup}.
*/
@GridCommonTest(group = "Kernal Self")
public class GridProjectionSelfTest extends GridProjectionAbstractTest {
/** Nodes count. */
private static final int NODES_CNT = 4;
/** Projection node IDs. */
private static Collection<UUID> ids;
/** */
private static Ignite ignite;
/** {@inheritDoc} */
@SuppressWarnings({"ConstantConditions"})
@Override protected void beforeTestsStarted() throws Exception {
assert NODES_CNT > 2;
ids = new LinkedList<>();
for (int i = 0; i < NODES_CNT; i++) {
Ignite g = startGrid(i);
ids.add(g.cluster().localNode().id());
if (i == 0)
ignite = g;
}
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
for (int i = 0; i < NODES_CNT; i++)
stopGrid(i);
}
/** {@inheritDoc} */
@Override protected ClusterGroup projection() {
return grid(0).cluster().forPredicate(F.nodeForNodeIds(ids));
}
/** {@inheritDoc} */
@Override protected UUID localNodeId() {
return grid(0).localNode().id();
}
/**
* @throws Exception If failed.
*/
public void testRandom() throws Exception {
assertTrue(ignite.cluster().nodes().contains(ignite.cluster().forRandom().node()));
}
/**
* @throws Exception If failed.
*/
public void testOldest() throws Exception {
ClusterGroup oldest = ignite.cluster().forOldest();
ClusterNode node = null;
long minOrder = Long.MAX_VALUE;
for (ClusterNode n : ignite.cluster().nodes()) {
if (n.order() < minOrder) {
node = n;
minOrder = n.order();
}
}
assertEquals(oldest.node(), ignite.cluster().forNode(node).node());
}
/**
* @throws Exception If failed.
*/
public void testYoungest() throws Exception {
ClusterGroup youngest = ignite.cluster().forYoungest();
ClusterNode node = null;
long maxOrder = Long.MIN_VALUE;
for (ClusterNode n : ignite.cluster().nodes()) {
if (n.order() > maxOrder) {
node = n;
maxOrder = n.order();
}
}
assertEquals(youngest.node(), ignite.cluster().forNode(node).node());
}
/**
* @throws Exception If failed.
*/
public void testNewNodes() throws Exception {
ClusterGroup youngest = ignite.cluster().forYoungest();
ClusterGroup oldest = ignite.cluster().forOldest();
ClusterNode old = oldest.node();
ClusterNode last = youngest.node();
assertNotNull(last);
try (Ignite g = startGrid(NODES_CNT)) {
ClusterNode n = g.cluster().localNode();
ClusterNode latest = youngest.node();
assertNotNull(latest);
assertEquals(latest.id(), n.id());
assertEquals(oldest.node(), old);
}
}
}
|
92387a36e5841ddf158f308f984cdf4c7ba93f0a | 709 | java | Java | sapjco-spring/src/main/java/cn/gitlab/virtualcry/sapjco/spring/context/annotation/JCoComponentScans.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | 3 | 2019-07-06T06:29:02.000Z | 2021-08-30T06:44:06.000Z | sapjco-spring/src/main/java/cn/gitlab/virtualcry/sapjco/spring/context/annotation/JCoComponentScans.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | null | null | null | sapjco-spring/src/main/java/cn/gitlab/virtualcry/sapjco/spring/context/annotation/JCoComponentScans.java | VirtualCry/sapjco-spring | 48937b94201fd79a0c10d83118803932a6261219 | [
"Apache-2.0"
] | 4 | 2019-07-06T06:29:52.000Z | 2021-04-11T23:45:07.000Z | 30.826087 | 90 | 0.777151 | 998,446 | package cn.gitlab.virtualcry.sapjco.spring.context.annotation;
import java.lang.annotation.*;
/**
* Container annotation that aggregates several {@link JCoComponentScan} annotations.
*
* <p>Can be used natively, declaring several nested {@link JCoComponentScan} annotations.
* Can also be used in conjunction with Java 8's support for repeatable annotations,
* where {@link JCoComponentScan} can simply be declared several times on the same method,
* implicitly generating this container annotation.
*
* @author VirtualCry
* @see JCoComponentScan
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface JCoComponentScans {
JCoComponentScan[] value();
}
|
92387af9b147a2ec8aaca474919f14b3526a34ce | 2,851 | java | Java | com.onpositive.text.analisys/src/com/onpositive/text/analysis/syntax/VerbParticleParser.java | 32kda/com.onpositive.textresearch | a183c9f62e0fae528e2cdbeffb95ad8d271424e5 | [
"Apache-2.0"
] | null | null | null | com.onpositive.text.analisys/src/com/onpositive/text/analysis/syntax/VerbParticleParser.java | 32kda/com.onpositive.textresearch | a183c9f62e0fae528e2cdbeffb95ad8d271424e5 | [
"Apache-2.0"
] | null | null | null | com.onpositive.text.analisys/src/com/onpositive/text/analysis/syntax/VerbParticleParser.java | 32kda/com.onpositive.textresearch | a183c9f62e0fae528e2cdbeffb95ad8d271424e5 | [
"Apache-2.0"
] | null | null | null | 27.95098 | 94 | 0.748159 | 998,447 | package com.onpositive.text.analysis.syntax;
import java.util.ArrayList;
import java.util.Stack;
import com.onpositive.semantic.wordnet.AbstractWordNet;
import com.onpositive.semantic.wordnet.Grammem.PartOfSpeech;
import com.onpositive.text.analysis.IToken;
public class VerbParticleParser extends AbstractSyntaxParser {
public VerbParticleParser(AbstractWordNet wordNet) {
super(wordNet);
}
@Override
protected void combineTokens(Stack<IToken> sample, ProcessingData processingData) {
if(sample.size()<2){
return;
}
SyntaxToken token0 = (SyntaxToken) sample.get(0);
SyntaxToken token1 = (SyntaxToken) sample.get(1);
if(checkIfAlreadyProcessed(token0, token1)) {
return;
}
ArrayList<IToken> rawTokens = matchMeanings(token0, token1);
ArrayList<IToken> tokens = new ArrayList<IToken>();
for(IToken newToken : rawTokens){
if(checkParents(newToken,sample)){
tokens.add(newToken);
}
}
if(tokens.size()==1){
processingData.addReliableToken(tokens.get(0));
}
else if(!tokens.isEmpty()){
processingData.addDoubtfulTokens(tokens);
}
}
private ArrayList<IToken> matchMeanings(SyntaxToken token0, SyntaxToken token1)
{
int startPosition = token0.getStartPosition();
int endPosition = token1.getEndPosition();
int tokenType = IToken.TOKEN_TYPE_VERB_PARTICLE;
ArrayList<IToken> tokens = new ArrayList<IToken>();
if(token0.hasGrammem(PartOfSpeech.PRCL)&&token1.hasGrammem(PartOfSpeech.VERB)){
tokens.add(new SyntaxToken(tokenType, token1, null, startPosition, endPosition));
}
if(token0.hasGrammem(PartOfSpeech.VERB)&&token1.hasGrammem(PartOfSpeech.PRCL)){
tokens.add(new SyntaxToken(tokenType, token0, null, startPosition, endPosition));
}
return tokens;
}
protected ProcessingResult continuePush(Stack<IToken> sample,IToken newToken) {
if(!(newToken instanceof SyntaxToken)){
return DO_NOT_ACCEPT_AND_BREAK;
}
SyntaxToken token1 = (SyntaxToken) newToken;
if (isPrepOrConj(token1)) return DO_NOT_ACCEPT_AND_BREAK;
SyntaxToken token0 = (SyntaxToken) sample.peek();
if(token0.hasGrammem(PartOfSpeech.VERB)){
if(token1.hasGrammem(PartOfSpeech.PRCL)){
return ACCEPT_AND_BREAK;
}
}
if(token1.hasGrammem(PartOfSpeech.VERB)){
if(token0.hasGrammem(PartOfSpeech.PRCL)){
return ACCEPT_AND_BREAK;
}
}
return DO_NOT_ACCEPT_AND_BREAK;
}
@Override
protected ProcessingResult checkToken(IToken newToken) {
if(!(newToken instanceof SyntaxToken)){
return DO_NOT_ACCEPT_AND_BREAK;
}
SyntaxToken token = (SyntaxToken) newToken;
if (isPrepOrConj(token)) return DO_NOT_ACCEPT_AND_BREAK;
if (token.hasGrammem(PartOfSpeech.VERB)) return CONTINUE_PUSH;
if (token.hasGrammem(PartOfSpeech.PRCL) && isVerbParticiple(newToken)) return CONTINUE_PUSH;
return DO_NOT_ACCEPT_AND_BREAK;
}
}
|
92387b5a7ab7375367e9645a4549801df9f14b73 | 579 | java | Java | Gemma/src/com/puttysoftware/gemma/battle/ArrowSpeedConstants.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | null | null | null | Gemma/src/com/puttysoftware/gemma/battle/ArrowSpeedConstants.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | null | null | null | Gemma/src/com/puttysoftware/gemma/battle/ArrowSpeedConstants.java | wrldwzrd89/older-java-games | 786b0c165d800c49ab9977a34ec17286797c4589 | [
"Unlicense"
] | null | null | null | 24.458333 | 87 | 0.70017 | 998,448 | /* Gemma: An RPG
Copyright (C) 2013-2014 Eric Ahnell
Any questions should be directed to the author via email at: ychag@example.com
*/
package com.puttysoftware.gemma.battle;
import com.puttysoftware.gemma.prefs.PreferencesManager;
class ArrowSpeedConstants {
// Constants
private static int ARROW_SPEED_FACTOR = 6;
// Constructor
private ArrowSpeedConstants() {
// Do nothing
}
// Method
static int getArrowSpeed() {
return PreferencesManager.getBattleSpeed()
/ ArrowSpeedConstants.ARROW_SPEED_FACTOR;
}
} |
92387beeeadec8e404d0f7edb5c3bd3fdbed1343 | 385 | java | Java | nondex-maven-plugin/src/it/excluded-groups-it/module2/src/test/java/edu/illinois/nondex/it/ExcludedGroupsTest.java | huangchengmin97/NonDex | 1739aab7659c4ae1fcf7fa601f87d8d379c24560 | [
"MIT"
] | 20 | 2016-09-09T19:03:13.000Z | 2022-01-22T16:14:27.000Z | nondex-maven-plugin/src/it/excluded-groups-it/module2/src/test/java/edu/illinois/nondex/it/ExcludedGroupsTest.java | huangchengmin97/NonDex | 1739aab7659c4ae1fcf7fa601f87d8d379c24560 | [
"MIT"
] | 64 | 2016-05-26T19:10:07.000Z | 2021-12-02T16:45:43.000Z | nondex-maven-plugin/src/it/excluded-groups-it/module2/src/test/java/edu/illinois/nondex/it/ExcludedGroupsTest.java | huangchengmin97/NonDex | 1739aab7659c4ae1fcf7fa601f87d8d379c24560 | [
"MIT"
] | 35 | 2016-05-25T22:13:43.000Z | 2021-11-16T04:29:00.000Z | 22.647059 | 50 | 0.758442 | 998,449 | package edu.illinois.nondex.it;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.HashSet;
public class ExcludedGroupsTest {
@Test
@Category(edu.illinois.NonDexIgnore.class)
public void testNonDexIgnore() {
assertFalse(true);
}
}
|
92387d1ff2eaf11db68d821285e548629b4da7f6 | 318 | java | Java | src/main/java/com/kucess/notebook/NotebookApplication.java | KUCESS/Notebook | 5ff528106c72ced73a3afe249a2b2c9131fea13b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/kucess/notebook/NotebookApplication.java | KUCESS/Notebook | 5ff528106c72ced73a3afe249a2b2c9131fea13b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/kucess/notebook/NotebookApplication.java | KUCESS/Notebook | 5ff528106c72ced73a3afe249a2b2c9131fea13b | [
"Apache-2.0"
] | null | null | null | 22.714286 | 68 | 0.81761 | 998,450 | package com.kucess.notebook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NotebookApplication {
public static void main(String[] args) {
SpringApplication.run(NotebookApplication.class, args);
}
}
|
92387d6b0c08956d61057a196cc8305e8ec35e30 | 157 | java | Java | src/net/ichatter/pattern/proxy/statics/Vehicle.java | ichatter/design-patterns | 8aeb1a4c563e48055f19da52acdd4f32755981c2 | [
"MIT"
] | 4 | 2020-02-05T15:32:07.000Z | 2020-02-18T11:12:04.000Z | src/net/ichatter/pattern/proxy/statics/Vehicle.java | ichatter/design-patterns | 8aeb1a4c563e48055f19da52acdd4f32755981c2 | [
"MIT"
] | null | null | null | src/net/ichatter/pattern/proxy/statics/Vehicle.java | ichatter/design-patterns | 8aeb1a4c563e48055f19da52acdd4f32755981c2 | [
"MIT"
] | null | null | null | 13.083333 | 44 | 0.605096 | 998,451 | package net.ichatter.pattern.proxy.statics;
/**
* A vehicle can run.
*
* @author yzy
*
*/
public interface Vehicle {
public void run();
}
|
92387ecf219e3529903c9abfef6196221a60d130 | 3,854 | java | Java | src/main/java/net/tirasa/batch/rest/poc/batch/server/BatchItemRequest.java | ilgrosso/batch-rest-poc | 46cb2e64bf0bd8bcd15f1d024c6df4325f8bd7a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/tirasa/batch/rest/poc/batch/server/BatchItemRequest.java | ilgrosso/batch-rest-poc | 46cb2e64bf0bd8bcd15f1d024c6df4325f8bd7a3 | [
"Apache-2.0"
] | 3 | 2018-07-24T09:18:32.000Z | 2018-08-02T09:32:22.000Z | src/main/java/net/tirasa/batch/rest/poc/batch/server/BatchItemRequest.java | ilgrosso/batch-rest-poc | 46cb2e64bf0bd8bcd15f1d024c6df4325f8bd7a3 | [
"Apache-2.0"
] | null | null | null | 30.109375 | 117 | 0.635703 | 998,452 | package net.tirasa.batch.rest.poc.batch.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.stream.Collectors;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.ws.rs.core.HttpHeaders;
import net.tirasa.batch.rest.poc.batch.BatchRequestItem;
import org.springframework.http.MediaType;
public class BatchItemRequest extends HttpServletRequestWrapper {
private final String basePath;
private final BatchRequestItem batchItem;
private final ServletInputStream inputStream;
public BatchItemRequest(
final String basePath,
final HttpServletRequest request,
final BatchRequestItem batchItem) {
super(request);
this.basePath = basePath;
this.batchItem = batchItem;
this.inputStream = new ServletInputStream() {
private final ByteArrayInputStream bais = new ByteArrayInputStream(batchItem.getContent().getBytes());
private boolean isFinished = false;
private boolean isReady = true;
@Override
public boolean isFinished() {
return isFinished;
}
@Override
public boolean isReady() {
return isReady;
}
@Override
public void setReadListener(final ReadListener readListener) {
// nope
}
@Override
public int read() {
isFinished = true;
isReady = false;
return bais.read();
}
};
}
@Override
public String getMethod() {
return batchItem.getMethod();
}
@Override
public StringBuffer getRequestURL() {
return new StringBuffer(basePath).append(getRequestURI());
}
@Override
public String getRequestURI() {
return batchItem.getRequestURI();
}
@Override
public String getQueryString() {
return batchItem.getQueryString();
}
@Override
public String getContentType() {
return batchItem.getHeaders().containsKey(HttpHeaders.CONTENT_TYPE)
? batchItem.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0).toString()
: MediaType.ALL_VALUE;
}
@Override
public int getContentLength() {
return batchItem.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)
? Integer.valueOf(batchItem.getHeaders().get(HttpHeaders.CONTENT_LENGTH).get(0).toString())
: 0;
}
@Override
public long getContentLengthLong() {
return getContentLength();
}
@Override
public String getHeader(final String name) {
return batchItem.getHeaders().containsKey(name)
? batchItem.getHeaders().get(name).get(0).toString()
: HttpHeaders.CONTENT_TYPE.equals(name) || HttpHeaders.ACCEPT.equals(name)
? MediaType.ALL_VALUE
: super.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(final String name) {
return batchItem.getHeaders().containsKey(name)
? Collections.enumeration(
batchItem.getHeaders().get(name).stream().map(Object::toString).collect(Collectors.toList()))
: HttpHeaders.CONTENT_TYPE.equals(name) || HttpHeaders.ACCEPT.equals(name)
? Collections.enumeration(Arrays.asList(MediaType.ALL_VALUE))
: super.getHeaders(name);
}
@Override
public ServletInputStream getInputStream() throws IOException {
return inputStream;
}
}
|
92387f9369c62d01fef496e7874b0264b97bc41a | 4,241 | java | Java | Onnuri/app/src/main/java/com/example/changk/urionnuri/storedetail/MapActivity.java | MobileSeoul/2016seoul-03 | 94a13dd4fb81e4862c4b63251e54a81e1e697f07 | [
"MIT"
] | 2 | 2019-05-23T00:57:15.000Z | 2019-05-23T00:58:00.000Z | Onnuri/app/src/main/java/com/example/changk/urionnuri/storedetail/MapActivity.java | MobileSeoul/2016seoul-03 | 94a13dd4fb81e4862c4b63251e54a81e1e697f07 | [
"MIT"
] | null | null | null | Onnuri/app/src/main/java/com/example/changk/urionnuri/storedetail/MapActivity.java | MobileSeoul/2016seoul-03 | 94a13dd4fb81e4862c4b63251e54a81e1e697f07 | [
"MIT"
] | 2 | 2019-05-23T00:57:16.000Z | 2020-10-07T01:27:42.000Z | 37.530973 | 259 | 0.709738 | 998,453 | package com.example.changk.urionnuri.storedetail;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.changk.urionnuri.BaseActivity;
import com.example.changk.urionnuri.R;
import com.example.changk.urionnuri.model.Store;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* Created by hoc on 2016-10-19.
*/
public class MapActivity extends BaseActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Store store;
private double lati, longi;
private TextView map_location;
private CameraPosition cameraPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
map_location = (TextView)findViewById(R.id.map_location);
map_location.setOnClickListener(onClickListener);
LinearLayout market_layout = (LinearLayout) findViewById(R.id.market_layout);
market_layout.setVisibility(View.GONE);
Intent intent = getIntent();
store = (Store) intent.getSerializableExtra("store");
lati = store.getLoc_lati();
longi = store.getLoc_longi();
ImageView map_back = (ImageView) findViewById(R.id.map_back);
Glide.with(this).load(R.drawable.back).thumbnail(0.1f).into(map_back);
map_back.setOnClickListener(onClickListener);
ImageView marketSeatch_img=(ImageView)findViewById(R.id.marketSeatch_img);
Glide.with(this).load(R.drawable.placholder).thumbnail(0.1f).into(marketSeatch_img);
ImageView mappin=(ImageView)findViewById(R.id.mappin);
Glide.with(this).load(R.drawable.mappin).thumbnail(0.1f).into(mappin);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng storeLocation = new LatLng(lati, longi);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(store.getName());
markerOptions.position(storeLocation);
mMap.addMarker(markerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(storeLocation));
mMap.setMyLocationEnabled(true);
cameraPosition = CameraPosition.builder()
.target(storeLocation)
.zoom(15)
.build();
// Animate the change in camera view over 2 seconds
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mMap.clear();
}
private final View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId()==R.id.map_back){
finish();
}if(v.getId()==R.id.map_location){
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
};
}
|
92387fe1fee8aa7989d03bfbcbc5aa589c0b4477 | 937 | java | Java | qbit/core/src/main/java/io/advantageous/qbit/service/BeforeMethodCallChain.java | advantageous/qbit | 533b3671785f238d576b02b5290c6525ed60f583 | [
"Apache-2.0"
] | 789 | 2015-02-05T23:44:19.000Z | 2022-02-16T12:36:06.000Z | qbit/core/src/main/java/io/advantageous/qbit/service/BeforeMethodCallChain.java | gaecom/qbit | 533b3671785f238d576b02b5290c6525ed60f583 | [
"Apache-2.0"
] | 623 | 2015-01-17T21:43:13.000Z | 2021-12-10T05:30:28.000Z | qbit/core/src/main/java/io/advantageous/qbit/service/BeforeMethodCallChain.java | gaecom/qbit | 533b3671785f238d576b02b5290c6525ed60f583 | [
"Apache-2.0"
] | 172 | 2015-01-09T21:47:28.000Z | 2022-02-27T14:51:28.000Z | 28.393939 | 102 | 0.731057 | 998,454 | package io.advantageous.qbit.service;
import io.advantageous.qbit.message.MethodCall;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BeforeMethodCallChain implements BeforeMethodCall {
private final List<BeforeMethodCall> beforeMethodCallList;
public BeforeMethodCallChain(List<BeforeMethodCall> beforeMethodCallList) {
this.beforeMethodCallList = Collections.unmodifiableList(beforeMethodCallList);
}
public static BeforeMethodCallChain beforeMethodCallChain(BeforeMethodCall... beforeMethodCalls) {
return new BeforeMethodCallChain(Arrays.asList(beforeMethodCalls));
}
@Override
public boolean before(final MethodCall call) {
for (final BeforeMethodCall beforeMethodCall : beforeMethodCallList) {
if (!beforeMethodCall.before(call)) {
return false;
}
}
return true;
}
}
|
9238803a86378ab235ce79770c33e74ca72d873c | 339 | java | Java | Backend/src/main/java/com/github/francisfire/anavis/repository/PrenotationRepository.java | FrancisFire/AnAVIS | c42a338eb9ddf152a7e56116fcd9273be48db547 | [
"MIT"
] | 1 | 2020-02-20T16:48:49.000Z | 2020-02-20T16:48:49.000Z | Backend/src/main/java/com/github/francisfire/anavis/repository/PrenotationRepository.java | ZamponiMarco/AnAVIS | c42a338eb9ddf152a7e56116fcd9273be48db547 | [
"MIT"
] | null | null | null | Backend/src/main/java/com/github/francisfire/anavis/repository/PrenotationRepository.java | ZamponiMarco/AnAVIS | c42a338eb9ddf152a7e56116fcd9273be48db547 | [
"MIT"
] | 4 | 2020-06-29T12:58:17.000Z | 2021-02-24T13:30:41.000Z | 33.9 | 91 | 0.864307 | 998,455 | package com.github.francisfire.anavis.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.github.francisfire.anavis.models.ActivePrenotation;
@Repository
public interface PrenotationRepository extends MongoRepository<ActivePrenotation, String> {
} |
92388062ea7b5bdf6b7ad3259e1d74c3387bf837 | 616 | java | Java | src/test/java/org/algorithms/coding_patterns/educative/modified_binary_search/NextLetterTest.java | vot-developer/practice | 1f2de69836069eceeffb88919a7866643a1dd7f6 | [
"MIT"
] | null | null | null | src/test/java/org/algorithms/coding_patterns/educative/modified_binary_search/NextLetterTest.java | vot-developer/practice | 1f2de69836069eceeffb88919a7866643a1dd7f6 | [
"MIT"
] | null | null | null | src/test/java/org/algorithms/coding_patterns/educative/modified_binary_search/NextLetterTest.java | vot-developer/practice | 1f2de69836069eceeffb88919a7866643a1dd7f6 | [
"MIT"
] | null | null | null | 38.5 | 95 | 0.618506 | 998,456 | package org.algorithms.coding_patterns.educative.modified_binary_search;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class NextLetterTest {
@Test
void searchNextLetter() {
assertEquals('h', NextLetter.searchNextLetter(new char[] { 'a', 'c', 'f', 'h' }, 'f'));
assertEquals('c', NextLetter.searchNextLetter(new char[] { 'a', 'c', 'f', 'h' }, 'b'));
assertEquals('a', NextLetter.searchNextLetter(new char[] { 'a', 'c', 'f', 'h' }, 'm'));
assertEquals('a', NextLetter.searchNextLetter(new char[] { 'a', 'c', 'f', 'h' }, 'h'));
}
} |
9238810bec02e2f7e12b1e4beabead0641c73254 | 385 | java | Java | learn-design/src/main/java/com/xp/bird/Ostrich.java | xp-zhao/learn-java | 49a76ae8043ce7ceb641ce6f0e094059d8ba9b55 | [
"MIT"
] | 1 | 2018-12-07T02:43:06.000Z | 2018-12-07T02:43:06.000Z | learn-design/src/main/java/com/xp/bird/Ostrich.java | xp-zhao/learn-java | 49a76ae8043ce7ceb641ce6f0e094059d8ba9b55 | [
"MIT"
] | 16 | 2020-05-15T19:23:08.000Z | 2022-03-31T18:48:42.000Z | learn-design/src/main/java/com/xp/bird/Ostrich.java | xp-zhao/learn-java | 49a76ae8043ce7ceb641ce6f0e094059d8ba9b55 | [
"MIT"
] | null | null | null | 16.73913 | 55 | 0.65974 | 998,457 | package com.xp.bird;
/**
* @author zhaoxiaoping
* @Description: 鸵鸟
* @Date 2020/4/3
**/
public class Ostrich implements Tweetable, EggLayable {
private EggLayAbility eggLay = new EggLayAbility();
private TweetAbility tweet = new TweetAbility();
@Override
public void layEgg() {
eggLay.layEgg();
}
@Override
public void tweet() {
tweet.tweet();
}
}
|
9238813aa051acc05974460348bf1cf91626f135 | 1,972 | java | Java | src/test/java/com/codeup/application/actions/AddMovieActionTest.java | MontealegreLuis/hibernate-example | 817691eb4c91ba26edbd906cc22cc0c2ec28f447 | [
"MIT"
] | null | null | null | src/test/java/com/codeup/application/actions/AddMovieActionTest.java | MontealegreLuis/hibernate-example | 817691eb4c91ba26edbd906cc22cc0c2ec28f447 | [
"MIT"
] | null | null | null | src/test/java/com/codeup/application/actions/AddMovieActionTest.java | MontealegreLuis/hibernate-example | 817691eb4c91ba26edbd906cc22cc0c2ec28f447 | [
"MIT"
] | null | null | null | 29.878788 | 100 | 0.725152 | 998,458 | /**
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup.application.actions;
import com.codeup.application.MoviesConsole;
import com.codeup.movies.Categories;
import com.codeup.movies.Category;
import com.codeup.movies.catalog.AddMovie;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AddMovieActionTest {
@Test
public void it_adds_a_new_movie() {
String title = "Casablanca";
int rating = 5;
String thumbnail = "casablanca.png";
when(categories.all()).thenReturn(allCategories);
when(console.askForMovieTitle()).thenReturn(title);
when(console.askForMovieRating()).thenReturn(rating);
when(console.askForThumbnail()).thenReturn(thumbnail);
when(console.chooseCategories(allCategories)).thenReturn(selectedCategories);
action.execute();
verify(addMovie).withDetails(title, rating, thumbnail, selectedCategories);
}
@Before
public void configureAction() {
Category drama = Category.named("drama");
Category musical = Category.named("musical");
Category animated = Category.named("animated");
allCategories = Arrays.asList(drama, musical, animated);
selectedCategories = Collections.singletonList(drama);
action = new AddMovieAction(addMovie, console, categories);
}
private AddMovieAction action;
private List<Category> allCategories;
private List<Category> selectedCategories;
@Mock
private AddMovie addMovie;
@Mock
private MoviesConsole console;
@Mock
private Categories categories;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.