repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
goribun/naive-rpc
naive-client/src/main/java/com/goribun/naive/client/poxy/RpcProxy.java
[ "public class OkHttpUtil {\n\n private static OkHttpClient CLIENT = new OkHttpClient();\n\n private OkHttpUtil() {\n }\n\n public static OkHttpClient getOkHttpClient() {\n return CLIENT;\n }\n\n}", "public enum SysErCode {\n IO_ERROR(0001, \"IO异常\"),\n OK_HTTP_ERROR(0002, \"okhttp请求错误\...
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import com.alibaba.fastjson.JSON; import com.goribun.naive.client.http.OkHttpUtil; import com.goribun.naive.core.constants.SysErCode; import com.goribun.naive.core.exception.SysException; import com.goribun.naive.core.protocol.Protocol; import com.goribun.naive.core.protocol.ProtocolStatus; import com.goribun.naive.core.serial.MethodCallEntity; import com.goribun.naive.core.serial.MethodCallUtil; import com.goribun.naive.core.utils.ExceptionUtil; import okhttp3.Request; import okhttp3.Response;
package com.goribun.naive.client.poxy; /** * Rpc代理 * * @author wangxuesong */ public class RpcProxy implements InvocationHandler { private String serviceName; private String host; public RpcProxy(String host, String serviceName) { this.host = host; this.serviceName = serviceName; } /** * 发送请求 * 列入:http://127.0.0.1:8080/service/类名/方法名?args={key1:value1,key2:value2} */ @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if ("toString".equals(methodName)) { return String.format("host:%s->service:%s", host, serviceName); } if ("hashCode".equals(methodName)) { return null; } String url = host + "/service/" + serviceName + "/" + method.getName(); MethodCallEntity entity = new MethodCallEntity(method, args); String argsJson = MethodCallUtil.getMethodCallStr(entity); url += "?args=" + argsJson; Class returnType = method.getReturnType(); Request request = new Request.Builder().url(url).build(); Response response = OkHttpUtil.getOkHttpClient().newCall(request).execute(); if (response.isSuccessful()) { String resultString = response.body().string(); //接收到的协议体 Protocol protocol = JSON.parseObject(resultString, Protocol.class); if (protocol.getCode() == ProtocolStatus.FAILURE) { throw ExceptionUtil.instanceThrowable(protocol.getExceptionDetail()); } if ("void".equals(returnType.getName()) && "void".equals(resultString)) { return null; } //返回反序列化的值 return JSON.parseObject(JSON.toJSONString(protocol.getData()), returnType); } else {
throw new SysException(SysErCode.OK_HTTP_ERROR);
1
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/dicom/ApplicationActivityEvent.java
[ "public abstract class DICOMActiveParticipantRoleIdCodes extends CodedValueType\n{\n\tprotected DICOMActiveParticipantRoleIdCodes(String value, String meaning)\n\t{\n\t\tsetCodeSystemName(\"DCM\");\n\t\tsetCode(value);\n\t\tsetOriginalText(meaning);\n\t}\n\t/**\n\t * \"DCM\",\"110150\", \"Application\"\n\t *\n\t * ...
import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMActiveParticipantRoleIdCodes; import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMEventIdCodes; import org.openhealthtools.ihe.atna.auditor.codes.dicom.DICOMEventTypeCodes; import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes; import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes.RFC3881EventOutcomeCodes; import org.openhealthtools.ihe.atna.auditor.events.GenericAuditEventMessageImpl; import java.util.Collections;
/******************************************************************************* * Copyright (c) 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.openhealthtools.ihe.atna.auditor.events.dicom; /** * Audit Event representing a DICOM 95 Application Activity event (DCM 110100) * * @author <a href="mailto:mattadav@us.ibm.com">Matthew Davis</a> */ public class ApplicationActivityEvent extends GenericAuditEventMessageImpl { /** * Creates an application activity event for a given outcome and * DICOM Event Type (e.g. Application Start or Application Stop) * @param outcome Event outcome indicator * @param type The DICOM 95 Event Type */
public ApplicationActivityEvent(RFC3881EventOutcomeCodes outcome, DICOMEventTypeCodes type)
4
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/search/facet/JresTermsFacetTest.java
[ "public class BaseJresTest {\n\n @BeforeClass\n public static void startLocalElasticSearch() {\n ElasticSearchTestInstance.triggerStaticInit();\n }\n\n /**\n * Configured to connect to a local ElasticSearch instance created specifically for unit testing\n */\n protected Jres jres = new...
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.model.search.TermsFacet; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.request.index.JresIndexDocument; import com.blacklocus.jres.request.index.JresRefresh; import com.blacklocus.jres.request.mapping.JresPutMapping; import com.blacklocus.jres.request.search.JresSearch; import com.blacklocus.jres.request.search.JresSearchBody; import com.blacklocus.jres.response.search.JresSearchReply; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; import java.util.Arrays;
/** * Copyright 2015 BlackLocus * * 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.blacklocus.jres.request.search.facet; public class JresTermsFacetTest extends BaseJresTest { @Test public void testTerms() { String index = "JresTermsFacetTest.testTerms".toLowerCase(); String type = "test"; jres.quest(new JresCreateIndex(index)); jres.quest(new JresPutMapping(index, type)); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "one"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "two"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "two"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresIndexDocument(index, type, ImmutableMap.of("value", "three"))); jres.quest(new JresRefresh(index)); JresSearchBody search = new JresSearchBody().size(0).facets(new JresTermsFacet("the_terms", "value"));
JresSearchReply reply = jres.quest(new JresSearch(index, type, search));
8
ds84182/OpenGX
src/main/java/ds/mods/opengx/Glasses.java
[ "public class ComponentButton extends Component implements ManagedEnvironment {\n\t\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentButton>> serverCGX = new WeakHashMap<World,HashMap<UUID,ComponentButton>>();\n\tpublic static final WeakHashMap<World,HashMap<UUID,ComponentButton>> clientCGX = new Weak...
import java.util.ArrayList; import java.util.Iterator; import java.util.Map.Entry; import java.util.UUID; import java.util.WeakHashMap; import li.cil.oc.api.FileSystem; import li.cil.oc.api.Machine; import li.cil.oc.api.Network; import li.cil.oc.api.driver.Container; import li.cil.oc.api.machine.Owner; import li.cil.oc.api.network.ManagedEnvironment; import li.cil.oc.api.network.Node; import li.cil.oc.server.component.WirelessNetworkCard; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.relauncher.Side; import ds.mods.opengx.component.ComponentButton; import ds.mods.opengx.component.ComponentGX; import ds.mods.opengx.component.ComponentMonitor; import ds.mods.opengx.component.ComponentPROM; import ds.mods.opengx.component.ComponentSensor; import ds.mods.opengx.network.GlassesButtonEventMessage; import ds.mods.opengx.network.GlassesComponentUUIDMessage; import ds.mods.opengx.network.GlassesErrorMessage;
package ds.mods.opengx; public class Glasses implements Owner, Container { public static WeakHashMap<World, ArrayList<Glasses>> svmap = new WeakHashMap<World, ArrayList<Glasses>>(); public static WeakHashMap<World, ArrayList<Glasses>> clmap = new WeakHashMap<World, ArrayList<Glasses>>(); public static WeakHashMap<World, ArrayList<Glasses>> getMap() { return FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT ? clmap : svmap; } public static Glasses get(UUID uuid, World w) { WeakHashMap<World, ArrayList<Glasses>> map = getMap(); Glasses g = null; if (map.get(w) == null) { System.out.println("NO ARRAY LIST"); return null; } for (Glasses _g : map.get(w)) { if (_g.uuid.equals(uuid)) { g = _g; break; } } return g; } public static void updateAll() { Iterator<Entry<World, ArrayList<Glasses>>> iter = getMap().entrySet().iterator(); while (iter.hasNext()) { Entry<World, ArrayList<Glasses>> e = iter.next(); Iterator<Glasses> giter = e.getValue().iterator(); while (giter.hasNext()) { Glasses g = giter.next(); if (g.hasntUpdatedIn++ > 200) { //turn off! g.turnOff(); giter.remove(); } } } } public int hasntUpdatedIn = 0; public li.cil.oc.api.machine.Machine machine = null; public EntityPlayer holder; public ItemStack stack; public UUID uuid = UUID.randomUUID(); public ComponentSensor sensors; public ComponentButton buttons; public ComponentGX gx;
public ComponentMonitor monitor;
2
CodeAndMagic/android-deferred-object
core/src/test/java/org/codeandmagic/promise/tests/PipePromisesTests.java
[ "public class DeferredObject<Success> extends AbstractPromise<Success> {\n\n public static <S> DeferredObject<S> successful(S value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S>...
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import org.codeandmagic.promise.*; import org.codeandmagic.promise.impl.DeferredObject; import org.codeandmagic.promise.Pipe; import org.codeandmagic.promise.Promise; import org.codeandmagic.promise.Pipe3; import org.codeandmagic.promise.impl.DeferredObject3; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static java.lang.System.currentTimeMillis;
/* * Copyright (c) 2014 Cristian Vrabie, Evelina Vrabie. * * This file is part of android-promise. * android-deferred-object is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License,or (at your option) * any later version. * * android-promise 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with android-promise * If not, see <http://www.gnu.org/licenses/>. */ package org.codeandmagic.promise.tests; /** * Created by cristian on 11/02/2014. */ @RunWith(JUnit4.class) public class PipePromisesTests { public Promise<Integer> deferredInt(final int number) { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.success(number); } catch (InterruptedException e) { deferredObject.failure(e); } } }.start(); return deferredObject; } public Promise<Integer> deferredException() { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.failure(new Exception("Failed!")); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); return deferredObject; } @Test public void testPipe() { Callback<String> onSuccess = mock(Callback.class); Callback<Throwable> onFailure = mock(Callback.class); DeferredObject3.<Integer, Throwable, Void>successful(3).pipe(new Pipe3<Integer, String, Throwable>() { @Override public Promise3<String, Throwable, Void> transform(Integer value) { return DeferredObject3.<String, Throwable, Void>failed(new Exception("Failed")); } }).onSuccess(onSuccess).onFailure(onFailure); verify(onSuccess, never()).onCallback(anyString()); verify(onFailure, only()).onCallback(any(Exception.class)); } @Test @Ignore public void testPipeMultiThreaded() { Callback<Integer> onSuccess1 = mock(Callback.class); Callback<Throwable> onFailure1 = mock(Callback.class); Callback<Integer> onSuccess2 = mock(Callback.class); Callback<Throwable> onFailure2 = mock(Callback.class); long start = currentTimeMillis(); Promise<Integer> exception = deferredException().onSuccess(onSuccess1).onFailure(onFailure1);
Promise<Integer> number = exception.recoverWith(new Pipe<Throwable, Integer>() {
1
fiware-cybercaptor/cybercaptor-server
src/main/java/org/fiware/cybercaptor/server/remediation/DeployableRemediation.java
[ "public class AttackPath extends MulvalAttackGraph implements Cloneable {\n\n /**\n * The scoring of the attack path (should be between 0 and 1)\n */\n public double scoring = 0;\n /**\n * The goal of the attacker\n */\n Vertex goal = null;\n\n /**\n * @param leavesToCorrect ...
import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.fiware.cybercaptor.server.attackgraph.AttackPath; import org.fiware.cybercaptor.server.attackgraph.serializable.SerializableAttackPath; import org.fiware.cybercaptor.server.informationsystem.InformationSystem; import org.fiware.cybercaptor.server.properties.ProjectProperties; import org.fiware.cybercaptor.server.remediation.serializable.SerializableDeployableRemediation; import org.jdom2.Element; import java.io.*; import java.util.AbstractMap; import java.util.ArrayList;
/**************************************************************************************** * This file is part of FIWARE CyberCAPTOR, * * instance of FIWARE Cyber Security Generic Enabler * * Copyright (C) 2012-2015 Thales Services S.A.S., * * 20-22 rue Grande Dame Rose 78140 VELIZY-VILACOUBLAY FRANCE * * * * FIWARE CyberCAPTOR 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. * * * * FIWARE CyberCAPTOR 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 FIWARE CyberCAPTOR. * * If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package org.fiware.cybercaptor.server.remediation; /** * Class representing a deployable remediation = a list of {@link DeployableRemediationAction} * (remediations that can be deployed on a host) with a cost. * * @author Francois -Xavier Aguessy */ public class DeployableRemediation { /** * The actions of the deployable remediation */ private List<DeployableRemediationAction> actions = new ArrayList<DeployableRemediationAction>(); /** * The cost of the deployable remediation */ private double cost = 0; /** * The corrected attack path */
private AttackPath correctedPath;
0
DiatomStudio/SketchChair
src/ShapePacking/spShapePack.java
[ "public class GLOBAL {\n\n\tpublic static boolean useMaskedUpdating = false;\n\n\tstatic SketchProperties sketchProperties = new SketchProperties();\n\t\n\tpublic static double CAM_OFFSET_X = 300;\n\tpublic static double CAM_OFFSET_Y = -900;\n\tpublic static int windowWidth;\n\tpublic static int windowHeight;\n\tpu...
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; import nu.xom.Serializer; import cc.sketchchair.core.GLOBAL; import cc.sketchchair.core.LOGGER; import cc.sketchchair.core.SETTINGS; import cc.sketchchair.functions.functions; import cc.sketchchair.sketch.Sketch; import ToolPathWriter.CraftRoboWriter; import ToolPathWriter.DXFWriter; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PFont; import processing.core.PGraphics; import processing.pdf.PGraphicsPDF;
String[] cmd = {"/usr/bin/open", "-a" , "Cutting Master 2 for CraftROBO.app", "/Applications/Cutting Master 2 CraftROBO 1.86/Release/"}; p = rt.exec(cmd); }else{ craftRoboPath = "C:/Program Files/Cutting Master 2 for CraftROBO 1.60/Program/App2.exe"; p = rt.exec(craftRoboPath); } LOGGER.info("Running: " + craftRoboPath); // in = p.getInputStream(); if (in.available() > 0) System.out.println(in.toString()); out = p.getOutputStream(); InputStream err = p.getErrorStream(); //p.destroy() ; } catch (Exception exc) {/*handle exception*/ } } public void setupFirstRender(PGraphics g){ ZOOM = ( (float)g.height/this.materialHeight); this.CAM_OFFSET_X = (int) -(this.materialWidth/2.0f); this.CAM_OFFSET_Y = (int) -(this.materialHeight/2.0f); } public void render(PGraphics g) { if(firstRender) setupFirstRender(g);//if this is the first time we have rendered then setup the correct postion on the screen if(ZOOM < minZoom) ZOOM = minZoom; if(ZOOM > maxZoom) ZOOM = maxZoom; if(CAM_OFFSET_X > maxCamX) CAM_OFFSET_X = maxCamX; if(CAM_OFFSET_X < minCamX) CAM_OFFSET_X = minCamX; if(CAM_OFFSET_Y > maxCamY) CAM_OFFSET_Y = maxCamY; if(CAM_OFFSET_Y < minCamY) CAM_OFFSET_Y = minCamY; firstRender = false; g.textSize(this.textSize); g.fill(0); g.noStroke(); g.pushMatrix(); g.translate(g.width/2, g.height/2); g.scale(this.ZOOM); g.translate(this.CAM_OFFSET_X, this.CAM_OFFSET_Y); this.pages.render(g); g.popMatrix(); } public void renderPickBuffer(PGraphics pickBuffer) { firstRender = false; pickBuffer.noFill(); pickBuffer.stroke(0); pickBuffer.pushMatrix(); pickBuffer.scale(this.ZOOM); pickBuffer.translate(this.CAM_OFFSET_X, this.CAM_OFFSET_Y); this.pages.renderPickBuffer(pickBuffer); pickBuffer.popMatrix(); } public void renderList(PGraphics g) { g.textSize(this.textSize); g.noFill(); g.stroke(0); g.pushMatrix(); this.pages.renderList(g); g.popMatrix(); } public void scaleAll(float scale) { this.shapes.scale(scale); } public void renderPickBufferList(PGraphics pickBuffer) { this.pages.renderPickBufferList(pickBuffer); } public void zoomView(float _zoomDelta, float _mouseX, float _mouseY){ float deltaMouseXBefore = (float) (((GLOBAL.applet.width/2)-_mouseX)/this.ZOOM); float deltaMouseYBefore = (float) (((GLOBAL.applet.height/2)-_mouseY)/this.ZOOM); this.ZOOM -= _zoomDelta;
if( (_zoomDelta > 0 && this.ZOOM < SETTINGS.MIN_ZOOM)){
2
setial/intellij-javadocs
src/main/java/com/github/setial/intellijjavadocs/action/JavaDocGenerateAction.java
[ "public class SetupTemplateException extends RuntimeException {\n\n /**\n * Instantiates a new Setup template exception.\n *\n * @param cause the cause\n */\n public SetupTemplateException(Throwable cause) {\n super(cause);\n }\n}", "public class TemplateNotFoundException extends R...
import com.github.setial.intellijjavadocs.exception.SetupTemplateException; import com.github.setial.intellijjavadocs.exception.TemplateNotFoundException; import com.github.setial.intellijjavadocs.generator.JavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.ClassJavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.FieldJavaDocGenerator; import com.github.setial.intellijjavadocs.generator.impl.MethodJavaDocGenerator; import com.github.setial.intellijjavadocs.operation.JavaDocWriter; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.MessageFormat; import java.util.LinkedList; import java.util.List; import static com.github.setial.intellijjavadocs.configuration.impl.JavaDocConfigurationImpl.JAVADOCS_PLUGIN_TITLE_MSG;
package com.github.setial.intellijjavadocs.action; /** * The type Java doc generate action. * * @author Sergey Timofiychuk */ public class JavaDocGenerateAction extends BaseAction { private static final Logger LOGGER = Logger.getInstance(JavaDocGenerateAction.class); private JavaDocWriter writer; /** * Instantiates a new Java doc generate action. */ public JavaDocGenerateAction() { this(new JavaDocHandler()); } /** * Instantiates a new Java doc generate action. * * @param handler the handler */ public JavaDocGenerateAction(CodeInsightActionHandler handler) { super(handler); writer = ServiceManager.getService(JavaDocWriter.class); } /** * Action performed. * * @param e the Event */ @Override public void actionPerformed(AnActionEvent e) { DumbService dumbService = DumbService.getInstance(e.getProject()); if (dumbService.isDumb()) { dumbService.showDumbModeNotification("Javadocs plugin is not available during indexing"); return; } Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); if (editor == null) { LOGGER.error("Cannot get com.intellij.openapi.editor.Editor");
Messages.showErrorDialog("Javadocs plugin is not available", JAVADOCS_PLUGIN_TITLE_MSG);
7
calibre2opds/calibre2opds
OpdsOutput/src/main/java/com/gmail/dpierron/calibre/opds/TagListSubCatalog.java
[ "public class Book extends GenericDataObject {\r\n private final static Logger logger = LogManager.getLogger(Book.class);\r\n\r\n private File bookFolder;\r\n private final String id;\r\n private final String uuid;\r\n private String title;\r\n private String titleSort;\r\n private final String path;\r\n ...
import com.gmail.dpierron.calibre.configuration.Icons; import com.gmail.dpierron.calibre.datamodel.Book; import com.gmail.dpierron.calibre.datamodel.GenericDataObject; import com.gmail.dpierron.calibre.datamodel.Tag; import com.gmail.dpierron.tools.i18n.Localization; import com.gmail.dpierron.calibre.trook.TrookSpecificSearchDatabaseManager; import com.gmail.dpierron.tools.Helper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import java.io.IOException; import java.util.*;
package com.gmail.dpierron.calibre.opds; /** * Class for defining methods that define a tag sub catalog */ public class TagListSubCatalog extends TagsSubCatalog { private final static Logger logger = LogManager.getLogger(TagListSubCatalog.class); public TagListSubCatalog(List<Object> stuffToFilterOut, List<Book> books) { super(stuffToFilterOut, books); setCatalogType(Constants.TAGLIST_TYPE); } public TagListSubCatalog(List<Book> books) { super(books); setCatalogType(Constants.TAGLIST_TYPE); } @Override //Composite<Element, String> getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException { Element getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException { return getListOfTags(pBreadcrumbs, getTags(), pBreadcrumbs.size() > 1, 0, Localization.Main.getText("tags.title"), getTags().size() > 1 ? Localization.Main.getText("tags.alphabetical", getTags().size()) : (getTags().size() == 1 ? Localization.Main.getText("authors.alphabetical.single") : "") , Constants.INITIAL_URN_PREFIX + getCatalogType() + getCatalogLevel(), getCatalogBaseFolderFileName(), null); } // private Composite<Element, String> getListOfTags( private Element getListOfTags( Breadcrumbs pBreadcrumbs,
List<Tag> listTags,
2
utapyngo/owl2vcs
src/main/java/owl2vcs/io/FunctionalChangesetSerializer.java
[ "public abstract class ChangeSet {\r\n\r\n protected ChangeSet() {\r\n }\r\n\r\n private SetOntologyFormatData formatChange;\r\n\r\n private Collection<PrefixChangeData> prefixChanges;\r\n\r\n private SetOntologyIDData ontologyIdChange;\r\n\r\n private Collection<ImportChangeData> importChanges;\r...
import java.io.PrintStream; import java.io.UnsupportedEncodingException; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.util.ShortFormProvider; import owl2vcs.changeset.ChangeSet; import owl2vcs.render.ChangeFormat; import owl2vcs.render.ChangeRenderer; import owl2vcs.render.FullFormProvider; import owl2vcs.render.FunctionalChangeRenderer;
package owl2vcs.io; public class FunctionalChangesetSerializer { public void write(ChangeSet cs, PrintStream out) {
write(cs, out, new FullFormProvider(), ChangeFormat.COMPACT);
1
KodeMunkie/imagetozxspec
src/main/java/uk/co/silentsoftware/core/converters/spectrum/TapeConverter.java
[ "public static byte[] copyBytes(byte[] from, byte[] to, int fromIndex) {\n\tSystem.arraycopy(from, 0, to, fromIndex, from.length);\n\treturn to;\n}", "public static byte getChecksum(byte[] bytes) {\n\tint checksum = 0;\n\tfor (byte b: bytes) {\n\t\tchecksum^=b;\n\t}\n\treturn (byte)checksum;\n}\t", "public sta...
import uk.co.silentsoftware.config.OptionsObject; import uk.co.silentsoftware.core.helpers.ByteHelper; import static uk.co.silentsoftware.core.helpers.ByteHelper.copyBytes; import static uk.co.silentsoftware.core.helpers.ByteHelper.getChecksum; import static uk.co.silentsoftware.core.helpers.ByteHelper.put; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Image to ZX Spec * Copyright (C) 2019 Silent Software (Benjamin Brown) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.silentsoftware.core.converters.spectrum; /** * Converter to output a Tape image format file (.tap) */ public class TapeConverter { private final Logger log = LoggerFactory.getLogger(this.getClass()); /** * Outputs an SCR format image into a tap file part * (i.e. a standard data block). * * @see <a href="http://www.zx-modules.de/fileformats/tapformat.html">http://www.zx-modules.de/fileformats/tapformat.html</a> * * @param image the SCR image data to add to the tap file * @return the tap file section containing the Spectrum encoded image */ public byte[] createTapPart(byte[] image) { // Standard ROM data block header ByteBuffer imageData = ByteBuffer.allocate(2+image.length); imageData.order(ByteOrder.LITTLE_ENDIAN); imageData.put(0, (byte)255); // 255 indicates ROM loading block - cast just for show put(imageData, image, 1); // SCR image data imageData.put(6913, getChecksum(imageData.array())); // XOR checksum // Screen header ByteBuffer imageHeader = ByteBuffer.allocate(19); imageHeader.order(ByteOrder.LITTLE_ENDIAN); imageHeader.put(0, (byte)0); // Indicates ROM header imageHeader.put(1, (byte)3); // Indicates BYTE header put(imageHeader, "Loading...".getBytes(), 2); // Program loading name imageHeader.putShort(12, (short)6912); // Length of data (should be 6912) imageHeader.putShort(14, (short)16384); // Start address to import to imageHeader.putShort(16, (short)32768); // Unused, must be 32768 imageHeader.put(18, getChecksum(imageHeader.array())); // XOR checksum // Copy image header block into data block sub block ByteBuffer imageHeaderBlock = ByteBuffer.allocate(2+imageHeader.array().length); imageHeaderBlock.order(ByteOrder.LITTLE_ENDIAN); imageHeaderBlock.putShort((short)(imageHeader.array().length)); put(imageHeaderBlock, imageHeader.array(), 2); // Copy image data into data block sub block ByteBuffer imageDataBlock = ByteBuffer.allocate(2+imageData.array().length); imageDataBlock.order(ByteOrder.LITTLE_ENDIAN); imageDataBlock.putShort((short)(imageData.array().length)); put(imageDataBlock, imageData.array(), 2); // Combined the header sub block and image data sub block and return the bytes byte[] b = new byte[imageHeaderBlock.array().length+imageDataBlock.array().length]; b = copyBytes(imageHeaderBlock.array(), b, 0); b = copyBytes(imageDataBlock.array(), b, imageHeaderBlock.array().length); return b; } /** * Returns a the new tap file bytes containing * a basic SCR loader followed by the SCR images * that have been already converted to TAP parts * * @param parts the TAP parts (data blocks) contain SCR images * @return the entire tap file as bytes */ public byte[] createTap(List<byte[]> parts) { byte[] loader = createLoader(); int size = loader.length; for (byte[] b: parts) { size+=b.length; } byte[] result = new byte[size]; ByteHelper.copyBytes(loader, result, 0); int index = loader.length; for (byte[] b: parts) { ByteHelper.copyBytes(b, result, index); index += b.length; } return result; } /** * Creates and returns the TAP loader from the options * selected loader file. N.b this byte data will already * be in little endian order. * * @return the byte data contained in the loader file */ private byte[] createLoader() {
OptionsObject oo = OptionsObject.getInstance();
3
ryft/NetVis
workspace/netvis/src/netvis/visualisations/DataflowVisualisation.java
[ "public class DataController implements ActionListener {\n\tDataFeeder dataFeeder;\n\tTimer timer;\n\tfinal List<DataControllerListener> listeners;\n\tfinal List<PacketFilter> filters;\n\tfinal List<Packet> allPackets;\n\tfinal List<Packet> filteredPackets;\n\tprivate int noUpdated = 0;\n\tprotected int intervalsCo...
import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Hashtable; import java.util.List; import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import netvis.data.DataController; import netvis.data.NormaliseFactory; import netvis.data.NormaliseFactory.Normaliser; import netvis.data.UndoAction; import netvis.data.UndoController; import netvis.data.model.Packet; import netvis.ui.OpenGLPanel; import netvis.ui.VisControlsContainer; import netvis.util.ColourPalette; import com.jogamp.opengl.util.gl2.GLUT;
GLUT.BITMAP_HELVETICA_12, normPasses.get(visHighlighted).denormalise((double)i/10) ); } } } @Override public void dispose(GLAutoDrawable arg0) { } @Override public void init(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); // Global settings. gl.glEnable(GL2.GL_POINT_SMOOTH); gl.glEnable(GL2.GL_LINE_SMOOTH); gl.glShadeModel(GL2.GL_SMOOTH); gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glScaled(1.8, 1.8, 1); gl.glTranslated(-0.5, -0.5, 0); gl.glClearColor(0.7f, 0.7f, 0.7f, 1); gl.glLineWidth(1); glut = new GLUT(); } @Override public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) { } @Override protected JPanel createControls() { JPanel panel = new JPanel(); int PAST_MIN = 1, PAST_MAX = 20, PAST_INIT = 1; final JSlider timeFilter = new JSlider(JSlider.HORIZONTAL, PAST_MIN, PAST_MAX, PAST_INIT); timeFilter.setMajorTickSpacing(3); timeFilter.setMinorTickSpacing(1); timeFilter.setPaintTicks(true); timeFilter.setPaintLabels(true); Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); labelTable.put( new Integer( 2 ), new JLabel("1 Min") ); labelTable.put( new Integer( 6 ), new JLabel("3 Min") ); labelTable.put( new Integer( PAST_MAX ), new JLabel("All") ); timeFilter.setLabelTable( labelTable ); timeFilter.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { pastLimit = timeFilter.getValue()*30; if (timeFilter.getValue() == 20) pastLimit = 1000; } }); Box box = Box.createHorizontalBox(); box.add(timeFilter); panel.add(box); String[] normNames = new String[NormaliseFactory.INSTANCE.getNormalisers().size()]; for (int i = 0; i < normNames.length; i++) normNames[i] = NormaliseFactory.INSTANCE.getNormaliser(i).name(); final JComboBox<String> normaliserBox = new JComboBox<String>(normNames); normaliserBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { colorPasser = normaliserBox.getSelectedIndex(); } }); box = Box.createHorizontalBox(); box.add(new JLabel("Colour")); box.add(normaliserBox); panel.add(box); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); return panel; } private void drawActivityBar(GL2 gl, float xc, float yc, float radius) { gl.glBegin(GL2.GL_POLYGON); gl.glVertex2f(xc+radius, yc+0.01f); gl.glVertex2f(xc+radius, yc); gl.glVertex2f(xc-radius, yc); gl.glVertex2f(xc-radius, yc+0.01f); gl.glEnd(); } @Override public String getName() { return "Data Flow"; } @Override public String getDescription() { return getName() + "\n\n" + "Saturation indicates time - grey lines are " + "past lines, coloured lines are more recent.\n" + "You can follow a packet by it's colour.\n" + "The red bars show traffic volume. " + "They shrink with each iteration by some percentage\n" + "and grow linearly with each packet, up to a limit.\n" + "Hover over an axis to show the scale.\n" + "Click an axis to switch to the distribution visualisation " + "for that attribute."; } @Override public void mouseClicked(MouseEvent e) { double xClicked = (double)e.getX()/this.getSize().getWidth(); int visChosen = (int)(xClicked * normPasses.size()); VisualisationsController vc = VisualisationsController.GetInstance(); vc.ActivateById(0); vc.getVList().get(0).setState(visChosen);
UndoController.INSTANCE.addUndoMove(new UndoAction(){
3
gaffo/scumd
src/test/java/com/asolutions/scmsshd/commands/git/SCMCommandTest.java
[ "public class ServerSession extends AbstractSession {\n\n private Timer timer;\n private TimerTask authTimerTask;\n private State state = State.ReceiveKexInit;\n private String username;\n private int maxAuthRequests = 20;\n private int nbAuthRequests;\n private int authTimeout = 10 * 60 * 1000...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.apache.sshd.server.CommandFactory.ExitCallback; import org.apache.sshd.server.session.ServerSession; import org.jmock.Expectations; import org.junit.Before; import org.junit.Test; import com.asolutions.MockTestCase; import com.asolutions.scmsshd.authorizors.AuthorizationLevel; import com.asolutions.scmsshd.commands.FilteredCommand; import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter; import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.git; public class SCMCommandTest extends MockTestCase { private static final String USERNAME = "username"; private static final String PROJECT = "proj-2"; private FilteredCommand filteredCommand; private IProjectAuthorizer mockProjectAuthorizer; private ServerSession mockSession;
private IPathToProjectNameConverter mockPathToProjectConverter;
5
JoostvDoorn/GlutenVrijApp
app/src/main/java/com/joostvdoorn/glutenvrij/scanner/core/oned/Code128Reader.java
[ "public final class BarcodeFormat {\n\n // No, we can't use an enum here. J2ME doesn't support it.\n\n private static final Hashtable VALUES = new Hashtable();\n\n /** Aztec 2D barcode format. */\n public static final BarcodeFormat AZTEC = new BarcodeFormat(\"AZTEC\");\n\n /** CODABAR 1D format. */\n public s...
import com.joostvdoorn.glutenvrij.scanner.core.BarcodeFormat; import com.joostvdoorn.glutenvrij.scanner.core.ChecksumException; import com.joostvdoorn.glutenvrij.scanner.core.FormatException; import com.joostvdoorn.glutenvrij.scanner.core.NotFoundException; import com.joostvdoorn.glutenvrij.scanner.core.Result; import com.joostvdoorn.glutenvrij.scanner.core.ResultPoint; import com.joostvdoorn.glutenvrij.scanner.core.common.BitArray; import java.util.Hashtable;
{2, 2, 1, 2, 1, 3}, {2, 2, 1, 3, 1, 2}, // 10 {2, 3, 1, 2, 1, 2}, {1, 1, 2, 2, 3, 2}, {1, 2, 2, 1, 3, 2}, {1, 2, 2, 2, 3, 1}, {1, 1, 3, 2, 2, 2}, // 15 {1, 2, 3, 1, 2, 2}, {1, 2, 3, 2, 2, 1}, {2, 2, 3, 2, 1, 1}, {2, 2, 1, 1, 3, 2}, {2, 2, 1, 2, 3, 1}, // 20 {2, 1, 3, 2, 1, 2}, {2, 2, 3, 1, 1, 2}, {3, 1, 2, 1, 3, 1}, {3, 1, 1, 2, 2, 2}, {3, 2, 1, 1, 2, 2}, // 25 {3, 2, 1, 2, 2, 1}, {3, 1, 2, 2, 1, 2}, {3, 2, 2, 1, 1, 2}, {3, 2, 2, 2, 1, 1}, {2, 1, 2, 1, 2, 3}, // 30 {2, 1, 2, 3, 2, 1}, {2, 3, 2, 1, 2, 1}, {1, 1, 1, 3, 2, 3}, {1, 3, 1, 1, 2, 3}, {1, 3, 1, 3, 2, 1}, // 35 {1, 1, 2, 3, 1, 3}, {1, 3, 2, 1, 1, 3}, {1, 3, 2, 3, 1, 1}, {2, 1, 1, 3, 1, 3}, {2, 3, 1, 1, 1, 3}, // 40 {2, 3, 1, 3, 1, 1}, {1, 1, 2, 1, 3, 3}, {1, 1, 2, 3, 3, 1}, {1, 3, 2, 1, 3, 1}, {1, 1, 3, 1, 2, 3}, // 45 {1, 1, 3, 3, 2, 1}, {1, 3, 3, 1, 2, 1}, {3, 1, 3, 1, 2, 1}, {2, 1, 1, 3, 3, 1}, {2, 3, 1, 1, 3, 1}, // 50 {2, 1, 3, 1, 1, 3}, {2, 1, 3, 3, 1, 1}, {2, 1, 3, 1, 3, 1}, {3, 1, 1, 1, 2, 3}, {3, 1, 1, 3, 2, 1}, // 55 {3, 3, 1, 1, 2, 1}, {3, 1, 2, 1, 1, 3}, {3, 1, 2, 3, 1, 1}, {3, 3, 2, 1, 1, 1}, {3, 1, 4, 1, 1, 1}, // 60 {2, 2, 1, 4, 1, 1}, {4, 3, 1, 1, 1, 1}, {1, 1, 1, 2, 2, 4}, {1, 1, 1, 4, 2, 2}, {1, 2, 1, 1, 2, 4}, // 65 {1, 2, 1, 4, 2, 1}, {1, 4, 1, 1, 2, 2}, {1, 4, 1, 2, 2, 1}, {1, 1, 2, 2, 1, 4}, {1, 1, 2, 4, 1, 2}, // 70 {1, 2, 2, 1, 1, 4}, {1, 2, 2, 4, 1, 1}, {1, 4, 2, 1, 1, 2}, {1, 4, 2, 2, 1, 1}, {2, 4, 1, 2, 1, 1}, // 75 {2, 2, 1, 1, 1, 4}, {4, 1, 3, 1, 1, 1}, {2, 4, 1, 1, 1, 2}, {1, 3, 4, 1, 1, 1}, {1, 1, 1, 2, 4, 2}, // 80 {1, 2, 1, 1, 4, 2}, {1, 2, 1, 2, 4, 1}, {1, 1, 4, 2, 1, 2}, {1, 2, 4, 1, 1, 2}, {1, 2, 4, 2, 1, 1}, // 85 {4, 1, 1, 2, 1, 2}, {4, 2, 1, 1, 1, 2}, {4, 2, 1, 2, 1, 1}, {2, 1, 2, 1, 4, 1}, {2, 1, 4, 1, 2, 1}, // 90 {4, 1, 2, 1, 2, 1}, {1, 1, 1, 1, 4, 3}, {1, 1, 1, 3, 4, 1}, {1, 3, 1, 1, 4, 1}, {1, 1, 4, 1, 1, 3}, // 95 {1, 1, 4, 3, 1, 1}, {4, 1, 1, 1, 1, 3}, {4, 1, 1, 3, 1, 1}, {1, 1, 3, 1, 4, 1}, {1, 1, 4, 1, 3, 1}, // 100 {3, 1, 1, 1, 4, 1}, {4, 1, 1, 1, 3, 1}, {2, 1, 1, 4, 1, 2}, {2, 1, 1, 2, 1, 4}, {2, 1, 1, 2, 3, 2}, // 105 {2, 3, 3, 1, 1, 1, 2} }; private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); private static final int CODE_SHIFT = 98; private static final int CODE_CODE_C = 99; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_A = 101; private static final int CODE_FNC_1 = 102; private static final int CODE_FNC_2 = 97; private static final int CODE_FNC_3 = 96; private static final int CODE_FNC_4_A = 101; private static final int CODE_FNC_4_B = 100; private static final int CODE_START_A = 103; private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_STOP = 106;
private static int[] findStartPattern(BitArray row) throws NotFoundException {
6
JEEventStore/JEEventStore
core/src/test/java/org/jeeventstore/notifier/AsyncEventStoreCommitNotifierTest.java
[ "public interface EventStoreCommitNotification {\n\n /**\n * Returns the change set that has been committed to the event store.\n * \n * @return the committed {@link ChangeSet}\n */\n ChangeSet changes();\n \n}", "public interface EventStoreCommitNotifier {\n\n /**\n * Notifies al...
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jeeventstore.ChangeSet; import org.jeeventstore.store.TestChangeSet; import org.jeeventstore.tests.DefaultDeployment; import static org.testng.Assert.*; import org.testng.annotations.Test; import org.jeeventstore.EventStoreCommitNotification; import org.jeeventstore.EventStoreCommitNotifier; import java.io.File; import java.util.UUID; import javax.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter;
/* * Copyright (c) 2013-2014 Red Rainbow IT Solutions GmbH, Germany * * 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 org.jeeventstore.notifier; public class AsyncEventStoreCommitNotifierTest extends AbstractEventStoreCommitNotifierTest { @Deployment public static Archive<?> deployment() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "test.ear") .addAsModule(ShrinkWrap.create(JavaArchive.class, "ejb.jar") .addAsManifestResource(new File("src/test/resources/META-INF/beans.xml")) .addAsManifestResource( new File("src/test/resources/META-INF/ejb-jar-AsyncEventStoreCommitNotifierTest.xml"), "ejb-jar.xml") .addPackage(AsyncEventStoreCommitNotifier.class.getPackage())
.addPackage(ChangeSet.class.getPackage())
2
UweTrottmann/thetvdb-java
src/main/java/com/uwetrottmann/thetvdb/TheTvdb.java
[ "public interface TheTvdbAuthentication {\n\n String PATH_LOGIN = \"login\";\n\n /**\n * Returns a session token to be included in the rest of the requests. Note that API key authentication is required\n * for all subsequent requests and user auth is required for routes in the User section.\n */\n...
import com.uwetrottmann.thetvdb.services.TheTvdbAuthentication; import com.uwetrottmann.thetvdb.services.TheTvdbEpisodes; import com.uwetrottmann.thetvdb.services.TheTvdbLanguages; import com.uwetrottmann.thetvdb.services.TheTvdbSearch; import com.uwetrottmann.thetvdb.services.TheTvdbSeries; import com.uwetrottmann.thetvdb.services.TheTvdbUpdated; import com.uwetrottmann.thetvdb.services.TheTvdbUser; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import javax.annotation.Nullable;
package com.uwetrottmann.thetvdb; @SuppressWarnings("WeakerAccess") public class TheTvdb { public static final String API_HOST = "api.thetvdb.com"; public static final String API_URL = "https://" + API_HOST + "/"; public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language"; public static final String HEADER_AUTHORIZATION = "Authorization"; @Nullable private OkHttpClient okHttpClient; @Nullable private Retrofit retrofit; private String apiKey; @Nullable private String currentJsonWebToken; /** * Create a new manager instance. */ public TheTvdb(String apiKey) { this.apiKey = apiKey; } public String apiKey() { return apiKey; } public void apiKey(String apiKey) { this.apiKey = apiKey; } @Nullable public String jsonWebToken() { return currentJsonWebToken; } public void jsonWebToken(@Nullable String value) { this.currentJsonWebToken = value; } /** * Creates a {@link Retrofit.Builder} that sets the base URL, adds a Gson converter and sets {@link * #okHttpClient()} as its client. * * @see #okHttpClient() */ protected Retrofit.Builder retrofitBuilder() { return new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient()); } /** * Returns the default OkHttp client instance. It is strongly recommended to override this and use your app * instance. * * @see #setOkHttpClientDefaults(OkHttpClient.Builder) */ protected synchronized OkHttpClient okHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); setOkHttpClientDefaults(builder); okHttpClient = builder.build(); } return okHttpClient; } /** * Adds a network interceptor to add version and auth headers and * an authenticator to automatically login using the API key. */ protected void setOkHttpClientDefaults(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new TheTvdbInterceptor(this)) .authenticator(new TheTvdbAuthenticator(this)); } /** * Return the {@link Retrofit} instance. If called for the first time builds the instance. */ protected Retrofit getRetrofit() { if (retrofit == null) { retrofit = retrofitBuilder().build(); } return retrofit; } /** * Obtaining and refreshing your JWT token. */ public TheTvdbAuthentication authentication() { return getRetrofit().create(TheTvdbAuthentication.class); } /** * Information about a specific episode. */ public TheTvdbEpisodes episodes() { return getRetrofit().create(TheTvdbEpisodes.class); } /** * Available languages and information. */ public TheTvdbLanguages languages() { return getRetrofit().create(TheTvdbLanguages.class); } /** * Information about a specific series. */ public TheTvdbSeries series() { return getRetrofit().create(TheTvdbSeries.class); } /** * Search for a particular series. */ public TheTvdbSearch search() { return getRetrofit().create(TheTvdbSearch.class); } /** * Retrieve series which were recently updated. */ public TheTvdbUpdated updated() { return getRetrofit().create(TheTvdbUpdated.class); } /** * Routes for handling user data. */
public TheTvdbUser user() {
6
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/ThompsonAutomatonBuilder.java
[ "public interface TokenType {\n\n\tboolean error();\n\tboolean accept();\n\n}", "static class EpsilonTransition extends BasicTransition implements EventlessTransition {\n\n\tpublic EpsilonTransition(State target) {\n\t\tsuper(target);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new StringBuilder...
import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.GenericAutomaton.EpsilonTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.ExactTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.RangeTransition; import com.almondtools.rexlex.automaton.GenericAutomaton.State; import com.almondtools.rexlex.automaton.ThompsonAutomatonBuilder.ThompsonAutomaton; import net.amygdalum.regexparser.AlternativesNode; import net.amygdalum.regexparser.AnyCharNode; import net.amygdalum.regexparser.BoundedLoopNode; import net.amygdalum.regexparser.CharClassNode; import net.amygdalum.regexparser.CompClassNode; import net.amygdalum.regexparser.ConcatNode; import net.amygdalum.regexparser.EmptyNode; import net.amygdalum.regexparser.GroupNode; import net.amygdalum.regexparser.OptionalNode; import net.amygdalum.regexparser.RangeCharNode; import net.amygdalum.regexparser.RegexNode; import net.amygdalum.regexparser.RegexNodeVisitor; import net.amygdalum.regexparser.SingleCharNode; import net.amygdalum.regexparser.SpecialCharClassNode; import net.amygdalum.regexparser.StringNode; import net.amygdalum.regexparser.UnboundedLoopNode;
package com.almondtools.rexlex.automaton; public class ThompsonAutomatonBuilder implements RegexNodeVisitor<ThompsonAutomaton>, AutomatonBuilder { public ThompsonAutomatonBuilder() { } public static ThompsonAutomaton match(char value) { GenericAutomaton automaton = new GenericAutomaton();
State s = new State();
4
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/complexscripts/scripts/ScriptProcessor.java
[ "public class GlyphSubstitutionTable extends GlyphTable {\n\n /** single substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_SINGLE = 1;\n /** multiple substitution subtable type */\n public static final int GSUB_LOOKUP_TYPE_MULTIPLE = 2;\n /** alternate substitution subtable type */\n pu...
import com.jaredrummler.fontreader.fonts.GlyphSubstitutionTable; import com.jaredrummler.fontreader.truetype.GlyphTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphDefinitionTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphPositioningTable; import com.jaredrummler.fontreader.complexscripts.util.CharScript; import com.jaredrummler.fontreader.util.GlyphSequence; import com.jaredrummler.fontreader.util.ScriptContextTester; import java.util.Arrays; import java.util.HashMap; import java.util.Map;
/* * Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.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.jaredrummler.fontreader.complexscripts.scripts; /** * <p>Abstract script processor base class for which an implementation of the substitution and positioning methods * must be supplied.</p> * * <p>This work was originally authored by Glenn Adams (gadams@apache.org).</p> */ public abstract class ScriptProcessor { private final String script; private final Map<AssembledLookupsKey, GlyphTable.UseSpec[]> assembledLookups; private static Map<String, ScriptProcessor> processors = new HashMap<String, ScriptProcessor>(); /** * Instantiate a script processor. * * @param script * a script identifier */ protected ScriptProcessor(String script) { if ((script == null) || (script.length() == 0)) { throw new IllegalArgumentException("script must be non-empty string"); } else { this.script = script; this.assembledLookups = new HashMap<>(); } } /** @return script identifier */ public final String getScript() { return script; } /** * Obtain script specific required substitution features. * * @return array of suppported substitution features or null */ public abstract String[] getSubstitutionFeatures(); /** * Obtain script specific optional substitution features. * * @return array of suppported substitution features or null */ public String[] getOptionalSubstitutionFeatures() { return new String[0]; } /** * Obtain script specific substitution context tester. * * @return substitution context tester or null */ public abstract ScriptContextTester getSubstitutionContextTester(); /** * Perform substitution processing using a specific set of lookup tables. * * @param gsub * the glyph substitution table that applies * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param lookups * a mapping from lookup specifications to glyph subtables to use for substitution processing * @return the substituted (output) glyph sequence */ public final GlyphSequence substitute(GlyphSubstitutionTable gsub, GlyphSequence gs, String script, String language, Map/*<LookupSpec,List<LookupTable>>>*/ lookups) { return substitute(gs, script, language, assembleLookups(gsub, getSubstitutionFeatures(), lookups), getSubstitutionContextTester()); } /** * Perform substitution processing using a specific set of ordered glyph table use specifications. * * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param usa * an ordered array of glyph table use specs * @param sct * a script specific context tester (or null) * @return the substituted (output) glyph sequence */ public GlyphSequence substitute(GlyphSequence gs, String script, String language, GlyphTable.UseSpec[] usa, ScriptContextTester sct) { assert usa != null; for (int i = 0, n = usa.length; i < n; i++) { GlyphTable.UseSpec us = usa[i]; gs = us.substitute(gs, script, language, sct); } return gs; } /** * Reorder combining marks in glyph sequence so that they precede (within the sequence) the base * character to which they are applied. N.B. In the case of RTL segments, marks are not reordered by this, * method since when the segment is reversed by BIDI processing, marks are automatically reordered to precede * their base glyph. * * @param gdef * the glyph definition table that applies * @param gs * an input glyph sequence * @param unscaledWidths * associated unscaled advance widths (also reordered) * @param gpa * associated glyph position adjustments (also reordered) * @param script * a script identifier * @param language * a language identifier * @return the reordered (output) glyph sequence */ public GlyphSequence reorderCombiningMarks(GlyphDefinitionTable gdef, GlyphSequence gs, int[] unscaledWidths, int[][] gpa, String script, String language) { return gs; } /** * Obtain script specific required positioning features. * * @return array of suppported positioning features or null */ public abstract String[] getPositioningFeatures(); /** * Obtain script specific optional positioning features. * * @return array of suppported positioning features or null */ public String[] getOptionalPositioningFeatures() { return new String[0]; } /** * Obtain script specific positioning context tester. * * @return positioning context tester or null */ public abstract ScriptContextTester getPositioningContextTester(); /** * Perform positioning processing using a specific set of lookup tables. * * @param gpos * the glyph positioning table that applies * @param gs * an input glyph sequence * @param script * a script identifier * @param language * a language identifier * @param fontSize * size in device units * @param lookups * a mapping from lookup specifications to glyph subtables to use for positioning processing * @param widths * array of default advancements for each glyph * @param adjustments * accumulated adjustments array (sequence) of 4-tuples of placement [PX,PY] and advance [AX,AY] adjustments, in * that order, * with one 4-tuple for each element of glyph sequence * @return true if some adjustment is not zero; otherwise, false */
public final boolean position(GlyphPositioningTable gpos, GlyphSequence gs, String script, String language,
3
SOM-Research/EMFtoCSP
plugins/fr.inria.atlanmod.emftocsp.emf/src/fr/inria/atlanmod/emftocsp/emf/impl/UmlModelBuilder.java
[ "public interface IModelReader<R, P, C, AS, AT, OP> {\n\n\tpublic R getModelResource(); \n\n\tpublic List<P> getPackages();\n\n\tpublic List<C> getClasses();\n\n\tpublic List<String> getClassesNames();\n\n\tpublic List<AT> getClassAttributes(C c);\n\n\tpublic List<OP> getClassOperations(C c); \n\n\tpublic List<C> ...
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.uml2.uml.Association; import org.eclipse.uml2.uml.Class; import org.eclipse.uml2.uml.Property; import org.eclipse.uml2.uml.UMLFactory; import org.eclipse.uml2.uml.UMLPackage; import org.eclipse.uml2.uml.resource.UMLResource; import org.eclipse.uml2.uml.resources.util.UMLResourcesUtil; import com.parctechnologies.eclipse.CompoundTerm; import fr.inria.atlanmod.emftocsp.IModelReader; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EAttributeUMLAdapter; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EClassUMLAdapter; import fr.inria.atlanmod.emftocsp.adapters.umlImpl.EReferenceUMLAdapter; import fr.inria.atlanmod.emftocsp.modelbuilder.AssocStruct; import fr.inria.atlanmod.emftocsp.modelbuilder.Field; import fr.inria.atlanmod.emftocsp.modelbuilder.ObjectStruct; import fr.inria.atlanmod.emftocsp.modelbuilder.Point;
/******************************************************************************* * Copyright (c) 2013 INRIA Rennes Bretagne-Atlantique. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * INRIA Rennes Bretagne-Atlantique - initial API and implementation *******************************************************************************/ package fr.inria.atlanmod.emftocsp.emf.impl; /** * @author <a href="mailto:amine.benelallam@inria.fr">Amine Benelallam</a> * */ public class UmlModelBuilder extends EmfModelBuilder{ public UmlModelBuilder() { }
public UmlModelBuilder(IModelReader<Resource, EPackage, EClass, EAssociation, EAttribute, EOperation> modelReader, CompoundTerm ct){
0
mpalourdio/SpringBootTemplate
src/test/java/com/mpalourdio/springboottemplate/controllers/MiscControllerTest.java
[ "@ExtendWith(SpringExtension.class)\n@TestPropertySource(locations = \"classpath:test.properties\")\n@Import({BeansFactory.class})\npublic abstract class AbstractTestRunner {\n\n protected Task task;\n protected People people;\n\n protected void initializeData() {\n task = new Task();\n task....
import com.mpalourdio.springboottemplate.AbstractTestRunner; import com.mpalourdio.springboottemplate.json.Account; import com.mpalourdio.springboottemplate.json.AccountDecorator; import com.mpalourdio.springboottemplate.json.Context; import com.mpalourdio.springboottemplate.mediatype.MediaType; import com.mpalourdio.springboottemplate.service.ToSerialize; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/* * 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.mpalourdio.springboottemplate.controllers; @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureTestDatabase
class MiscControllerTest extends AbstractTestRunner {
0
DigiArea/es5-model
com.digiarea.es5/src/com/digiarea/es5/FunctionDeclaration.java
[ "public abstract class Statement extends Node {\r\n\r\n Statement() {\r\n super();\r\n }\r\n\r\n Statement(JSDocComment jsDocComment, int posBegin, int posEnd) {\r\n super(jsDocComment, posBegin, posEnd);\r\n }\r\n\r\n}\r", "public class Parameter extends Expression {\r\n\r\n /** \r\n...
import com.digiarea.es5.Statement; import com.digiarea.es5.Parameter; import com.digiarea.es5.NodeList; import com.digiarea.es5.Block; import com.digiarea.es5.JSDocComment; import com.digiarea.es5.visitor.VoidVisitor; import com.digiarea.es5.visitor.GenericVisitor;
package com.digiarea.es5; /** * The Class FunctionDeclaration. */ public class FunctionDeclaration extends Statement { /** * The name. */ private String name; /** * The parameters. */ private NodeList<Parameter> parameters; /** * The body. */ private Block body; public String getName() { return name; } public void setName(String name) { this.name = name; } public NodeList<Parameter> getParameters() { return parameters; } public void setParameters(NodeList<Parameter> parameters) { this.parameters = parameters; } public Block getBody() { return body; } public void setBody(Block body) { this.body = body; } FunctionDeclaration() { super(); } FunctionDeclaration(String name, NodeList<Parameter> parameters, Block body, JSDocComment jsDocComment, int posBegin, int posEnd) { super(jsDocComment, posBegin, posEnd); this.name = name; this.parameters = parameters; this.body = body; } @Override
public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {
5
jjhesk/LoyalNativeSlider
library/src/main/java/com/hkm/slider/SliderLayout.java
[ "public interface BaseAnimationInterface {\n\n /**\n * When the current item prepare to start leaving the screen.\n *\n * @param current view\n */\n void onPrepareCurrentItemLeaveScreen(View current);\n\n /**\n * The next item which will be shown in ViewPager/\n *\n * @param nex...
import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.support.annotation.IntDef; import android.support.v4.view.PagerAdapter; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.Interpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.hkm.slider.Animations.BaseAnimationInterface; import com.hkm.slider.Indicators.NumContainer; import com.hkm.slider.Indicators.PagerIndicator; import com.hkm.slider.SliderTypes.BaseSliderView; import com.hkm.slider.Transformers.BaseTransformer; import com.hkm.slider.Tricks.AnimationHelper; import com.hkm.slider.Tricks.ArrowControl; import com.hkm.slider.Tricks.FixedSpeedScroller; import com.hkm.slider.Tricks.InfinitePagerAdapter; import com.hkm.slider.Tricks.InfiniteViewPager; import com.hkm.slider.Tricks.MultiViewPager; import com.hkm.slider.Tricks.ViewPagerEx; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; import static com.hkm.slider.SliderLayout.PresentationConfig.Dots; import static com.hkm.slider.SliderLayout.PresentationConfig.Numbers; import static com.hkm.slider.SliderLayout.PresentationConfig.Smart; import static com.hkm.slider.SliderLayout.PresentationConfig.byVal;
} }; private Handler postHandler = new Handler(); private ImageView mButtonLeft, mButtonRight; private int mLWidthB, mRWidthB; private boolean mLopen, mRopen, button_side_function_flip = false; private ArrowControl arrow_instance; private void navigation_button_initialization() { mButtonLeft = (ImageView) findViewById(R.id.arrow_l); mButtonRight = (ImageView) findViewById(R.id.arrow_r); mButtonLeft.setImageResource(buttondl); mButtonRight.setImageResource(buttondr); arrow_instance = new ArrowControl(mButtonLeft, mButtonRight); mLWidthB = mButtonLeft.getDrawable().getIntrinsicWidth(); mRWidthB = mButtonRight.getDrawable().getIntrinsicWidth(); if (!sidebuttons) { arrow_instance.noSlideButtons(); } else { arrow_instance.setListeners( new OnClickListener() { @Override public void onClick(View v) { if (!button_side_function_flip) moveNextPosition(true); else movePrevPosition(true); } }, new OnClickListener() { @Override public void onClick(View v) { if (!button_side_function_flip) movePrevPosition(true); else moveNextPosition(true); } } ); } mLopen = mRopen = true; } private void notify_navigation_buttons() { arrow_instance.setTotal(mSliderAdapter.getCount()); int count = mSliderAdapter.getCount(); //DisplayMetrics m = getResources().getDisplayMetrics(); // final int width = m.widthPixels; final int end_close_left = -mLWidthB; final int end_close_right = mRWidthB; final int open_left = 0; final int open_right = 0; if (count <= 1) { postHandler.postDelayed(new Runnable() { @Override public void run() { if (mButtonLeft != null && mLopen) { mButtonLeft.animate().translationX(end_close_left); mLopen = false; } if (mButtonRight != null && mRopen) { mButtonRight.animate().translationX(end_close_right); mRopen = false; } } }, mTransitionAnimation); } else { postHandler.postDelayed(new Runnable() { @Override public void run() { if (mButtonLeft != null && !mLopen) { mButtonLeft.animate().translationX(open_left); mLopen = true; } if (mButtonRight != null && !mRopen) { mButtonRight.animate().translationX(open_right); mRopen = true; } } }, mTransitionAnimation); } } public SliderLayout setType(final @SliderLayoutType int t) { pagerType = t; return this; } public SliderLayout setActivity(final Activity t) { activity = t; return this; } private void pagerSetup() { mSliderAdapter = new SliderAdapter(mContext); if (pagerType == NONZOOMABLE) { PagerAdapter wrappedAdapter = new InfinitePagerAdapter(mSliderAdapter); mViewPager = (InfiniteViewPager) findViewById(R.id.daimajia_slider_viewpager); if (mPagerMargin > -1) { mViewPager.setMargin(mPagerMargin); } mViewPager.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_UP: recoverCycle(); break; } return false; } }); mViewPager.setAdapter(wrappedAdapter); } else if (pagerType == ZOOMABLE) { } mSliderAdapter.registerDataSetObserver(sliderDataObserver); }
public <TN extends NumContainer> void setNumLayout(final TN container) {
1
stridercheng/chatui
app/src/main/java/com/rance/chatui/adapter/ChatAdapter.java
[ "public class BaseViewHolder<M> extends RecyclerView.ViewHolder {\n\n public BaseViewHolder(View itemView) {\n super(itemView);\n }\n\n public void setData(M data) {\n\n }\n}", "public class ChatAcceptViewHolder extends BaseViewHolder<MessageInfo> {\n private static final String TAG = \"Chat...
import android.os.Handler; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.rance.chatui.adapter.holder.BaseViewHolder; import com.rance.chatui.adapter.holder.ChatAcceptViewHolder; import com.rance.chatui.adapter.holder.ChatSendViewHolder; import com.rance.chatui.enity.MessageInfo; import com.rance.chatui.util.Constants; import java.util.ArrayList; import java.util.List;
package com.rance.chatui.adapter; /** * 作者:Rance on 2016/11/29 10:46 * 邮箱:rance935@163.com */ public class ChatAdapter extends RecyclerView.Adapter<BaseViewHolder> { private onItemClickListener onItemClickListener; public Handler handler; private List<MessageInfo> messageInfoList; public ChatAdapter(List<MessageInfo> messageInfoList) { handler = new Handler(); this.messageInfoList = messageInfoList; } // @Override // public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { // BaseViewHolder viewHolder = null; // switch (viewType) { // case Constants.CHAT_ITEM_TYPE_LEFT: // viewHolder = new ChatAcceptViewHolder(parent, onItemClickListener, handler); // break; // case Constants.CHAT_ITEM_TYPE_RIGHT: // viewHolder = new ChatSendViewHolder(parent, onItemClickListener, handler); // break; // } // return viewHolder; // } // // @Override // public int getViewType(int position) { // return getAllData().get(position).getType(); // } public void addItemClickListener(onItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { BaseViewHolder viewHolder = null; switch (viewType) { case Constants.CHAT_ITEM_TYPE_LEFT: viewHolder = new ChatAcceptViewHolder(parent, onItemClickListener, handler); break; case Constants.CHAT_ITEM_TYPE_RIGHT:
viewHolder = new ChatSendViewHolder(parent, onItemClickListener, handler);
2
rubenlagus/Tsupport
TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java
[ "public class AndroidUtilities {\n\n private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<>();\n private static int prevOrientation = -10;\n private static boolean waitingForSms = false;\n private static final Object smsLock = new Object();\n\n public static int statusBarHei...
import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.InputType; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.TLRPC; import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.BaseFragment;
/* * This is the source code of Telegram for Android v. 1.3.2. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013. */ package org.telegram.ui; public class ChangeChatNameActivity extends BaseFragment { private EditText firstNameField; private View headerLabelView; private int chat_id; private View doneButton; private final static int done_button = 1; public ChangeChatNameActivity(Bundle args) { super(args); } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); chat_id = getArguments().getInt("chat_id", 0); return true; } @Override public View createView(LayoutInflater inflater) { if (fragmentView == null) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == done_button) { if (firstNameField.getText().length() != 0) { saveName(); finishFragment(); } } } }); ActionBarMenu menu = actionBar.createMenu(); doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
TLRPC.Chat currentChat = MessagesController.getInstance().getChat(chat_id);
3
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/Episode.java
[ "public class ProfileManager {\n\n public static final String JS_SUBSCRIBED_PODCASTS = \"subscribedPodcasts\";\n public static final String JS_SUBSCRIBED_STATIONS = \"subscribedStations\";\n public static final String JS_RECENT_STATIONS = \"recentStations\";\n\n public static ProfileManager profileManag...
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.format.Formatter; import com.chickenkiller.upods2.controllers.app.ProfileManager; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import com.chickenkiller.upods2.utils.GlobalUtils; import com.chickenkiller.upods2.utils.Logger; import com.chickenkiller.upods2.utils.MediaUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 8/31/15. */ public class Episode extends Track { private static final String TABLE = "episodes"; private static String EPISODE_LOG = "EPISODE"; private String summary; private String length; private String duration; private String date; private String pathOnDisk; //Not in DB public boolean isNew; public boolean isDownloaded; public Episode() { super(); this.summary = ""; this.length = ""; this.duration = ""; this.date = ""; this.pathOnDisk = ""; this.isNew = false; this.isDownloaded = false; } public Episode(JSONObject jsonItem) { this(); try { this.title = jsonItem.has("title") ? jsonItem.getString("title") : ""; this.title = this.title.replace("\n", "").trim(); this.summary = jsonItem.has("summary") ? jsonItem.getString("summary") : ""; this.length = jsonItem.has("length") ? jsonItem.getString("length") : ""; this.duration = jsonItem.has("duration") ? jsonItem.getString("duration") : ""; this.date = jsonItem.has("date") ? jsonItem.getString("date") : ""; this.pathOnDisk = jsonItem.has("pathOnDisk") ? jsonItem.getString("pathOnDisk") : ""; this.audeoUrl = jsonItem.has("audeoUrl") ? jsonItem.getString("audeoUrl") : ""; } catch (JSONException e) {
Logger.printError(EPISODE_LOG, "Can't parse episod from json");
3
iloveeclipse/anyedittools
AnyEditTools/src/de/loskutov/anyedit/actions/compare/CompareWithAction.java
[ "public class AnyEditToolsPlugin extends AbstractUIPlugin {\n\n private static AnyEditToolsPlugin plugin;\n\n private static boolean isSaveHookInitialized;\n\n /**\n * The constructor.\n */\n public AnyEditToolsPlugin() {\n super();\n if(plugin != null) {\n throw new Ill...
import org.eclipse.compare.CompareUI; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.HandlerUtil; import de.loskutov.anyedit.AnyEditToolsPlugin; import de.loskutov.anyedit.compare.AnyeditCompareInput; import de.loskutov.anyedit.compare.ContentWrapper; import de.loskutov.anyedit.compare.ExternalFileStreamContent; import de.loskutov.anyedit.compare.FileStreamContent; import de.loskutov.anyedit.compare.StreamContent; import de.loskutov.anyedit.compare.TextStreamContent; import de.loskutov.anyedit.ui.editor.AbstractEditor;
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.anyedit.actions.compare; /** * @author Andrey * */ public abstract class CompareWithAction extends AbstractHandler implements IObjectActionDelegate { protected ContentWrapper selectedContent; protected AbstractEditor editor; public CompareWithAction() { super(); editor = new AbstractEditor(null); } @Override public Object execute(final ExecutionEvent event) throws ExecutionException { IWorkbenchPart activePart = HandlerUtil.getActivePart(event); Action dummyAction = new Action(){ @Override public String getId() { return event.getCommand().getId(); } }; setActivePart(dummyAction, activePart); ISelection currentSelection = HandlerUtil.getCurrentSelection(event); selectionChanged(dummyAction, currentSelection); if(dummyAction.isEnabled()) { run(dummyAction); } return null; } @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) { editor = new AbstractEditor(targetPart); } @Override public void run(IAction action) { StreamContent left = createLeftContent(); if (left == null) { return; } try { StreamContent right = createRightContent(left); if (right == null) { left.dispose(); return; } compare(left, right); } catch (CoreException e) { left.dispose(); AnyEditToolsPlugin.logError("Can't perform compare", e); } finally { selectedContent = null; editor = null; } } protected StreamContent createLeftContent() { if (!editor.isDisposed()) { String selectedText = editor.getSelectedText(); if (selectedText != null && selectedText.length() != 0) { return new TextStreamContent(selectedContent, editor); } } return createContent(selectedContent); } protected abstract StreamContent createRightContent(StreamContent left) throws CoreException; protected final StreamContent createContent(ContentWrapper content) { if (content == null) { return null; } /// XXX should we really first check for the document??? if (editor.getDocument() != null) { return new TextStreamContent(content, editor); } return createContentFromFile(content); } protected static final StreamContent createContentFromFile(ContentWrapper content) { if (content == null) { return null; } if (content.getIFile() != null) {
return new FileStreamContent(content);
4
recoilme/freemp
app/src/main/java/org/freemp/droid/player/ActPlayer.java
[ "public class ClsTrack implements Serializable {\n\n private static final long serialVersionUID = 1L;\n private String artist;\n private String title;\n private String album;\n private String composer;\n private int year;\n private int track;\n private int duration;\n private String path;...
import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.format.Time; import android.view.Display; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.androidquery.AQuery; import com.androidquery.util.AQUtility; import com.flurry.android.FlurryAgent; import org.freemp.droid.ClsTrack; import org.freemp.droid.Constants; import org.freemp.droid.FileUtils; import org.freemp.droid.MediaUtils; import org.freemp.droid.R; import org.freemp.droid.UpdateUtils; import org.freemp.droid.playlist.ActPlaylist; import java.util.ArrayList; import java.util.Collections; import java.util.Random;
package org.freemp.droid.player; /** * Created with IntelliJ IDEA. * User: recoilme * Date: 28/11/13 * Time: 15:10 * To change this template use File | Settings | File Templates. */ public class ActPlayer extends AppCompatActivity implements InterfacePlayer, ActivityCompat.OnRequestPermissionsResultCallback { public static final int LOGIN_RESULT = 101; private static final int PLAYLIST_CODE = 100; public static int selected = -1; private static Random randomGenerator; private AQuery aq; private AdpPlayer adapter;
private ArrayList<ClsTrack> items;
0
jenkinsci/plugin-compat-tester
plugins-compat-tester/src/test/java/org/jenkins/tools/test/PluginCompatTesterTest.java
[ "public class PCTPlugin {\n private String name;\n private final String groupId;\n private VersionNumber version;\n\n public PCTPlugin(String name, String groupId, VersionNumber version) {\n this.name = name;\n this.groupId = groupId;\n this.version = version;\n }\n\n public S...
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.io.File; import org.jenkins.tools.test.model.PCTPlugin; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jenkins.tools.test.exception.PomExecutionException; import org.jenkins.tools.test.model.MavenCoordinates; import org.jenkins.tools.test.model.PluginCompatReport; import org.jenkins.tools.test.model.PluginCompatResult; import org.jenkins.tools.test.model.PluginCompatTesterConfig; import org.jenkins.tools.test.model.PluginInfos; import org.jenkins.tools.test.model.PomData; import org.jenkins.tools.test.model.TestStatus; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; import org.springframework.core.io.ClassPathResource; import com.google.common.collect.ImmutableList; import hudson.util.VersionNumber;
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc. * * 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 org.jenkins.tools.test; /** * Main test class for plugin compatibility test frontend * * @author Frederic Camblor */ public class PluginCompatTesterTest { private static final String MAVEN_INSTALLATION_WINDOWS = "C:\\Jenkins\\tools\\hudson.tasks.Maven_MavenInstallation\\mvn\\bin\\mvn.cmd"; private static final String REPORT_FILE = String.format("%s%sreports%sPluginCompatReport.xml", System.getProperty("java.io.tmpdir"), File.separator, File.separator); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { SCMManagerFactory.getInstance().start(); File file = Paths.get(REPORT_FILE).toFile(); if (file.exists()) { FileUtils.deleteQuietly(file); } } @After public void tearDown() { SCMManagerFactory.getInstance().stop(); } @Ignore("TODO broken by https://github.com/jenkinsci/active-directory-plugin/releases/tag/active-directory-2.17; figure out how to pin a version") @Test public void testWithUrl() throws Throwable { PluginCompatTesterConfig config = getConfig(ImmutableList.of("active-directory")); config.setStoreAll(true); PluginCompatTester tester = new PluginCompatTester(config);
PluginCompatReport report = tester.testPlugins();
3
ErnestOrt/Trampoline
trampoline/src/main/java/org/ernest/applications/trampoline/controller/InstancesController.java
[ "@Component\npublic class InstanceInfoCollector {\n\n private static final Logger log = LoggerFactory.getLogger(InstanceInfoCollector.class);\n\n @Autowired\n EcosystemManager ecosystemManager;\n\n public InstanceGitInfo getInfo(String idInstance) {\n InstanceGitInfo info = new InstanceGitInfo();...
import org.ernest.applications.trampoline.collectors.InstanceInfoCollector; import org.ernest.applications.trampoline.entities.*; import org.ernest.applications.trampoline.exceptions.*; import org.ernest.applications.trampoline.services.EcosystemManager; import org.ernest.applications.trampoline.collectors.MetricsCollector; import org.ernest.applications.trampoline.collectors.TraceCollector; import org.ernest.applications.trampoline.utils.PortsChecker; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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 java.util.List; import java.util.Queue;
package org.ernest.applications.trampoline.controller; @Controller @RequestMapping("/instances") public class InstancesController { private static final String INSTANCES_VIEW = "instances"; @Autowired EcosystemManager ecosystemManager; @Autowired MetricsCollector metricsCollector; @Autowired TraceCollector traceCollector; @Autowired InstanceInfoCollector instanceInfoCollector; @RequestMapping("") public String getInstanceView(Model model) { Ecosystem ecosystem = ecosystemManager.getEcosystem(); model.addAttribute("microservices", ecosystem.getMicroservices()); model.addAttribute("externalInstances", ecosystem.getExternalInstances()); model.addAttribute("instances", ecosystem.getInstances()); model.addAttribute("microservicesgroups", ecosystem.getMicroservicesGroups()); return INSTANCES_VIEW; } @RequestMapping(value= "/health", method = RequestMethod.POST) @ResponseBody public String checkStatusInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return ecosystemManager.getStatusInstance(id); } @RequestMapping(value= "/instanceinfo", method = RequestMethod.POST) @ResponseBody public Microservice getInstanceInfo(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return ecosystemManager.getEcosystem().getMicroservices().stream().filter(m-> m.getId().equals(id)).findFirst().get(); } @RequestMapping(value= "/startinstance", method = RequestMethod.POST) @ResponseBody public void startInstance(@RequestParam(value="id") String id, @RequestParam(value="port") String port, @RequestParam(value="vmArguments") String vmArguments) throws CreatingSettingsFolderException, ReadingEcosystemException, RunningMicroserviceScriptException, SavingEcosystemException, InterruptedException { ecosystemManager.startInstance(id, port, vmArguments, 0); } @RequestMapping(value= "/restartinstance", method = RequestMethod.POST) @ResponseBody public void restartInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException, ShuttingDownInstanceException, InterruptedException { ecosystemManager.restartInstance(id); } @RequestMapping(value= "/killinstance", method = RequestMethod.POST) @ResponseBody public void killInstance(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, SavingEcosystemException, ShuttingDownInstanceException { ecosystemManager.killInstance(id); } @RequestMapping(value= "/metrics", method = RequestMethod.POST) @ResponseBody public Queue<Metrics> getMetrics(@RequestParam(value="id") String id) { return metricsCollector.getInstanceMetrics(id); } @RequestMapping(value= "/traces", method = RequestMethod.POST) @ResponseBody public List<TraceActuator> getTraces(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException, JSONException { return traceCollector.getTraces(id); } @RequestMapping(value= "/info", method = RequestMethod.POST) @ResponseBody public InstanceGitInfo getInstanceInfoWhenDeployed(@RequestParam(value="id") String id) throws CreatingSettingsFolderException, ReadingEcosystemException { return instanceInfoCollector.getInfo(id); } @RequestMapping(value= "/checkport", method = RequestMethod.POST) @ResponseBody public boolean checkPort(@RequestParam(value="port") int port) throws CreatingSettingsFolderException, ReadingEcosystemException { boolean declaredInstanceOnPort = ecosystemManager.getEcosystem().getInstances().stream().anyMatch(i -> i.getPort().equals(String.valueOf(port)));
return declaredInstanceOnPort == false ? PortsChecker.available(port) : false;
4
mike10004/xvfb-manager-java
xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/XvfbManagerTest.java
[ "public class ProcessTrackerRule extends ExternalResource {\n\n private static final Duration DEFAULT_DESTROY_TIMEOUT = Duration.ofMillis(1000);\n\n private final TestWatcher watcher;\n private final AtomicBoolean passage;\n private BasicProcessTracker processTracker;\n private final Duration process...
import com.galenframework.rainbow4j.Rainbow4J; import com.galenframework.rainbow4j.Spectrum; import com.galenframework.rainbow4j.colorscheme.ColorDistribution; import com.github.mike10004.common.image.ImageInfo; import com.github.mike10004.common.image.ImageInfos; import com.github.mike10004.xvfbunittesthelp.ProcessTrackerRule; import io.github.mike10004.subprocess.ProcessMonitor; import io.github.mike10004.subprocess.ProcessResult; import io.github.mike10004.subprocess.ProcessTracker; import io.github.mike10004.subprocess.Subprocess; import com.github.mike10004.xvfbmanager.XvfbController.XWindow; import com.github.mike10004.xvfbunittesthelp.Assumptions; import com.github.mike10004.xvfbunittesthelp.PackageManager; import com.github.mike10004.xvfbunittesthelp.XDiagnosticRule; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.io.Files; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package com.github.mike10004.xvfbmanager; public class XvfbManagerTest { private static final int _PRESUMABLY_VACANT_DISPLAY_NUM = 88; @Rule public ProcessTrackerRule processTrackerRule = new ProcessTrackerRule(); @Rule public XDiagnosticRule diagnostic = Tests.isDiagnosticEnabled() ? new XDiagnosticRule() : XDiagnosticRule.getDisabledInstance(); @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test public void toDisplayValue() { System.out.println("\ntoDisplayValue\n"); assertEquals("display", ":123", XvfbManager.toDisplayValue(123)); } @Test(expected=IllegalArgumentException.class) public void toDisplayValue_negative() { System.out.println("\ntoDisplayValue_negative\n"); XvfbManager.toDisplayValue(-1); } @BeforeClass public static void checkPrerequisities() throws IOException { PackageManager packageManager = PackageManager.getInstance(); Iterable<String> requiredExecutables = Iterables.concat(Collections.singletonList("Xvfb"), DefaultXvfbController.getRequiredPrograms()); for (String program : requiredExecutables) { boolean installed = packageManager.queryCommandExecutable(program);
Assumptions.assumeTrue(program + " must be installed for these tests to be executed", installed);
2
ppasupat/web-entity-extractor-ACL2014
src/edu/stanford/nlp/semparse/open/model/feature/FeatureTypeHoleBased.java
[ "public class BrownClusterTable {\n public static class Options {\n @Option public String brownClusterFilename = null;\n }\n public static Options opts = new Options();\n\n public static Map<String, String> wordClusterMap;\n public static Map<String, Integer> wordFrequencyMap;\n \n public static void init...
import java.util.*; import edu.stanford.nlp.semparse.open.ling.BrownClusterTable; import edu.stanford.nlp.semparse.open.ling.LingData; import edu.stanford.nlp.semparse.open.ling.LingUtils; import edu.stanford.nlp.semparse.open.model.candidate.Candidate; import edu.stanford.nlp.semparse.open.model.candidate.CandidateGroup; import edu.stanford.nlp.semparse.open.model.tree.KNode; import edu.stanford.nlp.semparse.open.util.Multiset; import fig.basic.LogInfo; import fig.basic.Option;
package edu.stanford.nlp.semparse.open.model.feature; /** * Fire features based on the existence of holes in the selected nodes (or ancestors). * * This won't work for wildcard PathEntry. */ public class FeatureTypeHoleBased extends FeatureType { public static class Options { @Option public boolean holeUseTag = true; @Option public List<Integer> headerPrefixes = new ArrayList<>(); @Option public boolean headerBinary = false; } public static Options opts = new Options(); @Override public void extract(Candidate candidate) { // Do nothing } @Override public void extract(CandidateGroup group) { extractHoleBasedFeatures(group); } protected void extractHoleBasedFeatures(CandidateGroup group) { if (isAllowedDomain("hole") || isAllowedDomain("header")) {
List<KNode> currentKNodes = group.selectedNodes;
5
Azure/azure-storage-android
microsoft-azure-storage-test/src/com/microsoft/azure/storage/StorageUriTests.java
[ "public interface CloudTests {\n}", "public interface DevFabricTests {\n}", "public interface DevStoreTests {\n}", "public final class CloudBlobContainer {\n\n /**\n * Converts the ACL string to a BlobContainerPermissions object.\n * \n * @param aclString\n * A <code>String</code...
import com.microsoft.azure.storage.TestRunners.CloudTests; import com.microsoft.azure.storage.TestRunners.DevFabricTests; import com.microsoft.azure.storage.TestRunners.DevStoreTests; import com.microsoft.azure.storage.blob.CloudBlobClient; import com.microsoft.azure.storage.blob.CloudBlobContainer; import com.microsoft.azure.storage.blob.CloudBlobDirectory; import com.microsoft.azure.storage.blob.CloudBlockBlob; import com.microsoft.azure.storage.blob.CloudPageBlob; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.queue.CloudQueue; import com.microsoft.azure.storage.queue.CloudQueueClient; import com.microsoft.azure.storage.table.CloudTable; import com.microsoft.azure.storage.table.CloudTableClient; import org.junit.Test; import org.junit.experimental.categories.Category; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import static org.junit.Assert.*;
/** * Copyright Microsoft Corporation * * 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.microsoft.azure.storage; @Category({ DevFabricTests.class, DevStoreTests.class, CloudTests.class }) public class StorageUriTests { private static final String ACCOUNT_NAME = "account"; private static final String SECONDARY_SUFFIX = "-secondary"; private static final String ENDPOINT_SUFFIX = ".core.windows.net"; private static final String BLOB_SERVICE = ".blob"; private static final String QUEUE_SERVICE = ".queue"; private static final String TABLE_SERVICE = ".table"; @Test public void testStorageUriWithTwoUris() throws URISyntaxException { URI primaryClientUri = new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX); URI primaryContainerUri = new URI(primaryClientUri + "/container"); URI secondaryClientUri = new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX); URI dummyClientUri = new URI("http://" + ACCOUNT_NAME + "-dummy" + BLOB_SERVICE + ENDPOINT_SUFFIX); // no uri try { new StorageUri(null, null); fail(SR.STORAGE_URI_NOT_NULL); } catch (IllegalArgumentException ex) { assertEquals(SR.STORAGE_URI_NOT_NULL, ex.getMessage()); } // primary uri only StorageUri singleUri = new StorageUri(primaryClientUri); assertEquals(primaryClientUri, singleUri.getPrimaryUri()); assertNull(singleUri.getSecondaryUri()); StorageUri singleUri2 = new StorageUri(primaryClientUri); assertEquals(singleUri, singleUri2); StorageUri singleUri3 = new StorageUri(secondaryClientUri); assertFalse(singleUri.equals(singleUri3)); // secondary uri only StorageUri singleSecondaryUri = new StorageUri(null, secondaryClientUri); assertEquals(secondaryClientUri, singleSecondaryUri.getSecondaryUri()); assertNull(singleSecondaryUri.getPrimaryUri()); StorageUri singleSecondarUri2 = new StorageUri(null, secondaryClientUri); assertEquals(singleSecondaryUri, singleSecondarUri2); StorageUri singleSecondarUri3 = new StorageUri(null, primaryClientUri); assertFalse(singleSecondaryUri.equals(singleSecondarUri3)); // primary and secondary uri StorageUri multiUri = new StorageUri(primaryClientUri, secondaryClientUri); assertEquals(primaryClientUri, multiUri.getPrimaryUri()); assertEquals(secondaryClientUri, multiUri.getSecondaryUri()); assertFalse(multiUri.equals(singleUri)); StorageUri multiUri2 = new StorageUri(primaryClientUri, secondaryClientUri); assertEquals(multiUri, multiUri2); try { new StorageUri(primaryClientUri, primaryContainerUri); fail(SR.STORAGE_URI_MUST_MATCH); } catch (IllegalArgumentException ex) { assertEquals(SR.STORAGE_URI_MUST_MATCH, ex.getMessage()); } StorageUri multiUri3 = new StorageUri(primaryClientUri, dummyClientUri); assertFalse(multiUri.equals(multiUri3)); StorageUri multiUri4 = new StorageUri(dummyClientUri, secondaryClientUri); assertFalse(multiUri.equals(multiUri4)); StorageUri multiUri5 = new StorageUri(secondaryClientUri, primaryClientUri); assertFalse(multiUri.equals(multiUri5)); } @Test public void testDevelopmentStorageWithTwoUris() throws URISyntaxException { CloudStorageAccount account = CloudStorageAccount.getDevelopmentStorageAccount(); URI primaryClientURI = account.getBlobStorageUri().getPrimaryUri(); URI primaryContainerURI = new URI(primaryClientURI.toString() + "/container"); URI secondaryClientURI = account.getBlobStorageUri().getSecondaryUri(); StorageUri singleURI = new StorageUri(primaryClientURI); assertTrue(primaryClientURI.equals(singleURI.getPrimaryUri())); assertNull(singleURI.getSecondaryUri()); StorageUri singleURI2 = new StorageUri(primaryClientURI); assertTrue(singleURI.equals(singleURI2)); StorageUri singleURI3 = new StorageUri(secondaryClientURI); assertFalse(singleURI.equals(singleURI3)); StorageUri multiURI = new StorageUri(primaryClientURI, secondaryClientURI); assertTrue(primaryClientURI.equals(multiURI.getPrimaryUri())); assertTrue(secondaryClientURI.equals(multiURI.getSecondaryUri())); assertFalse(multiURI.equals(singleURI)); StorageUri multiURI2 = new StorageUri(primaryClientURI, secondaryClientURI); assertTrue(multiURI.equals(multiURI2)); try { new StorageUri(primaryClientURI, primaryContainerURI); fail("StorageUri constructor should fail if both URIs do not point to the same resource"); } catch (IllegalArgumentException e) { assertEquals(SR.STORAGE_URI_MUST_MATCH, e.getMessage()); } StorageUri multiURI3 = new StorageUri(secondaryClientURI, primaryClientURI); assertFalse(multiURI.equals(multiURI3)); } @Test public void testCloudStorageAccountWithStorageUri() throws URISyntaxException, InvalidKeyException { StorageUri blobEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX)); StorageUri queueEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + QUEUE_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + QUEUE_SERVICE + ENDPOINT_SUFFIX)); StorageUri tableEndpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + TABLE_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + TABLE_SERVICE + ENDPOINT_SUFFIX)); CloudStorageAccount account = CloudStorageAccount.parse(String.format( "DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=dummyKey", ACCOUNT_NAME)); assertEquals(blobEndpoint, account.getBlobStorageUri()); assertEquals(queueEndpoint, account.getQueueStorageUri()); assertEquals(tableEndpoint, account.getTableStorageUri()); assertEquals(blobEndpoint, account.createCloudBlobClient().getStorageUri()); assertEquals(queueEndpoint, account.createCloudQueueClient().getStorageUri()); assertEquals(tableEndpoint, account.createCloudTableClient().getStorageUri()); assertEquals(blobEndpoint.getPrimaryUri(), account.getBlobEndpoint()); assertEquals(queueEndpoint.getPrimaryUri(), account.getQueueEndpoint()); assertEquals(tableEndpoint.getPrimaryUri(), account.getTableEndpoint()); } @Test public void testBlobTypesWithStorageUri() throws StorageException, URISyntaxException { CloudBlobClient blobClient = TestHelper.createCloudBlobClient(); StorageUri endpoint = new StorageUri(new URI("http://" + ACCOUNT_NAME + BLOB_SERVICE + ENDPOINT_SUFFIX), new URI("http://" + ACCOUNT_NAME + SECONDARY_SUFFIX + BLOB_SERVICE + ENDPOINT_SUFFIX)); CloudBlobClient client = new CloudBlobClient(endpoint, blobClient.getCredentials()); assertEquals(endpoint, client.getStorageUri()); assertEquals(endpoint.getPrimaryUri(), client.getEndpoint()); StorageUri containerUri = new StorageUri(new URI(endpoint.getPrimaryUri() + "/container"), new URI( endpoint.getSecondaryUri() + "/container"));
CloudBlobContainer container = client.getContainerReference("container");
3
JavaMoney/javamoney-shelter
retired/format/src/main/java/org/javamoney/format/internal/DefaultTokenizeableFormatsSingletonSpi.java
[ "public interface ItemFormat<T> {\n\n\t/**\n\t * Return the target type this {@link ItemFormat} is expecting and capable\n\t * to format.\n\t * \n\t * @return the target type, never {@code null}.\n\t */\n\tpublic Class<T> getTargetClass();\n\n\t/**\n\t * Access the {@link LocalizationContext} configuring this {@lin...
import org.javamoney.format.ItemFormat; import org.javamoney.format.ItemFormatException; import org.javamoney.format.LocalizationContext; import org.javamoney.format.spi.ItemFormatFactorySpi; import org.javamoney.format.spi.TokenizeableFormatsSingletonSpi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.money.spi.Bootstrap; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
/* * Copyright (c) 2012, 2013, Credit Suisse (Anatole Tresch), Werner Keil. * * 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.javamoney.format.internal; /** * This is the base class for implementing the * {@link org.javamoney.format.spi.TokenizeableFormatsSingletonSpi}. * * @author Anatole Tresch */ @Singleton public class DefaultTokenizeableFormatsSingletonSpi implements TokenizeableFormatsSingletonSpi{ @SuppressWarnings("rawtypes")
private Map<Class,Set<ItemFormatFactorySpi>> formatMap = new ConcurrentHashMap<Class,Set<ItemFormatFactorySpi>>();
3
agorava/agorava-twitter
agorava-twitter-cdi/src/main/java/org/agorava/twitter/impl/TwitterGeoServiceImpl.java
[ "public abstract class TwitterBaseService extends ProviderApiService {\n\n protected static final char MULTI_VALUE_SEPARATOR = ',';\n\n public static final String API_ROOT = \"https://api.twitter.com/1.1/\";\n\n public Map<String, String> buildPagingParametersWithCount(int page, int pageSize, long sinceId,...
import java.util.HashMap; import java.util.List; import java.util.Map; import org.agorava.TwitterBaseService; import org.agorava.twitter.Twitter; import org.agorava.twitter.TwitterGeoService; import org.agorava.twitter.jackson.PlacesList; import org.agorava.twitter.model.Place; import org.agorava.twitter.model.PlacePrototype; import org.agorava.twitter.model.PlaceType; import org.agorava.twitter.model.SimilarPlaces; import org.agorava.twitter.model.SimilarPlacesResponse; import javax.inject.Named;
/* * Copyright 2013 Agorava * * 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.agorava.twitter.impl; /** * @author Antoine Sabot-Durand * @author Craig Walls */ @Twitter @Named public class TwitterGeoServiceImpl extends TwitterBaseService implements TwitterGeoService { @Override public Place getPlace(String placeId) { return getService().get(buildAbsoluteUri("geo/id/" + placeId + ".json"), Place.class); } @Override public List<Place> reverseGeoCode(double latitude, double longitude) { return reverseGeoCode(latitude, longitude, null, null); } @Override public List<Place> reverseGeoCode(double latitude, double longitude, PlaceType granularity, String accuracy) { Map<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, null); return getService().get(buildUri("geo/reverse_geocode.json", parameters), PlacesList.class).getList(); } @Override public List<Place> search(double latitude, double longitude) { return search(latitude, longitude, null, null, null); } @Override public List<Place> search(double latitude, double longitude, PlaceType granularity, String accuracy, String query) { Map<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, query); return getService().get(buildUri("geo/search.json", parameters), PlacesList.class).getList(); } @Override public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name) { return findSimilarPlaces(latitude, longitude, name, null, null); } @Override public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name, String streetAddress, String containedWithin) { Map<String, String> parameters = buildPlaceParameters(latitude, longitude, name, streetAddress, containedWithin); SimilarPlacesResponse response = getService().get(buildUri("geo/similar_places.json", parameters), SimilarPlacesResponse.class);
PlacePrototype placePrototype = new PlacePrototype(response.getToken(), latitude, longitude, name, streetAddress,
4
SecUSo/privacy-friendly-memo-game
app/src/main/java/org/secuso/privacyfriendlymemory/ui/navigation/StatisticsActivity.java
[ "public final class Constants {\n\n private Constants(){} // this class should not be initialized\n\n // Preferences Constants\n public final static String FIRST_APP_START = \"FIRST_APP_START\";\n public final static String SELECTED_CARD_DESIGN = \"SELECTED_CARD_DESIGN\";\n public final ...
import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.secuso.privacyfriendlymemory.Constants; import org.secuso.privacyfriendlymemory.common.MemoGameStatistics; import org.secuso.privacyfriendlymemory.common.ResIdAdapter; import org.secuso.privacyfriendlymemory.model.CardDesign; import org.secuso.privacyfriendlymemory.model.MemoGameDefaultImages; import org.secuso.privacyfriendlymemory.model.MemoGameDifficulty; import org.secuso.privacyfriendlymemory.ui.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
package org.secuso.privacyfriendlymemory.ui.navigation; public class StatisticsActivity extends AppCompatActivity { private static StatisticsActivity statisticsActivity; private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; private SharedPreferences preferences = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_statistcs_content); preferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); setupActionBar(); this.statisticsActivity = this; // setup up fragments in sectionspager mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); // setup tab layout TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } @Override protected void onDestroy() { super.onDestroy(); statisticsActivity = null; } private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.menu_statistics); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#024265"))); actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_statistics, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; case R.id.menu_statistics_reset: List<Integer> resIdsDeckOne = MemoGameDefaultImages.getResIDs(CardDesign.FIRST, MemoGameDifficulty.Hard, false); List<Integer> resIdsDeckTwo = MemoGameDefaultImages.getResIDs(CardDesign.SECOND, MemoGameDifficulty.Hard, false);
List<String> resourceNamesDeckOne = ResIdAdapter.getResourceName(resIdsDeckOne, this);
2
ApplETS/applets-java-api
src/test/java/applets/etsmtl/ca/news/EventsResourcesTest.java
[ "@Path(\"events\")\npublic class EventsResources {\n\n private final EventDAO eventDAO;\n private final SourceDAO sourceDAO;\n\n @Inject\n public EventsResources(EventDAO eventDAO, SourceDAO sourceDAO) {\n this.eventDAO = eventDAO;\n this.sourceDAO = sourceDAO;\n }\n\n @GET\n @Pat...
import applets.etsmtl.ca.news.EventsResources; import applets.etsmtl.ca.news.db.EventDAO; import applets.etsmtl.ca.news.db.SourceDAO; import applets.etsmtl.ca.news.model.Event; import applets.etsmtl.ca.news.model.Source; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.ws.rs.core.Application; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.when;
package news; public class EventsResourcesTest extends JerseyTest { @Mock private EventDAO eventDAO; @Mock private SourceDAO sourceDAO; @Override protected Application configure() { MockitoAnnotations.initMocks(this);
EventsResources resource = new EventsResources(eventDAO, sourceDAO);
0
wwfdoink/jolokia-web
src/main/java/prj/jolokiaweb/controller/ApiController.java
[ "public class JolokiaApp {\n private static final int DEFAULT_PORT = 8080;\n private static final String DEFAULT_CONTEXT_PATH = \"\";\n private static Tomcat tomcat;\n private static String baseUrl;\n private static String contextPath;\n\n /**\n * @param tomcatPort Web server listening port\n ...
import org.jolokia.client.exception.J4pException; import org.jolokia.client.request.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import prj.jolokiaweb.JolokiaApp; import prj.jolokiaweb.form.ExecForm; import prj.jolokiaweb.form.ReadForm; import prj.jolokiaweb.form.WriteForm; import prj.jolokiaweb.jolokia.AgentInfo; import prj.jolokiaweb.jolokia.JolokiaClient; import javax.management.MalformedObjectNameException; import java.util.*;
package prj.jolokiaweb.controller; @RestController public class ApiController { @RequestMapping(value = "/api/checkPermissions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> checkPermissions() { JSONObject result = new JSONObject(); JSONArray arr = new JSONArray(); result.put("permissions", arr); if (JolokiaClient.getAgentInfo().getBeanPermissions().size() < 1) { arr.add(AgentInfo.JolokiaPermission.NONE); } else { for (AgentInfo.JolokiaPermission p: JolokiaClient.getAgentInfo().getBeanPermissions()) { arr.add(p); } } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/beans", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> beans() { JSONObject result = new JSONObject(); try { String path = null; // null means full tree Map<J4pQueryParameter,String> params = new HashMap<>();; params.put(J4pQueryParameter.CANONICAL_NAMING,"false"); result = JolokiaClient.getInstance().execute(new J4pListRequest(path), params).asJSONObject(); } catch(Exception e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/version", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> version() { JSONObject result = new JSONObject(); try { J4pReadRequest runtimeReq = new J4pReadRequest("java.lang:type=Runtime"); J4pReadResponse runtimeRes = JolokiaClient.getInstance().execute(runtimeReq); J4pVersionResponse versionRes = JolokiaClient.getInstance().execute(new J4pVersionRequest()); result.put("runtime", runtimeRes.getValue()); result.put("version", versionRes.getValue()); } catch (Exception e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/read", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<JSONObject> read(@RequestBody ReadForm readForm) { JSONObject result = new JSONObject(); try { J4pReadRequest readReq = new J4pReadRequest(readForm.getMbean()); Map<J4pQueryParameter,String> params = new HashMap<>(); params.put(J4pQueryParameter.IGNORE_ERRORS,"true"); J4pReadResponse readRes = JolokiaClient.getInstance().execute(readReq, params); result = readRes.getValue(); } catch (MalformedObjectNameException e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } catch (J4pException e) { result.put("error", e.getMessage()); return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } @RequestMapping(value = "/api/execute", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> execute(@RequestBody ExecForm execForm) {
1
Erudika/scoold
src/main/java/com/erudika/scoold/controllers/ReportsController.java
[ "@Component\n@Named\npublic class ScooldConfig extends Config {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ScooldConfig.class);\n\n\t@Override\n\tpublic com.typesafe.config.Config getFallbackConfig() {\n\t\treturn Para.getConfig().getConfig(); // fall back to para.* config\n\t}\n\n\t@Override...
import com.erudika.para.client.ParaClient; import com.erudika.para.core.utils.Config; import com.erudika.para.core.utils.Pager; import com.erudika.para.core.utils.ParaObjectUtils; import com.erudika.para.core.utils.Utils; import com.erudika.scoold.ScooldConfig; import static com.erudika.scoold.ScooldServer.REPORTSLINK; import static com.erudika.scoold.ScooldServer.SIGNINLINK; import com.erudika.scoold.core.Profile; import static com.erudika.scoold.core.Profile.Badge.REPORTER; import com.erudika.scoold.core.Report; import com.erudika.scoold.utils.ScooldUtils; import java.io.IOException; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam;
/* * Copyright 2013-2022 Erudika. https://erudika.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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.scoold.controllers; /** * * @author Alex Bogdanovski [alex@erudika.com] */ @Controller @RequestMapping("/reports") public class ReportsController { private static final ScooldConfig CONF = ScooldUtils.getConfig(); private final ScooldUtils utils; private final ParaClient pc; @Inject public ReportsController(ScooldUtils utils) { this.utils = utils; this.pc = utils.getParaClient(); } @GetMapping public String get(@RequestParam(required = false, defaultValue = Config._TIMESTAMP) String sortby, HttpServletRequest req, Model model) { if (utils.isAuthenticated(req) && !utils.isMod(utils.getAuthUser(req))) { return "redirect:" + REPORTSLINK; } else if (!utils.isAuthenticated(req)) {
return "redirect:" + SIGNINLINK + "?returnto=" + REPORTSLINK;
2
novucs/factions-top
core/src/main/java/net/novucs/ftop/listener/WorthListener.java
[ "public final class FactionsTopPlugin extends JavaPlugin {\n\n private final ChunkWorthTask chunkWorthTask = new ChunkWorthTask(this);\n private final GuiManager guiManager = new GuiManager(this);\n private final PersistenceTask persistenceTask = new PersistenceTask(this);\n private final RecalculateTas...
import com.google.common.collect.ImmutableMap; import net.novucs.ftop.FactionsTopPlugin; import net.novucs.ftop.PluginService; import net.novucs.ftop.RecalculateReason; import net.novucs.ftop.WorthType; import net.novucs.ftop.entity.BlockPos; import net.novucs.ftop.entity.ChestWorth; import net.novucs.ftop.hook.event.*; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.DoubleChest; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
package net.novucs.ftop.listener; public class WorthListener extends BukkitRunnable implements Listener, PluginService { private final FactionsTopPlugin plugin; private final Map<BlockPos, ChestWorth> chests = new HashMap<>(); private final Set<String> recentDisbands = new HashSet<>(); public WorthListener(FactionsTopPlugin plugin) { this.plugin = plugin; } @Override public void initialize() { plugin.getServer().getPluginManager().registerEvents(this, plugin); runTaskTimer(plugin, 1, 1); } @Override public void terminate() { HandlerList.unregisterAll(this); cancel(); } @Override public void run() { recentDisbands.clear(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void updateWorth(BlockPlaceEvent event) {
updateWorth(event.getBlock(), RecalculateReason.PLACE, false);
2
Gocnak/Botnak
src/main/java/face/Icons.java
[ "public class ChatPane implements DocumentListener {\n\n private JFrame poppedOutPane = null;\n\n // The timestamp of when we decided to wait to scroll back down\n private long scrollbarTimestamp = -1;\n\n public void setPoppedOutPane(JFrame pane) {\n poppedOutPane = pane;\n }\n\n public JF...
import gui.ChatPane; import gui.forms.GUIMain; import lib.scalr.Scalr; import util.AnimatedGifEncoder; import util.GifDecoder; import util.Utils; import util.settings.Settings; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL;
package face; /** * A class which specifies special chat icons, or 'badges'. * This allows for easier creation of custom icons, and * should be easily adaptable to create custom donation * levels. * * @author Joseph Blackman * @version 4/10/2015 */ public class Icons { /** * For a specified icon, returns the file containing the * image, resized to fit into the chat window. * * @param i the type of icon to get * @return the icon along with what type it is */ public static BotnakIcon getIcon(IconEnum i, String channel) { ImageIcon icon = null; switch (i) { case MOD: icon = sizeIcon(Settings.modIcon.getValue()); break; case BROADCASTER: icon = sizeIcon(Settings.broadIcon.getValue()); break; case ADMIN: icon = sizeIcon(Settings.adminIcon.getValue()); break; case STAFF: icon = sizeIcon(Settings.staffIcon.getValue()); break; case TURBO: icon = sizeIcon(Settings.turboIcon.getValue()); break; case PRIME:
icon = sizeIcon(ChatPane.class.getResource("/image/prime.png"));
0
rla/while
src/com/infdot/analysis/cfg/node/AssignmentNode.java
[ "public abstract class AbstractNodeVisitor<V> {\n\t\n\tprivate Map<AbstractNode, DataflowExpression<V>> visited =\n\t\tnew HashMap<AbstractNode, DataflowExpression<V>>();\n\t\n\tprivate int currentVarId = 0;\n\tprivate Map<AbstractNode, Integer> variables =\n\t\tnew HashMap<AbstractNode, Integer>();\n\t\n\tpublic a...
import java.util.HashSet; import java.util.Set; import com.infdot.analysis.cfg.node.visitor.AbstractNodeVisitor; import com.infdot.analysis.examples.VariableNameTransform; import com.infdot.analysis.language.expression.Expression; import com.infdot.analysis.language.expression.Identifier; import com.infdot.analysis.language.statement.Assignment; import com.infdot.analysis.solver.DataflowExpression; import com.infdot.analysis.solver.lattice.powerset.PowersetDomain; import com.infdot.analysis.util.CollectionUtil;
package com.infdot.analysis.cfg.node; /** * CFG node for assignments. * * @author Raivo Laanemets */ public class AssignmentNode extends AbstractNode { private Assignment assignment; public AssignmentNode(Assignment assignment) { this.assignment = assignment; }
public Identifier getIdentifier() {
3
zer0Black/zer0MQTTServer
zer0MQTTServer/src/com/syxy/protocol/mqttImp/MQTTProcess.java
[ "public class ConnectMessage extends Message {\n\t\n\tpublic ConnectMessage(FixedHeader fixedHeader, ConnectVariableHeader variableHeader,\n\t\t\tConnectPayload payload) {\n\t\tsuper(fixedHeader, variableHeader, payload);\n\t}\n\t\n\t@Override\n\tpublic ConnectVariableHeader getVariableHeader() {\n\t\treturn (Conne...
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import com.syxy.protocol.mqttImp.message.ConnectMessage; import com.syxy.protocol.mqttImp.message.Message; import com.syxy.protocol.mqttImp.message.PackageIdVariableHeader; import com.syxy.protocol.mqttImp.message.PublishMessage; import com.syxy.protocol.mqttImp.message.SubscribeMessage; import com.syxy.protocol.mqttImp.message.UnSubscribeMessage; import com.syxy.protocol.mqttImp.process.ProtocolProcess;
package com.syxy.protocol.mqttImp; /** * MQTT协议业务处理 * * @author zer0 * @version 1.0 * @date 2015-2-16 */ public class MQTTProcess extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ProtocolProcess process = ProtocolProcess.getInstance();
6
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/image/ImageProcessingThread.java
[ "public class DrawingSize {\n\n\tprivate static final NumberFormat nf = NumberFormat.getInstance();\n\tstatic{\n\t\tnf.setGroupingUsed(false);\n\t\tnf.setMaximumFractionDigits(5);\n\t\tnf.setMaximumFractionDigits(0);\n\t\tnf.setMinimumIntegerDigits(1);\n\t\tnf.setMaximumIntegerDigits(5);\n\t}\n\t\n\tprivate double ...
import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.image.AreaAveragingScaleFilter; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageProducer; import java.io.File; import javax.imageio.ImageIO; import marvin.image.MarvinImage; import marvin.image.MarvinImageMask; import marvin.plugin.MarvinImagePlugin; import marvin.util.MarvinPluginLoader; import org.apache.commons.io.FileUtils; import com.sketchy.drawing.DrawingSize; import com.sketchy.image.RenderedImageAttributes.CenterOption; import com.sketchy.image.RenderedImageAttributes.FlipOption; import com.sketchy.image.RenderedImageAttributes.RenderOption; import com.sketchy.image.RenderedImageAttributes.RotateOption; import com.sketchy.image.RenderedImageAttributes.ScaleOption; import com.sketchy.server.HttpServer; import com.sketchy.utils.image.SketchyImage;
plugin.setAttribute("brightness", brightnessValue); plugin.setAttribute("contrast", contrastValue); plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=30; if ((renderedImageAttributes.isInvertImage())){ statusMessage = "Inverting Image"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.invert.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Invert Image Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=35; if (renderedImageAttributes.getRotateOption()!=RotateOption.ROTATE_NONE){ statusMessage = "Rotating Image"; bufferedImage = rotateImage(bufferedImage, renderedImageAttributes.getRotateOption()); } if (cancel){ throw new CancelledException(); } progress=40; if (renderedImageAttributes.getFlipOption()!=FlipOption.FLIP_NONE){ statusMessage = "Flipping Image"; bufferedImage = flipImage(bufferedImage, renderedImageAttributes.getFlipOption()); } if (cancel){ throw new CancelledException(); } progress=50; if (renderedImageAttributes.getRenderOption()==RenderOption.RENDER_EDGE_DETECTION){ statusMessage = "Processing Edge Detection"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.edgeDetector.jar"); if (plugin==null){ throw new Exception("Error loading Marvin EdgeDetector Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } int drawingWidth = (int) Math.ceil(drawingSize.getWidth()*dotsPerMM); int drawingHeight = (int) Math.ceil(drawingSize.getHeight()*dotsPerMM); if (cancel){ throw new CancelledException(); } progress=55; statusMessage = "Scaling Image"; bufferedImage = resizeImage(bufferedImage, drawingWidth, drawingHeight, renderedImageAttributes.getCenterOption(), renderedImageAttributes.getScaleOption()); if (cancel){ throw new CancelledException(); } progress=60; if (renderedImageAttributes.getRenderOption()==RenderOption.RENDER_HALFTONE){ statusMessage = "Processing Halftone"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Halftone Plugin!"); } plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } progress=65; if ((renderedImageAttributes.getThreshold()!=50) && (renderedImageAttributes.getRenderOption()!=RenderOption.RENDER_HALFTONE)){ statusMessage = "Processing Threshold"; MarvinImage image = new MarvinImage(bufferedImage); MarvinImagePlugin plugin = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.thresholding.jar"); if (plugin==null){ throw new Exception("Error loading Marvin Threshold Plugin!"); } // Range is 0 to 256.. convert from 0 - 100 int thresholdValue = (256-(int)(renderedImageAttributes.getThreshold()*2.56)); plugin.setAttribute("threshold", thresholdValue); plugin.process(image,image,null,MarvinImageMask.NULL_MASK, false); image.update(); bufferedImage = image.getBufferedImage(); } if (cancel){ throw new CancelledException(); } statusMessage = "Saving Rendered Image"; File renderedFile = HttpServer.getUploadFile(renderedImageAttributes.getImageFilename()); renderedImageAttributes.setWidth(bufferedImage.getWidth()); renderedImageAttributes.setHeight(bufferedImage.getHeight()); progress=70;
SketchyImage sketchyImage = new SketchyImage(bufferedImage, dotsPerMM, dotsPerMM);
7
PathwayAndDataAnalysis/causalpath
src/main/java/org/panda/causalpath/run/TCGARecurrentCorrelationRun.java
[ "public class CausalitySearcher implements Cloneable\n{\n\t/**\n\t * If that is false, then we are interested in conflicting relations.\n\t */\n\tprivate int causal;\n\n\t/**\n\t * If this is false, then we don't care if the target site of a relation and the site on the data matches.\n\t */\n\tprivate boolean force...
import org.panda.causalpath.analyzer.CausalitySearcher; import org.panda.causalpath.analyzer.CorrelationDetector; import org.panda.causalpath.network.GraphWriter; import org.panda.causalpath.network.Relation; import org.panda.causalpath.resource.NetworkLoader; import org.panda.causalpath.resource.TCGALoader; import org.panda.utility.Kronometre; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
package org.panda.causalpath.run; /** * For finding recurrent causative correlations in TCGA RPPA data. */ public class TCGARecurrentCorrelationRun { public static void main(String[] args) throws IOException { Kronometre k = new Kronometre(); String base = "/home/babur/Documents/RPPA/TCGA/basic-correlation-rppa-mut/"; String single = base + "single/"; String recurrent = base + "recurrent/"; String tcgaDataDir = "/home/babur/Documents/TCGA"; if (!(new File(single).exists())) new File(single).mkdirs(); Map<Relation, Integer> relCnt = new HashMap<>(); for (File dir : new File(tcgaDataDir).listFiles()) { if (dir.getName().equals("PanCan")) continue; if (new File(dir.getPath() + "/rppa.txt").exists()) { String outFile = single + dir.getName() + ".sif"; Set<Relation> rels = NetworkLoader.load(); System.out.println("rels.size() = " + rels.size()); System.out.println("dir = " + dir.getName());
TCGALoader loader = new TCGALoader(dir.getPath());
4
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/ESP.java
[ "public class SigmoidTable {\n\n\t private int maxExponent = 6; //maximum permitted exponent\n\t private int tableSize\t\t = 1000;\n\t private double[] sigmoidTable;\n\t \n\t /**\n\t * \n\t */\n\t \n\t public SigmoidTable(int maxExponent, int tableSize)\n\t\t {\n\t\t \tthis.maxExponent \t= maxExponent;\n\...
import org.apache.lucene.document.Document; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.BytesRef; import org.netlib.blas.BLAS; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.utils.Bobcat; import pitt.search.semanticvectors.utils.SigmoidTable; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.BinaryVector; import pitt.search.semanticvectors.vectors.ComplexVector; import pitt.search.semanticvectors.vectors.ComplexVector.Mode; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.FileSystems; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger;
int qb = randomStartpoints.poll(); //the index number of the first predication-document to be drawn int qe = qb + (100000); //the index number of the last predication-document to be drawn int qplus = 0; //the number of predication-documents added to the queue for (int qc=qb; qc < qe && qc < luceneUtils.getNumDocs() && dc.get() < luceneUtils.getNumDocs()-1; qc++) { try { Document nextDoc = luceneUtils.getDoc(qc); dc.incrementAndGet(); if (nextDoc != null) { theQ.add(nextDoc); qplus++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } VerbatimLogger.info("\nAdded "+qplus+" documents to queue, now carrying "+theQ.size()); if (qplus == 0) return -1; else return qplus; } /** * Performs training by iterating over predications. Assumes that elemental vector stores are populated. * * @throws IOException */ private void trainIncrementalESPVectors() throws IOException { // For BINARY vectors, assign higher learning rates on account of the limited floating point precision of the voting record if (flagConfig.vectortype().equals(VectorType.BINARY)) { initial_alpha = 0.25; alpha = 0.25; min_alpha = 0.001; } //loop through the number of assigned epochs for (tc=0; tc <= flagConfig.trainingcycles(); tc++) { initializeRandomizationStartpoints(); theQ = new ConcurrentLinkedQueue<Document>(); dc.set(0); populateQueue(); double time = System.currentTimeMillis(); int numthreads = flagConfig.numthreads(); ExecutorService executor = Executors.newFixedThreadPool(numthreads); for (int q = 0; q < numthreads; q++) { executor.execute(new TrainPredThread(q)); } executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) { if (theQ.size() < 50000) populateQueue(); } int mp = flagConfig.mutablepredicatevectors() ? 1 : 0; double num_updates = pc.get() * (1 + flagConfig.negsamples()) * (4 + 2*mp); double lo = raw_loss.sumThenReset(); double ave_loss = lo / num_updates; VerbatimLogger.info("\nTime for cycle "+tc+" : "+((System.currentTimeMillis() - time) / (1000*60)) +" minutes"); VerbatimLogger.info("\nSummed loss = "+lo); VerbatimLogger.info("\nMean loss = "+ave_loss); VerbatimLogger.info("\nProcessed "+pc.get()+" total predications (total on disk = "+luceneUtils.getNumDocs()+")"); //normalization with each epoch if the vectors are not binary vectors if (!flagConfig.vectortype().equals(VectorType.BINARY)) { Enumeration<ObjectVector> semanticVectorEnumeration = semanticItemVectors.getAllVectors(); Enumeration<ObjectVector> elementalVectorEnumeration = elementalItemVectors.getAllVectors(); while (semanticVectorEnumeration.hasMoreElements()) { semanticVectorEnumeration.nextElement().getVector().normalize(); elementalVectorEnumeration.nextElement().getVector().normalize(); } } } // Finished all epochs Enumeration<ObjectVector> e = null; if (flagConfig.semtypesandcuis()) //write out cui vectors and normalize semantic vectors { // Also write out cui version of semantic vectors File vectorFile = new File("cuivectors.bin"); java.nio.file.Files.deleteIfExists(vectorFile.toPath()); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(FileSystems.getDefault().getPath(parentPath)); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName(), IOContext.DEFAULT); outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Tally votes of semantic vectors and write out. e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector ov = e.nextElement(); if (flagConfig.vectortype().equals(VectorType.BINARY))
((BinaryVector) ov.getVector()).tallyVotes();
1
DigiArea/es5-model
com.digiarea.es5/src/com/digiarea/es5/Project.java
[ "public abstract class Node {\r\n\r\n\t/**\r\n\t * The JSDoc comment.\r\n\t */\r\n\tprotected JSDocComment jsDocComment = null;\r\n\r\n\t/**\r\n\t * The position begin.\r\n\t */\r\n\tprotected int posBegin = 0;\r\n\r\n\t/**\r\n\t * The position end.\r\n\t */\r\n\tprotected int posEnd = 0;\r\n\r\n\tpublic JSDocComme...
import com.digiarea.es5.Node; import com.digiarea.es5.CompilationUnit; import com.digiarea.es5.NodeList; import com.digiarea.es5.JSDocComment; import com.digiarea.es5.visitor.VoidVisitor; import com.digiarea.es5.visitor.GenericVisitor;
package com.digiarea.es5; /** * The Class Project. */ public class Project extends Node { /** * The compilation units. */ private NodeList<CompilationUnit> compilationUnits = null; public NodeList<CompilationUnit> getCompilationUnits() { return compilationUnits; } public void setCompilationUnits(NodeList<CompilationUnit> compilationUnits) { this.compilationUnits = compilationUnits; } Project() { super(); } Project(NodeList<CompilationUnit> compilationUnits, JSDocComment jsDocComment, int posBegin, int posEnd) { super(jsDocComment, posBegin, posEnd); this.compilationUnits = compilationUnits; } @Override
public <C> void accept(VoidVisitor<C> v, C ctx) throws Exception {
4
gonmarques/cdi-properties
cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
[ "public class LocaleThreadLocal {\n\n public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();\n private final Locale locale;\n\n public LocaleThreadLocal(Locale locale) {\n this.locale = locale;\n }\n\n public Locale getLocale() {\n return locale;\n ...
import java.io.IOException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import com.byteslounge.cdi.test.common.LocaleThreadLocal; import com.byteslounge.cdi.test.common.servlet.TestServlet; import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory; import com.byteslounge.cdi.test.wpm.OtherService; import com.byteslounge.cdi.test.wpm.OtherServiceBean; import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal;
/* * Copyright 2015 byteslounge.com (Gonçalo Marques). * * 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.byteslounge.cdi.test.it.common; /** * Base class for Integration Tests which resolve the current locale from a ThreadLocal variable * * @author Gonçalo Marques * @since 1.1.0 */ public abstract class AbstractWarProvidedLocaleMethodThreadLocal { protected static WebArchive createArchive() throws IOException { WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, LocaleThreadLocal.class);
1
alexandre-normand/blood-shepherd
dexcom-receiver/src/test/java/org/glukit/dexcom/sync/TestDexcomAdapterService.java
[ "public class DexcomG4Constants {\n\n public static final int DATA_BITS = 8;\n public static final int STOP_BITS = 1;\n public static final int NO_PARITY = 0;\n public static final int FIRMWARE_BAUD_RATE = 0x9600;\n public static final Instant DEXCOM_EPOCH = Instant.from(ZonedDateTime.of(2009, 1, 1, 0, 0, 0, 0...
import org.glukit.dexcom.sync.g4.DexcomG4Constants; import org.glukit.dexcom.sync.model.DexcomSyncData; import org.glukit.dexcom.sync.model.GlucoseReadRecord; import org.glukit.dexcom.sync.model.ManufacturingParameters; import org.glukit.dexcom.sync.model.UserEventRecord; import org.glukit.sync.api.*; import org.junit.Test; import org.threeten.bp.Duration; import org.threeten.bp.Instant; import org.threeten.bp.LocalDateTime; import org.threeten.bp.ZoneId; import java.util.Arrays; import java.util.Collections; import java.util.List; import static java.lang.String.format; import static org.glukit.dexcom.sync.DexcomAdapterService.SPECIAL_GLUCOSE_VALUES; import static org.glukit.sync.api.InsulinInjection.InsulinType.UNKNOWN; import static org.glukit.sync.api.InsulinInjection.UNAVAILABLE_INSULIN_NAME; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat;
package org.glukit.dexcom.sync; /** * Unit test of {@link DexcomAdapterService}. * * @author alexandre.normand */ public class TestDexcomAdapterService { private static final String SERIAL_NUMBER = "serial"; private static final String HARDWARE_REVISION = "revision1"; private static final String HARDWARE_ID = "hardwareId"; private static final Integer NORMAL_READ_TEST_VALUE = 83; private static final List<GlucoseRead> EMPTY_GLUCOSE_READS = Collections.emptyList();
private static final List<GlucoseReadRecord> EMPTY_GLUCOSE_READ_RECORDS = Collections.emptyList();
2
AVMf/avmf
src/main/java/org/avmframework/examples/inputdatageneration/line/LineTestObject.java
[ "public class Vector extends AbstractVector {\n\n public void addVariable(Variable variable) {\n variables.add(variable);\n }\n\n public List<Variable> getVariables() {\n return new ArrayList<>(variables);\n }\n\n public void setVariablesToInitial() {\n for (Variable var : variables) {\n var.setV...
import org.avmframework.Vector; import org.avmframework.examples.inputdatageneration.Branch; import org.avmframework.examples.inputdatageneration.BranchTargetObjectiveFunction; import org.avmframework.examples.inputdatageneration.TestObject; import org.avmframework.variable.FixedPointVariable;
package org.avmframework.examples.inputdatageneration.line; public class LineTestObject extends TestObject { static final int NUM_BRANCHING_NODES = 7; static final int PRECISION = 1; static final double INITIAL_VALUE = 0.0; static final double MIN = 0.0; static final double MAX = 100.0; @Override public Vector getVector() { Vector vector = new Vector(); for (int i = 0; i < 8; i++) { vector.addVariable(new FixedPointVariable(INITIAL_VALUE, PRECISION, MIN, MAX)); } return vector; } @Override
public BranchTargetObjectiveFunction getObjectiveFunction(Branch target) {
2
dannormington/appengine-cqrs
src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
[ "public interface AggregateRoot {\n\n /**\n * get the Id\n * \n * @return\n */\n UUID getId();\n\n /**\n * Gets all change events since the\n * original hydration. If there are no\n * changes then null is returned\n * \n * @return\n */\n Iterable<Event> getUncommi...
import java.util.UUID; import com.cqrs.appengine.core.domain.AggregateRoot; import com.cqrs.appengine.core.exceptions.AggregateNotFoundException; import com.cqrs.appengine.core.exceptions.EventCollisionException; import com.cqrs.appengine.core.exceptions.HydrationException; import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence; /** * Implementation of a simple event repository * * @param <T> */ public class EventRepository<T extends AggregateRoot> implements Repository<T> { /** * Instance of the event store */ private EventStore eventStore; /** * The class type that the repository is working with */ private Class<T> aClass; /** * Default Constructor * * @param aClass */ public EventRepository(Class<T> aClass){ this.aClass = aClass; eventStore = new AppEngineEventStore(); } /** * Constructor to be used when specifying a specific * queue for events to be published to * * @param aClass */ public EventRepository(Class<T> aClass, String queue){ this.aClass = aClass; eventStore = new AppEngineEventStore(queue); } @Override
public void save(T aggregate) throws EventCollisionException {
2
highway-to-urhell/highway-to-urhell
h2hell-core/src/main/java/com/highway2urhell/service/ThunderExporterService.java
[ "public class CoreEngine {\n\n\tprivate static CoreEngine instance;\n\n\tprivate Map<String, LeechService> leechPluginRegistry = new HashMap<String, LeechService>();\n\tprivate Set<ReporterService> reporterPluginRegistry = new HashSet<ReporterService>();\n\tprivate final static String H2H_CONFIG = \"H2H_CONFIG\";\n...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.highway2urhell.CoreEngine; import com.highway2urhell.domain.EntryPathData; import com.highway2urhell.domain.MessageBreaker; import com.highway2urhell.domain.MessageMetrics; import com.highway2urhell.domain.MessageThunderApp; import com.sun.management.OperatingSystemMXBean; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.management.ManagementFactory; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*;
package com.highway2urhell.service; public class ThunderExporterService { private static ThunderExporterService instance; private BlockingQueue<MessageBreaker> queueRemoteBreaker = new LinkedBlockingQueue<MessageBreaker>(10000); private BlockingQueue<MessageMetrics> queueRemotePerformance = new LinkedBlockingQueue<MessageMetrics>(10000); private final static int MSG_SIZE = 50; private ThunderExporterService() { ScheduledExecutorService schExService = Executors.newScheduledThreadPool(1); schExService.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("Drain the queue Remote"); List<MessageBreaker> listBreaker = new ArrayList<MessageBreaker>(); int result = queueRemoteBreaker.drainTo(listBreaker, MSG_SIZE); System.out.println("Drain Remote size " + result); if (result > 0) { System.out.println("Send the Data "); sendDataHTTPOldSchool("/addBreaker", listBreaker); }
if (CoreEngine.getInstance().getConfig().getPerformance()) {
0
DSH105/SparkTrail
src/main/java/com/dsh105/sparktrail/util/fanciful/FancyMessage.java
[ "public class ReflectionUtil {\n\n public static String NMS_PATH = getNMSPackageName();\n public static String CBC_PATH = getCBCPackageName();\n\n public static String getServerVersion() {\n return Bukkit.getServer().getClass().getPackage().getName().replace(\".\", \",\").split(\",\")[3];\n }\n\n...
import com.dsh105.sparktrail.util.ReflectionUtil; import com.dsh105.sparktrail.util.protocol.wrapper.WrapperPacketChat; import com.dsh105.sparktrail.util.reflection.SafeConstructor; import com.dsh105.sparktrail.util.reflection.SafeField; import com.dsh105.sparktrail.util.reflection.SafeMethod; import org.bukkit.Achievement; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.Statistic.Type; import org.bukkit.craftbukkit.libs.com.google.gson.stream.JsonWriter; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.io.StringWriter; import java.util.ArrayList; import java.util.List;
/* * This file is part of SparkTrail 3. * * SparkTrail 3 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. * * SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>. */ /* * This file is part of HoloAPI. * * HoloAPI 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. * * HoloAPI 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 HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.sparktrail.util.fanciful; public class FancyMessage { private final List<MessagePart> messageParts; private String jsonString; private boolean dirty; public FancyMessage(final String firstPartText) { messageParts = new ArrayList<MessagePart>(); messageParts.add(new MessagePart(firstPartText)); jsonString = null; dirty = false; } public FancyMessage color(final ChatColor color) { if (!color.isColor()) { throw new IllegalArgumentException(color.name() + " is not a color"); } latest().color = color; dirty = true; return this; } public FancyMessage style(final ChatColor... styles) { for (final ChatColor style : styles) { if (!style.isFormat()) { throw new IllegalArgumentException(style.name() + " is not a style"); } } latest().styles = styles; dirty = true; return this; } public FancyMessage file(final String path) { onClick("open_file", path); return this; } public FancyMessage link(final String url) { onClick("open_url", url); return this; } public FancyMessage suggest(final String command) { onClick("suggest_command", command); return this; } public FancyMessage command(final String command) { onClick("run_command", command); return this; } public FancyMessage achievementTooltip(final String name) { onHover("show_achievement", "achievement." + name); return this; } public FancyMessage achievementTooltip(final Achievement which) {
Object achievement = new SafeMethod(ReflectionUtil.getCBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which);
0
ingwarsw/arquillian-suite-extension
src/test/java/org/eu/ingwar/tools/arquillian/extension/suite/Deployments.java
[ "public class EarGenericBuilder {\n\n private static final String RUN_AT_ARQUILLIAN_PATH = \"/runs-at-arquillian.txt\";\n private static final String RUN_AT_ARQUILLIAN_CONTENT = \"at-arquillian\";\n private static final Logger LOG = Logger.getLogger(EarGenericBuilder.class.getName());\n\n /**\n * Pr...
import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.eu.ingwar.tools.arquillian.extension.deployment.EarGenericBuilder; import org.eu.ingwar.tools.arquillian.extension.deployment.ModuleType; import org.eu.ingwar.tools.arquillian.extension.groups.AlphaGroup; import org.eu.ingwar.tools.arquillian.extension.suite.normal.Extension1Test; import org.eu.ingwar.tools.arquillian.extension.suite.inject.InjectedObject; import org.eu.ingwar.tools.arquillian.extension.suite.annotations.ArquillianSuiteDeployment; import org.eu.ingwar.tools.arquillian.extension.suite.extra.ExtensionExtra1Test; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.shrinkwrap.api.Archive;
package org.eu.ingwar.tools.arquillian.extension.suite; /* * #%L * Arquillian suite extension * %% * Copyright (C) 2013 Ingwar & co. * %% * 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. * #L% */ @ArquillianSuiteDeployment public class Deployments { @Deployment(name = "normal", order = 3) @TargetsContainer("app") public static Archive<?> generateDefaultDeployment() { return ShrinkWrap.create(WebArchive.class, "normal.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(Deployments.class) .addClass(InjectedObject.class) .addPackage(AlphaGroup.class.getPackage()) .addPackage(Extension1Test.class.getPackage()); } @Deployment(name = "extra", order = 4) @TargetsContainer("app") public static Archive<?> generateExtraDeployment() { Archive<?> ejb = ShrinkWrap.create(WebArchive.class, "extra_ejb.war") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .addClass(Deployments.class) .addClass(InjectedObject.class) .addPackage(AlphaGroup.class.getPackage()) .addPackage(ExtensionExtra1Test.class.getPackage()); return ejb; } @Deployment(name = "autogenerated", order = 2) @TargetsContainer("app") public static Archive<?> generateAutogeneratedDeployment() {
EnterpriseArchive ear = EarGenericBuilder.getModuleDeployment(ModuleType.EJB);
1
lacuna/bifurcan
src/io/lacuna/bifurcan/DurableEncodings.java
[ "public class BlockPrefix {\n\n public enum BlockType {\n // root (2 bits)\n PRIMITIVE,\n TABLE,\n DIFF, // continuation\n COLLECTION, // continuation\n\n // 3 bits preceded by COLLECTION\n HASH_MAP,\n SORTED_MAP,\n HASH_SET,\n SORTED_SET,\n LIST,\n COLLECTION_PLACEHOLDER_...
import io.lacuna.bifurcan.durable.BlockPrefix; import io.lacuna.bifurcan.durable.io.DurableBuffer; import io.lacuna.bifurcan.utils.Iterators; import java.util.Arrays; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.function.*; import static io.lacuna.bifurcan.durable.codecs.Core.decodeBlock; import static io.lacuna.bifurcan.durable.codecs.Core.encodeBlock;
Comparator<Object> comparator, Predicate<Object> isSingleton, Codec codec ) { return new IDurableEncoding.Primitive() { @Override public String description() { return description; } @Override public ToLongFunction<Object> hashFn() { return valueHash; } @Override public BiPredicate<Object, Object> equalityFn() { return valueEquality; } @Override public boolean isSingleton(Object o) { return isSingleton.test(o); } @Override public Comparator<Object> comparator() { return comparator; } @Override public int blockSize() { return blockSize; } @Override public void encode(IList<Object> primitives, DurableOutput out) { codec.encode(primitives, out); } @Override public SkippableIterator decode(DurableInput in, IDurableCollection.Root root) { return codec.decode(in, root); } }; } /** * Creates a tuple encoding, which allows us to decompose a compound object into individual values we know how to * encode. * <p> * To deconstruct the value, we use {@code preEncode}, which yields an array of individual values, which by convention * have the same order as {@code encodings}. * <p> * To reconstruct the value, we use {@code postDecode}, which takes an array of individual values an yields a * compound value. * <p> * The block size of this encoding is equal to the smallest block size of its sub-encodings. */ public static IDurableEncoding.Primitive tuple( Function<Object, Object[]> preEncode, Function<Object[], Object> postDecode, IDurableEncoding... encodings ) { return tuple( preEncode, postDecode, Arrays.stream(encodings).mapToInt(DurableEncodings::blockSize).min().getAsInt(), encodings ); } /** * Same as {@link DurableEncodings#tuple(Function, Function, IDurableEncoding...)}, except that {@code blockSize} can * be explicitly specified. */ public static IDurableEncoding.Primitive tuple( Function<Object, Object[]> preEncode, Function<Object[], Object> postDecode, int blockSize, IDurableEncoding... encodings ) { return new IDurableEncoding.Primitive() { @Override public String description() { StringBuilder sb = new StringBuilder("("); for (IDurableEncoding e : encodings) { sb.append(e.description()).append(", "); } sb.delete(sb.length() - 2, sb.length()).append(")"); return sb.toString(); } @Override public int blockSize() { return blockSize; } @Override public boolean isSingleton(Object o) { Object[] ary = preEncode.apply(o); for (int i = 0; i < ary.length; i++) { if (encodings[i].isSingleton(ary[i])) { return true; } } return false; } @Override public void encode(IList<Object> primitives, DurableOutput out) { int index = 0; IList<Object[]> arrays = primitives.stream().map(preEncode).collect(Lists.linearCollector()); for (IDurableEncoding e : encodings) { final int i = index++; DurableBuffer.flushTo( out, BlockPrefix.BlockType.PRIMITIVE,
inner -> encodeBlock(Lists.lazyMap(arrays, t -> t[i]), e, inner)
4
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorRendezvousResourceReliableTest.java
[ "public class TIBResource {\n\tprivate String filePath;\n\tprivate String type;\n\t\n\tprivate static final String REQUEST_GET_TYPE = \"/jndi:namedResource/@type\";\n\t\n\tpublic TIBResource(String filePath) throws Exception {\n\t\tthis.filePath = filePath;\n\t\tthis.type = Util.xpathEval(filePath, Constants.RESOUR...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.apache.log4j.Logger; import org.junit.Test; import com.tibco.exchange.tibreview.common.TIBResource; import com.tibco.exchange.tibreview.engine.Context; import com.tibco.exchange.tibreview.model.pmd.Violation; import com.tibco.exchange.tibreview.model.rules.Configuration; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; import com.tibco.exchange.tibreview.parser.RulesParser;
package com.tibco.exchange.tibreview.processor.resourcerule; public class CProcessorRendezvousResourceReliableTest { private static final Logger LOGGER = Logger.getLogger(CProcessorRendezvousResourceReliableTest.class); @Test public void testCProcessorRendezvousResourceReliableTest() { TIBResource fileresource; try { fileresource = new TIBResource("src/test/resources/FileResources/RendezvousResourceReliable.rvResource"); fileresource.toString(); LOGGER.info(fileresource.toString()); assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/RendezvousResourceReliable.rvResource, type=rvsharedresource:RVResource]")); Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/RendezvousResourceReliable.xml"); Resource resource = tibrules.getResource(); LOGGER.info(resource.getRule().size()); assertEquals(resource.getRule().size(),1); ConfigurationProcessor a = new ConfigurationProcessor(); Configuration Configuracion = resource.getRule().get(0).getConfiguration();
List<Violation> b = a.process(new Context(), fileresource, resource.getRule().get(0), Configuracion);
1
Daskiworks/ghwatch
app/src/main/java/com/daskiworks/ghwatch/WatchedRepositoriesActivity.java
[ "public class PreferencesUtils {\n\n private static final String TAG = PreferencesUtils.class.getSimpleName();\n\n /*\n * Names of user edited preferences.\n */\n public static final String PREF_SERVER_CHECK_PERIOD = \"pref_serverCheckPeriod\";\n public static final String PREF_SERVER_CHECK_WIFI_ONLY = \"pr...
import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.Toast; import com.daskiworks.ghwatch.backend.PreferencesUtils; import com.daskiworks.ghwatch.backend.ViewDataReloadStrategy; import com.daskiworks.ghwatch.backend.WatchedRepositoriesService; import com.daskiworks.ghwatch.image.ImageLoader; import com.daskiworks.ghwatch.model.BaseViewData; import com.daskiworks.ghwatch.model.LoadingStatus; import com.daskiworks.ghwatch.model.Repository; import com.daskiworks.ghwatch.model.WatchedRepositoriesViewData; import java.util.concurrent.RejectedExecutionException;
/* * Copyright 2014 contributors as indicated by the @authors tag. * * 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.daskiworks.ghwatch; /** * Activity used to show list of watched repositories. * * @author Vlastimil Elias <vlastimil.elias@worldonline.cz> */ public class WatchedRepositoriesActivity extends ActivityBase implements OnRefreshListener { private static final String TAG = WatchedRepositoriesActivity.class.getSimpleName(); // common fields private DataLoaderTask dataLoader; private ListView repositoriesListView; private WatchedRepositoryListAdapter repositoriesListAdapter; // backend services
private ImageLoader imageLoader;
2
Arjun-sna/Android-AudioRecorder-App
app/src/main/java/in/arjsna/audiorecorder/audiorecording/RecordFragment.java
[ "public class AppConstants {\n public static final String ACTION_PAUSE = \"in.arjsna.audiorecorder.PAUSE\";\n public static final String ACTION_RESUME = \"in.arjsna.audiorecorder.RESUME\";\n public static final String ACTION_STOP = \"in.arjsna.audiorecorder.STOP\";\n public static final String ACTION_IN_SERVICE...
import android.animation.FloatEvaluator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.TextView; import com.jakewharton.rxbinding2.view.RxView; import in.arjsna.audiorecorder.AppConstants; import in.arjsna.audiorecorder.R; import in.arjsna.audiorecorder.activities.PlayListActivity; import in.arjsna.audiorecorder.activities.SettingsActivity; import in.arjsna.audiorecorder.audiovisualization.GLAudioVisualizationView; import in.arjsna.audiorecorder.di.qualifiers.ActivityContext; import in.arjsna.audiorecorder.mvpbase.BaseFragment; import in.arjsna.audiorecorder.recordingservice.AudioRecordService; import in.arjsna.audiorecorder.recordingservice.AudioRecorder; import in.arjsna.audiorecorder.theme.ThemeHelper; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import javax.inject.Inject;
package in.arjsna.audiorecorder.audiorecording; public class RecordFragment extends BaseFragment implements AudioRecordMVPView { private static final String LOG_TAG = RecordFragment.class.getSimpleName(); private FloatingActionButton mRecordButton = null; private FloatingActionButton mPauseButton = null; private GLAudioVisualizationView audioVisualization; private TextView chronometer; private boolean mIsServiceBound = false; private AudioRecordService mAudioRecordService; private ObjectAnimator alphaAnimator; private FloatingActionButton mSettingsButton; private FloatingActionButton mPlayListBtn; @Inject @ActivityContext public Context mContext; @Inject public AudioRecordPresenter<AudioRecordMVPView> audioRecordPresenter; public static RecordFragment newInstance() { return new RecordFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); audioRecordPresenter.onAttach(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View recordView = inflater.inflate(R.layout.fragment_record, container, false); initViews(recordView); bindEvents(); return recordView; } private void bindEvents() { RxView.clicks(mRecordButton) .subscribe(o -> audioRecordPresenter.onToggleRecodingStatus()); RxView.clicks(mSettingsButton)
.subscribe(o -> startActivity(new Intent(mContext, SettingsActivity.class)));
2
onepf/OPFPush
opfpush/src/test/java/org/onepf/opfpush/OPFPushHelperTest.java
[ "@SuppressWarnings(\"PMD.MissingStaticMethodInNonInstantiatableClass\")\npublic final class Configuration {\n\n @NonNull\n private final List<PushProvider> providers;\n\n @Nullable\n private final EventListener eventListener;\n\n @Nullable\n private final CheckManifestHandler checkManifestHandler;...
import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import junit.framework.Assert; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.onepf.opfpush.configuration.Configuration; import org.onepf.opfpush.listener.SimpleEventListener; import org.onepf.opfpush.mock.MockPushProvider; import org.onepf.opfpush.model.AvailabilityResult; import org.onepf.opfpush.model.UnrecoverablePushError; import org.onepf.opfpush.pushprovider.PushProvider; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
package org.onepf.opfpush; /** * @author antonpp * @since 14.04.15 */ @Config(sdk = JELLY_BEAN_MR2, manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class OPFPushHelperTest extends Assert { private static final String TAG = OPFPushHelperTest.class.getSimpleName(); private static final int BUFFER_INITIAL_CAPACITY = 80; @TargetApi(Build.VERSION_CODES.KITKAT) @After public void eraseSettingsInstance() { Field instanceField; synchronized (Settings.class) { try { instanceField = Settings.class.getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, null); } catch (IllegalAccessException | NoSuchFieldException e) { Log.e(TAG, e.getMessage()); } } } @TargetApi(Build.VERSION_CODES.KITKAT) @Test public void testGetProviderName() { final String expected = "Courier"; final PushProvider provider = new MockPushProvider.Builder() .setName(expected)
.setAvailabilityResult(new AvailabilityResult(true))
3
grennis/MongoExplorer
app/src/main/java/com/innodroid/mongobrowser/ui/ConnectionEditDialogFragment.java
[ "public class Constants {\n\tpublic static final String LOG_TAG = \"mongoexp\";\n\n\tpublic static final String ARG_CONNECTION_ID = \"connid\";\n\tpublic static final String ARG_COLLECTION_INDEX = \"collname\";\n\tpublic static final String ARG_ACTIVATE_ON_CLICK = \"actonclick\";\n\tpublic static final String ARG_D...
import android.app.Activity; import android.app.Dialog; import android.content.ContentUris; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.innodroid.mongobrowser.Constants; import com.innodroid.mongobrowser.Events; import com.innodroid.mongobrowser.R; import com.innodroid.mongobrowser.data.MongoBrowserProvider; import com.innodroid.mongobrowser.data.MongoBrowserProviderHelper; import com.innodroid.mongobrowser.util.UiUtils; import butterknife.Bind;
package com.innodroid.mongobrowser.ui; public class ConnectionEditDialogFragment extends BaseDialogFragment implements LoaderCallbacks<Cursor> { @Bind(R.id.edit_connection_name) TextView mNameView; @Bind(R.id.edit_connection_server) TextView mServerView; @Bind(R.id.edit_connection_port) TextView mPortView; @Bind(R.id.edit_connection_db) TextView mDatabaseView; @Bind(R.id.edit_connection_user) TextView mUserView; @Bind(R.id.edit_connection_pass) TextView mPasswordView; public ConnectionEditDialogFragment() { super(); } public static ConnectionEditDialogFragment newInstance(long id) { ConnectionEditDialogFragment fragment = new ConnectionEditDialogFragment(); Bundle args = new Bundle(); args.putLong(Constants.ARG_CONNECTION_ID, id); fragment.setArguments(args); return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = super.onCreateDialog(R.layout.fragment_connection_edit); long id = getArguments().getLong(Constants.ARG_CONNECTION_ID, 0); if (id != 0) getLoaderManager().initLoader(0, getArguments(), this); return UiUtils.buildAlertDialog(view, R.drawable.ic_mode_edit_black, R.string.title_edit_connection, true, 0, new UiUtils.AlertDialogCallbacks() { @Override public boolean onOK() { return save(); } @Override public boolean onNeutralButton() { return false; } }); } private boolean save() { String name = mNameView.getText().toString(); String server = mServerView.getText().toString(); String porttxt = mPortView.getText().toString(); String db = mDatabaseView.getText().toString(); String user = mUserView.getText().toString(); String pass = mPasswordView.getText().toString(); if (name.length() == 0 || server.length() == 0 || porttxt.length() == 0 || db.length() == 0) { Toast.makeText(getActivity(), "Required values not provided", Toast.LENGTH_SHORT).show(); return false; } int port = 0; try { port = Integer.parseInt(porttxt); } catch (Exception e) { Toast.makeText(getActivity(), "Port must be a number", Toast.LENGTH_SHORT).show(); return false; } MongoBrowserProviderHelper helper = new MongoBrowserProviderHelper(getActivity().getContentResolver()); long id = getArguments().getLong(Constants.ARG_CONNECTION_ID, 0); if (id == 0) { id = helper.addConnection(name, server, port, db, user, pass);
Events.postConnectionAdded(id);
1
kecskemeti/dissect-cf
src/test/java/at/ac/uibk/dps/cloud/simulator/test/simple/cloud/ResourceConsumptionTest.java
[ "public abstract class Timed implements Comparable<Timed> {\n\n\t/**\n\t * The main container for all recurring events in the system\n\t */\n\tprivate static final PriorityQueue<Timed> timedlist = new PriorityQueue<Timed>();\n\t/**\n\t * If set to true, the event loop is processing this object at the moment.\n\t */...
import at.ac.uibk.dps.cloud.simulator.test.ConsumptionEventAssert; import at.ac.uibk.dps.cloud.simulator.test.ConsumptionEventFoundation; import hu.mta.sztaki.lpds.cloud.simulator.DeferredEvent; import hu.mta.sztaki.lpds.cloud.simulator.Timed; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ConsumptionEventAdapter; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.MaxMinConsumer; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.MaxMinProvider; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ResourceConsumption; import hu.mta.sztaki.lpds.cloud.simulator.iaas.resourcemodel.ResourceConsumption.ConsumptionEvent; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test;
/* * ======================================================================== * DIScrete event baSed Energy Consumption simulaTor * for Clouds and Federations (DISSECT-CF) * ======================================================================== * * This file is part of DISSECT-CF. * * DISSECT-CF is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * DISSECT-CF 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DISSECT-CF. If not, see <http://www.gnu.org/licenses/>. * * (C) Copyright 2014, Gabor Kecskemeti (gkecskem@dps.uibk.ac.at, * kecskemeti.gabor@sztaki.mta.hu) */ package at.ac.uibk.dps.cloud.simulator.test.simple.cloud; public class ResourceConsumptionTest extends ConsumptionEventFoundation { public static final double processingTasklen = 1; public static final double permsProcessing = processingTasklen / aSecond;
MaxMinProvider offer;
2
sdenier/GecoSI
src/test/net/gecosi/dataframe/Si5DataFrameTest.java
[ "public class Si5DataFrame extends SiAbstractDataFrame {\n\t\n\tprivate static final int SI5_TIMED_PUNCHES = 30;\n\n\tpublic Si5DataFrame(SiMessage message) {\n\t\tthis.dataFrame = extractDataFrame(message);\n\t\tthis.siNumber = extractSiNumber();\n\t}\n\n\tprotected byte[] extractDataFrame(SiMessage message) {\n\t...
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import net.gecosi.dataframe.Si5DataFrame; import net.gecosi.dataframe.SiDataFrame; import net.gecosi.dataframe.SiPunch; import net.gecosi.internal.SiMessage; import org.junit.Test; import test.net.gecosi.SiMessageFixtures;
/** * Copyright (c) 2013 Simon Denier */ package test.net.gecosi.dataframe; /** * @author Simon Denier * @since Mar 15, 2013 * */ public class Si5DataFrameTest { @Test public void getSiCardNumber() { assertThat(subject304243().getSiNumber(), equalTo("304243")); assertThat(subject36353().getSiNumber(), equalTo("36353")); } @Test public void getSiCardSeries() { assertThat(subject36353().getSiSeries(), equalTo("SiCard 5")); } @Test public void getStartTime() { assertThat(subject36353().getStartTime(), equalTo(1234000L)); } @Test public void getFinishTime() { assertThat(subject36353().getFinishTime(), equalTo(4321000L)); } @Test public void getCheckTime() { assertThat(subject36353().getCheckTime(), equalTo(4444000L)); } @Test public void getNbPunches() { assertThat(subject36353().getNbPunches(), equalTo(36)); } @Test public void getPunches() { SiPunch[] punches = subject36353().getPunches(); assertThat(punches[0].code(), equalTo(36)); assertThat(punches[0].timestamp(), equalTo(40059000L)); assertThat(punches[9].code(), equalTo(59)); assertThat(punches[9].timestamp(), equalTo(40104000L)); } @Test public void getPunches_with36Punches() { SiPunch[] punches = subject36353().getPunches(); assertThat(punches[30].code(), equalTo(31)); assertThat(punches[30].timestamp(), equalTo(Si5DataFrame.NO_TIME)); assertThat(punches[35].code(), equalTo(36)); assertThat(punches[35].timestamp(), equalTo(Si5DataFrame.NO_TIME)); } @Test public void getPunches_withZeroHourShift() { SiDataFrame subject = subject36353().startingAt(41400000L); assertThat(subject.getStartTime(), equalTo(44434000L)); assertThat(subject.getFinishTime(), equalTo(47521000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[9].timestamp(), equalTo(83304000L)); assertThat(punches[10].timestamp(), equalTo(Si5DataFrame.NO_TIME)); assertThat(punches[35].timestamp(), equalTo(Si5DataFrame.NO_TIME)); } @Test public void getPunches_withoutStartTime() { SiDataFrame subject = subject304243(); assertThat(subject.getStartTime(), equalTo(SiDataFrame.NO_TIME)); assertThat(subject.getFinishTime(), equalTo(43704000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[0].timestamp(), equalTo(40059000L)); assertThat(punches[9].timestamp(), equalTo(40104000L)); } @Test public void getPunches_withoutStartTime_withMidnightShift() { SiDataFrame subject = subject304243().startingAt(82800000L); assertThat(subject.getStartTime(), equalTo(SiDataFrame.NO_TIME)); assertThat(subject.getFinishTime(), equalTo(86904000L)); SiPunch[] punches = subject.getPunches(); assertThat(punches[0].timestamp(), equalTo(83259000L)); assertThat(punches[9].timestamp(), equalTo(83304000L)); } @Test public void advanceTimePast_doesNotChangeTimeWhen() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat("Time already past Ref", subject.advanceTimePast(1000, 0), equalTo(1000L)); assertThat("Time less than 1 hour behind Ref", subject.advanceTimePast(1000, 1500), equalTo(1000L)); assertThat("No time for Ref", subject.advanceTimePast(1000, SiDataFrame.NO_TIME), equalTo(1000L)); } @Test public void advanceTimePast_advancesBy12HoursStep() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat(subject.advanceTimePast(0, 3600001), equalTo(43200000L)); assertThat(subject.advanceTimePast(3600000, 100000000L), equalTo(133200000L)); // + 36 hours } @Test public void advanceTimePast_returnsNoTime() { Si5DataFrame subject = (Si5DataFrame) subject36353(); assertThat("Time is unknown", subject.advanceTimePast(0xEEEE * 1000, 0), equalTo(SiDataFrame.NO_TIME)); } private SiDataFrame subject304243() {
return new Si5DataFrame(SiMessageFixtures.sicard5_data).startingAt(0);
4
brutusin/wava
wava-core/src/main/java/org/brutusin/wava/core/io/CommandLineRequestExecutor.java
[ "public enum OpName {\n submit,\n cancel,\n jobs,\n group,\n exit\n}", "public enum Event {\r\n\r\n id,\r\n queued,\r\n priority,\r\n running,\r\n niceness,\r\n retcode,\r\n cancelled,\r\n ping,\r\n error,\r\n exceed_tree,\r\n shutdown,\r\n maxrss,\r\n maxswap...
import org.brutusin.wava.io.LineListener; import org.brutusin.wava.io.RequestExecutor; import org.brutusin.wava.utils.ANSICode; import org.brutusin.wava.io.OpName; import org.brutusin.wava.io.Event; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.brutusin.json.ParseException; import org.brutusin.json.spi.JsonCodec; import org.brutusin.json.spi.JsonNode; import org.brutusin.wava.Utils; import org.brutusin.wava.env.EnvEntry; import org.brutusin.wava.input.Input; import org.brutusin.wava.io.EventListener;
/* * Copyright 2016 Ignacio del Valle Alles idelvall@brutusin.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.brutusin.wava.core.io; /** * * @author Ignacio del Valle Alles idelvall@brutusin.org */ public class CommandLineRequestExecutor extends RequestExecutor { public Integer executeRequest(OpName opName, Input input) throws IOException, InterruptedException { if (input == null) { input = new Input(); } return executeRequest(opName, input, null, false); } public Integer executeRequest(OpName opName, Input input, final OutputStream eventStream, boolean prettyEvents) throws IOException, InterruptedException { EventListener evtListener = null; if (eventStream != null) { evtListener = new EventListener() { @Override public void onEvent(Event evt, String value, long time) { if (evt == Event.ping) { return; } if (!prettyEvents) { synchronized (eventStream) { try { if (value == null) { eventStream.write((time + ":" + evt.name() + "\n").getBytes()); } else { eventStream.write((time + ":" + evt.name() + ":" + value + "\n").getBytes()); } } catch (IOException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } else { Date date = new Date(time); ANSICode color = ANSICode.CYAN; if (evt == Event.id || evt == Event.running) { color = ANSICode.GREEN; } else if (evt == Event.queued) { color = ANSICode.YELLOW; } else if (evt == Event.cancelled) { color = ANSICode.YELLOW; } else if (evt == Event.retcode) { if (value.equals("0")) { color = ANSICode.GREEN; } else { color = ANSICode.RED; } } else if (evt == Event.error) { color = ANSICode.RED; if (value != null) { try { JsonNode node = JsonCodec.getInstance().parse(value); value = node.asString(); } catch (ParseException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } else if (evt == Event.shutdown) { color = ANSICode.RED; } synchronized (eventStream) { try { eventStream.write((color.getCode() + "[wava] [" + Utils.DATE_FORMAT.format(date) + "] [" + evt + (value != null ? (":" + value) : "") + "]" + ANSICode.RESET.getCode() + "\n").getBytes()); } catch (IOException ex) { Logger.getLogger(CommandLineRequestExecutor.class.getName()).log(Level.SEVERE, null, ex); } } } } }; }
LineListener sterrListener = new LineListener() {
6
naotawool/salary-calculation
src/test/java/salarycalculation/database/EmployeeDaoTest.java
[ "public static EmployeeRecordAssert assertThat(EmployeeRecord actual) {\n return new EmployeeRecordAssert(actual);\n}", "public static RecordNotFoundExceptionMatcher isClass(Class<?> expectEntityClass) {\n return new RecordNotFoundExceptionMatcher(expectEntityClass, null, null);\n}", "public static Record...
import static com.ninja_squad.dbsetup.Operations.deleteAllFrom; import static com.ninja_squad.dbsetup.Operations.insertInto; import static com.ninja_squad.dbsetup.Operations.sequenceOf; import static com.ninja_squad.dbsetup.destination.DriverManagerDestination.with; import static org.assertj.core.api.Assertions.assertThat; import static salarycalculation.assertions.EmployeeRecordAssert.assertThat; import static salarycalculation.matchers.RecordNotFoundExceptionMatcher.isClass; import static salarycalculation.matchers.RecordNotFoundExceptionMatcher.isKey; import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.internal.util.reflection.Whitebox; import com.ninja_squad.dbsetup.DbSetup; import com.ninja_squad.dbsetup.DbSetupTracker; import com.ninja_squad.dbsetup.operation.Operation; import salarycalculation.database.model.EmployeeRecord; import salarycalculation.dbsetup.CapabilitySetupSupport; import salarycalculation.dbsetup.OrganizationSetupSupport; import salarycalculation.dbsetup.RoleSetupSupport; import salarycalculation.exception.RecordNotFoundException;
package salarycalculation.database; /** * {@link EmployeeDao}に対するテストクラス。 * * @author naotake */ @RunWith(Enclosed.class) public class EmployeeDaoTest { public static class 社員情報を1件取得する場合 extends EmployeeDaoTestBase { @BeforeClass public static void setUpOnce() throws Exception { dbSetupTracker = new DbSetupTracker(); } @Rule public ExpectedException expect = ExpectedException.none(); @Test public void 社員情報を取得できること() { dbSetupTracker.skipNextLaunch(); EmployeeRecord actual = testee.get("1");
assertThat(actual).isNotNull().hasNo(1).hasName("愛媛 蜜柑");
0
TrumanDu/AutoProgramming
src/main/java/com/aibibang/web/system/service/impl/SysRoleServiceImpl.java
[ "public class Page<T> extends RowBounds {\r\n\r\n\tprivate int pageNo = 1;\t\t\t\t// 当前页数\r\n\tprivate int pageSize = 10;\t\t\t// 每页显示行数\r\n\tprivate int totalCount;\t\t\t\t// 总行数\r\n\tprivate int totalPages;\t\t\t\t// 总页数\r\n\t\r\n\tprivate List<T> result = new ArrayList<T>();// 查询结果\r\n\t\r\n\tprivate int offset;...
import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import com.aibibang.common.persistence.Page; import com.aibibang.web.system.dao.SysRoleDao; import com.aibibang.web.system.dao.SysRoleMenuDao; import com.aibibang.web.system.entity.SysRole; import com.aibibang.web.system.entity.SysRoleMenu; import com.aibibang.web.system.service.SysRoleService;
package com.aibibang.web.system.service.impl; /** * * 角色管理service实现类 * * <pre> * 历史记录: * 2016-08-01 22:42 King * 新建文件 * </pre> * * @author * <pre> * SD * King * PG * King * UT * * MA * </pre> * @version $Rev$ * * <p/> $Id$ * */ @Service("sysRoleService") public class SysRoleServiceImpl implements SysRoleService { @Resource private SysRoleDao sysRoleDao; @Resource private SysRoleMenuDao sysRoleMenuDao; @Override
public Page<SysRole> findByPage(SysRole sysRole, Page<SysRole> page) {
3
nullpointerexceptionapps/TeamCityDownloader
java/com/raidzero/teamcitydownloader/activities/BuildInfoActivity.java
[ "public class TeamCityBuild implements Parcelable {\n private static final String tag = \"TeamCityBuild\";\n\n private String number;\n private String status;\n private String url;\n private String webUrl;\n private String branch;\n\n public TeamCityBuild(String number, String status, String ur...
import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.raidzero.teamcitydownloader.R; import com.raidzero.teamcitydownloader.data.TeamCityBuild; import com.raidzero.teamcitydownloader.data.WebResponse; import com.raidzero.teamcitydownloader.global.DateUtility; import com.raidzero.teamcitydownloader.global.Debug; import com.raidzero.teamcitydownloader.global.QueryUtility; import com.raidzero.teamcitydownloader.global.TeamCityXmlParser; import com.raidzero.teamcitydownloader.global.ThemeUtility; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.text.ParseException; import java.util.HashMap; import java.util.Map;
package com.raidzero.teamcitydownloader.activities; /** * Created by raidzero on 8/14/14. */ public class BuildInfoActivity extends TeamCityActivity { private static final String tag = "BuildInfoActivity"; private TeamCityBuild build; private QueryUtility queryUtility; private TextView txt_triggered; private TextView txt_agent; private TextView txt_project; private TextView txt_queued; private TextView txt_started; private TextView txt_finished; private TextView txt_branch; private TextView txt_status; private TextView custom_properties_header; private LinearLayout custom_properties_container; // build info container private class TeamCityBuildInfo { public String branchName; public String webUrl; // not displayed public Map<String, String> buildProperties = new HashMap<String, String>(); public Map<String, String> customProperties = new HashMap<String, String>(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); build = intent.getParcelableExtra("selectedBuild"); queryUtility = new QueryUtility(this, build.getUrl()); setContentView(R.layout.build_info); } @Override public boolean onCreateOptionsMenu(Menu menu) {
Debug.Log(tag, "onCreateOptionsMenu()");
3
trond-arve-wasskog/nytt-folkeregister-atom
datomic/src/main/java/ske/folkeregister/dw/Server.java
[ "@SuppressWarnings(\"unchecked\")\npublic class FeedGenerator implements Runnable {\n\n private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);\n\n private static final Abdera abdera = Abdera.getInstance();\n private static final String attr_query =\n \"[:find ?attrname :in $ ?att...
import com.bazaarvoice.dropwizard.webjars.WebJarBundle; import com.sun.jersey.api.client.Client; import datomic.Connection; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import ske.folkeregister.datomic.feed.FeedGenerator; import ske.folkeregister.datomic.person.DatomicPersonApi; import ske.folkeregister.datomic.person.PersonApi; import ske.folkeregister.datomic.util.IO; import ske.folkeregister.dw.api.PersonResource; import ske.folkeregister.dw.conf.ServerConfig; import ske.folkeregister.dw.managed.DatomicConnectionManager; import ske.folkeregister.dw.managed.ThreadManager;
package ske.folkeregister.dw; public class Server extends Application<ServerConfig> { public static void main(String[] args) throws Exception { new Server().run(new String[]{"server", "src/main/conf/config.yml"}); } @Override public void initialize(Bootstrap<ServerConfig> bootstrap) { bootstrap.addBundle(new WebJarBundle()); bootstrap.addBundle(new AssetsBundle("/web/", "/web", "index.html")); } @Override public void run(ServerConfig conf, Environment env) throws Exception {
final Connection conn = IO.newMemConnection();
3
BoD/irondad
src/main/java/org/jraf/irondad/handler/commitstrip/CommitstripHandler.java
[ "public class Config {\n\n public static final boolean LOGD = true;\n\n}", "public class Constants {\n public static final String TAG = \"irondad/\";\n\n public static final String PROJECT_FULL_NAME = \"BoD irondad\";\n public static final String PROJECT_URL = \"https://github.com/BoD/irondad\";\n ...
import org.jraf.irondad.Config; import org.jraf.irondad.Constants; import org.jraf.irondad.handler.CommandHandler; import org.jraf.irondad.handler.HandlerContext; import org.jraf.irondad.protocol.Command; import org.jraf.irondad.protocol.Connection; import org.jraf.irondad.protocol.Message; import org.jraf.irondad.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.github.kevinsawicki.http.HttpRequest; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2016 Nicolas Pomepuy * Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/>. */ package org.jraf.irondad.handler.commitstrip; public class CommitstripHandler extends CommandHandler { private static final String TAG = Constants.TAG + CommitstripHandler.class.getSimpleName(); private static final String URL_HTML = "http://www.commitstrip.com/en/"; private final ExecutorService mThreadPool = Executors.newCachedThreadPool(); @Override protected String getCommand() { return "!commitstrip"; } @Override protected void handleChannelMessage(final Connection connection, final String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) throws Exception {
if (Config.LOGD) Log.d(TAG, "handleChannelMessage");
0
BottleRocketStudios/Android-GroundControl
GroundControl/groundcontrol/src/main/java/com/bottlerocketstudios/groundcontrol/convenience/StandardExecutionBuilder.java
[ "public class AgentExecutor implements InactivityCleanupListener {\n\n private static final String TAG = AgentExecutor.class.getSimpleName();\n\n public static final String DEFAULT_AGENT_EXECUTOR_ID = \"<def>\";\n\n private static final ConcurrentHashMap<String, AgentExecutor> sAgentExecutorMap = new Concu...
import android.text.TextUtils; import android.util.Log; import com.bottlerocketstudios.groundcontrol.AgentExecutor; import com.bottlerocketstudios.groundcontrol.agent.Agent; import com.bottlerocketstudios.groundcontrol.executor.JobPriority; import com.bottlerocketstudios.groundcontrol.listener.AgentListener; import com.bottlerocketstudios.groundcontrol.looper.LooperController; import com.bottlerocketstudios.groundcontrol.policy.AgentPolicy; import com.bottlerocketstudios.groundcontrol.policy.AgentPolicyBuilder; import com.bottlerocketstudios.groundcontrol.policy.StandardAgentPolicyBuilder; import com.bottlerocketstudios.groundcontrol.tether.AgentTether; import java.util.concurrent.TimeUnit;
/* * Copyright (c) 2016. Bottle Rocket LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bottlerocketstudios.groundcontrol.convenience; /** * Standard implementation of ExecutionBuilder. New instances should be created by the StandardExecutionBuilderFactory. */ public class StandardExecutionBuilder<ResultType, ProgressType> implements ExecutionBuilder<ResultType, ProgressType> { private static final long DEFAULT_ONE_TIME_CACHE_AGE_MS = TimeUnit.MINUTES.toMillis(2); private static final String TAG = StandardExecutionBuilder.class.getSimpleName(); private final Agent<ResultType, ProgressType> mAgent; private final String mAgentExecutorId;
private final Class<? extends AgentPolicyBuilder> mAgentPolicyBuilderClass;
6
DDoS/JICI
src/main/java/ca/sapon/jici/lexer/literal/number/LongLiteral.java
[ "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n ...
import ca.sapon.jici.lexer.TokenID; import ca.sapon.jici.util.StringUtil; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.EvaluatorException; import ca.sapon.jici.evaluator.type.PrimitiveType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.evaluator.value.ValueKind; import ca.sapon.jici.lexer.Symbol;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * 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 ca.sapon.jici.lexer.literal.number; public class LongLiteral extends NumberLiteral { private long value = 0; private boolean evaluated = false; public LongLiteral(String source, int index) { super(TokenID.LITERAL_LONG, source, index); } private LongLiteral(String source, int start, int end) { super(TokenID.LITERAL_LONG, source, start, end); } private void evaluate() { if (!evaluated) { String source = StringUtil.reduceSign(getSource()); final int lastIndex = source.length() - 1; if (StringUtil.equalsNoCaseASCII(source.charAt(lastIndex), 'l')) { source = source.substring(0, lastIndex); } final int radix = StringUtil.findRadix(source); try { source = StringUtil.removeRadixIdentifier(source, radix); value = Long.parseLong(source, radix); } catch (Exception exception) {
throw new EvaluatorException(exception.getMessage(), this);
1
lumag/JBookReader
src/org/jbookreader/book/parser/FB2Parser.java
[ "public interface IBinaryData {\n\n\t/**\n\t * Returns the content-type of the blob.\n\t * @return the content-type.\n\t */\n\tString getContentType();\n\n\t/**\n\t * Sets the content-type of the blob.\n\t * @param contentType new content-type\n\t */\n\tvoid setContentType(String contentType);\n\t\n\t/**\n\t * Retu...
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.jbookreader.book.bom.IBinaryData; import org.jbookreader.book.bom.IBook; import org.jbookreader.book.bom.IContainerNode; import org.jbookreader.book.bom.IImageNode; import org.jbookreader.book.bom.INode; import org.jbookreader.book.bom.impl.Book; import org.jbookreader.book.stylesheet.IStyleSheet; import org.jbookreader.book.stylesheet.fb2.FB2StyleSheet; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory;
/* * JBookReader - Java FictionBook Reader * Copyright (C) 2006 Dmitry Baryshkov * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jbookreader.book.parser; /** * This class represents a parser for the FB2 books format. * * @author Dmitry Baryshkov (dbaryshkov@gmail.com) * */ public class FB2Parser { /** * The namespace of FB2 tags */ public static final String FB2_XMLNS_URI = "http://www.gribuser.ru/xml/fictionbook/2.0"; /** * This parses the book located at the <code>uri</code>. * @param uri the location of book to parse * @return the parsed book representation * @throws IOException in case of I/O problem * @throws SAXException in case of XML parsing problem */
public static IBook parse(String uri) throws IOException, SAXException {
1
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/storylist/StoryListFragment.java
[ "public class HackerNewsApplication extends SugarApp {\n private static boolean mDebug = BuildConfig.DEBUG;\n private static HackerNewsApplication sInstance;\n private Context mContext;\n private static AppComponent sAppComponent;\n\n private static AppModule sAppModule;\n\n @Override\n public ...
import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import com.bluelinelabs.logansquare.LoganSquare; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.Story; import io.dwak.holohackernews.app.util.HNLog; import io.dwak.holohackernews.app.util.UIUtils; import retrofit.RetrofitError; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers;
package io.dwak.holohackernews.app.ui.storylist; public class StoryListFragment extends BaseViewModelFragment<StoryListViewModel> { public static final String FEED_TO_LOAD = "feed_to_load"; private static final String TAG = StoryListFragment.class.getSimpleName(); public static final String TOP_OF_LIST = "TOP_OF_LIST"; public static final String STORY_LIST = "STORY_LIST"; @InjectView(R.id.story_list) RecyclerView mRecyclerView; @InjectView(R.id.swipe_container) SwipeRefreshLayout mSwipeRefreshLayout; private OnStoryListFragmentInteractionListener mListener; private StoryListAdapter mRecyclerAdapter; private LinearLayoutManager mLayoutManager; @Inject StoryListViewModel mViewModel; public static StoryListFragment newInstance(@StoryListViewModel.FeedType int feedType) { StoryListFragment fragment = new StoryListFragment(); Bundle args = new Bundle(); args.putInt(FEED_TO_LOAD, feedType); fragment.setArguments(args); return fragment; } private void refresh() { mRecyclerAdapter.clear(); getViewModel().setIsRestoring(false); getViewModel().setStoryList(null); react(getViewModel().getStories(), false); } private void react(Observable<Story> stories, boolean pageTwo) { stories.subscribe(new Subscriber<Story>() { @Override public void onCompleted() { showProgress(false); mSwipeRefreshLayout.setRefreshing(false); getViewModel().setPageTwoLoaded(pageTwo); } @Override public void onError(Throwable e) { if (e instanceof RetrofitError) { Toast.makeText(getActivity(), R.string.story_list_error_toast_message, Toast.LENGTH_SHORT).show(); } else { throw new RuntimeException(e); } } @Override public void onNext(Story story) { if (story.getStoryId() != null && mRecyclerAdapter.getPositionOfItem(story) == -1) { mRecyclerAdapter.addStory(story); } } }); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnStoryListFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnStoryListFragmentInteractionListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerViewModelComponent.builder()
.appComponent(HackerNewsApplication.getAppComponent())
0
52North/SensorPlanningService
52n-sps-testplugin/src/test/java/org/n52/sps/sensor/cite/CiteTaskResultAccessTest.java
[ "public class ResultAccessDataServiceReference {\r\n \r\n private Long id; // database id\r\n \r\n private String reference;\r\n \r\n private String role;\r\n \r\n private String title;\r\n \r\n private String identifier;\r\n \r\n private String referenceAbstract;\r\n \r\n ...
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.junit.Before; import org.junit.Test; import org.n52.sps.sensor.model.ResultAccessDataServiceReference; import org.n52.sps.sensor.model.SensorTask; import org.n52.sps.service.admin.MissingSensorInformationException; import org.n52.sps.service.core.SensorInstanceProvider; import org.n52.testing.utilities.FileContentLoader; import org.x52North.schemas.sps.v2.SensorInstanceDataDocument; import org.x52North.schemas.sps.v2.SensorInstanceDataDocument.SensorInstanceData; import static org.junit.Assert.*; import net.opengis.ows.x11.ServiceReferenceType;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.sps.sensor.cite; public class CiteTaskResultAccessTest { private CiteTaskResultAccess citeTaskResultAccess; private String procedure; private String taskId; @Before public void setUp() throws Exception { XmlObject file = FileContentLoader.loadXmlFileViaClassloader("/files/sensorInstanceData.xml", getClass()); SensorInstanceDataDocument.Factory.newInstance(); SensorInstanceDataDocument instanceDataDoc = SensorInstanceDataDocument.Factory.parse(file.newInputStream()); SensorInstanceData sensorInstanceData = instanceDataDoc.getSensorInstanceData(); SensorInstanceProviderSeam sensorInstanceProviderSeam = new SensorInstanceProviderSeam(); ResultAccessDataServiceReference reference = sensorInstanceProviderSeam.createResultAccess(sensorInstanceData); procedure = "http://host.tld/procedure1/"; taskId = "http://host.tld/procedure1/tasks/1";
SensorTask validTask = new SensorTask(taskId, procedure);
1
VladThodo/behe-keyboard
app/src/main/java/com/vlath/keyboard/latin/settings/Settings.java
[ "public final class KeyboardTheme implements Comparable<KeyboardTheme> {\n private static final String TAG = KeyboardTheme.class.getSimpleName();\n\n static final String KLP_KEYBOARD_THEME_KEY = \"pref_keyboard_layout_20110916\";\n static final String LXX_KEYBOARD_THEME_KEY = \"pref_keyboard_theme_20140509...
import com.vlath.keyboard.latin.AudioAndHapticFeedbackManager; import com.vlath.keyboard.latin.InputAttributes; import com.vlath.keyboard.latin.utils.AdditionalSubtypeUtils; import com.vlath.keyboard.latin.utils.ResourceUtils; import com.vlath.keyboard.latin.utils.RunInLocale; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.preference.PreferenceManager; import androidx.annotation.NonNull; import android.util.Log; import java.util.Locale; import java.util.concurrent.locks.ReentrantLock; import com.vlath.keyboard.R; import com.vlath.keyboard.keyboard.KeyboardTheme;
private final ReentrantLock mSettingsValuesLock = new ReentrantLock(); private static final Settings sInstance = new Settings(); public static Settings getInstance() { return sInstance; } public static void init(final Context context) { sInstance.onCreate(context); } private Settings() { // Intentional empty constructor for singleton. } private void onCreate(final Context context) { mContext = context; mRes = context.getResources(); mPrefs = PreferenceManager.getDefaultSharedPreferences(context); mPrefs.registerOnSharedPreferenceChangeListener(this); } public void onDestroy() { mPrefs.unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) { mSettingsValuesLock.lock(); try { if (mSettingsValues == null) { // TODO: Introduce a static function to register this class and ensure that // loadSettings must be called before "onSharedPreferenceChanged" is called. Log.w(TAG, "onSharedPreferenceChanged called before loadSettings."); return; } loadSettings(mContext, mSettingsValues.mLocale, mSettingsValues.mInputAttributes); } finally { mSettingsValuesLock.unlock(); } } public void loadSettings(final Context context, final Locale locale, @NonNull final InputAttributes inputAttributes) { mSettingsValuesLock.lock(); mContext = context; try { final SharedPreferences prefs = mPrefs; final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { @Override protected SettingsValues job(final Resources res) { return new SettingsValues(prefs, res, inputAttributes); } }; mSettingsValues = job.runInLocale(mRes, locale); } finally { mSettingsValuesLock.unlock(); } } // TODO: Remove this method and add proxy method to SettingsValues. public SettingsValues getCurrent() { return mSettingsValues; } // Accessed from the settings interface, hence public public static boolean readKeypressSoundEnabled(final SharedPreferences prefs, final Resources res) { return prefs.getBoolean(PREF_SOUND_ON, res.getBoolean(R.bool.config_default_sound_enabled)); } public static boolean readVibrationEnabled(final SharedPreferences prefs, final Resources res) { final boolean hasVibrator = AudioAndHapticFeedbackManager.getInstance().hasVibrator(); return hasVibrator && prefs.getBoolean(PREF_VIBRATE_ON, res.getBoolean(R.bool.config_default_vibration_enabled)); } public static boolean readFromBuildConfigIfToShowKeyPreviewPopupOption(final Resources res) { return res.getBoolean(R.bool.config_enable_show_key_preview_popup_option); } public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs, final Resources res) { final boolean defaultKeyPreviewPopup = res.getBoolean( R.bool.config_default_key_preview_popup); if (!readFromBuildConfigIfToShowKeyPreviewPopupOption(res)) { return defaultKeyPreviewPopup; } return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup); } public static int readKeyPreviewPopupDismissDelay(final SharedPreferences prefs, final Resources res) { return Integer.parseInt(prefs.getString(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY, Integer.toString(res.getInteger( R.integer.config_key_preview_linger_timeout)))); } public static boolean readShowsLanguageSwitchKey(final SharedPreferences prefs) { return !prefs.getBoolean(PREF_HIDE_LANGUAGE_SWITCH_KEY, false); } public static boolean readHideSpecialChars(final SharedPreferences prefs) { return prefs.getBoolean(PREF_HIDE_SPECIAL_CHARS, false); } public static boolean readShowNumberRow(final SharedPreferences prefs) { return prefs.getBoolean(PREF_SHOW_NUMBER_ROW, false); } public static boolean readSpaceSwipeEnabled(final SharedPreferences prefs) { return prefs.getBoolean(PREF_SPACE_SWIPE, true); } public static String readPrefAdditionalSubtypes(final SharedPreferences prefs, final Resources res) {
final String predefinedPrefSubtypes = AdditionalSubtypeUtils.createPrefSubtypes(
3
SynBioDex/SBOLDesigner
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/OldInputDialog.java
[ "public class CharSequenceUtil {\r\n\tprivate CharSequenceUtil() {}\r\n\t\r\n\tpublic static CharSequence shorten(final CharSequence seq, final int maxLength) {\r\n\t\tint length = seq.length();\r\n\t\tif (length < maxLength) {\r\n\t\t\treturn seq;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tint endLength = maxLength / 3;\r\n\...
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil; import edu.utah.ece.async.sboldesigner.sbol.editor.Registries; import edu.utah.ece.async.sboldesigner.sbol.editor.Registry; import edu.utah.ece.async.sboldesigner.swing.AbstractListTableModel; import edu.utah.ece.async.sboldesigner.swing.ComboBoxRenderer; import edu.utah.ece.async.sboldesigner.swing.FormBuilder;
/* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.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 edu.utah.ece.async.sboldesigner.sbol.editor.dialog; /** * * @author Evren Sirin */ public abstract class OldInputDialog<T> extends JDialog { protected enum RegistryType { PART, VERSION, NONE } private final ComboBoxRenderer<Registry> registryRenderer = new ComboBoxRenderer<Registry>() { @Override protected String getLabel(Registry registry) { StringBuilder sb = new StringBuilder(); if (registry != null) { sb.append(registry.getName()); if (!registry.equals(Registry.BUILT_IN) && !registry.equals(Registry.WORKING_DOCUMENT)) { sb.append(" ("); sb.append(CharSequenceUtil.shorten(registry.getLocation(), 30)); sb.append(")"); } } return sb.toString(); } @Override protected String getToolTip(Registry registry) { return registry == null ? "" : registry.getDescription(); } }; private final ActionListener actionListener = new DialogActionListener(); private RegistryType registryType; private JComboBox registrySelection; private JButton cancelButton, selectButton, optionsButton; private FormBuilder builder = new FormBuilder(); protected boolean canceled = true; protected OldInputDialog(final Component parent, String title, RegistryType registryType) { super(JOptionPane.getFrameForComponent(parent), title, true); this.registryType = registryType; if (registryType != RegistryType.NONE) {
Registries registries = Registries.get();
1
andrewflynn/bettersettlers
app/src/main/java/com/nut/bettersettlers/logic/MapLogic.java
[ "public static final int[] PROBABILITY_MAPPING = {\n\t0, // 0\n 0, // 1\n 1, // 2\n 2, // 3\n 3, // 4\n 4, // 5\n 5, // 6\n 0, // 7\n 5, // 8\n 4, // 9\n 3, // 10\n 2, // 11\n 1 // 12\n};", "public final class CatanMap {\n\t/** ...
import static com.nut.bettersettlers.util.Consts.PROBABILITY_MAPPING; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import com.nut.bettersettlers.data.CatanMap; import com.nut.bettersettlers.data.Harbor; import com.nut.bettersettlers.data.MapType; import com.nut.bettersettlers.data.NumberOfResource; import com.nut.bettersettlers.data.Resource;
Resource nextResource; if (nextProb == 0) { set.add(Resource.DESERT); placedRecently = true; continue; } else if (nextProb < -1 && whitelistName != null && allowedWhitelists.containsKey(whitelistName) && allowedWhitelists.get(whitelistName).contains(Resource.DESERT)) { // Special case deserts with probs set.add(Resource.DESERT); placedRecently = true; continue; } else if (currentMap.landGridResources[nextIndex] != null) { nextResource = currentMap.landGridResources[nextIndex]; // If we have an assigned resource, use it set.add(nextResource); resourceMap.get(nextResource).add(nextProb); avail.remove(nextResource); placedRecently = true; continue; } else { nextResource = avail.remove(RAND.nextInt(avail.size())); } //BetterLog.v("Consuming: " + nextResource); boolean canPlaceHere = true; // Check to see if there's a whitelist if (whitelistName != null && allowedWhitelists.containsKey(whitelistName) && !allowedWhitelists.get(whitelistName).contains(nextResource)) { canPlaceHere = false; } if (nextProb == -1 && canPlaceHere) { // Just use it set.add(nextResource); resourceMap.get(nextResource).add(nextProb); placedRecently = true; if (whitelistName != null && allowedWhitelists.containsKey(whitelistName)) { allowedWhitelists.get(whitelistName).remove(nextResource); } continue; } // Check neighbors for same resource. if (!currentMap.name.equals("the_pirate_islands") && !currentMap.name.equals("the_pirate_islands_exp")) { for (int neighbor : currentMap.landNeighbors[nextIndex]) { //BetterLog.v(" " + neighbor); if (neighbor >= set.size()) { // Do nothing, it is not yet occupied } else { if (set.get(neighbor) == nextResource) { canPlaceHere = false; break; } else { // Do nothing, at least this neighbor isn't the same } } } } // If this number is already used by the same resource if (resourceMap.get(nextResource).contains(nextProb) && !currentMap.name.equals("the_pirate_islands") && !currentMap.name.equals("the_pirate_islands_exp")) { canPlaceHere = false; } // No 6s or 8s on golds if (nextResource == Resource.GOLD && (probs.get(nextIndex) == 6 || probs.get(nextIndex) == 8)) { canPlaceHere = false; } // If this is the last resource, check the probs of this resource int numOfResource = nextResource.numOfResource; ArrayList<Integer> tmpProbs = new ArrayList<>(); tmpProbs.addAll(resourceMap.get(nextResource)); tmpProbs.add(nextProb); if (!tmpProbs.contains(-1)) { // Skip missing probs if (numOfResource == NumberOfResource.LOW && tmpProbs.size() == currentMap.lowResourceNumber) { if (sumProbability(tmpProbs) < 3*currentMap.lowResourceNumber || sumProbability(tmpProbs) > 4*currentMap.lowResourceNumber) { canPlaceHere = false; } if (!isBalanced(tmpProbs)) { canPlaceHere = false; } } else if (numOfResource == NumberOfResource.HIGH && tmpProbs.size() == currentMap.highResourceNumber) { if (sumProbability(tmpProbs) < 3*currentMap.highResourceNumber || sumProbability(tmpProbs) > 4*currentMap.highResourceNumber) { canPlaceHere = false; } } } if (canPlaceHere) { set.add(nextResource); resourceMap.get(nextResource).add(nextProb); placedRecently = true; if (whitelistName != null && allowedWhitelists.containsKey(whitelistName)) { allowedWhitelists.get(whitelistName).remove(nextResource); } } else { tried.add(nextResource); } } } // Check for deserts at the end while (set.size() < probs.size()) { set.add(Resource.DESERT); } //BetterLog.v("Finished: " + set); return set; }
public static ArrayList<Harbor> getHarbors(CatanMap currentMap, int currentType,
2
pedrovgs/Nox
sample/src/main/java/com/github/pedrovgs/nox/sample/MainActivity.java
[ "public class NoxItem {\n\n private final String url;\n private final Integer resourceId;\n private final Integer placeholderId;\n\n public NoxItem(String url) {\n validateUrl(url);\n this.url = url;\n this.resourceId = null;\n this.placeholderId = null;\n }\n\n public NoxItem(int resourceId) {\n ...
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.github.pedrovgs.nox.NoxItem; import com.github.pedrovgs.nox.NoxView; import com.github.pedrovgs.nox.OnNoxItemClickListener; import com.github.pedrovgs.nox.shape.Shape; import com.github.pedrovgs.nox.shape.ShapeConfig; import java.util.ArrayList; import java.util.List;
/* * Copyright (C) 2015 Pedro Vicente Gomez Sanchez. * * 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.github.pedrovgs.nox.sample; /** * Sample activity created to show how to use NoxView with a List of NoxItem instances. * * @author Pedro Vicente Gomez Sanchez. */ public class MainActivity extends ActionBarActivity { private static final String LOGTAG = "MainActivity"; private NoxView noxView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); configureNoxView(); } private void configureNoxView() { noxView = (NoxView) findViewById(R.id.nox_view); noxView.post(new Runnable() { @Override public void run() { int numberOfItems = configureNoxItems(); configureShape(numberOfItems); configureClickListeners(); } }); } private int configureNoxItems() { List<NoxItem> noxItems = new ArrayList<NoxItem>(); noxItems.add(new NoxItem(R.drawable.ic_contacts)); noxItems.add(new NoxItem(R.drawable.ic_apps)); noxView.showNoxItems(noxItems); return noxItems.size(); } private void configureShape(int numberOfItems) { int width = noxView.getWidth(); int height = noxView.getHeight(); float itemSize = getResources().getDimension(R.dimen.nox_item_size); float itemMargin = getResources().getDimension(R.dimen.main_activity_nox_item_margin); ShapeConfig shapeConfig = new ShapeConfig(numberOfItems, width, height, itemSize, itemMargin);
Shape verticalLinearShape = new VerticalLinearShape(shapeConfig);
3
cert-se/megatron-java
src/se/sitic/megatron/fileprocessor/MultithreadedDnsProcessor.java
[ "public class AppProperties {\n // -- Keys in properties file --\n\n // Implicit\n public static final String JOB_TYPE_NAME_KEY = \"implicit.jobTypeName\";\n\n // General\n public static final String LOG4J_FILE_KEY = \"general.log4jConfigFile\";\n public static final String LOG_DIR_KEY = \"general...
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.log4j.Logger; import se.sitic.megatron.core.AppProperties; import se.sitic.megatron.core.JobContext; import se.sitic.megatron.core.MegatronException; import se.sitic.megatron.core.TypedProperties; import se.sitic.megatron.util.Constants; import se.sitic.megatron.util.DateUtil; import se.sitic.megatron.util.IpAddressUtil; import se.sitic.megatron.util.StringUtil;
package se.sitic.megatron.fileprocessor; /** * Extracts hostnames or IP addresses from the input file, and makes DNS lookups * respective reverse DNS lookups in multiple threads to improve performance. * <p> * The result is saved in a map, which is used by IpAddressDecorator and * HostnameDecorator. * <p> * TODO: Add support to write the result (IP address or hostname) in the file * instead of storing the result in memory. */ public class MultithreadedDnsProcessor implements IFileProcessor { /** Key for dnsMap in JobContext.additionalData */ public static final String DNS_MAP_KEY = "MultithreadedDnsProcessor.dnsMap"; /** Key for reverseDnsMap in JobContext.additionalData */ public static final String REVERSE_DNS_MAP_KEY = "MultithreadedDnsProcessor.reverseDnsMap"; // protected due to acess from innner class protected static final Logger log = Logger.getLogger(MultithreadedDnsProcessor.class); private static final String END_ITEM_MARKER = "---- End of Queue ----"; // protected due to acess from innner class protected CountDownLatch allThreadsFinishedLatch; protected BlockingQueue<String> queue; protected Map<String, Long> dnsMap; protected Map<Long, String> reverseDnsMap; private JobContext jobContext; private TypedProperties props; private int noOfThreads; private Matcher matcher; private Set<String> processedItems; private long printProgressInterval; private long lastProgressPrintTime; private long lastProgressPrintLineNo; private long noOfProcessedItems; private long noOfUniqueProcessedItems; public MultithreadedDnsProcessor() { // empty } @Override public void init(JobContext jobContext) throws MegatronException { this.jobContext = jobContext; props = jobContext.getProps(); // -- Setup result maps, queue, matcher etc. int initialCapacity = (int)jobContext.getNoOfLines(); if (initialCapacity < 16) { initialCapacity = 32; } processedItems = new HashSet<String>(initialCapacity); queue = new ArrayBlockingQueue<String>(256); boolean reverseDnsLookup = props.getBoolean(AppProperties.FILE_PROCESSOR_DNS_REVERSE_DNS_LOOKUP_KEY, true); String regExp = null; if (reverseDnsLookup) { reverseDnsMap = Collections.synchronizedMap(new HashMap<Long, String>(initialCapacity)); jobContext.addAdditionalData(REVERSE_DNS_MAP_KEY, reverseDnsMap); regExp = props.getString(AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY, null); if (StringUtil.isNullOrEmpty(regExp)) { throw new MegatronException("Regular expression not defined: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY); } } else { dnsMap = Collections.synchronizedMap(new HashMap<String, Long>(initialCapacity)); jobContext.addAdditionalData(DNS_MAP_KEY, dnsMap); regExp = props.getString(AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY, null); if (StringUtil.isNullOrEmpty(regExp)) { throw new MegatronException("Regular expression not defined: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY); } } try { matcher = Pattern.compile(regExp).matcher(""); } catch (PatternSyntaxException e) { String msg = "Cannot compile reg-exp: " + regExp; throw new MegatronException(msg, e); } // init attributes for printProgress lastProgressPrintTime = System.currentTimeMillis(); lastProgressPrintLineNo = 0L; printProgressInterval = 1000L*props.getLong(AppProperties.PRINT_PROGRESS_INTERVAL_KEY, 15L); // -- Setup threads noOfThreads = props.getInt(AppProperties.FILE_PROCESSOR_DNS_NO_OF_THREADS_KEY, 100); if (jobContext.getNoOfLines() < 10L) { noOfThreads = 4; } allThreadsFinishedLatch = new CountDownLatch(noOfThreads); for (int i = 0; i < noOfThreads; i++) { Thread thread = null; if (reverseDnsLookup) { thread = new Thread(new ReverseDnsLookupConsumer()); } else { thread = new Thread(new DnsLookupConsumer()); } String name = "Consumer-" + i; thread.setName(name); log.debug("Starting DNS lookup consumer thread: " + name); thread.start(); } } @Override public File execute(File inputFile) throws MegatronException { long t1 = System.currentTimeMillis(); // -- Read file BufferedReader in = null; try { String charSet = props.getString(AppProperties.INPUT_CHAR_SET_KEY, Constants.UTF8); in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), charSet)); long lineNo = 0L; String line = null; while ((line = in.readLine()) != null) { matcher.reset(line); while (matcher.find()) { if (matcher.groupCount() > 0) { for (int i = 1; i <= matcher.groupCount(); i++) { processItem(matcher.group(i)); } } else { processItem(matcher.group()); } } ++lineNo; printProgress(lineNo - queue.size()); } if ((noOfProcessedItems == 0L) && (lineNo > 10L)) { throw new MegatronException("No IP addresses or hostnames extracted. Please check regular expression: " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_IP_KEY + " or " + AppProperties.FILE_PROCESSOR_DNS_REG_EXP_HOSTNAME_KEY); } } catch (IOException e) { String msg = "Cannot read file: " + inputFile.getAbsolutePath(); throw new MegatronException(msg, e); } finally { try { if (in != null) in.close(); } catch (Exception ignored) {} } // -- Add "end of queue" items for (int i = 0; i < noOfThreads; i++) { try { queue.put(END_ITEM_MARKER); } catch (InterruptedException e) { throw new MegatronException("Cannot put 'end of queue' marker in queue (should not happen)", e); } } // -- Wait for threads to finish log.debug("All items added to queue; waiting for threads to finish."); try { allThreadsFinishedLatch.await(); } catch (InterruptedException e) { throw new MegatronException("Wait for all threads to finish interrupted (should not happen)", e); } String durationStr = DateUtil.formatDuration(System.currentTimeMillis() - t1); log.info("Total time for DNS lookups: " + durationStr); return inputFile; } @Override public void close(boolean jobSuccessful) throws MegatronException { if (dnsMap != null) { log.info("No. of parsed hostnames for DNS lookup [total / total unique]: " + noOfProcessedItems + " / " + noOfUniqueProcessedItems); log.info("No. of DNS lookups (hostname --> ip) [successful / failed]: " + dnsMap.size() + " / " + (noOfUniqueProcessedItems - dnsMap.size())); } else { log.info("No. of parsed IP addresses for reverse DNS lookup [total / total unique]: " + noOfProcessedItems + " / " + noOfUniqueProcessedItems); log.info("No. of DNS lookups (ip --> hostname) [successful / failed]: " + reverseDnsMap.size() + " / " + (noOfUniqueProcessedItems - reverseDnsMap.size())); } } /** * Process specified IP address or hostname. */ private void processItem(String itemStr) throws MegatronException { if (StringUtil.isNullOrEmpty(itemStr)) { return; } ++noOfProcessedItems; if (processedItems.contains(itemStr)) { return; } ++noOfUniqueProcessedItems; processedItems.add(itemStr); try { queue.put(itemStr); } catch (InterruptedException e) { throw new MegatronException("Cannot put DNS item in queue (should not happen)", e); } } private void printProgress(long lineNo) { long now = System.currentTimeMillis(); if ((printProgressInterval > 0L) && ((lastProgressPrintTime + printProgressInterval) < now)) { long noOfLines = jobContext.getNoOfLines(); double progress = 100d*((double)lineNo / (double)noOfLines); double linesPerSecond = ((double)lineNo - (double)lastProgressPrintLineNo) / (((double)now - (double)lastProgressPrintTime) / 1000d); DecimalFormat format = new DecimalFormat("0.00"); String progressStr = format.format(progress); String lineInfoStr = lineNo + " of " + noOfLines + " lines"; String linesPerSecondStr = format.format(linesPerSecond); String msg = "DNS Prefetch: " + progressStr + "% (" + lineInfoStr + ", " + linesPerSecondStr + " lines/second)"; if (props.isStdout()) { log.info(msg); } else { jobContext.writeToConsole(msg); } lastProgressPrintLineNo = lineNo; lastProgressPrintTime = now; } } /** * Takes an item (hostname or IP address) from queue and process it * (DNS lookup or reverse DNS lookup). */ private abstract class AbstractConsumer implements Runnable { public AbstractConsumer() { // empty } @Override public void run() { try { while (true) { String itemStr = queue.take(); if (itemStr == END_ITEM_MARKER) { break; } processItem(itemStr); } } catch (InterruptedException e) { log.error("DNS lookup or reverse DNS lookup failed; thread interrupted (should not happened).", e); } allThreadsFinishedLatch.countDown(); log.debug("Thread is exiting: " + Thread.currentThread().getName()); } protected abstract void processItem(String itemStr); } /** * Makes a DNS lookup. */ private class DnsLookupConsumer extends AbstractConsumer { public DnsLookupConsumer() { // empty } @Override protected void processItem(String itemStr) {
long ipAddress = IpAddressUtil.dnsLookup(itemStr);
4
HackGSU/mobile-android
app/src/main/java/com/hackgsu/fall2016/android/views/AnnouncementsRecyclerView.java
[ "public class DataStore {\n\tprivate static ArrayList<AboutPerson> aboutPeople;\n\tprivate static ArrayList<Announcement> announcements = new ArrayList<>();\n\tprivate static String openingCeremoniesRoomNumber;\n\tprivate static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();\n\n\tstatic {\n\t\taboutPe...
import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatImageButton; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.hackgsu.fall2016.android.DataStore; import com.hackgsu.fall2016.android.HackGSUApplication; import com.hackgsu.fall2016.android.R; import com.hackgsu.fall2016.android.controllers.AnnouncementController; import com.hackgsu.fall2016.android.model.Announcement; import com.hackgsu.fall2016.android.utils.SmoothLinearLayoutManager; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import java.util.Locale;
package com.hackgsu.fall2016.android.views; public class AnnouncementsRecyclerView extends ThemedEmptyStateRecyclerView { private AnnouncementEventAdapter adapter; private SmoothLinearLayoutManager layoutManager; private boolean showOnlyBookmarked; public AnnouncementsRecyclerView (Context context) { super(context); init(null, 0); } public AnnouncementsRecyclerView (Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public AnnouncementsRecyclerView (Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } public static String getTimestampString (Context context, LocalDateTime dateTime) { String timeTillString = HackGSUApplication.toHumanReadableRelative(dateTime); DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder(); DateTimeFormatter dateTimeFormatter = HackGSUApplication.getTimeFormatter24OrNot(context, dateTimeFormatterBuilder); return String.format("%s | %s", timeTillString, dateTime.toString(dateTimeFormatter)); } public class AnnouncementEventAdapter extends Adapter<AnnouncementsEventViewHolder> { @Override public AnnouncementsEventViewHolder onCreateViewHolder (ViewGroup parent, int viewType) { View inflate = View.inflate(getContext(), R.layout.announcement_card, null); inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); return new AnnouncementsEventViewHolder(inflate); } @Override public void onBindViewHolder (AnnouncementsEventViewHolder holder, int position) {
holder.loadAnnouncement(DataStore.getAnnouncements(shouldShowOnlyBookmarked()).get(position));
0
loopfz/Lucki
src/shaft/poker/agent/handranges/weightedrange/PlayerWTRange.java
[ "public interface IHandEvaluator {\n public void compute(List<Card> holecards, List<Card> board, IHandRange range, int numPlayers);\n \n public double effectiveHandStrength();\n public double rawHandStrength();\n public double posPotential();\n public double negPotential();\n }", "public inte...
import shaft.poker.game.table.IPlayerActionListener; import shaft.poker.game.ITable; import shaft.poker.game.ITable.*; import shaft.poker.game.table.*; import java.util.List; import shaft.poker.agent.IHandEvaluator; import shaft.poker.agent.IHandRange; import shaft.poker.agent.enumerationtools.EnumCandidate; import shaft.poker.agent.handranges.IPlayerRange; import shaft.poker.game.Card; import shaft.poker.game.Card.*;
/* * The MIT License * * Copyright 2013 Thomas Schaffer <thomas.schaffer@epitech.eu>. * * 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 shaft.poker.agent.handranges.weightedrange; /** * * @author Thomas Schaffer <thomas.schaffer@epitech.eu> */ public class PlayerWTRange implements IPlayerRange, IPlayerActionListener, IGameEventListener { private String _playerId; private IWeightTable _wt; private IFrequencyTable _freq; private IHandEvaluator _eval; private IHandRange _compositeRange; private static final double VARIANCE_FACTOR = 0.4; private static final double LOW_WEIGHT = 0.01; private static final double HIGH_WEIGHT = 1.00; private boolean _dead; private boolean _active; public PlayerWTRange(String playerId, IWeightTable wt, IFrequencyTable freq, IHandEvaluator eval, IHandRange compRange, ITable table) { _playerId = playerId; _wt = wt; _freq = freq; _eval = eval; _compositeRange = compRange; table.registerListenerForPlayer(playerId, this); table.registerEventListener(this); } private void reweight(double threshold, List<Card> board, int numPlayers, double potOdds) { double variance; variance = VARIANCE_FACTOR * (1 - threshold);
List<EnumCandidate> holeCards = EnumCandidate.buildCandidates(null, board);
2
sweer/hex-image-compress
src/pipeline/Decoder.java
[ "public class DoubleLattice extends Lattice {\r\n\t/**\r\n\t * @uml.property name=\"data\"\r\n\t */\r\n\tprivate final double[][] data;\r\n\tpublic DoubleLattice(double[][] data, int ox, int oy) {\r\n\t\tsuper(ox,oy);\r\n\t\tthis.data = data;\r\n\t}\r\n\t\r\n public DoubleLattice(DoubleLattice lattice) {\r\n ...
import util.ImageUtils; import filter.H2O; import filter.HexByteRavelet; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import lattice.DoubleLattice; import lattice.LongLattice; import lattice.LongLattice.Run; import rangecoder.Compressor;
package pipeline; /* * Copyright (C) 2012 Aleksejs Truhans * * 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/>. */ /** * Decodes byte stream into a lattice. @see Encoder for byte stream description. * * @see DecoderTest.testEncodeDecodeLena100() for usage example * * **/ public class Decoder { /** * Decodes byte stream into a hexagonal lattice. @see Encoder for byte * stream description. **/ public static LongLattice decodeToHexagonalLattice(byte[] source) { DecodeRunner decoder = new DecodeRunner(source); return decoder.decode(); } /** * Decodes byte stream into an orthogonal array. @see Encoder for byte * stream description. **/ public static double[][] decodeToImageInArray(byte[] encoded) { LongLattice lattice = decodeToHexagonalLattice(encoded); return hexagonalLatticeToImageInArray(lattice); } public static BufferedImage hexagonalLatticeToBufferedImage( LongLattice source) { double[][] imageInArray = hexagonalLatticeToImageInArray(source); BufferedImage image = new BufferedImage(imageInArray[0].length, imageInArray.length, BufferedImage.TYPE_BYTE_GRAY); ImageUtils.doubleArrayToImageRaster(image, imageInArray); return image; } public static double[][] hexagonalLatticeToImageInArray(LongLattice source) { DoubleLattice doubleLattice = H2O.h2o(source.getDequantizedLattice()); return doubleLattice.getData(); } /** * @author HP */ public static class DecodeRunner { /** * @uml.property name="lattice" * @uml.associationEnd */ private LongLattice lattice; private final ByteArrayInputStream byteIn; private final DataInputStream dataIn; /** * @uml.property name="ravelet" * @uml.associationEnd */
private HexByteRavelet ravelet;
6
RedMadRobot/Chronos
chronos/src/main/java/com/redmadrobot/chronos/gui/fragment/dialog/ChronosDialogFragment.java
[ "public final class ChronosConnector {\n\n private final static String KEY_CHRONOS_LISTENER_ID = \"chronos_listener_id\";\n\n private ChronosListener mChronosListener;\n\n private Object mGUIClient;\n\n /**\n * GUI client should call this method in its own onCreate() method.\n *\n * @param c...
import com.redmadrobot.chronos.ChronosConnector; import com.redmadrobot.chronos.ChronosOperation; import com.redmadrobot.chronos.gui.ChronosConnectorWrapper; import com.redmadrobot.chronos.gui.fragment.ChronosFragment; import com.redmadrobot.chronos.gui.fragment.ChronosSupportFragment; import org.jetbrains.annotations.Contract; import android.annotation.TargetApi; import android.app.DialogFragment; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull;
package com.redmadrobot.chronos.gui.fragment.dialog; /** * A DialogFragment that is connected to Chronos. * * @author maximefimov * @see ChronosFragment * @see ChronosSupportDialogFragment * @see ChronosSupportFragment */ @SuppressWarnings("unused") @TargetApi(Build.VERSION_CODES.HONEYCOMB) public abstract class ChronosDialogFragment extends DialogFragment implements
ChronosConnectorWrapper {
2
MinecraftForge/ForgeGradle
src/userdev/java/net/minecraftforge/gradle/userdev/util/Deobfuscator.java
[ "public enum HashFunction {\n MD5(\"md5\", 32),\n SHA1(\"SHA-1\", 40),\n SHA256(\"SHA-256\", 64),\n SHA512(\"SHA-512\", 128);\n\n private final String algo;\n private final String pad;\n\n HashFunction(String algo, int length) {\n this.algo = algo;\n this.pad = String.format(Local...
import net.minecraftforge.gradle.common.util.HashFunction; import net.minecraftforge.gradle.common.util.HashStore; import net.minecraftforge.gradle.common.util.MavenArtifactDownloader; import net.minecraftforge.gradle.common.util.McpNames; import net.minecraftforge.gradle.common.util.Utils; import net.minecraftforge.gradle.mcp.MCPRepo; import net.minecraftforge.gradle.userdev.tasks.RenameJarSrg2Mcp; import org.apache.commons.io.IOUtils; import org.gradle.api.Project; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory;
/* * ForgeGradle * Copyright (C) 2018 Forge Development LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.minecraftforge.gradle.userdev.util; public class Deobfuscator { private final Project project; private final File cacheRoot; private final DocumentBuilder xmlParser; private final XPath xPath; private final Transformer xmlTransformer; public Deobfuscator(Project project, File cacheRoot) { this.project = project; this.cacheRoot = cacheRoot; try { xPath = XPathFactory.newInstance().newXPath(); xmlParser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xmlTransformer = TransformerFactory.newInstance().newTransformer(); } catch (ParserConfigurationException | TransformerConfigurationException e) { throw new RuntimeException("Error configuring XML parsers", e); } } public File deobfPom(File original, String mappings, String... cachePath) throws IOException { project.getLogger().debug("Updating POM file {} with mappings {}", original.getName(), mappings); File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("mappings", mappings) .add("orig", original); if (!cache.isSame() || !output.exists()) { try { Document pom = xmlParser.parse(original); NodeList versionNodes = (NodeList) xPath.compile("/*[local-name()=\"project\"]/*[local-name()=\"version\"]").evaluate(pom, XPathConstants.NODESET); if (versionNodes.getLength() > 0) { versionNodes.item(0).setTextContent(versionNodes.item(0).getTextContent() + "_mapped_" + mappings); } xmlTransformer.transform(new DOMSource(pom), new StreamResult(output)); } catch (IOException | SAXException | XPathExpressionException | TransformerException e) { project.getLogger().error("Error attempting to modify pom file " + original.getName(), e); return original; } Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } @Nullable public File deobfBinary(File original, @Nullable String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating binary file {} with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { RenameJarSrg2Mcp rename = project.getTasks().create("_RenameSrg2Mcp_" + new Random().nextInt(), RenameJarSrg2Mcp.class); rename.getInput().set(original); rename.getOutput().set(output); rename.getMappings().set(names); rename.setSignatureRemoval(true); rename.apply(); rename.setEnabled(false); Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } @Nullable public File deobfSources(File original, @Nullable String mappings, String... cachePath) throws IOException { project.getLogger().debug("Deobfuscating sources file {} with mappings {}", original.getName(), mappings); File names = findMapping(mappings); if (names == null || !names.exists()) { return null; } File output = getCacheFile(cachePath); File input = new File(output.getParent(), output.getName() + ".input"); HashStore cache = new HashStore() .load(input) .add("names", names) .add("orig", original); if (!cache.isSame() || !output.exists()) { McpNames map = McpNames.load(names); try (ZipInputStream zin = new ZipInputStream(new FileInputStream(original)); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(output))) { ZipEntry _old; while ((_old = zin.getNextEntry()) != null) { zout.putNextEntry(Utils.getStableEntry(_old.getName())); if (_old.getName().endsWith(".java")) { String mapped = map.rename(zin, false); IOUtils.write(mapped, zout, StandardCharsets.UTF_8); } else { IOUtils.copy(zin, zout); } } } Utils.updateHash(output, HashFunction.SHA1); cache.save(); } return output; } private File getCacheFile(String... cachePath) { File cacheFile = new File(cacheRoot, String.join(File.separator, cachePath)); cacheFile.getParentFile().mkdirs(); return cacheFile; } @Nullable private File findMapping(@Nullable String mapping) { if (mapping == null) return null; int idx = mapping.lastIndexOf('_'); String channel = mapping.substring(0, idx); String version = mapping.substring(idx + 1); String desc = MCPRepo.getMappingDep(channel, version);
return MavenArtifactDownloader.generate(project, desc, false);
2
graywolf336/Jail
src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java
[ "public class JailManager {\n private JailMain plugin;\n private HashMap<String, Jail> jails;\n private HashMap<String, CreationPlayer> jailCreators;\n private HashMap<String, CreationPlayer> cellCreators;\n private HashMap<String, ConfirmPlayer> confirms;\n private HashMap<UUID, CachePrisoner> ca...
import java.util.Collections; import java.util.List; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang;
package com.graywolf336.jail.command.subcommands; @CommandInfo( maxArgs = 0, minimumArgs = 0, needsPlayer = true, pattern = "status|s", permission = "jail.usercmd.jailstatus", usage = "/jail status" )
public class JailStatusCommand implements Command{
3
gomathi/merkle-tree
test/org/hashtrees/test/HashTreesStoreTest.java
[ "@ThreadSafe\npublic class HashTreesMemStore extends HashTreesBaseStore {\n\n\tprivate final ConcurrentMap<Long, HashTreeMemStore> treeIdAndIndHashTree = new ConcurrentHashMap<>();\n\n\tprivate static class HashTreeMemStore {\n\t\tprivate final ConcurrentMap<Integer, ByteBuffer> segmentHashes = new ConcurrentSkipLi...
import org.hashtrees.thrift.generated.SegmentData; import org.hashtrees.thrift.generated.SegmentHash; import org.hashtrees.util.ByteUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hashtrees.store.HashTreesMemStore; import org.hashtrees.store.HashTreesPersistentStore; import org.hashtrees.store.HashTreesStore; import org.hashtrees.test.utils.HashTreesImplTestUtils;
/* * 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.hashtrees.test; public class HashTreesStoreTest { private static final int DEF_TREE_ID = 1; private static final int DEF_SEG_ID = 0; private static interface HTStoreHelper { HashTreesStore getInstance() throws IOException; HashTreesStore restartInstance(HashTreesStore htStore) throws IOException; void cleanup(HashTreesStore htStore) throws IOException; } private static class HTPersistentStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesPersistentStore( HashTreesImplTestUtils.randomDirName()); } @Override public void cleanup(HashTreesStore htStore) { ((HashTreesPersistentStore) htStore).delete(); } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { ((HashTreesPersistentStore) htStore).stop(); return new HashTreesPersistentStore( ((HashTreesPersistentStore) htStore).getDbDir()); } } private static class HTMemStoreHelper implements HTStoreHelper { @Override public HashTreesStore getInstance() throws IOException { return new HashTreesMemStore(); } @Override public void cleanup(HashTreesStore htStore) { // nothing to do. } @Override public HashTreesStore restartInstance(HashTreesStore htStore) throws IOException { return htStore; } } private static final Set<HTStoreHelper> helpers = new HashSet<>(); static { helpers.add(new HTPersistentStoreHelper()); helpers.add(new HTMemStoreHelper()); } @Test public void testSegmentData() throws IOException { for (HTStoreHelper helper : helpers) { HashTreesStore htStore = helper.getInstance(); try { ByteBuffer key = ByteBuffer.wrap("key1".getBytes());
ByteBuffer digest = ByteBuffer.wrap(ByteUtils.sha1("digest1"
6
ryantenney/passkit4j
src/main/java/com/ryantenney/passkit4j/Pass.java
[ "public interface NamedInputStreamSupplier extends InputStreamSupplier {\n\n\tpublic String getName();\n\n}", "@Data\n@Accessors(chain=true, fluent=true)\n@RequiredArgsConstructor\npublic class Barcode {\n\n\t@NonNull private BarcodeFormat format;\n\n\t@NonNull private String message;\n\n\tprivate String messageE...
import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.experimental.Accessors; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.util.ISO8601Utils; import com.ryantenney.passkit4j.io.NamedInputStreamSupplier; import com.ryantenney.passkit4j.model.Barcode; import com.ryantenney.passkit4j.model.Beacon; import com.ryantenney.passkit4j.model.Color; import com.ryantenney.passkit4j.model.Location; import com.ryantenney.passkit4j.model.NFC; import com.ryantenney.passkit4j.model.PassInformation;
package com.ryantenney.passkit4j; @Data @NoArgsConstructor @Accessors(chain=true, fluent=true) public class Pass { // Standard Keys @NonNull private String description; @NonNull private String organizationName; @NonNull private String passTypeIdentifier; @NonNull private String serialNumber; @NonNull private String teamIdentifier; @JsonProperty("formatVersion") private final int $formatVersion = 1; // Visual Appearance Keys private Barcode barcode; private List<Barcode> barcodes; private Color backgroundColor; private Color foregroundColor; private String groupingIdentifier; private Color labelColor; private String logoText; @JsonInclude(Include.NON_DEFAULT) private boolean suppressStripShine = false; // Web Service Keys private String webServiceURL; private String authenticationToken; // Relevance Keys private boolean ignoresTimeZone = false; private List<Location> locations; private List<Beacon> beacons; private Integer maxDistance; private Date relevantDate; // Associated App Keys private List<Long> associatedStoreIdentifiers; private String appLaunchURL; // Companion App Keys private JsonNode userInfo; // Expiration Keys private Date expirationDate; @JsonInclude(Include.NON_DEFAULT) private boolean voided = false; // NFC Keys private NFC nfc;
@JsonIgnore private PassInformation passInformation;
6
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/JobServiceStrategy.java
[ "public class UnsupportedClassException extends RuntimeException {\n public UnsupportedClassException() {\n }\n\n public UnsupportedClassException(String message) {\n super(message);\n }\n\n public UnsupportedClassException(String message, Throwable cause) {\n super(message, cause);\n ...
import com.github.quartzweb.exception.UnsupportedClassException; import com.github.quartzweb.job.MethodInvoker; import com.github.quartzweb.manager.web.JobInfosVO; import com.github.quartzweb.manager.web.QuartzWebManager; import com.github.quartzweb.service.JSONResult; import com.github.quartzweb.service.QuartzWebURL; import com.github.quartzweb.utils.Assert; import com.github.quartzweb.utils.StringUtils; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import java.util.LinkedHashMap; import java.util.Map;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author quxiucheng [quxiuchengdev@gmail.com] */ public class JobServiceStrategy implements ServiceStrategy<JobServiceStrategyParameter> { @Override public JSONResult service(ServiceStrategyURL serviceStrategyURL, JobServiceStrategyParameter parameter) { String url = serviceStrategyURL.getURL(); // 列出信息 if (QuartzWebURL.JobURL.INFO.getURL().equals(url)) { return getInfo(); } String schedulerName = parameter.getSchedulerName(); String jobName = parameter.getJobName(); String jobGroup = parameter.getJobGroup(); String jobClass = parameter.getJobClass(); Map<String, String> jobDataMap = parameter.getJobDataMap(); String description = parameter.getDescription(); // 转换类型 Map<String, Object> jobDataMapObject = new LinkedHashMap<String, Object>(); if (jobDataMap != null) { jobDataMapObject.putAll(jobDataMap); } //添加 if (QuartzWebURL.JobURL.ADD.getURL().equals(url)) { JobServiceStrategyParameter.JobType jobType = parameter.getJobType(); if (jobType == null) { throw new IllegalArgumentException("jobType can not be null"); } // 继承org.quartz.Job添加 if (jobType.getDictValue() == JobServiceStrategyParameter.JobType.JOB.getDictValue()) { return addQuartzJob(schedulerName, jobName, jobGroup, jobClass, jobDataMapObject, description); } else { String jobClassMethodName = parameter.getJobClassMethodName();
Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be null");
6
ArcadiaPlugins/Arcadia-Spigot
src/main/java/me/redraskal/arcadia/game/WingRushGame.java
[ "public class Arcadia extends JavaPlugin {\n\n private ArcadiaAPI api;\n public Configuration mainConfiguration;\n\n public void onEnable() {\n this.api = new ArcadiaAPI(this);\n new File(this.getDataFolder().getPath() + \"/translations/\").mkdirs();\n if(new File(this.getDataFolder()....
import me.redraskal.arcadia.Arcadia; import me.redraskal.arcadia.Freeze; import me.redraskal.arcadia.Utils; import me.redraskal.arcadia.api.game.BaseGame; import me.redraskal.arcadia.api.map.GameMap; import me.redraskal.arcadia.api.scoreboard.SidebarSettings; import me.redraskal.arcadia.api.scoreboard.WinMethod; import me.redraskal.arcadia.api.scoreboard.defaults.ScoreSidebar; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List;
package me.redraskal.arcadia.game; public class WingRushGame extends BaseGame { private Location startLocationCenter; private List<Freeze> freezeList = new ArrayList<>(); public WingRushGame(GameMap gameMap) { super(Arcadia.getPlugin(Arcadia.class).getAPI().getTranslationManager().fetchTranslation("game.wingrush.name").build(), new String[]{"startPositionCenter"},
new SidebarSettings(ScoreSidebar.class,
7
aponom84/MetrizedSmallWorld
src/main/java/org/latna/msw/evaluation/WikiSparseAggregationTest.java
[ "public abstract class MetricElement {\n private final List<MetricElement> friends;\n\n public MetricElement() {\n friends = Collections.synchronizedList(new ArrayList());\n }\n \n /**\n * Calculate metric between current object and another.\n * @param gme any element for whose metric ...
import org.latna.msw.MetricElement; import org.latna.msw.MaskValidator; import org.latna.msw.MetrizedSmallWorld; import org.latna.msw.AlgorithmLib; import org.latna.msw.euclidian.EuclidianFactory; import org.latna.msw.wikisparse.WikiSparse; import org.latna.msw.wikisparse.WikiSparseFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit;
package org.latna.msw.evaluation; /** * V02.05.2014 * @author Alexander Ponomarenko aponom84@gmail.com */ public class WikiSparseAggregationTest { public static final int NUMBER_OF_THREADS = 4; public static final String outFileName = "WikiSparceAggregate.txt"; /* public static SearchResult aggregateSearch(AbstractMetricStructure db, WikiSparse query, int attempts, int exactNumberOfAnswers) { int foundAnswers = 0; SearchResult res = db.knnSearch(query, 1, attempts); EvaluatedElement start = res.getViewedList().first(); HashSet <MetricElement> viewedSet = new HashSet <MetricElement> (); Set visitedSet = new HashSet <MetricElement>(); TreeSet <EvaluatedElement> candidateSet = new TreeSet(); List <MetricElement> newList; candidateSet.add(start); viewedSet.add(start.getMetricElement()); boolean stillContatinsCorrespoundAnswer = false; while (!candidateSet.isEmpty()) { EvaluatedElement currEv = candidateSet.first(); candidateSet.remove(currEv); stillContatinsCorrespoundAnswer = false; for (MetricElement e: currEv.getMetricElement().getAllFriends()) { if (!viewedSet.contains(e)) { viewedSet.add(e); WikiSparse ws = (WikiSparse) e; if ( ws.correspoundToMask(query) ) { foundAnswers++; candidateSet.add(new EvaluatedElement(e.calcDistance(query), e)); } } } System.out.println("Scaned: " + viewedSet.size() + " found: " + String.valueOf( (double) foundAnswers / (double) exactNumberOfAnswers ) ); } return res; } */ /** * Scan input string and run the test * @param args the command line arguments */ public static void main(String[] args) throws IOException { /*int nn = Integer.valueOf(args[0]); int k = Integer.valueOf(args[1]); int initAttempts = Integer.valueOf(args[2]); int minAttempts = Integer.valueOf(args[3]); int maxAttempts = Integer.valueOf(args[4]); int dataBaseSize = Integer.valueOf(args[5]); int querySetSize = Integer.valueOf(args[6]); int testSeqSize = Integer.valueOf(args[7]); String dataPath = args[8]; String queryPath = args[9]; */ // int[] checkPoints = {1000, 5000, 10000, 50000, 100000, 500000}; int[] checkPoints = {1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 100000, 500000}; // int[] checkPoints = {1000,5000, 10000, 50000,100000,500000, 1000000,2000000,5000000,10000000,20000000, 50000000}; // int[] checkPoints = {1000}; // int dimensionality = 30; int nn = 20; //number of nearest neighbors used in construction algorithm to approximate voronoi neighbor int k = 5; //number of k-closest elements for the knn search int initAttempts = 4; //number of search attempts used during the contruction of the structure int minAttempts = 1; //minimum number of attempts used during the test search int maxAttempts = 10; //maximum number of attempts //int dataBaseSize = 1000; // int dataBaseSize = 0; the restriction on the number of elements in the data structure. To set no restriction set value = 0 int querySetSize = 10; //the restriction on the number of quleries. To set no restriction set value = 0 //number elements in the random selected subset used to verify accuracy of the search. int elementNumber = 0; int lastSize = 0; // WikiSparse Factory factory = new WikiSparseFactory("C:\\Users\\Aponom\\wikipedia.txt"); WikiSparseFactory factory = new WikiSparseFactory("E:\\WikiData\\wikipedia.txt"); WikiSparseFactory queryFactory = new WikiSparseFactory(""); MetrizedSmallWorld db = new MetrizedSmallWorld(); db.setNN(nn); db.setInitAttempts(initAttempts);
List <MetricElement> testQueries = queryFactory.getShortQueries(querySetSize, 2, 10000);
0
desht/ScrollingMenuSign
src/main/java/me/desht/scrollingmenusign/views/SMSSpoutView.java
[ "public class SMSException extends DHUtilsException {\n\n private static final long serialVersionUID = 1L;\n\n public SMSException(String message) {\n super(message);\n }\n\n}", "public class SMSMenu extends Observable implements SMSPersistable, SMSUseLimitable, ConfigurationListener, Comparable<S...
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Observable; import java.util.UUID; import me.desht.dhutils.ConfigurationManager; import me.desht.dhutils.Debugger; import me.desht.dhutils.LogUtils; import me.desht.dhutils.PermissionUtils; import me.desht.scrollingmenusign.SMSException; import me.desht.scrollingmenusign.SMSMenu; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.spout.HexColor; import me.desht.scrollingmenusign.spout.SMSSpoutKeyMap; import me.desht.scrollingmenusign.spout.SpoutViewPopup; import me.desht.scrollingmenusign.spout.TextEntryPopup; import me.desht.scrollingmenusign.views.action.ViewUpdateAction; import org.bukkit.Bukkit; import org.bukkit.configuration.Configuration; import org.bukkit.entity.Player; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.gui.PopupScreen; import org.getspout.spoutapi.player.SpoutPlayer;
package me.desht.scrollingmenusign.views; /** * This view draws menus on a popped-up Spout view. */ public class SMSSpoutView extends SMSScrollableView implements PoppableView { // attributes public static final String AUTOPOPDOWN = "autopopdown"; public static final String SPOUTKEYS = "spoutkeys"; public static final String BACKGROUND = "background"; public static final String ALPHA = "alpha"; public static final String TEXTURE = "texture"; // list of all popups which have been created for this view, keyed by player ID private final Map<UUID, SpoutViewPopup> popups = new HashMap<UUID, SpoutViewPopup>(); // map a set of keypresses to the view which handles them private static final Map<String, String> keyMap = new HashMap<String, String>(); /** * Construct a new SMSSPoutView object * * @param name The view name * @param menu The menu to attach the object to * @throws SMSException */ public SMSSpoutView(String name, SMSMenu menu) throws SMSException { super(name, menu); setWrap(false); if (!ScrollingMenuSign.getInstance().isSpoutEnabled()) { throw new SMSException("Spout view cannot be created - server does not have Spout enabled"); } Configuration config = ScrollingMenuSign.getInstance().getConfig(); String defColor = config.getString("sms.spout.list_background"); Double defAlpha = config.getDouble("sms.spout.list_alpha"); registerAttribute(SPOUTKEYS, new SMSSpoutKeyMap(), "Key(s) to toggle view visibility"); registerAttribute(AUTOPOPDOWN, true, "Auto-popdown after item click?"); registerAttribute(BACKGROUND, new HexColor(defColor), "Background colour of view"); registerAttribute(ALPHA, defAlpha, "Transparency of view"); registerAttribute(TEXTURE, "", "Image to use as view background"); } public SMSSpoutView(SMSMenu menu) throws SMSException { this(null, menu); } // NOTE: explicit freeze() and thaw() methods not needed. No new object fields which are not attributes. /** * Show the given player's GUI for this view. * * @param player The player object */ @Override public void showGUI(Player player) { SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; Debugger.getInstance().debug("showing Spout GUI for " + getName() + " to " + sp.getDisplayName()); if (!popups.containsKey(sp.getUniqueId())) { // create a new gui for this player popups.put(sp.getUniqueId(), new SpoutViewPopup(sp, this)); } SpoutViewPopup gui = popups.get(sp.getUniqueId()); gui.popup(); } /** * Hide the given player's GUI for this view. * * @param player The player object */ @Override public void hideGUI(Player player) { SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; if (!popups.containsKey(sp.getUniqueId())) { return; } Debugger.getInstance().debug("hiding Spout GUI for " + getName() + " from " + sp.getDisplayName()); popups.get(sp.getUniqueId()).popdown(); // decision: destroy the gui object or not? // popups.remove(sp.getName()); } /** * Check if the given player has an active GUI (for any Spout view, not * necessarily this one). * * @param player the player to check for * @return true if a GUI is currently popped up, false otherwise */ @Override public boolean hasActiveGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return false; PopupScreen popup = sp.getMainScreen().getActivePopup(); return popup != null && popup instanceof SpoutViewPopup; } /** * Get the active GUI for the given player, if any (for any Spout view, not * necessarily this one). * * @param player the player to check for * @return the GUI object if one is currently popped up, null otherwise */ @Override public SMSPopup getActiveGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return null; PopupScreen popup = sp.getMainScreen().getActivePopup(); return popup instanceof SpoutViewPopup ? (SMSPopup) popup : null; } /** * Toggle the given player's visibility of the GUI for this view. If a GUI for a different view * is currently showing, pop that one down, and pop this one up. * * @param player The player object */ @Override public void toggleGUI(Player player) { final SpoutPlayer sp = SpoutManager.getPlayer(player); if (!sp.isSpoutCraftEnabled()) return; if (hasActiveGUI(sp)) { SMSPopup gui = getActiveGUI(sp); SMSSpoutView poppedUpView = (SMSSpoutView) gui.getView(); if (poppedUpView == this) { // the player has an active GUI from this view - just pop it down hideGUI(sp); } else { // the player has an active GUI, but it belongs to a different spout view, so pop down // that one and pop up the GUI for this view poppedUpView.hideGUI(sp); // just popping the GUI up immediately doesn't appear to work - we need to defer it by a few ticks Bukkit.getScheduler().scheduleSyncDelayedTask(ScrollingMenuSign.getInstance(), new Runnable() { @Override public void run() { showGUI(sp); } }, 3L); } } else { // no GUI shown right now - just pop this one up showGUI(sp); } } /* (non-Javadoc) * @see me.desht.scrollingmenusign.views.SMSScrollableView#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable menu, Object arg1) { super.update(menu, arg1);
ViewUpdateAction vu = ViewUpdateAction.getAction(arg1);
7
panhainan/BookHouse
src/main/java/com/phn/bookhouse/service/impl/OrderServiceImpl.java
[ "public interface AddressDao {\n\n\t/**\n\t * @author pan\n\t * @param addressid\n\t * @return\n\t */\n\tpublic Address selectAddressById(long addressid);\n\n\t/**\n\t * @author pan\n\t * @param addressid\n\t * @return\n\t */\n\tpublic int deleteAddress(long addressid);\n\n\t/**\n\t * @author pan\n\t * @param addre...
import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.phn.bookhouse.dao.AddressDao; import com.phn.bookhouse.dao.BookDao; import com.phn.bookhouse.dao.OrderDao; import com.phn.bookhouse.entity.Address; import com.phn.bookhouse.entity.Book; import com.phn.bookhouse.entity.Order; import com.phn.bookhouse.service.OrderService;
/** * */ package com.phn.bookhouse.service.impl; /** * @file OrderServiceImpl.java * @author pan * @date 2014年11月17日 * @email panhainan@yeah.net */ @Service("orderService") public class OrderServiceImpl implements OrderService { @Autowired
private OrderDao orderDao;
2
TechzoneMC/NPCLib
nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/HumanNPCHook.java
[ "@RequiredArgsConstructor\npublic enum Animation {\n /**\n * Makes the npc act hurt\n * <p/>\n * Only applicable to living entities\n */\n HURT,\n /**\n * Makes the npc lie on the ground\n * <p/>\n * Only applicable to living entities\n */\n DEAD,\n\n // Human Animatio...
import java.lang.reflect.Field; import java.util.List; import java.util.UUID; import net.minecraft.server.v1_7_R4.EntityPlayer; import net.minecraft.server.v1_7_R4.Packet; import net.minecraft.server.v1_7_R4.PacketPlayOutAnimation; import net.minecraft.server.v1_7_R4.PacketPlayOutPlayerInfo; import net.minecraft.util.com.mojang.authlib.GameProfile; import net.techcable.npclib.Animation; import net.techcable.npclib.HumanNPC; import net.techcable.npclib.nms.IHumanNPCHook; import net.techcable.npclib.nms.versions.v1_7_R4.entity.EntityNPCPlayer; import net.techcable.npclib.utils.Reflection; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import com.google.common.base.Preconditions;
package net.techcable.npclib.nms.versions.v1_7_R4; public class HumanNPCHook extends LivingNPCHook implements IHumanNPCHook { public HumanNPCHook(HumanNPC npc, Location toSpawn) { super(npc, toSpawn, EntityType.PLAYER); getNmsEntity().setHook(this); getNmsEntity().getWorld().players.remove(getNmsEntity()); } @Override public void setSkin(UUID id) { NMS.setSkin(getNmsEntity().getProfile(), id); respawn(); } private boolean shownInTabList; @Override public void showInTablist() { if (shownInTabList) return; if (ProtocolHack.isProtocolHack()) { Packet packet18 = ProtocolHack.newPlayerInfoDataAdd(getNmsEntity()); NMS.sendToAll(packet18); } else { PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(getNmsEntity().getProfile().getName(), true, 0); NMS.sendToAll(packet); } shownInTabList = true; } @Override public void hideFromTablist() { if (!shownInTabList) return; if (ProtocolHack.isProtocolHack()) { Packet packet18 = ProtocolHack.newPlayerInfoDataRemove(getNmsEntity()); NMS.sendToAll(packet18); } else { PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(getNmsEntity().getProfile().getName(), false, 0); NMS.sendToAll(packet); } shownInTabList = false; }
public EntityNPCPlayer getNmsEntity() {
3
Integreight/1Sheeld-Android-App
oneSheeld/src/main/java/com/integreight/onesheeld/appFragments/SheeldsList.java
[ "public class MainActivity extends FragmentActivity {\n public static final int PREMISSION_REQUEST_CODE = 1;\n public static final int DRAW_OVER_APPS_REQUEST_CODE = 2;\n public static final String IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_SP = \"com.integreight.onesheeld.IS_CONTEXT_MENU_BUTTON_TUTORIAL_SHOWN_S...
import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.analytics.HitBuilders; import com.integreight.onesheeld.BuildConfig; import com.integreight.onesheeld.MainActivity; import com.integreight.onesheeld.OneSheeldApplication; import com.integreight.onesheeld.R; import com.integreight.onesheeld.Tutorial; import com.integreight.onesheeld.adapters.ShieldsListAdapter; import com.integreight.onesheeld.enums.UIShield; import com.integreight.onesheeld.model.Shield; import com.integreight.onesheeld.popup.ArduinoConnectivityPopup; import com.integreight.onesheeld.popup.FirmwareUpdatingPopup; import com.integreight.onesheeld.popup.ValidationPopup; import com.integreight.onesheeld.popup.ValidationPopup.ValidationAction; import com.integreight.onesheeld.sdk.OneSheeldConnectionCallback; import com.integreight.onesheeld.sdk.OneSheeldDevice; import com.integreight.onesheeld.sdk.OneSheeldError; import com.integreight.onesheeld.sdk.OneSheeldErrorCallback; import com.integreight.onesheeld.sdk.OneSheeldSdk; import com.integreight.onesheeld.services.OneSheeldService; import com.integreight.onesheeld.shields.controller.CameraShield; import com.integreight.onesheeld.shields.controller.ColorDetectionShield; import com.integreight.onesheeld.shields.controller.FaceDetectionShield; import com.integreight.onesheeld.shields.controller.TaskerShield; import com.integreight.onesheeld.utils.AppShields; import com.integreight.onesheeld.utils.CrashlyticsUtils; import com.integreight.onesheeld.utils.Log; import com.integreight.onesheeld.utils.customviews.OneSheeldEditText; import com.manuelpeinado.quickreturnheader.QuickReturnHeaderHelper; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import hotchemi.android.rate.AppRate;
if (activity.getSupportFragmentManager() .getBackStackEntryCount() > 1) { activity.getSupportFragmentManager() .popBackStack(); activity.getSupportFragmentManager() .executePendingTransactions(); } OneSheeldSdk.getManager().disconnectAll(); } else { Log.test("Test", "Cannot disconnect in demoMode"); getApplication().setIsDemoMode(false); } if (!ArduinoConnectivityPopup.isOpened) { ArduinoConnectivityPopup.isOpened = true; new ArduinoConnectivityPopup(activity) .show(); } } }); return; } else { activity.replaceCurrentFragment(R.id.appTransitionsContainer, ShieldsOperations.getInstance(), ShieldsOperations.class.getName(), true, true); activity.findViewById(R.id.getAvailableDevices) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); } } } OneSheeldErrorCallback errorCallback = new OneSheeldErrorCallback() { @Override public void onError(OneSheeldDevice device, OneSheeldError error) { super.onError(device, error); if (activity != null && activity.getThisApplication().taskerController != null) { activity.getThisApplication().taskerController.reset(); } activity.runOnUiThread(new Runnable() { @Override public void run() { getApplication() .endConnectionTimerAndReport(); UIShield.setConnected(false); adapter.notifyDataSetChanged(); if (activity.getSupportFragmentManager().getBackStackEntryCount() > 1) { activity.getSupportFragmentManager().popBackStack(); activity.getSupportFragmentManager() .executePendingTransactions(); } if (!ArduinoConnectivityPopup.isOpened && !getApplication().getIsDemoMode()) { new ArduinoConnectivityPopup(activity).show(); } } }); } }; OneSheeldConnectionCallback connectionCallback = new OneSheeldConnectionCallback() { @Override public void onConnect(OneSheeldDevice device) { super.onConnect(device); ((OneSheeldApplication) activity.getApplication()).setConnectedDevice(device); if (activity.getThisApplication().getConnectedDevice() != null) activity.getThisApplication().getConnectedDevice().addVersionQueryCallback(activity.versionQueryCallback); Intent intent = new Intent(activity, OneSheeldService.class); intent.putExtra(ArduinoConnectivityPopup.EXTRA_DEVICE_NAME, device.getName()); activity.startService(intent); getApplication().setConnectedDevice(device); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.getThisApplication().taskerController = new TaskerShield( activity, UIShield.TASKER_SHIELD.name()); Log.e(TAG, "- ARDUINO CONNECTED -"); getApplication().getTracker() .send(new HitBuilders.ScreenViewBuilder().setNewSession() .build()); getApplication() .startConnectionTimer(); // if (isOneSheeldServiceRunning()) { if (adapter != null) adapter.applyToControllerTable(); // } AppRate.showRateDialogIfMeetsConditions(activity); activity.showMenuButtonTutorialOnce(); } }); } @Override public void onDisconnect(OneSheeldDevice device) { super.onDisconnect(device); getApplication().setConnectedDevice(null); activity.runOnUiThread(new Runnable() { @Override public void run() { if (activity != null) { if (activity.getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name()) != null) try { ((CameraShield) activity.getThisApplication().getRunningShields().get(UIShield.CAMERA_SHIELD.name())).hidePreview(); } catch (RemoteException e) { e.printStackTrace(); } if (activity.getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name()) != null) try { ((ColorDetectionShield) activity.getThisApplication().getRunningShields().get(UIShield.COLOR_DETECTION_SHIELD.name())).hidePreview(); } catch (RemoteException e) { e.printStackTrace(); } if (activity.getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name()) != null) try {
((FaceDetectionShield) activity.getThisApplication().getRunningShields().get(UIShield.FACE_DETECTION.name())).hidePreview();
7
btk5h/skript-mirror
src/main/java/com/btk5h/skriptmirror/skript/reflect/ExprProxy.java
[ "public class FunctionWrapper {\n private final String name;\n private final Object[] arguments;\n\n public FunctionWrapper(String name, Object[] arguments) {\n this.name = name;\n this.arguments = arguments;\n }\n\n public String getName() {\n return name;\n }\n\n public Object[] getArguments() {\n...
import ch.njol.skript.Skript; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.Variable; import ch.njol.skript.lang.function.Function; import ch.njol.skript.lang.function.FunctionEvent; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import com.btk5h.skriptmirror.FunctionWrapper; import com.btk5h.skriptmirror.JavaType; import com.btk5h.skriptmirror.LibraryLoader; import com.btk5h.skriptmirror.skript.Consent; import com.btk5h.skriptmirror.util.SkriptReflection; import com.btk5h.skriptmirror.util.SkriptUtil; import org.bukkit.event.Event; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*;
package com.btk5h.skriptmirror.skript.reflect; public class ExprProxy extends SimpleExpression<Object> { static { Skript.registerExpression(ExprProxy.class, Object.class, ExpressionType.COMBINED, "[a] [new] proxy [instance] of %javatypes% (using|from) %objects%"); } private Expression<JavaType> interfaces; private Variable<?> handler; @Override protected Object[] get(Event e) { Map<String, FunctionWrapper> handlers = new HashMap<>(); handler.variablesIterator(e) .forEachRemaining(pair -> { Object value = pair.getValue(); if (value instanceof FunctionWrapper) { handlers.put(pair.getKey(), ((FunctionWrapper) value)); } }); return new Object[]{ Proxy.newProxyInstance( LibraryLoader.getClassLoader(), Arrays.stream(interfaces.getArray(e)) .map(JavaType::getJavaClass) .filter(Class::isInterface) .toArray(Class[]::new), new VariableInvocationHandler(handlers) ) }; } private static class VariableInvocationHandler implements InvocationHandler { private final Map<String, FunctionWrapper> handlers; public VariableInvocationHandler(Map<String, FunctionWrapper> handlers) { this.handlers = handlers; } @Override public Object invoke(Object proxy, Method method, Object[] methodArgs) throws Throwable { FunctionWrapper functionWrapper = handlers.get(method.getName().toLowerCase()); if (functionWrapper == null) { return null; } Function<?> function = functionWrapper.getFunction(); Object[] functionArgs = functionWrapper.getArguments(); if (function == null) { return null; } if (methodArgs == null) { methodArgs = new Object[0]; } List<Object[]> params = new ArrayList<>(functionArgs.length + methodArgs.length + 1); Arrays.stream(functionArgs) .map(arg -> new Object[]{arg}) .forEach(params::add); params.add(new Object[]{proxy}); Arrays.stream(methodArgs) .map(arg -> new Object[]{arg}) .forEach(params::add); FunctionEvent functionEvent = new FunctionEvent(null); return function.execute( functionEvent, params.stream() .limit(SkriptReflection.getParameters(function).length) .toArray(Object[][]::new) ); } } @Override public boolean isSingle() { return true; } @Override public Class<?> getReturnType() { return Object.class; } @Override public String toString(Event e, boolean debug) { return String.format("proxy of %s from %s", interfaces.toString(e, debug), handler.toString(e, debug)); } @Override public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) {
if (!Consent.Feature.PROXIES.hasConsent(SkriptUtil.getCurrentScript())) {
5
Dynious/Biota
src/main/java/com/dynious/biota/command/CommandBiota.java
[ "public class BioSystem\n{\n private static final Random RANDOM = new Random();\n\n public final WeakReference<Chunk> chunkReference;\n private int tick = RANDOM.nextInt(Settings.TICKS_PER_BIOSYSTEM_UPDATE);\n\n /**\n * Stores the amount of plants in the chunk. Plant blocks can have different amount...
import com.dynious.biota.biosystem.BioSystem; import com.dynious.biota.biosystem.BioSystemHandler; import com.dynious.biota.biosystem.BioSystemInitThread; import com.dynious.biota.lib.Commands; import com.dynious.biota.network.NetworkHandler; import com.dynious.biota.network.message.MessageBioSystemUpdate; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import java.util.List;
package com.dynious.biota.command; public class CommandBiota extends CommandBase { @Override public String getCommandName() { return Commands.BIOTA; } @Override public int getRequiredPermissionLevel() { return 2; } @Override public String getCommandUsage(ICommandSender icommandsender) { return "/" + getCommandName() + " " + Commands.HELP; } @Override public void processCommand(ICommandSender icommandsender, String[] args) { if (args.length > 0) { String commandName = args[0]; if (commandName.equalsIgnoreCase(Commands.HELP)) { //Halp } else if (commandName.equalsIgnoreCase(Commands.GET_NUTRIENTS)) { World world = icommandsender.getEntityWorld(); Chunk chunk = world.getChunkFromBlockCoords(icommandsender.getPlayerCoordinates().posX, icommandsender.getPlayerCoordinates().posZ); BioSystem bioSystem = BioSystemHandler.getBioSystem(world, chunk); if (bioSystem != null) { icommandsender.addChatMessage(new ChatComponentText(String.format("Phosphorus: %f, Potassium: %f, Nitrogen %f", bioSystem.getPhosphorus(), bioSystem.getPotassium(), bioSystem.getNitrogen()))); } } else if (commandName.equalsIgnoreCase(Commands.SET_NUTRIENTS)) { if (args.length > 3) { World world = icommandsender.getEntityWorld(); Chunk chunk = world.getChunkFromBlockCoords(icommandsender.getPlayerCoordinates().posX, icommandsender.getPlayerCoordinates().posZ); BioSystem bioSystem = BioSystemHandler.getBioSystem(world, chunk); if (bioSystem != null) { bioSystem.setPhosphorus((float) parseDouble(icommandsender, args[1])); bioSystem.setPotassium((float) parseDouble(icommandsender, args[2])); bioSystem.setNitrogen((float) parseDouble(icommandsender, args[3]));
NetworkHandler.INSTANCE.sendToPlayersWatchingChunk(new MessageBioSystemUpdate(bioSystem), (WorldServer) world, chunk.xPosition, chunk.zPosition);
4
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/supstream/dvd/IfoParser.java
[ "public class Palette {\n /** Number of palette entries */\n private final int size;\n /** Byte buffer for RED info */\n private final byte[] r;\n /** Byte buffer for GREEN info */\n private final byte[] g;\n /** Byte buffer for BLUE info */\n private final byte[] b;\n /** Byte buffer for...
import bdsup2sub.bitmap.Palette; import bdsup2sub.core.CoreException; import bdsup2sub.core.Logger; import bdsup2sub.tools.FileBuffer; import bdsup2sub.tools.FileBufferException; import bdsup2sub.utils.ToolBox; import java.util.Arrays; import static bdsup2sub.core.Constants.DEFAULT_DVD_PALETTE; import static bdsup2sub.core.Constants.LANGUAGES;
/* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.supstream.dvd; public class IfoParser { private static final Logger logger = Logger.getInstance(); private static final byte[] IFO_HEADER = "DVDVIDEO-VTS".getBytes(); private final FileBuffer fileBuffer; private int screenWidth; private int screenHeight; private int languageIdx; private Palette srcPalette = new Palette(DEFAULT_DVD_PALETTE); public IfoParser(String filename) throws CoreException { try { this.fileBuffer = new FileBuffer(filename); processIFO(); } catch (FileBufferException e) { throw new CoreException(e.getMessage()); } } private void processIFO() throws CoreException { try { validateIfoHeader(); readVideoAttributes(); readFirstLanguageIndex(); readFirstPalette(); } catch (FileBufferException e) { throw new CoreException(e.getMessage()); } } private void validateIfoHeader() throws FileBufferException, CoreException { byte header[] = new byte[IFO_HEADER.length]; fileBuffer.getBytes(0, header, IFO_HEADER.length); if (!Arrays.equals(header, IFO_HEADER)) { throw new CoreException("Not a valid IFO file."); } } private void readVideoAttributes() throws FileBufferException { int vidAttr = fileBuffer.getWord(0x200); if ((vidAttr & 0x3000) != 0) { // PAL switch ((vidAttr>>3) & 3) { case 0: screenWidth = 720; screenHeight = 576; break; case 1: screenWidth = 704; screenHeight = 576; break; case 2: screenWidth = 352; screenHeight = 576; break; case 3: screenWidth = 352; screenHeight = 288; break; } } else { // NTSC switch ((vidAttr>>3) & 3) { case 0: screenWidth = 720; screenHeight = 480; break; case 1: screenWidth = 704; screenHeight = 480; break; case 2: screenWidth = 352; screenHeight = 480; break; case 3: screenWidth = 352; screenHeight = 240; break; } } logger.trace("Resolution: " + screenWidth + "x" + screenHeight + "\n"); } private void readFirstLanguageIndex() throws FileBufferException { if (fileBuffer.getWord(0x254) > 0 && fileBuffer.getByte(0x256) == 1) { StringBuilder langSB = new StringBuilder(2); boolean found = false; langSB.append((char) fileBuffer.getByte(0x258)); langSB.append((char) fileBuffer.getByte(0x259)); String lang = langSB.toString(); for (int i=0; i < LANGUAGES.length; i++) { if (lang.equalsIgnoreCase(LANGUAGES[i][1])) { languageIdx = i; found = true; break; } } if (!found) { logger.warn("Illegal language id: " + lang + "\n"); } else { logger.trace("Set language to: " + lang + "\n"); } } else { logger.warn("Missing language id.\n"); } } private void readFirstPalette() throws FileBufferException { // get start offset of Titles&Chapters table long VTS_PGCITI_ofs = fileBuffer.getDWord(0xCC) * 2048; // PTT_SRPTI VTS_PGCITI_ofs += fileBuffer.getDWord(VTS_PGCITI_ofs+0x0C);
logger.trace("Reading palette from offset: " + ToolBox.toHexLeftZeroPadded(VTS_PGCITI_ofs, 8) + "\n");
5
deephacks/westty
westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufPipelineFactory.java
[ "@ConfigScope\n@Config(name = \"protobuf\",\n desc = \"Protobuf configuration. Changes requires server restart.\")\npublic class ProtobufConfig {\n\n @Id(desc=\"Name of this server\")\n private String serverName = ServerConfig.DEFAULT_SERVER_NAME;\n\n public ProtobufConfig(){\n }\n\n public Pr...
import com.google.protobuf.MessageLite; import org.deephacks.westty.config.ProtobufConfig; import org.deephacks.westty.config.ServerSpecificConfigProxy; import org.deephacks.westty.protobuf.FailureMessages.Failure; import org.deephacks.westty.protobuf.ProtobufClient; import org.deephacks.westty.protobuf.ProtobufSerializer; import org.deephacks.westty.spi.ProviderShutdownEvent; import org.deephacks.westty.spi.ProviderStartupEvent; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import org.jboss.netty.handler.execution.ExecutionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Singleton; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import static org.jboss.netty.buffer.ChannelBuffers.wrappedBuffer;
/** * 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.deephacks.westty.internal.protobuf; @Singleton class ProtobufPipelineFactory implements ChannelPipelineFactory { private static final Logger log = LoggerFactory.getLogger(ProtobufChannelHandler.class); @Inject private ProtobufChannelHandler channelHandler; private ProtobufSerializer serializer; private ThreadPoolExecutor executor; private ExecutionHandler executionHandler; private Channel channel; private ServerBootstrap bootstrap; private ProtobufConfig config; @Inject public ProtobufPipelineFactory(ServerSpecificConfigProxy<ProtobufConfig> config, ThreadPoolExecutor executor, ProtobufSerializer serializer) { this.config = config.get(); this.executor = executor; this.serializer = serializer; ExecutorService workers = Executors.newCachedThreadPool(); ExecutorService boss = Executors.newCachedThreadPool(); bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(boss, workers, this.config.getIoWorkerCount())); bootstrap.setPipelineFactory(this); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); }
public void startup(@Observes ProviderStartupEvent event) {
6
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloader.java
[ "public class CustomComponentHolder {\n private DownloadMgrInitialParams initialParams;\n\n private FileDownloadHelper.ConnectionCountAdapter connectionCountAdapter;\n private FileDownloadHelper.ConnectionCreator connectionCreator;\n private FileDownloadHelper.OutputStreamCreator outputStreamCreator;\n ...
import com.liulishuo.filedownloader.util.FileDownloadProperties; import com.liulishuo.filedownloader.util.FileDownloadUtils; import java.io.File; import java.util.List; import android.app.Application; import android.app.Notification; import android.content.ComponentName; import android.content.Context; import android.content.ServiceConnection; import android.os.IBinder; import com.liulishuo.filedownloader.download.CustomComponentHolder; import com.liulishuo.filedownloader.event.DownloadServiceConnectChangedEvent; import com.liulishuo.filedownloader.model.FileDownloadStatus; import com.liulishuo.filedownloader.model.FileDownloadTaskAtom; import com.liulishuo.filedownloader.services.DownloadMgrInitialParams; import com.liulishuo.filedownloader.util.FileDownloadHelper; import com.liulishuo.filedownloader.util.FileDownloadLog;
/* * Copyright (c) 2015 LingoChamp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liulishuo.filedownloader; /** * The basic entrance for FileDownloader. * * @see com.liulishuo.filedownloader.services.FileDownloadService The service for FileDownloader. * @see FileDownloadProperties */ @SuppressWarnings("WeakerAccess") public class FileDownloader { /** * You can invoke this method anytime before you using the FileDownloader. * <p> * If you want to register your own customize components please using * {@link #setupOnApplicationOnCreate(Application)} on the {@link Application#onCreate()} * instead. * * @param context the context of Application or Activity etc.. */ public static void setup(Context context) { FileDownloadHelper.holdContext(context.getApplicationContext()); } /** * Using this method to setup the FileDownloader only you want to register your own customize * components for Filedownloader, otherwise just using {@link #setup(Context)} instead. * <p/> * Please invoke this method on the {@link Application#onCreate()} because of the customize * components must be assigned before FileDownloader is running. * <p/> * Such as: * <p/> * class MyApplication extends Application { * ... * public void onCreate() { * ... * FileDownloader.setupOnApplicationOnCreate(this) * .idGenerator(new MyIdGenerator()) * .database(new MyDatabase()) * ... * .commit(); * ... * } * ... * } * @param application the application. * @return the customize components maker. */ public static DownloadMgrInitialParams.InitCustomMaker setupOnApplicationOnCreate( Application application) { final Context context = application.getApplicationContext(); FileDownloadHelper.holdContext(context); DownloadMgrInitialParams.InitCustomMaker customMaker = new DownloadMgrInitialParams.InitCustomMaker(); CustomComponentHolder.getImpl().setInitCustomMaker(customMaker); return customMaker; } /** * @deprecated please use {@link #setup(Context)} instead. */ public static void init(final Context context) { if (context == null) { throw new IllegalArgumentException("the provided context must not be null!"); } setup(context); } /** * @deprecated please using {@link #setupOnApplicationOnCreate(Application)} instead. */ public static void init(final Context context, final DownloadMgrInitialParams.InitCustomMaker maker) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(FileDownloader.class, "init Downloader with params: %s %s", context, maker); } if (context == null) { throw new IllegalArgumentException("the provided context must not be null!"); } FileDownloadHelper.holdContext(context.getApplicationContext()); CustomComponentHolder.getImpl().setInitCustomMaker(maker); } private static final class HolderClass { private static final FileDownloader INSTANCE = new FileDownloader(); } public static FileDownloader getImpl() { return HolderClass.INSTANCE; } /** * For avoiding missing screen frames. * <p/> * This mechanism is used for avoid methods in {@link FileDownloadListener} is invoked too * frequent in result the system missing screen frames in the main thread. * <p> * We wrap the message package which size is {@link FileDownloadMessageStation#SUB_PACKAGE_SIZE} * and post the package to the main thread with the interval: * {@link FileDownloadMessageStation#INTERVAL} milliseconds. * <p/> * The default interval is 10ms, if {@code intervalMillisecond} equal to or less than 0, each * callback in {@link FileDownloadListener} will be posted to the main thread immediately. * * @param intervalMillisecond The time interval between posting two message packages. * @see #enableAvoidDropFrame() * @see #disableAvoidDropFrame() * @see #setGlobalHandleSubPackageSize(int) */ public static void setGlobalPost2UIInterval(final int intervalMillisecond) { FileDownloadMessageStation.INTERVAL = intervalMillisecond; } /** * For avoiding missing screen frames. * <p/> * This mechanism is used for avoid methods in {@link FileDownloadListener} is invoked too * frequent in result the system missing screen frames in the main thread. * <p> * We wrap the message package which size is {@link FileDownloadMessageStation#SUB_PACKAGE_SIZE} * and post the package to the main thread with the interval: * {@link FileDownloadMessageStation#INTERVAL} milliseconds. * <p> * The default count of message for a message package is 5. * * @param packageSize The count of message for a message package. * @see #setGlobalPost2UIInterval(int) */ public static void setGlobalHandleSubPackageSize(final int packageSize) { if (packageSize <= 0) { throw new IllegalArgumentException("sub package size must more than 0"); } FileDownloadMessageStation.SUB_PACKAGE_SIZE = packageSize; } /** * Avoid missing screen frames, this leads to all callbacks in {@link FileDownloadListener} do * not be invoked at once when it has already achieved to ensure callbacks don't be too frequent * * @see #isEnabledAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static void enableAvoidDropFrame() { setGlobalPost2UIInterval(FileDownloadMessageStation.DEFAULT_INTERVAL); } /** * Disable avoiding missing screen frames, let all callbacks in {@link FileDownloadListener} * can be invoked at once when it achieve. * * @see #isEnabledAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static void disableAvoidDropFrame() { setGlobalPost2UIInterval(-1); } /** * @return {@code true} if enabled the function of avoiding missing screen frames. * @see #enableAvoidDropFrame() * @see #disableAvoidDropFrame() * @see #setGlobalPost2UIInterval(int) */ public static boolean isEnabledAvoidDropFrame() { return FileDownloadMessageStation.isIntervalValid(); } /** * Create a download task. */ public BaseDownloadTask create(final String url) { return new DownloadTask(url); } /** * Start the download queue by the same listener. * * @param listener Used to assemble tasks which is bound by the same {@code listener} * @param isSerial Whether start tasks one by one rather than parallel. * @return {@code true} if start tasks successfully. */ public boolean start(final FileDownloadListener listener, final boolean isSerial) { if (listener == null) { FileDownloadLog.w(this, "Tasks with the listener can't start, because the listener " + "provided is null: [null, %B]", isSerial); return false; } return isSerial ? getQueuesHandler().startQueueSerial(listener) : getQueuesHandler().startQueueParallel(listener); } /** * Pause the download queue by the same {@code listener}. * * @param listener the listener. * @see #pause(int) */ public void pause(final FileDownloadListener listener) { FileDownloadTaskLauncher.getImpl().expire(listener); final List<BaseDownloadTask.IRunningTask> taskList = FileDownloadList.getImpl().copy(listener); for (BaseDownloadTask.IRunningTask task : taskList) { task.getOrigin().pause(); } } /** * Pause all tasks running in FileDownloader. */ public void pauseAll() { FileDownloadTaskLauncher.getImpl().expireAll(); final BaseDownloadTask.IRunningTask[] downloadList = FileDownloadList.getImpl().copy(); for (BaseDownloadTask.IRunningTask task : downloadList) { task.getOrigin().pause(); } // double check, for case: File Download progress alive but ui progress has died and relived // so FileDownloadList not always contain all running task exactly. if (FileDownloadServiceProxy.getImpl().isConnected()) { FileDownloadServiceProxy.getImpl().pauseAllTasks(); } else { PauseAllMarker.createMarker(); } } /** * Pause downloading tasks with the {@code id}. * * @param id the {@code id} . * @return The size of tasks has been paused. * @see #pause(FileDownloadListener) */ public int pause(final int id) { List<BaseDownloadTask.IRunningTask> taskList = FileDownloadList.getImpl() .getDownloadingList(id); if (null == taskList || taskList.isEmpty()) { FileDownloadLog.w(this, "request pause but not exist %d", id); return 0; } for (BaseDownloadTask.IRunningTask task : taskList) { task.getOrigin().pause(); } return taskList.size(); } /** * Clear the data with the provided {@code id}. * Normally used to deleting the data in filedownloader database, when it is paused or in * downloading status. If you want to re-download it clearly. * <p/> * <strong>Note:</strong> YOU NO NEED to clear the data when it is already completed downloading * because the data would be deleted when it completed downloading automatically by * FileDownloader. * <p> * If there are tasks with the {@code id} in downloading, will be paused first; * If delete the data with the {@code id} in the filedownloader database successfully, will try * to delete its intermediate downloading file and downloaded file. * * @param id the download {@code id}. * @param targetFilePath the target path. * @return {@code true} if the data with the {@code id} in filedownloader database was deleted, * and tasks with the {@code id} was paused; {@code false} otherwise. */ public boolean clear(final int id, final String targetFilePath) { pause(id); if (FileDownloadServiceProxy.getImpl().clearTaskData(id)) { // delete the task data in the filedownloader database successfully or no data with the // id in filedownloader database.
final File intermediateFile = new File(FileDownloadUtils.getTempPath(targetFilePath));
8
Azure/azure-storage-android
microsoft-azure-storage/src/com/microsoft/azure/storage/blob/CloudBlobContainer.java
[ "public final class Constants {\n /**\n * Defines constants for ServiceProperties requests.\n */\n public static class AnalyticsConstants {\n\n /**\n * The XML element for the CORS Rule AllowedHeaders\n */\n public static final String ALLOWED_HEADERS_ELEMENT = \"AllowedHe...
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.util.Calendar; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import com.microsoft.azure.storage.AccessCondition; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.DoesServiceRequest; import com.microsoft.azure.storage.IPRange; import com.microsoft.azure.storage.OperationContext; import com.microsoft.azure.storage.ResultContinuation; import com.microsoft.azure.storage.ResultContinuationType; import com.microsoft.azure.storage.ResultSegment; import com.microsoft.azure.storage.SharedAccessPolicyHandler; import com.microsoft.azure.storage.SharedAccessPolicySerializer; import com.microsoft.azure.storage.SharedAccessProtocols; import com.microsoft.azure.storage.StorageCredentials; import com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature; import com.microsoft.azure.storage.StorageErrorCodeStrings; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.StorageUri; import com.microsoft.azure.storage.core.ExecutionEngine; import com.microsoft.azure.storage.core.LazySegmentedIterable; import com.microsoft.azure.storage.core.PathUtility; import com.microsoft.azure.storage.core.RequestLocationMode; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.core.SegmentedStorageRequest; import com.microsoft.azure.storage.core.SharedAccessSignatureHelper; import com.microsoft.azure.storage.core.StorageCredentialsHelper; import com.microsoft.azure.storage.core.StorageRequest; import com.microsoft.azure.storage.core.UriQueryBuilder; import com.microsoft.azure.storage.core.Utility;
* @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { return this.exists(false, accessCondition, options, opContext); } @DoesServiceRequest private boolean exists(final boolean primaryOnly, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = BlobRequestOptions.populateAndApplyDefaults(options, BlobType.UNSPECIFIED, this.blobServiceClient); return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, this.existsImpl(primaryOnly, accessCondition, options), options.getRetryPolicyFactory(), opContext); } private StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> existsImpl(final boolean primaryOnly, final AccessCondition accessCondition, final BlobRequestOptions options) { final StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean> getRequest = new StorageRequest<CloudBlobClient, CloudBlobContainer, Boolean>( options, this.getStorageUri()) { @Override public void setRequestLocationMode() { this.setRequestLocationMode(primaryOnly ? RequestLocationMode.PRIMARY_ONLY : RequestLocationMode.PRIMARY_OR_SECONDARY); } @Override public HttpURLConnection buildRequest(CloudBlobClient client, CloudBlobContainer container, OperationContext context) throws Exception { return BlobRequest.getContainerProperties( container.getTransformedAddress().getUri(this.getCurrentLocation()), options, context, accessCondition); } @Override public void signRequest(HttpURLConnection connection, CloudBlobClient client, OperationContext context) throws Exception { StorageRequest.signBlobQueueAndFileRequest(connection, client, -1L, context); } @Override public Boolean preProcessResponse(CloudBlobContainer container, CloudBlobClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { // Set attributes final BlobContainerAttributes attributes = BlobResponse.getBlobContainerAttributes( this.getConnection(), client.isUsePathStyleUris()); container.metadata = attributes.getMetadata(); container.properties = attributes.getProperties(); container.name = attributes.getName(); return Boolean.valueOf(true); } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Boolean.valueOf(false); } else { this.setNonExceptionedRetryableFailure(true); // return false instead of null to avoid SCA issues return false; } } }; return getRequest; } /** * Returns a shared access signature for the container. Note this does not contain the leading "?". * * @param policy * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access * signature. * @param groupPolicyIdentifier * A <code>String</code> which represents the container-level access policy. * * @return A <code>String</code> which represents a shared access signature for the container. * * @throws StorageException * If a storage service error occurred. * @throws InvalidKeyException * If the key is invalid. */ public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier) throws InvalidKeyException, StorageException { return this.generateSharedAccessSignature( policy, groupPolicyIdentifier, null /* IP range */, null /* protocols */); } /** * Returns a shared access signature for the container. Note this does not contain the leading "?". * * @param policy * An {@link SharedAccessBlobPolicy} object that represents the access policy for the shared access * signature. * @param groupPolicyIdentifier * A <code>String</code> which represents the container-level access policy. * @param ipRange * A {@link IPRange} object containing the range of allowed IP addresses. * @param protocols * A {@link SharedAccessProtocols} representing the allowed Internet protocols. * * @return A <code>String</code> which represents a shared access signature for the container. * * @throws StorageException * If a storage service error occurred. * @throws InvalidKeyException * If the key is invalid. */ public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier, final IPRange ipRange, final SharedAccessProtocols protocols) throws InvalidKeyException, StorageException {
if (!StorageCredentialsHelper.canCredentialsSignRequest(this.blobServiceClient.getCredentials())) {
7
tgobbens/fluffybalance
core/src/com/balanceball/system/PhysicsSystem.java
[ "public class GravityComponent implements Component {\n public Vector2 normalisedGravity = new Vector2();\n}", "public class GravityEntity extends Entity {\n\n public GravityEntity() {\n addComponent(new GravityComponent());\n }\n}", "public class PhysicsComponent implements Component {\n pub...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Box2D; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.balanceball.component.GravityComponent; import com.balanceball.enity.GravityEntity; import com.balanceball.component.PhysicsComponent; import com.balanceball.component.PositionComponent; import com.balanceball.component.RotationComponent; import com.sec.Entity; import com.sec.System;
package com.balanceball.system; /** * Created by tijs on 14/07/2017. */ public class PhysicsSystem extends System { public interface BallPointContactListener { void onPointContact(int type); } public final static int BODY_USER_DATA_TYPE_BALL = 0; public final static int BODY_USER_DATA_TYPE_POINT_LEFT = 1; public final static int BODY_USER_DATA_TYPE_POINT_RIGHT = 2; public final static int BODY_USER_DATA_TYPE_OTHER = 3; public static class BodyUserDate { public BodyUserDate(int type) { this.type = type; } int type = BODY_USER_DATA_TYPE_OTHER; } private final float BASE_GRAVITY = 150.f; private float mAccumulator = 0.f; private World mWorld; private boolean mIsPaused = false; private BallPointContactListener mBallPointContactListener = null; public PhysicsSystem(BallPointContactListener ballPointContactListener) { addComponentType(PhysicsComponent.class); mBallPointContactListener = ballPointContactListener; } public void setIsPaused(boolean isPaused) { mIsPaused = isPaused; } public World getWorld() { return mWorld; } @Override public void create() { Box2D.init(); mWorld = new World(new Vector2(0, BASE_GRAVITY), true); mWorld.setContactListener(new ContactListener() { @Override public void beginContact(Contact contact) { BodyUserDate userDateA = (BodyUserDate) contact.getFixtureA().getBody().getUserData(); BodyUserDate userDateB = (BodyUserDate) contact.getFixtureB().getBody().getUserData(); // check if there was a contact between the left or right point if (userDateA != null && userDateB != null) { if ((userDateA.type == BODY_USER_DATA_TYPE_POINT_LEFT && userDateB.type == BODY_USER_DATA_TYPE_BALL) || (userDateA.type == BODY_USER_DATA_TYPE_BALL && userDateB.type == BODY_USER_DATA_TYPE_POINT_LEFT)) { // touched left ball mBallPointContactListener.onPointContact(BODY_USER_DATA_TYPE_POINT_LEFT); } else if ((userDateA.type == BODY_USER_DATA_TYPE_POINT_RIGHT && userDateB.type == BODY_USER_DATA_TYPE_BALL) || (userDateA.type == BODY_USER_DATA_TYPE_BALL && userDateB.type == BODY_USER_DATA_TYPE_POINT_RIGHT)) { // touched right ball mBallPointContactListener.onPointContact(BODY_USER_DATA_TYPE_POINT_RIGHT); } } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }); } public void updateFromEntities(Array<Entity> entities) { // if the game is not running don't update the physics if (mIsPaused) { return; } GravityComponent gravityComponent = mEngine.getComponentFromFirstEntity(
GravityEntity.class, GravityComponent.class);
1
jaychang0917/SimpleRecyclerView
app/src/main/java/com/jaychang/demo/srv/DragAndDropActivity.java
[ "public class BookCell extends SimpleCell<Book, BookCell.ViewHolder>\n implements Updatable<Book> {\n\n private static final String KEY_TITLE = \"KEY_TITLE\";\n private boolean showHandle;\n\n public BookCell(Book item) {\n super(item);\n }\n\n @Override\n protected int getLayoutRes() {\n return R.layo...
import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.jaychang.demo.srv.cell.BookCell; import com.jaychang.demo.srv.model.Book; import com.jaychang.demo.srv.util.DataUtils; import com.jaychang.srv.SimpleCell; import com.jaychang.srv.SimpleRecyclerView; import com.jaychang.srv.behavior.DragAndDropCallback; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
package com.jaychang.demo.srv; public class DragAndDropActivity extends BaseActivity { @BindView(R.id.linearRecyclerView) SimpleRecyclerView linearRecyclerView; @BindView(R.id.gridRecyclerView) SimpleRecyclerView gridRecyclerView; @BindView(R.id.resultView) TextView resultView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drag_and_drop); ButterKnife.bind(this); init(); bindBooks(linearRecyclerView, true); bindBooks(gridRecyclerView, false); } private void init() { DragAndDropCallback<Book> dragAndDropCallback = new DragAndDropCallback<Book>() { // Optional @Override public boolean enableDefaultRaiseEffect() { // return false if you manipulate custom drag effect in other 3 callbacks. return super.enableDefaultRaiseEffect(); } // Optional @Override public void onCellDragStarted(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int position) { resultView.setText("Started dragging " + item + " at position " + position); } // Optional @Override public void onCellMoved(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition) { resultView.setText("Moved " + item + " from position " + fromPosition + " to position " + toPosition); } @Override public void onCellDropped(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition) { resultView.setText("Dragged " + item + " from position " + fromPosition + " to position " + toPosition); } @Override public void onCellDragCancelled(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int currentPosition) { resultView.setText("Cancelled dragging " + item + " at position " + currentPosition); } }; linearRecyclerView.enableDragAndDrop(R.id.dragHandle, dragAndDropCallback); gridRecyclerView.enableDragAndDrop(dragAndDropCallback); } @OnClick(R.id.linearRadioButton) void showLinearRecyclerView() { linearRecyclerView.setVisibility(View.VISIBLE); gridRecyclerView.setVisibility(View.GONE); resultView.setText(""); } @OnClick(R.id.gridRadioButton) void showGridRecyclerView() { linearRecyclerView.setVisibility(View.GONE); gridRecyclerView.setVisibility(View.VISIBLE); resultView.setText(""); } private void bindBooks(SimpleRecyclerView simpleRecyclerView, boolean showHandle) { List<Book> books = DataUtils.getBooks(); List<SimpleCell> cells = new ArrayList<>(); for (Book book : books) {
BookCell cell = new BookCell(book);
0