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
9235e4bb5314b22b1a6d4fef648f53b88067e968
370
java
Java
src/main/java/mx/edx/com/cxf/spring/ServiceCXF.java
edwardX/ApacheCXF-Spring_wsdl2java
6e40e78a8794d787f894cd8327f24bb14e64e075
[ "MIT" ]
null
null
null
src/main/java/mx/edx/com/cxf/spring/ServiceCXF.java
edwardX/ApacheCXF-Spring_wsdl2java
6e40e78a8794d787f894cd8327f24bb14e64e075
[ "MIT" ]
null
null
null
src/main/java/mx/edx/com/cxf/spring/ServiceCXF.java
edwardX/ApacheCXF-Spring_wsdl2java
6e40e78a8794d787f894cd8327f24bb14e64e075
[ "MIT" ]
null
null
null
17.619048
66
0.621622
997,455
package mx.edx.com.cxf.spring; import javax.jws.WebParam; import javax.jws.WebService; /** * * @author edx */ @WebService public interface ServiceCXF { /** * We are using sayHiInput as is declared in WSDL * @param sayHi * @return sampleResponse */ String hiFromCXF(@WebParam(name="sayHiInput") String sayHi); }
9235e63d272989866600fb522c4f36e92786ca50
808
java
Java
android/TrakamCameraStuff/app/src/main/java/com/trakam/activities/CapturePreviewActivity.java
AnthonyLam/Trakam
6c8d941bcea5ba0857c61ac3071e55387b0f2777
[ "MIT" ]
2
2017-12-11T10:13:04.000Z
2020-01-28T22:51:51.000Z
android/TrakamCameraStuff/app/src/main/java/com/trakam/activities/CapturePreviewActivity.java
AnthonyLam/Trakam
6c8d941bcea5ba0857c61ac3071e55387b0f2777
[ "MIT" ]
6
2017-12-15T04:15:37.000Z
2021-09-07T23:48:47.000Z
android/TrakamCameraStuff/app/src/main/java/com/trakam/activities/CapturePreviewActivity.java
AnthonyLam/Trakam
6c8d941bcea5ba0857c61ac3071e55387b0f2777
[ "MIT" ]
null
null
null
31.076923
85
0.763614
997,456
package com.trakam.activities; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.widget.ImageView; import com.trakam.R; public class CapturePreviewActivity extends Activity { public static final String TAG = CapturePreviewActivity.class.getCanonicalName(); public static final String BITMAP_EXTRA = TAG + "_bitmap_extra"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.capture_preview_activity); final ImageView imageView = findViewById(R.id.imageView); final Bitmap bitmap = getIntent().getParcelableExtra(BITMAP_EXTRA); imageView.setImageBitmap(bitmap); } }
9235e784437598bb69db663f0235a9e2abe2d76a
8,875
java
Java
app/src/main/java/org/loader/liteplayer/activity/MainActivity.java
longyinzaitian/-LitePlayer
5834cc4568485e5e67a42b08515450e585806502
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/loader/liteplayer/activity/MainActivity.java
longyinzaitian/-LitePlayer
5834cc4568485e5e67a42b08515450e585806502
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/loader/liteplayer/activity/MainActivity.java
longyinzaitian/-LitePlayer
5834cc4568485e5e67a42b08515450e585806502
[ "Apache-2.0" ]
null
null
null
39.620536
109
0.481127
997,457
package org.loader.liteplayer.activity; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NavUtils; import android.widget.CompoundButton; import android.widget.RadioButton; import org.loader.liteplayer.R; import org.loader.liteplayer.application.AppUtil; import org.loader.liteplayer.fragment.HomePageFragment; import org.loader.liteplayer.fragment.MinePageFragment; import org.loader.liteplayer.fragment.NetSongFragment; import org.loader.liteplayer.service.PlayService; /** * 2015年8月15日 16:34:37 * 博文地址:http://blog.csdn.net/u010156024 * @author longyinzaitian */ public class MainActivity extends BaseActivity { private RadioButton mRbHomePage; private RadioButton mRbNetworkPage; private RadioButton mRbMinePage; private Fragment mPreShowFrm; private FragmentManager fragmentManager = getSupportFragmentManager(); /** * 获取音乐播放服务 */ public PlayService getPlayService() { return mPlayService; } public void onClick(int id) { mRbHomePage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.black)); mRbNetworkPage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.black)); mRbMinePage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.black)); Fragment fragment; FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); switch (id) { //网络歌曲页 case R.id.ac_rb_network_page: mRbNetworkPage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.springgreen)); fragment = fragmentManager.findFragmentByTag("NETWORK_PAGE"); if (fragment == null) { fragment = NetSongFragment.getInstance(); if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .add(R.id.am_content, fragment, "NETWORK_PAGE") .commitAllowingStateLoss(); } else { fragmentTransaction .add(R.id.am_content, fragment, "NETWORK_PAGE") .commitAllowingStateLoss(); } } else { fragmentTransaction .add(R.id.am_content, fragment, "NETWORK_PAGE") .commitAllowingStateLoss(); } } else { if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .show(fragment) .commitAllowingStateLoss(); } else { fragmentTransaction .show(fragment) .commitAllowingStateLoss(); } } } mPreShowFrm = fragment; break; //我的页 case R.id.ac_rb_mine_page: mRbMinePage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.springgreen)); fragment = fragmentManager.findFragmentByTag("MINE_PAGE"); if (fragment == null) { fragment = MinePageFragment.getInstance(); if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .add(R.id.am_content, fragment, "MINE_PAGE") .commitAllowingStateLoss(); } else { fragmentTransaction .add(R.id.am_content, fragment, "MINE_PAGE") .commitAllowingStateLoss(); } } else { fragmentTransaction .add(R.id.am_content, fragment, "MINE_PAGE") .commitAllowingStateLoss(); } } else { if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .show(fragment) .commitAllowingStateLoss(); } else { fragmentTransaction .show(fragment) .commitAllowingStateLoss(); } } } mPreShowFrm = fragment; break; //首页 case R.id.ac_rb_home_page: mRbHomePage.setTextColor(ActivityCompat.getColor(MainActivity.this, R.color.springgreen)); fragment = fragmentManager.findFragmentByTag("HOME_PAGE"); if (fragment == null) { fragment = HomePageFragment.getInstance(); if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .add(R.id.am_content, fragment, "HOME_PAGE") .commitAllowingStateLoss(); } else { fragmentTransaction .add(R.id.am_content, fragment, "HOME_PAGE") .commitAllowingStateLoss(); } } else { fragmentTransaction .add(R.id.am_content, fragment, "HOME_PAGE") .commitAllowingStateLoss(); } } else { if (mPreShowFrm != null) { if (mPreShowFrm != fragment) { fragmentTransaction .hide(mPreShowFrm) .show(fragment) .commitAllowingStateLoss(); } else { fragmentTransaction .show(fragment) .commitAllowingStateLoss(); } } } mPreShowFrm = fragment; break; default: break; } } @Override protected int getLayoutId() { return R.layout.activity_main; } @Override protected void bindView() { setupViews(); } private void setupViews() { mRbHomePage = findViewById(R.id.ac_rb_home_page); mRbNetworkPage = findViewById(R.id.ac_rb_network_page); mRbMinePage = findViewById(R.id.ac_rb_mine_page); mRbMinePage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { onClick(R.id.ac_rb_mine_page); } } }); mRbNetworkPage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { onClick(R.id.ac_rb_network_page); } } }); mRbHomePage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { onClick(R.id.ac_rb_home_page); } } }); onClick(R.id.ac_rb_home_page); } @Override protected void bindListener() { } @Override protected void loadData() { } @Override protected void clearData() { mPreShowFrm = null; AppUtil.getInstance().removeAllActivity(); } }
9235e7f46cf052fe6e50567a03c2b427476a9e3e
10,786
java
Java
jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/xloader/ProcIngestDataX.java
pauloaug/jena
e071927d24af6c4738edc2e7c06bac237e710cb2
[ "Apache-2.0" ]
null
null
null
jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/xloader/ProcIngestDataX.java
pauloaug/jena
e071927d24af6c4738edc2e7c06bac237e710cb2
[ "Apache-2.0" ]
null
null
null
jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/xloader/ProcIngestDataX.java
pauloaug/jena
e071927d24af6c4738edc2e7c06bac237e710cb2
[ "Apache-2.0" ]
null
null
null
38.248227
125
0.600593
997,458
/* * 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.jena.tdb2.xloader; import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.apache.jena.atlas.io.IO; import org.apache.jena.atlas.json.JSON; import org.apache.jena.atlas.json.JsonObject; import org.apache.jena.atlas.lib.BitsLong; import org.apache.jena.atlas.lib.DateTimeUtils; import org.apache.jena.atlas.lib.Pair; import org.apache.jena.atlas.lib.Timer; import org.apache.jena.atlas.logging.FmtLog; import org.apache.jena.dboe.base.file.Location; import org.apache.jena.dboe.sys.Names; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.irix.IRIProvider; import org.apache.jena.irix.SystemIRIx; import org.apache.jena.riot.system.AsyncParser; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.sparql.core.DatasetGraph; import org.apache.jena.sparql.core.Quad; import org.apache.jena.system.progress.ProgressMonitor; import org.apache.jena.system.progress.ProgressMonitorOutput; import org.apache.jena.tdb2.DatabaseMgr; import org.apache.jena.tdb2.solver.stats.Stats; import org.apache.jena.tdb2.solver.stats.StatsCollectorNodeId; import org.apache.jena.tdb2.store.DatasetGraphTDB; import org.apache.jena.tdb2.store.NodeId; import org.apache.jena.tdb2.store.nodetable.NodeTable; import org.apache.jena.tdb2.store.nodetupletable.NodeTupleTable; import org.apache.jena.tdb2.store.value.DoubleNode62; import org.apache.jena.tdb2.sys.TDBInternal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Create the Node table and write the triples/quads temporary files */ public class ProcIngestDataX { // See also TDB1 ProcNodeTableBuilder private static Logger LOG = LoggerFactory.getLogger("Data"); // Node Table. public static void exec(String location, XLoaderFiles loaderFiles, List<String> datafiles, boolean collectStats) { // Possible parser speed up. This has no effect if parsing in parallel // because the parser isn't the slowest step when loading at scale. IRIProvider provider = SystemIRIx.getProvider(); //SystemIRIx.setProvider(new IRIProviderAny()); // But we're not really interested in it all. DatasetGraph dsg = DatabaseMgr.connectDatasetGraph(location); ProgressMonitor monitor = ProgressMonitorOutput.create(LOG, "Data", BulkLoaderX.DataTick, BulkLoaderX.DataSuperTick); // WriteRows does it's own buffering and has direct write-to-buffer. // Do not buffer here. // Adds gzip processing. OutputStream outputTriples = IO.openOutputFile(loaderFiles.triplesFile); OutputStream outputQuads = IO.openOutputFile(loaderFiles.quadsFile); OutputStream outT = outputTriples; OutputStream outQ = outputQuads; dsg.executeWrite(() -> { Pair<Long, Long> p = build(dsg, monitor, outT, outQ, datafiles); String str = DateTimeUtils.nowAsXSDDateTimeString(); long cTriple = p.getLeft(); long cQuad = p.getRight(); FmtLog.info(LOG, "Triples = %,d ; Quads = %,d", cTriple, cQuad); JsonObject obj = JSON.buildObject(b->{ b.pair("ingested", str); b.key("data").startArray(); datafiles.forEach(fn->b.value(fn)); b.finishArray(); b.pair("triples", cTriple); b.pair("quads", cQuad); }); try ( OutputStream out = IO.openOutputFile(loaderFiles.loadInfo) ) { JSON.write(out, obj); } catch (IOException ex) { IO.exception(ex); } }); TDBInternal.expel(dsg); SystemIRIx.setProvider(provider); } private static Pair<Long, Long> build(DatasetGraph dsg, ProgressMonitor monitor, OutputStream outputTriples, OutputStream outputQuads, List<String> datafiles) { DatasetGraphTDB dsgtdb = TDBInternal.getDatasetGraphTDB(dsg); outputTriples = IO.ensureBuffered(outputTriples); outputQuads = IO.ensureBuffered(outputQuads); IngestData sink = new IngestData(dsgtdb, monitor, outputTriples, outputQuads, false); Timer timer = new Timer(); timer.startTimer(); // [BULK] XXX Start monitor on first item from parser. monitor.start(); sink.startBulk(); AsyncParser.asyncParse(datafiles, sink); // for( String filename : datafiles) { // if ( datafiles.size() > 0 ) // cmdLog.info("Load: "+filename+" -- "+DateTimeUtils.nowAsString()); // RDFParser.source(filename).parse(sink); // } sink.finishBulk(); IO.close(outputTriples); IO.close(outputQuads); long cTriple = sink.tripleCount(); long cQuad = sink.quadCount(); // ---- Stats // See Stats class. if ( sink.getCollector() != null ) { Location location = dsgtdb.getLocation(); if ( ! location.isMem() ) Stats.write(location.getPath(Names.optStats), sink.getCollector().results()); } // ---- Monitor monitor.finish(); long time = timer.endTimer(); long total = monitor.getTicks(); float elapsedSecs = time/1000F; float rate = (elapsedSecs!=0) ? total/elapsedSecs : 0; String str = String.format("Total: %,d tuples : %,.2f seconds : %,.2f tuples/sec [%s]", total, elapsedSecs, rate, DateTimeUtils.nowAsString()); LOG.info(str); return Pair.create(cTriple, cQuad); } static class IngestData implements StreamRDF { private DatasetGraphTDB dsg; private NodeTable nodeTable; long countTriples = 0; long countQuads = 0; private WriteRows writerTriples; private WriteRows writerQuads; private ProgressMonitor monitor; private StatsCollectorNodeId stats; IngestData(DatasetGraphTDB dsg, ProgressMonitor monitor, OutputStream outputTriples, OutputStream outputQuads, boolean collectStats) { this.dsg = dsg; this.monitor = monitor; NodeTupleTable ntt = dsg.getTripleTable().getNodeTupleTable(); this.nodeTable = ntt.getNodeTable(); this.writerTriples = new WriteRows(outputTriples, 3, 100_000); this.writerQuads = new WriteRows(outputQuads, 4, 100_000); if ( collectStats ) this.stats = new StatsCollectorNodeId(nodeTable); } // @Override public void startBulk() {} @Override public void start() {} @Override public void finish() {} // @Override public void finishBulk() { writerTriples.flush(); writerQuads.flush(); nodeTable.sync(); // dsg.getStoragePrefixes().sync(); } @Override public void triple(Triple triple) { countTriples++; Node s = triple.getSubject(); Node p = triple.getPredicate(); Node o = triple.getObject(); process(Quad.tripleInQuad, s, p, o); } @Override public void quad(Quad quad) { countQuads++; Node s = quad.getSubject(); Node p = quad.getPredicate(); Node o = quad.getObject(); Node g = null; // Union graph?! if ( !quad.isTriple() && !quad.isDefaultGraph() ) g = quad.getGraph(); process(g, s, p, o); } // --> From NodeIdFactory private static long encode(NodeId nodeId) { long x = nodeId.getPtrLocation(); // Should be "getValue" switch (nodeId.type()) { case PTR : return x; case XSD_DOUBLE : // XSD_DOUBLE is special. // Set value bit (63) and bit 62 x = DoubleNode62.insertType(x); return x; default : // Bit 62 is zero - tag is for doubles. x = BitsLong.pack(x, nodeId.getTypeValue(), 56, 62); // Set the high, value bit. x = BitsLong.set(x, 63); return x; } } private void write(WriteRows out, NodeId nodeId) { long x = encode(nodeId); out.write(x); } private void process(Node g, Node s, Node p, Node o) { NodeId sId = nodeTable.getAllocateNodeId(s); NodeId pId = nodeTable.getAllocateNodeId(p); NodeId oId = nodeTable.getAllocateNodeId(o); if ( g != null ) { NodeId gId = nodeTable.getAllocateNodeId(g); write(writerQuads, gId); write(writerQuads, sId); write(writerQuads, pId); write(writerQuads, oId); writerQuads.endOfRow(); if ( stats != null ) stats.record(gId, sId, pId, oId); } else { write(writerTriples, sId); write(writerTriples, pId); write(writerTriples, oId); writerTriples.endOfRow(); if ( stats != null ) stats.record(null, sId, pId, oId); } monitor.tick(); } public StatsCollectorNodeId getCollector() { return stats; } public long tripleCount() { return countTriples; } public long quadCount() { return countQuads; } @Override public void base(String base) {} @Override public void prefix(String prefix, String iri) { dsg.prefixes().add(prefix, iri); } } }
9235e87ac0b544b0bfc58ce1807a443ad9af258a
2,001
java
Java
s2fisshplate/src/main/java/org/seasar/fisshplate/creator/FisshplateCreator.java
seasarorg/fisshplate
663b158867cdaf3560b26c8376c0b5578ce758ba
[ "Apache-2.0" ]
1
2019-10-19T16:42:59.000Z
2019-10-19T16:42:59.000Z
s2fisshplate/src/main/java/org/seasar/fisshplate/creator/FisshplateCreator.java
seasarorg/fisshplate
663b158867cdaf3560b26c8376c0b5578ce758ba
[ "Apache-2.0" ]
null
null
null
s2fisshplate/src/main/java/org/seasar/fisshplate/creator/FisshplateCreator.java
seasarorg/fisshplate
663b158867cdaf3560b26c8376c0b5578ce758ba
[ "Apache-2.0" ]
3
2015-12-28T23:22:04.000Z
2022-02-04T07:55:02.000Z
33.35
73
0.72014
997,459
/** * Copyright 2004-2010 the Seasar Foundation and the Others. * * 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.seasar.fisshplate.creator; import org.seasar.framework.container.ComponentCustomizer; import org.seasar.framework.container.creator.ComponentCreatorImpl; import org.seasar.framework.container.deployer.InstanceDefFactory; import org.seasar.framework.convention.NamingConvention; /** * SMART deployでS2Fisshplateを利用するためのCreatorクラスです。 * @author rokugen */ public class FisshplateCreator extends ComponentCreatorImpl { private static final String DEFAULT_SUFFIX = "Fpao"; public FisshplateCreator(NamingConvention namingConvention) { super(namingConvention); setNameSuffix(DEFAULT_SUFFIX); setEnableInterface(true); setEnableAbstract(true); setInstanceDef(InstanceDefFactory.SINGLETON); } /** * {@link ComponentCustomizer}を戻します。 * customizer.dicon上でコンポーネント名を<code>fpaoCustomizer</code>とする必要があります。 * @return Fpao用ComponentCustomizer */ public ComponentCustomizer getFpaoCustomizer() { return getCustomizer(); } /** * {@link ComponentCustomizer}を設定します。 * customizer.dicon上でコンポーネント名を<code>fpaoCustomizer</code>とする必要があります。 * @param customizer Fpao用ComponentCustomizer */ public void setFpaoCustomizer(ComponentCustomizer customizer) { setCustomizer(customizer); } }
9235e892ec3c5f5e038320f464c7b69f7004a3e2
1,982
java
Java
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetUnusedGlusterBricksQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetUnusedGlusterBricksQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetUnusedGlusterBricksQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
39.64
112
0.704844
997,460
package org.ovirt.engine.core.bll.gluster; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ovirt.engine.core.bll.QueriesCommandBase; import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity; import org.ovirt.engine.core.common.businessentities.gluster.StorageDevice; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.queries.VdsIdParametersBase; public class GetUnusedGlusterBricksQuery<P extends VdsIdParametersBase> extends QueriesCommandBase<P> { public GetUnusedGlusterBricksQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { List<StorageDevice> storageDevicesInHost = getDbFacade().getStorageDeviceDao().getStorageDevicesInHost(getParameters().getVdsId()); getQueryReturnValue().setReturnValue(getUnUsedBricks(storageDevicesInHost)); } private List<StorageDevice> getUnUsedBricks(List<StorageDevice> bricksFromServer) { List<GlusterBrickEntity> usedBricks = getDbFacade().getGlusterBrickDao().getGlusterVolumeBricksByServerId(getParameters().getVdsId()); List<StorageDevice> freeBricks = new ArrayList<StorageDevice>(); Set<String> bricksDir = new HashSet<String>(); for (GlusterBrickEntity brick : usedBricks) { bricksDir.add(brick.getBrickDirectory()); } for (StorageDevice brick : bricksFromServer) { if (brick.getMountPoint() != null && !brick.getMountPoint().isEmpty() && brick.getMountPoint() .startsWith(Config.<String> getValue(ConfigValues.DefaultGlusterBrickMountPoint)) && !bricksDir.contains(brick.getMountPoint())) { freeBricks.add(brick); } } return freeBricks; } }
9235e9e369f50f0380ff6d774ed83ff41e34d29c
4,962
java
Java
jmx-metrics/src/test/java/io/opentelemetry/contrib/jmxmetrics/JmxConfigTest.java
cyrille-leclerc/opentelemetry-java-contrib
499bdfa943fdca78f65c508b732878aab6400889
[ "Apache-2.0" ]
51
2020-08-18T17:12:17.000Z
2022-03-13T00:26:49.000Z
jmx-metrics/src/test/java/io/opentelemetry/contrib/jmxmetrics/JmxConfigTest.java
cyrille-leclerc/opentelemetry-java-contrib
499bdfa943fdca78f65c508b732878aab6400889
[ "Apache-2.0" ]
118
2020-08-17T22:02:15.000Z
2022-03-31T04:31:45.000Z
jmx-metrics/src/test/java/io/opentelemetry/contrib/jmxmetrics/JmxConfigTest.java
cyrille-leclerc/opentelemetry-java-contrib
499bdfa943fdca78f65c508b732878aab6400889
[ "Apache-2.0" ]
40
2020-11-03T07:39:08.000Z
2022-03-10T17:59:10.000Z
41.35
97
0.731963
997,461
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.contrib.jmxmetrics; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import org.junitpioneer.jupiter.SetSystemProperty; class JmxConfigTest { @Test void staticValues() { assertThat(JmxConfig.AVAILABLE_TARGET_SYSTEMS) .containsOnly("cassandra", "jvm", "kafka", "kafka-consumer", "kafka-producer"); } @Test void defaultValues() { JmxConfig config = new JmxConfig(); assertThat(config.serviceUrl).isNull(); ; assertThat(config.groovyScript).isNull(); ; assertThat(config.targetSystem).isEmpty(); assertThat(config.targetSystems).isEmpty(); assertThat(config.intervalMilliseconds).isEqualTo(10000); assertThat(config.metricsExporterType).isEqualTo("logging"); assertThat(config.otlpExporterEndpoint).isNull(); assertThat(config.prometheusExporterHost).isEqualTo("0.0.0.0"); assertThat(config.prometheusExporterPort).isEqualTo(9464); assertThat(config.username).isNull(); assertThat(config.password).isNull(); assertThat(config.remoteProfile).isNull(); assertThat(config.realm).isNull(); } @Test @SetSystemProperty(key = "otel.jmx.service.url", value = "myServiceUrl") @SetSystemProperty(key = "otel.jmx.groovy.script", value = "myGroovyScript") @SetSystemProperty( key = "otel.jmx.target.system", value = "mytargetsystem,mytargetsystem,myothertargetsystem,myadditionaltargetsystem") @SetSystemProperty(key = "otel.jmx.interval.milliseconds", value = "123") @SetSystemProperty(key = "otel.metrics.exporter", value = "inmemory") @SetSystemProperty(key = "otel.exporter.otlp.endpoint", value = "https://myOtlpEndpoint") @SetSystemProperty(key = "otel.exporter.prometheus.host", value = "myPrometheusHost") @SetSystemProperty(key = "otel.exporter.prometheus.port", value = "234") @SetSystemProperty(key = "otel.jmx.username", value = "myUsername") @SetSystemProperty(key = "otel.jmx.password", value = "myPassword") @SetSystemProperty(key = "otel.jmx.remote.profile", value = "myRemoteProfile") @SetSystemProperty(key = "otel.jmx.realm", value = "myRealm") void specifiedValues() { JmxConfig config = new JmxConfig(); assertThat(config.serviceUrl).isEqualTo("myServiceUrl"); assertThat(config.groovyScript).isEqualTo("myGroovyScript"); assertThat(config.targetSystem) .isEqualTo("mytargetsystem,mytargetsystem,myothertargetsystem,myadditionaltargetsystem"); assertThat(config.targetSystems) .containsOnly("mytargetsystem", "myothertargetsystem", "myadditionaltargetsystem"); assertThat(config.intervalMilliseconds).isEqualTo(123); assertThat(config.metricsExporterType).isEqualTo("inmemory"); assertThat(config.otlpExporterEndpoint).isEqualTo("https://myOtlpEndpoint"); assertThat(config.prometheusExporterHost).isEqualTo("myPrometheusHost"); assertThat(config.prometheusExporterPort).isEqualTo(234); assertThat(config.username).isEqualTo("myUsername"); assertThat(config.password).isEqualTo("myPassword"); assertThat(config.remoteProfile).isEqualTo("myRemoteProfile"); assertThat(config.realm).isEqualTo("myRealm"); } @Test @SetSystemProperty(key = "otel.jmx.interval.milliseconds", value = "abc") void invalidInterval() { assertThatThrownBy(JmxConfig::new) .isInstanceOf(ConfigurationException.class) .hasMessage("Failed to parse otel.jmx.interval.milliseconds"); } @Test @SetSystemProperty(key = "otel.exporter.prometheus.port", value = "abc") void invalidPrometheusPort() { assertThatThrownBy(JmxConfig::new) .isInstanceOf(ConfigurationException.class) .hasMessage("Failed to parse otel.exporter.prometheus.port"); } @Test @SetSystemProperty(key = "otel.jmx.service.url", value = "requiredValue") @SetSystemProperty(key = "otel.jmx.groovy.script", value = "myGroovyScript") @SetSystemProperty(key = "otel.jmx.target.system", value = "myTargetSystem") void conflictingScriptAndTargetSystem() { JmxConfig config = new JmxConfig(); assertThatThrownBy(config::validate) .isInstanceOf(ConfigurationException.class) .hasMessage( "Only one of otel.jmx.groovy.script or otel.jmx.target.system can be specified."); } @Test @SetSystemProperty(key = "otel.jmx.service.url", value = "requiredValue") @SetSystemProperty(key = "otel.jmx.target.system", value = "jvm,unavailableTargetSystem") void invalidTargetSystem() { JmxConfig config = new JmxConfig(); assertThatThrownBy(config::validate) .isInstanceOf(ConfigurationException.class) .hasMessage( "[jvm, unavailabletargetsystem] must specify targets from " + "[cassandra, jvm, kafka, kafka-consumer, kafka-producer]"); } }
9235ea77cde0db2dd1aa6ea73cfb5cf7fed9ecd8
634
java
Java
LEDViz2/src/com/nzelot/ledviz2/gfx/res/loader/PNGLoader.java
nZeloT/ledviz2
862116ecd141633ddf81fb7189da0dc863429e29
[ "MIT" ]
null
null
null
LEDViz2/src/com/nzelot/ledviz2/gfx/res/loader/PNGLoader.java
nZeloT/ledviz2
862116ecd141633ddf81fb7189da0dc863429e29
[ "MIT" ]
null
null
null
LEDViz2/src/com/nzelot/ledviz2/gfx/res/loader/PNGLoader.java
nZeloT/ledviz2
862116ecd141633ddf81fb7189da0dc863429e29
[ "MIT" ]
null
null
null
24.384615
68
0.72082
997,462
package com.nzelot.ledviz2.gfx.res.loader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nzelot.ledviz2.gfx.core.Texture; import com.nzelot.ledviz2.gfx.core.TextureLoader; import com.nzelot.ledviz2.gfx.res.IResourceLoader; public class PNGLoader implements IResourceLoader { private final Logger l = LoggerFactory.getLogger(PNGLoader.class); @Override public Texture load(String file) { Texture t = null; try { t = TextureLoader.loadTexture(TextureLoader.loadImage(file)); } catch (Exception e) { l.error("Could not load resource: " + file, e); } return t; } }
9235eaf428fc86788754eef0c719c640753e52b9
3,916
java
Java
src/test/java/io/github/joaomlneto/travis_ci_tutorial_java/PriorityQueueTest.java
cstnaya/tt
40dbb0f29376fa2e8a8f452f8b3e6731b846d854
[ "MIT" ]
null
null
null
src/test/java/io/github/joaomlneto/travis_ci_tutorial_java/PriorityQueueTest.java
cstnaya/tt
40dbb0f29376fa2e8a8f452f8b3e6731b846d854
[ "MIT" ]
null
null
null
src/test/java/io/github/joaomlneto/travis_ci_tutorial_java/PriorityQueueTest.java
cstnaya/tt
40dbb0f29376fa2e8a8f452f8b3e6731b846d854
[ "MIT" ]
null
null
null
26.639456
80
0.550562
997,463
package main.java; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.util.ArrayList; import java.util.PriorityQueue; import static org.junit.jupiter.api.Assertions.*; class PriorityQueueTest { static PriorityQueue<Integer> q1 = new PriorityQueue(); static PriorityQueue<Integer> q2 = new PriorityQueue(); static PriorityQueue<Integer> q3 = new PriorityQueue(); static PriorityQueue<Integer> q4 = new PriorityQueue(); static PriorityQueue<Integer> q5 = new PriorityQueue(); static int[] t1 = {5, 1, 77, 45, -100}; static int[] t2 = {-25, 1, 86, 17, -27, 22}; static int[] t3 = {0, 0, 58, 84, -1, 4, -26}; static int[] t4 = {30, -638, 888, 397, 147, -78, 95, -386}; static int[] t5 = {-7, 628, 261, 667, -316, 110, -626, 258, 46}; @org.junit.jupiter.api.BeforeAll static void init() { for(int t : t1) { q1.add(t); } for(int t : t2) { q2.add(t); } for(int t : t3) { q3.add(t); } for(int t : t4) { q4.add(t); } for(int t : t5) { q5.add(t); } } @DisplayName("Exception 1") @org.junit.jupiter.api.Test void TestExpectedException() { System.out.println("Test_excp_1"); assertThrows(NumberFormatException.class, () -> { Integer.parseInt("One"); }); } @DisplayName("Testcase 1") @ParameterizedTest @ValueSource(ints = {-100, 1, 5, 145, 77}) // <- The correct ordered array. void test_pq_1 (int arg) { System.out.println("Test1"); int q = q1.poll(); assertEquals(q, arg); } @DisplayName("Testcase 2") @ParameterizedTest @ValueSource(ints = {-27, -25, 1, 17, 22, 86}) void test_pq_2 (int arg) { System.out.println("Test2"); int q = q2.poll(); assertEquals(q, arg); } @DisplayName("Exception 2") @org.junit.jupiter.api.Test void TestExpectedException_2 () { String s = null; assertThrows(IllegalArgumentException.class, () -> { Integer.parseInt(s); }); } @DisplayName("Testcase 3") @ParameterizedTest @ValueSource(ints = {-26, -1, 0, 0, 4, 58, 84}) void test_pq_3 (int arg) { System.out.println("Test3"); int q = q3.poll(); assertEquals(q, arg); } @DisplayName("Testcase 4") @ParameterizedTest @ValueSource(ints = {-638, -386, -78, 30, 95, 147, 397, 888}) void test_pq_4 (int arg) { System.out.println("Test4"); int q = q4.poll(); assertEquals(q, arg); } @DisplayName("Testcase 5") @ParameterizedTest @ValueSource(ints = {-626, -316, -7, 46, 110, 258, 261, 628, 667}) void test_pq_5 (int arg) { System.out.println("Test5"); int q = q5.poll(); assertEquals(q, arg); } @DisplayName("Exception 3") @org.junit.jupiter.api.Test void TestExpectedException_3 () { String s2 = null; assertThrows(IllegalArgumentException.class, () -> { Integer.valueOf(s2); }); } /* @org.junit.jupiter.api.AfterEach void tearDown() { } @org.junit.jupiter.api.Test void iterator() { } @org.junit.jupiter.api.Test void size() { } @org.junit.jupiter.api.Test void clear() { } @org.junit.jupiter.api.Test void offer() { } @org.junit.jupiter.api.Test void poll() { } @org.junit.jupiter.api.Test void peek() { } @org.junit.jupiter.api.Test void comparator() { } @org.junit.jupiter.api.Test void remove() { } @org.junit.jupiter.api.Test void add() { } */ }
9235ed43ecc7dc75e85bf154ab46726cf341480a
2,023
java
Java
src/main/java/com/power/mail/bean/MailBean.java
zhanglg40/power
65c55461f6d2875f8c274bf9918f0b5acd86850e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/power/mail/bean/MailBean.java
zhanglg40/power
65c55461f6d2875f8c274bf9918f0b5acd86850e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/power/mail/bean/MailBean.java
zhanglg40/power
65c55461f6d2875f8c274bf9918f0b5acd86850e
[ "Apache-2.0" ]
null
null
null
21.98913
52
0.611962
997,464
/** * */ package com.power.mail.bean; import java.util.List; import org.hibernate.validator.constraints.NotBlank; /** * * @team IT Team * @author zhanglg * @version 1.0 * @time 2016年10月28日 */ public class MailBean { @NotBlank(message="from不允许为空") private String from; @NotBlank(message="to不允许为空") private String to; @NotBlank(message="password不允许为空") private String password; @NotBlank(message="hostName不允许为空") private String hostName; @NotBlank(message="smtpPort不允许为空") private String smtpPort; @NotBlank(message="subTitle不允许为空") private String subTitle; @NotBlank(message="body不允许为空") private String body; private String name; private List<String> maillist; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getSmtpPort() { return smtpPort; } public void setSmtpPort(String smtpPort) { this.smtpPort = smtpPort; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public List<String> getMaillist() { return maillist; } public void setMaillist(List<String> maillist) { this.maillist = maillist; } }
9235ed8235257627870a72fe5ac34b7158baf8dc
4,270
java
Java
src/com/skenvy/fluent/xpath/predicates/PredicateNumberContext.java
Skenvy/FluentXPath
14168850d3940959126a9b0a522baf58069d103f
[ "Apache-2.0" ]
null
null
null
src/com/skenvy/fluent/xpath/predicates/PredicateNumberContext.java
Skenvy/FluentXPath
14168850d3940959126a9b0a522baf58069d103f
[ "Apache-2.0" ]
null
null
null
src/com/skenvy/fluent/xpath/predicates/PredicateNumberContext.java
Skenvy/FluentXPath
14168850d3940959126a9b0a522baf58069d103f
[ "Apache-2.0" ]
null
null
null
31.397059
98
0.669789
997,465
package com.skenvy.fluent.xpath.predicates; import com.skenvy.fluent.xpath.XPathAttributeContext; /*** * A collection of interfaces that describe functions that can be applied to * the inner class, while in the context of having the last element of the * inner class' method chained construction be a number component. */ public final class PredicateNumberContext extends PredicateBuilder implements BuildablePredicate { /*************************************************************************/ /* Constructors and "buildToString" */ /*************************************************************************/ /*** * Internal constructor used to instantiate a PredicateNumberContext * instance with some initial CharSequence * @param chars */ private PredicateNumberContext(CharSequence chars) { super(chars); } /*** * Create a new PredicateBuilder subclass that refers to an existing instance * of the PredicateBuilder as the superclass to the context class that brought * us to this context. */ /*Package Private*/ PredicateNumberContext(PredicateBuilder predicateBuilder) { super("(number("+predicateBuilder._buildToString()+"))"); } /*** * Instantiate a PredicateNumberContext wrapper of an XPathAttributeContext * @param xPathAttributeContext */ /*Package Private*/ PredicateNumberContext(XPathAttributeContext xPathAttributeContext) { super("(number("+xPathAttributeContext.buildToString()+"))"); } /*** * Instantiate a predicate "Number" from the java literal "int" * @param words */ /*Package Private*/ PredicateNumberContext(int number) { super("("+number+")"); } /*** * Instantiate a predicate "Number" from the java literal "long" * @param words */ /*Package Private*/ PredicateNumberContext(long number) { super("("+number+")"); } /*** * Instantiate a predicate "Number" from the java literal "float" * @param words */ /*Package Private*/ PredicateNumberContext(float number) { super("("+number+")"); } /*** * Instantiate a predicate "Number" from the java literal "double" * @param words */ /*Package Private*/ PredicateNumberContext(double number) { super("("+number+")"); } @Override public String buildToString() { return this.buildTheStringBuilder(); } /*************************************************************************/ /* Functions */ /*************************************************************************/ /*** * Implements the xpath function which returns a number value: * "ceiling(number)" * @param predicateNumberContext * @return PredicateNumberContext */ public PredicateNumberContext ceiling(PredicateNumberContext predicateNumberContext) { PredicateNumberContext pnc = new PredicateNumberContext("ceiling("); pnc.appendStringBuilder(predicateNumberContext); pnc.appendStringBuilder(")"); return pnc; } /*** * Implements the xpath function which returns a number value: * "floor(number)" * @param predicateNumberContext * @return PredicateNumberContext */ public PredicateNumberContext floor(PredicateNumberContext predicateNumberContext) { PredicateNumberContext pnc = new PredicateNumberContext("floor("); pnc.appendStringBuilder(predicateNumberContext); pnc.appendStringBuilder(")"); return pnc; } /*** * Implements the xpath function which returns a number value: * "round(number)" * @param predicateNumberContext * @return PredicateNumberContext */ public PredicateNumberContext round(PredicateNumberContext predicateNumberContext) { PredicateNumberContext pnc = new PredicateNumberContext("round("); pnc.appendStringBuilder(predicateNumberContext); pnc.appendStringBuilder(")"); return pnc; } /*** * Implements the xpath function which returns a number value: * "string-length(string)" * @param predicateStringContext * @return PredicateNumberContext */ public PredicateNumberContext stringLength(PredicateStringContext predicateStringContext) { PredicateNumberContext pnc = new PredicateNumberContext("string-length("); pnc.appendStringBuilder(predicateStringContext); pnc.appendStringBuilder(")"); return pnc; } }
9235eeec30738c671ea237a7e6eb14990186cdf9
10,698
java
Java
basex-core/src/test/java/org/basex/query/func/CryptoModuleTest.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
1
2017-03-23T17:41:51.000Z
2017-03-23T17:41:51.000Z
basex-core/src/test/java/org/basex/query/func/CryptoModuleTest.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
null
null
null
basex-core/src/test/java/org/basex/query/func/CryptoModuleTest.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
null
null
null
31.189504
90
0.650028
997,466
package org.basex.query.func; import java.util.logging.*; import org.basex.query.*; import org.junit.*; /** * This class tests the functions of the Cryptography Module. * * @author BaseX Team 2005-17, BSD License * @author Lukas Kircher */ public final class CryptoModuleTest extends AdvancedQueryTest { /** Set higher log level to avoid INFO output. */ public CryptoModuleTest() { Logger.getLogger("com.sun.org.apache.xml.internal").setLevel(Level.WARNING); } /** Checks default/empty arguments. */ @Test public void check() { query("crypto:hmac('msg','key','','')"); query("crypto:encrypt('msg','','keykeyke','')"); query("crypto:decrypt(crypto:encrypt('msg','','keykeyke',''),'','keykeyke','')"); query("crypto:generate-signature(<a/>,'','','','','')"); query("crypto:validate-signature(crypto:generate-signature(<a/>,'','','','',''))"); } /** * Test method for encrypt and decrypt with symmetric keys. */ @Test public void encryption1() { final String msg = "messagemessagemessagemessagemessagemessagemessage"; query("let $e := crypto:encrypt('" + msg + "','symmetric','aaabbbaa'," + "'DES') return crypto:decrypt($e,'symmetric'," + "'aaabbbaa','DES')", msg); } /** * Test method for encrypt and decrypt with symmetric keys. */ @Test public void encryption2() { final String msg = "messagemessagemessagemessagemessagemessagemessage"; query("let $e := crypto:encrypt('" + msg + "','symmetric','abababababababab'," + "'AES') return crypto:decrypt($e,'symmetric','abababababababab','AES')", msg); } /** * Tests the creation of a message authentication code for the md5 algorithm. */ @Test public void hmacMD5defencoding() { query("crypto:hmac('message','key','md5')", "TkdI5itGNSH2d1+/khI0tQ=="); } /** * Tests the creation of a message authentication code for the md5 algorithm. */ @Test public void hmacMD5hex() { query("crypto:hmac('message','key','md5', 'hex')", "4E4748E62B463521F6775FBF921234B5"); } /** * Tests the creation of a message authentication code for the md5 algorithm. */ @Test public void hmacMD5base64() { query("crypto:hmac('message','key','md5', 'base64')", "TkdI5itGNSH2d1+/khI0tQ=="); } /** * Tests the creation of a message authentication code for the sha1 algorithm. */ @Test public void hmacSHA1hex() { query("crypto:hmac('message','key','sha1', 'hex')", "2088DF74D5F2146B48146CAF4965377E9D0BE3A4"); } /** * Tests the creation of a message authentication code for the sha1 algorithm. */ @Test public void hmacSHA1base64() { query("crypto:hmac('message','key','sha1', 'base64')", "IIjfdNXyFGtIFGyvSWU3fp0L46Q="); } /** * Tests the creation of a message authentication code for the sha256 * algorithm. */ @Test public void hmacSHA256hex() { query("crypto:hmac('message','key','sha256', 'hex')", "6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A"); } /** * Tests the creation of a message authentication code for the sha256 * algorithm. */ @Test public void hmacSHA256base64() { query("crypto:hmac('message','key','sha256', 'base64')", "bp7ym3X//Ft6uuUn1Y/a2y/kLnIZARl2kXNDBl9Y7Uo="); } /** * Tests the creation of a message authentication code for the sha384 * algorithm. */ @Test public void hmacSHA384hex() { query("crypto:hmac('message','key','sha384', 'hex')", "2088DF74D5F2146B48146CAF4965377E9D0BE3A4"); } /** * Tests the creation of a message authentication code for the sha384 * algorithm. */ @Test public void hmacSHA384base64() { query("crypto:hmac('message','key','sha384', 'base64')", "IIjfdNXyFGtIFGyvSWU3fp0L46Q="); } /** * Tests the creation of a message authentication code for the sha512 * algorithm. */ @Test public void hmacSHA512hex() { query("crypto:hmac('message','key','sha512', 'hex')", "E477384D7CA229DD1426E64B63EBF2D36EBD6D7E669A6735424E72EA6C01D3F8" + "B56EB39C36D8232F5427999B8D1A3F9CD1128FC69F4D75B434216810FA367E98"); } /** * Tests the creation of a message authentication code for the sha512 * algorithm. */ @Test public void hmacSHA512base64() { query("crypto:hmac('message','key','sha512', 'base64')", "5Hc4TXyiKd0UJuZLY+vy0269bX5mmmc1Qk5y6mwB0/i1brOcNtgjL1QnmZuNGj+c0RK" + "Pxp9NdbQ0IWgQ+jZ+mA=="); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignature1() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'','','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignature1b() { query("crypto:validate-signature(" + "crypto:generate-signature(<a/>,'','SHA1','DSA_SHA1','','enveloped'))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignature1c() { final String input = "<a><Signature xmlns='http://www.w3.org/2000/09/xmldsig#'>" + "<SignedInfo><CanonicalizationMethod " + "Algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315'/>" + "<SignatureMethod Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-" + "sha1'/><Reference URI=''><Transforms><Transform Algorithm='http://" + "www.w3.org/2000/09/xmldsig#enveloped-signature'/></Transforms>" + "<DigestMethod Algorithm='http://www.w3.org/2000/09/xmldsig#sha1'/>" + "<DigestValue>9hvH4qztnIYgYfJDRLnEMPJdoaY=</DigestValue></Reference>" + "</SignedInfo><SignatureValue>W/BpXt9odK+Ot2cU0No0+tzwAJyqSx+CRMXG2B" + "T6NRc2qbMMSB7l+RcR6jwsu2Smt0LCltR1YFLTPoD+GCarZA==</SignatureValue>" + "<KeyInfo><KeyValue><RSAKeyValue><Modulus>mH+uHBX+3mE9bgWzcDym0pnyu" + "W3ca6EexNvQ/sAKgDNmO1xFNgVWSgKGMxmaGRzGyPi+8+KeGKGM0mS1jpRPQQ==" + "</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>" + "</KeyInfo></Signature></a>"; query("crypto:validate-signature(" + input + ')', "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithCanonicalization() { query("crypto:validate-signature(crypto:generate-signature(<a/>," + "'exclusive','','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithCanonicalization2() { query("crypto:validate-signature(crypto:generate-signature(<a/>," + "'exclusive-with-comments','','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithCanonicalization3() { query("crypto:validate-signature(crypto:generate-signature(<a/>," + "'inclusive','','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithCanonicalization4() { query("crypto:validate-signature(crypto:generate-signature(<a/>," + "'inclusive-with-comments','','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithDigestAlgorithm() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'','SHA1','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithDigestAlgorithm2() { query("crypto:validate-signature(crypto:generate-signature(" + "<a/>,'','SHA256','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithDigestAlgorithm3() { query("crypto:validate-signature(crypto:generate-signature(" + "<a/>,'','SHA512','','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithSignatureAlgorithm() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'',''," + "'DSA_SHA1','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithSignatureAlgorithm2() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'',''," + "'RSA_SHA1','',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithSignatureNamespace3() { query("crypto:validate-signature(crypto:generate-signature(" + "<a/>,'','','','prefix',''))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithSignatureType() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'','','',''," + "'enveloped'))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithSignatureType2() { query("crypto:validate-signature(crypto:generate-signature(<a/>,'','','',''," + "'enveloping'))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureWithXPath() { query("crypto:validate-signature(crypto:generate-signature(<a><n/><n/></a>," + "'','','','','','/a/n'))", "true"); } /** * Tests whether validate-signature returns true for a certificate created * with generate-signature. */ @Test public void validateSignatureFullySpecified() { query("crypto:validate-signature(crypto:generate-signature(<a><n/></a>," + "'exclusive','SHA512','RSA_SHA1','myPrefix','enveloped','/a/n'))", "true"); } }
9235eef713a246f7e2cb92f5be70ab485e687aed
86
java
Java
sinotopia-wechat/sinotopia-wechat-mp/sinotopia-wechat-mp-admin/src/main/java/com/sinotopia/wechat/mp/admin/controller/AppController.java
sinotopia/sinotopia
5a3e3d09db5e71707698f70acd8c2c035611b2da
[ "MIT" ]
null
null
null
sinotopia-wechat/sinotopia-wechat-mp/sinotopia-wechat-mp-admin/src/main/java/com/sinotopia/wechat/mp/admin/controller/AppController.java
sinotopia/sinotopia
5a3e3d09db5e71707698f70acd8c2c035611b2da
[ "MIT" ]
null
null
null
sinotopia-wechat/sinotopia-wechat-mp/sinotopia-wechat-mp-admin/src/main/java/com/sinotopia/wechat/mp/admin/controller/AppController.java
sinotopia/sinotopia
5a3e3d09db5e71707698f70acd8c2c035611b2da
[ "MIT" ]
null
null
null
10.75
49
0.767442
997,467
package com.sinotopia.wechat.mp.admin.controller; public class AppController { }
9235efdafc79422c9b52581a835af17bcdae5cfc
954
java
Java
src/main/java/com/model/Drug.java
NNSISA/BackIsa
49bca6174cb11f63e0df3f388644027f584a369d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/model/Drug.java
NNSISA/BackIsa
49bca6174cb11f63e0df3f388644027f584a369d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/model/Drug.java
NNSISA/BackIsa
49bca6174cb11f63e0df3f388644027f584a369d
[ "Apache-2.0" ]
null
null
null
16.448276
111
0.642558
997,468
package com.model; import javax.persistence.*; @Entity public class Drug { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name", nullable = false) private String name; @Column(name = "quantity", nullable = false) private int quantity; @Column(name = "price", nullable = false) private int price; public Long getId() { return id; } public String getName() { return name; } public int getQuantity() { return quantity; } public int getPrice() { return price; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setQuantity(int quantity) { this.quantity = quantity; } public void setPrice(int price) { this.price = price; } public Drug() { } @Override public String toString() { return "Drug{" + "id=" + id + ", name='" + name + '\'' + ", quantity=" + quantity + ", price=" + price + '}'; } }
9235f03daeec21ce34c998466898324735258024
236
java
Java
src/main/java/com/spring/nong4/IndexController.java
haseungwoo95/NONG.4
113b60d768a7d388bd16fc38a09fa481d6ee7362
[ "MIT" ]
3
2021-08-21T14:47:51.000Z
2021-12-26T08:36:48.000Z
src/main/java/com/spring/nong4/IndexController.java
haseungwoo95/NONG.4
113b60d768a7d388bd16fc38a09fa481d6ee7362
[ "MIT" ]
9
2021-07-12T07:36:35.000Z
2021-12-16T10:49:02.000Z
src/main/java/com/spring/nong4/IndexController.java
haseungwoo95/NONG.4
113b60d768a7d388bd16fc38a09fa481d6ee7362
[ "MIT" ]
4
2021-07-11T04:27:44.000Z
2021-07-12T05:34:02.000Z
18.153846
58
0.771186
997,469
package com.spring.nong4; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("index") public void index(){ } }
9235f0ec5ae203cc8757d31499ea0875dca8c77e
942
java
Java
bitshadow-java-client-integration/src/test/java/BitshadowServiceTestRunner.java
LittleMikeDev/bitshadow
abe5eea248488e2f50fc694968a5413258d9bbe1
[ "BSD-2-Clause" ]
1
2017-05-19T02:31:59.000Z
2017-05-19T02:31:59.000Z
bitshadow-java-client-integration/src/test/java/BitshadowServiceTestRunner.java
LittleMikeDev/bitshadow
abe5eea248488e2f50fc694968a5413258d9bbe1
[ "BSD-2-Clause" ]
null
null
null
bitshadow-java-client-integration/src/test/java/BitshadowServiceTestRunner.java
LittleMikeDev/bitshadow
abe5eea248488e2f50fc694968a5413258d9bbe1
[ "BSD-2-Clause" ]
null
null
null
40.956522
144
0.812102
997,470
import ch.qos.logback.classic.Level; import io.dropwizard.logging.DefaultLoggingFactory; import io.dropwizard.logging.LoggingFactory; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.BeforeClass; import org.junit.ClassRule; import uk.co.littlemike.bitshadow.client.integration.BitshadowServiceTest; import uk.co.littlemike.bitshadow.web.BitShadowWebService; import uk.co.littlemike.bitshadow.web.config.BitShadowConfiguration; public class BitshadowServiceTestRunner extends BitshadowServiceTest { @ClassRule public static final DropwizardAppRule<BitShadowConfiguration> BITSHADOW_SERVER = new DropwizardAppRule<>(BitShadowWebService.class); @BeforeClass public static void setUpServer() { DefaultLoggingFactory loggingFactory = (DefaultLoggingFactory) BITSHADOW_SERVER.getTestSupport().getConfiguration().getLoggingFactory(); loggingFactory.setLevel(Level.DEBUG); } }
9235f144bb4f2d1aace68d8edf18d06a1afee4d1
3,398
java
Java
src/main/java/de/altenerding/biber/pinkie/business/nuLiga/control/NuLigaCalenderProvider.java
danielsagert/Pinkie
f1cade54557f6792615ca5aa252cc622d1e816f6
[ "Apache-2.0" ]
1
2019-07-22T18:26:54.000Z
2019-07-22T18:26:54.000Z
src/main/java/de/altenerding/biber/pinkie/business/nuLiga/control/NuLigaCalenderProvider.java
AlexanderPraegla/Pinkie
f1cade54557f6792615ca5aa252cc622d1e816f6
[ "Apache-2.0" ]
90
2018-02-04T20:38:14.000Z
2021-12-14T21:14:17.000Z
src/main/java/de/altenerding/biber/pinkie/business/nuLiga/control/NuLigaCalenderProvider.java
AlexanderPraegla/Pinkie
f1cade54557f6792615ca5aa252cc622d1e816f6
[ "Apache-2.0" ]
null
null
null
40.452381
120
0.704238
997,471
package de.altenerding.biber.pinkie.business.nuLiga.control; import de.altenerding.biber.pinkie.business.nuLiga.entity.ClubMeeting; import de.altenerding.biber.pinkie.business.team.entity.Team; import net.fortuna.ical4j.data.CalendarOutputter; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.ProdId; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Version; import org.apache.commons.lang3.RandomStringUtils; import org.apache.logging.log4j.Logger; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.IOException; import java.io.OutputStream; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.List; public class NuLigaCalenderProvider { public static final int CONST_MEETING_DURATION = 90; @Inject private Logger logger; @PersistenceContext private EntityManager em; @Inject private NuLigaDataProvider nuLigaDataProvider; public static final String ALTENERDING_CLUB_ID = "10640"; public void createIcalFileMeetingsForTeam(Team team, OutputStream outputStream) throws IOException { Calendar calendar = new Calendar(); calendar.getProperties().add(new ProdId("-//Altenerding Handball//iCal4j 1.0//EN")); calendar.getProperties().add(Version.VERSION_2_0); calendar.getProperties().add(CalScale.GREGORIAN); List<ClubMeeting> teamMeetings = nuLigaDataProvider.getTeamMeetings(team); for (ClubMeeting teamMeeting : teamMeetings) { String eventName = createEventName(team, teamMeeting); LocalDateTime localStartTime = teamMeeting.getScheduled().toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); DateTime startDate = new DateTime(localStartTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); LocalDateTime localEndTime = localStartTime.plusMinutes(CONST_MEETING_DURATION); DateTime endDate = new DateTime(localEndTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); VEvent vEvent = new VEvent(startDate, endDate, eventName); vEvent.getProperties().add(new Location(teamMeeting.getCourtHallName())); vEvent.getProperties().add(new Uid(RandomStringUtils.random(20, true, true))); calendar.getComponents().add(vEvent); } CalendarOutputter outputter = new CalendarOutputter(); outputter.output(calendar, outputStream); } private String createEventName(Team team, ClubMeeting teamMeeting) { StringBuilder builder = new StringBuilder() .append(team.getName()) .append(" - "); if (teamMeeting.getTeamHomeClubNr().equals(ALTENERDING_CLUB_ID)) { builder.append("Heimspiel") .append(" - ") .append(teamMeeting.getTeamGuest()); } else { builder.append("Auswärtsspiel") .append(" - ") .append(teamMeeting.getTeamHome()); } return builder.toString(); } }
9235f1e16423940bb904bda78d452dad64235bac
20,198
java
Java
airbyte-config/persistence/src/test/java/io/airbyte/config/persistence/SecretsRepositoryWriterTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
22
2020-08-27T00:47:20.000Z
2020-09-17T15:39:39.000Z
airbyte-config/persistence/src/test/java/io/airbyte/config/persistence/SecretsRepositoryWriterTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
116
2020-08-27T01:11:27.000Z
2020-09-19T02:47:52.000Z
airbyte-config/persistence/src/test/java/io/airbyte/config/persistence/SecretsRepositoryWriterTest.java
asamoal/airbyte
83b9b4fca8087cf3e0b4ba8728c00235b3735e1b
[ "MIT" ]
1
2020-09-15T06:10:01.000Z
2020-09-15T06:10:01.000Z
52.761658
149
0.800648
997,472
/* * Copyright (c) 2022 Airbyte, Inc., all rights reserved. */ package io.airbyte.config.persistence; import static io.airbyte.config.persistence.MockData.HMAC_SECRET_PAYLOAD_1; import static io.airbyte.config.persistence.MockData.HMAC_SECRET_PAYLOAD_2; import static io.airbyte.config.persistence.MockData.MOCK_SERVICE_ACCOUNT_1; import static io.airbyte.config.persistence.MockData.MOCK_SERVICE_ACCOUNT_2; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.airbyte.commons.json.Jsons; import io.airbyte.config.AirbyteConfig; import io.airbyte.config.ConfigSchema; import io.airbyte.config.DestinationConnection; import io.airbyte.config.SourceConnection; import io.airbyte.config.StandardDestinationDefinition; import io.airbyte.config.StandardSourceDefinition; import io.airbyte.config.WorkspaceServiceAccount; import io.airbyte.config.persistence.split_secrets.MemorySecretPersistence; import io.airbyte.config.persistence.split_secrets.RealSecretsHydrator; import io.airbyte.config.persistence.split_secrets.SecretCoordinate; import io.airbyte.config.persistence.split_secrets.SecretPersistence; import io.airbyte.protocol.models.ConnectorSpecification; import io.airbyte.validation.json.JsonValidationException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @SuppressWarnings({"PMD.AvoidThrowingRawExceptionTypes", "PMD.UnusedPrivateField"}) class SecretsRepositoryWriterTest { private static final UUID UUID1 = UUID.randomUUID(); private static final ConnectorSpecification SPEC = new ConnectorSpecification() .withConnectionSpecification(Jsons.deserialize( "{ \"properties\": { \"username\": { \"type\": \"string\" }, \"password\": { \"type\": \"string\", \"airbyte_secret\": true } } }")); private static final String SECRET = "abc"; private static final JsonNode FULL_CONFIG = Jsons.deserialize(String.format("{ \"username\": \"airbyte\", \"password\": \"%s\"}", SECRET)); private static final SourceConnection SOURCE_WITH_FULL_CONFIG = new SourceConnection() .withSourceId(UUID1) .withSourceDefinitionId(UUID.randomUUID()) .withConfiguration(FULL_CONFIG); private static final DestinationConnection DESTINATION_WITH_FULL_CONFIG = new DestinationConnection() .withDestinationId(UUID1) .withConfiguration(FULL_CONFIG); private static final StandardSourceDefinition SOURCE_DEF = new StandardSourceDefinition() .withSourceDefinitionId(SOURCE_WITH_FULL_CONFIG.getSourceDefinitionId()) .withSpec(SPEC); private static final StandardDestinationDefinition DEST_DEF = new StandardDestinationDefinition() .withDestinationDefinitionId(DESTINATION_WITH_FULL_CONFIG.getDestinationDefinitionId()) .withSpec(SPEC); private static final String PASSWORD_PROPERTY_NAME = "password"; private static final String PASSWORD_FIELD_NAME = "_secret"; private ConfigRepository configRepository; private MemorySecretPersistence longLivedSecretPersistence; private MemorySecretPersistence ephemeralSecretPersistence; private SecretsRepositoryWriter secretsRepositoryWriter; private RealSecretsHydrator longLivedSecretsHydrator; private SecretsRepositoryReader longLivedSecretsRepositoryReader; private RealSecretsHydrator ephemeralSecretsHydrator; private SecretsRepositoryReader ephemeralSecretsRepositoryReader; @BeforeEach void setup() { configRepository = spy(mock(ConfigRepository.class)); longLivedSecretPersistence = new MemorySecretPersistence(); ephemeralSecretPersistence = new MemorySecretPersistence(); secretsRepositoryWriter = new SecretsRepositoryWriter( configRepository, Optional.of(longLivedSecretPersistence), Optional.of(ephemeralSecretPersistence)); longLivedSecretsHydrator = new RealSecretsHydrator(longLivedSecretPersistence); longLivedSecretsRepositoryReader = new SecretsRepositoryReader(configRepository, longLivedSecretsHydrator); ephemeralSecretsHydrator = new RealSecretsHydrator(ephemeralSecretPersistence); ephemeralSecretsRepositoryReader = new SecretsRepositoryReader(configRepository, ephemeralSecretsHydrator); } @Test void testWriteSourceConnection() throws JsonValidationException, IOException, ConfigNotFoundException { doThrow(ConfigNotFoundException.class).when(configRepository).getSourceConnection(UUID1); secretsRepositoryWriter.writeSourceConnection(SOURCE_WITH_FULL_CONFIG, SPEC); final SecretCoordinate coordinate = getCoordinateFromSecretsStore(longLivedSecretPersistence); assertNotNull(coordinate); final SourceConnection partialSource = injectCoordinateIntoSource(coordinate.getFullCoordinate()); verify(configRepository).writeSourceConnectionNoSecrets(partialSource); final Optional<String> persistedSecret = longLivedSecretPersistence.read(coordinate); assertTrue(persistedSecret.isPresent()); assertEquals(SECRET, persistedSecret.get()); // verify that the round trip works. reset(configRepository); when(configRepository.getSourceConnection(UUID1)).thenReturn(partialSource); assertEquals(SOURCE_WITH_FULL_CONFIG, longLivedSecretsRepositoryReader.getSourceConnectionWithSecrets(UUID1)); } @Test void testWriteDestinationConnection() throws JsonValidationException, IOException, ConfigNotFoundException { doThrow(ConfigNotFoundException.class).when(configRepository).getDestinationConnection(UUID1); secretsRepositoryWriter.writeDestinationConnection(DESTINATION_WITH_FULL_CONFIG, SPEC); final SecretCoordinate coordinate = getCoordinateFromSecretsStore(longLivedSecretPersistence); assertNotNull(coordinate); final DestinationConnection partialDestination = injectCoordinateIntoDestination(coordinate.getFullCoordinate()); verify(configRepository).writeDestinationConnectionNoSecrets(partialDestination); final Optional<String> persistedSecret = longLivedSecretPersistence.read(coordinate); assertTrue(persistedSecret.isPresent()); assertEquals(SECRET, persistedSecret.get()); // verify that the round trip works. reset(configRepository); when(configRepository.getDestinationConnection(UUID1)).thenReturn(partialDestination); assertEquals(DESTINATION_WITH_FULL_CONFIG, longLivedSecretsRepositoryReader.getDestinationConnectionWithSecrets(UUID1)); } @Test void testStatefulSplitEphemeralSecrets() throws JsonValidationException, IOException, ConfigNotFoundException { final JsonNode split = secretsRepositoryWriter.statefulSplitEphemeralSecrets( SOURCE_WITH_FULL_CONFIG.getConfiguration(), SPEC); final SecretCoordinate coordinate = getCoordinateFromSecretsStore(ephemeralSecretPersistence); assertNotNull(coordinate); final Optional<String> persistedSecret = ephemeralSecretPersistence.read(coordinate); assertTrue(persistedSecret.isPresent()); assertEquals(SECRET, persistedSecret.get()); // verify that the round trip works. assertEquals(SOURCE_WITH_FULL_CONFIG.getConfiguration(), ephemeralSecretsHydrator.hydrate(split)); } @SuppressWarnings("unchecked") @Test void testReplaceAllConfigs() throws IOException { final Map<AirbyteConfig, Stream<?>> configs = new HashMap<>(); configs.put(ConfigSchema.STANDARD_SOURCE_DEFINITION, Stream.of(Jsons.clone(SOURCE_DEF))); configs.put(ConfigSchema.STANDARD_DESTINATION_DEFINITION, Stream.of(Jsons.clone(DEST_DEF))); configs.put(ConfigSchema.SOURCE_CONNECTION, Stream.of(Jsons.clone(SOURCE_WITH_FULL_CONFIG))); configs.put(ConfigSchema.DESTINATION_CONNECTION, Stream.of(Jsons.clone(DESTINATION_WITH_FULL_CONFIG))); secretsRepositoryWriter.replaceAllConfigs(configs, false); final ArgumentCaptor<Map<AirbyteConfig, Stream<?>>> argument = ArgumentCaptor.forClass(Map.class); verify(configRepository).replaceAllConfigsNoSecrets(argument.capture(), eq(false)); final Map<AirbyteConfig, ? extends List<?>> actual = argument.getValue().entrySet() .stream() .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().collect(Collectors.toList()))); assertEquals(SOURCE_DEF, actual.get(ConfigSchema.STANDARD_SOURCE_DEFINITION).get(0)); assertEquals(DEST_DEF, actual.get(ConfigSchema.STANDARD_DESTINATION_DEFINITION).get(0)); // we can't easily get the pointer, so verify the secret has been stripped out and then make sure // the rest of the object meets expectations. final SourceConnection actualSource = (SourceConnection) actual.get(ConfigSchema.SOURCE_CONNECTION).get(0); assertTrue(actualSource.getConfiguration().get(PASSWORD_PROPERTY_NAME).has(PASSWORD_FIELD_NAME)); ((ObjectNode) actualSource.getConfiguration()).remove(PASSWORD_PROPERTY_NAME); final SourceConnection expectedSource = Jsons.clone(SOURCE_WITH_FULL_CONFIG); ((ObjectNode) expectedSource.getConfiguration()).remove(PASSWORD_PROPERTY_NAME); assertEquals(expectedSource, actualSource); final DestinationConnection actualDest = (DestinationConnection) actual.get(ConfigSchema.DESTINATION_CONNECTION).get(0); assertTrue(actualDest.getConfiguration().get(PASSWORD_PROPERTY_NAME).has(PASSWORD_FIELD_NAME)); ((ObjectNode) actualDest.getConfiguration()).remove(PASSWORD_PROPERTY_NAME); final DestinationConnection expectedDest = Jsons.clone(DESTINATION_WITH_FULL_CONFIG); ((ObjectNode) expectedDest.getConfiguration()).remove(PASSWORD_PROPERTY_NAME); assertEquals(expectedDest, actualDest); } // this only works if the secrets store has one secret. private SecretCoordinate getCoordinateFromSecretsStore(final MemorySecretPersistence secretPersistence) { return secretPersistence.getMap() .keySet() .stream() .findFirst() .orElse(null); } private static JsonNode injectCoordinate(final String coordinate) { return Jsons.deserialize(String.format("{ \"username\": \"airbyte\", \"password\": { \"_secret\": \"%s\" } }", coordinate)); } private static SourceConnection injectCoordinateIntoSource(final String coordinate) { return Jsons.clone(SOURCE_WITH_FULL_CONFIG).withConfiguration(injectCoordinate(coordinate)); } private static DestinationConnection injectCoordinateIntoDestination(final String coordinate) { return Jsons.clone(DESTINATION_WITH_FULL_CONFIG).withConfiguration(injectCoordinate(coordinate)); } @Test void testWriteWorkspaceServiceAccount() throws JsonValidationException, ConfigNotFoundException, IOException { final UUID workspaceId = UUID.randomUUID(); final String jsonSecretPayload = MOCK_SERVICE_ACCOUNT_1; final WorkspaceServiceAccount workspaceServiceAccount = new WorkspaceServiceAccount() .withWorkspaceId(workspaceId) .withHmacKey(HMAC_SECRET_PAYLOAD_1) .withServiceAccountId("a1e5ac98-7531-48e1-943b-b46636") .withServiceAccountEmail("nnheo@example.com") .withJsonCredential(Jsons.deserialize(jsonSecretPayload)); doThrow(new ConfigNotFoundException(ConfigSchema.WORKSPACE_SERVICE_ACCOUNT, workspaceId.toString())) .when(configRepository).getWorkspaceServiceAccountNoSecrets(workspaceId); secretsRepositoryWriter.writeServiceAccountJsonCredentials(workspaceServiceAccount); assertEquals(2, longLivedSecretPersistence.getMap().size()); String jsonPayloadInPersistence = null; String hmacPayloadInPersistence = null; SecretCoordinate jsonSecretCoordinate = null; SecretCoordinate hmacSecretCoordinate = null; for (final Map.Entry<SecretCoordinate, String> entry : longLivedSecretPersistence.getMap().entrySet()) { if (entry.getKey().getFullCoordinate().contains("json")) { jsonSecretCoordinate = entry.getKey(); jsonPayloadInPersistence = entry.getValue(); } else if (entry.getKey().getFullCoordinate().contains("hmac")) { hmacSecretCoordinate = entry.getKey(); hmacPayloadInPersistence = entry.getValue(); } else { throw new RuntimeException(""); } } assertNotNull(jsonPayloadInPersistence); assertNotNull(hmacPayloadInPersistence); assertNotNull(jsonSecretCoordinate); assertNotNull(hmacSecretCoordinate); assertEquals(jsonSecretPayload, jsonPayloadInPersistence); assertEquals(HMAC_SECRET_PAYLOAD_1.toString(), hmacPayloadInPersistence); verify(configRepository).writeWorkspaceServiceAccountNoSecrets( Jsons.clone(workspaceServiceAccount.withJsonCredential(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, jsonSecretCoordinate.getFullCoordinate()))) .withHmacKey(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, hmacSecretCoordinate.getFullCoordinate()))))); } @Test void testWriteSameStagingConfiguration() throws JsonValidationException, ConfigNotFoundException, IOException { final ConfigRepository configRepository = mock(ConfigRepository.class); final SecretPersistence secretPersistence = mock(SecretPersistence.class); final SecretsRepositoryWriter secretsRepositoryWriter = spy( new SecretsRepositoryWriter(configRepository, Optional.of(secretPersistence), Optional.of(secretPersistence))); final UUID workspaceId = UUID.fromString("13fb9a84-6bfa-4801-8f5e-ce717677babf"); final String jsonSecretPayload = MOCK_SERVICE_ACCOUNT_1; final WorkspaceServiceAccount workspaceServiceAccount = new WorkspaceServiceAccount().withWorkspaceId(workspaceId).withHmacKey( HMAC_SECRET_PAYLOAD_1) .withServiceAccountId("a1e5ac98-7531-48e1-943b-b46636") .withServiceAccountEmail("nnheo@example.com") .withJsonCredential(Jsons.deserialize(jsonSecretPayload)); final SecretCoordinate jsonSecretCoordinate = new SecretCoordinate( "service_account_json_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 1); final SecretCoordinate hmacSecretCoordinate = new SecretCoordinate( "service_account_hmac_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 1); final WorkspaceServiceAccount cloned = Jsons.clone(workspaceServiceAccount) .withJsonCredential(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, jsonSecretCoordinate.getFullCoordinate()))) .withHmacKey(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, hmacSecretCoordinate.getFullCoordinate()))); doReturn(cloned).when(configRepository).getWorkspaceServiceAccountNoSecrets(workspaceId); doReturn(Optional.of(jsonSecretPayload)).when(secretPersistence).read(jsonSecretCoordinate); doReturn(Optional.of(HMAC_SECRET_PAYLOAD_1.toString())).when(secretPersistence).read(hmacSecretCoordinate); secretsRepositoryWriter.writeServiceAccountJsonCredentials(workspaceServiceAccount); final ArgumentCaptor<SecretCoordinate> coordinates = ArgumentCaptor.forClass(SecretCoordinate.class); final ArgumentCaptor<String> payloads = ArgumentCaptor.forClass(String.class); verify(secretPersistence, times(2)).write(coordinates.capture(), payloads.capture()); final List<SecretCoordinate> actualCoordinates = coordinates.getAllValues(); assertEquals(2, actualCoordinates.size()); assertThat(actualCoordinates, containsInAnyOrder(jsonSecretCoordinate, hmacSecretCoordinate)); final List<String> actualPayload = payloads.getAllValues(); assertEquals(2, actualPayload.size()); assertThat(actualPayload, containsInAnyOrder(jsonSecretPayload, HMAC_SECRET_PAYLOAD_1.toString())); verify(secretPersistence).write(hmacSecretCoordinate, HMAC_SECRET_PAYLOAD_1.toString()); verify(configRepository).writeWorkspaceServiceAccountNoSecrets( cloned); } @Test void testWriteDifferentStagingConfiguration() throws JsonValidationException, ConfigNotFoundException, IOException { final ConfigRepository configRepository = mock(ConfigRepository.class); final SecretPersistence secretPersistence = mock(SecretPersistence.class); final SecretsRepositoryWriter secretsRepositoryWriter = spy(new SecretsRepositoryWriter(configRepository, Optional.of(secretPersistence), Optional.of(secretPersistence))); final UUID workspaceId = UUID.fromString("13fb9a84-6bfa-4801-8f5e-ce717677babf"); final String jsonSecretOldPayload = MOCK_SERVICE_ACCOUNT_1; final String jsonSecretNewPayload = MOCK_SERVICE_ACCOUNT_2; final WorkspaceServiceAccount workspaceServiceAccount = new WorkspaceServiceAccount() .withWorkspaceId(workspaceId) .withHmacKey(HMAC_SECRET_PAYLOAD_2) .withServiceAccountId("a1e5ac98-7531-48e1-943b-b46636") .withServiceAccountEmail("nnheo@example.com") .withJsonCredential(Jsons.deserialize(jsonSecretNewPayload)); final SecretCoordinate jsonSecretOldCoordinate = new SecretCoordinate( "service_account_json_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 1); final SecretCoordinate hmacSecretOldCoordinate = new SecretCoordinate( "service_account_hmac_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 1); final WorkspaceServiceAccount cloned = Jsons.clone(workspaceServiceAccount) .withJsonCredential(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, jsonSecretOldCoordinate.getFullCoordinate()))) .withHmacKey(Jsons.jsonNode(Map.of(PASSWORD_FIELD_NAME, hmacSecretOldCoordinate.getFullCoordinate()))); doReturn(cloned).when(configRepository).getWorkspaceServiceAccountNoSecrets(workspaceId); doReturn(Optional.of(HMAC_SECRET_PAYLOAD_1.toString())).when(secretPersistence).read(hmacSecretOldCoordinate); doReturn(Optional.of(jsonSecretOldPayload)).when(secretPersistence).read(jsonSecretOldCoordinate); secretsRepositoryWriter.writeServiceAccountJsonCredentials(workspaceServiceAccount); final SecretCoordinate jsonSecretNewCoordinate = new SecretCoordinate( "service_account_json_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 2); final SecretCoordinate hmacSecretNewCoordinate = new SecretCoordinate( "service_account_hmac_13fb9a84-6bfa-4801-8f5e-ce717677babf_secret_e86e2eab-af9b-42a3-b074-b923b4fa617e", 2); final ArgumentCaptor<SecretCoordinate> coordinates = ArgumentCaptor.forClass(SecretCoordinate.class); final ArgumentCaptor<String> payloads = ArgumentCaptor.forClass(String.class); verify(secretPersistence, times(2)).write(coordinates.capture(), payloads.capture()); final List<SecretCoordinate> actualCoordinates = coordinates.getAllValues(); assertEquals(2, actualCoordinates.size()); assertThat(actualCoordinates, containsInAnyOrder(jsonSecretNewCoordinate, hmacSecretNewCoordinate)); final List<String> actualPayload = payloads.getAllValues(); assertEquals(2, actualPayload.size()); assertThat(actualPayload, containsInAnyOrder(jsonSecretNewPayload, HMAC_SECRET_PAYLOAD_2.toString())); verify(configRepository).writeWorkspaceServiceAccountNoSecrets(Jsons.clone(workspaceServiceAccount).withJsonCredential(Jsons.jsonNode( Map.of(PASSWORD_FIELD_NAME, jsonSecretNewCoordinate.getFullCoordinate()))).withHmacKey(Jsons.jsonNode( Map.of(PASSWORD_FIELD_NAME, hmacSecretNewCoordinate.getFullCoordinate())))); } }
9235f1f92a515e8ca58b3e2bf9c7419478b37561
1,942
java
Java
domain/src/main/java/io/github/carlomicieli/catalog/brands/BrandFactory.java
CarloMicieli/microtrains
8124129b9e87dfc69a5540fecd3134a3a9024513
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
domain/src/main/java/io/github/carlomicieli/catalog/brands/BrandFactory.java
CarloMicieli/microtrains
8124129b9e87dfc69a5540fecd3134a3a9024513
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
domain/src/main/java/io/github/carlomicieli/catalog/brands/BrandFactory.java
CarloMicieli/microtrains
8124129b9e87dfc69a5540fecd3134a3a9024513
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
30.825397
95
0.709578
997,473
/* Copyright 2021 (C) Carlo Micieli 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.github.carlomicieli.catalog.brands; import io.github.carlomicieli.addresses.Address; import io.github.carlomicieli.domain.AggregateRootFactory; import io.github.carlomicieli.mail.MailAddress; import io.github.carlomicieli.util.Slug; import java.net.URL; import java.time.Clock; import java.util.function.Supplier; public final class BrandFactory extends AggregateRootFactory<Brand, BrandId> { public BrandFactory(Clock clock, Supplier<BrandId> identifierSource) { super(clock, identifierSource); } /** * Creates a new {@code Brand}, this method is not making any validation. The caller needs to * ensure only a valid object is created. */ public Brand createNewBrand( String name, String companyName, URL websiteUrl, String groupName, String description, Address address, BrandKind brandKind, MailAddress mailAddress) { var newId = generateNewId(); var createdDate = getCurrentInstant(); Slug brandSlug = Brand.buildSlug(name); return Brand.builder() .id(newId) .name(name) .slug(brandSlug) .companyName(companyName) .groupName(groupName) .address(address) .mailAddress(mailAddress) .brandKind(brandKind) .version(1) .createdDate(createdDate) .build(); } }
9235f32d1d697a5ebe83958eb718db1670f3e917
581
java
Java
service/service-cms/src/main/java/com/aiden/cms/BannerMain.java
AidenDan/education-parent
d35629990d76371f575354a8240877d4fe398397
[ "Apache-2.0" ]
1
2021-01-29T15:29:44.000Z
2021-01-29T15:29:44.000Z
service/service-cms/src/main/java/com/aiden/cms/BannerMain.java
AidenDan/education-parent
d35629990d76371f575354a8240877d4fe398397
[ "Apache-2.0" ]
null
null
null
service/service-cms/src/main/java/com/aiden/cms/BannerMain.java
AidenDan/education-parent
d35629990d76371f575354a8240877d4fe398397
[ "Apache-2.0" ]
null
null
null
25.26087
72
0.786575
997,474
package com.aiden.cms; import com.codingapi.txlcn.tc.config.EnableDistributedTransaction; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @author Aiden * @version 1.0 * @description * @date 2021-2-14 14:02:32 */ @EnableDistributedTransaction @EnableDiscoveryClient @SpringBootApplication public class BannerMain { public static void main(String[] args) { SpringApplication.run(BannerMain.class, args); } }
9235f363eb40a98169ea25a4e9ea0f50f60d31ef
2,962
java
Java
openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidatorTest.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
15
2018-10-02T14:54:35.000Z
2022-03-01T18:27:14.000Z
openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidatorTest.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
1
2021-09-21T17:35:15.000Z
2021-09-21T17:35:15.000Z
openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidatorTest.java
chardon1/onap-sdc
b2370800befb9c7c557a0651717a8fd604736542
[ "Apache-2.0" ]
31
2018-05-30T19:18:29.000Z
2022-03-01T06:16:47.000Z
44.878788
129
0.708305
997,475
/*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR; import static org.openecomp.sdc.tosca.csar.ToscaMetaEntryVersion261.OTHER_DEFINITIONS; import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.TestConstants.TOSCA_DEFINITION_FILEPATH; import org.openecomp.sdc.tosca.csar.ManifestTokenType; import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager; public class SOL004Version3MetaDirectoryValidatorTest extends SOL004MetaDirectoryValidatorTest { @Override public SOL004MetaDirectoryValidator getSOL004MetaDirectoryValidator() { return new SOL004Version3MetaDirectoryValidator(); } @Override public StringBuilder getMetaFileBuilder() { return super.getMetaFileBuilder().append(OTHER_DEFINITIONS.getName()) .append(ATTRIBUTE_VALUE_SEPARATOR.getToken()).append(" ").append(TOSCA_DEFINITION_FILEPATH).append("\n"); } @Override protected SOL004MetaDirectoryValidator getSol004WithSecurity(SecurityManager securityManagerMock) { return new SOL004Version3MetaDirectoryValidator(securityManagerMock); } @Override protected ManifestBuilder getVnfManifestSampleBuilder() { return super.getVnfManifestSampleBuilder() .withMetaData(ManifestTokenType.VNFD_ID.getToken(), "2116fd24-83f2-416b-bf3c-ca1964793aca") .withMetaData(ManifestTokenType.COMPATIBLE_SPECIFICATION_VERSIONS.getToken(), "2.7.1,3.3.1") .withMetaData(ManifestTokenType.VNF_SOFTWARE_VERSION.getToken(), "1.0.0") .withMetaData(ManifestTokenType.VNFM_INFO.getToken(), "etsivnfm:v2.3.1,0:myGreatVnfm-1"); } @Override protected ManifestBuilder getPnfManifestSampleBuilder() { return super.getPnfManifestSampleBuilder() .withMetaData(ManifestTokenType.COMPATIBLE_SPECIFICATION_VERSIONS.getToken(), "2.7.1,3.3.1"); } @Override protected int getManifestDefinitionErrorCount() { return 2; } }
9235f36da8044f15d808f62c6362d36ed9abda17
3,480
java
Java
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/WrapperLayerParamInitializer.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
13,006
2015-02-13T18:35:31.000Z
2022-03-18T12:11:44.000Z
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/WrapperLayerParamInitializer.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
5,319
2015-02-13T08:21:46.000Z
2019-06-12T14:56:50.000Z
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/params/WrapperLayerParamInitializer.java
zhangy10/deeplearning4j
9d31156ce600dee6ce4a7fac28286ebbaa211164
[ "Apache-2.0" ]
4,719
2015-02-13T22:48:55.000Z
2022-03-22T07:25:36.000Z
32.222222
115
0.658908
997,476
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.params; import org.deeplearning4j.nn.api.ParamInitializer; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.layers.Layer; import org.deeplearning4j.nn.conf.layers.wrapper.BaseWrapperLayer; import org.nd4j.linalg.api.ndarray.INDArray; import java.util.List; import java.util.Map; public class WrapperLayerParamInitializer implements ParamInitializer { private static final WrapperLayerParamInitializer INSTANCE = new WrapperLayerParamInitializer(); public static WrapperLayerParamInitializer getInstance(){ return INSTANCE; } private WrapperLayerParamInitializer(){ } @Override public long numParams(NeuralNetConfiguration conf) { return numParams(conf.getLayer()); } @Override public long numParams(Layer layer) { Layer l = underlying(layer); return l.initializer().numParams(l); } @Override public List<String> paramKeys(Layer layer) { Layer l = underlying(layer); return l.initializer().paramKeys(l); } @Override public List<String> weightKeys(Layer layer) { Layer l = underlying(layer); return l.initializer().weightKeys(l); } @Override public List<String> biasKeys(Layer layer) { Layer l = underlying(layer); return l.initializer().biasKeys(l); } @Override public boolean isWeightParam(Layer layer, String key) { Layer l = underlying(layer); return l.initializer().isWeightParam(layer, key); } @Override public boolean isBiasParam(Layer layer, String key) { Layer l = underlying(layer); return l.initializer().isBiasParam(layer, key); } @Override public Map<String, INDArray> init(NeuralNetConfiguration conf, INDArray paramsView, boolean initializeParams) { Layer orig = conf.getLayer(); Layer l = underlying(conf.getLayer()); conf.setLayer(l); Map<String,INDArray> m = l.initializer().init(conf, paramsView, initializeParams); conf.setLayer(orig); return m; } @Override public Map<String, INDArray> getGradientsFromFlattened(NeuralNetConfiguration conf, INDArray gradientView) { Layer orig = conf.getLayer(); Layer l = underlying(conf.getLayer()); conf.setLayer(l); Map<String,INDArray> m = l.initializer().getGradientsFromFlattened(conf, gradientView); conf.setLayer(orig); return m; } private Layer underlying(Layer layer){ while (layer instanceof BaseWrapperLayer) { layer = ((BaseWrapperLayer)layer).getUnderlying(); } return layer; } }
9235f46da456243b13dae3528ad564aa8cb5cc00
404
java
Java
src/main/java/org/januslabs/oauth2/jwt/mongo/repository/OAuthRefreshTokenRepository.java
nandhusriram/jwt_token_mongo_store
6b77bdec162f9cfd35a8ef19d28193ab159c1422
[ "Apache-2.0" ]
2
2016-03-28T02:09:11.000Z
2017-03-27T11:59:05.000Z
src/main/java/org/januslabs/oauth2/jwt/mongo/repository/OAuthRefreshTokenRepository.java
nandhusriram/jwt_token_mongo_store
6b77bdec162f9cfd35a8ef19d28193ab159c1422
[ "Apache-2.0" ]
null
null
null
src/main/java/org/januslabs/oauth2/jwt/mongo/repository/OAuthRefreshTokenRepository.java
nandhusriram/jwt_token_mongo_store
6b77bdec162f9cfd35a8ef19d28193ab159c1422
[ "Apache-2.0" ]
null
null
null
33.666667
97
0.851485
997,477
package org.januslabs.oauth2.jwt.mongo.repository; import org.januslabs.oauth2.jwt.mongo.domain.OAuthRefreshToken; import org.springframework.data.mongodb.repository.MongoRepository; public interface OAuthRefreshTokenRepository extends MongoRepository<OAuthRefreshToken, String> { public OAuthRefreshToken findByTokenId(String tokenId); public void delete(OAuthRefreshToken oauthRefreshToken); }
9235f4941af4ffe8f137ac0cbb2fee9b959986ff
115
java
Java
junit4osgi-runner/src/test/java/org/example/PropertyTest.java
nfalco79/osgi.junit4
5ec5e48a43e6045c004ca581238649cfb55389b0
[ "Apache-2.0" ]
3
2018-03-12T13:18:12.000Z
2018-11-20T17:09:37.000Z
junit4osgi-runner/src/test/java/org/example/PropertyTest.java
nfalco79/osgi.junit4
5ec5e48a43e6045c004ca581238649cfb55389b0
[ "Apache-2.0" ]
18
2018-05-13T18:47:04.000Z
2022-02-15T10:14:23.000Z
junit4osgi-runner/src/test/java/org/example/PropertyTest.java
nfalco79/osgi.junit4
5ec5e48a43e6045c004ca581238649cfb55389b0
[ "Apache-2.0" ]
null
null
null
10.454545
27
0.713043
997,478
package org.example; import org.junit.Test; public class PropertyTest { @Test public void do_nothing() { } }
9235f5acefe7b95ebdd8cd52fe15b1243b8f6124
2,052
java
Java
nodecore-cli/src/main/java/nodecore/cli/commands/serialization/CoinbaseTransactionInfo.java
PCasafont/nodecore
974651eaf1560261b4936a0bd12e006b0b838815
[ "MIT" ]
null
null
null
nodecore-cli/src/main/java/nodecore/cli/commands/serialization/CoinbaseTransactionInfo.java
PCasafont/nodecore
974651eaf1560261b4936a0bd12e006b0b838815
[ "MIT" ]
null
null
null
nodecore-cli/src/main/java/nodecore/cli/commands/serialization/CoinbaseTransactionInfo.java
PCasafont/nodecore
974651eaf1560261b4936a0bd12e006b0b838815
[ "MIT" ]
null
null
null
36.642857
108
0.765595
997,479
// VeriBlock NodeCore CLI // Copyright 2017-2019 Xenios SEZC // All rights reserved. // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. package nodecore.cli.commands.serialization; import com.google.gson.annotations.SerializedName; import nodecore.api.grpc.VeriBlockMessages; import nodecore.api.grpc.utilities.ByteStringUtility; import org.veriblock.core.utilities.Utility; import java.util.ArrayList; import java.util.List; public class CoinbaseTransactionInfo { public CoinbaseTransactionInfo(final VeriBlockMessages.CoinbaseTransaction coinbaseTransaction) { coinbase_tx_hash = ByteStringUtility.byteStringToHex(coinbaseTransaction.getTxId()); powCoinbaseAmount = Utility.formatAtomicLongWithDecimal(coinbaseTransaction.getPowCoinbaseAmount()); popCoinbaseAmount = Utility.formatAtomicLongWithDecimal(coinbaseTransaction.getPopCoinbaseAmount()); powFeeShare = Utility.formatAtomicLongWithDecimal(coinbaseTransaction.getPowFeeShare()); popFeeShare = Utility.formatAtomicLongWithDecimal(coinbaseTransaction.getPopFeeShare()); for (VeriBlockMessages.Output powOutput : coinbaseTransaction.getPowOutputsList()) { powOutputs.add(new OutputInfo(powOutput)); } for (VeriBlockMessages.Output popOutput : coinbaseTransaction.getPopOutputsList()) { popOutputs.add(new OutputInfo(popOutput)); } } @SerializedName("pow_coinbase_amount") public String powCoinbaseAmount; @SerializedName("pop_coinbase_amount") public String popCoinbaseAmount; @SerializedName("pow_fee_share") public String powFeeShare; @SerializedName("pop_fee_share") public String popFeeShare; @SerializedName("pow_outputs") public List<OutputInfo> powOutputs = new ArrayList<>(); @SerializedName("pop_outputs") public List<OutputInfo> popOutputs = new ArrayList<>(); public String coinbase_tx_hash; }
9235f701e414cf20b12cc723a13c3060abc54749
5,366
java
Java
CubbyHole.DesktopApp/src/com/cubbyhole/desktop/windows/OAuthBrowser.java
AlexisChevalier/CubbyHole
e3d8a84f9f1e0c0468b30b5468bc1bc86a6b764c
[ "MIT" ]
null
null
null
CubbyHole.DesktopApp/src/com/cubbyhole/desktop/windows/OAuthBrowser.java
AlexisChevalier/CubbyHole
e3d8a84f9f1e0c0468b30b5468bc1bc86a6b764c
[ "MIT" ]
null
null
null
CubbyHole.DesktopApp/src/com/cubbyhole/desktop/windows/OAuthBrowser.java
AlexisChevalier/CubbyHole
e3d8a84f9f1e0c0468b30b5468bc1bc86a6b764c
[ "MIT" ]
null
null
null
30.662857
88
0.720089
997,480
package com.cubbyhole.desktop.windows; import java.awt.Dimension; import java.awt.Toolkit; import java.security.GeneralSecurityException; import java.util.ArrayList; import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.SwingUtilities; import com.cubbyhole.desktop.utils.CHC; import com.cubbyhole.desktop.utils.TokenStorer; import com.cubbyhole.library.http.CHHeader; import com.cubbyhole.library.http.CHHttp; import com.cubbyhole.library.http.CHHttpDatas; import com.cubbyhole.library.http.CHHttpResponse; import com.cubbyhole.library.logger.Log; public class OAuthBrowser { protected static final String TAG = OAuthBrowser.class.getName(); private static int wndWidth; private static int wndHeight; public OAuthBrowser(final String url, int width, int height) { wndWidth = width; wndHeight = height; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initAndShowGUI(url); } }); } /* Create a JFrame containing the WebView. */ private static void initAndShowGUI(final String url) { JFrame frame = new JFrame("CubbyHole Authentication"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon imageIcon = new ImageIcon(OAuthBrowser.class.getResource(CHC.APP_ICON)); if (imageIcon != null) { frame.setIconImage(imageIcon.getImage()); } final JFXPanel fxPanel = new JFXPanel(); fxPanel.setSize(new Dimension(wndWidth, wndHeight)); frame.add(fxPanel); frame.getContentPane().setPreferredSize(new Dimension(wndWidth - 10, wndHeight - 10)); frame.pack(); frame.setResizable(false); frame.setVisible(true); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2); Platform.runLater(new Runnable() { @Override public void run() { initFX(fxPanel, url); } }); } /* Creates a WebView and display the url */ private static void initFX(final JFXPanel fxPanel, String url) { Group group = new Group(); Scene scene = new Scene(group); fxPanel.setScene(scene); WebView webView = new WebView(); group.getChildren().add(webView); webView.setMinSize(wndWidth, wndHeight); webView.setMaxSize(wndWidth, wndHeight); if (CHC.IGNORE_NOT_TRUSTED_CERT) { ignoreSSLCertificatesValidity(); } // Obtain the webEngine to navigate WebEngine webEngine = webView.getEngine(); webEngine.load(url); webEngine.setOnStatusChanged(new EventHandler<WebEvent<String>>() { @Override public void handle(WebEvent<String> event) { Object obj = event.getSource(); if (obj instanceof WebEngine) { WebEngine wbe = (WebEngine) event.getSource(); String url = wbe.getLocation(); //TODO: Somewhere else: String accessCodeFragment = CHC.OAUTH_PARAM_ACCESS_CODE + CHC.EQUAL; if (TokenStorer.getAccessToken() == null && url.contains(accessCodeFragment)) { // the GET request contains an authorization code String accessCode = url.substring(url.indexOf(accessCodeFragment)); if (accessCode != null) { accessCode = accessCode.split("=")[1]; Log.d(TAG, "We got the access code: " + accessCode); } ArrayList<CHHeader> headers = new ArrayList<CHHeader>(); headers.add(new CHHeader("Content-Type", "application/x-www-form-urlencoded")); CHHttpDatas datas = new CHHttpDatas() // .add(CHC.OAUTH_PARAM_CLIENT_ID, CHC.OAUTH_CLIENT_ID) // .add(CHC.OAUTH_PARAM_SECRET, CHC.OAUTH_CLIENT_SECRET) // .add(CHC.OAUTH_PARAM_CALLBACK, CHC.OAUTH_CALLBACK_URL) // .add(CHC.OAUTH_PARAM_GRANT_TYPE, CHC.OAUTH_GRANT_TYPE) // .add(CHC.OAUTH_PARAM_ACCESS_CODE, accessCode); CHHttpResponse response = CHHttp.post(CHC.OAUTH_URL_ACCESS_TOKEN, datas, headers, null); try { String token = response.getJson().asText(CHC.OAUTH_PARAM_ACESS_TOKEN); TokenStorer.setAccessToken(token); Log.d(TAG, token); } catch (Exception e) { Log.e(TAG, "Failed to get the access_token from the response !"); e.printStackTrace(); } } } } }); } private static void ignoreSSLCertificatesValidity() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException e) { } } }
9235f8bb2aa039eb7ca2db86e5f7503832c66b04
799
java
Java
spring-context/src/test/java/org/springframework/context/annotation/role/ComponentWithoutRole.java
user0819/spring
0edbaa1612989e7fc048c77787e96658a2f05b9a
[ "Apache-2.0" ]
4
2020-09-25T16:06:44.000Z
2021-07-02T15:43:02.000Z
spring-context/src/test/java/org/springframework/context/annotation/role/ComponentWithoutRole.java
user0819/spring
0edbaa1612989e7fc048c77787e96658a2f05b9a
[ "Apache-2.0" ]
4
2020-01-16T17:50:29.000Z
2022-03-08T21:12:39.000Z
spring-context/src/test/java/org/springframework/context/annotation/role/ComponentWithoutRole.java
user0819/spring
0edbaa1612989e7fc048c77787e96658a2f05b9a
[ "Apache-2.0" ]
10
2020-12-03T03:22:28.000Z
2021-04-30T13:35:41.000Z
34.73913
75
0.762203
997,481
/* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation.role; import org.springframework.stereotype.Component; @Component("componentWithoutRole") public class ComponentWithoutRole { }
9235f928ec2935574e2fdbf653db32b837685136
4,269
java
Java
clients/src/main/java/org/apache/kafka/common/record/Records.java
love1314sea/my_kafka-0.10.2.1
90dd02db80c2a4a8a0a66eacd69b4894d04c2c26
[ "Apache-2.0" ]
6
2021-01-29T01:13:26.000Z
2022-02-17T06:03:03.000Z
clients/src/main/java/org/apache/kafka/common/record/Records.java
love1314sea/my_kafka-0.10.2.1
90dd02db80c2a4a8a0a66eacd69b4894d04c2c26
[ "Apache-2.0" ]
null
null
null
clients/src/main/java/org/apache/kafka/common/record/Records.java
love1314sea/my_kafka-0.10.2.1
90dd02db80c2a4a8a0a66eacd69b4894d04c2c26
[ "Apache-2.0" ]
null
null
null
46.912088
121
0.725931
997,482
/** * 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.kafka.common.record; import java.io.IOException; import java.nio.channels.GatheringByteChannel; /** * Interface for accessing the records contained in a log. The log itself is represented as a sequence of log entries. * Each log entry consists of an 8 byte offset, a 4 byte record size, and a "shallow" {@link Record record}. * If the entry is not compressed, then each entry will have only the shallow record contained inside it. If it is * compressed, the entry contains "deep" records, which are packed into the value field of the shallow record. To iterate * over the shallow records, use {@link #shallowEntries()}; for the deep records, use {@link #deepEntries()}. Note * that the deep iterator handles both compressed and non-compressed entries: if the entry is not compressed, the * shallow record is returned; otherwise, the shallow record is decompressed and the deep entries are returned. * See {@link MemoryRecords} for the in-memory representation and {@link FileRecords} for the on-disk representation. */ public interface Records { int OFFSET_OFFSET = 0; int OFFSET_LENGTH = 8; int SIZE_OFFSET = OFFSET_OFFSET + OFFSET_LENGTH; int SIZE_LENGTH = 4; int LOG_OVERHEAD = SIZE_OFFSET + SIZE_LENGTH; /** * The size of these records in bytes. * @return The size in bytes of the records */ int sizeInBytes(); /** * Attempts to write the contents of this buffer to a channel. * @param channel The channel to write to * @param position The position in the buffer to write from * @param length The number of bytes to write * @return The number of bytes actually written * @throws IOException For any IO errors */ long writeTo(GatheringByteChannel channel, long position, int length) throws IOException; /** * Get the shallow log entries in this log buffer. Note that the signature allows subclasses * to return a more specific log entry type. This enables optimizations such as in-place offset * assignment (see {@link ByteBufferLogInputStream.ByteBufferLogEntry}), and partial reading of * record data (see {@link FileLogInputStream.FileChannelLogEntry#magic()}. * @return An iterator over the shallow entries of the log */ Iterable<? extends LogEntry> shallowEntries(); /** * Get the deep log entries (i.e. descend into compressed message sets). For the deep records, * there are fewer options for optimization since the data must be decompressed before it can be * returned. Hence there is little advantage in allowing subclasses to return a more specific type * as we do for {@link #shallowEntries()}. * @return An iterator over the deep entries of the log */ Iterable<LogEntry> deepEntries(); /** * Check whether all shallow entries in this buffer have a certain magic value. * @param magic The magic value to check * @return true if all shallow entries have a matching magic value, false otherwise */ boolean hasMatchingShallowMagic(byte magic); /** * Convert all entries in this buffer to the format passed as a parameter. Note that this requires * deep iteration since all of the deep records must also be converted to the desired format. * @param toMagic The magic value to convert to * @return A Records (which may or may not be the same instance) */ Records toMessageFormat(byte toMagic); }
9235f96ecfc50cd13c6c47eb8753d09bb2863f83
2,747
java
Java
JavaServer/ChChessServer/src/net/wdqipai/server/extmodel/QiziName.java
wdqipai/521266750_qq_com
6efbb975c5e3d4fd2d1cc04545b9200a4b5c7ffc
[ "Apache-2.0" ]
109
2015-08-24T09:01:32.000Z
2022-01-28T22:06:03.000Z
JavaServer/ChChessServer/src/net/wdqipai/server/extmodel/QiziName.java
yangyonglin/521266750_qq_com
6efbb975c5e3d4fd2d1cc04545b9200a4b5c7ffc
[ "Apache-2.0" ]
1
2019-11-20T12:50:36.000Z
2019-11-20T12:50:36.000Z
JavaServer/ChChessServer/src/net/wdqipai/server/extmodel/QiziName.java
yangyonglin/521266750_qq_com
6efbb975c5e3d4fd2d1cc04545b9200a4b5c7ffc
[ "Apache-2.0" ]
100
2015-09-21T14:46:27.000Z
2022-02-23T10:29:18.000Z
40.382353
66
0.723962
997,483
/* * SilverFoxServer: massive multiplayer game server for Flash, ... * VERSION:3.0 * PUBLISH DATE:2015-9-2 * GITHUB:github.com/wdmir/521266750_qq_com * UPDATES AND DOCUMENTATION AT: http://www.silverfoxserver.net * COPYRIGHT 2009-2015 SilverFoxServer.NET. All rights reserved. * MAIL:efpyi@example.com */ package net.wdqipai.server.extmodel; import net.wdqipai.server.*; /** 与客户端的State.Room.RoomModel.QiziName对应 */ public class QiziName { //En是元数据,共用 public final static String En_Bing = "bing"; public final static String En_Pao = "pao"; public final static String En_Ju = "ju"; public final static String En_Ma = "ma"; public final static String En_Xiang = "xiang"; public final static String En_Shi = "shi"; public final static String En_Jiang = "jiang"; /** * 红方棋子 */ public final static String red_bing_1 = "red_bing_1"; public final static String red_bing_2 = "red_bing_2"; public final static String red_bing_3 = "red_bing_3"; public final static String red_bing_4 = "red_bing_4"; public final static String red_bing_5 = "red_bing_5"; public final static String red_pao_1 = "red_pao_1"; public final static String red_pao_2 = "red_pao_2"; public final static String red_ju_1 = "red_ju_1"; public final static String red_ju_2 = "red_ju_2"; public final static String red_ma_1 = "red_ma_1"; public final static String red_ma_2 = "red_ma_2"; public final static String red_xiang_1 = "red_xiang_1"; public final static String red_xiang_2 = "red_xiang_2"; public final static String red_shi_1 = "red_shi_1"; public final static String red_shi_2 = "red_shi_2"; public final static String red_jiang_1 = "red_jiang_1"; /** * 黑方棋子 */ public final static String black_bing_1 = "black_bing_1"; public final static String black_bing_2 = "black_bing_2"; public final static String black_bing_3 = "black_bing_3"; public final static String black_bing_4 = "black_bing_4"; public final static String black_bing_5 = "black_bing_5"; public final static String black_pao_1 = "black_pao_1"; public final static String black_pao_2 = "black_pao_2"; public final static String black_ju_1 = "black_ju_1"; public final static String black_ju_2 = "black_ju_2"; public final static String black_ma_1 = "black_ma_1"; public final static String black_ma_2 = "black_ma_2"; public final static String black_xiang_1 = "black_xiang_1"; public final static String black_xiang_2 = "black_xiang_2"; public final static String black_shi_1 = "black_shi_1"; public final static String black_shi_2 = "black_shi_2"; public final static String black_jiang_1 = "black_jiang_1"; }
9235fa1503531b3c1fa1ef35bc9cefc5155ddd9b
2,570
java
Java
src/test/java/com/canfactory/html/iterators/TakeNIteratorTest.java
CanFactory/canfactory-html
2c021cbe1fed7eb4d6e82cdf741476ed7085691f
[ "Apache-2.0" ]
1
2017-08-19T12:51:33.000Z
2017-08-19T12:51:33.000Z
src/test/java/com/canfactory/html/iterators/TakeNIteratorTest.java
CanFactory/canfactory-html
2c021cbe1fed7eb4d6e82cdf741476ed7085691f
[ "Apache-2.0" ]
null
null
null
src/test/java/com/canfactory/html/iterators/TakeNIteratorTest.java
CanFactory/canfactory-html
2c021cbe1fed7eb4d6e82cdf741476ed7085691f
[ "Apache-2.0" ]
2
2015-09-21T09:51:47.000Z
2018-12-14T11:42:22.000Z
33.402597
98
0.601866
997,484
//----------------------------------------------------------------------- // Copyright Can Factory Limited, UK // http://www.canfactory.com - mailto:kenaa@example.com // // The copyright to the computer program(s) (source files, compiled // files and documentation) herein is the property of Can Factory // Limited, UK. // // The program(s) may be used and/or copied only with the written // permission of Can Factory Limited or in accordance with the terms // and conditions stipulated in the agreement/contract under which // the program(s) have been supplied. //----------------------------------------------------------------------- package com.canfactory.html.iterators; import org.testng.annotations.Test; import java.util.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.fail; /** * Created by ian on 23/02/2015. */ @Test public class TakeNIteratorTest { private Iterator<String> rawList; public void shouldTakeFirstN() { rawList = Arrays.asList("a", "b", "c").iterator(); assertEquals(consumeIter(new TakeNIterator<String>(rawList, 2)), Arrays.asList("a", "b")); assertEquals(consumeIter(new TakeNIterator<String>(rawList, 2)), Arrays.asList("c")); assertEquals(consumeIter(new TakeNIterator<String>(rawList, 2)), Collections.EMPTY_LIST); } protected List<String> consumeIter(Iterator<String> iter) { List<String> results = new ArrayList<String>(); while (iter.hasNext()) { results.add(iter.next()); } assertEndfOfIterator(iter); return results; } protected void assertEndfOfIterator(Iterator iter) { // random pick a strategy boolean testHasNextFirst = new Random(System.currentTimeMillis()).nextBoolean(); //testHasNextFirst = true; if (testHasNextFirst) { assertFalse(iter.hasNext(), "hasNext() called first and should return false"); try { iter.next(); fail("NoSuchElementException expected - calling hasNext first"); } catch (NoSuchElementException nsex) { // expected } } else { try { iter.next(); fail("NoSuchElementException expected - calling next first"); } catch (NoSuchElementException nsex) { // expected } assertFalse(iter.hasNext(), "hasNext() called last and should return false"); } } }
9235fa4b87c322e4a54364596d7553cac0bc5ab5
1,476
java
Java
actividades/prog/files/java/mil-ejemplos/darwin/strings/Undent.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
actividades/prog/files/java/mil-ejemplos/darwin/strings/Undent.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
actividades/prog/files/java/mil-ejemplos/darwin/strings/Undent.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
26.357143
66
0.589431
997,485
package strings; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; /** Undent - remove leading spaces * @author Ian F. Darwin, http://www.darwinsys.com/ * @version $Id: Undent.java,v 1.7 2006/04/11 22:58:40 ian Exp $ */ public class Undent { /** the maximum number of spaces to remove. */ protected int nSpaces; Undent(int n) { nSpaces = n; } public static void main(String[] av) { Undent c = new Undent(5); switch(av.length) { case 0: c.process(new BufferedReader( new InputStreamReader(System.in))); break; default: for (int i=0; i<av.length; i++) try { c.process(new BufferedReader(new FileReader(av[i]))); } catch (FileNotFoundException e) { System.err.println(e); } } } /** print one file, given an open BufferedReader */ public void process(BufferedReader is) { try { String inputLine; //+ while ((inputLine = is.readLine()) != null) { int toRemove = 0; for (int i=0; i<nSpaces && i < inputLine.length() && Character.isWhitespace(inputLine.charAt(i)); i++) ++toRemove; System.out.println(inputLine.substring(toRemove)); } //- is.close(); } catch (IOException e) { System.out.println("IOException: " + e); } } }
9235fb0822f65c122ab562729df73e1c4f41645e
2,032
java
Java
ph-commons/src/test/java/com/helger/commons/hierarchy/ChildrenProviderHasChildrenWithIDTest.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
29
2015-09-08T06:44:38.000Z
2022-02-25T08:15:02.000Z
ph-commons/src/test/java/com/helger/commons/hierarchy/ChildrenProviderHasChildrenWithIDTest.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
20
2017-01-05T16:31:14.000Z
2022-01-04T11:17:40.000Z
ph-commons/src/test/java/com/helger/commons/hierarchy/ChildrenProviderHasChildrenWithIDTest.java
phax/ph-commons
973db756523f3f49217e14fac8589fb504bae481
[ "Apache-2.0" ]
14
2015-03-23T13:43:32.000Z
2022-01-11T07:08:42.000Z
36.945455
125
0.739665
997,486
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]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.helger.commons.hierarchy; 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.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Test class for class {@link ChildrenProviderHasChildrenWithID}. * * @author Philip Helger */ public final class ChildrenProviderHasChildrenWithIDTest { @Test public void testAll () { final ChildrenProviderHasChildrenWithID <String, MockHasSortedChildren> cr = new ChildrenProviderHasChildrenWithID <> (); assertFalse (cr.hasChildren (null)); assertEquals (0, cr.getChildCount (null)); assertNull (cr.getAllChildren (null)); final MockHasSortedChildren hca = new MockHasSortedChildren ("a"); final MockHasSortedChildren hcb = new MockHasSortedChildren ("b"); final MockHasSortedChildren hc1 = new MockHasSortedChildren ("1", hcb, hca); assertTrue (cr.hasChildren (hc1)); assertFalse (cr.hasChildren (hca)); assertEquals (2, cr.getChildCount (hc1)); assertEquals (0, cr.getChildCount (hca)); assertNotNull (cr.getAllChildren (hc1)); assertNotNull (cr.getAllChildren (hca)); assertSame (hca, cr.getChildWithID (hc1, "a")); assertNull (cr.getChildWithID (hc1, "anyid")); } }
9235fb3c63ce6a9b9e301a49e1cd85a809f365d0
733
java
Java
src/test/java/hu/resanbt/visualparadigm/scripting/usecase/CloseDialogOnCloseButtonUseCaseTest.java
sz332/visual_paradigm_scripting_plugin_oss
d5b7642b2fd7d209711a16197f3e309bf69e1558
[ "Apache-2.0" ]
null
null
null
src/test/java/hu/resanbt/visualparadigm/scripting/usecase/CloseDialogOnCloseButtonUseCaseTest.java
sz332/visual_paradigm_scripting_plugin_oss
d5b7642b2fd7d209711a16197f3e309bf69e1558
[ "Apache-2.0" ]
3
2021-12-19T16:34:24.000Z
2021-12-24T13:15:27.000Z
src/test/java/hu/resanbt/visualparadigm/scripting/usecase/CloseDialogOnCloseButtonUseCaseTest.java
sz332/visual_paradigm_scripting_plugin_oss
d5b7642b2fd7d209711a16197f3e309bf69e1558
[ "Apache-2.0" ]
null
null
null
17.878049
52
0.634379
997,487
package hu.resanbt.visualparadigm.scripting.usecase; //import com.athaydes.automaton.Swinger; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * https://github.com/renatoathaydes/Automaton */ public class CloseDialogOnCloseButtonUseCaseTest { //Swinger swinger; MainApp myApp; @Before public void setup() { myApp = new MainApp(); myApp.start(); //swinger = Swinger.forSwingWindow(); } @After public void tearDown() { myApp.getDialog().dispose(); } @Test public void testFeature() { //swinger.clickOn("closeButton"); //swinger.clickOn( "closeButton" ); //assertNotNull(myApp.getDialog()); } }
9235fb3fb81589cfc04cf3759d93baf50c900396
1,838
java
Java
MySlidingProject/src/com/ihateflyingbugs/kidsm/login/RegisterClassItem.java
xxx4u/kidsm_for_android
eaf8797ff6099dfdc58070fd92269f5bb75f2daa
[ "Apache-2.0" ]
1
2015-04-03T09:03:31.000Z
2015-04-03T09:03:31.000Z
MySlidingProject/src/com/ihateflyingbugs/kidsm/login/RegisterClassItem.java
xxx4u/kidsm_for_android
eaf8797ff6099dfdc58070fd92269f5bb75f2daa
[ "Apache-2.0" ]
null
null
null
MySlidingProject/src/com/ihateflyingbugs/kidsm/login/RegisterClassItem.java
xxx4u/kidsm_for_android
eaf8797ff6099dfdc58070fd92269f5bb75f2daa
[ "Apache-2.0" ]
null
null
null
25.178082
79
0.73123
997,488
package com.ihateflyingbugs.kidsm.login; import java.util.ArrayList; import com.ihateflyingbugs.kidsm.BaseItem; import com.ihateflyingbugs.kidsm.uploadphoto.InputTag; import android.os.Parcel; import android.os.Parcelable; import android.view.View; public class RegisterClassItem extends BaseItem implements Parcelable { private String class_srl; private ArrayList<RegisterChildItem> childList; View layout; public RegisterClassItem(String class_srl, String name) { this.setClass_srl(class_srl); this.setChildList(new ArrayList<RegisterChildItem>()); this.name = name; } public void addChild(RegisterChildItem item) { getChildList().add(item); } // Parcelling part public RegisterClassItem(Parcel in){ setClass_srl(in.readString()); name = in.readString(); setChildList(new ArrayList<RegisterChildItem>()); in.readTypedList(getChildList(), RegisterChildItem.CREATOR); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public RegisterClassItem createFromParcel(Parcel in) { return new RegisterClassItem(in); } public RegisterClassItem[] newArray(int size) { return new RegisterClassItem[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getClass_srl()); dest.writeString(name); dest.writeTypedList(getChildList()); } public String getClass_srl() { return class_srl; } public void setClass_srl(String class_srl) { this.class_srl = class_srl; } public ArrayList<RegisterChildItem> getChildList() { return childList; } public void setChildList(ArrayList<RegisterChildItem> childList) { this.childList = childList; } }
9235fb46ac49a91bf37132848635648d5ca3622a
4,013
java
Java
orson-charts-1.7/src/test/java/com/orsoncharts/table/GradientRectanglePainterTest.java
uuganaa6000/analytics
dcc9e51f74189f8d878fb3bf759574ab5b4db051
[ "Apache-2.0" ]
null
null
null
orson-charts-1.7/src/test/java/com/orsoncharts/table/GradientRectanglePainterTest.java
uuganaa6000/analytics
dcc9e51f74189f8d878fb3bf759574ab5b4db051
[ "Apache-2.0" ]
null
null
null
orson-charts-1.7/src/test/java/com/orsoncharts/table/GradientRectanglePainterTest.java
uuganaa6000/analytics
dcc9e51f74189f8d878fb3bf759574ab5b4db051
[ "Apache-2.0" ]
null
null
null
40.13
80
0.678545
997,489
/* =========================================================== * Orson Charts : a 3D chart library for the Java(tm) platform * =========================================================== * * (C)opyright 2013-2016, by Object Refinery Limited. All rights reserved. * * http://www.object-refinery.com/orsoncharts/index.html * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * Orson Charts home page: * * http://www.object-refinery.com/orsoncharts/index.html * */ package com.orsoncharts.table; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import java.awt.Color; import com.orsoncharts.TestUtils; import com.orsoncharts.TitleAnchor; /** * Tests for the {@link GradientRectanglePainter} class. */ public class GradientRectanglePainterTest { @Test public void testEquals() { GradientRectanglePainter grp1 = new GradientRectanglePainter(Color.RED, TitleAnchor.TOP_CENTER, Color.BLUE, TitleAnchor.BOTTOM_CENTER); GradientRectanglePainter grp2 = new GradientRectanglePainter(Color.RED, TitleAnchor.TOP_CENTER, Color.BLUE, TitleAnchor.BOTTOM_CENTER); assertTrue(grp1.equals(grp2)); grp1 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_CENTER, Color.BLUE, TitleAnchor.BOTTOM_CENTER); assertFalse(grp1.equals(grp2)); grp2 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_CENTER, Color.BLUE, TitleAnchor.BOTTOM_CENTER); assertTrue(grp1.equals(grp2)); grp1 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.BLUE, TitleAnchor.BOTTOM_CENTER); assertFalse(grp1.equals(grp2)); grp2 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.BLUE, TitleAnchor.BOTTOM_CENTER); assertTrue(grp1.equals(grp2)); grp1 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.YELLOW, TitleAnchor.BOTTOM_CENTER); assertFalse(grp1.equals(grp2)); grp2 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.YELLOW, TitleAnchor.BOTTOM_CENTER); assertTrue(grp1.equals(grp2)); grp1 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.YELLOW, TitleAnchor.BOTTOM_RIGHT); assertFalse(grp1.equals(grp2)); grp2 = new GradientRectanglePainter(Color.GRAY, TitleAnchor.TOP_LEFT, Color.YELLOW, TitleAnchor.BOTTOM_RIGHT); assertTrue(grp1.equals(grp2)); } /** * A check for serialization. */ @Test public void testSerialization() { GradientRectanglePainter grp1 = new GradientRectanglePainter(Color.RED, TitleAnchor.TOP_CENTER, Color.BLUE, TitleAnchor.BOTTOM_CENTER); GradientRectanglePainter grp2 = (GradientRectanglePainter) TestUtils.serialized(grp1); assertEquals(grp1, grp2); } }
9235fb6d6ab030d6ac630add000f340082559908
666
java
Java
lectures/class7_8/Problem_19_SmallestMissNum.java
fzheng/codejam
5fbec4ef7f4737351c48ada6d52294260fa70efa
[ "MIT" ]
null
null
null
lectures/class7_8/Problem_19_SmallestMissNum.java
fzheng/codejam
5fbec4ef7f4737351c48ada6d52294260fa70efa
[ "MIT" ]
null
null
null
lectures/class7_8/Problem_19_SmallestMissNum.java
fzheng/codejam
5fbec4ef7f4737351c48ada6d52294260fa70efa
[ "MIT" ]
1
2016-08-24T01:08:34.000Z
2016-08-24T01:08:34.000Z
20.8125
74
0.498498
997,490
package class7_8; public class Problem_19_SmallestMissNum { public static int missNum(int[] arr) { int l = 0; int r = arr.length; while (l < r) { if (arr[l] == l + 1) { l++; } else if (arr[l] <= l || arr[l] > r || arr[arr[l] - 1] == arr[l]) { arr[l] = arr[--r]; } else { swap(arr, l, arr[l] - 1); } } return l + 1; } public static void swap(int[] arr, int index1, int index2) { int tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; } public static void main(String[] args) { int[] arr = {-1, 0, 2, 1, 3, 5}; System.out.println(missNum(arr)); } }
9235fbcb2a5183e3a642795c4a0bb3b3e4086317
1,254
java
Java
chapter_007/src/main/java/ru/job4j/storexml/ParserSax.java
nihrom205/zava-a-to-z
ce7c66b480baf26706a75b2fc15f1e18c3b05972
[ "Apache-2.0" ]
2
2017-11-11T16:45:00.000Z
2018-02-13T07:37:56.000Z
chapter_007/src/main/java/ru/job4j/storexml/ParserSax.java
nihrom205/zava-a-to-z
ce7c66b480baf26706a75b2fc15f1e18c3b05972
[ "Apache-2.0" ]
9
2020-03-04T22:21:23.000Z
2021-12-09T20:45:24.000Z
chapter_007/src/main/java/ru/job4j/storexml/ParserSax.java
nihrom205/zava-a-to-z
ce7c66b480baf26706a75b2fc15f1e18c3b05972
[ "Apache-2.0" ]
null
null
null
26.229167
121
0.638602
997,491
package ru.job4j.storexml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; /** * Class Parser. * * @author Alexey Rastorguev (envkt@example.com) * @version 0.1 * @since 16.07.2018 */ public class ParserSax { private int value = 0; /** * Метод считает сумму значений и выводит в консоль результат. * @param f файл из которыго считываются данные. */ public void count(File f) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); XMLHandler handler = new XMLHandler(); parser.parse(f, handler); } catch (Exception e) { e.printStackTrace(); } System.out.println(value); } private class XMLHandler extends DefaultHandler { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equals("entry")) { value += Integer.valueOf(attributes.getValue("href")); } } } }
9235fc3e518b823d0a72b646ce18c1c61ef6b0a5
2,439
java
Java
src/main/java/com/timeyang/amanda/api/CategoryEndpoint.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
8
2017-05-06T15:16:57.000Z
2021-06-23T08:02:13.000Z
src/main/java/com/timeyang/amanda/api/CategoryEndpoint.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
null
null
null
src/main/java/com/timeyang/amanda/api/CategoryEndpoint.java
codeSourc3/amanda
60883b77f56f1d053de02d9dff2d3f4e27279448
[ "Apache-2.0" ]
6
2017-09-09T05:09:00.000Z
2020-12-13T20:34:58.000Z
32.092105
74
0.701107
997,492
package com.timeyang.amanda.api; import com.timeyang.amanda.blog.domain.Category; import com.timeyang.amanda.blog.domain.CategoryPathNode; import com.timeyang.amanda.blog.service.CategoryService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * Category rest端点 * @author chaokunyang * @create 2017-04-25 */ @RestController @RequestMapping(value = "/api/categories") public class CategoryEndpoint { private static final Logger LOGGER = LogManager.getLogger(); @Autowired private CategoryService categoryService; @RequestMapping(method = RequestMethod.GET) public Category getRootCategoryTree() { LOGGER.info("获取分类树"); return categoryService.getRootCategoryTree(); } @RequestMapping(value = "/first_levels", method = RequestMethod.GET) public List<Category> getFirstLevelCategories() { LOGGER.info("获取第一级所有分类"); return categoryService.getFirstLevelCategories(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Category getCategory(@PathVariable Long id) { LOGGER.info("获取指定分类,分类id: " + id); return categoryService.getCategory(id); } @RequestMapping(value = "/path/{id}", method = RequestMethod.GET) public List<CategoryPathNode> getCategoryPath(@PathVariable Long id) { LOGGER.info("获取指定分类路径,分类id: " + id); return categoryService.getCategoryPath(id); } @RequestMapping(value = "/tree/{id}", method = RequestMethod.GET) public Category getCategoryTree(@PathVariable Long id) { LOGGER.info("获取指定分类,分类id: " + id); return categoryService.getCategoryTree(id); } @RequestMapping(method = RequestMethod.PUT) public Category update(@RequestBody Category category) { LOGGER.info("更新分类: {}", category); return categoryService.save(category); } @RequestMapping(method = RequestMethod.POST) public Category create(@RequestBody Category category) { LOGGER.info("创建分类: {}", category); return categoryService.create(category); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void delete(@PathVariable Long id) { LOGGER.info("删除分类,分类id: {}", id); categoryService.delete(id); } }
9235fc6cb3b8345f187c48b2c3d3ac446e0f8fa4
2,106
java
Java
test/src/main/java/com/timer/ScheduledManager.java
smallwy/spring-note
63b603ed5c4153440e9a2e2cc1d8852b91617d7c
[ "Apache-2.0" ]
null
null
null
test/src/main/java/com/timer/ScheduledManager.java
smallwy/spring-note
63b603ed5c4153440e9a2e2cc1d8852b91617d7c
[ "Apache-2.0" ]
null
null
null
test/src/main/java/com/timer/ScheduledManager.java
smallwy/spring-note
63b603ed5c4153440e9a2e2cc1d8852b91617d7c
[ "Apache-2.0" ]
null
null
null
25.071429
79
0.706078
997,493
package com.timer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.DelayQueue; public class ScheduledManager{ private Map<String, Trigger> runJobMap = new ConcurrentHashMap(); private DelayQueue<Trigger> taskQueue = new DelayQueue(); private WorldScene worldScene = WorldScene.getInstance(); private static ScheduledManager instance = new ScheduledManager(); public static ScheduledManager getInstance() { return instance; } public void execute() { while (true) { Trigger trigger = taskQueue.poll(); if (trigger != null) { worldScene.executeWorker(new JobRunService(trigger, runJobMap, taskQueue)); } } } public Map<String, Trigger> getRunJobMap() { return this.runJobMap; } public DelayQueue<Trigger> getTaskQueue() { return this.taskQueue; } public void schedule(Trigger trigger) { if ((trigger == null) || (trigger.getName() == null)) { throw new IllegalArgumentException("任务为空or任务参数不完整"); } if (this.runJobMap.containsKey(trigger.getName())) { throw new RuntimeException("已存在同名任务:" + trigger.getName()); } trigger.setSeqNum(Trigger.sequencer.getAndIncrement()); boolean ans = this.taskQueue.offer(trigger); if (ans) { this.runJobMap.put(trigger.getName(), trigger); } else { throw new RuntimeException("添加任务失败:" + trigger.getName()); } } public Trigger getTrigger(String name) { return this.runJobMap.get(name); } public boolean contains(String name) { return this.runJobMap.containsKey(name); } public boolean cancel(String jobName) { boolean ans = false; Trigger trigger = this.runJobMap.get(jobName); if (trigger != null) { trigger.setCancel(true); trigger.setTask(null); trigger.setListener(null); this.runJobMap.remove(trigger.getName()); ans = true; } return ans; } public String schInfo() { StringBuilder sb = new StringBuilder(); sb.append("当前正在执行的任务列表(总计" + this.runJobMap.size() + "个) \n"); for (Trigger trg : this.runJobMap.values()) { sb.append(trg.toString()); sb.append("\n"); } return sb.toString(); } }
9235fc73af48c8e1d0d6726a6263129b2456a262
2,951
java
Java
src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HashOutputStream.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
16,989
2015-09-01T19:57:15.000Z
2022-03-31T23:54:00.000Z
src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HashOutputStream.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
12,562
2015-09-01T09:06:01.000Z
2022-03-31T22:26:20.000Z
src/main/java/com/google/devtools/build/lib/bazel/repository/downloader/HashOutputStream.java
chadm-sq/bazel
715c9faabba573501c9cb7604192759950633205
[ "Apache-2.0" ]
3,707
2015-09-02T19:20:01.000Z
2022-03-31T17:06:14.000Z
32.788889
100
0.732972
997,494
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.repository.downloader; import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible; import java.io.IOException; import java.io.OutputStream; import javax.annotation.Nullable; import javax.annotation.WillCloseWhenClosed; /** * Output stream that guarantees its contents matches a hash code. * * <p>The actual checksum is computed gradually as the output is written. If it doesn't match, then * an {@link IOException} will be thrown when {@link #close()} is called. This error will be thrown * multiple times if these methods are called again for some reason. * * <p>Note that as the checksum can only be computed once the stream is closed, data will be written * to the underlying stream regardless of whether it matches the expected checksum. * * <p>This class is not thread safe, but it is safe to message pass this object between threads. */ @ThreadCompatible public final class HashOutputStream extends OutputStream { private final OutputStream delegate; private final Hasher hasher; private final HashCode code; @Nullable private volatile HashCode actual; public HashOutputStream(@WillCloseWhenClosed OutputStream delegate, Checksum checksum) { this.delegate = delegate; this.hasher = checksum.getKeyType().newHasher(); this.code = checksum.getHashCode(); } @Override public void write(int buffer) throws IOException { hasher.putByte((byte) buffer); delegate.write(buffer); } @Override public void write(byte[] buffer) throws IOException { hasher.putBytes(buffer); delegate.write(buffer); } @Override public void write(byte[] buffer, int offset, int length) throws IOException { hasher.putBytes(buffer, offset, length); delegate.write(buffer, offset, length); } @Override public void flush() throws IOException { delegate.flush(); } @Override public void close() throws IOException { delegate.close(); check(); } private void check() throws IOException { if (actual == null) { actual = hasher.hash(); } if (!code.equals(actual)) { throw new UnrecoverableHttpException( String.format("Checksum was %s but wanted %s", actual, code)); } } }
9235fd2af64089961ac8e8f2ece57b135044b5b1
3,795
java
Java
src/main/java/frc/robot/commands/autonomous/Slalom.java
AndrewLester/2021-robot
124e62b9968d26e54ea99ef54f1bb053c294af85
[ "MIT" ]
5
2021-02-05T20:00:57.000Z
2022-03-02T12:05:44.000Z
src/main/java/frc/robot/commands/autonomous/Slalom.java
AndrewLester/2021-robot
124e62b9968d26e54ea99ef54f1bb053c294af85
[ "MIT" ]
32
2020-12-16T00:45:47.000Z
2021-04-15T19:26:29.000Z
src/main/java/frc/robot/commands/autonomous/Slalom.java
AndrewLester/2021-robot
124e62b9968d26e54ea99ef54f1bb053c294af85
[ "MIT" ]
26
2021-01-16T15:03:42.000Z
2022-01-06T19:38:23.000Z
55.808824
101
0.595784
997,495
package frc.robot.commands.autonomous; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.geometry.Rotation2d; import edu.wpi.first.wpilibj.geometry.Translation2d; import edu.wpi.first.wpilibj.trajectory.Trajectory; import edu.wpi.first.wpilibj.trajectory.TrajectoryConfig; import edu.wpi.first.wpilibj.trajectory.TrajectoryGenerator; import edu.wpi.first.wpilibj.trajectory.constraint.CentripetalAccelerationConstraint; import edu.wpi.first.wpilibj.trajectory.constraint.DifferentialDriveVoltageConstraint; import edu.wpi.first.wpilibj.trajectory.constraint.RectangularRegionConstraint; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.robot.Constants; import frc.robot.commands.FollowTrajectoryCommand; import frc.robot.common.Odometry; import frc.robot.subsystems.DriveSubsystem; import frc.robot.subsystems.Limelight; import java.util.List; public class Slalom extends SequentialCommandGroup { public static final double MAX_GENERATION_VELOCITY = 3.5; // Meters per second public static final double MAX_GENERATION_ACCELERATION = 2.2; // Meters per second squared public Slalom(DriveSubsystem driveSubsystem, Odometry odometry, Limelight limelight, AHRS navx) { TrajectoryConfig forwardConfig = new TrajectoryConfig(MAX_GENERATION_VELOCITY, MAX_GENERATION_ACCELERATION) .setKinematics(DriveSubsystem.KINEMATICS) .addConstraint( new DifferentialDriveVoltageConstraint( DriveSubsystem.FEED_FORWARD, DriveSubsystem.KINEMATICS, Constants.MAX_GENERATION_VOLTAGE)) .addConstraint(new CentripetalAccelerationConstraint(4)) .addConstraint( new RectangularRegionConstraint( new Translation2d(6.743, -3.874), new Translation2d(8.7, -2.07), new CentripetalAccelerationConstraint(2.5))); Trajectory slalom = TrajectoryGenerator.generateTrajectory( new Pose2d(1.156, -3.886, new Rotation2d(0)), List.of( new Translation2d(2.43869629218164, -2.76885043743924), new Translation2d(3.50534814609082, -2.41329981946951), new Translation2d(4.99104179975003, -2.32441216497708), new Translation2d(6.47673545340924, -2.57837689209831), new Translation2d(6.99736314400777, -3.47995167337869), new Translation2d(7.874, -3.886), new Translation2d(8.674, -2.95932398278016), new Translation2d(7.874, -2.363), new Translation2d(7.378, -2.629), new Translation2d(7.162, -3.226), new Translation2d(6.299, -4.039), new Translation2d(3.84820052770448, -3.75931287321205), new Translation2d(2.769, -3.277), new Translation2d(2.147, -2.388)), new Pose2d(1.258, -1.918, new Rotation2d(3.14159)), forwardConfig); addCommands( new InstantCommand(() -> navx.reset()), new FollowTrajectoryCommand(slalom, odometry, driveSubsystem)); } }
9235fddfde7f811fe79262529184842528eaa048
1,406
java
Java
algorithms/designmanual/backtracking/Combinations.java
vj20284/Study
9dc6954b4cb3b218c3153b217567a49a7a8d185b
[ "MIT" ]
null
null
null
algorithms/designmanual/backtracking/Combinations.java
vj20284/Study
9dc6954b4cb3b218c3153b217567a49a7a8d185b
[ "MIT" ]
null
null
null
algorithms/designmanual/backtracking/Combinations.java
vj20284/Study
9dc6954b4cb3b218c3153b217567a49a7a8d185b
[ "MIT" ]
null
null
null
27.568627
78
0.655761
997,496
package com.practise.algorithms.designmanual.backtracking; import java.util.ArrayList; import java.util.List; public class Combinations { public List<List<Integer>> combinations(List<Integer> elements, int k) { return helper(elements, 0, k); } public List<List<Integer>> helper(List<Integer> elements, int start, int k) { List<List<Integer>> combinations = new ArrayList<List<Integer>>(); if (k == 1) { for (int i = start; i < elements.size(); i++) { List<Integer> newList = new ArrayList<Integer>(); newList.add(elements.get(i)); combinations.add(newList); } return combinations; } List<List<Integer>> myCombinations = new ArrayList<List<Integer>>(); for (int i = start; i <= elements.size() - k; i++) { List<List<Integer>> nextCombinations = helper(elements, i + 1, k - 1); for (List<Integer> list : nextCombinations) { list.add(0, elements.get(i)); myCombinations.add(list); } } return myCombinations; } public static void main(String[] args) { int k = 3; List<Integer> elements = new ArrayList<Integer>(); elements.add(1); elements.add(2); elements.add(3); elements.add(4); elements.add(5); Combinations c = new Combinations(); List<List<Integer>> ret = c.combinations(elements, k); for (List<Integer> list : ret) { for (Integer i : list) { System.out.print(i + " "); } System.out.println(); } } }
9235fe904c725c23e6283f7e4f91961775b1c35f
3,019
java
Java
src/main/java/seedu/trackermon/commons/core/GuiSettings.java
arcornior/tp
31124202a1f949bab45c85399a709e607b3e6ef9
[ "MIT" ]
1
2022-03-09T05:50:46.000Z
2022-03-09T05:50:46.000Z
src/main/java/seedu/trackermon/commons/core/GuiSettings.java
arcornior/tp
31124202a1f949bab45c85399a709e607b3e6ef9
[ "MIT" ]
162
2022-02-16T17:05:02.000Z
2022-03-31T16:22:15.000Z
src/main/java/seedu/trackermon/commons/core/GuiSettings.java
arcornior/tp
31124202a1f949bab45c85399a709e607b3e6ef9
[ "MIT" ]
5
2022-02-15T15:28:24.000Z
2022-02-16T13:42:37.000Z
31.123711
95
0.648559
997,497
package seedu.trackermon.commons.core; import java.awt.Point; import java.io.Serializable; import java.util.Objects; /** * A Serializable class that contains the GUI settings. * Guarantees: immutable. */ public class GuiSettings implements Serializable { private static final double DEFAULT_HEIGHT = 600; private static final double DEFAULT_WIDTH = 740; private final double windowWidth; private final double windowHeight; private final Point windowCoordinates; /** * Constructs a {@code GuiSettings} with the default height, width and position. */ public GuiSettings() { windowWidth = DEFAULT_WIDTH; windowHeight = DEFAULT_HEIGHT; windowCoordinates = null; // null represent no coordinates } /** * Constructs a {@code GuiSettings} with the specified height, width and position. * @param windowWidth the specified width of the window to be created. * @param windowHeight the specified height of the window to be created. * @param xPosition the x position of the window to be created. * @param yPosition the y position of the window to be created. */ public GuiSettings(double windowWidth, double windowHeight, int xPosition, int yPosition) { this.windowWidth = windowWidth; this.windowHeight = windowHeight; windowCoordinates = new Point(xPosition, yPosition); } public double getWindowWidth() { return windowWidth; } public double getWindowHeight() { return windowHeight; } public Point getWindowCoordinates() { return windowCoordinates != null ? new Point(windowCoordinates) : null; } /** * Returns whether the other object specified is equals this object. * @param other object to be checked against this object. * @return true if the other object is equal to this object. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof GuiSettings)) { //this handles null as well. return false; } GuiSettings o = (GuiSettings) other; return windowWidth == o.windowWidth && windowHeight == o.windowHeight && Objects.equals(windowCoordinates, o.windowCoordinates); } /** * Returns the hash code of the {@code GuiSettings} object. * @return a hash code of the object. */ @Override public int hashCode() { return Objects.hash(windowWidth, windowHeight, windowCoordinates); } /** * Returns a string representation of the {@code GuiSettings} object. * @return the string of the object. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Width : " + windowWidth + "\n"); sb.append("Height : " + windowHeight + "\n"); sb.append("Position : " + windowCoordinates); return sb.toString(); } }
923600697a84d5419516123bdef26bac282ce0a1
2,448
java
Java
log4j-1.2-api/src/main/java/org/apache/log4j/config/Log4j1Configuration.java
CrazyBills/logging-log4j2
b5635efa03bed3098d447caf07c24b5defe8f68c
[ "Apache-2.0" ]
3,034
2015-01-19T14:45:09.000Z
2022-03-31T06:11:10.000Z
log4j-1.2-api/src/main/java/org/apache/log4j/config/Log4j1Configuration.java
CrazyBills/logging-log4j2
b5635efa03bed3098d447caf07c24b5defe8f68c
[ "Apache-2.0" ]
559
2015-03-11T15:45:08.000Z
2022-03-31T17:56:24.000Z
log4j-1.2-api/src/main/java/org/apache/log4j/config/Log4j1Configuration.java
CrazyBills/logging-log4j2
b5635efa03bed3098d447caf07c24b5defe8f68c
[ "Apache-2.0" ]
1,620
2015-01-31T09:10:08.000Z
2022-03-31T17:42:41.000Z
35.478261
99
0.735703
997,498
/* * 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.log4j.config; import org.apache.log4j.builders.BuilderManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.AbstractConfiguration; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Reconfigurable; /** * Base Configuration for Log4j 1. */ public class Log4j1Configuration extends AbstractConfiguration implements Reconfigurable { public static final String MONITOR_INTERVAL = "log4j1.monitorInterval"; public static final String APPENDER_REF_TAG = "appender-ref"; public static final String THRESHOLD_PARAM = "Threshold"; public static final String INHERITED = "inherited"; public static final String NULL = "null"; protected final BuilderManager manager; public Log4j1Configuration(final LoggerContext loggerContext, final ConfigurationSource source, int monitorIntervalSeconds) { super(loggerContext, source); manager = new BuilderManager(); initializeWatchers(this, source, monitorIntervalSeconds); } public BuilderManager getBuilderManager() { return manager; } /** * Initialize the configuration. */ @Override public void initialize() { getStrSubstitutor().setConfiguration(this); super.getScheduler().start(); doConfigure(); setState(State.INITIALIZED); LOGGER.debug("Configuration {} initialized", this); } @Override public Configuration reconfigure() { return null; } }
923601ac3f41577825e372fdf930cbbefff6ffd6
3,692
java
Java
src/org/primeoservices/cfgateway/jms/lucee/AbstractLuceeJMSGateway.java
jbvanzuylen/cf-jms-gateway
728870e5128428a1cc2b8c3774e8730b3af3acc8
[ "Apache-2.0" ]
7
2016-10-13T22:09:30.000Z
2021-08-22T14:19:23.000Z
src/org/primeoservices/cfgateway/jms/lucee/AbstractLuceeJMSGateway.java
jbvanzuylen/cf-jms-gateway
728870e5128428a1cc2b8c3774e8730b3af3acc8
[ "Apache-2.0" ]
1
2018-01-03T12:54:06.000Z
2019-09-27T11:35:29.000Z
src/org/primeoservices/cfgateway/jms/lucee/AbstractLuceeJMSGateway.java
jbvanzuylen/cf-jms-gateway
728870e5128428a1cc2b8c3774e8730b3af3acc8
[ "Apache-2.0" ]
1
2021-08-08T19:32:06.000Z
2021-08-08T19:32:06.000Z
22.931677
85
0.689599
997,499
/* * Copyright 2016 Jean-Bernard van Zuylen * * 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.primeoservices.cfgateway.jms.lucee; import java.io.IOException; import java.util.Map; import org.primeoservices.cfgateway.jms.JMSConfiguration; import org.primeoservices.cfgateway.jms.JMSExchanger; import org.primeoservices.cfgateway.jms.JMSGateway; import org.primeoservices.cfgateway.jms.Logger; import org.primeoservices.cfgateway.jms.StopOnShutdownTask; import lucee.runtime.gateway.Gateway; public abstract class AbstractLuceeJMSGateway implements JMSGateway, Gateway { private String id; private int state = Gateway.STOPPED; private JMSConfiguration config; private Logger log; @SuppressWarnings({"rawtypes", "unchecked"}) protected void init(final String id, final Map config, final Logger log) { this.id = id; this.config = new LuceeJMSConfiguration(config); this.log = log; Runtime.getRuntime().addShutdownHook(new Thread(new StopOnShutdownTask(this))); } @Override public String getId() { return this.id; } @Override public JMSConfiguration getConfiguration() { return this.config; } @Override public Logger getLogger() { return this.log; } @Override public Object getHelper() { return null; } @Override public int getState() { return this.state; } @Override public boolean isRunning() { return this.state == RUNNING; } @Override public void start() throws Exception { this.doStart(); } @Override public void doStart() throws IOException { if (this.isRunning()) return; this.state = STARTING; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); this.getExchanger().start(); this.state = RUNNING; } catch (Throwable t) { this.state = FAILED; this.log.error("Unable to start gateway", t); final IOException ex = new IOException("Unable to start gateway", t); throw ex; } finally { Thread.currentThread().setContextClassLoader(loader); } } @Override public void stop() throws Exception { this.doStop(); } @Override public void doStop() throws IOException { if (!this.isRunning()) return; this.state = STOPPING; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); this.getExchanger().stop(); this.state = STOPPED; } catch (Throwable t) { this.state = FAILED; this.log.error("Unable to stop gateway", t); final IOException ex = new IOException("Unable to stop gateway", t); throw ex; } finally { Thread.currentThread().setContextClassLoader(loader); } } @Override public void doRestart() throws IOException { this.doStop(); this.doStart(); } protected abstract JMSExchanger getExchanger(); @Override public void handleError() { // TODO Auto-generated method stub } }
923601e0da88a1cf7d08a145e37889ac8d5a2c79
1,193
java
Java
src/main/java/com/zjc/bs/entity/check/Paper.java
can0501/BS
d05a6a9611b2804ac6ed31de1f63e4247bf2b09d
[ "MIT" ]
1
2020-04-25T02:20:32.000Z
2020-04-25T02:20:32.000Z
src/main/java/com/zjc/bs/entity/check/Paper.java
can0501/BS
d05a6a9611b2804ac6ed31de1f63e4247bf2b09d
[ "MIT" ]
null
null
null
src/main/java/com/zjc/bs/entity/check/Paper.java
can0501/BS
d05a6a9611b2804ac6ed31de1f63e4247bf2b09d
[ "MIT" ]
null
null
null
18.640625
68
0.725901
997,500
package com.zjc.bs.entity.check; import com.fasterxml.jackson.annotation.JsonFormat; import com.zjc.bs.base.Page; import java.util.Date; import lombok.*; import tk.mybatis.mapper.annotation.KeySql; import tk.mybatis.mapper.code.IdentityDialect; import javax.persistence.*; import java.util.Date; @Getter @Setter @Entity @Builder @NoArgsConstructor @AllArgsConstructor @Table(name = "paper", schema = "dbo") public class Paper extends Page { @Id @Column( insertable = false, updatable = false) @GeneratedValue(generator = "JDBC") private Integer id; private Integer pid; private String dep; private String classname; @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd") private Date createtime; private String coursename; private Integer courseregin; private Integer coursetype; private Integer solvetype; private Integer startweek; private Integer endweek; private Integer placetype; private String teachername; private String education; private String content; private String condition; private Integer status; private String suggession; private String checkname; }
9236022190532704a2c7abb38d222d9d074b076b
457
java
Java
app/src/main/java/me/pwcong/jpstart/rxbus/event/SettingEvent.java
pwcong/JPStart
d15c41b123b225ea798dd53238680e0e156ca6e1
[ "Apache-2.0" ]
8
2017-01-02T04:17:11.000Z
2020-11-26T04:59:36.000Z
app/src/main/java/me/pwcong/jpstart/rxbus/event/SettingEvent.java
pwcong/JPStart
d15c41b123b225ea798dd53238680e0e156ca6e1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/pwcong/jpstart/rxbus/event/SettingEvent.java
pwcong/JPStart
d15c41b123b225ea798dd53238680e0e156ca6e1
[ "Apache-2.0" ]
2
2019-09-20T04:28:48.000Z
2021-10-21T03:32:08.000Z
15.233333
38
0.512035
997,501
package me.pwcong.jpstart.rxbus.event; /** * Created by Pwcong on 2016/10/6. */ public class SettingEvent { private int msg; public SettingEvent(int msg) { this.msg = msg; } @Override public String toString() { return "SettingEvent{" + "msg=" + msg + '}'; } public int getMsg() { return msg; } public void setMsg(int msg) { this.msg = msg; } }
92360293ab68d84b22a76682bfb9a48fb3b3a763
551
java
Java
src/main/java/com/github/wuchao/filepreview/controller/ErrorController.java
wuchao/file-preview
04cdc203ac26aec94e12cb766ef710cb0a2dd099
[ "Apache-2.0" ]
2
2021-04-15T09:06:43.000Z
2021-09-28T07:04:39.000Z
src/main/java/com/github/wuchao/filepreview/controller/ErrorController.java
wuchao/file-preview
04cdc203ac26aec94e12cb766ef710cb0a2dd099
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/wuchao/filepreview/controller/ErrorController.java
wuchao/file-preview
04cdc203ac26aec94e12cb766ef710cb0a2dd099
[ "Apache-2.0" ]
1
2020-09-10T03:36:46.000Z
2020-09-10T03:36:46.000Z
15.305556
58
0.571688
997,502
package com.github.wuchao.filepreview.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ErrorController { /** * 403 页面 */ @GetMapping("/403") public String error403() { return "403"; } /** * 404 页面 */ @GetMapping("/404") public String error404() { return "404"; } /** * 500 页面 */ @GetMapping("/500") public String error500() { return "500"; } }
9236038e008dc21a129f1b1105f25cd599820ed7
3,116
java
Java
app/src/main/java/com/xiaoguang/happytoplay/utils/QrCodeUtils.java
mmengchen/happyToPlay
5a293b0551a0f85609054ddbc2a5cf1bbd6e1b5e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/xiaoguang/happytoplay/utils/QrCodeUtils.java
mmengchen/happyToPlay
5a293b0551a0f85609054ddbc2a5cf1bbd6e1b5e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/xiaoguang/happytoplay/utils/QrCodeUtils.java
mmengchen/happyToPlay
5a293b0551a0f85609054ddbc2a5cf1bbd6e1b5e
[ "Apache-2.0" ]
null
null
null
35.011236
98
0.564827
997,503
package com.xiaoguang.happytoplay.utils; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.xiaoguang.happytoplay.bean.User; import java.util.Hashtable; /** * 根据用户信息生成二维码 * Created by 11655 on 2016/10/12. */ public class QrCodeUtils { public static final int QR_WIDTH = 80; public static final int QR_HEIGHT = 80; public static Bitmap createQrCode(User user){ Bitmap bitmap = null; try { // 需要引入core包 QRCodeWriter writer = new QRCodeWriter(); String text = "乐玩旅行APP 用户信息: "+" 昵称:"+user.getNickName()+" 账号:"+user.getUsername(); if (text == null || "".equals(text) || text.length() < 1) { return null; } // 把输入的文本转为二维码 BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT); System.out.println("w:" + martix.getWidth() + "h:" + martix.getHeight()); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; for (int y = 0; y < QR_HEIGHT; y++) { for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); } catch (WriterException e) { e.printStackTrace(); } return bitmap; } // 解析QR图片 // public static void scanningImage() { // // Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>(); // hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); // // // 获得待解析的图片 // Bitmap bitmap = ((BitmapDrawable) qr_image.getDrawable()).getBitmap(); // RGBLuminanceSource source = new RGBLuminanceSource(bitmap); // BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); // QRCodeReader reader = new QRCodeReader(); // Result result; // try { // result = reader.decode(bitmap1, hints); // // 得到解析后的文字 // qr_result.setText(result.getText()); // } catch (NotFoundException e) { // e.printStackTrace(); // } catch (ChecksumException e) { // e.printStackTrace(); // } catch (FormatException e) { // e.printStackTrace(); // } // } }
923604732f22f0d14165b1063251544f8a17f7fc
1,281
java
Java
app/src/main/java/zhan/autorecycleradapter/standard/StandardSingleActivity.java
nahzur-h/AutoRecyclerAdapter
8d8d8552416630d89a501b54fbd1786e76d2f236
[ "Apache-2.0" ]
1
2020-10-26T00:50:15.000Z
2020-10-26T00:50:15.000Z
app/src/main/java/zhan/autorecycleradapter/standard/StandardSingleActivity.java
nahzur-h/AutoRecyclerAdapter
8d8d8552416630d89a501b54fbd1786e76d2f236
[ "Apache-2.0" ]
null
null
null
app/src/main/java/zhan/autorecycleradapter/standard/StandardSingleActivity.java
nahzur-h/AutoRecyclerAdapter
8d8d8552416630d89a501b54fbd1786e76d2f236
[ "Apache-2.0" ]
null
null
null
32.025
80
0.793911
997,504
package zhan.autorecycleradapter.standard; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.List; import zhan.autorecycleradapter.R; import zhan.autorecycleradapter.bean.ZhaoBean; import zhan.autorecycleradapter.standard.adapter.StandardSingleAdapter; import zhan.autorecycleradapter.utils.ModelHelper; /** * Created by ruzhan on 2017/4/6. */ public class StandardSingleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); StandardSingleAdapter adapter = new StandardSingleAdapter(); recyclerView.setAdapter(adapter); LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(manager); recyclerView.setHasFixedSize(true); //net work request data List<ZhaoBean> list = ModelHelper.getZhaoList(30); //refresh data adapter.setData(list); } }
923604a66d993da37b63f6106161cc47505c1d95
1,203
java
Java
traverseTreeByLayer/src/Solution/Solution.java
SilentSherlock/practice
625a01d9ba54a0062ae3c6f5ef6720fe26c5bbdc
[ "Apache-2.0" ]
null
null
null
traverseTreeByLayer/src/Solution/Solution.java
SilentSherlock/practice
625a01d9ba54a0062ae3c6f5ef6720fe26c5bbdc
[ "Apache-2.0" ]
null
null
null
traverseTreeByLayer/src/Solution/Solution.java
SilentSherlock/practice
625a01d9ba54a0062ae3c6f5ef6720fe26c5bbdc
[ "Apache-2.0" ]
null
null
null
27.340909
74
0.524522
997,505
package Solution; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class Solution { //层序遍历二叉树 public List<List<Integer>> solute(TreeNode root) { List<List<Integer>> result = new LinkedList<>(); Queue<TreeNode> queue = new LinkedList<>(); if (root != null) { queue.offer(root); }else { System.out.println("the root is NULL"); } while (!queue.isEmpty()) { List<Integer> level = new LinkedList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode head = queue.poll(); level.add(head.val); if (head.left != null) queue.offer(head.left); if (head.right != null) queue.offer(head.right); } result.add(level); } return result; } //判断二叉树是否相同 public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null) return false; if (p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
923604a9ceff2d8fa0bf23778e6fc10b5f1b2b1b
3,203
java
Java
src/test/java/uk/gov/gchq/syntheticdatagenerator/AlumnoTest.java
dagoull/ExamenLDH
163c379ecdd387e2a3304477bb8dde5d8798c853
[ "Apache-2.0" ]
null
null
null
src/test/java/uk/gov/gchq/syntheticdatagenerator/AlumnoTest.java
dagoull/ExamenLDH
163c379ecdd387e2a3304477bb8dde5d8798c853
[ "Apache-2.0" ]
1
2021-12-24T11:02:04.000Z
2021-12-24T11:02:59.000Z
src/test/java/uk/gov/gchq/syntheticdatagenerator/AlumnoTest.java
AlvaroGonzalezRodriguez/ProyectoLDH
b30e3eba766bda34b16f144d638c2221d70a5c27
[ "Apache-2.0" ]
null
null
null
32.353535
94
0.598501
997,506
/* * Copyright 2018-2021 Crown Copyright * * 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 uk.gov.gchq.syntheticdatagenerator; import org.apache.commons.io.FileUtils; import org.junit.Test; import uk.gov.gchq.syntheticdatagenerator.types.Alumno; import uk.gov.gchq.syntheticdatagenerator.types.Pas; import java.io.File; import java.util.ArrayList; import java.util.Random; public class AlumnoTest { @Test(expected = Test.None.class) public void generateAlumno() { ArrayList<Alumno> alumnos = new ArrayList<>(); int counter = 0; long startTime = System.currentTimeMillis(); Random random = new Random(0); for (int i = 0; i < 100; i++) { Alumno t = Alumno.generate(random); alumnos.add(t); counter++; } assert (alumnos.size() == counter); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + "ms to create 100 Alumnos"); } @Test(expected = Test.None.class) public void generatePas() { ArrayList<Pas> miembros = new ArrayList<>(); int counter = 0; long startTime = System.currentTimeMillis(); Random random = new Random(0); for (int i = 0; i < 100; i++) { Pas p = Pas.generate(random); miembros.add(p); counter++; } assert (miembros.size() == counter); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + "ms to create 100 Pas"); } @Test(expected = Test.None.class) public void generateAvroDataAlumno() { try { assert (CreateData.main(new String[]{"data", "50", "-avro", "1", "alumno"}) == 0); } finally { FileUtils.deleteQuietly(new File(".data")); } } @Test(expected = Test.None.class) public void generateJSONDataAlumno() { try { assert (CreateData.main(new String[]{"data", "50", "-json", "1", "alumno"}) == 0); } finally { FileUtils.deleteQuietly(new File(".data")); } } @Test(expected = Test.None.class) public void generateAvroDataPAS() { try { assert (CreateData.main(new String[]{"data", "50", "-avro", "1", "pas"}) == 0); } finally { FileUtils.deleteQuietly(new File(".data")); } } @Test(expected = Test.None.class) public void generateJSONData() { try { assert (CreateData.main(new String[]{"data", "50", "-json", "1", "pas"}) == 0); } finally { FileUtils.deleteQuietly(new File(".data")); } } }
9236053d42e5efb0e7eefbaacaac70a8c5fdd2e0
21,153
java
Java
components/reliable-messaging/org.wso2.carbon.rm/src/main/java/org/wso2/carbon/rm/service/RMAdminService.java
wso2/carbon-qos
9d3752097be0a67fd2b0f80e313dfeb3f8ebb6f5
[ "Apache-2.0" ]
1
2016-06-24T12:57:29.000Z
2016-06-24T12:57:29.000Z
components/reliable-messaging/org.wso2.carbon.rm/src/main/java/org/wso2/carbon/rm/service/RMAdminService.java
wso2/carbon-qos
9d3752097be0a67fd2b0f80e313dfeb3f8ebb6f5
[ "Apache-2.0" ]
2
2015-01-04T15:33:47.000Z
2015-01-13T03:29:41.000Z
components/reliable-messaging/org.wso2.carbon.rm/src/main/java/org/wso2/carbon/rm/service/RMAdminService.java
wso2-attic/carbon-qos
9d3752097be0a67fd2b0f80e313dfeb3f8ebb6f5
[ "Apache-2.0" ]
5
2015-01-26T09:10:31.000Z
2015-08-17T09:28:58.000Z
47.428251
115
0.657354
997,507
/* * Copyright 2004,2005 The Apache Software Foundation. * * 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.wso2.carbon.rm.service; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.description.*; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.neethi.Policy; import org.apache.sandesha2.Sandesha2Constants; import org.apache.sandesha2.policy.SandeshaPolicyBean; import org.apache.sandesha2.storage.jdbc.PersistentStorageManager; import org.wso2.carbon.core.AbstractAdmin; import org.wso2.carbon.core.RegistryResources; import org.wso2.carbon.core.Resources; import org.wso2.carbon.core.persistence.PersistenceException; import org.wso2.carbon.core.persistence.PersistenceFactory; import org.wso2.carbon.core.persistence.PersistenceUtils; import org.wso2.carbon.core.persistence.file.ServiceGroupFilePersistenceManager; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.utils.Transaction; import javax.xml.namespace.QName; import java.util.List; public class RMAdminService extends AbstractAdmin { private static final Log log = LogFactory.getLog(RMAdminService.class); private static final String RM_POLICY_ID = "RMPolicy"; private PersistenceFactory persistenceFactory; private ServiceGroupFilePersistenceManager serviceGroupFilePM; private Registry registry; public RMAdminService() throws Exception { persistenceFactory = PersistenceFactory.getInstance(getAxisConfig()); serviceGroupFilePM = persistenceFactory.getServiceGroupFilePM(); registry = getConfigSystemRegistry(); } public boolean isRMEnabled(String serviceName) throws AxisFault { AxisConfiguration axisConfiguration = getAxisConfig(); AxisService axisServce = axisConfiguration.getServiceForActivation(serviceName); AxisModule sandeshaModule = axisConfiguration.getModule("sandesha2"); return axisServce.isEngaged(sandeshaModule); } public void enableRM(String serviceName) throws AxisFault { AxisConfiguration axisConfiguration = getAxisConfig(); AxisService axisService = axisConfiguration.getServiceForActivation(serviceName); String serviceGroupId = axisService.getAxisServiceGroup().getServiceGroupName(); AxisModule sandesahModule = axisConfiguration.getModule("sandesha2"); String serviceXPath = PersistenceUtils.getResourcePath(axisService); // engage at registry try { boolean transactionStarted = serviceGroupFilePM.isTransactionStarted(serviceGroupId); if (!transactionStarted) { serviceGroupFilePM.beginTransaction(serviceGroupId); } // Check if an association exist between servicePath and moduleResourcePath. List associations = serviceGroupFilePM.getAll(serviceGroupId, serviceXPath + "/" + Resources.ModuleProperties.MODULE_XML_TAG + PersistenceUtils.getXPathAttrPredicate( Resources.ModuleProperties.TYPE, Resources.Associations.ENGAGED_MODULES)); boolean associationExist = false; String version = sandesahModule.getVersion().toString(); if (sandesahModule.getVersion() == null) { version = Resources.ModuleProperties.UNDEFINED; } for (Object node : associations) { OMElement association = (OMElement) node; if (association.getAttributeValue(new QName(Resources.NAME)).equals( sandesahModule.getName()) && association.getAttributeValue(new QName(Resources.VERSION)).equals(version)) { associationExist = true; break; } } //if RM is not found, add a new association if (!associationExist) { serviceGroupFilePM.put(serviceGroupId, PersistenceUtils.createModule(sandesahModule.getName(), version, Resources.Associations.ENGAGED_MODULES), serviceXPath); } if (!transactionStarted) { serviceGroupFilePM.commitTransaction(serviceGroupId); } /* Association[] associations = registry.getAssociations(servicePath, RegistryResources.Associations.ENGAGED_MODULES); boolean associationExist = false; for (Association association : associations) { if (association.getDestinationPath().equals(getModuleResourcePath(sandesahModule))) { associationExist = true; break; } } //if throttling is not found, add a new association if (!associationExist) { registry.addAssociation(servicePath, getModuleResourcePath(sandesahModule), RegistryResources.Associations.ENGAGED_MODULES); }*/ }/* catch (RegistryException e) { log.error("Error occured in engaging throttlin at registry", e); throw new AxisFault("Can not save to the registry"); }*/ catch (PersistenceException e) { log.error("Error occured persisting RM", e); throw new AxisFault("Cannot persist RM metadata"); } axisService.engageModule(sandesahModule); } public void disableRM(String serviceName) throws AxisFault { AxisConfiguration axisConfiguration = getAxisConfig(); AxisService axisService = axisConfiguration.getServiceForActivation(serviceName); String serviceGroupId = axisService.getAxisServiceGroup().getServiceGroupName(); AxisModule sandesahModule = axisConfiguration.getModule("sandesha2"); String servicePath = RegistryResources.SERVICE_GROUPS + axisService.getAxisServiceGroup().getServiceGroupName() + RegistryResources.SERVICES + serviceName; ServiceGroupFilePersistenceManager sfpm = persistenceFactory.getServiceGroupFilePM(); try { boolean transactionStarted = sfpm.isTransactionStarted(serviceGroupId); if (!transactionStarted) { sfpm.beginTransaction(serviceGroupId); } sfpm.delete(serviceGroupId, PersistenceUtils.getResourcePath(axisService) + "/" + Resources.ModuleProperties.MODULE_XML_TAG + PersistenceUtils.getXPathAttrPredicate( Resources.NAME, sandesahModule.getName()) + PersistenceUtils.getXPathAttrPredicate( Resources.ModuleProperties.TYPE, Resources.Associations.ENGAGED_MODULES)); if (!transactionStarted) { sfpm.commitTransaction(serviceGroupId); } } catch (PersistenceException e) { log.error("Error ocurred in disengaging the module ", e); throw new AxisFault("Error ocurred in disengaging the module "); } /* Registry registry = getConfigSystemRegistry(); try { registry.removeAssociation(servicePath, getModuleResourcePath(sandesahModule), RegistryResources.Associations.ENGAGED_MODULES); String policyPath = servicePath + RegistryResources.POLICIES + RM_POLICY_ID; if (registry.resourceExists(policyPath)) { registry.delete(policyPath); } } catch (RegistryException e) { log.error("Error ocurred in disengaging the module ", e); throw new AxisFault("Error ocurred in disengaging the module "); } */ axisService.disengageModule(sandesahModule); } public void setParameters(String serviceName, RMParameterBean parameters) throws AxisFault { AxisConfiguration axisConfiguration = getAxisConfig(); AxisService axisService = axisConfiguration.getServiceForActivation(serviceName); if (parameters != null) { Parameter sandeshaPolicyBeanParameter = axisService.getParameter( Sandesha2Constants.SANDESHA_PROPERTY_BEAN); SandeshaPolicyBean sandeshaPolicyBean; if (sandeshaPolicyBeanParameter != null) { sandeshaPolicyBean = (SandeshaPolicyBean) sandeshaPolicyBeanParameter.getValue(); if (sandeshaPolicyBean.getParent() == null) { sandeshaPolicyBean = new SandeshaPolicyBean(); sandeshaPolicyBean.setParent( (SandeshaPolicyBean) sandeshaPolicyBeanParameter.getValue()); axisService.addParameter(Sandesha2Constants.SANDESHA_PROPERTY_BEAN, sandeshaPolicyBean); } } else { sandeshaPolicyBean = new SandeshaPolicyBean(); axisService.addParameter(Sandesha2Constants.SANDESHA_PROPERTY_BEAN, sandeshaPolicyBean); } sandeshaPolicyBean.setInactiveTimeoutInterval( parameters.getInactivityTimeoutInterval(), parameters.getInactivityTimeoutMeasure()); sandeshaPolicyBean.setSequenceRemovalTimeoutInterval( parameters.getSequenceRemovalTimeoutInterval(), parameters.getSequenceRemovalTimeoutMeasure()); sandeshaPolicyBean.setSequenceRemovalTimeoutMeasure( parameters.getSequenceRemovalTimeoutMeasure()); sandeshaPolicyBean.setAcknowledgementInterval(parameters.getAcknowledgementInterval()); sandeshaPolicyBean.setRetransmissionInterval(parameters.getRetransmissionInterval()); sandeshaPolicyBean.setExponentialBackoff(parameters.isExponentialBackoff()); sandeshaPolicyBean.setMaximumRetransmissionCount( parameters.getMaximumRetransmissionCount()); // String serviceResourcePath = RegistryResources.SERVICE_GROUPS // + axisService.getAxisServiceGroup().getServiceGroupName() // + RegistryResources.SERVICES + serviceName; updatePolicy(axisService, sandeshaPolicyBean); } } private void updatePolicy(AxisService axisService, SandeshaPolicyBean sandeshaPolicyBean) throws AxisFault { // Registry registry = getConfigSystemRegistry(); Policy sandeshaPolicy = new Policy(); sandeshaPolicy.setId(RM_POLICY_ID); sandeshaPolicy.setName(RM_POLICY_ID); sandeshaPolicy.addPolicyComponent(sandeshaPolicyBean); String serviceGroupId = axisService.getAxisServiceGroup().getServiceGroupName(); boolean isProxyService = PersistenceUtils.isProxyService(axisService); try { //to registry boolean registryTransactionStarted = true; registryTransactionStarted = Transaction.isStarted(); if (isProxyService && !registryTransactionStarted) { registry.beginTransaction(); } if (isProxyService) { String policyType = "" + PolicyInclude.AXIS_SERVICE_POLICY; String servicePath = PersistenceUtils.getRegistryResourcePath(axisService); persistenceFactory.getServicePM().persistPolicyToRegistry(sandeshaPolicy, policyType, servicePath); } //to file OMFactory omFactory = OMAbstractFactory.getOMFactory(); OMElement policyWrapperEle = omFactory.createOMElement(Resources.POLICY, null); policyWrapperEle.addAttribute(Resources.ServiceProperties.POLICY_TYPE, String.valueOf(PolicyInclude.AXIS_SERVICE_POLICY), null); OMElement idElement = omFactory.createOMElement(Resources.ServiceProperties.POLICY_UUID, null); idElement.setText(sandeshaPolicy.getId()); policyWrapperEle.addChild(idElement); OMElement policyEleToPersist = PersistenceUtils.createPolicyElement(sandeshaPolicy); policyWrapperEle.addChild(policyEleToPersist); String serviceXPath = PersistenceUtils.getResourcePath(axisService); boolean transactionStarted = serviceGroupFilePM.isTransactionStarted(serviceGroupId); if (!transactionStarted) { serviceGroupFilePM.beginTransaction(serviceGroupId); } //check if "policies" section exists otherwise create, and delete the existing policy if exists if (!serviceGroupFilePM.elementExists(serviceGroupId, serviceXPath + "/" + Resources.POLICIES)) { serviceGroupFilePM.put(serviceGroupId, omFactory.createOMElement(Resources.POLICIES, null), serviceXPath); } else { //you must manually delete the existing policy before adding new one. String pathToPolicy = serviceXPath + "/" + Resources.POLICIES + "/" + Resources.POLICY + PersistenceUtils.getXPathTextPredicate( Resources.ServiceProperties.POLICY_UUID, sandeshaPolicy.getId()); if (serviceGroupFilePM.elementExists(serviceGroupId, pathToPolicy)) { serviceGroupFilePM.delete(serviceGroupId, pathToPolicy); } } //put the policy serviceGroupFilePM.put(serviceGroupId, policyWrapperEle, serviceXPath + "/" + Resources.POLICIES); if (!serviceGroupFilePM.elementExists(serviceGroupId, serviceXPath + PersistenceUtils.getXPathTextPredicate( Resources.ServiceProperties.POLICY_UUID, sandeshaPolicy.getId()))) { serviceGroupFilePM.put(serviceGroupId, idElement.cloneOMElement(), serviceXPath); } if (!transactionStarted) { serviceGroupFilePM.commitTransaction(serviceGroupId); } if (isProxyService && !registryTransactionStarted) { registry.commitTransaction(); } } catch (PersistenceException e) { log.error("Problem when setting parameter values", e); serviceGroupFilePM.rollbackTransaction(serviceGroupId); if (isProxyService) { try { registry.rollbackTransaction(); } catch (RegistryException re) { log.error(e.getMessage(), e); } } throw new AxisFault("Problem when setting parameter values"); } catch (Exception e) { log.error("Problem when setting parameter values", e); serviceGroupFilePM.rollbackTransaction(serviceGroupId); if (isProxyService) { try { registry.rollbackTransaction(); } catch (RegistryException re) { log.error(e.getMessage(), e); } } throw new AxisFault("Problem when setting parameter values"); } /*try { String resourcePath = serviceResourcePath + RegistryResources.POLICIES + RM_POLICY_ID; Resource policyResource; if (registry.resourceExists(resourcePath)) { policyResource = registry.get(resourcePath); } else { policyResource = registry.newResource(); policyResource.setProperty(RegistryResources.ServiceProperties.POLICY_TYPE, String.valueOf(PolicyInclude.SERVICE_POLICY)); policyResource.setProperty(RegistryResources.ServiceProperties.POLICY_UUID, RM_POLICY_ID); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(baos); sandeshaPolicy.serialize(writer); writer.flush(); policyResource.setContent(baos.toString()); registry.put(resourcePath, policyResource); } catch (RegistryException e) { throw new AxisFault("Problem when setting parameter values"); } catch (XMLStreamException e) { throw new AxisFault("Problem when setting parameter values"); }*/ } public RMParameterBean getParameters(String serviceName) throws AxisFault { AxisConfiguration axisConfiguration = getAxisConfig(); AxisService axisService = axisConfiguration.getServiceForActivation(serviceName); RMParameterBean rmParameterBean = new RMParameterBean(); Parameter sandeshaPolicyBeanParameter = axisService.getParameter( Sandesha2Constants.SANDESHA_PROPERTY_BEAN); if (sandeshaPolicyBeanParameter != null) { SandeshaPolicyBean sandeshaPolicyBean = (SandeshaPolicyBean) sandeshaPolicyBeanParameter.getValue(); // sandesha policy bean stored them in miliseconds so we make them seconds to display users. rmParameterBean.setInactivityTimeoutInterval( sandeshaPolicyBean.getInactivityTimeoutInterval() / 1000); rmParameterBean.setInactivityTimeoutMeasure("seconds"); rmParameterBean.setSequenceRemovalTimeoutInterval( sandeshaPolicyBean.getSequenceRemovalTimeoutInterval() / 1000); rmParameterBean.setSequenceRemovalTimeoutMeasure("seconds"); rmParameterBean.setAcknowledgementInterval( sandeshaPolicyBean.getAcknowledgementInterval()); rmParameterBean.setRetransmissionInterval( sandeshaPolicyBean.getRetransmissionInterval()); rmParameterBean.setExponentialBackoff( sandeshaPolicyBean.isExponentialBackoff()); rmParameterBean.setMaximumRetransmissionCount( sandeshaPolicyBean.getMaximumRetransmissionCount()); } return rmParameterBean; } /* //commented out since this is unused private String getModuleResourcePath(AxisModule axisModule) { String moduleName = axisModule.getName(); String moduleVersion = axisModule.getVersion().toString(); if (moduleVersion == null || moduleVersion.length() == 0) { moduleVersion = "SNAPSHOT"; } return RegistryResources.MODULES + moduleName + "/" + moduleVersion; } */ public void ConfigurePermenentStorage(String connectionString, String driver, String userName, String password) throws AxisFault { ConfigurationContext configurationContext = getConfigContext(); AxisConfiguration axisConfiguration = configurationContext.getAxisConfiguration(); ModuleConfiguration moduleConfiguration = new ModuleConfiguration("sandesha2", null); moduleConfiguration.addParameter(new Parameter("db.connectionstring", connectionString)); moduleConfiguration.addParameter(new Parameter("db.driver", driver)); moduleConfiguration.addParameter(new Parameter("db.user", userName)); moduleConfiguration.addParameter(new Parameter("db.password", password)); axisConfiguration.addModuleConfig(moduleConfiguration); AxisModule sandeshaModule = axisConfiguration.getModule("sandesha2"); PersistentStorageManager persistentStorageManager = new PersistentStorageManager(configurationContext); persistentStorageManager.initStorage(sandeshaModule); Parameter permenentStorage = axisConfiguration.getParameter( Sandesha2Constants.PERMANENT_STORAGE_MANAGER); if (permenentStorage != null) { axisConfiguration.removeParameter(permenentStorage); } // change the permenetent storage manager. axisConfiguration.addParameter(Sandesha2Constants.PERMANENT_STORAGE_MANAGER, persistentStorageManager); } }
92360589cdfb68f796f3659bde7a2d7b1ad25196
2,241
java
Java
BaseLibSample/baselib/src/main/java/com/ankhrom/base/networking/volley/BaseVolleyRequest.java
Ankhrom/baselib
43eeca149b89d9fb014b8387c4e99aa3233c05f9
[ "Apache-2.0" ]
null
null
null
BaseLibSample/baselib/src/main/java/com/ankhrom/base/networking/volley/BaseVolleyRequest.java
Ankhrom/baselib
43eeca149b89d9fb014b8387c4e99aa3233c05f9
[ "Apache-2.0" ]
null
null
null
BaseLibSample/baselib/src/main/java/com/ankhrom/base/networking/volley/BaseVolleyRequest.java
Ankhrom/baselib
43eeca149b89d9fb014b8387c4e99aa3233c05f9
[ "Apache-2.0" ]
null
null
null
27
212
0.677822
997,508
package com.ankhrom.base.networking.volley; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.ankhrom.base.common.statics.StringHelper; import com.ankhrom.base.interfaces.ObjectFactory; import java.util.Map; public abstract class BaseVolleyRequest<T> extends Request<T> { private final Response.Listener<T> listener; private final String contentType; private final Map<String, String> header; private final Map<String, String> params; private final byte[] body; public BaseVolleyRequest(int method, String url, String contentType, Map<String, String> header, Map<String, String> params, byte[] body, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(method, url, errorListener); this.contentType = contentType; this.header = header; this.params = params; this.body = body; this.listener = listener; } @Override public String getPostBodyContentType() { return getBodyContentType(); } @Override public byte[] getPostBody() throws AuthFailureError { return getBody(); } @Override protected Map<String, String> getPostParams() throws AuthFailureError { return getParams(); } @Override public String getBodyContentType() { return !StringHelper.isEmpty(contentType) ? contentType : super.getBodyContentType(); } @Override public Map<String, String> getParams() throws AuthFailureError { return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return header != null ? header : super.getHeaders(); } @Override public byte[] getBody() throws AuthFailureError { return body != null ? body : super.getBody(); } @Override protected void deliverResponse(T response) { if (listener != null) { listener.onResponse(response); } } public void queue(ObjectFactory factory) { queue(factory.getRequestQueue()); } public void queue(RequestQueue queue) { queue.add(this); } }
923605b0dc4405f3e4ead3e6b4fc6a74555fdf82
213
java
Java
src/main/java/mtr/gui/TrainRedstoneSensorScreen.java
Kenny-Hui/Minecraft-Transit-Railway
1ff550ca31daead37b97fa8b861ffe2ae814e18c
[ "MIT" ]
null
null
null
src/main/java/mtr/gui/TrainRedstoneSensorScreen.java
Kenny-Hui/Minecraft-Transit-Railway
1ff550ca31daead37b97fa8b861ffe2ae814e18c
[ "MIT" ]
null
null
null
src/main/java/mtr/gui/TrainRedstoneSensorScreen.java
Kenny-Hui/Minecraft-Transit-Railway
1ff550ca31daead37b97fa8b861ffe2ae814e18c
[ "MIT" ]
null
null
null
19.363636
70
0.793427
997,509
package mtr.gui; import net.minecraft.util.math.BlockPos; public class TrainRedstoneSensorScreen extends TrainSensorScreenBase { public TrainRedstoneSensorScreen(BlockPos pos) { super(pos, null, null); } }
9236075b10d123709fdb91a36a30b177f190ed3a
316
java
Java
thanos-java/thanos-api/src/main/java/com/virjar/thanos/api/bean/Seed.java
virjar/thanos
33491325c43548d43c9b17d323b76f76c18208a3
[ "Apache-2.0" ]
26
2020-10-28T12:01:43.000Z
2022-01-26T02:09:50.000Z
thanos-java/thanos-api/src/main/java/com/virjar/thanos/api/bean/Seed.java
virjar/thanos
33491325c43548d43c9b17d323b76f76c18208a3
[ "Apache-2.0" ]
1
2020-12-15T07:39:30.000Z
2021-11-24T09:54:08.000Z
thanos-java/thanos-api/src/main/java/com/virjar/thanos/api/bean/Seed.java
virjar/thanos
33491325c43548d43c9b17d323b76f76c18208a3
[ "Apache-2.0" ]
5
2020-10-29T04:00:12.000Z
2021-06-03T17:00:32.000Z
18.588235
42
0.778481
997,510
package com.virjar.thanos.api.bean; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import lombok.Data; /** * 任务种子,其中seedId用于唯一标记这个种子任务。 * param表示这个种子任务需要的附加数据,param和业务有关,但不代表唯一性 */ @Data @AllArgsConstructor public class Seed { public String seedId; public JSONObject param; }
923607cbe14f5b518a44255d1819db878e8c9f58
1,047
java
Java
addons/preferences/src/org/holoeverywhere/preference/PreferenceCategory.java
Xed89o/HoffGarni
3d7b3d48aa1ee158746b54d4518975fab6c219f6
[ "MIT" ]
384
2015-01-02T13:59:20.000Z
2022-03-06T12:52:11.000Z
addons/preferences/src/org/holoeverywhere/preference/PreferenceCategory.java
Xed89o/HoffGarni
3d7b3d48aa1ee158746b54d4518975fab6c219f6
[ "MIT" ]
12
2015-12-03T12:41:11.000Z
2020-07-02T17:38:50.000Z
addons/preferences/src/org/holoeverywhere/preference/PreferenceCategory.java
Xed89o/HoffGarni
3d7b3d48aa1ee158746b54d4518975fab6c219f6
[ "MIT" ]
144
2015-01-02T08:53:12.000Z
2022-01-25T12:35:01.000Z
28.297297
82
0.681948
997,511
package org.holoeverywhere.preference; import android.content.Context; import android.util.AttributeSet; public class PreferenceCategory extends PreferenceGroup { private static final String TAG = "PreferenceCategory"; public PreferenceCategory(Context context) { this(context, null); } public PreferenceCategory(Context context, AttributeSet attrs) { this(context, attrs, R.attr.preferenceCategoryStyle); } public PreferenceCategory(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean isEnabled() { return false; } @Override protected boolean onPrepareAddPreference(Preference preference) { if (preference instanceof PreferenceCategory) { throw new IllegalArgumentException("Cannot add a " + PreferenceCategory.TAG + " directly to a " + PreferenceCategory.TAG); } return super.onPrepareAddPreference(preference); } }
9236080085c328c265437159c37ce49f42b27f4a
3,684
java
Java
AgriMonitor/src/main/java/com/agri/monitor/controller/datamanage/FarmProductInfoController.java
cuckoolll/AgriMonitor
1f064e851e7001818be6619f0009e5a6f369319c
[ "Apache-2.0" ]
null
null
null
AgriMonitor/src/main/java/com/agri/monitor/controller/datamanage/FarmProductInfoController.java
cuckoolll/AgriMonitor
1f064e851e7001818be6619f0009e5a6f369319c
[ "Apache-2.0" ]
null
null
null
AgriMonitor/src/main/java/com/agri/monitor/controller/datamanage/FarmProductInfoController.java
cuckoolll/AgriMonitor
1f064e851e7001818be6619f0009e5a6f369319c
[ "Apache-2.0" ]
null
null
null
37.979381
95
0.78013
997,512
package com.agri.monitor.controller.datamanage; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.agri.monitor.annotation.IgnoreSession; import com.agri.monitor.entity.FarmProductInfo; import com.agri.monitor.entity.UserInfo; import com.agri.monitor.enums.CacheTypeEnum; import com.agri.monitor.service.datamanage.FarmProductInfoService; import com.agri.monitor.utils.CacheUtil; import com.agri.monitor.vo.FarmProductQueryVO; @Controller @RequestMapping("/farmproductinfo") public class FarmProductInfoController { @Autowired private FarmProductInfoService farmProductInfoService; /** * 渔业生产信息页面 . * @return . */ @RequestMapping("") public String farmproductinfo(Model model) { model.addAttribute("towns", CacheUtil.getCache(CacheTypeEnum.TOWNS)); return "/datamanage/farmproductinfo/farmproductinfo"; } @RequestMapping(value="/queryInfo", method = RequestMethod.POST) @ResponseBody @IgnoreSession public Map queryInfo(FarmProductQueryVO queryVo, HttpServletRequest request) { UserInfo user = (UserInfo) request.getSession().getAttribute("userinfo"); return farmProductInfoService.queryInfoForPage(queryVo, user.getUser_id()); } @ResponseBody @RequestMapping(value="/dataImport",method=RequestMethod.POST) public Map dataImport(@RequestParam("file") MultipartFile file, HttpServletRequest request) { return farmProductInfoService.dataImport(file, request); } @IgnoreSession @RequestMapping("/update") public String add(Model model) { return "/datamanage/farmproductinfo/farmproductupdate"; } @ResponseBody @RequestMapping(value="/save",method=RequestMethod.POST) public Map doUpdate(FarmProductInfo farmproductinfo, HttpServletRequest request) { UserInfo user = (UserInfo) request.getSession().getAttribute("userinfo"); return farmProductInfoService.saveOrUpdate(farmproductinfo, user.getUser_id()); } @ResponseBody @RequestMapping(value="/delInfoByGid",method=RequestMethod.POST) public Map delInfoByGid(@RequestBody ArrayList<Integer> gids, HttpServletRequest request) { UserInfo user = (UserInfo) request.getSession().getAttribute("userinfo"); return farmProductInfoService.delInfoByGid(gids, user.getUser_id()); } @ResponseBody @RequestMapping(value="/findById",method=RequestMethod.POST) public FarmProductInfo findById(Integer gid, HttpServletRequest request) { UserInfo user = (UserInfo) request.getSession().getAttribute("userinfo"); return farmProductInfoService.findById(gid, user.getUser_id()); } // @RequestMapping("/grassAnalysis") // public String grassAnalysis(Model model) { // model.addAttribute("grassindex", CacheUtil.getCache(CacheTypeEnum.GRASSINDEX)); // model.addAttribute("towns", CacheUtil.getCache(CacheTypeEnum.TOWNS)); // return "/statisticanalysis/grassanalysis/grassanalysis"; // } // // @ResponseBody // @RequestMapping(value="/queryAnalysisData", method=RequestMethod.POST) // public Map queryAnalysisData(HttpServletRequest request) { // return grassInfoService.queryAnalysisData(request); // } }
923608286c46e83fa2e3784fd7eaf9647a23e924
2,151
java
Java
crary/src/main/java/com/croquis/crary/restclient/gson/GsonQueryConverter.java
croquiscom/Crary-Android
19bedacc2487ed9fc43ea45fbf215b5c635483c5
[ "MIT" ]
3
2016-01-04T06:17:00.000Z
2017-04-21T00:17:16.000Z
crary/src/main/java/com/croquis/crary/restclient/gson/GsonQueryConverter.java
croquiscom/Crary-Android
19bedacc2487ed9fc43ea45fbf215b5c635483c5
[ "MIT" ]
1
2015-09-02T09:29:59.000Z
2015-09-02T09:29:59.000Z
crary/src/main/java/com/croquis/crary/restclient/gson/GsonQueryConverter.java
croquiscom/Crary-Android
19bedacc2487ed9fc43ea45fbf215b5c635483c5
[ "MIT" ]
3
2015-07-20T04:34:08.000Z
2021-03-24T17:13:28.000Z
33.609375
101
0.583914
997,513
package com.croquis.crary.restclient.gson; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; public class GsonQueryConverter { public static String convert(JsonObject object) { if (object == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.append("?"); addJsonObject(sb, "", object); sb.deleteCharAt(sb.length() - 1); return sb.toString().replace(' ', '+'); } public static String convert(Object object, Gson gson) { JsonElement json = gson.toJsonTree(object); if (json.isJsonObject()) { return convert((JsonObject) json); } return ""; } private static void addJsonElement(StringBuilder sb, String path, JsonElement object) { if (object.isJsonObject()) { addJsonObject(sb, path, (JsonObject) object); } else if (object.isJsonArray()) { addJsonArray(sb, path, (JsonArray) object); } else if (object.isJsonPrimitive()) { sb.append(path).append("="); try { sb.append(URLEncoder.encode(object.getAsString(), "UTF-8")); } catch (UnsupportedEncodingException ignored) { } sb.append("&"); } else { // null sb.append(path).append("=").append("&"); } } private static void addJsonObject(StringBuilder sb, String path, JsonObject object) { for (Map.Entry<String, JsonElement> entry : object.entrySet()) { String sub_path = path.length() > 0 ? path + "[" + entry.getKey() + "]" : entry.getKey(); addJsonElement(sb, sub_path, entry.getValue()); } } private static void addJsonArray(StringBuilder sb, String path, JsonArray object) { for (int i = 0; i < object.size(); i++) { String sub_path = path + "[" + i + "]"; addJsonElement(sb, sub_path, object.get(i)); } } }
923608fa42423818e3fa92265a9e9e9204570e68
2,154
java
Java
x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/permissioninfo/ExcuteListPermissionBySection.java
fancylou/o2oa
e7ec39fc586fab3d38b62415ed06448e6a9d6e26
[ "BSD-3-Clause" ]
1
2019-10-05T03:47:23.000Z
2019-10-05T03:47:23.000Z
x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/permissioninfo/ExcuteListPermissionBySection.java
Mendeling/o2oa
afd053e465b54b1b21b8db558bffbd93e7923b79
[ "BSD-3-Clause" ]
null
null
null
x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/permissioninfo/ExcuteListPermissionBySection.java
Mendeling/o2oa
afd053e465b54b1b21b8db558bffbd93e7923b79
[ "BSD-3-Clause" ]
null
null
null
35.9
160
0.753018
997,514
package com.x.bbs.assemble.control.jaxrs.permissioninfo; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.x.base.core.http.ActionResult; import com.x.base.core.http.EffectivePerson; import com.x.base.core.logger.Logger; import com.x.base.core.logger.LoggerFactory; import com.x.bbs.assemble.control.WrapTools; import com.x.bbs.assemble.control.jaxrs.permissioninfo.exception.PermissionInfoProcessException; import com.x.bbs.assemble.control.jaxrs.permissioninfo.exception.SectionIdEmptyException; import com.x.bbs.entity.BBSPermissionInfo; public class ExcuteListPermissionBySection extends ExcuteBase { private Logger logger = LoggerFactory.getLogger( ExcuteListPermissionBySection.class ); protected ActionResult<List<WrapOutPermissionInfo>> execute( HttpServletRequest request, EffectivePerson effectivePerson, String sectionId ) throws Exception { ActionResult<List<WrapOutPermissionInfo>> result = new ActionResult<>(); List<WrapOutPermissionInfo> wraps = new ArrayList<>(); List<BBSPermissionInfo> permissionInfoList = null; Boolean check = true; if( check ){ if( sectionId == null || sectionId.isEmpty() ){ check = false; Exception exception = new SectionIdEmptyException(); result.error( exception ); } } if( check ){ try { permissionInfoList = permissionInfoService.listPermissionBySection( sectionId ); if( permissionInfoList == null ){ permissionInfoList = new ArrayList<BBSPermissionInfo>(); } } catch (Exception e) { check = false; Exception exception = new PermissionInfoProcessException( e, "根据指定的版块列示所有的权限信息时时发生异常.Section:" + sectionId ); result.error( exception ); logger.error( e, effectivePerson, request, null); } } if( check ){ try { wraps = WrapTools.permissionInfo_wrapout_copier.copy( permissionInfoList ); result.setData( wraps ); } catch (Exception e) { Exception exception = new PermissionInfoProcessException( e, "将查询结果转换为可输出的数据信息时发生异常." ); result.error( exception ); logger.error( e, effectivePerson, request, null); } } return result; } }
92360912b14404f1622f1862757747afb70c574e
6,933
java
Java
jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/MaxOutgoingFramesTest.java
tet-lenovo/jetty.project
0a3632cdda0e4a12229dadd77112f95c57431cba
[ "Apache-2.0" ]
3,353
2015-01-06T13:30:21.000Z
2022-03-31T08:33:56.000Z
jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/MaxOutgoingFramesTest.java
stoty/jetty.project
1223bb50ec91fd3387ee7b7983c8e79c5c975318
[ "Apache-2.0" ]
6,018
2015-01-30T17:42:33.000Z
2022-03-31T22:37:40.000Z
jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/MaxOutgoingFramesTest.java
stoty/jetty.project
1223bb50ec91fd3387ee7b7983c8e79c5c975318
[ "Apache-2.0" ]
1,997
2015-01-05T03:35:02.000Z
2022-03-29T02:47:56.000Z
38.516667
131
0.689168
997,515
// // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.websocket.tests; import java.net.URI; import java.nio.channels.WritePendingException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.eclipse.jetty.websocket.api.WriteCallback; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.core.AbstractExtension; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.WebSocketComponents; import org.eclipse.jetty.websocket.core.client.WebSocketCoreClient; import org.eclipse.jetty.websocket.core.server.WebSocketServerComponents; import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.eclipse.jetty.websocket.tests.util.FutureWriteCallback; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class MaxOutgoingFramesTest { public static CountDownLatch outgoingBlocked; public static CountDownLatch firstFrameBlocked; private final EventSocket serverSocket = new EventSocket(); private Server server; private ServerConnector connector; private WebSocketClient client; @BeforeEach public void start() throws Exception { outgoingBlocked = new CountDownLatch(1); firstFrameBlocked = new CountDownLatch(1); server = new Server(); connector = new ServerConnector(server); server.addConnector(connector); ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.setContextPath("/"); JettyWebSocketServletContainerInitializer.configure(contextHandler, (context, container) -> { container.addMapping("/", (req, resp) -> serverSocket); WebSocketComponents components = WebSocketServerComponents.getWebSocketComponents(context); components.getExtensionRegistry().register(BlockingOutgoingExtension.class.getName(), BlockingOutgoingExtension.class); }); server.setHandler(contextHandler); client = new WebSocketClient(); server.start(); client.start(); } @AfterEach public void stop() throws Exception { outgoingBlocked.countDown(); server.stop(); client.stop(); } public static class BlockingOutgoingExtension extends AbstractExtension { @Override public String getName() { return BlockingOutgoingExtension.class.getName(); } @Override public void sendFrame(Frame frame, Callback callback, boolean batch) { try { firstFrameBlocked.countDown(); outgoingBlocked.await(); super.sendFrame(frame, callback, batch); } catch (InterruptedException e) { throw new RuntimeException(e); } } } public static class CountingCallback implements WriteCallback { private final CountDownLatch successes; public CountingCallback(int count) { successes = new CountDownLatch(count); } @Override public void writeSuccess() { successes.countDown(); } @Override public void writeFailed(Throwable t) { t.printStackTrace(); } } @Test public void testMaxOutgoingFrames() throws Exception { // We need to have the frames queued but not yet sent, we do this by blocking in the ExtensionStack. WebSocketCoreClient coreClient = client.getBean(WebSocketCoreClient.class); coreClient.getExtensionRegistry().register(BlockingOutgoingExtension.class.getName(), BlockingOutgoingExtension.class); URI uri = URI.create("ws://localhost:" + connector.getLocalPort() + "/"); EventSocket socket = new EventSocket(); ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(); upgradeRequest.addExtensions(BlockingOutgoingExtension.class.getName()); client.connect(socket, uri, upgradeRequest).get(5, TimeUnit.SECONDS); assertTrue(socket.openLatch.await(5, TimeUnit.SECONDS)); int numFrames = 30; RemoteEndpoint remote = socket.session.getRemote(); remote.setMaxOutgoingFrames(numFrames); // Verify that we can send up to numFrames without any problem. // First send will block in the Extension so it needs to be done in new thread, others frames will be queued. CountingCallback countingCallback = new CountingCallback(numFrames); new Thread(() -> remote.sendString("0", countingCallback)).start(); assertTrue(firstFrameBlocked.await(5, TimeUnit.SECONDS)); for (int i = 1; i < numFrames; i++) { remote.sendString(Integer.toString(i), countingCallback); } // Sending any more frames will result in WritePendingException. FutureWriteCallback callback = new FutureWriteCallback(); remote.sendString("fail", callback); ExecutionException executionException = assertThrows(ExecutionException.class, () -> callback.get(5, TimeUnit.SECONDS)); assertThat(executionException.getCause(), instanceOf(WritePendingException.class)); // Check that all callbacks are succeeded when the server processes the frames. outgoingBlocked.countDown(); assertTrue(countingCallback.successes.await(5, TimeUnit.SECONDS)); // Close successfully. socket.session.close(); assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS)); assertTrue(socket.closeLatch.await(5, TimeUnit.SECONDS)); } }
923609a04ed82d1943d177b3569ee829b7f6cc8a
475
java
Java
src/main/java/com/spaghettyArts/projectakrasia/repository/ResetRepository.java
Spaghetty-Arts/Project-Akrasia-WebServer
2e5eedb9828d080b1965ae66a263260e738955e1
[ "MIT" ]
1
2021-05-19T22:09:25.000Z
2021-05-19T22:09:25.000Z
src/main/java/com/spaghettyArts/projectakrasia/repository/ResetRepository.java
Spaghetty-Arts/project-akrasia-webserver
2e5eedb9828d080b1965ae66a263260e738955e1
[ "MIT" ]
null
null
null
src/main/java/com/spaghettyArts/projectakrasia/repository/ResetRepository.java
Spaghetty-Arts/project-akrasia-webserver
2e5eedb9828d080b1965ae66a263260e738955e1
[ "MIT" ]
null
null
null
27.941176
77
0.793684
997,516
package com.spaghettyArts.projectakrasia.repository; import com.spaghettyArts.projectakrasia.model.ResetModel; import org.springframework.data.jpa.repository.JpaRepository; /** * O repositório para as querys a tabela reset da base de dados * @author Fabian Nunes * @version 1.0 */ public interface ResetRepository extends JpaRepository<ResetModel, Integer> { ResetModel findByTokenAndEmail(String token, String email); ResetModel findByEmail(String email); }
923609a5d7dfa95a2f980de6586f1ba0833bcaa5
1,467
java
Java
ycsb-core/src/main/java/com/leo/ycsb/measurements/exporter/XxlJobMeasurementsExporter.java
Lijiaxian559/ycsb-web
3770de86206fa0e61c45ecc16c42b37dae5bd8b3
[ "MIT" ]
7
2021-02-23T09:49:15.000Z
2022-01-14T14:16:07.000Z
ycsb-core/src/main/java/com/leo/ycsb/measurements/exporter/XxlJobMeasurementsExporter.java
Lijiaxian559/ycsb-web
3770de86206fa0e61c45ecc16c42b37dae5bd8b3
[ "MIT" ]
1
2022-03-10T05:21:26.000Z
2022-03-10T05:21:27.000Z
ycsb-core/src/main/java/com/leo/ycsb/measurements/exporter/XxlJobMeasurementsExporter.java
Lijiaxian559/ycsb-web
3770de86206fa0e61c45ecc16c42b37dae5bd8b3
[ "MIT" ]
1
2022-01-15T05:27:03.000Z
2022-01-15T05:27:03.000Z
31.212766
87
0.625085
997,517
package com.leo.ycsb.measurements.exporter; import com.leo.ycsb.job.core.context.XxlJobHelper; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; /** * @author leojie 2021/2/11 2:32 下午 */ public class XxlJobMeasurementsExporter implements MeasurementsExporter { private final BufferedWriter bw; public XxlJobMeasurementsExporter(OutputStream os){ this.bw = new BufferedWriter(new OutputStreamWriter(os)); } @Override public void write(String metric, String measurement, int i) throws IOException { XxlJobHelper.log("[" + metric + "], " + measurement + ", " + i); bw.write("[" + metric + "], " + measurement + ", " + i); bw.newLine(); } @Override public void write(String metric, String measurement, long i) throws IOException { XxlJobHelper.log("[" + metric + "], " + measurement + ", " + i); bw.write("[" + metric + "], " + measurement + ", " + i); bw.newLine(); } @Override public void write(String metric, String measurement, double d) throws IOException { XxlJobHelper.log("[" + metric + "], " + measurement + ", " + d); bw.write("[" + metric + "], " + measurement + ", " + d); bw.newLine(); } @Override public void close() throws IOException { XxlJobHelper.log("XxlJobMeasurementsExporter is closed."); this.bw.close(); } }
92360dbae4f1bc3753356644fe35039269470bc7
4,024
java
Java
youliao-web/src/main/java/com/seahorse/youliao/config/ScheduleTaskComponent.java
gitSina9468/youliao
d8d91c858d38b26aeabdf903724f8aa45a889322
[ "Apache-2.0" ]
6
2020-07-13T19:29:36.000Z
2022-03-27T09:55:54.000Z
youliao-web/src/main/java/com/seahorse/youliao/config/ScheduleTaskComponent.java
gitSina9468/youliao
d8d91c858d38b26aeabdf903724f8aa45a889322
[ "Apache-2.0" ]
6
2020-07-09T03:08:12.000Z
2022-02-01T01:03:10.000Z
youliao-web/src/main/java/com/seahorse/youliao/config/ScheduleTaskComponent.java
gitSina9468/youliao
d8d91c858d38b26aeabdf903724f8aa45a889322
[ "Apache-2.0" ]
4
2020-07-13T19:29:38.000Z
2022-03-27T09:55:55.000Z
28.742857
114
0.637177
997,518
package com.seahorse.youliao.config; import com.seahorse.youliao.service.ScheduleConfigService; import com.seahorse.youliao.service.entity.ScheduleConfigDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.lang.reflect.Method; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; /** * @ProjectName: youliao * @Package: com.seahorse.youliao.config * @ClassName: ScheduleTaskComponent * @Description: 定时任务组件初始化加载定时任务 * @author:songqiang * @Date:2020-06-24 16:38 **/ @Slf4j @Component public class ScheduleTaskComponent { // 保存任务 private Map<String, ScheduledFuture<?>> futuresMap = new ConcurrentHashMap<String, ScheduledFuture<?>>(); @Autowired private ScheduleConfigService scheduleConfigService; // 创建ThreadPoolTaskScheduler线程池 @Autowired private ThreadPoolTaskScheduler threadPoolTaskScheduler; // 初始化任务 @PostConstruct public void initSchedule(){ List<ScheduleConfigDTO> list = scheduleConfigService.getList(null); for (ScheduleConfigDTO config : list){ ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(getRunnable(config), getTrigger(config)); futuresMap.put(config.getJobName(), future); } } /** * 暂停任务 * @param key * @return */ public boolean pauseeTask(String key) { ScheduledFuture toBeRemovedFuture = futuresMap.remove(key); if (toBeRemovedFuture != null) { toBeRemovedFuture.cancel(true); return true; } else { return false; } } /** * 添加任务 * @param config */ public void addTask(ScheduleConfigDTO config){ ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(getRunnable(config), getTrigger(config)); futuresMap.put(config.getJobName(), future); } /** * 更新任务 * @param config */ public void updateTask(ScheduleConfigDTO config) { ScheduledFuture toBeRemovedFuture = futuresMap.remove(config.getJobName()); if (toBeRemovedFuture != null) { toBeRemovedFuture.cancel(true); } addTask(config); } /** * 转换首字母小写 * * @param str * @return */ public static String lowerFirstCapse(String str) { char[] chars = str.toCharArray(); chars[0] += 32; return String.valueOf(chars); } /** * runnable * @param scheduleConfig * @return */ private Runnable getRunnable(ScheduleConfigDTO scheduleConfig){ return new Runnable() { @Override public void run() { Class<?> clazz; try { clazz = Class.forName(scheduleConfig.getClassName()); Method method = clazz.getMethod(scheduleConfig.getMethod()); //调用方法 method.invoke(clazz.newInstance()); } catch (Exception e) { log.error(e.getMessage()); } } }; } /** * Trigger * @param scheduleConfig * @return */ private Trigger getTrigger(ScheduleConfigDTO scheduleConfig) { return new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { CronTrigger trigger = new CronTrigger(scheduleConfig.getCron()); Date nextExec = trigger.nextExecutionTime(triggerContext); return nextExec; } }; } }
92360df658d96108b5e2240b8805ee7a91c0999f
3,127
java
Java
perfload-client/src/main/java/com/mgmtp/perfload/core/client/web/event/DefaultLoggingListener.java
mgm-tp/perfload-core
a33b59e9f7b07b3beadf09438d3c0e48505b982a
[ "Apache-2.0" ]
null
null
null
perfload-client/src/main/java/com/mgmtp/perfload/core/client/web/event/DefaultLoggingListener.java
mgm-tp/perfload-core
a33b59e9f7b07b3beadf09438d3c0e48505b982a
[ "Apache-2.0" ]
null
null
null
perfload-client/src/main/java/com/mgmtp/perfload/core/client/web/event/DefaultLoggingListener.java
mgm-tp/perfload-core
a33b59e9f7b07b3beadf09438d3c0e48505b982a
[ "Apache-2.0" ]
null
null
null
30.359223
122
0.73393
997,519
/* * Copyright (c) 2002-2015 mgm technology partners GmbH * * 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.mgmtp.perfload.core.client.web.event; import java.util.UUID; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import com.mgmtp.perfload.core.client.web.config.WebLtModule; import com.mgmtp.perfload.core.client.web.response.ResponseInfo; import com.mgmtp.perfload.logging.ResultLogger; import com.mgmtp.perfload.logging.TimeInterval; /** * Listener for logging time measurements. This listener is registered internally by perfLoad in * {@link WebLtModule}. * * @author rnaegele */ @Singleton @ThreadSafe @Immutable public final class DefaultLoggingListener implements RequestFlowEventListener { private final Provider<ResultLogger> loggerProvider; /** * @param loggerProvider * The {@link Provider} for the {@link ResultLogger}. Since this class has * {@link Singleton} scope and the result logger may have a narrower scope, a * provider must be injected in order to avoid scope widening. */ @Inject public DefaultLoggingListener(final Provider<ResultLogger> loggerProvider) { this.loggerProvider = loggerProvider; } /** * Does nothing. */ @Override public void beforeRequestFlow(final RequestFlowEvent event) { /* no-op */ } /** * Does nothing. */ @Override public void afterRequestFlow(final RequestFlowEvent event) { /* no-op */ } /** * Does nothing. */ @Override public void beforeRequest(final RequestFlowEvent event) { /* no-op */ } /** * Retrieves the {@link ResponseInfo} from the {@code event} and, if {@code non-null}, logs it * with the current {@link ResultLogger}. */ @Override public void afterRequest(final RequestFlowEvent event) { ResponseInfo responseInfo = event.getResponseInfo(); if (responseInfo != null) { String errorMsg = event.getErrorMsg(); String type = responseInfo.getMethodType(); TimeInterval tiBeforeBody = responseInfo.getTimeIntervalBeforeBody(); TimeInterval tiTotal = responseInfo.getTimeIntervalTotal(); String uri = responseInfo.getUri(); String uriAlias = responseInfo.getUriAlias(); if (uriAlias == null) { uriAlias = uri; } UUID execId = responseInfo.getExecutionId(); UUID requestId = responseInfo.getRequestId(); ResultLogger logger = loggerProvider.get(); logger.logResult(errorMsg, responseInfo.getTimestamp(), tiBeforeBody, tiTotal, type, uri, uriAlias, execId, requestId); } } }
92360e8f3971d9beb22d2014a6e09e6eb9bd3ded
2,452
java
Java
src/main/java/com/sbnvw/artemis/Setup.java
djmbritt/Artemis
d9e646e143ed8359c7375322081f138ab3dc6d50
[ "MIT" ]
null
null
null
src/main/java/com/sbnvw/artemis/Setup.java
djmbritt/Artemis
d9e646e143ed8359c7375322081f138ab3dc6d50
[ "MIT" ]
null
null
null
src/main/java/com/sbnvw/artemis/Setup.java
djmbritt/Artemis
d9e646e143ed8359c7375322081f138ab3dc6d50
[ "MIT" ]
null
null
null
48.078431
117
0.778548
997,520
package com.sbnvw.artemis; import com.sbnvw.artemis.animal_kingdom.traits.TraitBehaviour; import com.sbnvw.artemis.animal_kingdom.traits.TraitGroup; import com.sbnvw.artemis.animal_kingdom.treeOfLife.Animal; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.ClassType; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Family; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Genus; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Kingdom; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Order; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Phylum; import com.sbnvw.artemis.animal_kingdom.treeOfLife.classifications.Species; import com.sbnvw.artemis.animal_kingdom.treeOfLife.factorys.AnimalFactory; import com.sbnvw.artemis.animal_kingdom.treeOfLife.factorys.ClassificationFactory; import com.sbnvw.artemis.managers.ClassificationManager; import com.sbnvw.artemis.managers.TraitsManager; /** * * @author Marcel van Wilgenburg */ public class Setup { public Setup() throws ClassNotFoundException { setupClassifications(); } private void setupClassifications() throws ClassNotFoundException { Kingdom Animal = (Kingdom) ClassificationFactory.makeClassification("Animal", null, "Kingdom"); Phylum Chordata = (Phylum) ClassificationFactory.makeClassification("Chordata", Animal, "Phylum"); ClassType Mammalia = (ClassType) ClassificationFactory.makeClassification("Mammalia", Chordata, "ClassType"); Order Carnivora = (Order) ClassificationFactory.makeClassification("Carnivora", Mammalia, "Order"); Family Felidae = (Family) ClassificationFactory.makeClassification("Felidae", Carnivora, "Family"); Genus felis = (Genus) ClassificationFactory.makeClassification("Felis", Felidae, "Genus"); Species cat = (Species) ClassificationFactory.makeClassification("Cat", felis, "Species"); Animal korthaar = AnimalFactory.makeAnimal("Korthaar", cat); TraitGroup diet = new TraitGroup("Diet"); diet.addTraitBehaviour(new TraitBehaviour("Eats meat", diet)); diet.addTraitBehaviour(new TraitBehaviour("Eats plants", diet)); diet.addTraitBehaviour(new TraitBehaviour("Eats meat and plants", diet)); ClassificationManager.getClassificationByName("Carnivora").addTrait(diet.getTraitBehaviours().get(0)); } }
92360ea51257ed85eba17dc8d50c4717178aadea
2,013
java
Java
api/src/main/java/cz/muni/fi/pa165/sportsclub/dto/PlayerDto.java
HonzaCech/PA165-SportClub
995f9db00c63ecb12a1d814d11be546c75ba81cb
[ "Apache-2.0" ]
null
null
null
api/src/main/java/cz/muni/fi/pa165/sportsclub/dto/PlayerDto.java
HonzaCech/PA165-SportClub
995f9db00c63ecb12a1d814d11be546c75ba81cb
[ "Apache-2.0" ]
73
2017-10-29T17:36:08.000Z
2018-01-11T23:13:43.000Z
api/src/main/java/cz/muni/fi/pa165/sportsclub/dto/PlayerDto.java
HonzaCech/PA165-SportClub
995f9db00c63ecb12a1d814d11be546c75ba81cb
[ "Apache-2.0" ]
3
2017-10-28T12:29:33.000Z
2017-10-29T16:20:04.000Z
22.617978
146
0.670144
997,521
package cz.muni.fi.pa165.sportsclub.dto; import com.fasterxml.jackson.annotation.JsonManagedReference; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Date; import java.util.Objects; import java.util.Set; /** * DTO for player * * @author 422636 Adam Krajcik */ public class PlayerDto extends PersonDto { private int height; private int weight; private Date dateOfBirth; @JsonManagedReference private Set<RosterEntryDto> rosterEntries; private int age; private String localDate; public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Set<RosterEntryDto> getRosterEntries() { return rosterEntries; } public void setRosterEntries(Set<RosterEntryDto> rosterEntries) { this.rosterEntries = rosterEntries; } public int getAge() { return Period.between(dateOfBirth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalDate.now()).getYears(); } public String getLocalDate() { return dateOfBirth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlayerDto playerDto = (PlayerDto) o; return Objects.equals(getEmail(), playerDto.getEmail()); } @Override public int hashCode() { return Objects.hash(getEmail()); } }
92360fff30d90a80b620dac9365c159e7bb8b657
3,093
java
Java
src/main/java/ftb/utils/api/guide/lines/GuideExtendedTextLine.java
cosmicdan/FTBUtilitiesAW2
15580ba0446124da585ac5b52d681cf84e41fc27
[ "MIT" ]
null
null
null
src/main/java/ftb/utils/api/guide/lines/GuideExtendedTextLine.java
cosmicdan/FTBUtilitiesAW2
15580ba0446124da585ac5b52d681cf84e41fc27
[ "MIT" ]
null
null
null
src/main/java/ftb/utils/api/guide/lines/GuideExtendedTextLine.java
cosmicdan/FTBUtilitiesAW2
15580ba0446124da585ac5b52d681cf84e41fc27
[ "MIT" ]
null
null
null
21.331034
82
0.667637
997,523
package ftb.utils.api.guide.lines; import com.google.gson.*; import cpw.mods.fml.relauncher.*; import ftb.lib.JsonHelper; import ftb.lib.api.client.FTBLibClient; import ftb.lib.api.notification.ClickAction; import ftb.utils.api.guide.GuidePage; import ftb.utils.mod.client.gui.guide.*; import net.minecraft.event.*; import net.minecraft.util.IChatComponent; import java.util.*; /** * Created by LatvianModder on 20.03.2016. */ public class GuideExtendedTextLine extends GuideTextLine { protected IChatComponent text; private ClickAction clickAction; private List<IChatComponent> hover; public GuideExtendedTextLine(GuidePage c, IChatComponent cc) { super(c, null); text = cc; if(text != null) { ClickEvent clickEvent = text.getChatStyle().getChatClickEvent(); if(clickEvent != null) { clickAction = ClickAction.from(clickEvent); } HoverEvent hoverEvent = text.getChatStyle().getChatHoverEvent(); if(hoverEvent != null && hoverEvent.getAction() == HoverEvent.Action.SHOW_TEXT) { hover = Collections.singletonList(hoverEvent.getValue()); } } } public IChatComponent getText() { return text; } @SideOnly(Side.CLIENT) public ButtonGuideTextLine createWidget(GuiGuide gui) { return new ButtonGuideExtendedTextLine(gui, this); } public List<IChatComponent> getHover() { return hover; } @SideOnly(Side.CLIENT) public boolean hasClickAction() { return clickAction != null; } @SideOnly(Side.CLIENT) public void onClicked() { if(clickAction != null) { FTBLibClient.playClickSound(); clickAction.onClicked(); } } public void func_152753_a(JsonElement e) { JsonObject o = e.getAsJsonObject(); text = o.has("text") ? JsonHelper.deserializeICC(o.get("text")) : null; if(o.has("click")) { clickAction = new ClickAction(); clickAction.func_152753_a(o.get("click")); } else clickAction = null; if(o.has("hover")) { hover = new ArrayList<>(); JsonElement e1 = o.get("hover"); if(e1.isJsonPrimitive()) hover.add(JsonHelper.deserializeICC(e1)); else { for(JsonElement e2 : o.get("hover").getAsJsonArray()) { hover.add(JsonHelper.deserializeICC(e2)); } } if(hover.isEmpty()) hover = null; } else hover = null; } public JsonElement getSerializableElement() { JsonObject o = new JsonObject(); if(text != null) o.add("text", JsonHelper.serializeICC(text)); if(clickAction != null) { o.add("click", clickAction.getSerializableElement()); } if(hover != null && !hover.isEmpty()) { if(hover.size() == 1) { o.add("hover", JsonHelper.serializeICC(hover.get(0))); } else { JsonArray a = new JsonArray(); for(IChatComponent c : hover) { a.add(JsonHelper.serializeICC(c)); } o.add("hover", a); } } return o; } public void setClickAction(ClickAction a) { clickAction = a; } public void setHover(List<IChatComponent> h) { if(h == null || h.isEmpty()) hover = null; else { hover = new ArrayList<>(h.size()); hover.addAll(h); } } }
9236103ad89649c6398826b96900a9ab23d61a38
998
java
Java
src/main/java/dev/itboot/mb/mapper/StaffMapper.java
noikedan/springmybatis
7de7eb105c1b4917854a826b108718bfbd712901
[ "MIT" ]
1
2021-06-07T15:38:55.000Z
2021-06-07T15:38:55.000Z
src/main/java/dev/itboot/mb/mapper/StaffMapper.java
noikedan/springmybatis
7de7eb105c1b4917854a826b108718bfbd712901
[ "MIT" ]
null
null
null
src/main/java/dev/itboot/mb/mapper/StaffMapper.java
noikedan/springmybatis
7de7eb105c1b4917854a826b108718bfbd712901
[ "MIT" ]
null
null
null
22.177778
63
0.622244
997,524
package dev.itboot.mb.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import dev.itboot.mb.model.Staff; @Mapper public interface StaffMapper { @Select("SELECT * FROM staff") List<Staff> selectAll(); // 以下を追加 @Select({ "SELECT * FROM staff", "WHERE id = #{id}" }) Staff selectByPrimaryKey(Long id); @Insert({ "INSERT INTO staff(name, email, status, registration)", "VALUES(#{name}, #{email}, 't' ,sysdate)" }) int insert(Staff record); @Update({ "UPDATE staff", "SET name = #{name}, email = #{email}", "WHERE id = #{id}" }) int updateByPrimaryKey(Staff record); @Delete({ "DELETE FROM staff", "WHERE id = #{id}" }) int deleteByPrimaryKey(Long id); }
923610a1e272d3abda9f8d9af128849c2630576a
495
java
Java
src/main/java/com/ekocaman/config/CalculatorApplication.java
johndavid93/webpro11
d61d05dce916928d626bb3eeb84c21b7978db391
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ekocaman/config/CalculatorApplication.java
johndavid93/webpro11
d61d05dce916928d626bb3eeb84c21b7978db391
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ekocaman/config/CalculatorApplication.java
johndavid93/webpro11
d61d05dce916928d626bb3eeb84c21b7978db391
[ "Apache-2.0" ]
null
null
null
29.117647
69
0.781818
997,525
package com.ekocaman.config; import com.ekocaman.rest.CalculatorResource; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.scope.RequestContextFilter; public class CalculatorApplication extends ResourceConfig { public CalculatorApplication() { register(RequestContextFilter.class); register(CalculatorResource.class); register(ParameterExceptionMapper.class); register(ArithmeticExceptionMapper.class); } }
923610db0bdc999485877634ddd9516c12bd8154
5,522
java
Java
Client/Mdk3/app/src/main/java/com/coko/mdk3/CopyMainActivity.java
denisu08/hackathonmania
ef417458450a884d92bc70e6434d3f8242034868
[ "MIT" ]
null
null
null
Client/Mdk3/app/src/main/java/com/coko/mdk3/CopyMainActivity.java
denisu08/hackathonmania
ef417458450a884d92bc70e6434d3f8242034868
[ "MIT" ]
null
null
null
Client/Mdk3/app/src/main/java/com/coko/mdk3/CopyMainActivity.java
denisu08/hackathonmania
ef417458450a884d92bc70e6434d3f8242034868
[ "MIT" ]
null
null
null
38.347222
135
0.655016
997,526
package com.coko.mdk3; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ListView; import com.coko.mdk3.adapter.DrawerItemCustomAdapter; import com.coko.mdk3.adapter.ImageDashboardAdapter; import com.coko.mdk3.model.LauncherIcon; import com.coko.mdk3.model.ObjectDrawerItem; import com.coko.mdk3.utility.SessionManager; public class CopyMainActivity extends AppCompatActivity { private String[] mNavigationDrawerItemTitles; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private Toolbar toolbar; private GridView gridView; SessionManager session; private int selectedPosition; static final ObjectDrawerItem[ ] drawerItems = { new ObjectDrawerItem(R.drawable.ic_action_copy, "Help"), new ObjectDrawerItem(R.drawable.ic_logout, "Logout") }; static final LauncherIcon[] icons = { new LauncherIcon(R.drawable.ic_logo_golkar,"Golkar","ic_logo_golkar.png"), new LauncherIcon(R.drawable.ic_logo_pdi,"PDI","ic_logo_pdi.jpg"), new LauncherIcon(R.drawable.ic_logo_pks,"PKS","ic_logo_pks.png"), new LauncherIcon(R.drawable.ic_logo_nasdem,"Nasdem","ic_logo_nasdem.jpg") }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); session = new SessionManager(getApplicationContext()); if(!session.isLoggedIn()){ Intent intent = new Intent(CopyMainActivity.this,LoginActivity.class); startActivity(intent); } mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.navlist); toolbar = (Toolbar) findViewById(R.id.toolbar); gridView = (GridView) findViewById(R.id.dashboard_grid); /* ====== Toolbar layout ============= */ // TODO : add inbox icon in toolbar for notification toolbar.setNavigationIcon(R.drawable.ic_drawer); if(toolbar != null) { setSupportActionBar(toolbar); } /*======= Drawer Layout =========== */ // TODO : Add my profile icon and preview in drawer layout, delete unecessary menu mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this,R.layout.navdrawer_list_item_row,drawerItems); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedPosition = position; mDrawerLayout.closeDrawer(mDrawerList); if(drawerItems[selectedPosition].name.equals("Logout")){ session.clearAllSession(); Intent intent = new Intent(CopyMainActivity.this,LoginActivity.class); startActivity(intent); finish(); } } }); /* ============ News Layout ====================*/ //TODO : Add news layout between toolbar and gridview, slider type /* ========== Grid Layout ========== */ // TODO : create activity for detail on image is clicked ImageDashboardAdapter imageDashboardAdapter = new ImageDashboardAdapter(getApplicationContext(),R.layout.dashboard_icon,icons); gridView.setAdapter(imageDashboardAdapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Intent intent = new Intent(this,DetailPartaiActivity.class); // startActivity(intent); } }); //disable gridview scrolling gridView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return event.getAction() == MotionEvent.ACTION_MOVE; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mDrawerLayout.openDrawer(GravityCompat.START); return true; case R.id.action_notification: Intent intent = new Intent(this,ElectionScheduleActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onStop(){ super.onStop(); this.finish(); } }
9236134293f45b1c085c38e328d0aacb903ed60f
952
java
Java
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/cas/CasLogoutHandler.java
haidisenlin/apollo
bac472184cd9a45c5492ac3d6cd6976d603940d7
[ "Apache-2.0" ]
null
null
null
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/cas/CasLogoutHandler.java
haidisenlin/apollo
bac472184cd9a45c5492ac3d6cd6976d603940d7
[ "Apache-2.0" ]
null
null
null
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/cas/CasLogoutHandler.java
haidisenlin/apollo
bac472184cd9a45c5492ac3d6cd6976d603940d7
[ "Apache-2.0" ]
null
null
null
29.75
82
0.678571
997,527
package com.ctrip.framework.apollo.portal.spi.cas; import com.ctrip.framework.apollo.portal.spi.LogoutHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Date; public class CasLogoutHandler implements LogoutHandler { @Override public void logout(HttpServletRequest request, HttpServletResponse response) { //将session销毁 HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } //重定向到Cas的logout地址 String casServerUrl = "http://sso.sunnyoptical.cn"; String serverName = "http://127.0.0.1:8070/?"+new Date(); try { response.sendRedirect(casServerUrl + "/logout?service=" + serverName); } catch (IOException e) { throw new RuntimeException(e); } } }
9236134b1eac303a241fc613e1f739f2bac82ba5
2,996
java
Java
src/test/java/cufy/io/BufferedReaderTest.java
cufyorg/io
c56e9b53bc29b44b7c88b7885178ea2f38aa1231
[ "Apache-2.0" ]
7
2020-04-15T20:59:54.000Z
2021-06-03T22:50:24.000Z
src/test/java/cufy/io/BufferedReaderTest.java
LSafer/Cufy-IO
c56e9b53bc29b44b7c88b7885178ea2f38aa1231
[ "Apache-2.0" ]
3
2021-06-16T11:26:48.000Z
2021-06-16T11:27:55.000Z
src/test/java/cufy/io/BufferedReaderTest.java
LSafer/Cufy-IO
c56e9b53bc29b44b7c88b7885178ea2f38aa1231
[ "Apache-2.0" ]
3
2020-04-15T21:08:38.000Z
2021-06-16T11:17:19.000Z
25.606838
99
0.648531
997,528
package cufy.io; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.io.Reader; import java.io.StringReader; @SuppressWarnings("JavaDoc") public class BufferedReaderTest { @SuppressWarnings("StringConcatenationInLoop") @Test(timeout = 200) public void mark_remark() throws IOException { String text = "ABC" + "DEF"; Reader reader = new BufferedReader(new StringReader(text)); reader.mark(10); String s = ""; int i; char c; while ((i = reader.read()) != -1 && (c = (char) i) != 'D') { s += c; } reader.reset(); reader.mark(10); String s1 = ""; int i1; char c1; while ((i1 = reader.read()) != -1 && (c1 = (char) i1) != 'D') { s1 += c1; } Assert.assertEquals("Can't read at all!", "ABC", s); Assert.assertEquals("Remark don't work!", "ABC", s1); } @SuppressWarnings({"StringConcatenationInLoop", "SpellCheckingInspection"}) @Test public void read_mark_skip_reset_followup() throws IOException { String str = "ABCD" + "EFGH" + "IJKL" + "MNOP" + "QRST" + "UVWX" + "YZ01"; Reader reader = new StringReader(str); BufferedReader mask = new BufferedReader(reader); //reader & mask CURSOR before 'A' mask.mark(4); //mask MARK before 'A' String str_init = ""; for (int i : new int[4]) str_init += (char) mask.read(); //reader & mask CURSOR before 'E' Assert.assertEquals("Wrong sequence", "ABCD", str_init); mask.reset(); //reader CURSOR before 'E'; mask CURSOR before 'A' String str_reset = ""; for (int i : new int[4]) str_reset += (char) mask.read(); //reader & mask CURSOR before 'E' Assert.assertEquals("Mask maybe not reset", "ABCD", str_reset); mask.skip(4); //reader & mask CURSOR before 'I' String str_skip = ""; for (int i : new int[4]) str_skip += (char) mask.read(); //reader & mask CURSOR before 'M' Assert.assertEquals("Mask maybe not skipped", "IJKL", str_skip); mask.mark(4); //mask MARK before 'M' mask.skip(4); //reader & mask CURSOR before 'Q' mask.reset(); //reader CURSOR before 'Q'; mask CURSOR before 'M' String str_remark = ""; for (int i : new int[4]) str_remark += (char) mask.read(); //reader & mask CURSOR before 'Q' Assert.assertEquals("Mask not reset to latest mark", "MNOP", str_remark); String str_continue_raw = ""; for (int i : new int[4]) str_continue_raw += (char) reader.read(); //reader CURSOR before 'U'; mask CURSOR before 'Q' Assert.assertEquals("Reader should continue as where mask stopped at", "QRST", str_continue_raw); mask.mark(4); //mask MARK before 'Q' mask.getBuffer().write(str_continue_raw.toCharArray(), 0, str_continue_raw.length()); //reader & mask CURSOR before 'U' mask.reset(); //reader CURSOR before 'U'; mask CURSOR before 'Q' String str_followup = ""; for (int i : new int[4]) str_followup += (char) mask.read(); //reader & mask CURSOR before 'U' Assert.assertEquals("Followup maybe not working", "QRST", str_followup); } }
9236137e3e7aea62770c628662d3e7629ab6c5bc
9,906
java
Java
gen/simplerlangParser.java
rafael-telles/UFABC-MCTA007-17
7f0ce26230363024f48700b01617f3b21fa05c5c
[ "MIT" ]
null
null
null
gen/simplerlangParser.java
rafael-telles/UFABC-MCTA007-17
7f0ce26230363024f48700b01617f3b21fa05c5c
[ "MIT" ]
null
null
null
gen/simplerlangParser.java
rafael-telles/UFABC-MCTA007-17
7f0ce26230363024f48700b01617f3b21fa05c5c
[ "MIT" ]
1
2019-07-14T01:45:25.000Z
2019-07-14T01:45:25.000Z
29.927492
119
0.701393
997,529
// Generated from /home/rafael/Desktop/UFABC/Compiladores/Projeto Final/src/main/antlr4/Stark.g4 by ANTLR 4.7.2 import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class simplerlangParser extends Parser { static { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, T__1=2, VAR=3, INT=4, WS=5; public static final int RULE_program = 0, RULE_statement = 1, RULE_let = 2, RULE_show = 3; private static String[] makeRuleNames() { return new String[] { "program", "statement", "let", "show" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'='", "'show'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, null, null, "VAR", "INT", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "Stark.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public simplerlangParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class ProgramContext extends ParserRuleContext { public List<StatementContext> statement() { return getRuleContexts(StatementContext.class); } public StatementContext statement(int i) { return getRuleContext(StatementContext.class,i); } public ProgramContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_program; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).enterProgram(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).exitProgram(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof simplerlangVisitor ) return ((simplerlangVisitor<? extends T>)visitor).visitProgram(this); else return visitor.visitChildren(this); } } public final ProgramContext program() throws RecognitionException { ProgramContext _localctx = new ProgramContext(_ctx, getState()); enterRule(_localctx, 0, RULE_program); int _la; try { enterOuterAlt(_localctx, 1); { setState(9); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(8); statement(); } } setState(11); _errHandler.sync(this); _la = _input.LA(1); } while ( _la==T__1 || _la==VAR ); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class StatementContext extends ParserRuleContext { public LetContext let() { return getRuleContext(LetContext.class,0); } public ShowContext show() { return getRuleContext(ShowContext.class,0); } public StatementContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_statement; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).enterStatement(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).exitStatement(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof simplerlangVisitor ) return ((simplerlangVisitor<? extends T>)visitor).visitStatement(this); else return visitor.visitChildren(this); } } public final StatementContext statement() throws RecognitionException { StatementContext _localctx = new StatementContext(_ctx, getState()); enterRule(_localctx, 2, RULE_statement); try { setState(15); _errHandler.sync(this); switch (_input.LA(1)) { case VAR: enterOuterAlt(_localctx, 1); { setState(13); let(); } break; case T__1: enterOuterAlt(_localctx, 2); { setState(14); show(); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LetContext extends ParserRuleContext { public TerminalNode VAR() { return getToken(simplerlangParser.VAR, 0); } public TerminalNode INT() { return getToken(simplerlangParser.INT, 0); } public LetContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_let; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).enterLet(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).exitLet(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof simplerlangVisitor ) return ((simplerlangVisitor<? extends T>)visitor).visitLet(this); else return visitor.visitChildren(this); } } public final LetContext let() throws RecognitionException { LetContext _localctx = new LetContext(_ctx, getState()); enterRule(_localctx, 4, RULE_let); try { enterOuterAlt(_localctx, 1); { setState(17); match(VAR); setState(18); match(T__0); setState(19); match(INT); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ShowContext extends ParserRuleContext { public TerminalNode INT() { return getToken(simplerlangParser.INT, 0); } public TerminalNode VAR() { return getToken(simplerlangParser.VAR, 0); } public ShowContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_show; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).enterShow(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof simplerlangListener ) ((simplerlangListener)listener).exitShow(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof simplerlangVisitor ) return ((simplerlangVisitor<? extends T>)visitor).visitShow(this); else return visitor.visitChildren(this); } } public final ShowContext show() throws RecognitionException { ShowContext _localctx = new ShowContext(_ctx, getState()); enterRule(_localctx, 6, RULE_show); int _la; try { enterOuterAlt(_localctx, 1); { setState(21); match(T__1); setState(22); _la = _input.LA(1); if ( !(_la==VAR || _la==INT) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\7\33\4\2\t\2\4\3"+ "\t\3\4\4\t\4\4\5\t\5\3\2\6\2\f\n\2\r\2\16\2\r\3\3\3\3\5\3\22\n\3\3\4\3"+ "\4\3\4\3\4\3\5\3\5\3\5\3\5\2\2\6\2\4\6\b\2\3\3\2\5\6\2\30\2\13\3\2\2\2"+ "\4\21\3\2\2\2\6\23\3\2\2\2\b\27\3\2\2\2\n\f\5\4\3\2\13\n\3\2\2\2\f\r\3"+ "\2\2\2\r\13\3\2\2\2\r\16\3\2\2\2\16\3\3\2\2\2\17\22\5\6\4\2\20\22\5\b"+ "\5\2\21\17\3\2\2\2\21\20\3\2\2\2\22\5\3\2\2\2\23\24\7\5\2\2\24\25\7\3"+ "\2\2\25\26\7\6\2\2\26\7\3\2\2\2\27\30\7\4\2\2\30\31\t\2\2\2\31\t\3\2\2"+ "\2\4\r\21"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
923613aa38ec091d757f110786c7586781b02329
951
java
Java
main/tests/server/src/com/google/refine/commands/EngineDependentCommandTests.java
Nishtha3512/OpenRefine
93f6715f61d9e131b9c992d7091b4614a8639f6c
[ "BSD-3-Clause" ]
2
2020-06-18T22:32:15.000Z
2020-06-18T22:32:22.000Z
main/tests/server/src/com/google/refine/commands/EngineDependentCommandTests.java
Nishtha3512/OpenRefine
93f6715f61d9e131b9c992d7091b4614a8639f6c
[ "BSD-3-Clause" ]
55
2021-11-23T17:26:52.000Z
2022-03-30T17:23:23.000Z
main/tests/server/src/com/google/refine/commands/EngineDependentCommandTests.java
Nishtha3512/OpenRefine
93f6715f61d9e131b9c992d7091b4614a8639f6c
[ "BSD-3-Clause" ]
2
2020-07-17T02:32:08.000Z
2020-07-17T02:33:42.000Z
24.384615
90
0.805468
997,530
package com.google.refine.commands; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.refine.browsing.EngineConfig; import com.google.refine.model.AbstractOperation; import com.google.refine.model.Project; public class EngineDependentCommandTests extends CommandTestBase { private static class EngineDependentCommandStub extends EngineDependentCommand { @Override protected AbstractOperation createOperation(Project project, HttpServletRequest request, EngineConfig engineConfig) throws Exception { return null; } } @BeforeMethod public void setUpCommand() { command = new EngineDependentCommandStub(); } @Test public void testCSRFProtection() throws ServletException, IOException { command.doPost(request, response); assertCSRFCheckFailed(); } }
923613e209a7c65c8c70f3884372b7aea377ff09
477
java
Java
gmall-oms/src/main/java/com/atguigu/gmall/oms/service/OrderReturnReasonService.java
daiyuquan123456/gmall
5d3fd4a7db8144149f985a55fd54c4d1bda410ee
[ "Apache-2.0" ]
null
null
null
gmall-oms/src/main/java/com/atguigu/gmall/oms/service/OrderReturnReasonService.java
daiyuquan123456/gmall
5d3fd4a7db8144149f985a55fd54c4d1bda410ee
[ "Apache-2.0" ]
2
2021-04-22T17:01:42.000Z
2021-09-20T20:54:24.000Z
gmall-oms/src/main/java/com/atguigu/gmall/oms/service/OrderReturnReasonService.java
daiyuquan123456/gmall
5d3fd4a7db8144149f985a55fd54c4d1bda410ee
[ "Apache-2.0" ]
null
null
null
22.714286
85
0.784067
997,531
package com.atguigu.gmall.oms.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.gmall.oms.entity.OrderReturnReasonEntity; import com.atguigu.core.bean.PageVo; import com.atguigu.core.bean.QueryCondition; /** * 退货原因 * * @author daiyuquan * @email anpch@example.com * @date 2019-12-03 12:51:56 */ public interface OrderReturnReasonService extends IService<OrderReturnReasonEntity> { PageVo queryPage(QueryCondition params); }
92361417961ea68a1d398d97ac7cd0b8400a48ec
105
java
Java
source/java/interview/delei-interview-spring/src/main/java/cn/delei/spring/aop/service/AopService.java
delei/Learn-Tutorial
7fcd3a19371f78118a92e776161fc36231f06cdd
[ "Apache-2.0" ]
1
2021-04-12T09:51:56.000Z
2021-04-12T09:51:56.000Z
source/java/interview/delei-interview-spring/src/main/java/cn/delei/spring/aop/service/AopService.java
delei/Learn-Tutorial
7fcd3a19371f78118a92e776161fc36231f06cdd
[ "Apache-2.0" ]
1
2021-03-15T15:42:26.000Z
2021-03-15T15:42:26.000Z
source/java/interview/delei-interview-spring/src/main/java/cn/delei/spring/aop/service/AopService.java
delei/Learn-Tutorial
7fcd3a19371f78118a92e776161fc36231f06cdd
[ "Apache-2.0" ]
null
null
null
15
36
0.685714
997,532
package cn.delei.spring.aop.service; public interface AopService { void run(); void aopRun(); }
923614a9518cdc9031cfc1316d97ebd20031d3d4
3,119
java
Java
modules/ejbca-ws-cli/src-gen/org/ejbca/core/protocol/ws/client/gen/SoftTokenRequest.java
ligson/ejbca
7b70dae768c2aa3064b74991f835223d8db2ca52
[ "Apache-2.0" ]
null
null
null
modules/ejbca-ws-cli/src-gen/org/ejbca/core/protocol/ws/client/gen/SoftTokenRequest.java
ligson/ejbca
7b70dae768c2aa3064b74991f835223d8db2ca52
[ "Apache-2.0" ]
null
null
null
modules/ejbca-ws-cli/src-gen/org/ejbca/core/protocol/ws/client/gen/SoftTokenRequest.java
ligson/ejbca
7b70dae768c2aa3064b74991f835223d8db2ca52
[ "Apache-2.0" ]
null
null
null
21.964789
106
0.543123
997,533
package org.ejbca.core.protocol.ws.client.gen; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for softTokenRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="softTokenRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="arg0" type="{http://ws.protocol.core.ejbca.org/}userDataVOWS" minOccurs="0"/> * &lt;element name="arg1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="arg2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="arg3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "softTokenRequest", propOrder = { "arg0", "arg1", "arg2", "arg3" }) public class SoftTokenRequest { protected UserDataVOWS arg0; protected String arg1; protected String arg2; protected String arg3; /** * Gets the value of the arg0 property. * * @return * possible object is * {@link UserDataVOWS } * */ public UserDataVOWS getArg0() { return arg0; } /** * Sets the value of the arg0 property. * * @param value * allowed object is * {@link UserDataVOWS } * */ public void setArg0(UserDataVOWS value) { this.arg0 = value; } /** * Gets the value of the arg1 property. * * @return * possible object is * {@link String } * */ public String getArg1() { return arg1; } /** * Sets the value of the arg1 property. * * @param value * allowed object is * {@link String } * */ public void setArg1(String value) { this.arg1 = value; } /** * Gets the value of the arg2 property. * * @return * possible object is * {@link String } * */ public String getArg2() { return arg2; } /** * Sets the value of the arg2 property. * * @param value * allowed object is * {@link String } * */ public void setArg2(String value) { this.arg2 = value; } /** * Gets the value of the arg3 property. * * @return * possible object is * {@link String } * */ public String getArg3() { return arg3; } /** * Sets the value of the arg3 property. * * @param value * allowed object is * {@link String } * */ public void setArg3(String value) { this.arg3 = value; } }
923614f37dd15ba6c34164146dba642542c6793c
3,430
java
Java
src/test/java/org/cactoos/scalar/HashCodeTest.java
evpl/cactoos
4968768b1c35c483116c70913def7e1a8494b2cb
[ "MIT" ]
751
2017-05-23T16:00:09.000Z
2022-03-12T15:13:14.000Z
src/test/java/org/cactoos/scalar/HashCodeTest.java
evpl/cactoos
4968768b1c35c483116c70913def7e1a8494b2cb
[ "MIT" ]
1,630
2017-05-23T20:05:54.000Z
2022-02-25T10:06:59.000Z
src/test/java/org/cactoos/scalar/HashCodeTest.java
evpl/cactoos
4968768b1c35c483116c70913def7e1a8494b2cb
[ "MIT" ]
256
2017-05-23T18:54:08.000Z
2022-02-13T18:16:48.000Z
36.88172
113
0.658601
997,534
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Objects; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion; import org.llorllale.cactoos.matchers.HasValue; /** * Tests for {@link HashCode}. * @since 1.0 */ final class HashCodeTest { /** * {@link HashCode} must compute the exact same hashCode as produced * by Joshua Block's "Item 9: Always override hashCode when you override * equals" in Effective Java, 2nd edition. */ @Test void computeHashCode() { final int initial = 5; final int multiplier = 31; final Object[] attributes = {5, 31, "abc", 5, 50f, "xyz"}; new Assertion<>( "Value must be equal to Josh Block's implementation of hashCode()", new HashCode(initial, multiplier, attributes), new HasValue<>( joshBloch(initial, multiplier, attributes) ) ).affirm(); } /** * {@link HashCode} must assume an {@code initial} values of 17 and a * {@code multiplier} value of 31 when these are not provided. */ @Test void computeHashCodeWithDefaultValues() { final int initial = 17; final int multiplier = 31; final Object[] attributes = {494, 43, "test", 190, 298f, "joshua"}; new Assertion<>( // @checkstyle LineLength (1 line) "Value must be equal to Josh Block's implementation of hashCode() with initial=17 and multiplier=31", new HashCode(attributes), new HasValue<>( joshBloch(initial, multiplier, attributes) ) ).affirm(); } /** * Joshua Bloch's implementation of hashCode() as per Effective Java, * 2nd Edition, Item 9: "Always override hashCode when you override equals". * @param initial Initial value * @param multiplier Step multiplier * @param attributes The object's attributes * @return Hashcode value */ private static int joshBloch( final int initial, final int multiplier, final Object... attributes ) { int hash = initial; for (final Object attr : attributes) { hash = hash * multiplier + Objects.hashCode(attr); } return hash; } }
9236164e7847d063d5050862cadea7b485b552d2
701
java
Java
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java
mociek124/java_pft
090a5f58ee9f943c265cc40b40f74f1458681fba
[ "Apache-2.0" ]
1
2017-05-02T12:54:43.000Z
2017-05-02T12:54:43.000Z
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java
mociek124/java_pft
090a5f58ee9f943c265cc40b40f74f1458681fba
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/NavigationHelper.java
mociek124/java_pft
090a5f58ee9f943c265cc40b40f74f1458681fba
[ "Apache-2.0" ]
null
null
null
20.617647
74
0.651926
997,535
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; /** * Created by mocius on 2017-03-26. */ public class NavigationHelper extends HelperBase { public NavigationHelper(WebDriver wd) { super(wd); } public void groupPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Groups") && isElementPresent(By.name("new"))) { click(By.linkText("groups")); } } public void homePage(){ if (isElementPresent(By.id("maintable"))){ return; } click(By.linkText("home")); } }
9236176ead262051219cde6217774856ca831679
3,193
java
Java
simple_java_behavior/src/main/java/edu/virginia/biocomplexity/pansim_behavior/StateDataFrameBuilder.java
parantapa/pansim
d0dc7437d0caf57e6b462fd31fd6378174ad1752
[ "Apache-2.0" ]
null
null
null
simple_java_behavior/src/main/java/edu/virginia/biocomplexity/pansim_behavior/StateDataFrameBuilder.java
parantapa/pansim
d0dc7437d0caf57e6b462fd31fd6378174ad1752
[ "Apache-2.0" ]
null
null
null
simple_java_behavior/src/main/java/edu/virginia/biocomplexity/pansim_behavior/StateDataFrameBuilder.java
parantapa/pansim
d0dc7437d0caf57e6b462fd31fd6378174ad1752
[ "Apache-2.0" ]
1
2021-12-17T13:13:16.000Z
2021-12-17T13:13:16.000Z
30.122642
97
0.632321
997,536
/* * 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 edu.virginia.biocomplexity.pansim_behavior; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.channels.Channels; import java.util.Arrays; import java.util.List; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.FieldVector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.TinyIntVector; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.ipc.ArrowFileWriter; import org.apache.arrow.vector.types.pojo.Field; /** * * @author parantapa */ public class StateDataFrameBuilder extends StateDataFrame { public StateDataFrameBuilder(int max_rows, BufferAllocator allocator) { pid = new BigIntVector("pid", allocator); group = new TinyIntVector("group", allocator); current_state = new TinyIntVector("current_state", allocator); next_state = new TinyIntVector("next_state", allocator); dwell_time = new IntVector("dwell_time", allocator); seed = new BigIntVector("seed", allocator); pid.allocateNew(max_rows); group.allocateNew(max_rows); current_state.allocateNew(max_rows); next_state.allocateNew(max_rows); dwell_time.allocateNew(max_rows); seed.allocateNew(max_rows); List<Field> fields = Arrays.asList( pid.getField(), group.getField(), current_state.getField(), next_state.getField(), dwell_time.getField(), seed.getField() ); List<FieldVector> vectors = Arrays.asList( pid, group, current_state, next_state, dwell_time, seed ); schemaRoot = new VectorSchemaRoot(fields, vectors); } public void setValueCount(int count) { pid.setValueCount(count); group.setValueCount(count); current_state.setValueCount(count); next_state.setValueCount(count); dwell_time.setValueCount(count); seed.setValueCount(count); schemaRoot.setRowCount(count); } public void reset() { pid.reset(); group.reset(); current_state.reset(); next_state.reset(); dwell_time.reset(); seed.reset(); } public void close() { pid.close(); group.close(); current_state.close(); next_state.close(); dwell_time.close(); seed.close(); } public byte[] toBytes() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ArrowFileWriter writer = new ArrowFileWriter(schemaRoot, null, Channels.newChannel(out)); writer.start(); writer.writeBatch(); writer.end(); writer.close(); byte[] outb = out.toByteArray(); out.close(); return outb; } }
923617e93637d92b69664fb76d354255d1c64d70
890
java
Java
ha-metadata/src/main/java/com/g2forge/habitat/metadata/access/computed/mixin/IPredicateModifier.java
gdgib/habitat
a657a000a358360cca06bce6995b240271dde629
[ "Apache-2.0" ]
null
null
null
ha-metadata/src/main/java/com/g2forge/habitat/metadata/access/computed/mixin/IPredicateModifier.java
gdgib/habitat
a657a000a358360cca06bce6995b240271dde629
[ "Apache-2.0" ]
null
null
null
ha-metadata/src/main/java/com/g2forge/habitat/metadata/access/computed/mixin/IPredicateModifier.java
gdgib/habitat
a657a000a358360cca06bce6995b240271dde629
[ "Apache-2.0" ]
1
2019-08-02T03:12:04.000Z
2019-08-02T03:12:04.000Z
44.5
203
0.824719
997,537
package com.g2forge.habitat.metadata.access.computed.mixin; import com.g2forge.alexandria.java.function.IPredicate1; import com.g2forge.alexandria.java.function.builder.IModifier; import com.g2forge.habitat.metadata.type.IMetadataPredicateTypeFactory; import com.g2forge.habitat.metadata.type.predicate.IPredicateType; import com.g2forge.habitat.metadata.value.IMetadataPredicateFactory; public interface IPredicateModifier extends IModifier<MixinMetadataRegistry.MixinMetadataRegistryBuilder>, IMetadataPredicateFactory<IValueModifier<?>>, IMetadataPredicateTypeFactory<IValueModifier<?>> { @Override public <T> IValueModifier<T> bind(Class<T> type); @Override public <T> IValueModifier<T> bind(IPredicateType<T> predicateType); @Override public <T> IValueModifier<T> predicate(Class<T> type); public <T> IValueModifier<T> test(IPredicate1<? super IPredicateType<?>> filter); }
923618b06f5b979f95bb5efad8e02d887f4d1474
3,145
java
Java
poom-caches/poom-caches-management/src/main/java/org/codingmatters/poom/caches/management/CacheManager.java
flexiooss/poom-services
6bc504cbe833db07b9e9a460e1c27e55db3af3aa
[ "Apache-2.0" ]
null
null
null
poom-caches/poom-caches-management/src/main/java/org/codingmatters/poom/caches/management/CacheManager.java
flexiooss/poom-services
6bc504cbe833db07b9e9a460e1c27e55db3af3aa
[ "Apache-2.0" ]
140
2019-06-24T14:26:39.000Z
2022-03-01T16:07:51.000Z
poom-caches/poom-caches-management/src/main/java/org/codingmatters/poom/caches/management/CacheManager.java
nelt/poom-services
9d5f1b865c1a28cd69a604f9f89dad215330f11f
[ "Apache-2.0" ]
1
2020-06-02T15:22:04.000Z
2020-06-02T15:22:04.000Z
40.320513
250
0.702385
997,538
package org.codingmatters.poom.caches.management; import org.codingmatters.poom.caches.Cache; import org.codingmatters.poom.caches.management.caches.CacheWithStore; import org.codingmatters.poom.caches.management.lru.LRUManager; import org.codingmatters.poom.caches.management.stores.CacheStore; import org.codingmatters.poom.caches.management.stores.MapCacheStore; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class CacheManager<K, V> implements Closeable { static public <K, V> CacheManager<K, V> newHashMapBackedCache( Cache.ValueRetriever<K, V> retriever, Cache.ValueInvalidator<K, V> invalidator, int capacity, ScheduledExecutorService scheduler, long delay, TimeUnit delayUnit) { return newMapBackedCache(new HashMap<>(), retriever, invalidator, capacity, scheduler, delay, delayUnit); } static public <K, V> CacheManager<K, V> newMapBackedCache(Map<K, Optional<V>> map, Cache.ValueRetriever<K, V> retriever, Cache.ValueInvalidator<K, V> invalidator, int capacity, ScheduledExecutorService scheduler, long delay, TimeUnit delayUnit) { CacheStore<K, V> cacheStore = new MapCacheStore<>(map); return newCache(cacheStore, retriever, invalidator, capacity, scheduler, delay, delayUnit); } private static <K, V> CacheManager<K, V> newCache(CacheStore<K, V> cacheStore, Cache.ValueRetriever<K, V> retriever, Cache.ValueInvalidator<K, V> invalidator, int capacity, ScheduledExecutorService scheduler, long delay, TimeUnit delayUnit) { return new CacheManager<K, V>( new CacheWithStore<>(retriever, cacheStore, invalidator), capacity, scheduler, delay, delayUnit ); } private final Cache<K, V> cache; private final ScheduledExecutorService scheduler; private final LRUManager<K> lruManager; private final long delay; private final TimeUnit timeUnit; private final ScheduledFuture<?> task; public CacheManager(Cache<K, V> cache, int capacity, ScheduledExecutorService scheduler, long delay, TimeUnit timeUnit) { this.cache = cache; this.scheduler = scheduler; this.lruManager = new LRUManager<>(capacity); this.delay = delay; this.timeUnit = timeUnit; this.cache.addAccessListener(key -> this.lruManager.accessed(key)); this.task = this.scheduler.scheduleWithFixedDelay(this::cleanup, this.delay, this.delay, this.timeUnit); } public Cache<K, V> cache() { return cache; } private void cleanup() { List<K> overload = this.lruManager.overload(); for (K key : overload) { this.cache.prune(key); } for (K key : overload) { this.lruManager.removed(key); } } @Override public void close() throws IOException { this.task.cancel(false); } }
9236192dd6fe90c6a77ef4e17ec5aff6d8622d32
4,822
java
Java
saasy-api/src/main/java/org/geoint/saasy/ID.java
GEOINT/saasy
3519e0d5814cde698bbc2c94317dcb59fddd55ac
[ "Apache-2.0" ]
1
2020-07-16T13:07:07.000Z
2020-07-16T13:07:07.000Z
saasy-api/src/main/java/org/geoint/saasy/ID.java
GEOINT/saasy
3519e0d5814cde698bbc2c94317dcb59fddd55ac
[ "Apache-2.0" ]
null
null
null
saasy-api/src/main/java/org/geoint/saasy/ID.java
GEOINT/saasy
3519e0d5814cde698bbc2c94317dcb59fddd55ac
[ "Apache-2.0" ]
2
2018-08-24T08:12:54.000Z
2020-07-16T13:07:10.000Z
37.092308
82
0.66404
997,539
/* * Copyright 2016 geoint.org. * * 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.geoint.saasy; import java.util.Iterator; import java.util.Map; import java.util.ServiceLoader; import java.util.function.Predicate; import java.util.logging.Logger; /** * Bootstrap class for {@link IdentityManager}. * <p> * This class uses a {@link ServiceLoader} to discover and construct instances * of {@link IdentityMangager} found on the classpath of the calling thread. * Constructed instances of IdentityManager are not immediately initialized (see * method descriptions on how initialization takes place). * * @author steve_siebert */ public class ID { private static final Logger LOGGER = Logger.getLogger(ID.class.getName()); /* * Optionally set JVM-default identity manager. * * If loadAndSetDefaultManager() wasn't previously called this variable * will be null. */ private static IdentityManager defaultSecurityManager; /** * Returns an initialized IdentityManager instance which is accepted by the * provided filter. * * @param filter manager implementation filter * @param config manager config * @return initialized identity manager instance * @throws IdentityException if the identity manager fails to initialize * @throws NoIdentityManagerFoundException if acceptable identity manager is * found */ public static IdentityManager loadIdentityManager( Predicate<IdentityManager> filter, Map<String, String> config) throws IdentityException { ServiceLoader<IdentityManager> loader = ServiceLoader.load(IdentityManager.class); Iterator<IdentityManager> iterator = loader.iterator(); if (!iterator.hasNext()) { LOGGER.severe("No identity manager implementation was found by " + "ServiceLoader."); } while (iterator.hasNext()) { IdentityManager idm = iterator.next(); if (filter.test(idm)) { LOGGER.info(() -> String.format("IdentityMaanger implementation " + "'%s' was accepted as the identity manager.", idm.getClass().getName())); idm.initialize(config); LOGGER.fine(() -> String.format("IdentityManager '%s' was " + "successfully initialized.", idm.getClass().getName())); return idm; } LOGGER.fine(() -> String.format("IdentityManager implementation '%s' " + "was not accepted as the identity manager.", idm.getClass().getName())); } throw new NoIdentityManagerFoundException(); } /** * Loads a new IdentityMangaer instance and sets it as the JVM-default * identity manager. * * @param filter manager implementation filter * @param config manager config * @return initialized identity manager instance * @throws IdentityException if the identity manager fails to initialize * @throws NoIdentityManagerFoundException if acceptable identity manager is * found */ public static synchronized IdentityManager loadAndSetDefaultManager( Predicate<IdentityManager> filter, Map<String, String> config) throws IdentityException { defaultSecurityManager = loadIdentityManager(filter, config); return defaultSecurityManager; } /** * Returns the JVM-default identity manager, if previously set, otherwise * throws NoIdentityManagerFoundException. * * @return JVM-default security manager, if set * @throws NoIdentityManagerFoundException if a JVM-default identity manager * was not set by previously calling * {@link ID#loadAndSetDefaultManager(Predicate, Map) } */ public static synchronized IdentityManager getDefaultManager() throws NoIdentityManagerFoundException { if (defaultSecurityManager == null) { throw new NoIdentityManagerFoundException("Default identitiy " + "manager could not be retrieved, identity manager has " + "not yet been set."); } return defaultSecurityManager; } }
923619bad6eb5f70bb7c767d9d9dc14356106476
114
java
Java
JAVA/spring-workspace/Lecture-Spring/src/main/java/di/anno02/KumhoTire.java
Bonseong/KOPO_TIL
28da91fc052632f5a504e07f7cebfd1bfcc8cbc1
[ "MIT" ]
null
null
null
JAVA/spring-workspace/Lecture-Spring/src/main/java/di/anno02/KumhoTire.java
Bonseong/KOPO_TIL
28da91fc052632f5a504e07f7cebfd1bfcc8cbc1
[ "MIT" ]
null
null
null
JAVA/spring-workspace/Lecture-Spring/src/main/java/di/anno02/KumhoTire.java
Bonseong/KOPO_TIL
28da91fc052632f5a504e07f7cebfd1bfcc8cbc1
[ "MIT" ]
null
null
null
11.4
39
0.701754
997,540
package di.anno02; public class KumhoTire implements Tire{ public String getBrand() { return "금호타이어"; } }
923619bd1464de5979ca71e3656ea9a3e20c067d
1,045
java
Java
cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/setup/CheckImageRequest.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
174
2017-07-14T03:20:42.000Z
2022-03-25T05:03:18.000Z
cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/setup/CheckImageRequest.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
2,242
2017-07-12T05:52:01.000Z
2022-03-31T15:50:08.000Z
cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/setup/CheckImageRequest.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
172
2017-07-12T08:53:48.000Z
2022-03-24T12:16:33.000Z
28.243243
121
0.691866
997,541
package com.sequenceiq.cloudbreak.cloud.event.setup; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformRequest; import com.sequenceiq.cloudbreak.cloud.model.CloudCredential; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.cloudbreak.cloud.model.Image; public class CheckImageRequest<T> extends CloudPlatformRequest<CheckImageResult> { private final Image image; private final CloudStack stack; public CheckImageRequest(CloudContext cloudContext, CloudCredential cloudCredential, CloudStack stack, Image image) { super(cloudContext, cloudCredential); this.image = image; this.stack = stack; } public Image getImage() { return image; } public CloudStack getStack() { return stack; } @Override public String toString() { return "CheckImageRequest{" + "image=" + image + ", stack=" + stack + '}'; } }
923619bd511d6b65b8d16b6f4f0a3e0d1b648145
2,294
java
Java
brut.apktool.smali/dexlib2/src/main/java/org/jf/dexlib2/base/value/BaseNullEncodedValue.java
kuter007/android-apktool
35f9786facda2d6f148d303c00c14b929c35049c
[ "Apache-2.0" ]
1,034
2015-03-07T15:41:21.000Z
2022-03-19T01:29:55.000Z
src/org/jf/dexlib2/base/value/BaseNullEncodedValue.java
yoyfook/ZjDroid
6f680d6d97e94c2c86f641d9015f8befb3a7ce68
[ "Apache-2.0" ]
6
2018-05-08T09:54:05.000Z
2019-05-23T08:24:31.000Z
src/org/jf/dexlib2/base/value/BaseNullEncodedValue.java
yoyfook/ZjDroid
6f680d6d97e94c2c86f641d9015f8befb3a7ce68
[ "Apache-2.0" ]
552
2015-03-10T12:24:34.000Z
2022-02-11T06:17:39.000Z
38.233333
73
0.752833
997,542
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.base.value; import com.google.common.primitives.Ints; import org.jf.dexlib2.ValueType; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.iface.value.NullEncodedValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class BaseNullEncodedValue implements NullEncodedValue { @Override public int hashCode() { return 0; } @Override public boolean equals(@Nullable Object o) { return o instanceof NullEncodedValue; } @Override public int compareTo(@Nonnull EncodedValue o) { return Ints.compare(getValueType(), o.getValueType()); } public int getValueType() { return ValueType.NULL; } }
923619fa6a514177085d76b53f8b6a0127f7bf68
3,062
java
Java
src/main/java/com/filelug/desktop/service/websocket/DeleteComputerWebSocketService.java
filelug/filelug-desktop
0078fae9fefb044b53dc42aecbdabe118708500a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/filelug/desktop/service/websocket/DeleteComputerWebSocketService.java
filelug/filelug-desktop
0078fae9fefb044b53dc42aecbdabe118708500a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/filelug/desktop/service/websocket/DeleteComputerWebSocketService.java
filelug/filelug-desktop
0078fae9fefb044b53dc42aecbdabe118708500a
[ "Apache-2.0" ]
null
null
null
41.378378
156
0.690398
997,543
package com.filelug.desktop.service.websocket; import ch.qos.logback.classic.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import com.filelug.desktop.PropertyConstants; import com.filelug.desktop.Utility; import com.filelug.desktop.model.RequestDeleteComputerModel; import com.filelug.desktop.model.User; import com.filelug.desktop.service.ResetApplicationNotificationService; import org.slf4j.LoggerFactory; import javax.websocket.Session; /** * <code>DeleteComputerWebSocketService</code> receives and process the web socket message from server with service id: DELETE_COMPUTER_V2 * * @author masonhsieh * @version 1.0 */ public class DeleteComputerWebSocketService { private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(DeleteComputerWebSocketService.class.getSimpleName()); private final Session session; private final String message; private final ConnectSocket connectSocket; public DeleteComputerWebSocketService(final Session session, final String message, final ConnectSocket connectSocket) { this.session = session; this.message = message; this.connectSocket = connectSocket; } public void deleteComputer() { ObjectMapper mapper = Utility.createObjectMapper(); try { RequestDeleteComputerModel requestModel = mapper.readValue(message, RequestDeleteComputerModel.class); String operatorId = requestModel.getOperatorId(); String clientLocale = requestModel.getLocale(); String verification = requestModel.getVerification(); User user = connectSocket.getUserService().findAdministrator(); Long computerId = Utility.getPreferenceLong(PropertyConstants.PROPERTY_NAME_COMPUTER_ID, -1); String computerGroup = Utility.getPreference(PropertyConstants.PROPERTY_NAME_COMPUTER_GROUP, ""); if (verification == null || verification.trim().length() < 1 || user == null || user.getAdmin() == null || computerId < 0 || computerGroup.trim().length() < 1) { String errorMessage = Utility.localizedString("failed.delete.computer.data.not.integrity"); LOGGER.error(errorMessage); } else { String adminId = user.getAccount(); String expectedVerification = Utility.generateVerificationToDeleteComputer(adminId, computerId); if (!verification.equals(expectedVerification)) { LOGGER.warn("Be careful that user: '" + operatorId + "' is trying to hack the verification code to delete this computer!"); } else { ResetApplicationNotificationService.getInstance().applicationShouldReset(ResetApplicationNotificationService.REASON.COMPUTER_NOT_FOUND); // connectSocket.getUserService().resetAndExitQuietly(); } } } catch (Exception e) { LOGGER.error("Error on deleting computer.", e); } } }
92361a4195184ff5a835a8d5ef4d68837e3421e4
253
java
Java
android/common/src/main/java/com/stardust/pio/PReadableBinaryFile.java
snailuncle/autojs-web-control
ec4586109c6b5da01183eb3f63913904e72b99c7
[ "MIT" ]
null
null
null
android/common/src/main/java/com/stardust/pio/PReadableBinaryFile.java
snailuncle/autojs-web-control
ec4586109c6b5da01183eb3f63913904e72b99c7
[ "MIT" ]
2
2021-03-02T01:47:51.000Z
2021-07-20T07:46:49.000Z
android/common/src/main/java/com/stardust/pio/PReadableBinaryFile.java
FFHixio/autojs-web-control
ec4586109c6b5da01183eb3f63913904e72b99c7
[ "MIT" ]
2
2020-10-04T18:15:49.000Z
2020-12-01T17:51:29.000Z
14.055556
55
0.70751
997,544
package com.stardust.pio; import java.io.Closeable; import java.io.IOException; /** * Created by Stardust on 2017/4/6. */ public class PReadableBinaryFile implements Closeable { @Override public void close() throws IOException { } }
92361a96606f0d9fc5adddd7a130d0438509f67c
765
java
Java
algorithm/src/com/caleb/algorithm/review/ReverseKGroup25.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
algorithm/src/com/caleb/algorithm/review/ReverseKGroup25.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
algorithm/src/com/caleb/algorithm/review/ReverseKGroup25.java
CalebLogin/JavaDemo
95f4ef8d041e02f6f59bdcf00c2c356127b1c95a
[ "Apache-2.0" ]
null
null
null
17.790698
54
0.636601
997,545
package com.caleb.algorithm.review; import com.caleb.algorithm.offerdemo.ListNode; /** * @author:Caleb * @Date :2021-08-14 23:36:14 */ public class ReverseKGroup25 { public ListNode reverseKGroup(ListNode head, int k) { int i = 0; ListNode node = head; while (i < k && node != null) { node = node.next; i++; } if (i != k) { return head; } ListNode after = node.next; node.next = null; ListNode reNode = reverseGroup(head); head.next = reverseKGroup(after, k); return reNode; } public ListNode reverseGroup(ListNode node) { if (node == null) { return null; } if (node.next == null) { return node; } ListNode after = reverseGroup(node.next); node.next.next = node; node.next = null; return after; } }
92361ad7d012c651a5ed03474c489ea4549346ac
5,412
java
Java
perftests/visualisation-jfc/src/main/java/org/apache/qpid/disttest/charting/writer/ChartWriter.java
tqrg-bot/qpid-broker-j
66eabc0d836c40e4e34d999149175652aa0d799d
[ "Apache-2.0" ]
52
2017-12-15T08:49:31.000Z
2022-03-10T19:10:11.000Z
perftests/visualisation-jfc/src/main/java/org/apache/qpid/disttest/charting/writer/ChartWriter.java
tqrg-bot/qpid-broker-j
66eabc0d836c40e4e34d999149175652aa0d799d
[ "Apache-2.0" ]
42
2017-10-18T12:36:17.000Z
2022-02-05T13:55:18.000Z
perftests/visualisation-jfc/src/main/java/org/apache/qpid/disttest/charting/writer/ChartWriter.java
tqrg-bot/qpid-broker-j
66eabc0d836c40e4e34d999149175652aa0d799d
[ "Apache-2.0" ]
46
2017-09-12T10:26:06.000Z
2022-03-21T07:52:46.000Z
37.846154
141
0.601256
997,546
/* * 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.qpid.disttest.charting.writer; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.util.SortedMap; import java.util.TreeMap; import org.apache.qpid.disttest.charting.ChartingException; import org.apache.qpid.disttest.charting.definition.ChartingDefinition; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChartWriter { private static final Logger LOGGER = LoggerFactory.getLogger(ChartWriter.class); static final String SUMMARY_FILE_NAME = "chart-summary.html"; private File _chartDirectory = new File("."); private SortedMap<File,ChartingDefinition> _chartFilesToChartDef = new TreeMap<File, ChartingDefinition>(); public void writeChartToFileSystem(JFreeChart chart, ChartingDefinition chartDef) { OutputStream pngOutputStream = null; try { File pngFile = new File(_chartDirectory, chartDef.getChartStemName() + ".png"); pngOutputStream = new BufferedOutputStream(new FileOutputStream(pngFile)); ChartUtilities.writeChartAsPNG(pngOutputStream, chart, 600, 400, true, 0); pngOutputStream.close(); _chartFilesToChartDef.put(pngFile, chartDef); LOGGER.info("Written {} chart", pngFile); } catch (IOException e) { throw new ChartingException("Failed to create chart", e); } finally { if (pngOutputStream != null) { try { pngOutputStream.close(); } catch (IOException e) { throw new ChartingException("Failed to create chart", e); } } } } public void writeHtmlSummaryToFileSystem(String summaryPageTitle) { if(_chartFilesToChartDef.size() < 2) { LOGGER.info("Only {} chart image(s) have been written so no HTML summary file will be produced", _chartFilesToChartDef.size()); return; } String htmlHeader = String.format( "<html>%n" + " <head>%n" + " <title>%s</title>%n" + " <style type='text/css'>figure { float: left; display: table; width: 87px;}</style>%n" + " </head>%n" + " <body>%n" + " <h1>%s</h1>%n", summaryPageTitle, summaryPageTitle); String htmlFooter = String.format(" </body>%n" + "</html>"); File summaryFile = new File(_chartDirectory, SUMMARY_FILE_NAME); LOGGER.debug("About to produce HTML summary file " + summaryFile.getAbsolutePath() + " from charts " + _chartFilesToChartDef); try(BufferedWriter writer = new BufferedWriter(new FileWriter(summaryFile))) { writer.write(htmlHeader); writer.write(String.format(" <ul>%n")); for (File chartFile : _chartFilesToChartDef.keySet()) { writer.write(String.format(" <li><a href='#" + chartFile.getName() + "'>" + chartFile.getName() + "</a></li>%n")); } writer.write(String.format(" </ul>%n")); for (File chartFile : _chartFilesToChartDef.keySet()) { ChartingDefinition def = _chartFilesToChartDef.get(chartFile); writer.write(String.format(" <figure>%n")); writer.write(String.format(" <a name='" + chartFile.getName() + "'/>%n")); writer.write(String.format(" <img src='" + chartFile.getName() + "'/>%n")); if (def.getChartDescription() != null) { writer.write(String.format(" <figcaption>%s</figcaption>%n", def.getChartDescription())); } writer.write(String.format(" </figure>%n")); } writer.write(htmlFooter); writer.close(); } catch (Exception e) { throw new ChartingException("Failed to create HTML summary file", e); } } public void setOutputDirectory(final File chartDirectory) { _chartDirectory = chartDirectory; LOGGER.info("Set chart directory: {}", chartDirectory); } }
92361c2dfe1cba55543ca4aa78b614b980ef382d
616
java
Java
spring-boot-jar/src/main/java/com/wjz/controller/NegotiationController.java
BINGJJFLY/bingjjfly-springboot
7564abb411c8f4695f4ce264cef9b8f871da4b8b
[ "Apache-2.0" ]
null
null
null
spring-boot-jar/src/main/java/com/wjz/controller/NegotiationController.java
BINGJJFLY/bingjjfly-springboot
7564abb411c8f4695f4ce264cef9b8f871da4b8b
[ "Apache-2.0" ]
null
null
null
spring-boot-jar/src/main/java/com/wjz/controller/NegotiationController.java
BINGJJFLY/bingjjfly-springboot
7564abb411c8f4695f4ce264cef9b8f871da4b8b
[ "Apache-2.0" ]
null
null
null
23.692308
62
0.706169
997,547
package com.wjz.controller; import com.wjz.domain.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController public class NegotiationController { @RequestMapping("/negotiation") public User negotiation() { User user = new User(); user.setName("bingjjfly"); user.setBirth(new Date()); return user; } @RequestMapping("/negotiation/index") public String index() { return "thymeleaf"; } }
92361c6230e6fd710bd83f4209e11d13ca1305e6
8,147
java
Java
src/main/java/org/wymiwyg/commons/util/text/W3CDateFormat.java
retog/wymiwyg-commons-core
5b5ba4fef4e810b8cea0ac08ce105fa402eaee3c
[ "Apache-2.0" ]
null
null
null
src/main/java/org/wymiwyg/commons/util/text/W3CDateFormat.java
retog/wymiwyg-commons-core
5b5ba4fef4e810b8cea0ac08ce105fa402eaee3c
[ "Apache-2.0" ]
2
2015-03-16T02:23:09.000Z
2019-12-22T16:23:03.000Z
src/main/java/org/wymiwyg/commons/util/text/W3CDateFormat.java
retog/wymiwyg-commons-core
5b5ba4fef4e810b8cea0ac08ce105fa402eaee3c
[ "Apache-2.0" ]
null
null
null
33.813278
81
0.656768
997,548
/* * Created on Apr 26, 2004 * * * ==================================================================== * * The WYMIWYG Software License, Version 1.0 * * Copyright (c) 2002-2003 WYMIWYG All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowlegement: "This product includes software * developed by WYMIWYG." Alternately, this acknowlegement may appear in the * software itself, if and wherever such third-party acknowlegements normally * appear. * * 4. The name "WYMIWYG" or "WYMIWYG.org" must not be used to endorse or promote * products derived from this software without prior written permission. For * written permission, please contact ychag@example.com. * * 5. Products derived from this software may not be called "WYMIWYG" nor may * "WYMIWYG" appear in their names without prior written permission of WYMIWYG. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WYMIWYG OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many individuals on * behalf of WYMIWYG. For more information on WYMIWYG, please see * http://www.WYMIWYG.org/. * * This licensed is based on The Apache Software License, Version 1.1, see * http://www.apache.org/. */ package org.wymiwyg.commons.util.text; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; //TODO support all formats /** implements http://www.w3.org/TR/NOTE-datetime * * Year: YYYY (eg 1997) Year and month: YYYY-MM (eg 1997-07) Complete date: YYYY-MM-DD (eg 1997-07-16) Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) * @author reto */ public class W3CDateFormat extends DateFormat { private static final TimeZone utcTZ = new SimpleTimeZone(0, "UTC"); private static final long serialVersionUID = 3258407344076372025L; /** * @see java.text.DateFormat#format(java.util.Date, java.lang.StringBuffer, * java.text.FieldPosition) */ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ"); String string = dateFormat.format(date); StringBuffer result = new StringBuffer(string); result.insert(string.length() - 2, ':'); return result; } /** * @see java.text.DateFormat#parse(java.lang.String, * java.text.ParsePosition) */ public Date parse(String dateString, ParsePosition parsePos) { int position = parsePos.getIndex(); int y1 = dateString.charAt(position++) - '0'; int y2 = dateString.charAt(position++) - '0'; int y3 = dateString.charAt(position++) - '0'; int y4 = dateString.charAt(position++) - '0'; int year = 1000 * y1 + 100 * y2 + 10 * y3 + y4; position++; // skip '-' int m1 = dateString.charAt(position++) - '0'; int m2 = dateString.charAt(position++) - '0'; int month = 10 * m1 + m2; position++; // skip '-' int d1 = dateString.charAt(position++) - '0'; int d2 = dateString.charAt(position++) - '0'; int day = 10 * d1 + d2; position++; // skip 'T' int hour; int minutes; int secs; Calendar resultCalendar; if (dateString.length() > position) { int h1 = dateString.charAt(position++) - '0'; int h2 = dateString.charAt(position++) - '0'; hour = 10 * h1 + h2; position++; // skip ':' int min1 = dateString.charAt(position++) - '0'; int min2 = dateString.charAt(position++) - '0'; minutes = 10 * min1 + min2; position++; // skip ':' int s1 = dateString.charAt(position++) - '0'; int s2 = dateString.charAt(position++) - '0'; secs = 10 * s1 + s2; // if there is time there is an explicit time-zone which will deduct or a Z resultCalendar = new GregorianCalendar(year, month - 1, day, hour, minutes, secs); resultCalendar.setTimeZone(utcTZ); } else { resultCalendar = new GregorianCalendar(year, month - 1, day); } long timeInMillis = resultCalendar.getTimeInMillis(); if (dateString.length() > position) { if (dateString.charAt(position) == '.') { position++; // skip '.' int ms1 = dateString.charAt(position++) - '0'; char msc2 = dateString.charAt(position); int ms2; int ms3; if ((msc2 != 'Z') && (msc2 != '-') && (msc2 != '+')) { position++; ms2 = msc2 - '0'; char msc3 = dateString.charAt(position); if ((msc3 != 'Z') && (msc3 != '-') && (msc3 != '+')) { position++; ms3 = msc3 - '0'; } else { ms3 = 0; } } else { ms2 = 0; ms3 = 0; } int msecs = 100 * ms1 + 10 * ms2 + ms3; timeInMillis += msecs; } char tzd1 = dateString.charAt(position++); if (tzd1 != 'Z') { int htz1 = dateString.charAt(position++) - '0'; int htz2 = dateString.charAt(position++) - '0'; int hourtz = 10 * htz1 + htz2; position++; // skip ':' int mintz1 = dateString.charAt(position++) - '0'; int mintz2 = dateString.charAt(position++) - '0'; int minutestz = 10 * mintz1 + mintz2; int offSetInMillis = (hourtz * 60 + minutestz) * 60000; if (tzd1 == '+') { timeInMillis -= offSetInMillis; } else { timeInMillis += offSetInMillis; } } } parsePos.setIndex(position); return new Date(timeInMillis); } public Date parseOld(String dateString, ParsePosition pos) { if (dateString.charAt(dateString.length() - 3) == ':') { StringBuffer buffer = new StringBuffer(dateString); buffer.deleteCharAt(buffer.length() - 3); dateString = buffer.toString(); } if (Character.toUpperCase(dateString.charAt(dateString.length() - 1)) == 'Z') { StringBuffer buffer = new StringBuffer(dateString); buffer.deleteCharAt(buffer.length() - 1); buffer.append("+0000"); dateString = buffer.toString(); } Date result = null; try { result = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ") .parse(dateString, pos); } catch (Exception ex) { } if (result == null) { try { result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse( dateString, pos); } catch (Exception ex1) { } } if (result == null) { try { result = new SimpleDateFormat("yyyy-MM-dd").parse(dateString, pos); } catch (Exception ex2) { System.err .println(" hat a DC:date that could not be parsed, using current"); return new Date(); } } return result; } }
92361c7cfc752a4f74ef1e9382904e264255f609
1,945
java
Java
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
rnzhiw/DistributedMall
115f11a05778f58bc7254ed0fa64ed46d168962c
[ "Apache-2.0" ]
4
2021-11-11T13:05:07.000Z
2021-11-13T11:42:01.000Z
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
rnzhiw/DistributedMall
115f11a05778f58bc7254ed0fa64ed46d168962c
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/atguigu/gulimall/order/controller/RefundInfoController.java
rnzhiw/DistributedMall
115f11a05778f58bc7254ed0fa64ed46d168962c
[ "Apache-2.0" ]
null
null
null
22.835294
62
0.689851
997,549
package com.atguigu.gulimall.order.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.order.entity.RefundInfoEntity; import com.atguigu.gulimall.order.service.RefundInfoService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * 退款信息 * * @author rnzhiw * @email efpyi@example.com * @date 2021-09-12 13:22:08 */ @RestController @RequestMapping("order/refundinfo") public class RefundInfoController { @Autowired private RefundInfoService refundInfoService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = refundInfoService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ RefundInfoEntity refundInfo = refundInfoService.getById(id); return R.ok().put("refundInfo", refundInfo); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody RefundInfoEntity refundInfo){ refundInfoService.save(refundInfo); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody RefundInfoEntity refundInfo){ refundInfoService.updateById(refundInfo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ refundInfoService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
92361c833e1fd814d5522de4b35776fc4ff39278
1,022
java
Java
Ia/Coup.java
Nsmsb/Diaballik-AI-minimax
8e9ab197051fbb3c06931ac4bd1629f78df637a0
[ "MIT" ]
1
2020-06-25T15:42:52.000Z
2020-06-25T15:42:52.000Z
Ia/Coup.java
Nsmsb/Diaballik-AI-minimax
8e9ab197051fbb3c06931ac4bd1629f78df637a0
[ "MIT" ]
null
null
null
Ia/Coup.java
Nsmsb/Diaballik-AI-minimax
8e9ab197051fbb3c06931ac4bd1629f78df637a0
[ "MIT" ]
null
null
null
23.227273
97
0.593933
997,550
package Ia; import java.util.ArrayList; import java.util.List; public class Coup { List<Action> actions; /** * Coup est une list d'Actions (decplacements ou passes) */ public Coup() { this.actions = new ArrayList<Action>(); } /** * Constricteur prendre une Lists d'Actions * @param actions List d'actions, chaque action contien pos et posNouveau du support/bille */ public Coup(List<Action> actions) { this.actions = actions; } /** * Ajouter une action à la list des actions du Coup * @param action */ public void ajouterAction(Action action) { this.actions.add(action); } /** * Copier le Coup * @return un Objet Coup, avec une nouvelle list qui contient les méme réferences des Actions */ public Coup copier() { List<Action> copy = new ArrayList<Action>(); for (Action action : actions) { copy.add(action); } return new Coup(copy); } }
92361d89d4361fc75cdfc51bdc0102e6e70c19ae
2,809
java
Java
app/src/main/java/com/experiments/whereapp/data/service/RestClient.java
krupalshah/PinPlace
0b89287af3aaf751f20ec89a1876cf7c4a238dce
[ "Apache-2.0" ]
1
2016-08-28T09:06:46.000Z
2016-08-28T09:06:46.000Z
app/src/main/java/com/experiments/whereapp/data/service/RestClient.java
krupalshah/Where
0b89287af3aaf751f20ec89a1876cf7c4a238dce
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/experiments/whereapp/data/service/RestClient.java
krupalshah/Where
0b89287af3aaf751f20ec89a1876cf7c4a238dce
[ "Apache-2.0" ]
null
null
null
37.453333
93
0.687077
997,551
/* * * Copyright (c) 2016 Krupal Shah, Harsh Bhavsar * 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.experiments.whereapp.data.service; import com.experiments.whereapp.config.AppConfig; import com.experiments.whereapp.config.ServerConfig; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; /** * Author : Krupal Shah * Date : 17-Apr-16 * <p> * configures OkHttp client and provides {@link WebServices} */ public class RestClient { private static WebServices webServices; /** * builds api client and provides reference to {@link WebServices} * * @return reference to {@link WebServices} created with retrofit */ public static WebServices getWebServices() { if (webServices == null) { //don't build it every time //configuring OkHttp client with timeouts defined OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder() .connectTimeout(ServerConfig.TimeOuts.CONNECT, TimeUnit.SECONDS) .readTimeout(ServerConfig.TimeOuts.READ, TimeUnit.SECONDS) .writeTimeout(ServerConfig.TimeOuts.WRITE, TimeUnit.SECONDS); //enabling logging interceptor for debug builds if (AppConfig.DEBUG) { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClientBuilder.addInterceptor(httpLoggingInterceptor); } //configuring retrofit with jackson converter and rxjava call adapter Retrofit retrofit = new Retrofit.Builder() .baseUrl(ServerConfig.baseUrl()) .client(okHttpClientBuilder.build()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build(); webServices = retrofit.create(WebServices.class); } return webServices; } }
92361ddea96e2b5cc217cd03b4228c08e691e19e
2,084
java
Java
Behavioral Patterns/Observer/Source/src/main/java/com/code2bits/designpatterns/behavioral/observer/option1/GhostMovementSignals.java
apfmiranda/Design-Patterns-Java
6a057a0a5ad3ca4196901f3cd6e5f9524bf1ce60
[ "MIT" ]
null
null
null
Behavioral Patterns/Observer/Source/src/main/java/com/code2bits/designpatterns/behavioral/observer/option1/GhostMovementSignals.java
apfmiranda/Design-Patterns-Java
6a057a0a5ad3ca4196901f3cd6e5f9524bf1ce60
[ "MIT" ]
null
null
null
Behavioral Patterns/Observer/Source/src/main/java/com/code2bits/designpatterns/behavioral/observer/option1/GhostMovementSignals.java
apfmiranda/Design-Patterns-Java
6a057a0a5ad3ca4196901f3cd6e5f9524bf1ce60
[ "MIT" ]
1
2020-11-17T20:15:32.000Z
2020-11-17T20:15:32.000Z
27.064935
81
0.745202
997,552
/** * MIT License * * Copyright (c) 2017 André Maré * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.code2bits.designpatterns.behavioral.observer.option1; import java.util.ArrayList; import java.util.List; /** * The GhostMovementSignals class * * @author André Maré */ public class GhostMovementSignals implements Subject { private List<Observer> observerList; private GhostMode ghostMode; public GhostMovementSignals() { observerList = new ArrayList<Observer>(); } public void registerObserver(Observer observer) { observerList.add(observer); } public void removeObserver(Observer observer) { int observerIndex = observerList.indexOf(observer); if (observerIndex >= 0) { observerList.remove(observer); } } public void notifyObserver() { for (Observer observer : observerList) { observer.update(ghostMode); } } public GhostMode getGhostMode() { return ghostMode; } public void setGhostMode(GhostMode ghostMode) { this.ghostMode = ghostMode; this.notifyObserver(); } }
92361eb5409cad9bfbbfc2b57698d5a43b4b3fe4
39,833
java
Java
uimaj-as-core/src/main/java/org/apache/uima/aae/handler/input/ProcessResponseHandler.java
abrami/uima-async-scaleout
163e92a2573907ce508071d416d7abe56980062d
[ "Apache-2.0" ]
10
2015-11-29T03:32:06.000Z
2020-01-21T21:38:38.000Z
uimaj-as-core/src/main/java/org/apache/uima/aae/handler/input/ProcessResponseHandler.java
abrami/uima-async-scaleout
163e92a2573907ce508071d416d7abe56980062d
[ "Apache-2.0" ]
2
2020-04-08T18:25:17.000Z
2020-04-08T18:25:18.000Z
uimaj-as-core/src/main/java/org/apache/uima/aae/handler/input/ProcessResponseHandler.java
isabella232/uima-as_old
c6faa8b6fd8b4dd914e0fa6ded4ce330462f7236
[ "Apache-2.0" ]
10
2015-12-09T21:38:31.000Z
2020-01-21T21:38:40.000Z
49.176543
181
0.686366
997,553
/* * 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.uima.aae.handler.input; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import org.apache.uima.UIMAFramework; import org.apache.uima.UIMARuntimeException; import org.apache.uima.aae.InProcessCache.CacheEntry; import org.apache.uima.aae.SerializerCache; import org.apache.uima.aae.UIMAEE_Constants; import org.apache.uima.aae.UimaSerializer; import org.apache.uima.aae.controller.AggregateAnalysisEngineController; import org.apache.uima.aae.controller.AnalysisEngineController; import org.apache.uima.aae.controller.BaseAnalysisEngineController; import org.apache.uima.aae.controller.Endpoint; import org.apache.uima.aae.controller.LocalCache.CasStateEntry; import org.apache.uima.aae.delegate.Delegate; import org.apache.uima.aae.error.AsynchAEException; import org.apache.uima.aae.error.ErrorContext; import org.apache.uima.aae.error.ExpiredMessageException; import org.apache.uima.aae.error.ServiceShutdownException; import org.apache.uima.aae.error.UimaAsDelegateException; import org.apache.uima.aae.error.UimaEEServiceException; import org.apache.uima.aae.handler.HandlerBase; import org.apache.uima.aae.jmx.ServicePerformance; import org.apache.uima.aae.message.AsynchAEMessage; import org.apache.uima.aae.message.MessageContext; import org.apache.uima.aae.monitor.Monitor; import org.apache.uima.aae.monitor.statistics.AnalysisEnginePerformanceMetrics; import org.apache.uima.aae.monitor.statistics.LongNumericStatistic; import org.apache.uima.cas.CAS; import org.apache.uima.cas.SerialFormat; import org.apache.uima.cas.impl.AllowPreexistingFS; import org.apache.uima.cas.impl.BinaryCasSerDes6; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.MarkerImpl; import org.apache.uima.cas.impl.Serialization; import org.apache.uima.cas.impl.TypeSystemImpl; import org.apache.uima.cas.impl.XmiSerializationSharedData; import org.apache.uima.cas.impl.BinaryCasSerDes6.ReuseInfo; import org.apache.uima.util.Level; public class ProcessResponseHandler extends HandlerBase { private static final Class CLASS_NAME = ProcessResponseHandler.class; public ProcessResponseHandler(String aName) { super(aName); } private Endpoint lookupEndpoint(String anEndpointName, String aCasReferenceId) { return getController().getInProcessCache().getEndpoint(anEndpointName, aCasReferenceId); } private void cancelTimer(MessageContext aMessageContext, String aCasReferenceId, boolean removeEndpoint) throws AsynchAEException { if (aMessageContext != null && aMessageContext.getEndpoint() != null) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, CLASS_NAME.getName(), "cancelTimer", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cancel_timer__FINE", new Object[] { aMessageContext.getEndpoint().getEndpoint(), aCasReferenceId }); } // Retrieve the endpoint from the cache using endpoint name // and casRefereceId if (aCasReferenceId == null && aMessageContext.propertyExists(AsynchAEMessage.Command) && aMessageContext.getMessageIntProperty(AsynchAEMessage.Command) == AsynchAEMessage.CollectionProcessComplete) { aCasReferenceId = ":CpC"; } if (aMessageContext != null && aMessageContext.getEndpoint() != null) { Endpoint endpoint = lookupEndpoint(aMessageContext.getEndpoint().getEndpoint(), aCasReferenceId); if (endpoint != null) { // Received the response within timeout interval so // cancel the running timer endpoint.cancelTimer(); if (removeEndpoint) { getController().getInProcessCache().removeEndpoint( aMessageContext.getEndpoint().getEndpoint(), aCasReferenceId); } } else { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "cancelTimer", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_endpoint_not_found__INFO", new Object[] { aMessageContext.getEndpoint().getEndpoint(), aCasReferenceId }); } } } } } private void cancelTimerAndProcess(MessageContext aMessageContext, String aCasReferenceId, CAS aCAS) throws AsynchAEException { computeStats(aMessageContext, aCasReferenceId); super.invokeProcess(aCAS, aCasReferenceId, null, aMessageContext, null); } private boolean isMessageExpected(String aCasReferenceId, Endpoint anEndpointWithTimer) { if (getController().getInProcessCache().entryExists(aCasReferenceId) && anEndpointWithTimer.isWaitingForResponse()) { return true; } return false; } private void handleUnexpectedMessage(String aCasReferenceId, Endpoint anEndpoint) { // Cas does not exist in the CAS Cache. This would be possible if the // CAS has been dropped due to timeout and the delegate // sends the response later. In asynch communication this scenario is // possible. The service may not be up when the client sends // the message. Messages accumulate in the service queue until the // service becomes available. When this happens, the service // will pickup messages from the queue, process them and send respones // to an appropriate response queue. Most likely such // respones should be thrown away. Well perhaps logged first. ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.CasReference, aCasReferenceId); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.Endpoint, anEndpoint); AnalysisEngineController controller = getController(); controller.getErrorHandlerChain().handle(new ExpiredMessageException(), errorContext, controller); } private void handleProcessResponseFromRemote(MessageContext aMessageContext, String aDelegateKey) { CAS cas = null; String casReferenceId = null; Endpoint endpointWithTimer = null; try { final int payload = aMessageContext.getMessageIntProperty(AsynchAEMessage.Payload); casReferenceId = aMessageContext.getMessageStringProperty(AsynchAEMessage.CasReference); endpointWithTimer = lookupEndpoint(aMessageContext.getEndpoint().getEndpoint(), casReferenceId); if (endpointWithTimer == null) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(), "handleProcessResponseFromRemote", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_invalid_endpoint__WARNING", new Object[] { aMessageContext.getEndpoint().getEndpoint(), casReferenceId }); } return; } String delegateKey = ((AggregateAnalysisEngineController) getController()) .lookUpDelegateKey(aMessageContext.getEndpoint().getEndpoint()); Delegate delegate = ((AggregateAnalysisEngineController) getController()) .lookupDelegate(delegateKey); boolean casRemovedFromOutstandingList = delegate.removeCasFromOutstandingList(casReferenceId); // Check if this process reply message is expected. A message is expected if the Cas Id // in the message matches an entry in the delegate's outstanding list. This list stores // ids of CASes sent to the remote delegate pending reply. if (!casRemovedFromOutstandingList) { //handleUnexpectedMessage(casReferenceId, aMessageContext.getEndpoint()); return; // out of band reply. Most likely the CAS previously timedout } // Increment number of CASes processed by this delegate if (aDelegateKey != null) { ServicePerformance delegateServicePerformance = ((AggregateAnalysisEngineController) getController()) .getServicePerformance(aDelegateKey); if (delegateServicePerformance != null) { delegateServicePerformance.incrementNumberOfCASesProcessed(); } } String xmi = aMessageContext.getStringMessage(); // Fetch entry from the cache for a given Cas Id. The entry contains a CAS that will be used // during deserialization CacheEntry cacheEntry = getController().getInProcessCache().getCacheEntryForCAS( casReferenceId); // check if the client requested Performance Metrics for the CAS if ( aMessageContext.propertyExists(AsynchAEMessage.CASPerComponentMetrics) ) { try { // find top ancestor of this CAS. All metrics are accumulated there since // this is what will be returned to the client CacheEntry ancestor = getController(). getInProcessCache(). getTopAncestorCasEntry(cacheEntry); if ( ancestor != null ) { // fetch Performance Metrics from remote delegate reply List<AnalysisEnginePerformanceMetrics> metrics = UimaSerializer.deserializePerformanceMetrics(aMessageContext.getMessageStringProperty(AsynchAEMessage.CASPerComponentMetrics)); List<AnalysisEnginePerformanceMetrics> adjustedMetrics = new ArrayList<AnalysisEnginePerformanceMetrics>(); for(AnalysisEnginePerformanceMetrics delegateMetric : metrics ) { String adjustedUniqueName = ((AggregateAnalysisEngineController) getController()).getJmxContext(); if ( adjustedUniqueName.startsWith("p0=")) { adjustedUniqueName = adjustedUniqueName.substring(3); // skip p0= } adjustedUniqueName = adjustedUniqueName.replaceAll(" Components", ""); if (!adjustedUniqueName.startsWith("/")) { adjustedUniqueName = "/"+adjustedUniqueName; } adjustedUniqueName += delegateMetric.getUniqueName(); boolean found = false; AnalysisEnginePerformanceMetrics metric = null; for( AnalysisEnginePerformanceMetrics met : ancestor.getDelegateMetrics() ) { if ( met.getUniqueName().equals(adjustedUniqueName)) { long at = delegateMetric.getAnalysisTime(); long count = delegateMetric.getNumProcessed(); metric = new AnalysisEnginePerformanceMetrics(delegateMetric.getName(),adjustedUniqueName,at,count); found = true; ancestor.getDelegateMetrics().remove(met); break; } } if ( !found ) { metric = new AnalysisEnginePerformanceMetrics(delegateMetric.getName(),adjustedUniqueName,delegateMetric.getAnalysisTime(),delegateMetric.getNumProcessed()); } adjustedMetrics.add(metric); } ancestor.addDelegateMetrics(delegateKey, adjustedMetrics, true); // true=remote } } catch (Exception e) { // An exception be be thrown here if the service is being stopped. // The top level controller may have already cleaned up the cache // and the getCacheEntryForCAS() will throw an exception. Ignore it // here, we are shutting down. } } CasStateEntry casStateEntry = ((AggregateAnalysisEngineController) getController()) .getLocalCache().lookupEntry(casReferenceId); if (casStateEntry != null) { casStateEntry.setReplyReceived(); // Set the key of the delegate that returned the CAS casStateEntry.setLastDelegate(delegate); } else { return; // Cache Entry Not found } cas = cacheEntry.getCas(); int totalNumberOfParallelDelegatesProcessingCas = casStateEntry .getNumberOfParallelDelegates(); if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINE, CLASS_NAME.getName(), "handleProcessResponseFromRemote", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_number_parallel_delegates_FINE", new Object[] { totalNumberOfParallelDelegatesProcessingCas, Thread.currentThread().getId(), Thread.currentThread().getName() }); } if (totalNumberOfParallelDelegatesProcessingCas > 1) { // Block this thread until CAS is dispatched to all delegates in parallel step. Fixes race condition where // a reply comes from one of delegates in parallel step before dispatch sequence completes. Without // this blocking the result of analysis are merged into a CAS. casStateEntry.blockIfParallelDispatchNotComplete(); } if (cas == null) { throw new AsynchAEException(Thread.currentThread().getName() + "-Cache Does not contain a CAS. Cas Reference Id::" + casReferenceId); } if (UIMAFramework.getLogger().isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(), "handleProcessResponseFromRemote", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_rcvd_reply_FINEST", new Object[] { aMessageContext.getEndpoint().getEndpoint(), casReferenceId, xmi }); } long t1 = getController().getCpuTime(); /* --------------------- */ /** DESERIALIZE THE CAS. */ /* --------------------- */ //all subsequent serialization must be complete CAS. if ( !aMessageContext.getMessageBooleanProperty(AsynchAEMessage.SentDeltaCas)) { cacheEntry.setAcceptsDeltaCas(false); } SerialFormat serialFormat = endpointWithTimer.getSerialFormat(); // check if the CAS is part of the Parallel Step if (totalNumberOfParallelDelegatesProcessingCas > 1) { // Synchronized because replies are merged into the same CAS. synchronized (cas) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINEST)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(), "handleProcessResponseFromRemote", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_delegate_responded_count_FINEST", new Object[] { casStateEntry.howManyDelegatesResponded(), casReferenceId }); } // If a delta CAS, merge it while checking that no pre-existing FSs are modified. if (aMessageContext.getMessageBooleanProperty(AsynchAEMessage.SentDeltaCas)) { switch (serialFormat) { case XMI: int highWaterMark = cacheEntry.getHighWaterMark(); deserialize(xmi, cas, casReferenceId, highWaterMark, AllowPreexistingFS.disallow); break; case COMPRESSED_FILTERED: deserialize(aMessageContext.getByteMessage(), cas, cacheEntry, endpointWithTimer.getTypeSystemImpl(), AllowPreexistingFS.disallow); break; default: throw new UIMARuntimeException(new Exception("Internal error")); } } else { // If not a delta CAS (old service), take all of first reply, and merge in the new // entries in the later replies. Ignoring pre-existing FS for 2.2.2 compatibility // Note: can't be a compressed binary - that would have returned a delta if (casStateEntry.howManyDelegatesResponded() == 0) { deserialize(xmi, cas, casReferenceId); } else { // process secondary reply from a parallel step int highWaterMark = cacheEntry.getHighWaterMark(); deserialize(xmi, cas, casReferenceId, highWaterMark, AllowPreexistingFS.ignore); } } casStateEntry.incrementHowManyDelegatesResponded(); } } else { // Processing a reply from a non-parallel delegate (binary or delta xmi or xmi) byte[] binaryData = aMessageContext.getByteMessage(); ByteArrayInputStream istream = new ByteArrayInputStream(binaryData); switch (serialFormat) { case BINARY: ((CASImpl)cas).reinit(istream); break; case COMPRESSED_FILTERED: BinaryCasSerDes6 bcs = new BinaryCasSerDes6(cas, (MarkerImpl) cacheEntry.getMarker(), endpointWithTimer.getTypeSystemImpl(), cacheEntry.getCompress6ReuseInfo()); bcs.deserialize(istream, AllowPreexistingFS.allow); break; case XMI: if (aMessageContext.getMessageBooleanProperty(AsynchAEMessage.SentDeltaCas)) { int highWaterMark = cacheEntry.getHighWaterMark(); deserialize(xmi, cas, casReferenceId, highWaterMark, AllowPreexistingFS.allow); } else { deserialize(xmi, cas, casReferenceId); } break; default: throw new UIMARuntimeException(new Exception("Internal error")); } } long timeToDeserializeCAS = getController().getCpuTime() - t1; getController().getServicePerformance().incrementCasDeserializationTime(timeToDeserializeCAS); ServicePerformance casStats = getController().getCasStatistics(casReferenceId); casStats.incrementCasDeserializationTime(timeToDeserializeCAS); LongNumericStatistic statistic; if ((statistic = getController().getMonitor().getLongNumericStatistic("", Monitor.TotalDeserializeTime)) != null) { statistic.increment(timeToDeserializeCAS); } computeStats(aMessageContext, casReferenceId); // Send CAS for processing when all delegates reply // totalNumberOfParallelDelegatesProcessingCas indicates how many delegates are processing CAS // in parallel. Default is 1, meaning only one delegate processes the CAS at the same. // Otherwise, check if all delegates responded before passing CAS on to the Flow Controller. // The idea is that all delegates processing one CAS concurrently must respond, before the CAS // is allowed to move on to the next step. // HowManyDelegatesResponded is incremented every time a parallel delegate sends response. if (totalNumberOfParallelDelegatesProcessingCas == 1 || receivedAllResponsesFromParallelDelegates(casStateEntry, totalNumberOfParallelDelegatesProcessingCas)) { super.invokeProcess(cas, casReferenceId, null, aMessageContext, null); } } catch (Exception e) { // Check if the exception was thrown by the Cache while looking up // the CAS. It may be the case if in the parallel step one thread // drops the CAS in the Error Handling while another thread processes // reply from another delegate in the Parallel Step. A race condition // may occur here. If one thread drops the CAS due to excessive exceptions // and Flow Controller is configured to drop the CAS, the other thread // should not be allowed to move the CAS to process()method. The second // thread will find the CAS missing in the cache and the logic below // just logs the stale CAS and returns and doesnt attempt to handle // the missing CAS exception. if (e instanceof AsynchAEException && e.getMessage() != null && e.getMessage().startsWith("Cas Not Found")) { String key = "N/A"; if (endpointWithTimer != null) { key = ((AggregateAnalysisEngineController) getController()) .lookUpDelegateKey(endpointWithTimer.getEndpoint()); } if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(), "handleProcessResponseFromRemote", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_stale_reply__INFO", new Object[] { getController().getComponentName(), key, casReferenceId }); } // The reply came late. The CAS was removed from the cache. return; } ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.CasReference, casReferenceId); errorContext.add(AsynchAEMessage.Endpoint, aMessageContext.getEndpoint()); getController().getErrorHandlerChain().handle(e, errorContext, getController()); } finally { incrementDelegateProcessCount(aMessageContext); } } private synchronized boolean receivedAllResponsesFromParallelDelegates( CasStateEntry aCasStateEntry, int totalNumberOfParallelDelegatesProcessingCas) { if (aCasStateEntry.howManyDelegatesResponded() == totalNumberOfParallelDelegatesProcessingCas) { aCasStateEntry.resetDelegateResponded(); return true; } return false; } private void deserialize(String xmi, CAS cas, String casReferenceId, int highWaterMark, AllowPreexistingFS allow) throws Exception { XmiSerializationSharedData deserSharedData; deserSharedData = getController().getInProcessCache().getCacheEntryForCAS(casReferenceId) .getDeserSharedData(); UimaSerializer uimaSerializer = SerializerCache.lookupSerializerByThreadId(); uimaSerializer.deserializeCasFromXmi(xmi, cas, deserSharedData, true, highWaterMark, allow); } private void deserialize(byte[] bytes, CAS cas, CacheEntry cacheEntry, TypeSystemImpl remoteTs, AllowPreexistingFS allow) throws Exception { ByteArrayInputStream istream = new ByteArrayInputStream(bytes); ReuseInfo reuseInfo = cacheEntry.getCompress6ReuseInfo(); Serialization.deserializeCAS(cas, istream, remoteTs, reuseInfo, allow); } private void deserialize(String xmi, CAS cas, String casReferenceId) throws Exception { CacheEntry entry = getController().getInProcessCache().getCacheEntryForCAS(casReferenceId); // Processing the reply from a standard, non-parallel delegate XmiSerializationSharedData deserSharedData; deserSharedData = entry.getDeserSharedData(); if (deserSharedData == null) { deserSharedData = new XmiSerializationSharedData(); entry.setXmiSerializationData(deserSharedData); } UimaSerializer uimaSerializer = SerializerCache.lookupSerializerByThreadId(); uimaSerializer.deserializeCasFromXmi(xmi, cas, deserSharedData, true, -1); } private void handleProcessResponseWithCASReference(MessageContext aMessageContext) { String casReferenceId = null; CacheEntry cacheEntry = null; try { casReferenceId = aMessageContext.getMessageStringProperty(AsynchAEMessage.CasReference); cacheEntry = getController().getInProcessCache().getCacheEntryForCAS(casReferenceId); CasStateEntry casStateEntry = ((AggregateAnalysisEngineController) getController()) .getLocalCache().lookupEntry(casReferenceId); CAS cas = cacheEntry.getCas(); String delegateKey = ((AggregateAnalysisEngineController) getController()) .lookUpDelegateKey(aMessageContext.getEndpoint().getEndpoint()); Delegate delegate = ((AggregateAnalysisEngineController) getController()) .lookupDelegate(delegateKey); if (casStateEntry != null) { casStateEntry.setReplyReceived(); casStateEntry.setLastDelegate(delegate); } delegate.removeCasFromOutstandingList(casReferenceId); if (cas != null) { cancelTimerAndProcess(aMessageContext, casReferenceId, cas); } else { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb( Level.INFO, CLASS_NAME.getName(), "handleProcessResponseWithCASReference", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_cas_not_in_cache__INFO", new Object[] { getController().getName(), casReferenceId, aMessageContext.getEndpoint().getEndpoint() }); } throw new AsynchAEException("CAS with Reference Id:" + casReferenceId + " Not Found in CasManager's CAS Cache"); } } catch (Exception e) { ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.CasReference, casReferenceId); errorContext.add(AsynchAEMessage.Endpoint, aMessageContext.getEndpoint()); getController().getErrorHandlerChain().handle(e, errorContext, getController()); } finally { incrementDelegateProcessCount(aMessageContext); if (getController() instanceof AggregateAnalysisEngineController) { try { String endpointName = aMessageContext.getEndpoint().getEndpoint(); String delegateKey = ((AggregateAnalysisEngineController) getController()) .lookUpDelegateKey(endpointName); if (delegateKey != null) { Endpoint endpoint = ((AggregateAnalysisEngineController) getController()) .lookUpEndpoint(delegateKey, false); // Check if the multiplier aborted during processing of this input CAS if (endpoint != null && endpoint.isCasMultiplier() && cacheEntry.isAborted()) { if (!getController().getInProcessCache().isEmpty()) { getController().getInProcessCache().registerCallbackWhenCacheEmpty( getController().getEventListener()); } else { // Callback to notify that the cache is empty // !!!!!!!!!!!!!!! WHY DO WE NEED TO CALL onCacheEmpty() IF CAS IS ABORTED? // !!!!!!!!!!!!!!!!!!!!!! ????????????????????????????????? // getController().getEventListener().onCacheEmpty(); } } } } catch (Exception e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { if ( getController() != null ) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(), "handleProcessResponseWithCASReference", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_service_exception_WARNING", getController().getComponentName()); } UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "handleProcessResponseWithCASReference", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", e); } } } } } private void incrementDelegateProcessCount(MessageContext aMessageContext) { Endpoint endpoint = aMessageContext.getEndpoint(); if (endpoint != null && getController() instanceof AggregateAnalysisEngineController) { try { String delegateKey = ((AggregateAnalysisEngineController) getController()) .lookUpDelegateKey(endpoint.getEndpoint()); LongNumericStatistic stat = getController().getMonitor().getLongNumericStatistic( delegateKey, Monitor.ProcessCount); stat.increment(); } catch (Exception e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.INFO)) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "incrementDelegateProcessCount", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_delegate_key_for_endpoint_not_found__INFO", new Object[] { getController().getComponentName(), endpoint.getEndpoint() }); } } } } private boolean isException(Object object) { return (object instanceof Exception || object instanceof Throwable); } private boolean isShutdownException(Object object) { return (object instanceof Exception && object instanceof UimaEEServiceException && ((UimaEEServiceException) object).getCause() != null && ((UimaEEServiceException) object) .getCause() instanceof ServiceShutdownException); } private boolean ignoreException(Object object) { if (object != null && isException(object) && !isShutdownException(object)) { return false; } return true; } private synchronized void handleProcessResponseWithException(MessageContext aMessageContext, String delegateKey) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.FINE)) { UIMAFramework.getLogger(CLASS_NAME) .logrb( Level.FINE, CLASS_NAME.getName(), "handleProcessResponseWithException", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_handling_exception_from_delegate_FINE", new Object[] { getController().getName(), aMessageContext.getEndpoint().getEndpoint() }); } boolean isCpCError = false; String casReferenceId = null; try { // If a Process Request, increment number of docs processed if (aMessageContext.getMessageIntProperty(AsynchAEMessage.MessageType) == AsynchAEMessage.Response && aMessageContext.getMessageIntProperty(AsynchAEMessage.Command) == AsynchAEMessage.Process) { // Increment number of CASes processed by a delegate incrementDelegateProcessCount(aMessageContext); } Object object = aMessageContext.getObjectMessage(); if (object == null) { // Could be a C++ exception. In this case the exception is just a String in the message // cargo if (aMessageContext.getStringMessage() != null) { object = new UimaEEServiceException(aMessageContext.getStringMessage()); } } if (ignoreException(object)) { return; } if (getController() instanceof AggregateAnalysisEngineController && aMessageContext.propertyExists(AsynchAEMessage.Command) && aMessageContext.getMessageIntProperty(AsynchAEMessage.Command) == AsynchAEMessage.CollectionProcessComplete) { isCpCError = true; ((AggregateAnalysisEngineController) getController()) .processCollectionCompleteReplyFromDelegate(delegateKey, false); } else { casReferenceId = aMessageContext.getMessageStringProperty(AsynchAEMessage.CasReference); } if (object != null && (object instanceof Exception || object instanceof Throwable)) { String casid_msg = (casReferenceId == null) ? "" : " on CAS:" + casReferenceId; String controllerName = "/" + getController().getComponentName(); if (!getController().isTopLevelComponent()) { controllerName += ((BaseAnalysisEngineController) getController().getParentController()) .getUimaContextAdmin().getQualifiedContextName(); } Exception remoteException = new UimaAsDelegateException("----> Controller:" + controllerName + " Received Exception " + casid_msg + " From Delegate:" + delegateKey, (Exception) object); ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, aMessageContext .getMessageIntProperty(AsynchAEMessage.Command)); errorContext.add(AsynchAEMessage.MessageType, aMessageContext .getMessageIntProperty(AsynchAEMessage.MessageType)); if (!isCpCError) { errorContext.add(AsynchAEMessage.CasReference, casReferenceId); } errorContext.add(AsynchAEMessage.Endpoint, aMessageContext.getEndpoint()); getController().getErrorHandlerChain().handle(remoteException, errorContext, getController()); } } catch (Exception e) { ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.Process); errorContext.add(AsynchAEMessage.CasReference, casReferenceId); errorContext.add(AsynchAEMessage.Endpoint, aMessageContext.getEndpoint()); getController().getErrorHandlerChain().handle(e, errorContext, getController()); } } private void handleCollectionProcessCompleteReply(MessageContext aMessageContext, String delegateKey) { try { if (getController() instanceof AggregateAnalysisEngineController) { ((AggregateAnalysisEngineController) getController()) .processCollectionCompleteReplyFromDelegate(delegateKey, true); } } catch (Exception e) { ErrorContext errorContext = new ErrorContext(); errorContext.add(AsynchAEMessage.Command, AsynchAEMessage.CollectionProcessComplete); errorContext.add(AsynchAEMessage.Endpoint, aMessageContext.getEndpoint()); getController().getErrorHandlerChain().handle(e, errorContext, getController()); } } private void resetErrorCounts(String aDelegate) { getController().getMonitor().resetCountingStatistic(aDelegate, Monitor.ProcessErrorCount); getController().getMonitor().resetCountingStatistic(aDelegate, Monitor.ProcessErrorRetryCount); } private void handlePingReply(MessageContext aMessageContext) { try { } catch (Exception e) { if (UIMAFramework.getLogger(CLASS_NAME).isLoggable(Level.WARNING)) { if ( getController() != null ) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(), "handlePingReply", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_service_exception_WARNING", getController().getComponentName()); } UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "handlePingReply", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", e); } } } private void handleServiceInfoReply(MessageContext messageContext) { String casReferenceId = null; try { casReferenceId = messageContext.getMessageStringProperty(AsynchAEMessage.CasReference); if ( casReferenceId == null ) { return; // nothing to do } Endpoint freeCasEndpoint = messageContext.getEndpoint(); CasStateEntry casStateEntry = ((AggregateAnalysisEngineController) getController()) .getLocalCache().lookupEntry(casReferenceId); if (casStateEntry != null) { casStateEntry.setFreeCasNotificationEndpoint(freeCasEndpoint); // Fetch host IP where the CAS is being processed. When the UIMA AS service // receives a CAS it immediately sends ServiceInfo Reply message containing // IP of the host where the service is running. String serviceHostIp = messageContext.getMessageStringProperty(AsynchAEMessage.ServerIP); if ( serviceHostIp != null ) { casStateEntry.setHostIpProcessingCAS(serviceHostIp); } } } catch (Exception e) { UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, getClass().getName(), "handleServiceInfoReply", UIMAEE_Constants.JMS_LOG_RESOURCE_BUNDLE, "UIMAEE_exception__WARNING", e); return; } } public void handle(Object anObjectToHandle) throws AsynchAEException { super.validate(anObjectToHandle); MessageContext messageContext = (MessageContext) anObjectToHandle; if (isHandlerForMessage(messageContext, AsynchAEMessage.Response, AsynchAEMessage.Process) || isHandlerForMessage(messageContext, AsynchAEMessage.Response, AsynchAEMessage.ACK) || isHandlerForMessage(messageContext, AsynchAEMessage.Response, AsynchAEMessage.ServiceInfo) || isHandlerForMessage(messageContext, AsynchAEMessage.Response, AsynchAEMessage.CollectionProcessComplete)) { int payload = messageContext.getMessageIntProperty(AsynchAEMessage.Payload); int command = messageContext.getMessageIntProperty(AsynchAEMessage.Command); String delegate = ((Endpoint) messageContext.getEndpoint()).getEndpoint(); String key = null; String fromServer = null; if (getController() instanceof AggregateAnalysisEngineController) { if (((Endpoint) messageContext.getEndpoint()).isRemote()) { if (((MessageContext) anObjectToHandle).propertyExists(AsynchAEMessage.EndpointServer)) { fromServer = ((MessageContext) anObjectToHandle) .getMessageStringProperty(AsynchAEMessage.EndpointServer); } // If old service does not echo back the external broker name then the queue name must be // unique. // Can't use the ServerURI set by the service as it may be its local name for the broker, // e.g. tcp://localhost:61616 } key = ((AggregateAnalysisEngineController) getController()).lookUpDelegateKey(delegate, fromServer); } if (AsynchAEMessage.CASRefID == payload) { handleProcessResponseWithCASReference(messageContext); if (key != null) { resetErrorCounts(key); } } else if (AsynchAEMessage.XMIPayload == payload || AsynchAEMessage.BinaryPayload == payload) { handleProcessResponseFromRemote(messageContext, key); if (key != null) { resetErrorCounts(key); } } else if (AsynchAEMessage.Exception == payload) { if (key == null) { key = ((Endpoint) messageContext.getEndpoint()).getEndpoint(); } handleProcessResponseWithException(messageContext, key); } else if (AsynchAEMessage.None == payload && AsynchAEMessage.CollectionProcessComplete == command) { if (key == null) { key = ((Endpoint) messageContext.getEndpoint()).getEndpoint(); } handleCollectionProcessCompleteReply(messageContext, key); } else if (AsynchAEMessage.None == payload && AsynchAEMessage.ACK == command) { handleACK(messageContext, key); } else if (AsynchAEMessage.None == payload && AsynchAEMessage.Ping == command) { handlePingReply(messageContext); } else if (AsynchAEMessage.None == payload && AsynchAEMessage.ServiceInfo == command) { handleServiceInfoReply(messageContext); } else { throw new AsynchAEException("Invalid Payload. Expected XMI or CasReferenceId Instead Got::" + payload); } // Handled Request to Process with A given Payload return; } // Not a Request nor Command. Delegate to the next handler in the chain super.delegate(messageContext); } private void handleACK(MessageContext aMessageContext, String key) throws AsynchAEException { } }
92361fce27da40fafaf8681a7df22a01ac2f6cc1
852
java
Java
toolkit-basic/src/main/java/pxf/toolkit/basic/unit/NumberUnit.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
toolkit-basic/src/main/java/pxf/toolkit/basic/unit/NumberUnit.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
toolkit-basic/src/main/java/pxf/toolkit/basic/unit/NumberUnit.java
potatoxf/Toolkit
3b92c6a01ce49996907d291e7607e600eb04d934
[ "Apache-2.0" ]
null
null
null
19.363636
91
0.67723
997,554
package pxf.toolkit.basic.unit; import pxf.toolkit.basic.unit.impl.NonIsometric; import pxf.toolkit.basic.unit.impl.UnitConverter; import pxf.toolkit.basic.unit.impl.UnitConverterImpl; /** * 数字进位 * * @author potatoxf * @date 2021/3/13 */ public enum NumberUnit implements NonIsometric<NumberUnit>, UnitConverterImpl<NumberUnit> { /** 万分比 */ TEN_THOUSANDTHS(10), /** 千分比 */ THOUSANDS(10), /** 百分比 */ PERCENTAGE(100), /** 正常 */ NORMAL(-1); private final UnitConverter<NumberUnit> converter = UnitConverter.of(this); private final int next; NumberUnit(int next) { this.next = next; } @Override public int nextInterval() { return next; } /** * 返回持有单位转换器 * * @return {@code UnitConverter<E>} */ @Override public UnitConverter<NumberUnit> holdingUnitConverter() { return converter; } }
92362020d1954fedfe51dcff5a899e32241222fc
1,743
java
Java
WerkUI/src/org/werk/ui/controls/steptypesform/StepTypesTable.java
codekrolik2/Werk
3ec9bfb2f1963be5256be35e898d2d0a51a238cc
[ "MIT" ]
null
null
null
WerkUI/src/org/werk/ui/controls/steptypesform/StepTypesTable.java
codekrolik2/Werk
3ec9bfb2f1963be5256be35e898d2d0a51a238cc
[ "MIT" ]
null
null
null
WerkUI/src/org/werk/ui/controls/steptypesform/StepTypesTable.java
codekrolik2/Werk
3ec9bfb2f1963be5256be35e898d2d0a51a238cc
[ "MIT" ]
1
2021-04-26T18:07:25.000Z
2021-04-26T18:07:25.000Z
29.05
127
0.738956
997,555
package org.werk.ui.controls.steptypesform; import java.io.IOException; import org.werk.meta.StepType; import org.werk.ui.controls.mainapp.MainApp; import org.werk.ui.controls.table.ButtonCell; import org.werk.ui.guice.LoaderFactory; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.util.Callback; import lombok.Setter; public class StepTypesTable extends TableView<StepType<Long>> { @Setter MainApp mainApp; @FXML TableColumn<StepType<Long>, String> detailsColumn; @FXML TableColumn<StepType<Long>, String> jobTypesColumn; public StepTypesTable() { FXMLLoader fxmlLoader = LoaderFactory.getInstance().loader(getClass().getResource("StepTypesTable.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } } public void initialize() { detailsColumn.setCellFactory(new StepTypeDetailsCellFactory()); } public void hideJobs() { jobTypesColumn.setVisible(false); } class StepTypeDetailsCellFactory implements Callback<TableColumn<StepType<Long>, String>, TableCell<StepType<Long>, String>> { @Override public TableCell<StepType<Long>, String> call(final TableColumn<StepType<Long>, String> param) { return new ButtonCell<StepType<Long>, String>("Details") { @Override protected void handle(ActionEvent event) { StepType<Long> stepType = getTableView().getItems().get(getIndex()); mainApp.createStepTypeTab(stepType); } }; } } }