id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
sequencelengths
4
4
31,506
public void testToString() { System.out.println("testToString"); // TODO add your test code below by replacing the default call to fail. fail("The test case is empty."); }
public void testToString() { System.out.println("testToString"); fail("The test case is empty."); }
public void testtostring() { system.out.println("testtostring"); fail("the test case is empty."); }
CBIIT/camod
[ 0, 0, 0, 1 ]
31,507
public void testEquals() { System.out.println("testEquals"); // TODO add your test code below by replacing the default call to fail. fail("The test case is empty."); }
public void testEquals() { System.out.println("testEquals"); fail("The test case is empty."); }
public void testequals() { system.out.println("testequals"); fail("the test case is empty."); }
CBIIT/camod
[ 0, 0, 0, 1 ]
15,312
private void initMenuItems() { menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { var fileChooser = new FileChooser(); var selected = fileChooser.showOpenDialog(null); if (selected != null) { //TODO: file was choosen; ifmlEngine.loadStory(selected); } } }); menuItemFileRestart.setDisable(true); menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //TODO: Ask You are sure ? ifmlEngine.restart(); } }); menuItemFileSave.setDisable(true); menuItemFileLoad.setDisable(true); menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { //TODO: Add question: You are really want to exit. Platform.exit(); } }); menuItemLibraryCatalog.setDisable(true); menuItemLibraryImport.setDisable(true); menuItemSettingsCheat.setDisable(true); menuItemSettingsSettings.setDisable(true); }
private void initMenuItems() { menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { var fileChooser = new FileChooser(); var selected = fileChooser.showOpenDialog(null); if (selected != null) { ifmlEngine.loadStory(selected); } } }); menuItemFileRestart.setDisable(true); menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { ifmlEngine.restart(); } }); menuItemFileSave.setDisable(true); menuItemFileLoad.setDisable(true); menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Platform.exit(); } }); menuItemLibraryCatalog.setDisable(true); menuItemLibraryImport.setDisable(true); menuItemSettingsCheat.setDisable(true); menuItemSettingsSettings.setDisable(true); }
private void initmenuitems() { menuitemfileopen.setonaction(new eventhandler<actionevent>() { @override public void handle(actionevent event) { var filechooser = new filechooser(); var selected = filechooser.showopendialog(null); if (selected != null) { ifmlengine.loadstory(selected); } } }); menuitemfilerestart.setdisable(true); menuitemfilerestart.setonaction(new eventhandler<actionevent>() { @override public void handle(actionevent event) { ifmlengine.restart(); } }); menuitemfilesave.setdisable(true); menuitemfileload.setdisable(true); menuitemfileexit.setonaction(new eventhandler<actionevent>() { @override public void handle(actionevent event) { platform.exit(); } }); menuitemlibrarycatalog.setdisable(true); menuitemlibraryimport.setdisable(true); menuitemsettingscheat.setdisable(true); menuitemsettingssettings.setdisable(true); }
IFML2/ifml-player
[ 0, 1, 0, 0 ]
15,473
private static Path resolve(Path parent, String path) { // Ensure directories exist File directory = parent.toFile(); if (!directory.exists() && !directory.mkdirs()) { // Failed to create directories... should probably let this crash ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...", directory.getAbsolutePath()); } return parent.resolve(path); }
private static Path resolve(Path parent, String path) { File directory = parent.toFile(); if (!directory.exists() && !directory.mkdirs()) { ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...", directory.getAbsolutePath()); } return parent.resolve(path); }
private static path resolve(path parent, string path) { file directory = parent.tofile(); if (!directory.exists() && !directory.mkdirs()) { scalinghealth.logger.error("failed to create config directory '{}'. this won't end well...", directory.getabsolutepath()); } return parent.resolve(path); }
Cyborgmas/ScalingHealth
[ 0, 0, 1, 0 ]
15,483
private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException { Constructor<?> ctor = clazz.getDeclaredConstructors()[0]; ctor.setAccessible(true); Object instance = ctor.newInstance(); Method method = null; Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method m : declaredMethods) { if (m.getName().equals("apply")) method = m; } assert method != null: "Method 'apply' not found in annotation class"; method.setAccessible(true); Object result; try { result = method.invoke(instance, trees); } catch (InvocationTargetException e) { // we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible // also flatten to avoid getting nested ITEs RuntimeException exception = new RuntimeException(e.getTargetException().toString()); exception.setStackTrace(e.getStackTrace()); throw exception; } return result; }
private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException { Constructor<?> ctor = clazz.getDeclaredConstructors()[0]; ctor.setAccessible(true); Object instance = ctor.newInstance(); Method method = null; Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method m : declaredMethods) { if (m.getName().equals("apply")) method = m; } assert method != null: "Method 'apply' not found in annotation class"; method.setAccessible(true); Object result; try { result = method.invoke(instance, trees); } catch (InvocationTargetException e) { RuntimeException exception = new RuntimeException(e.getTargetException().toString()); exception.setStackTrace(e.getStackTrace()); throw exception; } return result; }
private static object invokeannotation(class<?> clazz, object[] trees) throws instantiationexception, illegalaccessexception, invocationtargetexception { constructor<?> ctor = clazz.getdeclaredconstructors()[0]; ctor.setaccessible(true); object instance = ctor.newinstance(); method method = null; method[] declaredmethods = clazz.getdeclaredmethods(); for (method m : declaredmethods) { if (m.getname().equals("apply")) method = m; } assert method != null: "method 'apply' not found in annotation class"; method.setaccessible(true); object result; try { result = method.invoke(instance, trees); } catch (invocationtargetexception e) { runtimeexception exception = new runtimeexception(e.gettargetexception().tostring()); exception.setstacktrace(e.getstacktrace()); throw exception; } return result; }
FogInTheFrog/intellij-scala
[ 0, 1, 0, 0 ]
23,785
private static void replaceParagraphWithPreface(final Context context, final XWPFParagraph paragraph) { try (final CursorHelper cursorHelper = context.newCursorHelper(paragraph)) { // TODO insert preface } finally { context.getDocument().removeBodyElement(context.getDocument().getPosOfParagraph(paragraph)); } }
private static void replaceParagraphWithPreface(final Context context, final XWPFParagraph paragraph) { try (final CursorHelper cursorHelper = context.newCursorHelper(paragraph)) { } finally { context.getDocument().removeBodyElement(context.getDocument().getPosOfParagraph(paragraph)); } }
private static void replaceparagraphwithpreface(final context context, final xwpfparagraph paragraph) { try (final cursorhelper cursorhelper = context.newcursorhelper(paragraph)) { } finally { context.getdocument().removebodyelement(context.getdocument().getposofparagraph(paragraph)); } }
FIT-Mobility/dimo-tool-suite
[ 0, 1, 0, 0 ]
15,634
public void sendObjOutbound(MongoSession ms, SubNode parent, SubNode node, boolean forceSendToPublic) { exec.run(() -> { try { boolean isAccnt = NodeType.ACCOUNT.s().equals(node.getType()); // Get the inReplyTo from the parent property (foreign node) or if not found generate one based on // what the local server version of it is. String inReplyTo = !isAccnt ? apUtil.buildUrlForReplyTo(ms, parent) : null; APList attachments = !isAccnt ? apub.createAttachmentsList(node) : null; String replyToType = parent.getStr(NodeProp.ACT_PUB_OBJ_TYPE); String boostTarget = parent.getStr(NodeProp.BOOST); // toUserNames will hold ALL usernames in the ACL list (both local and foreign user names) HashSet<String> toUserNames = new HashSet<>(); boolean privateMessage = true; if (forceSendToPublic) { privateMessage = false; } else { if (ok(node.getAc())) { /* * Lookup all userNames from the ACL info, to add them all to 'toUserNames' */ for (String accntId : node.getAc().keySet()) { if (PrincipalName.PUBLIC.s().equals(accntId)) { privateMessage = false; } else { SubNode accntNode = cachedGetAccntNodeById(ms, accntId); // get username off this node and add to 'toUserNames' if (ok(accntNode)) { toUserNames.add(accntNode.getStr(NodeProp.USER)); } } } } } // String apId = parent.getStringProp(NodeProp.ACT_PUB_ID.s()); String fromUser = ThreadLocals.getSC().getUserName(); String fromActor = apUtil.makeActorUrlForUserName(fromUser); String privateKey = apCrypto.getPrivateKey(ms, fromUser); String objUrl = snUtil.getIdBasedUrl(node); APObj message = null; if (node.getType().equals(NodeType.ACCOUNT.s())) { // construct the Update-type wrapper around teh Person object, and send message = apFactory.newUpdateForPerson(fromUser, toUserNames, fromActor, privateMessage, node); log.debug("Sending updated Person outbound: " + XString.prettyPrint(message)); } else { // if this node has a boostTarget, we know it's an Announce so we send out the announce // todo-0: we should probably rely on if there's an ActPub TYPE itself that's "Announce" (we save // that right?) if (!StringUtils.isEmpty(boostTarget)) { ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); message = apFactory.newAnnounce(fromUser, fromActor, objUrl, toUserNames, boostTarget, now, privateMessage); } // else send out as a note. else { message = apFactory.newCreateForNote(fromUser, toUserNames, fromActor, inReplyTo, replyToType, node.getContent(), objUrl, privateMessage, attachments); } } // for users that don't have a sharedInbox we collect their inboxes here to send to them // individually HashSet<String> userInboxes = new HashSet<>(); // When posting a public message we send out to all unique sharedInboxes here if (!privateMessage) { HashSet<String> sharedInboxes = new HashSet<>(); // loads ONLY foreign user's inboxes into the two sets. getSharedInboxesOfFollowers(fromUser, sharedInboxes, userInboxes); // merge both sets of inboxes into allInboxes and send to them HashSet<String> allInboxes = new HashSet<>(userInboxes); allInboxes.addAll(sharedInboxes); apUtil.securePostEx(allInboxes, fromActor, privateKey, fromActor, message, APConst.MTYPE_LD_JSON_PROF); } // Post message to all foreign usernames found in 'toUserNames', but skip all in userInboxes becasue // we just sent to those above. if (toUserNames.size() > 0) { sendMessageToUsers(ms, toUserNames, fromUser, message, privateMessage, userInboxes); } } // catch (Exception e) { log.error("sendNote failed", e); throw new RuntimeException(e); } }); }
public void sendObjOutbound(MongoSession ms, SubNode parent, SubNode node, boolean forceSendToPublic) { exec.run(() -> { try { boolean isAccnt = NodeType.ACCOUNT.s().equals(node.getType()); String inReplyTo = !isAccnt ? apUtil.buildUrlForReplyTo(ms, parent) : null; APList attachments = !isAccnt ? apub.createAttachmentsList(node) : null; String replyToType = parent.getStr(NodeProp.ACT_PUB_OBJ_TYPE); String boostTarget = parent.getStr(NodeProp.BOOST); HashSet<String> toUserNames = new HashSet<>(); boolean privateMessage = true; if (forceSendToPublic) { privateMessage = false; } else { if (ok(node.getAc())) { for (String accntId : node.getAc().keySet()) { if (PrincipalName.PUBLIC.s().equals(accntId)) { privateMessage = false; } else { SubNode accntNode = cachedGetAccntNodeById(ms, accntId); if (ok(accntNode)) { toUserNames.add(accntNode.getStr(NodeProp.USER)); } } } } } String fromUser = ThreadLocals.getSC().getUserName(); String fromActor = apUtil.makeActorUrlForUserName(fromUser); String privateKey = apCrypto.getPrivateKey(ms, fromUser); String objUrl = snUtil.getIdBasedUrl(node); APObj message = null; if (node.getType().equals(NodeType.ACCOUNT.s())) { message = apFactory.newUpdateForPerson(fromUser, toUserNames, fromActor, privateMessage, node); log.debug("Sending updated Person outbound: " + XString.prettyPrint(message)); } else { if (!StringUtils.isEmpty(boostTarget)) { ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); message = apFactory.newAnnounce(fromUser, fromActor, objUrl, toUserNames, boostTarget, now, privateMessage); } else { message = apFactory.newCreateForNote(fromUser, toUserNames, fromActor, inReplyTo, replyToType, node.getContent(), objUrl, privateMessage, attachments); } } HashSet<String> userInboxes = new HashSet<>(); if (!privateMessage) { HashSet<String> sharedInboxes = new HashSet<>(); getSharedInboxesOfFollowers(fromUser, sharedInboxes, userInboxes); HashSet<String> allInboxes = new HashSet<>(userInboxes); allInboxes.addAll(sharedInboxes); apUtil.securePostEx(allInboxes, fromActor, privateKey, fromActor, message, APConst.MTYPE_LD_JSON_PROF); } if (toUserNames.size() > 0) { sendMessageToUsers(ms, toUserNames, fromUser, message, privateMessage, userInboxes); } } catch (Exception e) { log.error("sendNote failed", e); throw new RuntimeException(e); } }); }
public void sendobjoutbound(mongosession ms, subnode parent, subnode node, boolean forcesendtopublic) { exec.run(() -> { try { boolean isaccnt = nodetype.account.s().equals(node.gettype()); string inreplyto = !isaccnt ? aputil.buildurlforreplyto(ms, parent) : null; aplist attachments = !isaccnt ? apub.createattachmentslist(node) : null; string replytotype = parent.getstr(nodeprop.act_pub_obj_type); string boosttarget = parent.getstr(nodeprop.boost); hashset<string> tousernames = new hashset<>(); boolean privatemessage = true; if (forcesendtopublic) { privatemessage = false; } else { if (ok(node.getac())) { for (string accntid : node.getac().keyset()) { if (principalname.public.s().equals(accntid)) { privatemessage = false; } else { subnode accntnode = cachedgetaccntnodebyid(ms, accntid); if (ok(accntnode)) { tousernames.add(accntnode.getstr(nodeprop.user)); } } } } } string fromuser = threadlocals.getsc().getusername(); string fromactor = aputil.makeactorurlforusername(fromuser); string privatekey = apcrypto.getprivatekey(ms, fromuser); string objurl = snutil.getidbasedurl(node); apobj message = null; if (node.gettype().equals(nodetype.account.s())) { message = apfactory.newupdateforperson(fromuser, tousernames, fromactor, privatemessage, node); log.debug("sending updated person outbound: " + xstring.prettyprint(message)); } else { if (!stringutils.isempty(boosttarget)) { zoneddatetime now = zoneddatetime.now(zoneoffset.utc); message = apfactory.newannounce(fromuser, fromactor, objurl, tousernames, boosttarget, now, privatemessage); } else { message = apfactory.newcreatefornote(fromuser, tousernames, fromactor, inreplyto, replytotype, node.getcontent(), objurl, privatemessage, attachments); } } hashset<string> userinboxes = new hashset<>(); if (!privatemessage) { hashset<string> sharedinboxes = new hashset<>(); getsharedinboxesoffollowers(fromuser, sharedinboxes, userinboxes); hashset<string> allinboxes = new hashset<>(userinboxes); allinboxes.addall(sharedinboxes); aputil.securepostex(allinboxes, fromactor, privatekey, fromactor, message, apconst.mtype_ld_json_prof); } if (tousernames.size() > 0) { sendmessagetousers(ms, tousernames, fromuser, message, privatemessage, userinboxes); } } catch (exception e) { log.error("sendnote failed", e); throw new runtimeexception(e); } }); }
Clay-Ferguson/Quantizr
[ 1, 0, 0, 0 ]
15,732
@Override public ReactionToIncomingMessage processIncomingMessage(Object message) { if (isIncomingMessageValid(message, CableCheckReqType.class, cableCheckRes)) { V2GMessage v2gMessageReq = (V2GMessage) message; CableCheckReqType cableCheckReq = (CableCheckReqType) v2gMessageReq.getBody().getBodyElement().getValue(); // TODO how to react to failure status of DCEVStatus of cableCheckReq? /* * TODO we need a timeout mechanism here so that a response can be sent within 2s * the DCEVSEStatus should be generated according to already available values * (if EVSEProcessing == ONGOING, maybe because of EVSE_IsolationMonitoringActive, * within a certain timeout, then the status must be different) */ setEvseProcessingFinished(true); if (isEvseProcessingFinished()) { cableCheckRes.setEVSEProcessing(EVSEProcessingType.FINISHED); cableCheckRes.setDCEVSEStatus( ((IDCEVSEController) getCommSessionContext().getDCEvseController()).getDCEVSEStatus(EVSENotificationType.NONE) ); return getSendMessage(cableCheckRes, V2GMessages.PRE_CHARGE_REQ); } else { cableCheckRes.setEVSEProcessing(EVSEProcessingType.ONGOING); return getSendMessage(cableCheckRes, V2GMessages.CABLE_CHECK_REQ); } } else { setMandatoryFieldsForFailedRes(); } return getSendMessage(cableCheckRes, V2GMessages.NONE); }
@Override public ReactionToIncomingMessage processIncomingMessage(Object message) { if (isIncomingMessageValid(message, CableCheckReqType.class, cableCheckRes)) { V2GMessage v2gMessageReq = (V2GMessage) message; CableCheckReqType cableCheckReq = (CableCheckReqType) v2gMessageReq.getBody().getBodyElement().getValue(); setEvseProcessingFinished(true); if (isEvseProcessingFinished()) { cableCheckRes.setEVSEProcessing(EVSEProcessingType.FINISHED); cableCheckRes.setDCEVSEStatus( ((IDCEVSEController) getCommSessionContext().getDCEvseController()).getDCEVSEStatus(EVSENotificationType.NONE) ); return getSendMessage(cableCheckRes, V2GMessages.PRE_CHARGE_REQ); } else { cableCheckRes.setEVSEProcessing(EVSEProcessingType.ONGOING); return getSendMessage(cableCheckRes, V2GMessages.CABLE_CHECK_REQ); } } else { setMandatoryFieldsForFailedRes(); } return getSendMessage(cableCheckRes, V2GMessages.NONE); }
@override public reactiontoincomingmessage processincomingmessage(object message) { if (isincomingmessagevalid(message, cablecheckreqtype.class, cablecheckres)) { v2gmessage v2gmessagereq = (v2gmessage) message; cablecheckreqtype cablecheckreq = (cablecheckreqtype) v2gmessagereq.getbody().getbodyelement().getvalue(); setevseprocessingfinished(true); if (isevseprocessingfinished()) { cablecheckres.setevseprocessing(evseprocessingtype.finished); cablecheckres.setdcevsestatus( ((idcevsecontroller) getcommsessioncontext().getdcevsecontroller()).getdcevsestatus(evsenotificationtype.none) ); return getsendmessage(cablecheckres, v2gmessages.pre_charge_req); } else { cablecheckres.setevseprocessing(evseprocessingtype.ongoing); return getsendmessage(cablecheckres, v2gmessages.cable_check_req); } } else { setmandatoryfieldsforfailedres(); } return getsendmessage(cablecheckres, v2gmessages.none); }
I2SE/RISE-V2G
[ 0, 1, 0, 0 ]
15,882
public static void startActionFoo(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_FOO); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); }
public static void startActionFoo(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_FOO); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); }
public static void startactionfoo(context context, string param1, string param2) { intent intent = new intent(context, myintentservice.class); intent.setaction(action_foo); intent.putextra(extra_param1, param1); intent.putextra(extra_param2, param2); context.startservice(intent); }
CasterIO/Bootstrap
[ 0, 1, 0, 0 ]
15,883
public static void startActionBaz(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_BAZ); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); }
public static void startActionBaz(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_BAZ); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); }
public static void startactionbaz(context context, string param1, string param2) { intent intent = new intent(context, myintentservice.class); intent.setaction(action_baz); intent.putextra(extra_param1, param1); intent.putextra(extra_param2, param2); context.startservice(intent); }
CasterIO/Bootstrap
[ 0, 1, 0, 0 ]
24,133
public String deResolve(eu.hyvar.feature.HyFeatureAttribute element, eu.hyvar.context.contextValidity.HyAttributeValidityFormula container, EReference reference) { return HyFeatureResolverUtil.deresolveFeatureAttribute(element, new Date()); }
public String deResolve(eu.hyvar.feature.HyFeatureAttribute element, eu.hyvar.context.contextValidity.HyAttributeValidityFormula container, EReference reference) { return HyFeatureResolverUtil.deresolveFeatureAttribute(element, new Date()); }
public string deresolve(eu.hyvar.feature.hyfeatureattribute element, eu.hyvar.context.contextvalidity.hyattributevalidityformula container, ereference reference) { return hyfeatureresolverutil.deresolvefeatureattribute(element, new date()); }
DarwinSPL/DarwinSPL
[ 0, 1, 0, 0 ]
15,951
public ExpressionStageOptions generateExpressionStageOptions() { List<String> allExpressionStagesRaw = retrieveExpressionStages.getDmelanogasterExpressionStages(); ExpressionStageOptions expressionStageOptions = new ExpressionStageOptions(); List<ExpressionStageGroup> expressionStageGroupList = new LinkedList<ExpressionStageGroup>(); List<ExpressionStage> allExpressionStages = new ArrayList<ExpressionStage>(allExpressionStagesRaw.size()); int idCounter = 0; for (String expressionStageString : allExpressionStagesRaw) { ExpressionStage expressionStage = new ExpressionStage(); expressionStage.setExpressionStageTitle(expressionStageString); expressionStage.setExpressionStageId("stage" + idCounter); expressionStage.setExpressionStageNumericalId(idCounter); allExpressionStages.add(expressionStage); idCounter++; } // Add expressionStageList to returned object expressionStageOptions.setExpressionStageList(allExpressionStages); /* * Add embryogenesis expressionStageGroup */ ExpressionStageGroup embryologyExpressionStageGroup = new ExpressionStageGroup(); embryologyExpressionStageGroup.setGroupTitle("embryogenesis"); embryologyExpressionStageGroup.setGroupId("group" + 0); embryologyExpressionStageGroup.setGroupNumericalId(0); List<ExpressionStage> embryologyExpressionStageList = new LinkedList<ExpressionStage>(); // Add embryo stages for (int i = 56; i <= 67; i++) { embryologyExpressionStageList.add(allExpressionStages.get(i)); } embryologyExpressionStageGroup.setExpressionStageList(embryologyExpressionStageList); expressionStageGroupList.add(embryologyExpressionStageGroup); /* * Add development expressionStageGroup */ ExpressionStageGroup developmentExpressionStageGroup = new ExpressionStageGroup(); developmentExpressionStageGroup.setGroupTitle("development"); developmentExpressionStageGroup.setGroupId("group" + 1); developmentExpressionStageGroup.setGroupNumericalId(1); List<ExpressionStage> developmentExpressionStageList = new LinkedList<ExpressionStage>(); // Add embryo stages for (int i = 56; i <= 67; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } // larva stages for (int i = 75; i <= 81; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } developmentExpressionStageList.add(allExpressionStages.get(97)); for (int i = 49; i <= 54; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 38; i <= 41; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } // TODO: Add the others developmentExpressionStageList.add(allExpressionStages.get(19)); developmentExpressionStageList.add(allExpressionStages.get(44)); developmentExpressionStageGroup.setExpressionStageList(developmentExpressionStageList); expressionStageGroupList.add(developmentExpressionStageGroup); /* * Add tissue expressionStageGroup */ ExpressionStageGroup tissueExpressionStageGroup = new ExpressionStageGroup(); tissueExpressionStageGroup.setGroupTitle("tissue"); tissueExpressionStageGroup.setGroupId("group" + 2); tissueExpressionStageGroup.setGroupNumericalId(2); List<ExpressionStage> tissueExpressionStageList = new LinkedList<ExpressionStage>(); // A Mate stages for (int i = 11; i <= 29; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 32; i <= 37; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 42; i <= 43; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 47; i <= 48; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } tissueExpressionStageGroup.setExpressionStageList(tissueExpressionStageList); expressionStageGroupList.add(tissueExpressionStageGroup); /* * Add treatment expressionStageGroup */ ExpressionStageGroup treatmentExpressionStageGroup = new ExpressionStageGroup(); treatmentExpressionStageGroup.setGroupTitle("treatment"); treatmentExpressionStageGroup.setGroupId("group" + 3); treatmentExpressionStageGroup.setGroupNumericalId(3); List<ExpressionStage> treatmentExpressionStageList = new LinkedList<ExpressionStage>(); // larva stages for (int i = 82; i <= 90; i++) { treatmentExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 0; i <= 10; i++) { treatmentExpressionStageList.add(allExpressionStages.get(i)); } treatmentExpressionStageGroup.setExpressionStageList(treatmentExpressionStageList); expressionStageGroupList.add(treatmentExpressionStageGroup); /* * Add cell-line expressionStageGroup */ ExpressionStageGroup cellLineExpressionStageGroup = new ExpressionStageGroup(); cellLineExpressionStageGroup.setGroupTitle("cell-line"); cellLineExpressionStageGroup.setGroupId("group" + 4); cellLineExpressionStageGroup.setGroupNumericalId(4); List<ExpressionStage> cellLineExpressionStageList = new LinkedList<ExpressionStage>(); // Add embryo stages for (int i = 98; i <= 103; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } // larva stages for (int i = 68; i <= 74; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 91; i <= 96; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 45; i <= 46; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 30; i <= 31; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } cellLineExpressionStageList.add(allExpressionStages.get(55)); // TODO: Add the others cellLineExpressionStageGroup.setExpressionStageList(cellLineExpressionStageList); expressionStageGroupList.add(cellLineExpressionStageGroup); expressionStageOptions.setExpressionStageGroupList(expressionStageGroupList); return expressionStageOptions; }
public ExpressionStageOptions generateExpressionStageOptions() { List<String> allExpressionStagesRaw = retrieveExpressionStages.getDmelanogasterExpressionStages(); ExpressionStageOptions expressionStageOptions = new ExpressionStageOptions(); List<ExpressionStageGroup> expressionStageGroupList = new LinkedList<ExpressionStageGroup>(); List<ExpressionStage> allExpressionStages = new ArrayList<ExpressionStage>(allExpressionStagesRaw.size()); int idCounter = 0; for (String expressionStageString : allExpressionStagesRaw) { ExpressionStage expressionStage = new ExpressionStage(); expressionStage.setExpressionStageTitle(expressionStageString); expressionStage.setExpressionStageId("stage" + idCounter); expressionStage.setExpressionStageNumericalId(idCounter); allExpressionStages.add(expressionStage); idCounter++; } expressionStageOptions.setExpressionStageList(allExpressionStages); ExpressionStageGroup embryologyExpressionStageGroup = new ExpressionStageGroup(); embryologyExpressionStageGroup.setGroupTitle("embryogenesis"); embryologyExpressionStageGroup.setGroupId("group" + 0); embryologyExpressionStageGroup.setGroupNumericalId(0); List<ExpressionStage> embryologyExpressionStageList = new LinkedList<ExpressionStage>(); for (int i = 56; i <= 67; i++) { embryologyExpressionStageList.add(allExpressionStages.get(i)); } embryologyExpressionStageGroup.setExpressionStageList(embryologyExpressionStageList); expressionStageGroupList.add(embryologyExpressionStageGroup); ExpressionStageGroup developmentExpressionStageGroup = new ExpressionStageGroup(); developmentExpressionStageGroup.setGroupTitle("development"); developmentExpressionStageGroup.setGroupId("group" + 1); developmentExpressionStageGroup.setGroupNumericalId(1); List<ExpressionStage> developmentExpressionStageList = new LinkedList<ExpressionStage>(); for (int i = 56; i <= 67; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 75; i <= 81; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } developmentExpressionStageList.add(allExpressionStages.get(97)); for (int i = 49; i <= 54; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 38; i <= 41; i++) { developmentExpressionStageList.add(allExpressionStages.get(i)); } developmentExpressionStageList.add(allExpressionStages.get(19)); developmentExpressionStageList.add(allExpressionStages.get(44)); developmentExpressionStageGroup.setExpressionStageList(developmentExpressionStageList); expressionStageGroupList.add(developmentExpressionStageGroup); ExpressionStageGroup tissueExpressionStageGroup = new ExpressionStageGroup(); tissueExpressionStageGroup.setGroupTitle("tissue"); tissueExpressionStageGroup.setGroupId("group" + 2); tissueExpressionStageGroup.setGroupNumericalId(2); List<ExpressionStage> tissueExpressionStageList = new LinkedList<ExpressionStage>(); for (int i = 11; i <= 29; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 32; i <= 37; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 42; i <= 43; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 47; i <= 48; i++) { tissueExpressionStageList.add(allExpressionStages.get(i)); } tissueExpressionStageGroup.setExpressionStageList(tissueExpressionStageList); expressionStageGroupList.add(tissueExpressionStageGroup); ExpressionStageGroup treatmentExpressionStageGroup = new ExpressionStageGroup(); treatmentExpressionStageGroup.setGroupTitle("treatment"); treatmentExpressionStageGroup.setGroupId("group" + 3); treatmentExpressionStageGroup.setGroupNumericalId(3); List<ExpressionStage> treatmentExpressionStageList = new LinkedList<ExpressionStage>(); for (int i = 82; i <= 90; i++) { treatmentExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 0; i <= 10; i++) { treatmentExpressionStageList.add(allExpressionStages.get(i)); } treatmentExpressionStageGroup.setExpressionStageList(treatmentExpressionStageList); expressionStageGroupList.add(treatmentExpressionStageGroup); ExpressionStageGroup cellLineExpressionStageGroup = new ExpressionStageGroup(); cellLineExpressionStageGroup.setGroupTitle("cell-line"); cellLineExpressionStageGroup.setGroupId("group" + 4); cellLineExpressionStageGroup.setGroupNumericalId(4); List<ExpressionStage> cellLineExpressionStageList = new LinkedList<ExpressionStage>(); for (int i = 98; i <= 103; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 68; i <= 74; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 91; i <= 96; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 45; i <= 46; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } for (int i = 30; i <= 31; i++) { cellLineExpressionStageList.add(allExpressionStages.get(i)); } cellLineExpressionStageList.add(allExpressionStages.get(55)); cellLineExpressionStageGroup.setExpressionStageList(cellLineExpressionStageList); expressionStageGroupList.add(cellLineExpressionStageGroup); expressionStageOptions.setExpressionStageGroupList(expressionStageGroupList); return expressionStageOptions; }
public expressionstageoptions generateexpressionstageoptions() { list<string> allexpressionstagesraw = retrieveexpressionstages.getdmelanogasterexpressionstages(); expressionstageoptions expressionstageoptions = new expressionstageoptions(); list<expressionstagegroup> expressionstagegrouplist = new linkedlist<expressionstagegroup>(); list<expressionstage> allexpressionstages = new arraylist<expressionstage>(allexpressionstagesraw.size()); int idcounter = 0; for (string expressionstagestring : allexpressionstagesraw) { expressionstage expressionstage = new expressionstage(); expressionstage.setexpressionstagetitle(expressionstagestring); expressionstage.setexpressionstageid("stage" + idcounter); expressionstage.setexpressionstagenumericalid(idcounter); allexpressionstages.add(expressionstage); idcounter++; } expressionstageoptions.setexpressionstagelist(allexpressionstages); expressionstagegroup embryologyexpressionstagegroup = new expressionstagegroup(); embryologyexpressionstagegroup.setgrouptitle("embryogenesis"); embryologyexpressionstagegroup.setgroupid("group" + 0); embryologyexpressionstagegroup.setgroupnumericalid(0); list<expressionstage> embryologyexpressionstagelist = new linkedlist<expressionstage>(); for (int i = 56; i <= 67; i++) { embryologyexpressionstagelist.add(allexpressionstages.get(i)); } embryologyexpressionstagegroup.setexpressionstagelist(embryologyexpressionstagelist); expressionstagegrouplist.add(embryologyexpressionstagegroup); expressionstagegroup developmentexpressionstagegroup = new expressionstagegroup(); developmentexpressionstagegroup.setgrouptitle("development"); developmentexpressionstagegroup.setgroupid("group" + 1); developmentexpressionstagegroup.setgroupnumericalid(1); list<expressionstage> developmentexpressionstagelist = new linkedlist<expressionstage>(); for (int i = 56; i <= 67; i++) { developmentexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 75; i <= 81; i++) { developmentexpressionstagelist.add(allexpressionstages.get(i)); } developmentexpressionstagelist.add(allexpressionstages.get(97)); for (int i = 49; i <= 54; i++) { developmentexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 38; i <= 41; i++) { developmentexpressionstagelist.add(allexpressionstages.get(i)); } developmentexpressionstagelist.add(allexpressionstages.get(19)); developmentexpressionstagelist.add(allexpressionstages.get(44)); developmentexpressionstagegroup.setexpressionstagelist(developmentexpressionstagelist); expressionstagegrouplist.add(developmentexpressionstagegroup); expressionstagegroup tissueexpressionstagegroup = new expressionstagegroup(); tissueexpressionstagegroup.setgrouptitle("tissue"); tissueexpressionstagegroup.setgroupid("group" + 2); tissueexpressionstagegroup.setgroupnumericalid(2); list<expressionstage> tissueexpressionstagelist = new linkedlist<expressionstage>(); for (int i = 11; i <= 29; i++) { tissueexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 32; i <= 37; i++) { tissueexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 42; i <= 43; i++) { tissueexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 47; i <= 48; i++) { tissueexpressionstagelist.add(allexpressionstages.get(i)); } tissueexpressionstagegroup.setexpressionstagelist(tissueexpressionstagelist); expressionstagegrouplist.add(tissueexpressionstagegroup); expressionstagegroup treatmentexpressionstagegroup = new expressionstagegroup(); treatmentexpressionstagegroup.setgrouptitle("treatment"); treatmentexpressionstagegroup.setgroupid("group" + 3); treatmentexpressionstagegroup.setgroupnumericalid(3); list<expressionstage> treatmentexpressionstagelist = new linkedlist<expressionstage>(); for (int i = 82; i <= 90; i++) { treatmentexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 0; i <= 10; i++) { treatmentexpressionstagelist.add(allexpressionstages.get(i)); } treatmentexpressionstagegroup.setexpressionstagelist(treatmentexpressionstagelist); expressionstagegrouplist.add(treatmentexpressionstagegroup); expressionstagegroup celllineexpressionstagegroup = new expressionstagegroup(); celllineexpressionstagegroup.setgrouptitle("cell-line"); celllineexpressionstagegroup.setgroupid("group" + 4); celllineexpressionstagegroup.setgroupnumericalid(4); list<expressionstage> celllineexpressionstagelist = new linkedlist<expressionstage>(); for (int i = 98; i <= 103; i++) { celllineexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 68; i <= 74; i++) { celllineexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 91; i <= 96; i++) { celllineexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 45; i <= 46; i++) { celllineexpressionstagelist.add(allexpressionstages.get(i)); } for (int i = 30; i <= 31; i++) { celllineexpressionstagelist.add(allexpressionstages.get(i)); } celllineexpressionstagelist.add(allexpressionstages.get(55)); celllineexpressionstagegroup.setexpressionstagelist(celllineexpressionstagelist); expressionstagegrouplist.add(celllineexpressionstagegroup); expressionstageoptions.setexpressionstagegrouplist(expressionstagegrouplist); return expressionstageoptions; }
CodingBash/fly-transcription-webapp
[ 1, 1, 0, 0 ]
7,837
public Image LoadImageAnim(String fileName, int frames) { Image image = new Image(); int framesCount = 1; if (SUPPORT_FILEFORMAT_GIF) { if (rCore.IsFileExtension(fileName, ".gif")) { byte[] fileData = null; try{ BufferedImage tmpImg = ImageIO.read(new File(fileName)); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(tmpImg, rCore.GetFileExtension(fileName).substring(1), os); fileData = os.toByteArray(); } catch (IOException exception) { exception.printStackTrace(); } if (fileData != null) { try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer widthBuffer = stack.mallocInt(1); IntBuffer heightBuffer = stack.mallocInt(1); IntBuffer compBuffer = stack.mallocInt(1); PointerBuffer delaysBuffer = null; IntBuffer framesBuffer = stack.mallocInt(1); framesBuffer.put(framesCount).flip(); ByteBuffer fileDataBuffer = MemoryUtil.memAlloc(fileData.length); fileDataBuffer.put(fileData).flip(); ByteBuffer imgBuffer = STBImage.stbi_load_gif_from_memory(fileDataBuffer, delaysBuffer, widthBuffer, heightBuffer, framesBuffer, compBuffer, 4); image.width = widthBuffer.get(); image.height = heightBuffer.get(); image.mipmaps = 1; image.format = RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; if (imgBuffer != null) { byte[] bytes = new byte[imgBuffer.capacity()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = imgBuffer.get(); } image.setData(bytes); } fileData = null; } } } } else{ image = LoadImage(fileName); } // TODO: Support APNG animated images? frames = framesCount; return image; }
public Image LoadImageAnim(String fileName, int frames) { Image image = new Image(); int framesCount = 1; if (SUPPORT_FILEFORMAT_GIF) { if (rCore.IsFileExtension(fileName, ".gif")) { byte[] fileData = null; try{ BufferedImage tmpImg = ImageIO.read(new File(fileName)); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(tmpImg, rCore.GetFileExtension(fileName).substring(1), os); fileData = os.toByteArray(); } catch (IOException exception) { exception.printStackTrace(); } if (fileData != null) { try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer widthBuffer = stack.mallocInt(1); IntBuffer heightBuffer = stack.mallocInt(1); IntBuffer compBuffer = stack.mallocInt(1); PointerBuffer delaysBuffer = null; IntBuffer framesBuffer = stack.mallocInt(1); framesBuffer.put(framesCount).flip(); ByteBuffer fileDataBuffer = MemoryUtil.memAlloc(fileData.length); fileDataBuffer.put(fileData).flip(); ByteBuffer imgBuffer = STBImage.stbi_load_gif_from_memory(fileDataBuffer, delaysBuffer, widthBuffer, heightBuffer, framesBuffer, compBuffer, 4); image.width = widthBuffer.get(); image.height = heightBuffer.get(); image.mipmaps = 1; image.format = RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; if (imgBuffer != null) { byte[] bytes = new byte[imgBuffer.capacity()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = imgBuffer.get(); } image.setData(bytes); } fileData = null; } } } } else{ image = LoadImage(fileName); } frames = framesCount; return image; }
public image loadimageanim(string filename, int frames) { image image = new image(); int framescount = 1; if (support_fileformat_gif) { if (rcore.isfileextension(filename, ".gif")) { byte[] filedata = null; try{ bufferedimage tmpimg = imageio.read(new file(filename)); bytearrayoutputstream os = new bytearrayoutputstream(); imageio.write(tmpimg, rcore.getfileextension(filename).substring(1), os); filedata = os.tobytearray(); } catch (ioexception exception) { exception.printstacktrace(); } if (filedata != null) { try (memorystack stack = memorystack.stackpush()) { intbuffer widthbuffer = stack.mallocint(1); intbuffer heightbuffer = stack.mallocint(1); intbuffer compbuffer = stack.mallocint(1); pointerbuffer delaysbuffer = null; intbuffer framesbuffer = stack.mallocint(1); framesbuffer.put(framescount).flip(); bytebuffer filedatabuffer = memoryutil.memalloc(filedata.length); filedatabuffer.put(filedata).flip(); bytebuffer imgbuffer = stbimage.stbi_load_gif_from_memory(filedatabuffer, delaysbuffer, widthbuffer, heightbuffer, framesbuffer, compbuffer, 4); image.width = widthbuffer.get(); image.height = heightbuffer.get(); image.mipmaps = 1; image.format = rl_pixelformat_uncompressed_r8g8b8a8; if (imgbuffer != null) { byte[] bytes = new byte[imgbuffer.capacity()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = imgbuffer.get(); } image.setdata(bytes); } filedata = null; } } } } else{ image = loadimage(filename); } frames = framescount; return image; }
CreedVI/Raylib-J
[ 0, 1, 0, 0 ]
7,893
public static GetEntityResponse<EventInfo> toEvent( final IcalCallback cb, final BwCalendar cal, final Icalendar ical, final Component val, final boolean mergeAttendees) { final var resp = new GetEntityResponse<EventInfo>(); if (val == null) { return Response.notOk(resp, failed, "No component supplied"); } String currentPrincipal = null; final BwPrincipal principal = cb.getPrincipal(); if (principal != null) { currentPrincipal = principal.getPrincipalRef(); } final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE); final int methodType = ical.getMethodType(); String attUri = null; if (mergeAttendees) { // We'll need this later. attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef()); } final String colPath; if (cal == null) { colPath = null; } else { colPath = cal.getPath(); } try { final PropertyList<Property> pl = val.getProperties(); boolean vpoll = false; boolean event = false; boolean task = false; if (pl == null) { // Empty component return Response.notOk(resp, failed, "Empty component"); } final int entityType; if (val instanceof VEvent) { entityType = IcalDefs.entityTypeEvent; event = true; } else if (val instanceof VToDo) { entityType = IcalDefs.entityTypeTodo; task = true; } else if (val instanceof VJournal) { entityType = IcalDefs.entityTypeJournal; } else if (val instanceof VFreeBusy) { entityType = IcalDefs.entityTypeFreeAndBusy; } else if (val instanceof VAvailability) { entityType = IcalDefs.entityTypeVavailability; } else if (val instanceof Available) { entityType = IcalDefs.entityTypeAvailable; } else if (val instanceof VPoll) { entityType = IcalDefs.entityTypeVpoll; vpoll = true; } else { return Response.error(resp, "org.bedework.invalid.component.type: " + val.getName()); } // Get the guid from the component String guid = null; final Uid uidp = pl.getProperty(Property.UID); if (uidp != null) { testXparams(uidp, hasXparams); guid = uidp.getValue(); } if (guid == null) { /* XXX A guid is required - but are there devices out there without a * guid - and if so how do we handle it? */ return Response.notOk(resp, failed, CalFacadeException.noGuid); } /* See if we have a recurrence id */ BwDateTime ridObj = null; String rid = null; TimeZone ridTz = null; final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID); if (ridp != null) { testXparams(ridp, hasXparams); ridObj = BwDateTime.makeBwDateTime(ridp); if (ridObj.getRange() != null) { /* XXX What do I do with it? */ logger.warn("TRANS-TO_EVENT: Got a recurrence id range"); } rid = ridObj.getDate(); } EventInfo masterEI = null; EventInfo evinfo = null; final BwEvent ev; /* If we have a recurrence id see if we already have the master (we should * get a master + all its overrides). * * If so find the override and use the annnotation or if no override, * make one. * * If no override retrieve the event, add it to our table and then locate the * annotation. * * If there is no annotation, create one. * * It's possible we have been sent 'detached' instances of a recurring * event. This may happen if we are invited to one or more instances of a * meeting. In this case we try to retrieve the master and if it doesn't * exist we manufacture one. We consider such an instance an update to * that instance only and leave the others alone. */ /* We need this in a couple of places */ final DtStart dtStart = pl.getProperty(Property.DTSTART); /* if (rid != null) { // See if we have a new master event. If so create a proxy to that event. masterEI = findMaster(guid, ical.getComponents()); if (masterEI == null) { masterEI = makeNewEvent(cb, chg, entityType, guid, cal); BwEvent e = masterEI.getEvent(); // XXX This seems bogus DtStart mdtStart; String bogusDate = "19980118T230000"; if (dtStart.isUtc()) { mdtStart = new DtStart(bogusDate + "Z"); } else if (dtStart.getTimeZone() == null) { mdtStart = new DtStart(bogusDate); } else { mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone()); } setDates(e, mdtStart, null, null, chg); e.setRecurring(true); e.addRdate(ridObj); e.setSuppressed(true); ical.addComponent(masterEI); } if (masterEI != null) { evinfo = masterEI.findOverride(rid); } } */ /* If this is a recurrence instance see if we can find the master We only need this because the master may follow the overrides. */ if (rid != null) { // See if we have a new master event. If so create a proxy to this event. masterEI = findMaster(guid, ical.getComponents()); if (masterEI != null) { evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; } } if ((evinfo == null) && (cal != null) && (cal.getCalType() != BwCalendar.calTypeInbox) && (cal.getCalType() != BwCalendar.calTypePendingInbox) && (cal.getCalType() != BwCalendar.calTypeOutbox)) { if (logger.debug()) { logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid); } final GetEntitiesResponse<EventInfo> eisResp = cb.getEvent(colPath, guid); if (eisResp.isError()) { return Response.fromResponse(resp, eisResp); } final var eis = eisResp.getEntities(); if (!Util.isEmpty(eis)) { if (eis.size() > 1) { // DORECUR - wrong again return Response.notOk(resp, failed, "More than one event returned for guid."); } evinfo = eis.iterator().next(); } if (logger.debug()) { if (evinfo != null) { logger.debug("TRANS-TO_EVENT: fetched event with guid"); } else { logger.debug("TRANS-TO_EVENT: did not find event with guid"); } } if (evinfo != null) { if (rid != null) { // We just retrieved it's master masterEI = evinfo; masterEI.setInstanceOnly(true); evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; ical.addComponent(masterEI); } else if (methodType == ScheduleMethods.methodTypeCancel) { // This should never have an rid for cancel of entire event. evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed()); } else { // Presumably sent an update for the entire event. No longer suppressed master evinfo.getEvent().setSuppressed(false); } } else if (rid != null) { /* Manufacture a master for the instance */ masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath); final BwEvent e = masterEI.getEvent(); // XXX This seems bogus final DtStart mdtStart; final String bogusDate = "19980118"; final String bogusTime = "T230000"; // Base dtstart on the recurrence id. final boolean isDateType = ridObj.getDateType(); if (isDateType) { mdtStart = new DtStart(new Date(bogusDate)); } else if (dtStart.isUtc()) { mdtStart = new DtStart(bogusDate + bogusTime + "Z"); } else if (ridObj.getTzid() == null) { mdtStart = new DtStart(bogusDate + bogusTime); } else { mdtStart = new DtStart(bogusDate + bogusTime, Timezones.getTz(ridObj.getTzid())); } IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(), masterEI, mdtStart, null, null); e.setRecurring(true); // e.addRdate(ridObj); final var sum = (Summary)pl.getProperty(Property.SUMMARY); e.setSummary(sum.getValue()); e.setSuppressed(true); ical.addComponent(masterEI); evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; masterEI.setInstanceOnly(rid != null); } } if (evinfo == null) { evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath); } else if (evinfo.getEvent().getEntityType() != entityType) { return Response.notOk(resp, failed, "org.bedework.mismatched.entity.type: " + val); } final ChangeTable chg = evinfo.getChangeset( cb.getPrincipal().getPrincipalRef()); if (rid != null) { final String evrid = evinfo.getEvent().getRecurrenceId(); if ((evrid == null) || (!evrid.equals(rid))) { logger. warn("Mismatched rid ev=" + evrid + " expected " + rid); chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious??? } if (masterEI.getEvent().getSuppressed()) { masterEI.getEvent().addRdate(ridObj); } } ev = evinfo.getEvent(); ev.setScheduleMethod(methodType); DtEnd dtEnd = null; if (entityType == IcalDefs.entityTypeTodo) { final Due due = pl.getProperty(Property.DUE); if (due != null ) { dtEnd = new DtEnd(due.getParameters(), due.getValue()); } } else { dtEnd = pl.getProperty(Property.DTEND); } final Duration duration = pl.getProperty(Property.DURATION); IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(), evinfo, dtStart, dtEnd, duration); for (final Property prop: pl) { testXparams(prop, hasXparams); //debug("ical prop " + prop.getClass().getName()); String pval = prop.getValue(); if ((pval != null) && (pval.length() == 0)) { pval = null; } final PropertyInfoIndex pi; if (prop instanceof XProperty) { pi = PropertyInfoIndex.XPROP; } else { pi = PropertyInfoIndex.fromName(prop.getName()); } if (pi == null) { logger.debug("Unknown property with name " + prop.getName() + " class " + prop.getClass() + " and value " + pval); continue; } chg.present(pi); switch (pi) { case ACCEPT_RESPONSE: /* ------------------- Accept Response -------------------- */ String sval = prop.getValue(); if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) { ev.setPollAcceptResponse(sval); } break; case ATTACH: /* ------------------- Attachment -------------------- */ chg.addValue(pi, IcalUtil.getAttachment((Attach)prop)); break; case ATTENDEE: /* ------------------- Attendee -------------------- */ if (methodType == ScheduleMethods.methodTypePublish) { if (cb.getStrictness() == IcalCallback.conformanceStrict) { return Response.notOk(resp, failed, CalFacadeException.attendeesInPublish); } //if (cb.getStrictness() == IcalCallback.conformanceWarn) { // warn("Had attendees for PUBLISH"); //} } final Attendee attPr = (Attendee)prop; if (evinfo.getNewEvent() || !mergeAttendees) { chg.addValue(pi, IcalUtil.getAttendee(cb, attPr)); } else { final String pUri = cb.getCaladdr(attPr.getValue()); if (pUri.equals(attUri)) { /* Only update for our own attendee * We're doing a PUT and this must be the attendee updating their * partstat. We don't allow them to change other attendees * whatever the PUT content says. */ chg.addValue(pi, IcalUtil.getAttendee(cb, attPr)); } else { // Use the value we currently have boolean found = false; for (final BwAttendee att: ev.getAttendees()) { if (pUri.equals(att.getAttendeeUri())) { chg.addValue(pi, att.clone()); found = true; break; } } if (!found) { // An added attendee final BwAttendee att = IcalUtil .getAttendee(cb, attPr); att.setPartstat(IcalDefs.partstatValNeedsAction); chg.addValue(pi, att); } } } break; case BUSYTYPE: final int ibt = BwEvent.fromBusyTypeString(pval); if (chg.changed(pi, ev.getBusyType(), ibt)) { ev.setBusyType(ibt); } break; case CATEGORIES: /* ------------------- Categories -------------------- */ final Categories cats = (Categories)prop; final TextList cl = cats.getCategories(); String lang = IcalUtil.getLang(cats); if (cl != null) { /* Got some categories */ for (final String wd: cl) { if (wd == null) { continue; } final BwString key = new BwString(lang, wd); final var fcResp = cb.findCategory(key); final BwCategory cat; if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isNotFound()) { cat = BwCategory.makeCategory(); cat.setWord(key); cb.addCategory(cat); } else { cat = fcResp.getEntity(); } chg.addValue(pi, cat); } } break; case CLASS: /* ------------------- Class -------------------- */ if (chg.changed(pi, ev.getClassification(), pval)) { ev.setClassification(pval); } break; case COMMENT: /* ------------------- Comment -------------------- */ chg.addValue(pi, new BwString(null, pval)); break; case COMPLETED: /* ------------------- Completed -------------------- */ if (chg.changed(pi, ev.getCompleted(), pval)) { ev.setCompleted(pval); } break; case CONCEPT: /* ------------------- Concept -------------------- */ final Concept c = (Concept)prop; final String cval = c.getValue(); if (cval != null) { /* Got a concept */ chg.addValue(PropertyInfoIndex.XPROP, BwXproperty.makeIcalProperty("CONCEPT", null, cval)); } break; case CONTACT: /* ------------------- Contact -------------------- */ final String altrep = getAltRepPar(prop); lang = IcalUtil.getLang(prop); final String uid = getUidPar(prop); final BwString nm = new BwString(lang, pval); BwContact contact = null; if (uid != null) { final var fcResp = cb.getContact(uid); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { contact = fcResp.getEntity(); } } if (contact == null) { final var fcResp = cb.findContact(nm); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { contact = fcResp.getEntity(); } } if (contact == null) { contact = BwContact.makeContact(); contact.setCn(nm); contact.setLink(altrep); cb.addContact(contact); } else { contact.setCn(nm); contact.setLink(altrep); } chg.addValue(pi, contact); break; case CREATED: /* ------------------- Created -------------------- */ if (chg.changed(pi, ev.getCreated(), pval)) { ev.setCreated(pval); } break; case DESCRIPTION: /* ------------------- Description -------------------- */ if (chg.changed(pi, ev.getDescription(), pval)) { ev.setDescription(pval); } break; case DTEND: /* ------------------- DtEnd -------------------- */ break; case DTSTAMP: /* ------------------- DtStamp -------------------- */ ev.setDtstamp(pval); break; case DTSTART: /* ------------------- DtStart -------------------- */ break; case DUE: /* -------------------- Due ------------------------ */ break; case DURATION: /* ------------------- Duration -------------------- */ break; case EXDATE: /* ------------------- ExDate -------------------- */ chg.addValues(pi, IcalUtil.makeDateTimes((DateListProperty)prop)); break; case EXRULE: /* ------------------- ExRule -------------------- */ chg.addValue(pi, pval); break; case FREEBUSY: /* ------------------- freebusy -------------------- */ final FreeBusy fbusy = (FreeBusy)prop; final PeriodList perpl = fbusy.getPeriods(); final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE"); final int fbtype; if (par == null) { fbtype = BwFreeBusyComponent.typeBusy; } else if (par.equals(FbType.BUSY)) { fbtype = BwFreeBusyComponent.typeBusy; } else if (par.equals(FbType.BUSY_TENTATIVE)) { fbtype = BwFreeBusyComponent.typeBusyTentative; } else if (par.equals(FbType.BUSY_UNAVAILABLE)) { fbtype = BwFreeBusyComponent.typeBusyUnavailable; } else if (par.equals(FbType.FREE)) { fbtype = BwFreeBusyComponent.typeFree; } else { if (logger.debug()) { logger.debug("Unsupported parameter " + par.getName()); } return Response.notOk(resp, failed, "Unsupported parameter " + par.getName()); } final BwFreeBusyComponent fbc = new BwFreeBusyComponent(); fbc.setType(fbtype); for (final Period per : perpl) { fbc.addPeriod(per); } ev.addFreeBusyPeriod(fbc); break; case GEO: /* ------------------- Geo -------------------- */ final Geo g = (Geo)prop; final BwGeo geo = new BwGeo(g.getLatitude(), g.getLongitude()); if (chg.changed(pi, ev.getGeo(), geo)) { ev.setGeo(geo); } break; case LAST_MODIFIED: /* ------------------- LastModified -------------------- */ if (chg.changed(pi, ev.getLastmod(), pval)) { ev.setLastmod(pval); } break; case LOCATION: /* ------------------- Location -------------------- */ BwLocation loc = null; //String uid = getUidPar(prop); /* At the moment Mozilla lightning is broken and this leads to all * sorts of problems. if (uid != null) { loc = cb.getLocation(uid); } */ lang = IcalUtil.getLang(prop); BwString addr = null; if (pval != null) { if (loc == null) { addr = new BwString(lang, pval); final var fcResp = cb.findLocation(addr); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { loc = fcResp.getEntity(); } } if (loc == null) { loc = BwLocation.makeLocation(); loc.setAddress(addr); cb.addLocation(loc); } } final BwLocation evloc = ev.getLocation(); if (chg.changed(pi, evloc, loc)) { // CHGTBL - this only shows that it's a different location object ev.setLocation(loc); } else if ((loc != null) && (evloc != null)) { // See if the value is changed final String evval = evloc.getAddress().getValue(); final String inval = loc.getAddress().getValue(); if (!evval.equals(inval)) { chg.changed(pi, evval, inval); evloc.getAddress().setValue(inval); } } break; case ORGANIZER: /* ------------------- Organizer -------------------- */ final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop); final BwOrganizer evorg = ev.getOrganizer(); final BwOrganizer evorgCopy; if (evorg == null) { evorgCopy = null; } else { evorgCopy = (BwOrganizer)evorg.clone(); } if (chg.changed(pi, evorgCopy, org)) { if (evorg == null) { ev.setOrganizer(org); } else { evorg.update(org); } } break; case PERCENT_COMPLETE: /* ------------------- PercentComplete -------------------- */ Integer ival = ((PercentComplete)prop).getPercentage(); if (chg.changed(pi, ev.getPercentComplete(), ival)) { ev.setPercentComplete(ival); } break; case POLL_MODE: /* ------------------- Poll mode -------------------- */ sval = prop.getValue(); if (chg.changed(pi, ev.getPollMode(), sval)) { ev.setPollMode(sval); } break; case POLL_PROPERTIES: /* ------------------- Poll properties ---------------- */ sval = prop.getValue(); if (chg.changed(pi, ev.getPollProperties(), sval)) { ev.setPollProperties(sval); } break; case POLL_WINNER: /* ------------------- Poll winner -------------------- */ ival = ((PollWinner)prop).getPollwinner(); if (chg.changed(pi, ev.getPollWinner(), ival)) { ev.setPollWinner(ival); } break; case PRIORITY: /* ------------------- Priority -------------------- */ ival = ((Priority)prop).getLevel(); if (chg.changed(pi, ev.getPriority(), ival)) { ev.setPriority(ival); } break; case RDATE: /* ------------------- RDate -------------------- */ chg.addValues(pi, IcalUtil.makeDateTimes((DateListProperty)prop)); break; case RECURRENCE_ID: /* ------------------- RecurrenceID -------------------- */ // Done above break; case RELATED_TO: /* ------------------- RelatedTo -------------------- */ final RelatedTo irelto = (RelatedTo)prop; final BwRelatedTo relto = new BwRelatedTo(); final String parval = IcalUtil.getParameterVal(irelto, "RELTYPE"); if (parval != null) { relto.setRelType(parval); } relto.setValue(irelto.getValue()); if (chg.changed(pi, ev.getRelatedTo(), relto)) { ev.setRelatedTo(relto); } break; case REQUEST_STATUS: /* ------------------- RequestStatus -------------------- */ final BwRequestStatus rs = BwRequestStatus .fromRequestStatus((RequestStatus)prop); chg.addValue(pi, rs); break; case RESOURCES: /* ------------------- Resources -------------------- */ final TextList rl = ((Resources)prop).getResources(); if (rl != null) { /* Got some resources */ lang = IcalUtil.getLang(prop); for (final String s: rl) { final BwString rsrc = new BwString(lang, s); chg.addValue(pi, rsrc); } } break; case RRULE: /* ------------------- RRule -------------------- */ chg.addValue(pi, pval); break; case SEQUENCE: /* ------------------- Sequence -------------------- */ final int seq = ((Sequence)prop).getSequenceNo(); if (seq != ev.getSequence()) { chg.changed(pi, ev.getSequence(), seq); ev.setSequence(seq); } break; case STATUS: /* ------------------- Status -------------------- */ if (chg.changed(pi, ev.getStatus(), pval)) { ev.setStatus(pval); } break; case SUMMARY: /* ------------------- Summary -------------------- */ if (chg.changed(pi, ev.getSummary(), pval)) { ev.setSummary(pval); } break; case TRANSP: /* ------------------- Transp -------------------- */ if (chg.changed(pi, ev.getPeruserTransparency( cb.getPrincipal() .getPrincipalRef()), pval)) { final BwXproperty pu = ev.setPeruserTransparency( cb.getPrincipal().getPrincipalRef(), pval); if (pu != null) { chg.addValue(PropertyInfoIndex.XPROP, pu); } } break; case UID: /* ------------------- Uid -------------------- */ /* We did this above */ break; case URL: /* ------------------- Url -------------------- */ if (chg.changed(pi, ev.getLink(), pval)) { ev.setLink(pval); } break; case XPROP: /* ------------------------- x-property --------------------------- */ final String name = prop.getName(); if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) { if (chg.changed(PropertyInfoIndex.COST, ev.getCost(), pval)) { ev.setCost(pval); } break; } if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) { if (checkCategory(cb, chg, ev, null, pval)) { break; } } if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) { if (checkLocation(cb, chg, ev, prop)) { break; } } if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) { if (checkContact(cb, chg, ev, null, pval)) { break; } } /* See if this is an x-category that can be converted to a real category */ final XProperty xp = (XProperty)prop; chg.addValue(PropertyInfoIndex.XPROP, new BwXproperty(name, xp.getParameters() .toString(), pval)); break; default: if (logger.debug()) { logger.debug("Unsupported property with index " + pi + "; class " + prop.getClass() + " and value " + pval); } } } /* =================== Process sub-components =============== */ final ComponentList<Component> subComps; if (val instanceof ComponentContainer) { subComps = ((ComponentContainer<Component>)val).getComponents(); } else { subComps = null; } final Set<Integer> pids; if (vpoll) { pids = new TreeSet<>(); final BwEvent vp = evinfo.getEvent(); if (!Util.isEmpty(vp.getPollItems())) { vp.clearPollItems(); } } else { pids = null; } if (!Util.isEmpty(subComps)) { for (final var subComp: subComps) { if (subComp instanceof Available) { if (!(val instanceof VAvailability)) { return Response.error(resp, "AVAILABLE only valid in VAVAILABLE"); } final var avlResp = processAvailable(cb, cal, ical, (VAvailability)val, (Available)subComp, evinfo); if (!avlResp.isOk()) { return Response.fromResponse(resp, avlResp); } continue; } if (subComp instanceof Participant) { if (vpoll) { final var vresp = processVoter(cb, (VPoll)val, (Participant)subComp, evinfo, chg, mergeAttendees); if (!vresp.isOk()) { return Response.fromResponse(resp, vresp); } continue; } logger.warn("Unimplemented Participant object"); continue; } if (subComp instanceof VResource) { logger.warn("Unimplemented VResource object"); continue; } if (subComp instanceof VLocation) { logger.warn("Unimplemented VLocation object"); continue; } if (subComp instanceof VAlarm) { final var aresp = VAlarmUtil.processAlarm(cb, val, (VAlarm)subComp, ev, currentPrincipal, chg); if (!aresp.isOk()) { return Response.fromResponse(resp, aresp); } continue; } if (vpoll && (event || task)) { final var vresp = processCandidate((VPoll)val, subComp, evinfo, pids, chg); if (!vresp.isOk()) { return Response.fromResponse(resp, vresp); } continue; } logger.warn("Unimplemented Component object: " + subComp); } } /* Fix up timestamps. */ if (ev.getCreated() == null) { if (ev.getLastmod() != null) { ev.setCreated(ev.getLastmod()); chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated()); } else { ev.updateDtstamp(); chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated()); chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod()); } } if (ev.getLastmod() == null) { // created cannot be null now ev.setLastmod(ev.getCreated()); chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod()); } processTimezones(ev, ical, chg); /* Remove any recipients and originator */ if (ev.getRecipients() != null) { ev.getRecipients().clear(); } ev.setOriginator(null); if (hasXparams.value) { /* Save a text copy of the entire event as an x-property */ final Component valCopy = val.copy(); /* Remove potentially large values */ final Description desp = valCopy.getProperty(Property.DESCRIPTION); if (desp != null) { desp.setValue(null); } final Attach attachp = valCopy.getProperty(Property.ATTACH); // Don't store the entire attachment - we just need the parameters. if (attachp != null) { final Value v = attachp.getParameter(Parameter.VALUE); if (v != null) { attachp.setValue(String.valueOf(attachp.getValue().hashCode())); } } chg.addValue(PropertyInfoIndex.XPROP, new BwXproperty(BwXproperty.bedeworkIcal, null, valCopy.toString())); } chg.processChanges(ev, true, false); ev.setRecurring(ev.isRecurringEntity()); if (logger.debug()) { logger.debug(chg.toString()); logger.debug(ev.toString()); } if (masterEI != null) { // Just return notfound as this event is on its override list return Response.notFound(resp); } resp.setEntity(evinfo); return resp; } catch (final Throwable t) { if (logger.debug()) { logger.error(t); } return Response.error(resp, t); } }
public static GetEntityResponse<EventInfo> toEvent( final IcalCallback cb, final BwCalendar cal, final Icalendar ical, final Component val, final boolean mergeAttendees) { final var resp = new GetEntityResponse<EventInfo>(); if (val == null) { return Response.notOk(resp, failed, "No component supplied"); } String currentPrincipal = null; final BwPrincipal principal = cb.getPrincipal(); if (principal != null) { currentPrincipal = principal.getPrincipalRef(); } final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE); final int methodType = ical.getMethodType(); String attUri = null; if (mergeAttendees) { attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef()); } final String colPath; if (cal == null) { colPath = null; } else { colPath = cal.getPath(); } try { final PropertyList<Property> pl = val.getProperties(); boolean vpoll = false; boolean event = false; boolean task = false; if (pl == null) { return Response.notOk(resp, failed, "Empty component"); } final int entityType; if (val instanceof VEvent) { entityType = IcalDefs.entityTypeEvent; event = true; } else if (val instanceof VToDo) { entityType = IcalDefs.entityTypeTodo; task = true; } else if (val instanceof VJournal) { entityType = IcalDefs.entityTypeJournal; } else if (val instanceof VFreeBusy) { entityType = IcalDefs.entityTypeFreeAndBusy; } else if (val instanceof VAvailability) { entityType = IcalDefs.entityTypeVavailability; } else if (val instanceof Available) { entityType = IcalDefs.entityTypeAvailable; } else if (val instanceof VPoll) { entityType = IcalDefs.entityTypeVpoll; vpoll = true; } else { return Response.error(resp, "org.bedework.invalid.component.type: " + val.getName()); } String guid = null; final Uid uidp = pl.getProperty(Property.UID); if (uidp != null) { testXparams(uidp, hasXparams); guid = uidp.getValue(); } if (guid == null) { return Response.notOk(resp, failed, CalFacadeException.noGuid); } BwDateTime ridObj = null; String rid = null; TimeZone ridTz = null; final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID); if (ridp != null) { testXparams(ridp, hasXparams); ridObj = BwDateTime.makeBwDateTime(ridp); if (ridObj.getRange() != null) { logger.warn("TRANS-TO_EVENT: Got a recurrence id range"); } rid = ridObj.getDate(); } EventInfo masterEI = null; EventInfo evinfo = null; final BwEvent ev; final DtStart dtStart = pl.getProperty(Property.DTSTART); if (rid != null) { masterEI = findMaster(guid, ical.getComponents()); if (masterEI != null) { evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; } } if ((evinfo == null) && (cal != null) && (cal.getCalType() != BwCalendar.calTypeInbox) && (cal.getCalType() != BwCalendar.calTypePendingInbox) && (cal.getCalType() != BwCalendar.calTypeOutbox)) { if (logger.debug()) { logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid); } final GetEntitiesResponse<EventInfo> eisResp = cb.getEvent(colPath, guid); if (eisResp.isError()) { return Response.fromResponse(resp, eisResp); } final var eis = eisResp.getEntities(); if (!Util.isEmpty(eis)) { if (eis.size() > 1) { return Response.notOk(resp, failed, "More than one event returned for guid."); } evinfo = eis.iterator().next(); } if (logger.debug()) { if (evinfo != null) { logger.debug("TRANS-TO_EVENT: fetched event with guid"); } else { logger.debug("TRANS-TO_EVENT: did not find event with guid"); } } if (evinfo != null) { if (rid != null) { masterEI = evinfo; masterEI.setInstanceOnly(true); evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; ical.addComponent(masterEI); } else if (methodType == ScheduleMethods.methodTypeCancel) { evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed()); } else { evinfo.getEvent().setSuppressed(false); } } else if (rid != null) { masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath); final BwEvent e = masterEI.getEvent(); final DtStart mdtStart; final String bogusDate = "19980118"; final String bogusTime = "T230000"; final boolean isDateType = ridObj.getDateType(); if (isDateType) { mdtStart = new DtStart(new Date(bogusDate)); } else if (dtStart.isUtc()) { mdtStart = new DtStart(bogusDate + bogusTime + "Z"); } else if (ridObj.getTzid() == null) { mdtStart = new DtStart(bogusDate + bogusTime); } else { mdtStart = new DtStart(bogusDate + bogusTime, Timezones.getTz(ridObj.getTzid())); } IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(), masterEI, mdtStart, null, null); e.setRecurring(true); final var sum = (Summary)pl.getProperty(Property.SUMMARY); e.setSummary(sum.getValue()); e.setSuppressed(true); ical.addComponent(masterEI); evinfo = masterEI.findOverride(rid); evinfo.recurrenceSeen = true; masterEI.setInstanceOnly(rid != null); } } if (evinfo == null) { evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath); } else if (evinfo.getEvent().getEntityType() != entityType) { return Response.notOk(resp, failed, "org.bedework.mismatched.entity.type: " + val); } final ChangeTable chg = evinfo.getChangeset( cb.getPrincipal().getPrincipalRef()); if (rid != null) { final String evrid = evinfo.getEvent().getRecurrenceId(); if ((evrid == null) || (!evrid.equals(rid))) { logger. warn("Mismatched rid ev=" + evrid + " expected " + rid); chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); } if (masterEI.getEvent().getSuppressed()) { masterEI.getEvent().addRdate(ridObj); } } ev = evinfo.getEvent(); ev.setScheduleMethod(methodType); DtEnd dtEnd = null; if (entityType == IcalDefs.entityTypeTodo) { final Due due = pl.getProperty(Property.DUE); if (due != null ) { dtEnd = new DtEnd(due.getParameters(), due.getValue()); } } else { dtEnd = pl.getProperty(Property.DTEND); } final Duration duration = pl.getProperty(Property.DURATION); IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(), evinfo, dtStart, dtEnd, duration); for (final Property prop: pl) { testXparams(prop, hasXparams); String pval = prop.getValue(); if ((pval != null) && (pval.length() == 0)) { pval = null; } final PropertyInfoIndex pi; if (prop instanceof XProperty) { pi = PropertyInfoIndex.XPROP; } else { pi = PropertyInfoIndex.fromName(prop.getName()); } if (pi == null) { logger.debug("Unknown property with name " + prop.getName() + " class " + prop.getClass() + " and value " + pval); continue; } chg.present(pi); switch (pi) { case ACCEPT_RESPONSE: String sval = prop.getValue(); if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) { ev.setPollAcceptResponse(sval); } break; case ATTACH: chg.addValue(pi, IcalUtil.getAttachment((Attach)prop)); break; case ATTENDEE: if (methodType == ScheduleMethods.methodTypePublish) { if (cb.getStrictness() == IcalCallback.conformanceStrict) { return Response.notOk(resp, failed, CalFacadeException.attendeesInPublish); } } final Attendee attPr = (Attendee)prop; if (evinfo.getNewEvent() || !mergeAttendees) { chg.addValue(pi, IcalUtil.getAttendee(cb, attPr)); } else { final String pUri = cb.getCaladdr(attPr.getValue()); if (pUri.equals(attUri)) { chg.addValue(pi, IcalUtil.getAttendee(cb, attPr)); } else { boolean found = false; for (final BwAttendee att: ev.getAttendees()) { if (pUri.equals(att.getAttendeeUri())) { chg.addValue(pi, att.clone()); found = true; break; } } if (!found) { final BwAttendee att = IcalUtil .getAttendee(cb, attPr); att.setPartstat(IcalDefs.partstatValNeedsAction); chg.addValue(pi, att); } } } break; case BUSYTYPE: final int ibt = BwEvent.fromBusyTypeString(pval); if (chg.changed(pi, ev.getBusyType(), ibt)) { ev.setBusyType(ibt); } break; case CATEGORIES: final Categories cats = (Categories)prop; final TextList cl = cats.getCategories(); String lang = IcalUtil.getLang(cats); if (cl != null) { for (final String wd: cl) { if (wd == null) { continue; } final BwString key = new BwString(lang, wd); final var fcResp = cb.findCategory(key); final BwCategory cat; if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isNotFound()) { cat = BwCategory.makeCategory(); cat.setWord(key); cb.addCategory(cat); } else { cat = fcResp.getEntity(); } chg.addValue(pi, cat); } } break; case CLASS: if (chg.changed(pi, ev.getClassification(), pval)) { ev.setClassification(pval); } break; case COMMENT: chg.addValue(pi, new BwString(null, pval)); break; case COMPLETED: if (chg.changed(pi, ev.getCompleted(), pval)) { ev.setCompleted(pval); } break; case CONCEPT: final Concept c = (Concept)prop; final String cval = c.getValue(); if (cval != null) { chg.addValue(PropertyInfoIndex.XPROP, BwXproperty.makeIcalProperty("CONCEPT", null, cval)); } break; case CONTACT: final String altrep = getAltRepPar(prop); lang = IcalUtil.getLang(prop); final String uid = getUidPar(prop); final BwString nm = new BwString(lang, pval); BwContact contact = null; if (uid != null) { final var fcResp = cb.getContact(uid); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { contact = fcResp.getEntity(); } } if (contact == null) { final var fcResp = cb.findContact(nm); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { contact = fcResp.getEntity(); } } if (contact == null) { contact = BwContact.makeContact(); contact.setCn(nm); contact.setLink(altrep); cb.addContact(contact); } else { contact.setCn(nm); contact.setLink(altrep); } chg.addValue(pi, contact); break; case CREATED: if (chg.changed(pi, ev.getCreated(), pval)) { ev.setCreated(pval); } break; case DESCRIPTION: if (chg.changed(pi, ev.getDescription(), pval)) { ev.setDescription(pval); } break; case DTEND: break; case DTSTAMP: ev.setDtstamp(pval); break; case DTSTART: break; case DUE: break; case DURATION: break; case EXDATE: chg.addValues(pi, IcalUtil.makeDateTimes((DateListProperty)prop)); break; case EXRULE: chg.addValue(pi, pval); break; case FREEBUSY: final FreeBusy fbusy = (FreeBusy)prop; final PeriodList perpl = fbusy.getPeriods(); final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE"); final int fbtype; if (par == null) { fbtype = BwFreeBusyComponent.typeBusy; } else if (par.equals(FbType.BUSY)) { fbtype = BwFreeBusyComponent.typeBusy; } else if (par.equals(FbType.BUSY_TENTATIVE)) { fbtype = BwFreeBusyComponent.typeBusyTentative; } else if (par.equals(FbType.BUSY_UNAVAILABLE)) { fbtype = BwFreeBusyComponent.typeBusyUnavailable; } else if (par.equals(FbType.FREE)) { fbtype = BwFreeBusyComponent.typeFree; } else { if (logger.debug()) { logger.debug("Unsupported parameter " + par.getName()); } return Response.notOk(resp, failed, "Unsupported parameter " + par.getName()); } final BwFreeBusyComponent fbc = new BwFreeBusyComponent(); fbc.setType(fbtype); for (final Period per : perpl) { fbc.addPeriod(per); } ev.addFreeBusyPeriod(fbc); break; case GEO: final Geo g = (Geo)prop; final BwGeo geo = new BwGeo(g.getLatitude(), g.getLongitude()); if (chg.changed(pi, ev.getGeo(), geo)) { ev.setGeo(geo); } break; case LAST_MODIFIED: if (chg.changed(pi, ev.getLastmod(), pval)) { ev.setLastmod(pval); } break; case LOCATION: BwLocation loc = null; lang = IcalUtil.getLang(prop); BwString addr = null; if (pval != null) { if (loc == null) { addr = new BwString(lang, pval); final var fcResp = cb.findLocation(addr); if (fcResp.isError()) { return Response.fromResponse(resp, fcResp); } if (fcResp.isOk()) { loc = fcResp.getEntity(); } } if (loc == null) { loc = BwLocation.makeLocation(); loc.setAddress(addr); cb.addLocation(loc); } } final BwLocation evloc = ev.getLocation(); if (chg.changed(pi, evloc, loc)) { ev.setLocation(loc); } else if ((loc != null) && (evloc != null)) { final String evval = evloc.getAddress().getValue(); final String inval = loc.getAddress().getValue(); if (!evval.equals(inval)) { chg.changed(pi, evval, inval); evloc.getAddress().setValue(inval); } } break; case ORGANIZER: final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop); final BwOrganizer evorg = ev.getOrganizer(); final BwOrganizer evorgCopy; if (evorg == null) { evorgCopy = null; } else { evorgCopy = (BwOrganizer)evorg.clone(); } if (chg.changed(pi, evorgCopy, org)) { if (evorg == null) { ev.setOrganizer(org); } else { evorg.update(org); } } break; case PERCENT_COMPLETE: Integer ival = ((PercentComplete)prop).getPercentage(); if (chg.changed(pi, ev.getPercentComplete(), ival)) { ev.setPercentComplete(ival); } break; case POLL_MODE: sval = prop.getValue(); if (chg.changed(pi, ev.getPollMode(), sval)) { ev.setPollMode(sval); } break; case POLL_PROPERTIES: sval = prop.getValue(); if (chg.changed(pi, ev.getPollProperties(), sval)) { ev.setPollProperties(sval); } break; case POLL_WINNER: ival = ((PollWinner)prop).getPollwinner(); if (chg.changed(pi, ev.getPollWinner(), ival)) { ev.setPollWinner(ival); } break; case PRIORITY: ival = ((Priority)prop).getLevel(); if (chg.changed(pi, ev.getPriority(), ival)) { ev.setPriority(ival); } break; case RDATE: chg.addValues(pi, IcalUtil.makeDateTimes((DateListProperty)prop)); break; case RECURRENCE_ID: break; case RELATED_TO: final RelatedTo irelto = (RelatedTo)prop; final BwRelatedTo relto = new BwRelatedTo(); final String parval = IcalUtil.getParameterVal(irelto, "RELTYPE"); if (parval != null) { relto.setRelType(parval); } relto.setValue(irelto.getValue()); if (chg.changed(pi, ev.getRelatedTo(), relto)) { ev.setRelatedTo(relto); } break; case REQUEST_STATUS: final BwRequestStatus rs = BwRequestStatus .fromRequestStatus((RequestStatus)prop); chg.addValue(pi, rs); break; case RESOURCES: final TextList rl = ((Resources)prop).getResources(); if (rl != null) { lang = IcalUtil.getLang(prop); for (final String s: rl) { final BwString rsrc = new BwString(lang, s); chg.addValue(pi, rsrc); } } break; case RRULE: chg.addValue(pi, pval); break; case SEQUENCE: final int seq = ((Sequence)prop).getSequenceNo(); if (seq != ev.getSequence()) { chg.changed(pi, ev.getSequence(), seq); ev.setSequence(seq); } break; case STATUS: if (chg.changed(pi, ev.getStatus(), pval)) { ev.setStatus(pval); } break; case SUMMARY: if (chg.changed(pi, ev.getSummary(), pval)) { ev.setSummary(pval); } break; case TRANSP: if (chg.changed(pi, ev.getPeruserTransparency( cb.getPrincipal() .getPrincipalRef()), pval)) { final BwXproperty pu = ev.setPeruserTransparency( cb.getPrincipal().getPrincipalRef(), pval); if (pu != null) { chg.addValue(PropertyInfoIndex.XPROP, pu); } } break; case UID: break; case URL: if (chg.changed(pi, ev.getLink(), pval)) { ev.setLink(pval); } break; case XPROP: final String name = prop.getName(); if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) { if (chg.changed(PropertyInfoIndex.COST, ev.getCost(), pval)) { ev.setCost(pval); } break; } if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) { if (checkCategory(cb, chg, ev, null, pval)) { break; } } if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) { if (checkLocation(cb, chg, ev, prop)) { break; } } if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) { if (checkContact(cb, chg, ev, null, pval)) { break; } } final XProperty xp = (XProperty)prop; chg.addValue(PropertyInfoIndex.XPROP, new BwXproperty(name, xp.getParameters() .toString(), pval)); break; default: if (logger.debug()) { logger.debug("Unsupported property with index " + pi + "; class " + prop.getClass() + " and value " + pval); } } } final ComponentList<Component> subComps; if (val instanceof ComponentContainer) { subComps = ((ComponentContainer<Component>)val).getComponents(); } else { subComps = null; } final Set<Integer> pids; if (vpoll) { pids = new TreeSet<>(); final BwEvent vp = evinfo.getEvent(); if (!Util.isEmpty(vp.getPollItems())) { vp.clearPollItems(); } } else { pids = null; } if (!Util.isEmpty(subComps)) { for (final var subComp: subComps) { if (subComp instanceof Available) { if (!(val instanceof VAvailability)) { return Response.error(resp, "AVAILABLE only valid in VAVAILABLE"); } final var avlResp = processAvailable(cb, cal, ical, (VAvailability)val, (Available)subComp, evinfo); if (!avlResp.isOk()) { return Response.fromResponse(resp, avlResp); } continue; } if (subComp instanceof Participant) { if (vpoll) { final var vresp = processVoter(cb, (VPoll)val, (Participant)subComp, evinfo, chg, mergeAttendees); if (!vresp.isOk()) { return Response.fromResponse(resp, vresp); } continue; } logger.warn("Unimplemented Participant object"); continue; } if (subComp instanceof VResource) { logger.warn("Unimplemented VResource object"); continue; } if (subComp instanceof VLocation) { logger.warn("Unimplemented VLocation object"); continue; } if (subComp instanceof VAlarm) { final var aresp = VAlarmUtil.processAlarm(cb, val, (VAlarm)subComp, ev, currentPrincipal, chg); if (!aresp.isOk()) { return Response.fromResponse(resp, aresp); } continue; } if (vpoll && (event || task)) { final var vresp = processCandidate((VPoll)val, subComp, evinfo, pids, chg); if (!vresp.isOk()) { return Response.fromResponse(resp, vresp); } continue; } logger.warn("Unimplemented Component object: " + subComp); } } if (ev.getCreated() == null) { if (ev.getLastmod() != null) { ev.setCreated(ev.getLastmod()); chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated()); } else { ev.updateDtstamp(); chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated()); chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod()); } } if (ev.getLastmod() == null) { ev.setLastmod(ev.getCreated()); chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod()); } processTimezones(ev, ical, chg); if (ev.getRecipients() != null) { ev.getRecipients().clear(); } ev.setOriginator(null); if (hasXparams.value) { final Component valCopy = val.copy(); final Description desp = valCopy.getProperty(Property.DESCRIPTION); if (desp != null) { desp.setValue(null); } final Attach attachp = valCopy.getProperty(Property.ATTACH); if (attachp != null) { final Value v = attachp.getParameter(Parameter.VALUE); if (v != null) { attachp.setValue(String.valueOf(attachp.getValue().hashCode())); } } chg.addValue(PropertyInfoIndex.XPROP, new BwXproperty(BwXproperty.bedeworkIcal, null, valCopy.toString())); } chg.processChanges(ev, true, false); ev.setRecurring(ev.isRecurringEntity()); if (logger.debug()) { logger.debug(chg.toString()); logger.debug(ev.toString()); } if (masterEI != null) { return Response.notFound(resp); } resp.setEntity(evinfo); return resp; } catch (final Throwable t) { if (logger.debug()) { logger.error(t); } return Response.error(resp, t); } }
public static getentityresponse<eventinfo> toevent( final icalcallback cb, final bwcalendar cal, final icalendar ical, final component val, final boolean mergeattendees) { final var resp = new getentityresponse<eventinfo>(); if (val == null) { return response.notok(resp, failed, "no component supplied"); } string currentprincipal = null; final bwprincipal principal = cb.getprincipal(); if (principal != null) { currentprincipal = principal.getprincipalref(); } final holder<boolean> hasxparams = new holder<>(boolean.false); final int methodtype = ical.getmethodtype(); string atturi = null; if (mergeattendees) { atturi = cb.getcaladdr(cb.getprincipal().getprincipalref()); } final string colpath; if (cal == null) { colpath = null; } else { colpath = cal.getpath(); } try { final propertylist<property> pl = val.getproperties(); boolean vpoll = false; boolean event = false; boolean task = false; if (pl == null) { return response.notok(resp, failed, "empty component"); } final int entitytype; if (val instanceof vevent) { entitytype = icaldefs.entitytypeevent; event = true; } else if (val instanceof vtodo) { entitytype = icaldefs.entitytypetodo; task = true; } else if (val instanceof vjournal) { entitytype = icaldefs.entitytypejournal; } else if (val instanceof vfreebusy) { entitytype = icaldefs.entitytypefreeandbusy; } else if (val instanceof vavailability) { entitytype = icaldefs.entitytypevavailability; } else if (val instanceof available) { entitytype = icaldefs.entitytypeavailable; } else if (val instanceof vpoll) { entitytype = icaldefs.entitytypevpoll; vpoll = true; } else { return response.error(resp, "org.bedework.invalid.component.type: " + val.getname()); } string guid = null; final uid uidp = pl.getproperty(property.uid); if (uidp != null) { testxparams(uidp, hasxparams); guid = uidp.getvalue(); } if (guid == null) { return response.notok(resp, failed, calfacadeexception.noguid); } bwdatetime ridobj = null; string rid = null; timezone ridtz = null; final recurrenceid ridp = pl.getproperty(property.recurrence_id); if (ridp != null) { testxparams(ridp, hasxparams); ridobj = bwdatetime.makebwdatetime(ridp); if (ridobj.getrange() != null) { logger.warn("trans-to_event: got a recurrence id range"); } rid = ridobj.getdate(); } eventinfo masterei = null; eventinfo evinfo = null; final bwevent ev; final dtstart dtstart = pl.getproperty(property.dtstart); if (rid != null) { masterei = findmaster(guid, ical.getcomponents()); if (masterei != null) { evinfo = masterei.findoverride(rid); evinfo.recurrenceseen = true; } } if ((evinfo == null) && (cal != null) && (cal.getcaltype() != bwcalendar.caltypeinbox) && (cal.getcaltype() != bwcalendar.caltypependinginbox) && (cal.getcaltype() != bwcalendar.caltypeoutbox)) { if (logger.debug()) { logger.debug("trans-to_event: try to fetch event with guid=" + guid); } final getentitiesresponse<eventinfo> eisresp = cb.getevent(colpath, guid); if (eisresp.iserror()) { return response.fromresponse(resp, eisresp); } final var eis = eisresp.getentities(); if (!util.isempty(eis)) { if (eis.size() > 1) { return response.notok(resp, failed, "more than one event returned for guid."); } evinfo = eis.iterator().next(); } if (logger.debug()) { if (evinfo != null) { logger.debug("trans-to_event: fetched event with guid"); } else { logger.debug("trans-to_event: did not find event with guid"); } } if (evinfo != null) { if (rid != null) { masterei = evinfo; masterei.setinstanceonly(true); evinfo = masterei.findoverride(rid); evinfo.recurrenceseen = true; ical.addcomponent(masterei); } else if (methodtype == schedulemethods.methodtypecancel) { evinfo.setinstanceonly(evinfo.getevent().getsuppressed()); } else { evinfo.getevent().setsuppressed(false); } } else if (rid != null) { masterei = cnvutil.makenewevent(cb, entitytype, guid, colpath); final bwevent e = masterei.getevent(); final dtstart mdtstart; final string bogusdate = "19980118"; final string bogustime = "t230000"; final boolean isdatetype = ridobj.getdatetype(); if (isdatetype) { mdtstart = new dtstart(new date(bogusdate)); } else if (dtstart.isutc()) { mdtstart = new dtstart(bogusdate + bogustime + "z"); } else if (ridobj.gettzid() == null) { mdtstart = new dtstart(bogusdate + bogustime); } else { mdtstart = new dtstart(bogusdate + bogustime, timezones.gettz(ridobj.gettzid())); } icalutil.setdates(cb.getprincipal().getprincipalref(), masterei, mdtstart, null, null); e.setrecurring(true); final var sum = (summary)pl.getproperty(property.summary); e.setsummary(sum.getvalue()); e.setsuppressed(true); ical.addcomponent(masterei); evinfo = masterei.findoverride(rid); evinfo.recurrenceseen = true; masterei.setinstanceonly(rid != null); } } if (evinfo == null) { evinfo = cnvutil.makenewevent(cb, entitytype, guid, colpath); } else if (evinfo.getevent().getentitytype() != entitytype) { return response.notok(resp, failed, "org.bedework.mismatched.entity.type: " + val); } final changetable chg = evinfo.getchangeset( cb.getprincipal().getprincipalref()); if (rid != null) { final string evrid = evinfo.getevent().getrecurrenceid(); if ((evrid == null) || (!evrid.equals(rid))) { logger. warn("mismatched rid ev=" + evrid + " expected " + rid); chg.changed(propertyinfoindex.recurrence_id, evrid, rid); } if (masterei.getevent().getsuppressed()) { masterei.getevent().addrdate(ridobj); } } ev = evinfo.getevent(); ev.setschedulemethod(methodtype); dtend dtend = null; if (entitytype == icaldefs.entitytypetodo) { final due due = pl.getproperty(property.due); if (due != null ) { dtend = new dtend(due.getparameters(), due.getvalue()); } } else { dtend = pl.getproperty(property.dtend); } final duration duration = pl.getproperty(property.duration); icalutil.setdates(cb.getprincipal().getprincipalref(), evinfo, dtstart, dtend, duration); for (final property prop: pl) { testxparams(prop, hasxparams); string pval = prop.getvalue(); if ((pval != null) && (pval.length() == 0)) { pval = null; } final propertyinfoindex pi; if (prop instanceof xproperty) { pi = propertyinfoindex.xprop; } else { pi = propertyinfoindex.fromname(prop.getname()); } if (pi == null) { logger.debug("unknown property with name " + prop.getname() + " class " + prop.getclass() + " and value " + pval); continue; } chg.present(pi); switch (pi) { case accept_response: string sval = prop.getvalue(); if (chg.changed(pi, ev.getpollacceptresponse(), sval)) { ev.setpollacceptresponse(sval); } break; case attach: chg.addvalue(pi, icalutil.getattachment((attach)prop)); break; case attendee: if (methodtype == schedulemethods.methodtypepublish) { if (cb.getstrictness() == icalcallback.conformancestrict) { return response.notok(resp, failed, calfacadeexception.attendeesinpublish); } } final attendee attpr = (attendee)prop; if (evinfo.getnewevent() || !mergeattendees) { chg.addvalue(pi, icalutil.getattendee(cb, attpr)); } else { final string puri = cb.getcaladdr(attpr.getvalue()); if (puri.equals(atturi)) { chg.addvalue(pi, icalutil.getattendee(cb, attpr)); } else { boolean found = false; for (final bwattendee att: ev.getattendees()) { if (puri.equals(att.getattendeeuri())) { chg.addvalue(pi, att.clone()); found = true; break; } } if (!found) { final bwattendee att = icalutil .getattendee(cb, attpr); att.setpartstat(icaldefs.partstatvalneedsaction); chg.addvalue(pi, att); } } } break; case busytype: final int ibt = bwevent.frombusytypestring(pval); if (chg.changed(pi, ev.getbusytype(), ibt)) { ev.setbusytype(ibt); } break; case categories: final categories cats = (categories)prop; final textlist cl = cats.getcategories(); string lang = icalutil.getlang(cats); if (cl != null) { for (final string wd: cl) { if (wd == null) { continue; } final bwstring key = new bwstring(lang, wd); final var fcresp = cb.findcategory(key); final bwcategory cat; if (fcresp.iserror()) { return response.fromresponse(resp, fcresp); } if (fcresp.isnotfound()) { cat = bwcategory.makecategory(); cat.setword(key); cb.addcategory(cat); } else { cat = fcresp.getentity(); } chg.addvalue(pi, cat); } } break; case class: if (chg.changed(pi, ev.getclassification(), pval)) { ev.setclassification(pval); } break; case comment: chg.addvalue(pi, new bwstring(null, pval)); break; case completed: if (chg.changed(pi, ev.getcompleted(), pval)) { ev.setcompleted(pval); } break; case concept: final concept c = (concept)prop; final string cval = c.getvalue(); if (cval != null) { chg.addvalue(propertyinfoindex.xprop, bwxproperty.makeicalproperty("concept", null, cval)); } break; case contact: final string altrep = getaltreppar(prop); lang = icalutil.getlang(prop); final string uid = getuidpar(prop); final bwstring nm = new bwstring(lang, pval); bwcontact contact = null; if (uid != null) { final var fcresp = cb.getcontact(uid); if (fcresp.iserror()) { return response.fromresponse(resp, fcresp); } if (fcresp.isok()) { contact = fcresp.getentity(); } } if (contact == null) { final var fcresp = cb.findcontact(nm); if (fcresp.iserror()) { return response.fromresponse(resp, fcresp); } if (fcresp.isok()) { contact = fcresp.getentity(); } } if (contact == null) { contact = bwcontact.makecontact(); contact.setcn(nm); contact.setlink(altrep); cb.addcontact(contact); } else { contact.setcn(nm); contact.setlink(altrep); } chg.addvalue(pi, contact); break; case created: if (chg.changed(pi, ev.getcreated(), pval)) { ev.setcreated(pval); } break; case description: if (chg.changed(pi, ev.getdescription(), pval)) { ev.setdescription(pval); } break; case dtend: break; case dtstamp: ev.setdtstamp(pval); break; case dtstart: break; case due: break; case duration: break; case exdate: chg.addvalues(pi, icalutil.makedatetimes((datelistproperty)prop)); break; case exrule: chg.addvalue(pi, pval); break; case freebusy: final freebusy fbusy = (freebusy)prop; final periodlist perpl = fbusy.getperiods(); final parameter par = icalutil.getparameter(fbusy, "fbtype"); final int fbtype; if (par == null) { fbtype = bwfreebusycomponent.typebusy; } else if (par.equals(fbtype.busy)) { fbtype = bwfreebusycomponent.typebusy; } else if (par.equals(fbtype.busy_tentative)) { fbtype = bwfreebusycomponent.typebusytentative; } else if (par.equals(fbtype.busy_unavailable)) { fbtype = bwfreebusycomponent.typebusyunavailable; } else if (par.equals(fbtype.free)) { fbtype = bwfreebusycomponent.typefree; } else { if (logger.debug()) { logger.debug("unsupported parameter " + par.getname()); } return response.notok(resp, failed, "unsupported parameter " + par.getname()); } final bwfreebusycomponent fbc = new bwfreebusycomponent(); fbc.settype(fbtype); for (final period per : perpl) { fbc.addperiod(per); } ev.addfreebusyperiod(fbc); break; case geo: final geo g = (geo)prop; final bwgeo geo = new bwgeo(g.getlatitude(), g.getlongitude()); if (chg.changed(pi, ev.getgeo(), geo)) { ev.setgeo(geo); } break; case last_modified: if (chg.changed(pi, ev.getlastmod(), pval)) { ev.setlastmod(pval); } break; case location: bwlocation loc = null; lang = icalutil.getlang(prop); bwstring addr = null; if (pval != null) { if (loc == null) { addr = new bwstring(lang, pval); final var fcresp = cb.findlocation(addr); if (fcresp.iserror()) { return response.fromresponse(resp, fcresp); } if (fcresp.isok()) { loc = fcresp.getentity(); } } if (loc == null) { loc = bwlocation.makelocation(); loc.setaddress(addr); cb.addlocation(loc); } } final bwlocation evloc = ev.getlocation(); if (chg.changed(pi, evloc, loc)) { ev.setlocation(loc); } else if ((loc != null) && (evloc != null)) { final string evval = evloc.getaddress().getvalue(); final string inval = loc.getaddress().getvalue(); if (!evval.equals(inval)) { chg.changed(pi, evval, inval); evloc.getaddress().setvalue(inval); } } break; case organizer: final bworganizer org = icalutil.getorganizer(cb, (organizer)prop); final bworganizer evorg = ev.getorganizer(); final bworganizer evorgcopy; if (evorg == null) { evorgcopy = null; } else { evorgcopy = (bworganizer)evorg.clone(); } if (chg.changed(pi, evorgcopy, org)) { if (evorg == null) { ev.setorganizer(org); } else { evorg.update(org); } } break; case percent_complete: integer ival = ((percentcomplete)prop).getpercentage(); if (chg.changed(pi, ev.getpercentcomplete(), ival)) { ev.setpercentcomplete(ival); } break; case poll_mode: sval = prop.getvalue(); if (chg.changed(pi, ev.getpollmode(), sval)) { ev.setpollmode(sval); } break; case poll_properties: sval = prop.getvalue(); if (chg.changed(pi, ev.getpollproperties(), sval)) { ev.setpollproperties(sval); } break; case poll_winner: ival = ((pollwinner)prop).getpollwinner(); if (chg.changed(pi, ev.getpollwinner(), ival)) { ev.setpollwinner(ival); } break; case priority: ival = ((priority)prop).getlevel(); if (chg.changed(pi, ev.getpriority(), ival)) { ev.setpriority(ival); } break; case rdate: chg.addvalues(pi, icalutil.makedatetimes((datelistproperty)prop)); break; case recurrence_id: break; case related_to: final relatedto irelto = (relatedto)prop; final bwrelatedto relto = new bwrelatedto(); final string parval = icalutil.getparameterval(irelto, "reltype"); if (parval != null) { relto.setreltype(parval); } relto.setvalue(irelto.getvalue()); if (chg.changed(pi, ev.getrelatedto(), relto)) { ev.setrelatedto(relto); } break; case request_status: final bwrequeststatus rs = bwrequeststatus .fromrequeststatus((requeststatus)prop); chg.addvalue(pi, rs); break; case resources: final textlist rl = ((resources)prop).getresources(); if (rl != null) { lang = icalutil.getlang(prop); for (final string s: rl) { final bwstring rsrc = new bwstring(lang, s); chg.addvalue(pi, rsrc); } } break; case rrule: chg.addvalue(pi, pval); break; case sequence: final int seq = ((sequence)prop).getsequenceno(); if (seq != ev.getsequence()) { chg.changed(pi, ev.getsequence(), seq); ev.setsequence(seq); } break; case status: if (chg.changed(pi, ev.getstatus(), pval)) { ev.setstatus(pval); } break; case summary: if (chg.changed(pi, ev.getsummary(), pval)) { ev.setsummary(pval); } break; case transp: if (chg.changed(pi, ev.getperusertransparency( cb.getprincipal() .getprincipalref()), pval)) { final bwxproperty pu = ev.setperusertransparency( cb.getprincipal().getprincipalref(), pval); if (pu != null) { chg.addvalue(propertyinfoindex.xprop, pu); } } break; case uid: break; case url: if (chg.changed(pi, ev.getlink(), pval)) { ev.setlink(pval); } break; case xprop: final string name = prop.getname(); if (name.equalsignorecase(bwxproperty.bedeworkcost)) { if (chg.changed(propertyinfoindex.cost, ev.getcost(), pval)) { ev.setcost(pval); } break; } if (name.equalsignorecase(bwxproperty.xbedeworkcategories)) { if (checkcategory(cb, chg, ev, null, pval)) { break; } } if (name.equalsignorecase(bwxproperty.xbedeworklocation)) { if (checklocation(cb, chg, ev, prop)) { break; } } if (name.equalsignorecase(bwxproperty.xbedeworkcontact)) { if (checkcontact(cb, chg, ev, null, pval)) { break; } } final xproperty xp = (xproperty)prop; chg.addvalue(propertyinfoindex.xprop, new bwxproperty(name, xp.getparameters() .tostring(), pval)); break; default: if (logger.debug()) { logger.debug("unsupported property with index " + pi + "; class " + prop.getclass() + " and value " + pval); } } } final componentlist<component> subcomps; if (val instanceof componentcontainer) { subcomps = ((componentcontainer<component>)val).getcomponents(); } else { subcomps = null; } final set<integer> pids; if (vpoll) { pids = new treeset<>(); final bwevent vp = evinfo.getevent(); if (!util.isempty(vp.getpollitems())) { vp.clearpollitems(); } } else { pids = null; } if (!util.isempty(subcomps)) { for (final var subcomp: subcomps) { if (subcomp instanceof available) { if (!(val instanceof vavailability)) { return response.error(resp, "available only valid in vavailable"); } final var avlresp = processavailable(cb, cal, ical, (vavailability)val, (available)subcomp, evinfo); if (!avlresp.isok()) { return response.fromresponse(resp, avlresp); } continue; } if (subcomp instanceof participant) { if (vpoll) { final var vresp = processvoter(cb, (vpoll)val, (participant)subcomp, evinfo, chg, mergeattendees); if (!vresp.isok()) { return response.fromresponse(resp, vresp); } continue; } logger.warn("unimplemented participant object"); continue; } if (subcomp instanceof vresource) { logger.warn("unimplemented vresource object"); continue; } if (subcomp instanceof vlocation) { logger.warn("unimplemented vlocation object"); continue; } if (subcomp instanceof valarm) { final var aresp = valarmutil.processalarm(cb, val, (valarm)subcomp, ev, currentprincipal, chg); if (!aresp.isok()) { return response.fromresponse(resp, aresp); } continue; } if (vpoll && (event || task)) { final var vresp = processcandidate((vpoll)val, subcomp, evinfo, pids, chg); if (!vresp.isok()) { return response.fromresponse(resp, vresp); } continue; } logger.warn("unimplemented component object: " + subcomp); } } if (ev.getcreated() == null) { if (ev.getlastmod() != null) { ev.setcreated(ev.getlastmod()); chg.changed(propertyinfoindex.created, null, ev.getcreated()); } else { ev.updatedtstamp(); chg.changed(propertyinfoindex.created, null, ev.getcreated()); chg.changed(propertyinfoindex.last_modified, null, ev.getlastmod()); } } if (ev.getlastmod() == null) { ev.setlastmod(ev.getcreated()); chg.changed(propertyinfoindex.last_modified, null, ev.getlastmod()); } processtimezones(ev, ical, chg); if (ev.getrecipients() != null) { ev.getrecipients().clear(); } ev.setoriginator(null); if (hasxparams.value) { final component valcopy = val.copy(); final description desp = valcopy.getproperty(property.description); if (desp != null) { desp.setvalue(null); } final attach attachp = valcopy.getproperty(property.attach); if (attachp != null) { final value v = attachp.getparameter(parameter.value); if (v != null) { attachp.setvalue(string.valueof(attachp.getvalue().hashcode())); } } chg.addvalue(propertyinfoindex.xprop, new bwxproperty(bwxproperty.bedeworkical, null, valcopy.tostring())); } chg.processchanges(ev, true, false); ev.setrecurring(ev.isrecurringentity()); if (logger.debug()) { logger.debug(chg.tostring()); logger.debug(ev.tostring()); } if (masterei != null) { return response.notfound(resp); } resp.setentity(evinfo); return resp; } catch (final throwable t) { if (logger.debug()) { logger.error(t); } return response.error(resp, t); } }
Bedework/bw-calendar-convert
[ 1, 0, 1, 0 ]
7,967
@GET @Produces(MediaType.APPLICATION_JSON) // FIXME Uncomment when overrides can be handled // @OutSchema("wdk.users.get-by-id") public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException { UserBundle userBundle = getUserBundle(Access.PUBLIC); List<UserPropertyName> propDefs = getWdkModel().getModelConfig() .getAccountDB().getUserPropertyNames(); return formatUser(userBundle.getTargetUser(), userBundle.isSessionUser(), getFlag(includePreferences), propDefs); }
@GET @Produces(MediaType.APPLICATION_JSON) public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException { UserBundle userBundle = getUserBundle(Access.PUBLIC); List<UserPropertyName> propDefs = getWdkModel().getModelConfig() .getAccountDB().getUserPropertyNames(); return formatUser(userBundle.getTargetUser(), userBundle.isSessionUser(), getFlag(includePreferences), propDefs); }
@get @produces(mediatype.application_json) public jsonobject getbyid(@queryparam("includepreferences") boolean includepreferences) throws wdkmodelexception { userbundle userbundle = getuserbundle(access.public); list<userpropertyname> propdefs = getwdkmodel().getmodelconfig() .getaccountdb().getuserpropertynames(); return formatuser(userbundle.gettargetuser(), userbundle.issessionuser(), getflag(includepreferences), propdefs); }
EuPathDB-Infra/WDK
[ 1, 0, 0, 0 ]
24,418
public static void useDropper(PlayerEntity player, Object tank, int button) { ItemStack stack = player.inventory.getItemStack(); if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) { return; } if (!stack.isEmpty()) { FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack); if (tank instanceof IChemicalTank) { IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank; if (chemicalTank.getEmptyStack() == GasStack.EMPTY) { //It is actually a gas tank IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank; Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY)); if (capability.isPresent()) { IGasHandler gasHandlerItem = capability.get(); if (gasHandlerItem.getGasTankCount() > 0) { //Validate something didn't go terribly wrong and we actually do have the tank we expect to have GasStack storedGas = gasHandlerItem.getGasInTank(0); if (!storedGas.isTypeEqual(gasTank.getStack())) { return; } if (button == 0) { //Insert gas into dropper if (!storedFluid.isEmpty() || gasTank.isEmpty()) { return; } GasStack gasInTank = gasTank.getStack(); GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE); int remainder = simulatedRemainder.getAmount(); int amount = gasInTank.getAmount(); if (remainder < amount) { //We are able to fit at least some of the gas from our tank into the item GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL); if (!extractedGas.isEmpty()) { //If we were able to actually extract it from our tank, then insert it into the item if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) { //TODO: Print warning/error } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 1) { //Extract gas from dropper if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) { //If the dropper has fluid or the tank interacting with is already full of gas return; } GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL); int gasInItemAmount = storedGas.getAmount(); int remainder = simulatedRemainder.getAmount(); if (remainder < gasInItemAmount) { GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE); if (!extractedGas.isEmpty()) { //If we were able to actually extract it from the item, then insert it into our gas tank if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) { //TODO: Print warning/error } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 2) { //Dump the tank gasTank.setEmpty(); } } } else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) { //It is actually an infusion tank IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank; //TODO: Implement at some point } } //TODO: Handle other chemical tanks like maybe infusion tanks } else if (tank instanceof IExtendedFluidTank) { IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank; if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) { return; } GasStack storedGas = GasStack.EMPTY; Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY)); if (gasCapability.isPresent()) { IGasHandler gasHandlerItem = gasCapability.get(); if (gasHandlerItem.getGasTankCount() > 0) { storedGas = gasHandlerItem.getGasInTank(0); } } if (button == 2) { //Dump the tank fluidTank.setEmpty(); } Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack)); if (!capability.isPresent()) { //If something went wrong and we don't have a fluid handler on our tank, then fail return; } IFluidHandlerItem fluidHandlerItem = capability.get(); if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) { //TODO: Decide if we want to support someone replacing our fluid handler with another? //If it isn't one of our fluid handlers fail return; } IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null); if (itemFluidTank == null) { //If something went wrong and we don't have a fluid tank fail return; } if (button == 0) { //Insert fluid into dropper if (!storedGas.isEmpty() || fluidTank.isEmpty()) { return; } FluidStack fluidInTank = fluidTank.getFluid(); FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL); int remainder = simulatedRemainder.getAmount(); int amount = fluidInTank.getAmount(); if (remainder < amount) { //We are able to fit at least some of the fluid from our tank into the item FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!extractedFluid.isEmpty()) { //If we were able to actually extract it from our tank, then insert it into the item if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) { //TODO: Print warning/error } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 1) { //Extract fluid from dropper if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) { return; } FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL); int fluidInItemAmount = storedFluid.getAmount(); int remainder = simulatedRemainder.getAmount(); if (remainder < fluidInItemAmount) { FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!drainedGas.isEmpty()) { //If we were able to actually extract it from the item, then insert it into our gas tank if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) { //TODO: Print warning/error } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } } } }
public static void useDropper(PlayerEntity player, Object tank, int button) { ItemStack stack = player.inventory.getItemStack(); if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) { return; } if (!stack.isEmpty()) { FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack); if (tank instanceof IChemicalTank) { IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank; if (chemicalTank.getEmptyStack() == GasStack.EMPTY) { IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank; Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY)); if (capability.isPresent()) { IGasHandler gasHandlerItem = capability.get(); if (gasHandlerItem.getGasTankCount() > 0) { GasStack storedGas = gasHandlerItem.getGasInTank(0); if (!storedGas.isTypeEqual(gasTank.getStack())) { return; } if (button == 0) { if (!storedFluid.isEmpty() || gasTank.isEmpty()) { return; } GasStack gasInTank = gasTank.getStack(); GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE); int remainder = simulatedRemainder.getAmount(); int amount = gasInTank.getAmount(); if (remainder < amount) { GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL); if (!extractedGas.isEmpty()) { if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) { } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 1) { if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) { return; } GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL); int gasInItemAmount = storedGas.getAmount(); int remainder = simulatedRemainder.getAmount(); if (remainder < gasInItemAmount) { GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE); if (!extractedGas.isEmpty()) { if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) { } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 2) { gasTank.setEmpty(); } } } else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) { IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank; } } } else if (tank instanceof IExtendedFluidTank) { IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank; if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) { return; } GasStack storedGas = GasStack.EMPTY; Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY)); if (gasCapability.isPresent()) { IGasHandler gasHandlerItem = gasCapability.get(); if (gasHandlerItem.getGasTankCount() > 0) { storedGas = gasHandlerItem.getGasInTank(0); } } if (button == 2) { fluidTank.setEmpty(); } Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack)); if (!capability.isPresent()) { return; } IFluidHandlerItem fluidHandlerItem = capability.get(); if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) { return; } IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null); if (itemFluidTank == null) { return; } if (button == 0) { if (!storedGas.isEmpty() || fluidTank.isEmpty()) { return; } FluidStack fluidInTank = fluidTank.getFluid(); FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL); int remainder = simulatedRemainder.getAmount(); int amount = fluidInTank.getAmount(); if (remainder < amount) { FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!extractedFluid.isEmpty()) { if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) { } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } else if (button == 1) { if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) { return; } FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL); int fluidInItemAmount = storedFluid.getAmount(); int remainder = simulatedRemainder.getAmount(); if (remainder < fluidInItemAmount) { FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!drainedGas.isEmpty()) { if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) { } ((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer); } } } } } }
public static void usedropper(playerentity player, object tank, int button) { itemstack stack = player.inventory.getitemstack(); if (stack.isempty() || !(stack.getitem() instanceof itemgaugedropper)) { return; } if (!stack.isempty()) { fluidstack storedfluid = storageutils.getstoredfluidfromnbt(stack); if (tank instanceof ichemicaltank) { ichemicaltank<?, ?> chemicaltank = (ichemicaltank<?, ?>) tank; if (chemicaltank.getemptystack() == gasstack.empty) { ichemicaltank<gas, gasstack> gastank = (ichemicaltank<gas, gasstack>) chemicaltank; optional<igashandler> capability = mekanismutils.tooptional(stack.getcapability(capabilities.gas_handler_capability)); if (capability.ispresent()) { igashandler gashandleritem = capability.get(); if (gashandleritem.getgastankcount() > 0) { gasstack storedgas = gashandleritem.getgasintank(0); if (!storedgas.istypeequal(gastank.getstack())) { return; } if (button == 0) { if (!storedfluid.isempty() || gastank.isempty()) { return; } gasstack gasintank = gastank.getstack(); gasstack simulatedremainder = gashandleritem.insertgas(gasintank, action.simulate); int remainder = simulatedremainder.getamount(); int amount = gasintank.getamount(); if (remainder < amount) { gasstack extractedgas = gastank.extract(amount - remainder, action.execute, automationtype.internal); if (!extractedgas.isempty()) { if (!gashandleritem.insertgas(extractedgas, action.execute).isempty()) { } ((serverplayerentity) player).sendcontainertoplayer(player.opencontainer); } } } else if (button == 1) { if (!storedfluid.isempty() || gastank.getneeded() == 0) { return; } gasstack simulatedremainder = gastank.insert(storedgas, action.simulate, automationtype.internal); int gasinitemamount = storedgas.getamount(); int remainder = simulatedremainder.getamount(); if (remainder < gasinitemamount) { gasstack extractedgas = gashandleritem.extractgas(0, gasinitemamount - remainder, action.execute); if (!extractedgas.isempty()) { if (!gastank.insert(extractedgas, action.execute, automationtype.internal).isempty()) { } ((serverplayerentity) player).sendcontainertoplayer(player.opencontainer); } } } else if (button == 2) { gastank.setempty(); } } } else if (chemicaltank.getemptystack() == infusionstack.empty) { ichemicaltank<infusetype, infusionstack> infusiontank = (ichemicaltank<infusetype, infusionstack>) chemicaltank; } } } else if (tank instanceof iextendedfluidtank) { iextendedfluidtank fluidtank = (iextendedfluidtank) tank; if (!storedfluid.isempty() && !fluidtank.isempty() && !storedfluid.isfluidequal(fluidtank.getfluid())) { return; } gasstack storedgas = gasstack.empty; optional<igashandler> gascapability = mekanismutils.tooptional(stack.getcapability(capabilities.gas_handler_capability)); if (gascapability.ispresent()) { igashandler gashandleritem = gascapability.get(); if (gashandleritem.getgastankcount() > 0) { storedgas = gashandleritem.getgasintank(0); } } if (button == 2) { fluidtank.setempty(); } optional<ifluidhandleritem> capability = mekanismutils.tooptional(fluidutil.getfluidhandler(stack)); if (!capability.ispresent()) { return; } ifluidhandleritem fluidhandleritem = capability.get(); if (!(fluidhandleritem instanceof imekanismfluidhandler)) { return; } iextendedfluidtank itemfluidtank = ((imekanismfluidhandler) fluidhandleritem).getfluidtank(0, null); if (itemfluidtank == null) { return; } if (button == 0) { if (!storedgas.isempty() || fluidtank.isempty()) { return; } fluidstack fluidintank = fluidtank.getfluid(); fluidstack simulatedremainder = itemfluidtank.insert(fluidintank, action.simulate, automationtype.manual); int remainder = simulatedremainder.getamount(); int amount = fluidintank.getamount(); if (remainder < amount) { fluidstack extractedfluid = fluidtank.extract(amount - remainder, action.execute, automationtype.manual); if (!extractedfluid.isempty()) { if (!itemfluidtank.insert(extractedfluid, action.execute, automationtype.manual).isempty()) { } ((serverplayerentity) player).sendcontainertoplayer(player.opencontainer); } } } else if (button == 1) { if (!storedgas.isempty() || fluidtank.getneeded() == 0) { return; } fluidstack simulatedremainder = fluidtank.insert(storedfluid, action.simulate, automationtype.manual); int fluidinitemamount = storedfluid.getamount(); int remainder = simulatedremainder.getamount(); if (remainder < fluidinitemamount) { fluidstack drainedgas = itemfluidtank.extract(fluidinitemamount - remainder, action.execute, automationtype.manual); if (!drainedgas.isempty()) { if (!fluidtank.insert(drainedgas, action.execute, automationtype.internal).isempty()) { } ((serverplayerentity) player).sendcontainertoplayer(player.opencontainer); } } } } } }
Chiefwright/Mekanism
[ 0, 1, 0, 0 ]
24,703
@Override public boolean onStartNode(ProjectPath path) { JpaEntityMap entityMap = (JpaEntityMap) path.getObject(); // TODO: andrus, 4/28/2006 - actually we need to analyze preloaded classes and // see how they were annotated to choose the right access type... entityMap.setAccess(AccessType.FIELD); return true; }
@Override public boolean onStartNode(ProjectPath path) { JpaEntityMap entityMap = (JpaEntityMap) path.getObject(); entityMap.setAccess(AccessType.FIELD); return true; }
@override public boolean onstartnode(projectpath path) { jpaentitymap entitymap = (jpaentitymap) path.getobject(); entitymap.setaccess(accesstype.field); return true; }
JavaQualitasCorpus/cayenne-3.0.1
[ 1, 0, 0, 0 ]
24,704
@Override public boolean onStartNode(ProjectPath path) { JpaRelationship relationship = (JpaRelationship) path.getObjectParent(); JpaJoinColumn column = (JpaJoinColumn) path.getObject(); if (column.getTable() == null) { JpaEntity entity = path.firstInstanceOf(JpaEntity.class); column.setTable(entity.getTable().getName()); } // JPA Spec, 2.1.8.2 (same for all relationship owners): // The following mapping defaults apply: [...] // Table A contains a foreign key to table B. The foreign key column // name is formed as the concatenation of the following: the name of // the relationship property or field of entityA; "_" ; the name of // the primary key column in table B. The foreign key column has the // same type as the primary key of table B. JpaEntityMap map = path.firstInstanceOf(JpaEntityMap.class); JpaEntity target = map.entityForClass(relationship.getTargetEntityName()); if (target == null) { context.recordConflict(new SimpleValidationFailure( relationship, "Invalid relationship target " + relationship.getTargetEntityName())); } else if (target.getAttributes() == null || target.getAttributes().getIds().isEmpty()) { context.recordConflict(new SimpleValidationFailure( target, "Relationship target has no PK defined: " + relationship.getTargetEntityName())); } else if (target.getAttributes().getIds().size() > 1) { // TODO: andrus, 4/30/2006 implement this; note that instead of // checking for "attribute.getJoinColumns().isEmpty()" above, // we'll have to match individual columns context.recordConflict(new SimpleValidationFailure( relationship, "Defaults for compound FK are not implemented.")); } else { JpaId id = target.getAttributes().getIds().iterator().next(); String pkName = id.getColumn() != null ? id.getColumn().getName() : id .getName(); column.setName(relationship.getName() + '_' + pkName); column.setReferencedColumnName(id.getColumn() != null ? id .getColumn() .getName() : id.getName()); } return true; }
@Override public boolean onStartNode(ProjectPath path) { JpaRelationship relationship = (JpaRelationship) path.getObjectParent(); JpaJoinColumn column = (JpaJoinColumn) path.getObject(); if (column.getTable() == null) { JpaEntity entity = path.firstInstanceOf(JpaEntity.class); column.setTable(entity.getTable().getName()); } JpaEntityMap map = path.firstInstanceOf(JpaEntityMap.class); JpaEntity target = map.entityForClass(relationship.getTargetEntityName()); if (target == null) { context.recordConflict(new SimpleValidationFailure( relationship, "Invalid relationship target " + relationship.getTargetEntityName())); } else if (target.getAttributes() == null || target.getAttributes().getIds().isEmpty()) { context.recordConflict(new SimpleValidationFailure( target, "Relationship target has no PK defined: " + relationship.getTargetEntityName())); } else if (target.getAttributes().getIds().size() > 1) { context.recordConflict(new SimpleValidationFailure( relationship, "Defaults for compound FK are not implemented.")); } else { JpaId id = target.getAttributes().getIds().iterator().next(); String pkName = id.getColumn() != null ? id.getColumn().getName() : id .getName(); column.setName(relationship.getName() + '_' + pkName); column.setReferencedColumnName(id.getColumn() != null ? id .getColumn() .getName() : id.getName()); } return true; }
@override public boolean onstartnode(projectpath path) { jparelationship relationship = (jparelationship) path.getobjectparent(); jpajoincolumn column = (jpajoincolumn) path.getobject(); if (column.gettable() == null) { jpaentity entity = path.firstinstanceof(jpaentity.class); column.settable(entity.gettable().getname()); } jpaentitymap map = path.firstinstanceof(jpaentitymap.class); jpaentity target = map.entityforclass(relationship.gettargetentityname()); if (target == null) { context.recordconflict(new simplevalidationfailure( relationship, "invalid relationship target " + relationship.gettargetentityname())); } else if (target.getattributes() == null || target.getattributes().getids().isempty()) { context.recordconflict(new simplevalidationfailure( target, "relationship target has no pk defined: " + relationship.gettargetentityname())); } else if (target.getattributes().getids().size() > 1) { context.recordconflict(new simplevalidationfailure( relationship, "defaults for compound fk are not implemented.")); } else { jpaid id = target.getattributes().getids().iterator().next(); string pkname = id.getcolumn() != null ? id.getcolumn().getname() : id .getname(); column.setname(relationship.getname() + '_' + pkname); column.setreferencedcolumnname(id.getcolumn() != null ? id .getcolumn() .getname() : id.getname()); } return true; }
JavaQualitasCorpus/cayenne-3.0.1
[ 0, 1, 0, 0 ]
16,569
private Result executeTest(Path.ID id, QCInterpreter interpreter, Decl.FunctionOrMethod dec, TestType testType, int numTest, BigInteger lowerLimit, BigInteger upperLimit) { // Get the method for generating test values GenerateTest testGen; try { if(testType == TestType.EXHAUSTIVE) { testGen = new ExhaustiveGenerateTest(dec.getParameters(), interpreter, numTest, lowerLimit, upperLimit); } else { testGen = new RandomGenerateTest(dec.getParameters(), interpreter, numTest, lowerLimit, upperLimit); } } catch (IntegerRangeException e) { System.out.println("Integer range was invalid for the limits given."); return Result.ERRORS; } // Get the function's relevant header information NameID name = new NameID(id, dec.getName().get()); Type.Callable type = dec.getType(); Tuple<Expr> preconditions = dec.getRequires(); Tuple<Expr> postconditions = dec.getEnsures(); Tuple<Decl.Variable> inputParameters = dec.getParameters(); Tuple<Decl.Variable> outputParameters = dec.getReturns(); System.out.println("Name of the function/method: " + name.name()); // System.out.println("FUNCTION PARAM TYPES "+ inputParameters); // System.out.println("PRECONDITION "+ preconditions); // System.out.println("POSTCONDITION "+ postconditions); // // Have to remove the pre and post conditions out of the // // function so the function is executed without validation // // Validation will be conducted manually inside the function. // Tuple<Expr> empty = new Tuple<Expr>(); // dec.setOperand(4, empty); // Remove precondition // dec.setOperand(5, empty); // Remove postcondition boolean completedAll = false; int numSkipped = 0; int numPassed = 0; int numFailed = 0; for(int i=0; i < numTest; i++) { recursiveType.clear(); // Stop execution if all possible combinations have been generated // Can do this for methods as well as a new call stack is created each time if(testGen.exceedSize() && i != 0) { completedAll = true; break; } RValue[] paramValues = null; CallStack frame = interpreter.new CallStack(); // Check the precondition try { paramValues = testGen.generateParameters(); for(int j=0; j < inputParameters.size(); j++) { Decl.Variable parameter = inputParameters.get(j); frame.putLocal(parameter.getName(), paramValues[j]); } interpreter.checkInvariants(frame, preconditions); } catch(CannotGenerateException e) { System.out.println(e); return Result.ERRORS; } catch(AssertionError e){ System.out.println("Pre-condition failed on input: " + Arrays.toString(paramValues)); numSkipped++; continue; } catch(RuntimeException e) { System.out.println("Error occurred when generating input " + e + ": " + e.getMessage()); return Result.ERRORS; } System.out.println("INPUT: " + Arrays.toString(paramValues)); // Checks the postcondition when it is executed RValue[] returns = null; try { returns = interpreter.execute(name, type, frame, false, false, paramValues); recursiveType.clear(); } catch(AssertionError e) { System.out.println("Error occurred during execution " + e + ": " + e.getMessage()); numFailed++; continue; } catch(RuntimeException e) { System.out.println("Error occurred during execution " + e + ": " + e.getMessage()); return Result.ERRORS; } try { // Add the return values into the frame for validation for(int j=0; j < outputParameters.size(); j++) { Decl.Variable parameter = outputParameters.get(j); Type paramType = parameter.getType(); boolean valid = checkInvariant(interpreter, paramType, returns[j]); if(!valid) { throw new AssertionError("Type constraints for " + parameter + " failed"); } frame.putLocal(parameter.getName(), returns[j]); } try { interpreter.checkInvariants(frame, postconditions); numPassed++; // // Print out any return values produced if (returns != null) { System.out.println("OUTPUT: " + Arrays.toString(returns)); } } catch(AssertionError e) { System.out.printf("Failed Input: %s%nFailed Output: %s%n", Arrays.toString(paramValues), Arrays.toString(returns)); System.out.println("Postcondition failed " + e); numFailed++; } catch(RuntimeException e) { System.out.println("Error when checking invariants of return values " + e + ": " + e.getMessage()); return Result.ERRORS; } } catch(AssertionError e) { System.out.printf("Failed Input: %s%nFailed Output: %s%n", Arrays.toString(paramValues), Arrays.toString(returns)); System.out.println("Due to error " + e); numFailed++; } catch(RuntimeException e) { System.out.println("Error when checking type invariants of return values " + e + ": " + e.getMessage()); return Result.ERRORS; } catch (ResolutionError e) { // FIXME resolution error e.printStackTrace(); assert false; } } // Overall test statistics if(completedAll) { System.out.println("Tested all possible combinations"); int numActualTest = numPassed + numFailed + numSkipped; if(numFailed == 0) { if(numPassed > 0) { System.out.printf("Ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numPassed, (double) 100 * numPassed/numActualTest, numSkipped, (double) 100 * numSkipped/numActualTest, numActualTest); return Result.PASSED; } else { System.out.println("All tests skipped!"); return Result.SKIPPED; } } System.out.printf("Failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numPassed, (double) 100 * numPassed/numActualTest, numFailed, (double) 100 * numFailed/numActualTest, numSkipped, (double) 100 * numSkipped/numActualTest, numActualTest); return Result.FAILED; } else if(numPassed + numSkipped == numTest) { assert numFailed == 0; System.out.printf("Ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numPassed, (double) 100 * numPassed/numTest, numSkipped, (double) 100 * numSkipped/numTest, numTest); return Result.PASSED; } else if(numSkipped == numTest) { System.out.println("All tests skipped!"); return Result.SKIPPED; } else { System.out.printf("Failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numPassed, (double) 100 * numPassed/numTest, numFailed, (double) 100 * numFailed/numTest, numSkipped, (double) 100 * numSkipped/numTest, numTest); return Result.FAILED; } }
private Result executeTest(Path.ID id, QCInterpreter interpreter, Decl.FunctionOrMethod dec, TestType testType, int numTest, BigInteger lowerLimit, BigInteger upperLimit) { GenerateTest testGen; try { if(testType == TestType.EXHAUSTIVE) { testGen = new ExhaustiveGenerateTest(dec.getParameters(), interpreter, numTest, lowerLimit, upperLimit); } else { testGen = new RandomGenerateTest(dec.getParameters(), interpreter, numTest, lowerLimit, upperLimit); } } catch (IntegerRangeException e) { System.out.println("Integer range was invalid for the limits given."); return Result.ERRORS; } NameID name = new NameID(id, dec.getName().get()); Type.Callable type = dec.getType(); Tuple<Expr> preconditions = dec.getRequires(); Tuple<Expr> postconditions = dec.getEnsures(); Tuple<Decl.Variable> inputParameters = dec.getParameters(); Tuple<Decl.Variable> outputParameters = dec.getReturns(); System.out.println("Name of the function/method: " + name.name()); boolean completedAll = false; int numSkipped = 0; int numPassed = 0; int numFailed = 0; for(int i=0; i < numTest; i++) { recursiveType.clear(); if(testGen.exceedSize() && i != 0) { completedAll = true; break; } RValue[] paramValues = null; CallStack frame = interpreter.new CallStack(); try { paramValues = testGen.generateParameters(); for(int j=0; j < inputParameters.size(); j++) { Decl.Variable parameter = inputParameters.get(j); frame.putLocal(parameter.getName(), paramValues[j]); } interpreter.checkInvariants(frame, preconditions); } catch(CannotGenerateException e) { System.out.println(e); return Result.ERRORS; } catch(AssertionError e){ System.out.println("Pre-condition failed on input: " + Arrays.toString(paramValues)); numSkipped++; continue; } catch(RuntimeException e) { System.out.println("Error occurred when generating input " + e + ": " + e.getMessage()); return Result.ERRORS; } System.out.println("INPUT: " + Arrays.toString(paramValues)); RValue[] returns = null; try { returns = interpreter.execute(name, type, frame, false, false, paramValues); recursiveType.clear(); } catch(AssertionError e) { System.out.println("Error occurred during execution " + e + ": " + e.getMessage()); numFailed++; continue; } catch(RuntimeException e) { System.out.println("Error occurred during execution " + e + ": " + e.getMessage()); return Result.ERRORS; } try { for(int j=0; j < outputParameters.size(); j++) { Decl.Variable parameter = outputParameters.get(j); Type paramType = parameter.getType(); boolean valid = checkInvariant(interpreter, paramType, returns[j]); if(!valid) { throw new AssertionError("Type constraints for " + parameter + " failed"); } frame.putLocal(parameter.getName(), returns[j]); } try { interpreter.checkInvariants(frame, postconditions); numPassed++; if (returns != null) { System.out.println("OUTPUT: " + Arrays.toString(returns)); } } catch(AssertionError e) { System.out.printf("Failed Input: %s%nFailed Output: %s%n", Arrays.toString(paramValues), Arrays.toString(returns)); System.out.println("Postcondition failed " + e); numFailed++; } catch(RuntimeException e) { System.out.println("Error when checking invariants of return values " + e + ": " + e.getMessage()); return Result.ERRORS; } } catch(AssertionError e) { System.out.printf("Failed Input: %s%nFailed Output: %s%n", Arrays.toString(paramValues), Arrays.toString(returns)); System.out.println("Due to error " + e); numFailed++; } catch(RuntimeException e) { System.out.println("Error when checking type invariants of return values " + e + ": " + e.getMessage()); return Result.ERRORS; } catch (ResolutionError e) { e.printStackTrace(); assert false; } } if(completedAll) { System.out.println("Tested all possible combinations"); int numActualTest = numPassed + numFailed + numSkipped; if(numFailed == 0) { if(numPassed > 0) { System.out.printf("Ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numPassed, (double) 100 * numPassed/numActualTest, numSkipped, (double) 100 * numSkipped/numActualTest, numActualTest); return Result.PASSED; } else { System.out.println("All tests skipped!"); return Result.SKIPPED; } } System.out.printf("Failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numPassed, (double) 100 * numPassed/numActualTest, numFailed, (double) 100 * numFailed/numActualTest, numSkipped, (double) 100 * numSkipped/numActualTest, numActualTest); return Result.FAILED; } else if(numPassed + numSkipped == numTest) { assert numFailed == 0; System.out.printf("Ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numPassed, (double) 100 * numPassed/numTest, numSkipped, (double) 100 * numSkipped/numTest, numTest); return Result.PASSED; } else if(numSkipped == numTest) { System.out.println("All tests skipped!"); return Result.SKIPPED; } else { System.out.printf("Failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numPassed, (double) 100 * numPassed/numTest, numFailed, (double) 100 * numFailed/numTest, numSkipped, (double) 100 * numSkipped/numTest, numTest); return Result.FAILED; } }
private result executetest(path.id id, qcinterpreter interpreter, decl.functionormethod dec, testtype testtype, int numtest, biginteger lowerlimit, biginteger upperlimit) { generatetest testgen; try { if(testtype == testtype.exhaustive) { testgen = new exhaustivegeneratetest(dec.getparameters(), interpreter, numtest, lowerlimit, upperlimit); } else { testgen = new randomgeneratetest(dec.getparameters(), interpreter, numtest, lowerlimit, upperlimit); } } catch (integerrangeexception e) { system.out.println("integer range was invalid for the limits given."); return result.errors; } nameid name = new nameid(id, dec.getname().get()); type.callable type = dec.gettype(); tuple<expr> preconditions = dec.getrequires(); tuple<expr> postconditions = dec.getensures(); tuple<decl.variable> inputparameters = dec.getparameters(); tuple<decl.variable> outputparameters = dec.getreturns(); system.out.println("name of the function/method: " + name.name()); boolean completedall = false; int numskipped = 0; int numpassed = 0; int numfailed = 0; for(int i=0; i < numtest; i++) { recursivetype.clear(); if(testgen.exceedsize() && i != 0) { completedall = true; break; } rvalue[] paramvalues = null; callstack frame = interpreter.new callstack(); try { paramvalues = testgen.generateparameters(); for(int j=0; j < inputparameters.size(); j++) { decl.variable parameter = inputparameters.get(j); frame.putlocal(parameter.getname(), paramvalues[j]); } interpreter.checkinvariants(frame, preconditions); } catch(cannotgenerateexception e) { system.out.println(e); return result.errors; } catch(assertionerror e){ system.out.println("pre-condition failed on input: " + arrays.tostring(paramvalues)); numskipped++; continue; } catch(runtimeexception e) { system.out.println("error occurred when generating input " + e + ": " + e.getmessage()); return result.errors; } system.out.println("input: " + arrays.tostring(paramvalues)); rvalue[] returns = null; try { returns = interpreter.execute(name, type, frame, false, false, paramvalues); recursivetype.clear(); } catch(assertionerror e) { system.out.println("error occurred during execution " + e + ": " + e.getmessage()); numfailed++; continue; } catch(runtimeexception e) { system.out.println("error occurred during execution " + e + ": " + e.getmessage()); return result.errors; } try { for(int j=0; j < outputparameters.size(); j++) { decl.variable parameter = outputparameters.get(j); type paramtype = parameter.gettype(); boolean valid = checkinvariant(interpreter, paramtype, returns[j]); if(!valid) { throw new assertionerror("type constraints for " + parameter + " failed"); } frame.putlocal(parameter.getname(), returns[j]); } try { interpreter.checkinvariants(frame, postconditions); numpassed++; if (returns != null) { system.out.println("output: " + arrays.tostring(returns)); } } catch(assertionerror e) { system.out.printf("failed input: %s%nfailed output: %s%n", arrays.tostring(paramvalues), arrays.tostring(returns)); system.out.println("postcondition failed " + e); numfailed++; } catch(runtimeexception e) { system.out.println("error when checking invariants of return values " + e + ": " + e.getmessage()); return result.errors; } } catch(assertionerror e) { system.out.printf("failed input: %s%nfailed output: %s%n", arrays.tostring(paramvalues), arrays.tostring(returns)); system.out.println("due to error " + e); numfailed++; } catch(runtimeexception e) { system.out.println("error when checking type invariants of return values " + e + ": " + e.getmessage()); return result.errors; } catch (resolutionerror e) { e.printstacktrace(); assert false; } } if(completedall) { system.out.println("tested all possible combinations"); int numactualtest = numpassed + numfailed + numskipped; if(numfailed == 0) { if(numpassed > 0) { system.out.printf("ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numpassed, (double) 100 * numpassed/numactualtest, numskipped, (double) 100 * numskipped/numactualtest, numactualtest); return result.passed; } else { system.out.println("all tests skipped!"); return result.skipped; } } system.out.printf("failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numpassed, (double) 100 * numpassed/numactualtest, numfailed, (double) 100 * numfailed/numactualtest, numskipped, (double) 100 * numskipped/numactualtest, numactualtest); return result.failed; } else if(numpassed + numskipped == numtest) { assert numfailed == 0; system.out.printf("ok: %d passed (%.2f %%), %d skipped (%.2f %%), ran %d tests %n", numpassed, (double) 100 * numpassed/numtest, numskipped, (double) 100 * numskipped/numtest, numtest); return result.passed; } else if(numskipped == numtest) { system.out.println("all tests skipped!"); return result.skipped; } else { system.out.printf("failed: %d passed (%.2f %%), %d failed (%.2f %%), %d skipped (%.2f %%), ran %d tests%n", numpassed, (double) 100 * numpassed/numtest, numfailed, (double) 100 * numfailed/numtest, numskipped, (double) 100 * numskipped/numtest, numtest); return result.failed; } }
JC626/quickcheck-for-whiley
[ 0, 0, 1, 0 ]
8,419
@GET @Path("getDefaultNotebook") @Produces(MediaType.TEXT_PLAIN) public String getDefaultNotebook() { final String defaultNotebookUrl = this.bkConfig.getDefaultNotebookUrl(); // TODO, assume the url is a file path for now. java.nio.file.Path defaultNotebookFile = Paths.get(defaultNotebookUrl); String content = this.utils.readFile(defaultNotebookFile); if (content == null) { System.out.println("Warning, default notebook is empty"); return ""; } return clean(content); }
@GET @Path("getDefaultNotebook") @Produces(MediaType.TEXT_PLAIN) public String getDefaultNotebook() { final String defaultNotebookUrl = this.bkConfig.getDefaultNotebookUrl(); java.nio.file.Path defaultNotebookFile = Paths.get(defaultNotebookUrl); String content = this.utils.readFile(defaultNotebookFile); if (content == null) { System.out.println("Warning, default notebook is empty"); return ""; } return clean(content); }
@get @path("getdefaultnotebook") @produces(mediatype.text_plain) public string getdefaultnotebook() { final string defaultnotebookurl = this.bkconfig.getdefaultnotebookurl(); java.nio.file.path defaultnotebookfile = paths.get(defaultnotebookurl); string content = this.utils.readfile(defaultnotebookfile); if (content == null) { system.out.println("warning, default notebook is empty"); return ""; } return clean(content); }
NunoEdgarGFlowHub/beaker-notebook
[ 1, 0, 0, 0 ]
8,421
@POST @Path("setPreference") public synchronized void setPreference( @FormParam("preferencename") String preferenceName, @FormParam("preferencevalue") String preferenceValue) { if ((preferenceName == null) || (preferenceValue == null)) return; Object newValue = null; // Validate boolean preferences String[] booleanPrefs = {"advanced-mode", "allow-anonymous-usage-tracking", "fs-reverse"}; if (Arrays.asList(booleanPrefs).contains(preferenceName)){ switch (preferenceValue){ case "true": newValue = Boolean.TRUE; break; case "false": newValue = Boolean.FALSE; break; default: return; } if (preferenceName.equals("advanced-mode")) this.isUseAdvancedMode = (Boolean) newValue; else if (preferenceName == "allow") this.isAllowAnonymousTracking = (Boolean) newValue; } // Validate edit mode else if (preferenceName.equals("edit-mode")){ String[] validModes = {"vim", "emacs", "default"}; if (Arrays.asList(validModes).contains(preferenceValue)){ newValue = preferenceValue; this.editMode = preferenceValue; } } // Validate edit mode else if (preferenceName.equals("fs-order-by")){ String[] validModes = {"uri", "modified"}; if (Arrays.asList(validModes).contains(preferenceValue)){ newValue = preferenceValue; } } final String preferenceFileUrl = this.bkConfig.getPreferenceFileUrl(); // TODO, assume the url is a file path for now. // System.out.println(preferenceFileUrl + " url!!!!\n"); // Use a temporary for atomic writing java.nio.file.Path preferenceFileTmp = Paths.get(preferenceFileUrl + ".tmp"); java.nio.file.Path preferenceFile = Paths.get(preferenceFileUrl); try { ObjectMapper om = new ObjectMapper(); TypeReference readType = new TypeReference<HashMap<String, Object>>() { }; Map<String, Object> prefs = om.readValue(preferenceFile.toFile(), readType); Object oldValue = (Object) prefs.get(preferenceName); // If value changed, write it to the file too if (!Objects.equals(newValue, oldValue)) { Files.deleteIfExists(preferenceFileTmp); prefs.put(preferenceName, newValue); om.writerWithDefaultPrettyPrinter().writeValue(preferenceFileTmp.toFile(), prefs); // Move tmp to normal Files.move(preferenceFileTmp, preferenceFile, REPLACE_EXISTING); } } catch (IOException e) { e.printStackTrace(); } }
@POST @Path("setPreference") public synchronized void setPreference( @FormParam("preferencename") String preferenceName, @FormParam("preferencevalue") String preferenceValue) { if ((preferenceName == null) || (preferenceValue == null)) return; Object newValue = null; String[] booleanPrefs = {"advanced-mode", "allow-anonymous-usage-tracking", "fs-reverse"}; if (Arrays.asList(booleanPrefs).contains(preferenceName)){ switch (preferenceValue){ case "true": newValue = Boolean.TRUE; break; case "false": newValue = Boolean.FALSE; break; default: return; } if (preferenceName.equals("advanced-mode")) this.isUseAdvancedMode = (Boolean) newValue; else if (preferenceName == "allow") this.isAllowAnonymousTracking = (Boolean) newValue; } else if (preferenceName.equals("edit-mode")){ String[] validModes = {"vim", "emacs", "default"}; if (Arrays.asList(validModes).contains(preferenceValue)){ newValue = preferenceValue; this.editMode = preferenceValue; } } else if (preferenceName.equals("fs-order-by")){ String[] validModes = {"uri", "modified"}; if (Arrays.asList(validModes).contains(preferenceValue)){ newValue = preferenceValue; } } final String preferenceFileUrl = this.bkConfig.getPreferenceFileUrl(); java.nio.file.Path preferenceFileTmp = Paths.get(preferenceFileUrl + ".tmp"); java.nio.file.Path preferenceFile = Paths.get(preferenceFileUrl); try { ObjectMapper om = new ObjectMapper(); TypeReference readType = new TypeReference<HashMap<String, Object>>() { }; Map<String, Object> prefs = om.readValue(preferenceFile.toFile(), readType); Object oldValue = (Object) prefs.get(preferenceName); if (!Objects.equals(newValue, oldValue)) { Files.deleteIfExists(preferenceFileTmp); prefs.put(preferenceName, newValue); om.writerWithDefaultPrettyPrinter().writeValue(preferenceFileTmp.toFile(), prefs); Files.move(preferenceFileTmp, preferenceFile, REPLACE_EXISTING); } } catch (IOException e) { e.printStackTrace(); } }
@post @path("setpreference") public synchronized void setpreference( @formparam("preferencename") string preferencename, @formparam("preferencevalue") string preferencevalue) { if ((preferencename == null) || (preferencevalue == null)) return; object newvalue = null; string[] booleanprefs = {"advanced-mode", "allow-anonymous-usage-tracking", "fs-reverse"}; if (arrays.aslist(booleanprefs).contains(preferencename)){ switch (preferencevalue){ case "true": newvalue = boolean.true; break; case "false": newvalue = boolean.false; break; default: return; } if (preferencename.equals("advanced-mode")) this.isuseadvancedmode = (boolean) newvalue; else if (preferencename == "allow") this.isallowanonymoustracking = (boolean) newvalue; } else if (preferencename.equals("edit-mode")){ string[] validmodes = {"vim", "emacs", "default"}; if (arrays.aslist(validmodes).contains(preferencevalue)){ newvalue = preferencevalue; this.editmode = preferencevalue; } } else if (preferencename.equals("fs-order-by")){ string[] validmodes = {"uri", "modified"}; if (arrays.aslist(validmodes).contains(preferencevalue)){ newvalue = preferencevalue; } } final string preferencefileurl = this.bkconfig.getpreferencefileurl(); java.nio.file.path preferencefiletmp = paths.get(preferencefileurl + ".tmp"); java.nio.file.path preferencefile = paths.get(preferencefileurl); try { objectmapper om = new objectmapper(); typereference readtype = new typereference<hashmap<string, object>>() { }; map<string, object> prefs = om.readvalue(preferencefile.tofile(), readtype); object oldvalue = (object) prefs.get(preferencename); if (!objects.equals(newvalue, oldvalue)) { files.deleteifexists(preferencefiletmp); prefs.put(preferencename, newvalue); om.writerwithdefaultprettyprinter().writevalue(preferencefiletmp.tofile(), prefs); files.move(preferencefiletmp, preferencefile, replace_existing); } } catch (ioexception e) { e.printstacktrace(); } }
NunoEdgarGFlowHub/beaker-notebook
[ 1, 0, 0, 0 ]
8,420
private void resetConfig() { final String configFileUrl = this.bkConfig.getConfigFileUrl(); final String preferenceFileUrl = this.bkConfig.getPreferenceFileUrl(); // TODO, assume the url is a file path for now. java.nio.file.Path configFile = Paths.get(configFileUrl); java.nio.file.Path preferenceFile = Paths.get(preferenceFileUrl); try { JSONParser parser = new JSONParser(); JSONObject configJsonObject = (JSONObject) parser.parse(this.utils.readFile(configFile)); JSONObject preferenceJsonObject = (JSONObject) parser.parse(this.utils.readFile(preferenceFile)); String isAllowTracking = mergeBooleanSetting( "allow-anonymous-usage-tracking", configJsonObject, preferenceJsonObject); setPreference("allow-anonymous-usage-tracking", isAllowTracking); String isUseAdvancedMode = mergeBooleanSetting( "advanced-mode", configJsonObject, preferenceJsonObject); setPreference("advanced-mode", isUseAdvancedMode); String mergedEditMode = mergeStringSetting( "edit-mode", configJsonObject, preferenceJsonObject); setPreference("edit-mode", mergedEditMode); this.initPlugins.addAll( mergeListSetting("init", configJsonObject, preferenceJsonObject)); this.controlPanelMenuPlugins.addAll( mergeListSetting("control-panel-menu-plugins", configJsonObject, preferenceJsonObject)); this.menuPlugins.addAll( mergeListSetting("notebook-app-menu-plugins", configJsonObject, preferenceJsonObject)); this.cellMenuPlugins.addAll( mergeListSetting("notebook-cell-menu-plugins", configJsonObject, preferenceJsonObject)); } catch (ParseException e) { throw new RuntimeException("failed getting beaker configurations from config file", e); } }
private void resetConfig() { final String configFileUrl = this.bkConfig.getConfigFileUrl(); final String preferenceFileUrl = this.bkConfig.getPreferenceFileUrl(); java.nio.file.Path configFile = Paths.get(configFileUrl); java.nio.file.Path preferenceFile = Paths.get(preferenceFileUrl); try { JSONParser parser = new JSONParser(); JSONObject configJsonObject = (JSONObject) parser.parse(this.utils.readFile(configFile)); JSONObject preferenceJsonObject = (JSONObject) parser.parse(this.utils.readFile(preferenceFile)); String isAllowTracking = mergeBooleanSetting( "allow-anonymous-usage-tracking", configJsonObject, preferenceJsonObject); setPreference("allow-anonymous-usage-tracking", isAllowTracking); String isUseAdvancedMode = mergeBooleanSetting( "advanced-mode", configJsonObject, preferenceJsonObject); setPreference("advanced-mode", isUseAdvancedMode); String mergedEditMode = mergeStringSetting( "edit-mode", configJsonObject, preferenceJsonObject); setPreference("edit-mode", mergedEditMode); this.initPlugins.addAll( mergeListSetting("init", configJsonObject, preferenceJsonObject)); this.controlPanelMenuPlugins.addAll( mergeListSetting("control-panel-menu-plugins", configJsonObject, preferenceJsonObject)); this.menuPlugins.addAll( mergeListSetting("notebook-app-menu-plugins", configJsonObject, preferenceJsonObject)); this.cellMenuPlugins.addAll( mergeListSetting("notebook-cell-menu-plugins", configJsonObject, preferenceJsonObject)); } catch (ParseException e) { throw new RuntimeException("failed getting beaker configurations from config file", e); } }
private void resetconfig() { final string configfileurl = this.bkconfig.getconfigfileurl(); final string preferencefileurl = this.bkconfig.getpreferencefileurl(); java.nio.file.path configfile = paths.get(configfileurl); java.nio.file.path preferencefile = paths.get(preferencefileurl); try { jsonparser parser = new jsonparser(); jsonobject configjsonobject = (jsonobject) parser.parse(this.utils.readfile(configfile)); jsonobject preferencejsonobject = (jsonobject) parser.parse(this.utils.readfile(preferencefile)); string isallowtracking = mergebooleansetting( "allow-anonymous-usage-tracking", configjsonobject, preferencejsonobject); setpreference("allow-anonymous-usage-tracking", isallowtracking); string isuseadvancedmode = mergebooleansetting( "advanced-mode", configjsonobject, preferencejsonobject); setpreference("advanced-mode", isuseadvancedmode); string mergededitmode = mergestringsetting( "edit-mode", configjsonobject, preferencejsonobject); setpreference("edit-mode", mergededitmode); this.initplugins.addall( mergelistsetting("init", configjsonobject, preferencejsonobject)); this.controlpanelmenuplugins.addall( mergelistsetting("control-panel-menu-plugins", configjsonobject, preferencejsonobject)); this.menuplugins.addall( mergelistsetting("notebook-app-menu-plugins", configjsonobject, preferencejsonobject)); this.cellmenuplugins.addall( mergelistsetting("notebook-cell-menu-plugins", configjsonobject, preferencejsonobject)); } catch (parseexception e) { throw new runtimeexception("failed getting beaker configurations from config file", e); } }
NunoEdgarGFlowHub/beaker-notebook
[ 1, 0, 0, 0 ]
8,457
@Override @StartHandler(phase = Phase.INBOUND_EVENT_CONNECTORS) public void start() { if (activeProcessorThreads() > 0 || workLauncherRunning.get()) { if (state.get().isRunning()) { // then it's ok. It's already running return; } else { // this is problematic. There are still active threads pending a shutdown. throw new IllegalStateException("Cannot start this processor. It is pending shutdown..."); } } State previousState = state.getAndSet(State.STARTED); if (!previousState.isRunning()) { startSegmentWorkers(); } }
@Override @StartHandler(phase = Phase.INBOUND_EVENT_CONNECTORS) public void start() { if (activeProcessorThreads() > 0 || workLauncherRunning.get()) { if (state.get().isRunning()) { return; } else { throw new IllegalStateException("Cannot start this processor. It is pending shutdown..."); } } State previousState = state.getAndSet(State.STARTED); if (!previousState.isRunning()) { startSegmentWorkers(); } }
@override @starthandler(phase = phase.inbound_event_connectors) public void start() { if (activeprocessorthreads() > 0 || worklauncherrunning.get()) { if (state.get().isrunning()) { return; } else { throw new illegalstateexception("cannot start this processor. it is pending shutdown..."); } } state previousstate = state.getandset(state.started); if (!previousstate.isrunning()) { startsegmentworkers(); } }
Mu-L/AxonFramework
[ 0, 0, 1, 0 ]
275
public void update(Observable arg0, Object arg) { // arg is Event if (!(arg instanceof Event)) return; Event event = (Event) arg; // check the event function against the functions we have notifications watching for String function = event.getEvent(); //we err on the side of caution here in checking all events that might invalidate the data in the cache -DH if (UserDirectoryService.SECURE_ADD_USER.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_OWN_PASSWORD.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_ANY.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_OWN.equals(function)) { //we need the userId Reference ref = entityManager.newReference(event.getResource()); // look for group reference. Need to replace it with parent site reference String refId = ref.getId(); try { String eid = userDirectoryService.getUserEid(refId); log.debug("removing " + eid + " from cache"); authenticationCache.removeAuthentification(eid); userCache.remove(UserDirectoryService.IDCACHE + eid); userCache.remove(UserDirectoryService.EIDCACHE + refId); } catch (UserNotDefinedException e) { //not sure how we'd end up here log.warn(e.getMessage(), e); } } }
public void update(Observable arg0, Object arg) { if (!(arg instanceof Event)) return; Event event = (Event) arg; String function = event.getEvent(); if (UserDirectoryService.SECURE_ADD_USER.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_OWN_PASSWORD.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_ANY.equals(function) || UserDirectoryService.SECURE_UPDATE_USER_OWN.equals(function)) { Reference ref = entityManager.newReference(event.getResource()); String refId = ref.getId(); try { String eid = userDirectoryService.getUserEid(refId); log.debug("removing " + eid + " from cache"); authenticationCache.removeAuthentification(eid); userCache.remove(UserDirectoryService.IDCACHE + eid); userCache.remove(UserDirectoryService.EIDCACHE + refId); } catch (UserNotDefinedException e) { log.warn(e.getMessage(), e); } } }
public void update(observable arg0, object arg) { if (!(arg instanceof event)) return; event event = (event) arg; string function = event.getevent(); if (userdirectoryservice.secure_add_user.equals(function) || userdirectoryservice.secure_update_user_own_password.equals(function) || userdirectoryservice.secure_update_user_any.equals(function) || userdirectoryservice.secure_update_user_own.equals(function)) { reference ref = entitymanager.newreference(event.getresource()); string refid = ref.getid(); try { string eid = userdirectoryservice.getusereid(refid); log.debug("removing " + eid + " from cache"); authenticationcache.removeauthentification(eid); usercache.remove(userdirectoryservice.idcache + eid); usercache.remove(userdirectoryservice.eidcache + refid); } catch (usernotdefinedexception e) { log.warn(e.getmessage(), e); } } }
RyanAFinney/sakai
[ 1, 0, 0, 0 ]
286
public static String getAppProcess32Bit() { return getAppProcess32Bit(true); }
public static String getAppProcess32Bit() { return getAppProcess32Bit(true); }
public static string getappprocess32bit() { return getappprocess32bit(true); }
Lobesitdoll/librootjava
[ 0, 0, 0, 0 ]
8,492
@Pure @Override public boolean equals(@Nullable Object o) { if (o == null) return false; // never happens if (this == o) return true; // This test is illegal because WeakKey is a generic type, // so use the getClass hack below instead. // if (!(o instanceof WeakKey)) return false; if (!(o.getClass().equals(WeakKey.class))) return false; Object t = this.get(); @SuppressWarnings("unchecked") Object u = ((WeakKey) o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyEquals(t, u); }
@Pure @Override public boolean equals(@Nullable Object o) { if (o == null) return false; if (this == o) return true; if (!(o.getClass().equals(WeakKey.class))) return false; Object t = this.get(); @SuppressWarnings("unchecked") Object u = ((WeakKey) o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyEquals(t, u); }
@pure @override public boolean equals(@nullable object o) { if (o == null) return false; if (this == o) return true; if (!(o.getclass().equals(weakkey.class))) return false; object t = this.get(); @suppresswarnings("unchecked") object u = ((weakkey) o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyequals(t, u); }
Nargeshdb/plume-util
[ 1, 0, 0, 0 ]
16,687
public void applyGPSSetting() { // verify if GPS enable on device if(GPSService.isGPSProviderEnable(context) || GPSService.isNetworkProviderEnable(context)) { GPSSettingController gpsSettingController = new GPSSettingController(mMapView.getContext()); Boolean showGPSLocation = gpsSettingController.getGPSLocationState(); Boolean showGPSLocationOnCenter = gpsSettingController.getGPSCenterState(); if (showGPSLocation != null) if (showGPSLocation) { MainActivity mainActivity = (MainActivity) context; GPSOverlayController gpsOverlayController = mainActivity.getMainController().getGpsOverlayController(); gpsOverlayController.addGPSTrackerLayer(); gpsOverlayController.setKeepOnCenter( ((showGPSLocationOnCenter != null)?(showGPSLocationOnCenter):(false)) ); } }else { // TODO: notify user when the state of the GPS resource is disabled. use one icon on action bar? } }
public void applyGPSSetting() { if(GPSService.isGPSProviderEnable(context) || GPSService.isNetworkProviderEnable(context)) { GPSSettingController gpsSettingController = new GPSSettingController(mMapView.getContext()); Boolean showGPSLocation = gpsSettingController.getGPSLocationState(); Boolean showGPSLocationOnCenter = gpsSettingController.getGPSCenterState(); if (showGPSLocation != null) if (showGPSLocation) { MainActivity mainActivity = (MainActivity) context; GPSOverlayController gpsOverlayController = mainActivity.getMainController().getGpsOverlayController(); gpsOverlayController.addGPSTrackerLayer(); gpsOverlayController.setKeepOnCenter( ((showGPSLocationOnCenter != null)?(showGPSLocationOnCenter):(false)) ); } }else { } }
public void applygpssetting() { if(gpsservice.isgpsproviderenable(context) || gpsservice.isnetworkproviderenable(context)) { gpssettingcontroller gpssettingcontroller = new gpssettingcontroller(mmapview.getcontext()); boolean showgpslocation = gpssettingcontroller.getgpslocationstate(); boolean showgpslocationoncenter = gpssettingcontroller.getgpscenterstate(); if (showgpslocation != null) if (showgpslocation) { mainactivity mainactivity = (mainactivity) context; gpsoverlaycontroller gpsoverlaycontroller = mainactivity.getmaincontroller().getgpsoverlaycontroller(); gpsoverlaycontroller.addgpstrackerlayer(); gpsoverlaycontroller.setkeeponcenter( ((showgpslocationoncenter != null)?(showgpslocationoncenter):(false)) ); } }else { } }
MalteBerlin/TerraMobile
[ 0, 1, 0, 0 ]
325
void tracksDropped(Point startPoint, Point dropPoint, List<Track> tracks) { // This cast is horrid but we can't fix everything at once. TrackPanel panel = ((TrackPanel) getParent()); List<MouseableRegion> regions = getMouseRegions(); if (regions.isEmpty()) { // empty panel, just add the tracks panel.addTracks(tracks); } else { // Find the regions containing the startPoint and point boolean before = true; MouseableRegion dropRegion = null; MouseableRegion startRegion = null; for (MouseableRegion region : regions) { if (region.containsPoint(dropPoint.x, dropPoint.y)) { dropRegion = region; Rectangle bnds = dropRegion.getBounds(); int dy1 = (dropPoint.y - bnds.y); int dy2 = bnds.height - dy1; before = dy1 < dy2; } if (region.containsPoint(startPoint.x, startPoint.y)) { startRegion = region; } if (dropRegion != null && startRegion != null) { break; } } Track dropTrack = null; if (dropRegion != null) { Iterator<Track> tmp = dropRegion.getTracks().iterator(); if (tmp.hasNext()) { dropTrack = tmp.next(); } } panel.moveSelectedTracksTo(tracks, dropTrack, before); } }
void tracksDropped(Point startPoint, Point dropPoint, List<Track> tracks) { TrackPanel panel = ((TrackPanel) getParent()); List<MouseableRegion> regions = getMouseRegions(); if (regions.isEmpty()) { panel.addTracks(tracks); } else { boolean before = true; MouseableRegion dropRegion = null; MouseableRegion startRegion = null; for (MouseableRegion region : regions) { if (region.containsPoint(dropPoint.x, dropPoint.y)) { dropRegion = region; Rectangle bnds = dropRegion.getBounds(); int dy1 = (dropPoint.y - bnds.y); int dy2 = bnds.height - dy1; before = dy1 < dy2; } if (region.containsPoint(startPoint.x, startPoint.y)) { startRegion = region; } if (dropRegion != null && startRegion != null) { break; } } Track dropTrack = null; if (dropRegion != null) { Iterator<Track> tmp = dropRegion.getTracks().iterator(); if (tmp.hasNext()) { dropTrack = tmp.next(); } } panel.moveSelectedTracksTo(tracks, dropTrack, before); } }
void tracksdropped(point startpoint, point droppoint, list<track> tracks) { trackpanel panel = ((trackpanel) getparent()); list<mouseableregion> regions = getmouseregions(); if (regions.isempty()) { panel.addtracks(tracks); } else { boolean before = true; mouseableregion dropregion = null; mouseableregion startregion = null; for (mouseableregion region : regions) { if (region.containspoint(droppoint.x, droppoint.y)) { dropregion = region; rectangle bnds = dropregion.getbounds(); int dy1 = (droppoint.y - bnds.y); int dy2 = bnds.height - dy1; before = dy1 < dy2; } if (region.containspoint(startpoint.x, startpoint.y)) { startregion = region; } if (dropregion != null && startregion != null) { break; } } track droptrack = null; if (dropregion != null) { iterator<track> tmp = dropregion.gettracks().iterator(); if (tmp.hasnext()) { droptrack = tmp.next(); } } panel.moveselectedtracksto(tracks, droptrack, before); } }
Karimi-Lab/ALEA
[ 1, 0, 0, 0 ]
343
@AfterMethod public void cleanupResources() throws SQLException { TEST_NUMBER++; //todo issue #232 fix increment topic partition name for tests on multi jvm ALL_RESOURCES.cleanUpClusters(); DB_RESOURCE.executeResource(JDBCUtil.DROP_TABLE_SQL_RESOURCE); }
@AfterMethod public void cleanupResources() throws SQLException { TEST_NUMBER++; ALL_RESOURCES.cleanUpClusters(); DB_RESOURCE.executeResource(JDBCUtil.DROP_TABLE_SQL_RESOURCE); }
@aftermethod public void cleanupresources() throws sqlexception { test_number++; all_resources.cleanupclusters(); db_resource.executeresource(jdbcutil.drop_table_sql_resource); }
MayerRoman/Lagerta
[ 0, 0, 1, 0 ]
24,925
private void scheduleCleanup() { if (cleanupRegistration != null) { // Already scheduled return; } cleanupRegistration = ui.beforeClientResponse(ui, ignore -> { cleanupRegistration = null; pendingCleanup = false; // TODO Avoid copying by using Iterator.remove() properties.keySet().stream().filter(property -> !lastUsed.contains(property)).collect(Collectors.toList()) .forEach(unused -> properties.remove(unused).unregister()); }); }
private void scheduleCleanup() { if (cleanupRegistration != null) { return; } cleanupRegistration = ui.beforeClientResponse(ui, ignore -> { cleanupRegistration = null; pendingCleanup = false; properties.keySet().stream().filter(property -> !lastUsed.contains(property)).collect(Collectors.toList()) .forEach(unused -> properties.remove(unused).unregister()); }); }
private void schedulecleanup() { if (cleanupregistration != null) { return; } cleanupregistration = ui.beforeclientresponse(ui, ignore -> { cleanupregistration = null; pendingcleanup = false; properties.keyset().stream().filter(property -> !lastused.contains(property)).collect(collectors.tolist()) .foreach(unused -> properties.remove(unused).unregister()); }); }
Legioth/reactivevaadin
[ 0, 1, 0, 0 ]
24,936
@Override protected Path getPath(Canvas canvas, Paint paint) { Path path = new Path(); String text = formatText(); if (text == null) { return path; } // TODO: get path while TextPath is set. if (setupFillPaint(paint, 1.0f, getBox(paint, text))) { applyTextPropertiesToPaint(paint); paint.getTextPath(text, 0, text.length(), 0, -paint.ascent(), path); path.transform(mMatrix); } return path; }
@Override protected Path getPath(Canvas canvas, Paint paint) { Path path = new Path(); String text = formatText(); if (text == null) { return path; } if (setupFillPaint(paint, 1.0f, getBox(paint, text))) { applyTextPropertiesToPaint(paint); paint.getTextPath(text, 0, text.length(), 0, -paint.ascent(), path); path.transform(mMatrix); } return path; }
@override protected path getpath(canvas canvas, paint paint) { path path = new path(); string text = formattext(); if (text == null) { return path; } if (setupfillpaint(paint, 1.0f, getbox(paint, text))) { applytextpropertiestopaint(paint); paint.gettextpath(text, 0, text.length(), 0, -paint.ascent(), path); path.transform(mmatrix); } return path; }
L8RMedia/exponent
[ 0, 1, 0, 0 ]
8,573
public void translate() { //TODO: translate code }
public void translate() { }
public void translate() { }
JC-Bodoque/geometric-transformer
[ 0, 1, 0, 0 ]
636
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
@override public <q extends facet> q getfacet(final class<q> facettype) { final q facet = super.getfacet(facettype); q noopfacet = null; if (isnotanoopfacet(facet)) { return facet; } else { noopfacet = facet; } if (interfaces() != null) { final list<objectspecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final objectspecification interfacespec = interfaces.get(i); if (interfacespec == null) { continue; } final q interfacefacet = interfacespec.getfacet(facettype); if (isnotanoopfacet(interfacefacet)) { return interfacefacet; } else { if (noopfacet == null) { noopfacet = interfacefacet; } } } } final objectspecification superspec = superclass(); if (superspec != null) { final q superclassfacet = superspec.getfacet(facettype); if (isnotanoopfacet(superclassfacet)) { return superclassfacet; } } return noopfacet; }
K-Rhen/isis
[ 1, 0, 0, 0 ]
643
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
protected void blast(t message) { logger.debug("blast called for message: " + message); map<string,object> filter = kstringutil.tomap(message.getfilter()); long affinityappid = null; map<string, object> data = createpayloaddata(message); list<d> devicelist = getdevicelist(filter, affinityappid, message.issandbox()); int sendcount = 0; list<string> blasterrors = new arraylist<string>(); list<string> deviceidlist = new arraylist<string>(); for (d device : devicelist) { logger.debug("blast push device: " + device); kpushservice.platform platform = getpushservice().getpushplatform(device.getplatformname(), device.issandbox()); string endpoint = device.getpushendpoint(); if (platform == null || endpoint == null) { continue; } try { getpushservice().publish(platform, endpoint, message.getmessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendcount += 1; deviceidlist.add(device.getid().tostring()); } catch (exception e) { blasterrors.add(e.getmessage()); } } logger.debug("blast: updating sendcount: " + sendcount); if (blasterrors.size() > 0) { logger.warn("broadcast blast errors" + kstringutil.join(blasterrors, "\n\n")); } message.setdevicecount(sendcount); message.setdevices(kstringutil.join(deviceidlist,",").getbytes()); update(message); }
LinuxTek/kona-app-model
[ 0, 0, 1, 0 ]
17,067
protected void closeLayout( ) { //TODO support specified height/width/alignment if ( root != null ) { root.setContentHeight( childHeight ); IStyle areaStyle = root.getStyle( ); int width = getCurrentIP( ) + getOffsetX( ) + getDimensionValue( areaStyle .getProperty( StyleConstants.STYLE_PADDING_RIGHT ) ) + getDimensionValue( areaStyle .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); root.setWidth( width ); int height = 0; Iterator iter = root.getChildren( ); while(iter.hasNext()) { AbstractArea child = (AbstractArea)iter.next( ); height = Math.max( height, child.getAllocatedHeight( )); } root.setContentHeight( height ); } //FIXME verticalAlign may effect the root height. verticalAlign(); }
protected void closeLayout( ) { if ( root != null ) { root.setContentHeight( childHeight ); IStyle areaStyle = root.getStyle( ); int width = getCurrentIP( ) + getOffsetX( ) + getDimensionValue( areaStyle .getProperty( StyleConstants.STYLE_PADDING_RIGHT ) ) + getDimensionValue( areaStyle .getProperty( StyleConstants.STYLE_BORDER_RIGHT_WIDTH ) ); root.setWidth( width ); int height = 0; Iterator iter = root.getChildren( ); while(iter.hasNext()) { AbstractArea child = (AbstractArea)iter.next( ); height = Math.max( height, child.getAllocatedHeight( )); } root.setContentHeight( height ); } verticalAlign(); }
protected void closelayout( ) { if ( root != null ) { root.setcontentheight( childheight ); istyle areastyle = root.getstyle( ); int width = getcurrentip( ) + getoffsetx( ) + getdimensionvalue( areastyle .getproperty( styleconstants.style_padding_right ) ) + getdimensionvalue( areastyle .getproperty( styleconstants.style_border_right_width ) ); root.setwidth( width ); int height = 0; iterator iter = root.getchildren( ); while(iter.hasnext()) { abstractarea child = (abstractarea)iter.next( ); height = math.max( height, child.getallocatedheight( )); } root.setcontentheight( height ); } verticalalign(); }
JamesCao2048/BlizzardData
[ 0, 1, 1, 0 ]
8,889
private void performEnableScreen() { synchronized (mGlobalLock) { if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled + " mForceDisplayEnabled=" + mForceDisplayEnabled + " mShowingBootMessages=" + mShowingBootMessages + " mSystemBooted=" + mSystemBooted + " mOnlyCore=" + mOnlyCore, new RuntimeException("here").fillInStackTrace()); if (mDisplayEnabled) { return; } if (!mSystemBooted && !mShowingBootMessages) { return; } if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) { return; } // Don't enable the screen until all existing windows have been drawn. if (!mForceDisplayEnabled // TODO(multidisplay): Expand to all displays? && getDefaultDisplayContentLocked().checkWaitingForWindows()) { return; } if (!mBootAnimationStopped) { Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0); // stop boot animation // formerly we would just kill the process, but we now ask it to exit so it // can choose where to stop the animation. SystemProperties.set("service.bootanim.exit", "1"); mBootAnimationStopped = true; } if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) { if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: Waiting for anim complete"); return; } try { IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger"); if (surfaceFlinger != null) { Slog.i(TAG_WM, "******* TELLING SURFACE FLINGER WE ARE BOOTED!"); Parcel data = Parcel.obtain(); data.writeInterfaceToken("android.ui.ISurfaceComposer"); surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION, // BOOT_FINISHED data, null, 0); data.recycle(); } } catch (RemoteException ex) { Slog.e(TAG_WM, "Boot completed: SurfaceFlinger is dead!"); } EventLog.writeEvent(EventLogTags.WM_BOOT_ANIMATION_DONE, SystemClock.uptimeMillis()); Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0); mDisplayEnabled = true; if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG_WM, "******************** ENABLING SCREEN!"); // Enable input dispatch. mInputManagerCallback.setEventDispatchingLw(mEventDispatchingEnabled); } try { mActivityManager.bootAnimationComplete(); } catch (RemoteException e) { } mPolicy.enableScreenAfterBoot(); // Make sure the last requested orientation has been applied. updateRotationUnchecked(false, false); }
private void performEnableScreen() { synchronized (mGlobalLock) { if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled + " mForceDisplayEnabled=" + mForceDisplayEnabled + " mShowingBootMessages=" + mShowingBootMessages + " mSystemBooted=" + mSystemBooted + " mOnlyCore=" + mOnlyCore, new RuntimeException("here").fillInStackTrace()); if (mDisplayEnabled) { return; } if (!mSystemBooted && !mShowingBootMessages) { return; } if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) { return; } if (!mForceDisplayEnabled && getDefaultDisplayContentLocked().checkWaitingForWindows()) { return; } if (!mBootAnimationStopped) { Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0); SystemProperties.set("service.bootanim.exit", "1"); mBootAnimationStopped = true; } if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) { if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: Waiting for anim complete"); return; } try { IBinder surfaceFlinger = ServiceManager.getService("SurfaceFlinger"); if (surfaceFlinger != null) { Slog.i(TAG_WM, "******* TELLING SURFACE FLINGER WE ARE BOOTED!"); Parcel data = Parcel.obtain(); data.writeInterfaceToken("android.ui.ISurfaceComposer"); surfaceFlinger.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0); data.recycle(); } } catch (RemoteException ex) { Slog.e(TAG_WM, "Boot completed: SurfaceFlinger is dead!"); } EventLog.writeEvent(EventLogTags.WM_BOOT_ANIMATION_DONE, SystemClock.uptimeMillis()); Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER, "Stop bootanim", 0); mDisplayEnabled = true; if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG_WM, "******************** ENABLING SCREEN!"); mInputManagerCallback.setEventDispatchingLw(mEventDispatchingEnabled); } try { mActivityManager.bootAnimationComplete(); } catch (RemoteException e) { } mPolicy.enableScreenAfterBoot(); updateRotationUnchecked(false, false); }
private void performenablescreen() { synchronized (mgloballock) { if (debug_boot) slog.i(tag_wm, "performenablescreen: mdisplayenabled=" + mdisplayenabled + " mforcedisplayenabled=" + mforcedisplayenabled + " mshowingbootmessages=" + mshowingbootmessages + " msystembooted=" + msystembooted + " monlycore=" + monlycore, new runtimeexception("here").fillinstacktrace()); if (mdisplayenabled) { return; } if (!msystembooted && !mshowingbootmessages) { return; } if (!mshowingbootmessages && !mpolicy.candismissbootanimation()) { return; } if (!mforcedisplayenabled && getdefaultdisplaycontentlocked().checkwaitingforwindows()) { return; } if (!mbootanimationstopped) { trace.asynctracebegin(trace_tag_window_manager, "stop bootanim", 0); systemproperties.set("service.bootanim.exit", "1"); mbootanimationstopped = true; } if (!mforcedisplayenabled && !checkbootanimationcompletelocked()) { if (debug_boot) slog.i(tag_wm, "performenablescreen: waiting for anim complete"); return; } try { ibinder surfaceflinger = servicemanager.getservice("surfaceflinger"); if (surfaceflinger != null) { slog.i(tag_wm, "******* telling surface flinger we are booted!"); parcel data = parcel.obtain(); data.writeinterfacetoken("android.ui.isurfacecomposer"); surfaceflinger.transact(ibinder.first_call_transaction, data, null, 0); data.recycle(); } } catch (remoteexception ex) { slog.e(tag_wm, "boot completed: surfaceflinger is dead!"); } eventlog.writeevent(eventlogtags.wm_boot_animation_done, systemclock.uptimemillis()); trace.asynctraceend(trace_tag_window_manager, "stop bootanim", 0); mdisplayenabled = true; if (debug_screen_on || debug_boot) slog.i(tag_wm, "******************** enabling screen!"); minputmanagercallback.seteventdispatchinglw(meventdispatchingenabled); } try { mactivitymanager.bootanimationcomplete(); } catch (remoteexception e) { } mpolicy.enablescreenafterboot(); updaterotationunchecked(false, false); }
LynzhX/android_frameworks_base-1
[ 1, 0, 0, 0 ]
8,894
boolean viewServerGetFocusedWindow(Socket client) { if (isSystemSecure()) { return false; } boolean result = true; WindowState focusedWindow = getFocusedWindow(); BufferedWriter out = null; // Any uncaught exception will crash the system process try { OutputStream clientStream = client.getOutputStream(); out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024); if(focusedWindow != null) { out.write(Integer.toHexString(System.identityHashCode(focusedWindow))); out.write(' '); out.append(focusedWindow.mAttrs.getTitle()); } out.write('\n'); out.flush(); } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }
boolean viewServerGetFocusedWindow(Socket client) { if (isSystemSecure()) { return false; } boolean result = true; WindowState focusedWindow = getFocusedWindow(); BufferedWriter out = null; try { OutputStream clientStream = client.getOutputStream(); out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024); if(focusedWindow != null) { out.write(Integer.toHexString(System.identityHashCode(focusedWindow))); out.write(' '); out.append(focusedWindow.mAttrs.getTitle()); } out.write('\n'); out.flush(); } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }
boolean viewservergetfocusedwindow(socket client) { if (issystemsecure()) { return false; } boolean result = true; windowstate focusedwindow = getfocusedwindow(); bufferedwriter out = null; try { outputstream clientstream = client.getoutputstream(); out = new bufferedwriter(new outputstreamwriter(clientstream), 8 * 1024); if(focusedwindow != null) { out.write(integer.tohexstring(system.identityhashcode(focusedwindow))); out.write(' '); out.append(focusedwindow.mattrs.gettitle()); } out.write('\n'); out.flush(); } catch (exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (ioexception e) { result = false; } } } return result; }
LynzhX/android_frameworks_base-1
[ 0, 1, 0, 0 ]
17,124
@Test public void simpleEndpointReturnsPostsWithoutTransformation() { //This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test //Given ForumPosts posts = generateTestPosts(); when(exampleApiService.getPosts()).thenReturn(posts); //When ForumPosts controllerOutput = exerciseController.posts(); //Then assertEquals(controllerOutput.size(), 2); assertTrue(controllerOutput.get(0).getTitle().contains("Test")); }
@Test public void simpleEndpointReturnsPostsWithoutTransformation() { ForumPosts posts = generateTestPosts(); when(exampleApiService.getPosts()).thenReturn(posts); ForumPosts controllerOutput = exerciseController.posts(); assertEquals(controllerOutput.size(), 2); assertTrue(controllerOutput.get(0).getTitle().contains("Test")); }
@test public void simpleendpointreturnspostswithouttransformation() { forumposts posts = generatetestposts(); when(exampleapiservice.getposts()).thenreturn(posts); forumposts controlleroutput = exercisecontroller.posts(); assertequals(controlleroutput.size(), 2); asserttrue(controlleroutput.get(0).gettitle().contains("test")); }
JoseAlban/etc
[ 0, 0, 0, 1 ]
17,125
@Test public void transformedEndpointReturnsPostsWithCurrentDate() { //This unit-test class is the wrong place to test that behaviour, unless it becomes an integration test //Given TransformedForumPosts transformed = generateTransformedTestPosts(); when(exampleApiService.getTransformedPosts()).thenReturn(transformed); //When TransformedForumPosts controllerOutput = exerciseController.transformed(); //Then assertEquals(controllerOutput.size(), 2); assertTrue(controllerOutput.get(0).getTitle().contains("Test")); assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST")); assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d")); }
@Test public void transformedEndpointReturnsPostsWithCurrentDate() { TransformedForumPosts transformed = generateTransformedTestPosts(); when(exampleApiService.getTransformedPosts()).thenReturn(transformed); TransformedForumPosts controllerOutput = exerciseController.transformed(); assertEquals(controllerOutput.size(), 2); assertTrue(controllerOutput.get(0).getTitle().contains("Test")); assertTrue(controllerOutput.get(0).getUppercaseTitle().contains("TEST")); assertTrue(controllerOutput.get(0).getPostDate().matches("\\d{4}-[01]\\d-[0-3]\\d")); }
@test public void transformedendpointreturnspostswithcurrentdate() { transformedforumposts transformed = generatetransformedtestposts(); when(exampleapiservice.gettransformedposts()).thenreturn(transformed); transformedforumposts controlleroutput = exercisecontroller.transformed(); assertequals(controlleroutput.size(), 2); asserttrue(controlleroutput.get(0).gettitle().contains("test")); asserttrue(controlleroutput.get(0).getuppercasetitle().contains("test")); asserttrue(controlleroutput.get(0).getpostdate().matches("\\d{4}-[01]\\d-[0-3]\\d")); }
JoseAlban/etc
[ 0, 0, 0, 1 ]
33,512
@Override public void doServerTick(World world) { super.doServerTick(world); Entity rider = entity.getControllingPassenger(); pokemob.setGeneralState(GeneralStates.CONTROLLED, rider != null); if (rider == null) return; Config config = PokecubeCore.instance.getConfig(); boolean move = false; entity.rotationYaw = pokemob.getHeading(); boolean shouldControl = entity.onGround || pokemob.floats(); boolean verticalControl = false; boolean waterSpeed = false; boolean airSpeed = !entity.onGround; boolean canFly = pokemob.canUseFly(); boolean canSurf = pokemob.canUseSurf(); boolean canDive = pokemob.canUseDive(); if (rider instanceof EntityPlayerMP) { EntityPlayer player = (EntityPlayer) rider; IPermissionHandler handler = PermissionAPI.getPermissionHandler(); PlayerContext context = new PlayerContext(player); PokedexEntry entry = pokemob.getPokedexEntry(); if (config.permsFly && canFly && !handler.hasPermission(player.getGameProfile(), Permissions.FLYPOKEMOB, context)) { canFly = false; } if (config.permsFlySpecific && canFly && !handler.hasPermission(player.getGameProfile(), Permissions.FLYSPECIFIC.get(entry), context)) { canFly = false; } if (config.permsSurf && canSurf && !handler.hasPermission(player.getGameProfile(), Permissions.SURFPOKEMOB, context)) { canSurf = false; } if (config.permsSurfSpecific && canSurf && !handler.hasPermission(player.getGameProfile(), Permissions.SURFSPECIFIC.get(entry), context)) { canSurf = false; } if (config.permsDive && canDive && !handler.hasPermission(player.getGameProfile(), Permissions.DIVEPOKEMOB, context)) { canDive = false; } if (config.permsDiveSpecific && canDive && !handler.hasPermission(player.getGameProfile(), Permissions.DIVESPECIFIC.get(entry), context)) { canDive = false; } } if (canFly) for (int i = 0; i < PokecubeMod.core.getConfig().flyDimBlacklist.length; i++) if (PokecubeMod.core.getConfig().flyDimBlacklist[i] == world.provider.getDimension()) { canFly = false; break; } if (canFly) shouldControl = verticalControl = PokecubeMod.core.getConfig().flyEnabled || shouldControl; if ((canSurf || canDive) && (waterSpeed = entity.isInWater())) shouldControl = verticalControl = PokecubeMod.core.getConfig().surfEnabled || shouldControl; if (waterSpeed) airSpeed = false; Entity controller = rider; if (pokemob.getPokedexEntry().shouldDive) { PotionEffect vision = new PotionEffect(Potion.getPotionFromResourceLocation("night_vision"), 300, 1, true, false); ItemStack stack = new ItemStack(Blocks.BARRIER); vision.setCurativeItems(Lists.newArrayList(stack)); for (Entity e : entity.getRecursivePassengers()) { if (e instanceof EntityLivingBase) { if (entity.isInWater()) { ((EntityLivingBase) e).addPotionEffect(vision); ((EntityLivingBase) e).setAir(300); } else((EntityLivingBase) e).curePotionEffects(stack); } } } float speedFactor = (float) (1 + Math.sqrt(pokemob.getPokedexEntry().getStatVIT()) / (10F)); float moveSpeed = (float) (0.25f * throttle * speedFactor); if (forwardInputDown) { move = true; float f = moveSpeed / 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; if (shouldControl) { if (!entity.onGround) f *= 2; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } } if (backInputDown) { move = true; float f = -moveSpeed / 4; if (shouldControl) { if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } } if (upInputDown) { if (entity.onGround) { entity.getJumpHelper().setJumping(); } else if (verticalControl) { entity.motionY += 0.1 * throttle; } else if (entity.isInLava() || entity.isInWater()) { entity.motionY += 0.05 * throttle; } } if (downInputDown) { if (verticalControl && !entity.onGround) { entity.motionY -= 0.1 * throttle; } } else if (!verticalControl && !entity.onGround) { entity.motionY -= 0.1; } if (!followOwnerLook) {// TODO some way to make this change based on how long button is held? if (leftInputDown) { pokemob.setHeading(pokemob.getHeading() - 5); } if (rightInputDown) { pokemob.setHeading(pokemob.getHeading() + 5); } } else if (!entity.getPassengers().isEmpty()) { pokemob.setHeading(controller.rotationYaw); float f = moveSpeed / 2; if (leftInputDown) { move = true; if (shouldControl) { if (!entity.onGround) f *= 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } } if (rightInputDown) { move = true; if (shouldControl) { if (!entity.onGround) f *= 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } } } if (!move) { entity.motionX *= 0.5; entity.motionZ *= 0.5; } // Sync the rotations. entity.setRenderYawOffset(pokemob.getHeading()); entity.setRotationYawHead(pokemob.getHeading()); }
@Override public void doServerTick(World world) { super.doServerTick(world); Entity rider = entity.getControllingPassenger(); pokemob.setGeneralState(GeneralStates.CONTROLLED, rider != null); if (rider == null) return; Config config = PokecubeCore.instance.getConfig(); boolean move = false; entity.rotationYaw = pokemob.getHeading(); boolean shouldControl = entity.onGround || pokemob.floats(); boolean verticalControl = false; boolean waterSpeed = false; boolean airSpeed = !entity.onGround; boolean canFly = pokemob.canUseFly(); boolean canSurf = pokemob.canUseSurf(); boolean canDive = pokemob.canUseDive(); if (rider instanceof EntityPlayerMP) { EntityPlayer player = (EntityPlayer) rider; IPermissionHandler handler = PermissionAPI.getPermissionHandler(); PlayerContext context = new PlayerContext(player); PokedexEntry entry = pokemob.getPokedexEntry(); if (config.permsFly && canFly && !handler.hasPermission(player.getGameProfile(), Permissions.FLYPOKEMOB, context)) { canFly = false; } if (config.permsFlySpecific && canFly && !handler.hasPermission(player.getGameProfile(), Permissions.FLYSPECIFIC.get(entry), context)) { canFly = false; } if (config.permsSurf && canSurf && !handler.hasPermission(player.getGameProfile(), Permissions.SURFPOKEMOB, context)) { canSurf = false; } if (config.permsSurfSpecific && canSurf && !handler.hasPermission(player.getGameProfile(), Permissions.SURFSPECIFIC.get(entry), context)) { canSurf = false; } if (config.permsDive && canDive && !handler.hasPermission(player.getGameProfile(), Permissions.DIVEPOKEMOB, context)) { canDive = false; } if (config.permsDiveSpecific && canDive && !handler.hasPermission(player.getGameProfile(), Permissions.DIVESPECIFIC.get(entry), context)) { canDive = false; } } if (canFly) for (int i = 0; i < PokecubeMod.core.getConfig().flyDimBlacklist.length; i++) if (PokecubeMod.core.getConfig().flyDimBlacklist[i] == world.provider.getDimension()) { canFly = false; break; } if (canFly) shouldControl = verticalControl = PokecubeMod.core.getConfig().flyEnabled || shouldControl; if ((canSurf || canDive) && (waterSpeed = entity.isInWater())) shouldControl = verticalControl = PokecubeMod.core.getConfig().surfEnabled || shouldControl; if (waterSpeed) airSpeed = false; Entity controller = rider; if (pokemob.getPokedexEntry().shouldDive) { PotionEffect vision = new PotionEffect(Potion.getPotionFromResourceLocation("night_vision"), 300, 1, true, false); ItemStack stack = new ItemStack(Blocks.BARRIER); vision.setCurativeItems(Lists.newArrayList(stack)); for (Entity e : entity.getRecursivePassengers()) { if (e instanceof EntityLivingBase) { if (entity.isInWater()) { ((EntityLivingBase) e).addPotionEffect(vision); ((EntityLivingBase) e).setAir(300); } else((EntityLivingBase) e).curePotionEffects(stack); } } } float speedFactor = (float) (1 + Math.sqrt(pokemob.getPokedexEntry().getStatVIT()) / (10F)); float moveSpeed = (float) (0.25f * throttle * speedFactor); if (forwardInputDown) { move = true; float f = moveSpeed / 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; if (shouldControl) { if (!entity.onGround) f *= 2; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } } if (backInputDown) { move = true; float f = -moveSpeed / 4; if (shouldControl) { if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX += MathHelper.sin(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.cos(entity.rotationYaw * 0.017453292F) * f; } } if (upInputDown) { if (entity.onGround) { entity.getJumpHelper().setJumping(); } else if (verticalControl) { entity.motionY += 0.1 * throttle; } else if (entity.isInLava() || entity.isInWater()) { entity.motionY += 0.05 * throttle; } } if (downInputDown) { if (verticalControl && !entity.onGround) { entity.motionY -= 0.1 * throttle; } } else if (!verticalControl && !entity.onGround) { entity.motionY -= 0.1; } if (!followOwnerLook) if (leftInputDown) { pokemob.setHeading(pokemob.getHeading() - 5); } if (rightInputDown) { pokemob.setHeading(pokemob.getHeading() + 5); } } else if (!entity.getPassengers().isEmpty()) { pokemob.setHeading(controller.rotationYaw); float f = moveSpeed / 2; if (leftInputDown) { move = true; if (shouldControl) { if (!entity.onGround) f *= 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX += MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ += MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } } if (rightInputDown) { move = true; if (shouldControl) { if (!entity.onGround) f *= 2; if (airSpeed) f *= config.flySpeedFactor; else if (waterSpeed) f *= config.surfSpeedFactor; else f *= config.groundSpeedFactor; entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } else if (entity.isInLava() || entity.isInWater()) { f *= 0.1; entity.motionX -= MathHelper.cos(-entity.rotationYaw * 0.017453292F) * f; entity.motionZ -= MathHelper.sin(entity.rotationYaw * 0.017453292F) * f; } } } if (!move) { entity.motionX *= 0.5; entity.motionZ *= 0.5; } entity.setRenderYawOffset(pokemob.getHeading()); entity.setRotationYawHead(pokemob.getHeading()); }
@override public void doservertick(world world) { super.doservertick(world); entity rider = entity.getcontrollingpassenger(); pokemob.setgeneralstate(generalstates.controlled, rider != null); if (rider == null) return; config config = pokecubecore.instance.getconfig(); boolean move = false; entity.rotationyaw = pokemob.getheading(); boolean shouldcontrol = entity.onground || pokemob.floats(); boolean verticalcontrol = false; boolean waterspeed = false; boolean airspeed = !entity.onground; boolean canfly = pokemob.canusefly(); boolean cansurf = pokemob.canusesurf(); boolean candive = pokemob.canusedive(); if (rider instanceof entityplayermp) { entityplayer player = (entityplayer) rider; ipermissionhandler handler = permissionapi.getpermissionhandler(); playercontext context = new playercontext(player); pokedexentry entry = pokemob.getpokedexentry(); if (config.permsfly && canfly && !handler.haspermission(player.getgameprofile(), permissions.flypokemob, context)) { canfly = false; } if (config.permsflyspecific && canfly && !handler.haspermission(player.getgameprofile(), permissions.flyspecific.get(entry), context)) { canfly = false; } if (config.permssurf && cansurf && !handler.haspermission(player.getgameprofile(), permissions.surfpokemob, context)) { cansurf = false; } if (config.permssurfspecific && cansurf && !handler.haspermission(player.getgameprofile(), permissions.surfspecific.get(entry), context)) { cansurf = false; } if (config.permsdive && candive && !handler.haspermission(player.getgameprofile(), permissions.divepokemob, context)) { candive = false; } if (config.permsdivespecific && candive && !handler.haspermission(player.getgameprofile(), permissions.divespecific.get(entry), context)) { candive = false; } } if (canfly) for (int i = 0; i < pokecubemod.core.getconfig().flydimblacklist.length; i++) if (pokecubemod.core.getconfig().flydimblacklist[i] == world.provider.getdimension()) { canfly = false; break; } if (canfly) shouldcontrol = verticalcontrol = pokecubemod.core.getconfig().flyenabled || shouldcontrol; if ((cansurf || candive) && (waterspeed = entity.isinwater())) shouldcontrol = verticalcontrol = pokecubemod.core.getconfig().surfenabled || shouldcontrol; if (waterspeed) airspeed = false; entity controller = rider; if (pokemob.getpokedexentry().shoulddive) { potioneffect vision = new potioneffect(potion.getpotionfromresourcelocation("night_vision"), 300, 1, true, false); itemstack stack = new itemstack(blocks.barrier); vision.setcurativeitems(lists.newarraylist(stack)); for (entity e : entity.getrecursivepassengers()) { if (e instanceof entitylivingbase) { if (entity.isinwater()) { ((entitylivingbase) e).addpotioneffect(vision); ((entitylivingbase) e).setair(300); } else((entitylivingbase) e).curepotioneffects(stack); } } } float speedfactor = (float) (1 + math.sqrt(pokemob.getpokedexentry().getstatvit()) / (10f)); float movespeed = (float) (0.25f * throttle * speedfactor); if (forwardinputdown) { move = true; float f = movespeed / 2; if (airspeed) f *= config.flyspeedfactor; else if (waterspeed) f *= config.surfspeedfactor; else f *= config.groundspeedfactor; if (shouldcontrol) { if (!entity.onground) f *= 2; entity.motionx += mathhelper.sin(-entity.rotationyaw * 0.017453292f) * f; entity.motionz += mathhelper.cos(entity.rotationyaw * 0.017453292f) * f; } else if (entity.isinlava() || entity.isinwater()) { f *= 0.1; entity.motionx += mathhelper.sin(-entity.rotationyaw * 0.017453292f) * f; entity.motionz += mathhelper.cos(entity.rotationyaw * 0.017453292f) * f; } } if (backinputdown) { move = true; float f = -movespeed / 4; if (shouldcontrol) { if (airspeed) f *= config.flyspeedfactor; else if (waterspeed) f *= config.surfspeedfactor; else f *= config.groundspeedfactor; entity.motionx += mathhelper.sin(-entity.rotationyaw * 0.017453292f) * f; entity.motionz += mathhelper.cos(entity.rotationyaw * 0.017453292f) * f; } } if (upinputdown) { if (entity.onground) { entity.getjumphelper().setjumping(); } else if (verticalcontrol) { entity.motiony += 0.1 * throttle; } else if (entity.isinlava() || entity.isinwater()) { entity.motiony += 0.05 * throttle; } } if (downinputdown) { if (verticalcontrol && !entity.onground) { entity.motiony -= 0.1 * throttle; } } else if (!verticalcontrol && !entity.onground) { entity.motiony -= 0.1; } if (!followownerlook) if (leftinputdown) { pokemob.setheading(pokemob.getheading() - 5); } if (rightinputdown) { pokemob.setheading(pokemob.getheading() + 5); } } else if (!entity.getpassengers().isempty()) { pokemob.setheading(controller.rotationyaw); float f = movespeed / 2; if (leftinputdown) { move = true; if (shouldcontrol) { if (!entity.onground) f *= 2; if (airspeed) f *= config.flyspeedfactor; else if (waterspeed) f *= config.surfspeedfactor; else f *= config.groundspeedfactor; entity.motionx += mathhelper.cos(-entity.rotationyaw * 0.017453292f) * f; entity.motionz += mathhelper.sin(entity.rotationyaw * 0.017453292f) * f; } else if (entity.isinlava() || entity.isinwater()) { f *= 0.1; entity.motionx += mathhelper.cos(-entity.rotationyaw * 0.017453292f) * f; entity.motionz += mathhelper.sin(entity.rotationyaw * 0.017453292f) * f; } } if (rightinputdown) { move = true; if (shouldcontrol) { if (!entity.onground) f *= 2; if (airspeed) f *= config.flyspeedfactor; else if (waterspeed) f *= config.surfspeedfactor; else f *= config.groundspeedfactor; entity.motionx -= mathhelper.cos(-entity.rotationyaw * 0.017453292f) * f; entity.motionz -= mathhelper.sin(entity.rotationyaw * 0.017453292f) * f; } else if (entity.isinlava() || entity.isinwater()) { f *= 0.1; entity.motionx -= mathhelper.cos(-entity.rotationyaw * 0.017453292f) * f; entity.motionz -= mathhelper.sin(entity.rotationyaw * 0.017453292f) * f; } } } if (!move) { entity.motionx *= 0.5; entity.motionz *= 0.5; } entity.setrenderyawoffset(pokemob.getheading()); entity.setrotationyawhead(pokemob.getheading()); }
Pokecube-Development/Pokecube-Core
[ 1, 0, 0, 0 ]
17,267
public void split (FeatureSelection fs) { if (ilist == null) throw new IllegalStateException ("Frozen. Cannot split."); InstanceList ilist0 = new InstanceList (ilist.getPipe()); InstanceList ilist1 = new InstanceList (ilist.getPipe()); for (int i = 0; i < ilist.size(); i++) { Instance instance = ilist.getInstance(i); FeatureVector fv = (FeatureVector) instance.getData (); // xxx What test should this be? What to do with negative values? // Whatever is decided here should also go in InfoGain.calcInfoGains() if (fv.value (featureIndex) != 0) { //System.out.println ("list1 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i)); ilist1.add (instance, ilist.getInstanceWeight(i)); } else { //System.out.println ("list0 add "+instance.getUri()+" weight="+ilist.getInstanceWeight(i)); ilist0.add (instance, ilist.getInstanceWeight(i)); } } logger.info("child0="+ilist0.size()+" child1="+ilist1.size()); child0 = new Node (ilist0, this, fs); child1 = new Node (ilist1, this, fs); }
public void split (FeatureSelection fs) { if (ilist == null) throw new IllegalStateException ("Frozen. Cannot split."); InstanceList ilist0 = new InstanceList (ilist.getPipe()); InstanceList ilist1 = new InstanceList (ilist.getPipe()); for (int i = 0; i < ilist.size(); i++) { Instance instance = ilist.getInstance(i); FeatureVector fv = (FeatureVector) instance.getData (); if (fv.value (featureIndex) != 0) { ilist1.add (instance, ilist.getInstanceWeight(i)); } else { ilist0.add (instance, ilist.getInstanceWeight(i)); } } logger.info("child0="+ilist0.size()+" child1="+ilist1.size()); child0 = new Node (ilist0, this, fs); child1 = new Node (ilist1, this, fs); }
public void split (featureselection fs) { if (ilist == null) throw new illegalstateexception ("frozen. cannot split."); instancelist ilist0 = new instancelist (ilist.getpipe()); instancelist ilist1 = new instancelist (ilist.getpipe()); for (int i = 0; i < ilist.size(); i++) { instance instance = ilist.getinstance(i); featurevector fv = (featurevector) instance.getdata (); if (fv.value (featureindex) != 0) { ilist1.add (instance, ilist.getinstanceweight(i)); } else { ilist0.add (instance, ilist.getinstanceweight(i)); } } logger.info("child0="+ilist0.size()+" child1="+ilist1.size()); child0 = new node (ilist0, this, fs); child1 = new node (ilist1, this, fs); }
JULIELab/jcore-dependencies
[ 0, 0, 0, 1 ]
25,541
Uri findNext() { // TODO: Unify with searchSubtitles() if (mPrefs.scopeUri != null || isTvBox) { DocumentFile video = null; File videoRaw = null; if (!isTvBox && mPrefs.scopeUri != null) { if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) { // Fast search based on path in uri video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri); } else { // Slow search based on matching metadata, no path in uri // Provider "com.android.providers.media.documents" when using "Videos" tab in file picker DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri); DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri); video = SubtitleUtils.findDocInScope(fileScope, fileMedia); } } else if (isTvBox) { videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart()); video = DocumentFile.fromFile(videoRaw); } if (video != null) { DocumentFile next; if (!isTvBox) { next = SubtitleUtils.findNext(video); } else { File parentRaw = videoRaw.getParentFile(); DocumentFile dir = DocumentFile.fromFile(parentRaw); next = SubtitleUtils.findNext(video, dir); } if (next != null) { return next.getUri(); } } } return null; }
Uri findNext() { if (mPrefs.scopeUri != null || isTvBox) { DocumentFile video = null; File videoRaw = null; if (!isTvBox && mPrefs.scopeUri != null) { if ("com.android.externalstorage.documents".equals(mPrefs.mediaUri.getHost())) { video = SubtitleUtils.findUriInScope(this, mPrefs.scopeUri, mPrefs.mediaUri); } else { DocumentFile fileScope = DocumentFile.fromTreeUri(this, mPrefs.scopeUri); DocumentFile fileMedia = DocumentFile.fromSingleUri(this, mPrefs.mediaUri); video = SubtitleUtils.findDocInScope(fileScope, fileMedia); } } else if (isTvBox) { videoRaw = new File(mPrefs.mediaUri.getSchemeSpecificPart()); video = DocumentFile.fromFile(videoRaw); } if (video != null) { DocumentFile next; if (!isTvBox) { next = SubtitleUtils.findNext(video); } else { File parentRaw = videoRaw.getParentFile(); DocumentFile dir = DocumentFile.fromFile(parentRaw); next = SubtitleUtils.findNext(video, dir); } if (next != null) { return next.getUri(); } } } return null; }
uri findnext() { if (mprefs.scopeuri != null || istvbox) { documentfile video = null; file videoraw = null; if (!istvbox && mprefs.scopeuri != null) { if ("com.android.externalstorage.documents".equals(mprefs.mediauri.gethost())) { video = subtitleutils.finduriinscope(this, mprefs.scopeuri, mprefs.mediauri); } else { documentfile filescope = documentfile.fromtreeuri(this, mprefs.scopeuri); documentfile filemedia = documentfile.fromsingleuri(this, mprefs.mediauri); video = subtitleutils.finddocinscope(filescope, filemedia); } } else if (istvbox) { videoraw = new file(mprefs.mediauri.getschemespecificpart()); video = documentfile.fromfile(videoraw); } if (video != null) { documentfile next; if (!istvbox) { next = subtitleutils.findnext(video); } else { file parentraw = videoraw.getparentfile(); documentfile dir = documentfile.fromfile(parentraw); next = subtitleutils.findnext(video, dir); } if (next != null) { return next.geturi(); } } } return null; }
Radfanyemen/Player
[ 0, 1, 0, 0 ]
17,459
private void mOSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mOSActionPerformed // TODO add your handling code here: // new ViewOrdemServico().setVisible(true); }
private void mOSActionPerformed(java.awt.event.ActionEvent evt) { }
private void mosactionperformed(java.awt.event.actionevent evt) { }
LeandroDosSantosPereira/sistemaBarbearia
[ 0, 1, 0, 0 ]
9,278
@SubscribeEvent(priority = EventPriority.NORMAL) public void onRenderOverlay(RenderGameOverlayEvent.Post event) { /* if (event.getType() != RenderGameOverlayEvent.ElementType.CROSSHAIRS) { return; } FIXME: still needed? if so, search for ported way */ ItemStack activeStack = mc.player.getUseItem(); if (activeStack.getItem() instanceof ModularCrossbowItem) { ModularCrossbowItem item = (ModularCrossbowItem) activeStack.getItem(); gui.setProgress(item.getProgress(activeStack, mc.player), 0); } else { gui.setProgress(0, 0); } gui.draw(); }
@SubscribeEvent(priority = EventPriority.NORMAL) public void onRenderOverlay(RenderGameOverlayEvent.Post event) { ItemStack activeStack = mc.player.getUseItem(); if (activeStack.getItem() instanceof ModularCrossbowItem) { ModularCrossbowItem item = (ModularCrossbowItem) activeStack.getItem(); gui.setProgress(item.getProgress(activeStack, mc.player), 0); } else { gui.setProgress(0, 0); } gui.draw(); }
@subscribeevent(priority = eventpriority.normal) public void onrenderoverlay(rendergameoverlayevent.post event) { itemstack activestack = mc.player.getuseitem(); if (activestack.getitem() instanceof modularcrossbowitem) { modularcrossbowitem item = (modularcrossbowitem) activestack.getitem(); gui.setprogress(item.getprogress(activestack, mc.player), 0); } else { gui.setprogress(0, 0); } gui.draw(); }
LordGrimmauld/tetra
[ 1, 0, 0, 0 ]
33,945
public static boolean isAlphabetic(String s) { if (isEmpty(s)) return defaultEmptyOK; // Search through string's characters one by one // until we find a non-alphabetic character. // When we do, return false; if we don't, return true. for (int i = 0; i < s.length(); i++) { // Check that current character is letter. char c = s.charAt(i); if (!isLetter(c)) return false; } // All characters are letters. return true; }
public static boolean isAlphabetic(String s) { if (isEmpty(s)) return defaultEmptyOK; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!isLetter(c)) return false; } return true; }
public static boolean isalphabetic(string s) { if (isempty(s)) return defaultemptyok; for (int i = 0; i < s.length(); i++) { char c = s.charat(i); if (!isletter(c)) return false; } return true; }
Mark110/e-commerce
[ 1, 0, 0, 0 ]
17,649
private void rollupParameters(TLParamGroup sourceParamGroup, TLParamGroup targetParamGroup, RollupReferenceHandler referenceHandler, ModelElementCloner cloner) { for (TLParameter sourceParam : sourceParamGroup.getParameters()) { TLMemberField<?> sourceFieldRef = sourceParam.getFieldRef(); if (sourceFieldRef != null) { TLParameter targetParam = targetParamGroup.getParameter( sourceFieldRef.getName() ); if (targetParam == null) { targetParam = cloner.clone( sourceParam ); // TODO: After cloning, targetParam.fieldRef is null targetParamGroup.addParameter( targetParam ); referenceHandler.captureRollupReferences( targetParam ); } if (targetParam.getDocumentation() == null) { targetParam.setDocumentation( cloner.clone( sourceParam.getDocumentation() ) ); } } } }
private void rollupParameters(TLParamGroup sourceParamGroup, TLParamGroup targetParamGroup, RollupReferenceHandler referenceHandler, ModelElementCloner cloner) { for (TLParameter sourceParam : sourceParamGroup.getParameters()) { TLMemberField<?> sourceFieldRef = sourceParam.getFieldRef(); if (sourceFieldRef != null) { TLParameter targetParam = targetParamGroup.getParameter( sourceFieldRef.getName() ); if (targetParam == null) { targetParam = cloner.clone( sourceParam ); targetParamGroup.addParameter( targetParam ); referenceHandler.captureRollupReferences( targetParam ); } if (targetParam.getDocumentation() == null) { targetParam.setDocumentation( cloner.clone( sourceParam.getDocumentation() ) ); } } } }
private void rollupparameters(tlparamgroup sourceparamgroup, tlparamgroup targetparamgroup, rollupreferencehandler referencehandler, modelelementcloner cloner) { for (tlparameter sourceparam : sourceparamgroup.getparameters()) { tlmemberfield<?> sourcefieldref = sourceparam.getfieldref(); if (sourcefieldref != null) { tlparameter targetparam = targetparamgroup.getparameter( sourcefieldref.getname() ); if (targetparam == null) { targetparam = cloner.clone( sourceparam ); targetparamgroup.addparameter( targetparam ); referencehandler.capturerollupreferences( targetparam ); } if (targetparam.getdocumentation() == null) { targetparam.setdocumentation( cloner.clone( sourceparam.getdocumentation() ) ); } } } }
OpenTravel/OTM-DE-Compiler
[ 0, 1, 0, 0 ]
9,475
private static List<TestConfiguration> getAdditionalConfigurations(Activity activity) { List<TestConfiguration> additionalConfigurations = new ArrayList<>(); if (Constants.USE_GMS_CONFIGURATION) { additionalConfigurations.add(new GmsPermissionConfiguration(activity)); } // TODO: Any custom configurations that are intended to be run as part of this test should // be added here. return additionalConfigurations; }
private static List<TestConfiguration> getAdditionalConfigurations(Activity activity) { List<TestConfiguration> additionalConfigurations = new ArrayList<>(); if (Constants.USE_GMS_CONFIGURATION) { additionalConfigurations.add(new GmsPermissionConfiguration(activity)); } return additionalConfigurations; }
private static list<testconfiguration> getadditionalconfigurations(activity activity) { list<testconfiguration> additionalconfigurations = new arraylist<>(); if (constants.use_gms_configuration) { additionalconfigurations.add(new gmspermissionconfiguration(activity)); } return additionalconfigurations; }
LaudateCorpus1/security-certification-resources
[ 1, 0, 0, 0 ]
9,644
@Override public void simpleRender(RenderManager rm) { //TODO: add render code }
@Override public void simpleRender(RenderManager rm) { }
@override public void simplerender(rendermanager rm) { }
MeFisto94/test-bot-1
[ 0, 1, 0, 0 ]
9,670
public int applyLayers(int[] data) { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockStateHolder<BlockState> tmpBlock = BlockTypes.AIR.getDefaultState(); int maxY4 = maxY << 4; int index = 0; // Apply heightmap for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; //Clamp newHeight within the selection area int newHeight = Math.min(maxY4, data[index++]); int curBlock = (curHeight) >> 4; int newBlock = (newHeight + 15) >> 4; // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { // Grow -- start from 1 below top replacing airblocks for (int setY = newBlock - 1, getY = curBlock; setY >= curBlock; --setY, getY--) { BlockStateHolder<BlockState> get = session.getBlock(xr, getY, zr); if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } int setData = newHeight & 15; if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } } } else if (curHeight > newHeight) { // Fill rest with air for (int y = newBlock + 1; y <= ((curHeight + 15) >> 4); ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) int setData = newHeight & 15; BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); } ++blocksChanged; } } } return blocksChanged; }
public int applyLayers(int[] data) { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockStateHolder<BlockState> tmpBlock = BlockTypes.AIR.getDefaultState(); int maxY4 = maxY << 4; int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; int newHeight = Math.min(maxY4, data[index++]); int curBlock = (curHeight) >> 4; int newBlock = (newHeight + 15) >> 4; int xr = x + originX; if (newHeight > curHeight) { BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); if (existing.getBlockType().getMaterial().isMovementBlocker()) { for (int setY = newBlock - 1, getY = curBlock; setY >= curBlock; --setY, getY--) { BlockStateHolder<BlockState> get = session.getBlock(xr, getY, zr); if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } int setData = newHeight & 15; if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); ++blocksChanged; } } } else if (curHeight > newHeight) { for (int y = newBlock + 1; y <= ((curHeight + 15) >> 4); ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } int setData = newHeight & 15; BlockStateHolder<BlockState> existing = session.getBlock(xr, curBlock, zr); if (setData != 0) { existing = PropertyGroup.LEVEL.set(existing, setData - 1); session.setBlock(xr, newBlock, zr, existing); } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); } ++blocksChanged; } } } return blocksChanged; }
public int applylayers(int[] data) { checknotnull(data); blockvector3 miny = region.getminimumpoint(); int originx = miny.getblockx(); int originz = miny.getblockz(); int maxy = region.getmaximumpoint().getblocky(); blockstate fillerair = blocktypes.air.getdefaultstate(); int blockschanged = 0; blockstateholder<blockstate> tmpblock = blocktypes.air.getdefaultstate(); int maxy4 = maxy << 4; int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originz; for (int x = 0; x < width; ++x) { if (this.invalid != null && this.invalid[index]) { continue; } int curheight = this.data[index]; int newheight = math.min(maxy4, data[index++]); int curblock = (curheight) >> 4; int newblock = (newheight + 15) >> 4; int xr = x + originx; if (newheight > curheight) { blockstateholder<blockstate> existing = session.getblock(xr, curblock, zr); if (existing.getblocktype().getmaterial().ismovementblocker()) { for (int sety = newblock - 1, gety = curblock; sety >= curblock; --sety, gety--) { blockstateholder<blockstate> get = session.getblock(xr, gety, zr); if (get != blocktypes.air.getdefaultstate()) { tmpblock = get; } session.setblock(xr, sety, zr, tmpblock); ++blockschanged; } int setdata = newheight & 15; if (setdata != 0) { existing = propertygroup.level.set(existing, setdata - 1); session.setblock(xr, newblock, zr, existing); ++blockschanged; } else { existing = propertygroup.level.set(existing, 15); session.setblock(xr, newblock, zr, existing); ++blockschanged; } } } else if (curheight > newheight) { for (int y = newblock + 1; y <= ((curheight + 15) >> 4); ++y) { session.setblock(xr, y, zr, fillerair); ++blockschanged; } int setdata = newheight & 15; blockstateholder<blockstate> existing = session.getblock(xr, curblock, zr); if (setdata != 0) { existing = propertygroup.level.set(existing, setdata - 1); session.setblock(xr, newblock, zr, existing); } else { existing = propertygroup.level.set(existing, 15); session.setblock(xr, newblock, zr, existing); } ++blockschanged; } } } return blockschanged; }
IronApollo/FastAsyncWorldEdit
[ 0, 1, 0, 0 ]
9,671
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; // Clamp newHeight within the selection area int newHeight = Math.min(maxY, data[index]); // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) BlockState existing = session.getBlock(xr, curHeight, zr); // Skip water/lava if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } // Drop trees to the floor -- TODO return blocksChanged; }
public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originZ; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curHeight = this.data[index]; int newHeight = Math.min(maxY, data[index]); int xr = x + originX; if (newHeight > curHeight) { BlockState existing = session.getBlock(xr, curHeight, zr); if (existing.getBlockType().getMaterial().isMovementBlocker()) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { BlockState get; if (getY >= 0 && getY < 256) { get = session.getBlock(xr, getY, zr); } else { get = BlockTypes.AIR.getDefaultState(); } if (get != BlockTypes.AIR.getDefaultState()) { tmpBlock = get; } session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } session.setBlock(xr, newHeight, zr, existing); ++blocksChanged; } } else if (curHeight > newHeight) { session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); ++blocksChanged; for (int y = newHeight + 1; y <= curHeight; ++y) { session.setBlock(xr, y, zr, fillerAir); ++blocksChanged; } } } } return blocksChanged; }
public int apply(int[] data) throws maxchangedblocksexception { checknotnull(data); blockvector3 miny = region.getminimumpoint(); int originx = miny.getblockx(); int originy = miny.getblocky(); int originz = miny.getblockz(); int maxy = region.getmaximumpoint().getblocky(); blockstate fillerair = blocktypes.air.getdefaultstate(); int blockschanged = 0; blockstate tmpblock = blocktypes.air.getdefaultstate(); int index = 0; for (int z = 0; z < height; ++z) { int zr = z + originz; for (int x = 0; x < width; ++x, index++) { if (this.invalid != null && this.invalid[index]) { continue; } int curheight = this.data[index]; int newheight = math.min(maxy, data[index]); int xr = x + originx; if (newheight > curheight) { blockstate existing = session.getblock(xr, curheight, zr); if (existing.getblocktype().getmaterial().ismovementblocker()) { int y0 = newheight - 1; for (int sety = y0, gety = curheight - 1; sety >= curheight; sety--, gety--) { blockstate get; if (gety >= 0 && gety < 256) { get = session.getblock(xr, gety, zr); } else { get = blocktypes.air.getdefaultstate(); } if (get != blocktypes.air.getdefaultstate()) { tmpblock = get; } session.setblock(xr, sety, zr, tmpblock); ++blockschanged; } session.setblock(xr, newheight, zr, existing); ++blockschanged; } } else if (curheight > newheight) { session.setblock(xr, newheight, zr, session.getblock(xr, curheight, zr)); ++blockschanged; for (int y = newheight + 1; y <= curheight; ++y) { session.setblock(xr, y, zr, fillerair); ++blockschanged; } } } } return blockschanged; }
IronApollo/FastAsyncWorldEdit
[ 0, 1, 0, 0 ]
1,494
private void initialization(int minXSize, int maxXSize) { // TODO: current implementation is less elegant. code refactoring may be needed. dfaConfig = new DFAConfig(); // allocates a new config every time. Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } // alphabet size: range[6 ~ 16] or [10, 20] int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); // randomly fill the alphabet int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } // faulty event size (make sure it less than a half of alphabet size) int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
private void initialization(int minXSize, int maxXSize) { dfaConfig = new DFAConfig(); Random r = new Random(); dfaConfig.stateSize = r.nextInt((maxXSize - minXSize) + 1) + minXSize; dfaConfig.faultyStateSize = Math.max(dfaConfig.stateSize / 10, 4); LOGGER.debug("Generated overall state size and faulty state size: {}, {}", dfaConfig.stateSize, dfaConfig.faultyStateSize); dfaConfig.states = new int[dfaConfig.stateSize]; for (int i = 0; i < dfaConfig.stateSize; i++) { dfaConfig.states[i] = i; } int base = dfaConfig.stateSize > 20 ? 10 : 6; int alphabetSize = r.nextInt(11) + base; dfaConfig.alphabet = new char[alphabetSize]; LOGGER.debug("Chosen alphabet size is {}", alphabetSize); int alphabetSpaceLen = dfaConfig.alphabetSpace.length(); boolean[] tempFlags = new boolean[alphabetSpaceLen]; int tempIndex; for (int i = 0; i < dfaConfig.alphabet.length; i++) { tempIndex = r.nextInt(alphabetSpaceLen); while (tempFlags[tempIndex]) { tempIndex = r.nextInt(alphabetSpaceLen); } tempFlags[tempIndex] = true; dfaConfig.alphabet[i] = dfaConfig.alphabetSpace.charAt(tempIndex); } int faultEventSize = Math.max(dfaConfig.faultyStateSize / 2, 2); faultEventSize = faultEventSize >= 5 ? 4 : faultEventSize; if (alphabetSize > 15 && (dfaConfig.faultyStateSize / faultEventSize) > 3) { faultEventSize = faultEventSize + r.nextInt(2) + 1; } dfaConfig.faultyEvents = new int[faultEventSize]; LOGGER.debug("Chosen faulty event size: {}", faultEventSize); boolean[] chosenFaultMarks = new boolean[alphabetSize]; int choose; for (int i = 0; i < faultEventSize; i++) { choose = r.nextInt(alphabetSize); while (chosenFaultMarks[choose]) choose = r.nextInt(alphabetSize); chosenFaultMarks[choose] = true; dfaConfig.faultyEvents[i] = choose; } LOGGER.debug("Generated alphabet set: {}", Arrays.toString(dfaConfig.alphabet)); LOGGER.debug("Faulty events (index): {}", Arrays.toString(dfaConfig.faultyEvents)); Set<Integer> faultyEventIndexSet = new HashSet<>(); for (int fi : dfaConfig.faultyEvents) faultyEventIndexSet.add(fi); int ui = 0; int oi = 0; dfaConfig.observableEvents = new char[alphabetSize - faultEventSize]; dfaConfig.unobservableEvents = new char[faultEventSize]; for (int i = 0; i < alphabetSize; i++) { if (faultyEventIndexSet.contains(i)) dfaConfig.unobservableEvents[ui++] = dfaConfig.alphabet[i]; else dfaConfig.observableEvents[oi++] = dfaConfig.alphabet[i]; } LOGGER.debug("selected observable events : {}", Arrays.toString(dfaConfig.observableEvents)); LOGGER.debug("selected unobservable events : {}", Arrays.toString(dfaConfig.unobservableEvents)); }
private void initialization(int minxsize, int maxxsize) { dfaconfig = new dfaconfig(); random r = new random(); dfaconfig.statesize = r.nextint((maxxsize - minxsize) + 1) + minxsize; dfaconfig.faultystatesize = math.max(dfaconfig.statesize / 10, 4); logger.debug("generated overall state size and faulty state size: {}, {}", dfaconfig.statesize, dfaconfig.faultystatesize); dfaconfig.states = new int[dfaconfig.statesize]; for (int i = 0; i < dfaconfig.statesize; i++) { dfaconfig.states[i] = i; } int base = dfaconfig.statesize > 20 ? 10 : 6; int alphabetsize = r.nextint(11) + base; dfaconfig.alphabet = new char[alphabetsize]; logger.debug("chosen alphabet size is {}", alphabetsize); int alphabetspacelen = dfaconfig.alphabetspace.length(); boolean[] tempflags = new boolean[alphabetspacelen]; int tempindex; for (int i = 0; i < dfaconfig.alphabet.length; i++) { tempindex = r.nextint(alphabetspacelen); while (tempflags[tempindex]) { tempindex = r.nextint(alphabetspacelen); } tempflags[tempindex] = true; dfaconfig.alphabet[i] = dfaconfig.alphabetspace.charat(tempindex); } int faulteventsize = math.max(dfaconfig.faultystatesize / 2, 2); faulteventsize = faulteventsize >= 5 ? 4 : faulteventsize; if (alphabetsize > 15 && (dfaconfig.faultystatesize / faulteventsize) > 3) { faulteventsize = faulteventsize + r.nextint(2) + 1; } dfaconfig.faultyevents = new int[faulteventsize]; logger.debug("chosen faulty event size: {}", faulteventsize); boolean[] chosenfaultmarks = new boolean[alphabetsize]; int choose; for (int i = 0; i < faulteventsize; i++) { choose = r.nextint(alphabetsize); while (chosenfaultmarks[choose]) choose = r.nextint(alphabetsize); chosenfaultmarks[choose] = true; dfaconfig.faultyevents[i] = choose; } logger.debug("generated alphabet set: {}", arrays.tostring(dfaconfig.alphabet)); logger.debug("faulty events (index): {}", arrays.tostring(dfaconfig.faultyevents)); set<integer> faultyeventindexset = new hashset<>(); for (int fi : dfaconfig.faultyevents) faultyeventindexset.add(fi); int ui = 0; int oi = 0; dfaconfig.observableevents = new char[alphabetsize - faulteventsize]; dfaconfig.unobservableevents = new char[faulteventsize]; for (int i = 0; i < alphabetsize; i++) { if (faultyeventindexset.contains(i)) dfaconfig.unobservableevents[ui++] = dfaconfig.alphabet[i]; else dfaconfig.observableevents[oi++] = dfaconfig.alphabet[i]; } logger.debug("selected observable events : {}", arrays.tostring(dfaconfig.observableevents)); logger.debug("selected unobservable events : {}", arrays.tostring(dfaconfig.unobservableevents)); }
OES2018/randomly-generation-of-diagnosable-dfa
[ 1, 0, 0, 0 ]
34,283
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); // TODO: actually implement this lol }
@Override public BiomeProvider load(AnnotatedType t, Object c, ConfigLoader loader) throws LoadException { return loader.loadType(BiomePipelineProvider.class, c); }
@override public biomeprovider load(annotatedtype t, object c, configloader loader) throws loadexception { return loader.loadtype(biomepipelineprovider.class, c); }
PolyhedralDev/Terra-biome-provider-pipeline
[ 0, 1, 0, 0 ]
34,349
public List<List<String>> rows() { try { List<List<String>> results = new ArrayList<>(); for (BaseWork baseWork : topSortedWork) { String vertexName = baseWork.getName(); VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 // TODO: can we pass custom things thru the progress? results.add( Arrays.asList( getNameWithProgress(vertexName, progress.succeededTaskCount, progress.totalTaskCount), getMode(baseWork), progress.vertexStatus(vertexStatusMap.get(vertexName)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(), progress.killed() ) ); } } return results; } catch (Exception e) { console.printInfo( "Getting Progress Bar table rows failed: " + e.getMessage() + " stack trace: " + Arrays .toString(e.getStackTrace()) ); } return Collections.emptyList(); }
public List<List<String>> rows() { try { List<List<String>> results = new ArrayList<>(); for (BaseWork baseWork : topSortedWork) { String vertexName = baseWork.getName(); VertexProgress progress = progressCountsMap.get(vertexName); if (progress != null) { results.add( Arrays.asList( getNameWithProgress(vertexName, progress.succeededTaskCount, progress.totalTaskCount), getMode(baseWork), progress.vertexStatus(vertexStatusMap.get(vertexName)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(), progress.killed() ) ); } } return results; } catch (Exception e) { console.printInfo( "Getting Progress Bar table rows failed: " + e.getMessage() + " stack trace: " + Arrays .toString(e.getStackTrace()) ); } return Collections.emptyList(); }
public list<list<string>> rows() { try { list<list<string>> results = new arraylist<>(); for (basework basework : topsortedwork) { string vertexname = basework.getname(); vertexprogress progress = progresscountsmap.get(vertexname); if (progress != null) { results.add( arrays.aslist( getnamewithprogress(vertexname, progress.succeededtaskcount, progress.totaltaskcount), getmode(basework), progress.vertexstatus(vertexstatusmap.get(vertexname)), progress.total(), progress.completed(), progress.running(), progress.pending(), progress.failed(), progress.killed() ) ); } } return results; } catch (exception e) { console.printinfo( "getting progress bar table rows failed: " + e.getmessage() + " stack trace: " + arrays .tostring(e.getstacktrace()) ); } return collections.emptylist(); }
JSA-Insubria/hive
[ 1, 0, 0, 0 ]
9,779
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); // todo - improved error message if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { // data case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } // data change case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; // control case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
Statement compileSQLProcedureStatementOrNull(Routine routine, StatementCompound context) { Statement cs = null; HsqlName label = null; RangeVariable[] rangeVariables = context == null ? routine.getParameterRangeVariables() : context.getRangeVariables(); if (!routine.isTrigger() && isSimpleName() && !isReservedKey()) { label = readNewSchemaObjectName(SchemaObject.LABEL, false); if (token.tokenType != Tokens.COLON) { throw unexpectedToken(label.getNameString()); } readThis(Tokens.COLON); } compileContext.reset(); HsqlName oldSchema = session.getCurrentSchemaHsqlName(); session.setCurrentSchemaHsqlName(routine.getSchemaName()); try { switch (token.tokenType) { case Tokens.OPEN : { if (routine.dataImpact == Routine.CONTAINS_SQL) { throw Error.error(ErrorCode.X_42602, routine.getDataImpactString()); } if (label != null) { throw unexpectedToken(); } cs = compileOpenCursorStatement(context); break; } case Tokens.SELECT : { if (label != null) { throw unexpectedToken(); } cs = compileSelectSingleRowStatement(rangeVariables); break; } case Tokens.INSERT : if (label != null) { throw unexpectedToken(); } cs = compileInsertStatement(rangeVariables); break; case Tokens.UPDATE : if (label != null) { throw unexpectedToken(); } cs = compileUpdateStatement(rangeVariables); break; case Tokens.DELETE : if (label != null) { throw unexpectedToken(); } cs = compileDeleteStatement(rangeVariables); break; case Tokens.TRUNCATE : if (label != null) { throw unexpectedToken(); } cs = compileTruncateStatement(); break; case Tokens.MERGE : if (label != null) { throw unexpectedToken(); } cs = compileMergeStatement(rangeVariables); break; case Tokens.SET : if (label != null) { throw unexpectedToken(); } if (routine.isTrigger()) { if (routine.triggerOperation == StatementTypes.DELETE_WHERE) { cs = compileSetStatement(rangeVariables); break; } if (routine.triggerType != TriggerDef.BEFORE) { cs = compileSetStatement(rangeVariables); break; } int position = super.getPosition(); try { cs = compileTriggerSetStatement( routine.triggerTable, rangeVariables); } catch (HsqlException e) { rewind(position); cs = compileSetStatement(rangeVariables); } } else { cs = compileSetStatement(rangeVariables); } break; case Tokens.GET : if (label != null) { throw unexpectedToken(); } cs = this.compileGetStatement(rangeVariables); break; case Tokens.CALL : { if (label != null) { throw unexpectedToken(); } cs = compileCallStatement(rangeVariables, true); Routine proc = ((StatementProcedure) cs).procedure; if (proc != null) { switch (routine.dataImpact) { case Routine.CONTAINS_SQL : { if (proc.dataImpact == Routine.READS_SQL || proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } case Routine.READS_SQL : { if (proc.dataImpact == Routine.MODIFIES_SQL) { throw Error.error( ErrorCode.X_42602, routine.getDataImpactString()); } break; } } } break; } case Tokens.RETURN : { if (routine.isTrigger() || label != null) { throw unexpectedToken(); } read(); cs = compileReturnValue(routine, context); break; } case Tokens.BEGIN : { cs = compileCompoundStatement(routine, context, label); break; } case Tokens.WHILE : { if (routine.isTrigger()) { throw unexpectedToken(); } cs = compileWhile(routine, context, label); break; } case Tokens.REPEAT : { cs = compileRepeat(routine, context, label); break; } case Tokens.LOOP : { cs = compileLoop(routine, context, label); break; } case Tokens.FOR : { cs = compileFor(routine, context, label); break; } case Tokens.ITERATE : { if (label != null) { throw unexpectedToken(); } cs = compileIterate(); break; } case Tokens.LEAVE : { if (label != null) { throw unexpectedToken(); } cs = compileLeave(routine, context); break; } case Tokens.IF : { cs = compileIf(routine, context); break; } case Tokens.CASE : { cs = compileCase(routine, context); break; } case Tokens.SIGNAL : { cs = compileSignal(routine, context, label); break; } case Tokens.RESIGNAL : { cs = compileResignal(routine, context, label); break; } default : return null; } cs.setRoot(routine); cs.setParent(context); return cs; } finally { session.setCurrentSchemaHsqlName(oldSchema); } }
statement compilesqlprocedurestatementornull(routine routine, statementcompound context) { statement cs = null; hsqlname label = null; rangevariable[] rangevariables = context == null ? routine.getparameterrangevariables() : context.getrangevariables(); if (!routine.istrigger() && issimplename() && !isreservedkey()) { label = readnewschemaobjectname(schemaobject.label, false); if (token.tokentype != tokens.colon) { throw unexpectedtoken(label.getnamestring()); } readthis(tokens.colon); } compilecontext.reset(); hsqlname oldschema = session.getcurrentschemahsqlname(); session.setcurrentschemahsqlname(routine.getschemaname()); try { switch (token.tokentype) { case tokens.open : { if (routine.dataimpact == routine.contains_sql) { throw error.error(errorcode.x_42602, routine.getdataimpactstring()); } if (label != null) { throw unexpectedtoken(); } cs = compileopencursorstatement(context); break; } case tokens.select : { if (label != null) { throw unexpectedtoken(); } cs = compileselectsinglerowstatement(rangevariables); break; } case tokens.insert : if (label != null) { throw unexpectedtoken(); } cs = compileinsertstatement(rangevariables); break; case tokens.update : if (label != null) { throw unexpectedtoken(); } cs = compileupdatestatement(rangevariables); break; case tokens.delete : if (label != null) { throw unexpectedtoken(); } cs = compiledeletestatement(rangevariables); break; case tokens.truncate : if (label != null) { throw unexpectedtoken(); } cs = compiletruncatestatement(); break; case tokens.merge : if (label != null) { throw unexpectedtoken(); } cs = compilemergestatement(rangevariables); break; case tokens.set : if (label != null) { throw unexpectedtoken(); } if (routine.istrigger()) { if (routine.triggeroperation == statementtypes.delete_where) { cs = compilesetstatement(rangevariables); break; } if (routine.triggertype != triggerdef.before) { cs = compilesetstatement(rangevariables); break; } int position = super.getposition(); try { cs = compiletriggersetstatement( routine.triggertable, rangevariables); } catch (hsqlexception e) { rewind(position); cs = compilesetstatement(rangevariables); } } else { cs = compilesetstatement(rangevariables); } break; case tokens.get : if (label != null) { throw unexpectedtoken(); } cs = this.compilegetstatement(rangevariables); break; case tokens.call : { if (label != null) { throw unexpectedtoken(); } cs = compilecallstatement(rangevariables, true); routine proc = ((statementprocedure) cs).procedure; if (proc != null) { switch (routine.dataimpact) { case routine.contains_sql : { if (proc.dataimpact == routine.reads_sql || proc.dataimpact == routine.modifies_sql) { throw error.error( errorcode.x_42602, routine.getdataimpactstring()); } break; } case routine.reads_sql : { if (proc.dataimpact == routine.modifies_sql) { throw error.error( errorcode.x_42602, routine.getdataimpactstring()); } break; } } } break; } case tokens.return : { if (routine.istrigger() || label != null) { throw unexpectedtoken(); } read(); cs = compilereturnvalue(routine, context); break; } case tokens.begin : { cs = compilecompoundstatement(routine, context, label); break; } case tokens.while : { if (routine.istrigger()) { throw unexpectedtoken(); } cs = compilewhile(routine, context, label); break; } case tokens.repeat : { cs = compilerepeat(routine, context, label); break; } case tokens.loop : { cs = compileloop(routine, context, label); break; } case tokens.for : { cs = compilefor(routine, context, label); break; } case tokens.iterate : { if (label != null) { throw unexpectedtoken(); } cs = compileiterate(); break; } case tokens.leave : { if (label != null) { throw unexpectedtoken(); } cs = compileleave(routine, context); break; } case tokens.if : { cs = compileif(routine, context); break; } case tokens.case : { cs = compilecase(routine, context); break; } case tokens.signal : { cs = compilesignal(routine, context, label); break; } case tokens.resignal : { cs = compileresignal(routine, context, label); break; } default : return null; } cs.setroot(routine); cs.setparent(context); return cs; } finally { session.setcurrentschemahsqlname(oldschema); } }
RabadanLab/Pegasus
[ 0, 1, 0, 0 ]
34,400
public int pcToLine(int pc) { /* * Line number entries don't have to appear in any particular * order, so we have to do a linear search. TODO: If * this turns out to be a bottleneck, consider sorting the * list prior to use. */ int sz = size(); int bestPc = -1; int bestLine = -1; for (int i = 0; i < sz; i++) { Item one = get(i); int onePc = one.getStartPc(); if ((onePc <= pc) && (onePc > bestPc)) { bestPc = onePc; bestLine = one.getLineNumber(); if (bestPc == pc) { // We can't do better than this break; } } } return bestLine; }
public int pcToLine(int pc) { int sz = size(); int bestPc = -1; int bestLine = -1; for (int i = 0; i < sz; i++) { Item one = get(i); int onePc = one.getStartPc(); if ((onePc <= pc) && (onePc > bestPc)) { bestPc = onePc; bestLine = one.getLineNumber(); if (bestPc == pc) { break; } } } return bestLine; }
public int pctoline(int pc) { int sz = size(); int bestpc = -1; int bestline = -1; for (int i = 0; i < sz; i++) { item one = get(i); int onepc = one.getstartpc(); if ((onepc <= pc) && (onepc > bestpc)) { bestpc = onepc; bestline = one.getlinenumber(); if (bestpc == pc) { break; } } } return bestline; }
MaTriXy/atlas
[ 1, 0, 0, 0 ]
9,846
public void free() { currState = NO_STATE; if (Sage.DBG) System.out.println("Closing down mplayer"); if (uiMgr != null) uiMgr.putFloat("mplayer/last_volume", currVolume); timeGuessMillis = 0; guessTimestamp = 0; currVolume = 1.0f; if (mpStdin != null && isMPlayerRunning()) { // Be sure to clear the active file bit in case MPlayer is waiting for more data // Be sure we don't close the stdin connection before we send the quit message, but don't // hang waiting for the quit to be processed // inactiveFile(); // stop(); Thread t = new Thread("PlayerSendCmd") { public void run() { if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear..."); synchronized (sendCmdQueue) { while (!sendCmdQueue.isEmpty()) { try { sendCmdQueue.wait(50); } catch (InterruptedException e){} continue; } } if (Sage.DBG) System.out.println("Sending mplayer command: quit"); if (!fileDeactivated) { fileDeactivated = true; synchronized (mpStdin) { mpStdin.println("inactive_file"); } } if (currState == PLAY_STATE && !eos) { synchronized (mpStdin) { mpStdin.println("pause"); } currState = STOPPED_STATE; } else currState = STOPPED_STATE; synchronized (mpStdin) { mpStdin.println("quit"); } mpStdin.close(); mpStdin = null; if (mpStdout != null) { try { mpStdout.close(); } catch (java.io.IOException e) {} mpStdout = null; } if (mpStderr != null) { try { mpStderr.close(); } catch (java.io.IOException e) {} mpStderr = null; } } }; t.setPriority(Thread.currentThread().getPriority()); t.setDaemon(true); t.start(); } if (mpProc != null) { long startWait = Sage.eventTime(); // FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between... long killDelay = (Sage.MAC_OS_X ? 2000 : 15000); while (true) { try { int exitValue = mpProc.exitValue(); if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue); break; } catch (IllegalThreadStateException e) { if (Sage.DBG) System.out.println("MPlayer process has not exited yet..."); try{Thread.sleep(100);}catch(Exception e1){} if (Sage.eventTime() - startWait > killDelay) { if (Sage.DBG) System.out.println("Forcibly killing MPlayer process!"); mpProc.destroy(); break; } } } mpProc = null; } if (launchedAsyncRenderThread) ((DirectX9SageRenderer)uiMgr.getRootPanel().getRenderEngine()).asyncVideoRender(null); if (releaseServerAccessVobSubBase != null) { NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".idx"), false); NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".sub"), false); releaseServerAccessVobSubBase = null; } }
public void free() { currState = NO_STATE; if (Sage.DBG) System.out.println("Closing down mplayer"); if (uiMgr != null) uiMgr.putFloat("mplayer/last_volume", currVolume); timeGuessMillis = 0; guessTimestamp = 0; currVolume = 1.0f; if (mpStdin != null && isMPlayerRunning()) { Thread t = new Thread("PlayerSendCmd") { public void run() { if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear..."); synchronized (sendCmdQueue) { while (!sendCmdQueue.isEmpty()) { try { sendCmdQueue.wait(50); } catch (InterruptedException e){} continue; } } if (Sage.DBG) System.out.println("Sending mplayer command: quit"); if (!fileDeactivated) { fileDeactivated = true; synchronized (mpStdin) { mpStdin.println("inactive_file"); } } if (currState == PLAY_STATE && !eos) { synchronized (mpStdin) { mpStdin.println("pause"); } currState = STOPPED_STATE; } else currState = STOPPED_STATE; synchronized (mpStdin) { mpStdin.println("quit"); } mpStdin.close(); mpStdin = null; if (mpStdout != null) { try { mpStdout.close(); } catch (java.io.IOException e) {} mpStdout = null; } if (mpStderr != null) { try { mpStderr.close(); } catch (java.io.IOException e) {} mpStderr = null; } } }; t.setPriority(Thread.currentThread().getPriority()); t.setDaemon(true); t.start(); } if (mpProc != null) { long startWait = Sage.eventTime(); long killDelay = (Sage.MAC_OS_X ? 2000 : 15000); while (true) { try { int exitValue = mpProc.exitValue(); if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue); break; } catch (IllegalThreadStateException e) { if (Sage.DBG) System.out.println("MPlayer process has not exited yet..."); try{Thread.sleep(100);}catch(Exception e1){} if (Sage.eventTime() - startWait > killDelay) { if (Sage.DBG) System.out.println("Forcibly killing MPlayer process!"); mpProc.destroy(); break; } } } mpProc = null; } if (launchedAsyncRenderThread) ((DirectX9SageRenderer)uiMgr.getRootPanel().getRenderEngine()).asyncVideoRender(null); if (releaseServerAccessVobSubBase != null) { NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".idx"), false); NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".sub"), false); releaseServerAccessVobSubBase = null; } }
public void free() { currstate = no_state; if (sage.dbg) system.out.println("closing down mplayer"); if (uimgr != null) uimgr.putfloat("mplayer/last_volume", currvolume); timeguessmillis = 0; guesstimestamp = 0; currvolume = 1.0f; if (mpstdin != null && ismplayerrunning()) { thread t = new thread("playersendcmd") { public void run() { if (sage.dbg) system.out.println("waiting for the cmd queue to clear..."); synchronized (sendcmdqueue) { while (!sendcmdqueue.isempty()) { try { sendcmdqueue.wait(50); } catch (interruptedexception e){} continue; } } if (sage.dbg) system.out.println("sending mplayer command: quit"); if (!filedeactivated) { filedeactivated = true; synchronized (mpstdin) { mpstdin.println("inactive_file"); } } if (currstate == play_state && !eos) { synchronized (mpstdin) { mpstdin.println("pause"); } currstate = stopped_state; } else currstate = stopped_state; synchronized (mpstdin) { mpstdin.println("quit"); } mpstdin.close(); mpstdin = null; if (mpstdout != null) { try { mpstdout.close(); } catch (java.io.ioexception e) {} mpstdout = null; } if (mpstderr != null) { try { mpstderr.close(); } catch (java.io.ioexception e) {} mpstderr = null; } } }; t.setpriority(thread.currentthread().getpriority()); t.setdaemon(true); t.start(); } if (mpproc != null) { long startwait = sage.eventtime(); long killdelay = (sage.mac_os_x ? 2000 : 15000); while (true) { try { int exitvalue = mpproc.exitvalue(); if (sage.dbg) system.out.println("mplayer process exit code:" + exitvalue); break; } catch (illegalthreadstateexception e) { if (sage.dbg) system.out.println("mplayer process has not exited yet..."); try{thread.sleep(100);}catch(exception e1){} if (sage.eventtime() - startwait > killdelay) { if (sage.dbg) system.out.println("forcibly killing mplayer process!"); mpproc.destroy(); break; } } } mpproc = null; } if (launchedasyncrenderthread) ((directx9sagerenderer)uimgr.getrootpanel().getrenderengine()).asyncvideorender(null); if (releaseserveraccessvobsubbase != null) { networkclient.getsn().requestmediaserveraccess(new java.io.file(releaseserveraccessvobsubbase + ".idx"), false); networkclient.getsn().requestmediaserveraccess(new java.io.file(releaseserveraccessvobsubbase + ".sub"), false); releaseserveraccessvobsubbase = null; } }
Narflex/sagetv
[ 0, 0, 1, 0 ]
26,236
@Test public void testNullValueDisallowed() throws Exception { { String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": 100, \"status\": \"placed\" }"; org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class); assertEquals(100L, (long)o.getQuantity()); assertEquals(org.openapitools.client.model.Order.StatusEnum.PLACED, o.getStatus()); } { String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }"; org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class); // TODO: the null value is not allowed per OAS document. // The deserialization should fail. assertNull(o.getQuantity()); } }
@Test public void testNullValueDisallowed() throws Exception { { String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": 100, \"status\": \"placed\" }"; org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class); assertEquals(100L, (long)o.getQuantity()); assertEquals(org.openapitools.client.model.Order.StatusEnum.PLACED, o.getStatus()); } { String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }"; org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class); assertNull(o.getQuantity()); } }
@test public void testnullvaluedisallowed() throws exception { { string str = "{ \"id\": 123, \"petid\": 345, \"quantity\": 100, \"status\": \"placed\" }"; org.openapitools.client.model.order o = json.getcontext(null).readvalue(str, org.openapitools.client.model.order.class); assertequals(100l, (long)o.getquantity()); assertequals(org.openapitools.client.model.order.statusenum.placed, o.getstatus()); } { string str = "{ \"id\": 123, \"petid\": 345, \"quantity\": null }"; org.openapitools.client.model.order o = json.getcontext(null).readvalue(str, org.openapitools.client.model.order.class); assertnull(o.getquantity()); } }
IonBazan/openapi-generator
[ 0, 0, 1, 0 ]
9,930
public static String getUserDocumentsPath() { if (m_documents == null) { //TODO: Should I look at the OneDrive entry first? // The OneDrive key from the web is different from mine. m_documents = Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "Personal"); if (m_documents == null) { m_documents = Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", "Personal"); if (m_documents == null) { Server.logger().log(Level.SEVERE, "Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\", \"Personal\") returned NULL"); System.out.println("Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\", \"Personal\") returned NULL"); //if we cannot get this, we have to exit because we don't know where to store our data. System.exit(1); } } if (m_documents.contains("%USERPROFILE%")) { m_documents = m_documents.replace("%USERPROFILE%", System.getenv("USERPROFILE")); } } return m_documents; }
public static String getUserDocumentsPath() { if (m_documents == null) { m_documents = Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "Personal"); if (m_documents == null) { m_documents = Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", "Personal"); if (m_documents == null) { Server.logger().log(Level.SEVERE, "Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\", \"Personal\") returned NULL"); System.out.println("Advapi32Util.registryGetStringValue(HKEY_CURRENT_USER, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\User Shell Folders\", \"Personal\") returned NULL"); System.exit(1); } } if (m_documents.contains("%USERPROFILE%")) { m_documents = m_documents.replace("%USERPROFILE%", System.getenv("USERPROFILE")); } } return m_documents; }
public static string getuserdocumentspath() { if (m_documents == null) { m_documents = advapi32util.registrygetstringvalue(hkey_current_user, "software\\microsoft\\windows\\currentversion\\explorer\\shell folders", "personal"); if (m_documents == null) { m_documents = advapi32util.registrygetstringvalue(hkey_current_user, "software\\microsoft\\windows\\currentversion\\explorer\\user shell folders", "personal"); if (m_documents == null) { server.logger().log(level.severe, "advapi32util.registrygetstringvalue(hkey_current_user, \"software\\\\microsoft\\\\windows\\\\currentversion\\\\explorer\\\\user shell folders\", \"personal\") returned null"); system.out.println("advapi32util.registrygetstringvalue(hkey_current_user, \"software\\\\microsoft\\\\windows\\\\currentversion\\\\explorer\\\\user shell folders\", \"personal\") returned null"); system.exit(1); } } if (m_documents.contains("%userprofile%")) { m_documents = m_documents.replace("%userprofile%", system.getenv("userprofile")); } } return m_documents; }
SIMRacingApps/SIMRacingAppsServer
[ 1, 0, 0, 0 ]
34,529
public void testWrongName() { try { construct("--- !!org.yaml.snakeyaml.constructor.TestBean\nwrongName: No one\nage: 24\nborn: 1982-05-03\n"); fail("IntrospectionException expected."); } catch (Exception e) { // TODO improve the error message - the pointer should be at the // property name, not value assertEquals( "Cannot create property=wrongName for JavaBean=#<org.jvyaml.TestBean name=\"null\" age=0 born=\"null\">\n" + " in 'string', line 1, column 5:\n" + " --- !!org.yaml.snakeyaml.constructor ... \n" + " ^\n" + "Unable to find property 'wrongName' on class: org.yaml.snakeyaml.constructor.TestBean\n" + " in 'string', line 2, column 12:\n" + " wrongName: No one\n" + " ^\n", e.getMessage()); } }
public void testWrongName() { try { construct("--- !!org.yaml.snakeyaml.constructor.TestBean\nwrongName: No one\nage: 24\nborn: 1982-05-03\n"); fail("IntrospectionException expected."); } catch (Exception e) { assertEquals( "Cannot create property=wrongName for JavaBean=#<org.jvyaml.TestBean name=\"null\" age=0 born=\"null\">\n" + " in 'string', line 1, column 5:\n" + " --- !!org.yaml.snakeyaml.constructor ... \n" + " ^\n" + "Unable to find property 'wrongName' on class: org.yaml.snakeyaml.constructor.TestBean\n" + " in 'string', line 2, column 12:\n" + " wrongName: No one\n" + " ^\n", e.getMessage()); } }
public void testwrongname() { try { construct("--- !!org.yaml.snakeyaml.constructor.testbean\nwrongname: no one\nage: 24\nborn: 1982-05-03\n"); fail("introspectionexception expected."); } catch (exception e) { assertequals( "cannot create property=wrongname for javabean=#<org.jvyaml.testbean name=\"null\" age=0 born=\"null\">\n" + " in 'string', line 1, column 5:\n" + " --- !!org.yaml.snakeyaml.constructor ... \n" + " ^\n" + "unable to find property 'wrongname' on class: org.yaml.snakeyaml.constructor.testbean\n" + " in 'string', line 2, column 12:\n" + " wrongname: no one\n" + " ^\n", e.getmessage()); } }
PRECISE/ROSLab
[ 1, 0, 0, 0 ]
1,770
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; if (objectID != request.objectID) return false; if (methodIdentifier != null ? !methodIdentifier.equals(request.methodIdentifier) : request.methodIdentifier != null) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(args, request.args); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; if (objectID != request.objectID) return false; if (methodIdentifier != null ? !methodIdentifier.equals(request.methodIdentifier) : request.methodIdentifier != null) return false; return Arrays.equals(args, request.args); }
@override public boolean equals(object o) { if (this == o) return true; if (o == null || getclass() != o.getclass()) return false; request request = (request) o; if (objectid != request.objectid) return false; if (methodidentifier != null ? !methodidentifier.equals(request.methodidentifier) : request.methodidentifier != null) return false; return arrays.equals(args, request.args); }
MatzeS/blackbird_java
[ 0, 0, 1, 0 ]
34,690
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { log.debug("Authentication success"); // TODO: Optimize Map<String, Object> result = new HashMap<>(1); result.put("redirect", sitProperties.redirect()); JSONWriter.write(response, HttpStatus.OK, Result.ok(result)); }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { log.debug("Authentication success"); Map<String, Object> result = new HashMap<>(1); result.put("redirect", sitProperties.redirect()); JSONWriter.write(response, HttpStatus.OK, Result.ok(result)); }
@override public void onauthenticationsuccess(httpservletrequest request, httpservletresponse response, authentication authentication) throws servletexception, ioexception { log.debug("authentication success"); map<string, object> result = new hashmap<>(1); result.put("redirect", sitproperties.redirect()); jsonwriter.write(response, httpstatus.ok, result.ok(result)); }
O70/spring-laboratory
[ 1, 0, 0, 0 ]
18,316
private Set<String> findUris(Graph graph) { Set<String> result = new HashSet<>(); for (Triple t : graph.iterate()) { try { String object = t.getObject().toString().replace("<", "").replace(">", ""); // check for valid uri new URL(object).toURI(); result.add(object); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } return result; }
private Set<String> findUris(Graph graph) { Set<String> result = new HashSet<>(); for (Triple t : graph.iterate()) { try { String object = t.getObject().toString().replace("<", "").replace(">", ""); new URL(object).toURI(); result.add(object); } catch (MalformedURLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } return result; }
private set<string> finduris(graph graph) { set<string> result = new hashset<>(); for (triple t : graph.iterate()) { try { string object = t.getobject().tostring().replace("<", "").replace(">", ""); new url(object).touri(); result.add(object); } catch (malformedurlexception e) { e.printstacktrace(); } catch (urisyntaxexception e) { e.printstacktrace(); } } return result; }
Interactions-HSG/wot-search
[ 1, 0, 0, 0 ]
10,287
@Override public PipelineData execute(ActionExpressionType expression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException { boolean rebind = expressionHelper.getArgumentAsBoolean(expression.getParameter(), PARAM_REBIND_RESOURCES, input, context, false, PARAM_REBIND_RESOURCES, globalResult); PipelineData output = PipelineData.createEmpty(); for (PipelineItem item: input.getData()) { PrismValue value = item.getValue(); OperationResult result = operationsHelper.createActionResult(item, this, context, globalResult); context.checkTaskStop(); if (value instanceof PrismObjectValue && ((PrismObjectValue) value).asObjectable() instanceof ConnectorHostType) { PrismObject<ConnectorHostType> connectorHostTypePrismObject = ((PrismObjectValue) value).asPrismObject(); Set<ConnectorType> newConnectors; long started = operationsHelper.recordStart(context, connectorHostTypePrismObject.asObjectable()); Throwable exception = null; try { newConnectors = modelService.discoverConnectors(connectorHostTypePrismObject.asObjectable(), context.getTask(), result); operationsHelper.recordEnd(context, connectorHostTypePrismObject.asObjectable(), started, null); } catch (CommunicationException | SecurityViolationException | SchemaException | ConfigurationException | ObjectNotFoundException | RuntimeException e) { operationsHelper.recordEnd(context, connectorHostTypePrismObject.asObjectable(), started, e); exception = processActionException(e, NAME, value, context); newConnectors = Collections.emptySet(); } context.println((exception != null ? "Attempted to discover " : "Discovered " + newConnectors.size()) + " new connector(s) from " + connectorHostTypePrismObject + exceptionSuffix(exception)); for (ConnectorType connectorType : newConnectors) { output.addValue(connectorType.asPrismObject().getValue(), item.getResult()); } try { if (rebind) { rebindConnectors(newConnectors, context, result); } } catch (ScriptExecutionException e) { //noinspection ThrowableNotThrown processActionException(e, NAME, value, context); // TODO better message } } else { //noinspection ThrowableNotThrown processActionException(new ScriptExecutionException("Input item is not a PrismObject<ConnectorHost>"), NAME, value, context); } operationsHelper.trimAndCloneResult(result, globalResult, context); } return output; // TODO configurable output (either connector hosts or discovered connectors) }
@Override public PipelineData execute(ActionExpressionType expression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException { boolean rebind = expressionHelper.getArgumentAsBoolean(expression.getParameter(), PARAM_REBIND_RESOURCES, input, context, false, PARAM_REBIND_RESOURCES, globalResult); PipelineData output = PipelineData.createEmpty(); for (PipelineItem item: input.getData()) { PrismValue value = item.getValue(); OperationResult result = operationsHelper.createActionResult(item, this, context, globalResult); context.checkTaskStop(); if (value instanceof PrismObjectValue && ((PrismObjectValue) value).asObjectable() instanceof ConnectorHostType) { PrismObject<ConnectorHostType> connectorHostTypePrismObject = ((PrismObjectValue) value).asPrismObject(); Set<ConnectorType> newConnectors; long started = operationsHelper.recordStart(context, connectorHostTypePrismObject.asObjectable()); Throwable exception = null; try { newConnectors = modelService.discoverConnectors(connectorHostTypePrismObject.asObjectable(), context.getTask(), result); operationsHelper.recordEnd(context, connectorHostTypePrismObject.asObjectable(), started, null); } catch (CommunicationException | SecurityViolationException | SchemaException | ConfigurationException | ObjectNotFoundException | RuntimeException e) { operationsHelper.recordEnd(context, connectorHostTypePrismObject.asObjectable(), started, e); exception = processActionException(e, NAME, value, context); newConnectors = Collections.emptySet(); } context.println((exception != null ? "Attempted to discover " : "Discovered " + newConnectors.size()) + " new connector(s) from " + connectorHostTypePrismObject + exceptionSuffix(exception)); for (ConnectorType connectorType : newConnectors) { output.addValue(connectorType.asPrismObject().getValue(), item.getResult()); } try { if (rebind) { rebindConnectors(newConnectors, context, result); } } catch (ScriptExecutionException e) { processActionException(e, NAME, value, context); } } else { processActionException(new ScriptExecutionException("Input item is not a PrismObject<ConnectorHost>"), NAME, value, context); } operationsHelper.trimAndCloneResult(result, globalResult, context); } return output; }
@override public pipelinedata execute(actionexpressiontype expression, pipelinedata input, executioncontext context, operationresult globalresult) throws scriptexecutionexception { boolean rebind = expressionhelper.getargumentasboolean(expression.getparameter(), param_rebind_resources, input, context, false, param_rebind_resources, globalresult); pipelinedata output = pipelinedata.createempty(); for (pipelineitem item: input.getdata()) { prismvalue value = item.getvalue(); operationresult result = operationshelper.createactionresult(item, this, context, globalresult); context.checktaskstop(); if (value instanceof prismobjectvalue && ((prismobjectvalue) value).asobjectable() instanceof connectorhosttype) { prismobject<connectorhosttype> connectorhosttypeprismobject = ((prismobjectvalue) value).asprismobject(); set<connectortype> newconnectors; long started = operationshelper.recordstart(context, connectorhosttypeprismobject.asobjectable()); throwable exception = null; try { newconnectors = modelservice.discoverconnectors(connectorhosttypeprismobject.asobjectable(), context.gettask(), result); operationshelper.recordend(context, connectorhosttypeprismobject.asobjectable(), started, null); } catch (communicationexception | securityviolationexception | schemaexception | configurationexception | objectnotfoundexception | runtimeexception e) { operationshelper.recordend(context, connectorhosttypeprismobject.asobjectable(), started, e); exception = processactionexception(e, name, value, context); newconnectors = collections.emptyset(); } context.println((exception != null ? "attempted to discover " : "discovered " + newconnectors.size()) + " new connector(s) from " + connectorhosttypeprismobject + exceptionsuffix(exception)); for (connectortype connectortype : newconnectors) { output.addvalue(connectortype.asprismobject().getvalue(), item.getresult()); } try { if (rebind) { rebindconnectors(newconnectors, context, result); } } catch (scriptexecutionexception e) { processactionexception(e, name, value, context); } } else { processactionexception(new scriptexecutionexception("input item is not a prismobject<connectorhost>"), name, value, context); } operationshelper.trimandcloneresult(result, globalresult, context); } return output; }
Neovision-xin/dev
[ 1, 0, 0, 0 ]
34,916
private boolean analyzeLastLine( PageAnalysis analysis, PageElementTag tag, Collection<CheckErrorResult> errors) { // TODO: Refactor // Check type of tag if (!HtmlTagType.CENTER.equals(tag.getType()) && !HtmlTagType.SMALL.equals(tag.getType())) { return false; } // Check namespace Integer namespace = analysis.getPage().getNamespace(); if ((namespace == null) || (namespace.intValue() == Namespace.TEMPLATE)) { return false; } // Go to the end of the last line String contents = analysis.getContents(); int index = contents.length(); while ((index > 0) && (contents.charAt(index - 1) == '\n')) { index--; } while ((index > 0) && (contents.charAt(index - 1) == ' ')) { index--; } if (index == 0) { return false; } // Check if there's a tag at the end of the last line int lastIndex = index; PageElementTag lastTag = null; if (contents.charAt(index - 1) == '>') { lastTag = analysis.isInTag(index - 1); if (lastTag != null) { index = lastTag.getBeginIndex(); } } // Check if the tag is in the last line int tagEndIndex = tag.getEndIndex(); while ((index > tagEndIndex) && (contents.charAt(index - 1) != '\n')) { index--; if (contents.charAt(index) == '>') { if (analysis.isInTag(index - 1, tag.getType()) != null) { return false; } } } if (index > tagEndIndex) { return false; } // Check if there's an other opening tag before in the page List<PageElementTag> tags = analysis.getTags(tag.getType()); boolean after = false; boolean hasOtherTagBefore = false; for (PageElementTag otherTag : tags) { if (!after) { if (otherTag == tag) { after = true; } else if (!otherTag.isComplete()) { hasOtherTagBefore = true; } } } // Decide what to do if (lastTag == tag) { CheckErrorResult errorResult = createCheckErrorResult(analysis, tag.getBeginIndex(), tag.getEndIndex()); errorResult.addReplacement(""); if (hasOtherTagBefore && (tag.getParametersCount() == 0)) { errorResult.addReplacement( TagBuilder.from(tag.getName(), TagFormat.CLOSE).toString()); } errors.add(errorResult); return true; } if (lastTag != null) { CheckErrorResult errorResult = analyzeArea( analysis, tag, lastTag.getBeginIndex(), tag.getEndIndex(), !hasOtherTagBefore, ActionAlone.ALONE_NOTHING); if (errorResult != null) { errors.add(errorResult); return true; } } else { CheckErrorResult errorResult = analyzeArea( analysis, tag, tag.getBeginIndex(), lastIndex, !hasOtherTagBefore, ActionAlone.ALONE_NOTHING); if (errorResult != null) { errors.add(errorResult); return true; } } return false; }
private boolean analyzeLastLine( PageAnalysis analysis, PageElementTag tag, Collection<CheckErrorResult> errors) { if (!HtmlTagType.CENTER.equals(tag.getType()) && !HtmlTagType.SMALL.equals(tag.getType())) { return false; } Integer namespace = analysis.getPage().getNamespace(); if ((namespace == null) || (namespace.intValue() == Namespace.TEMPLATE)) { return false; } String contents = analysis.getContents(); int index = contents.length(); while ((index > 0) && (contents.charAt(index - 1) == '\n')) { index--; } while ((index > 0) && (contents.charAt(index - 1) == ' ')) { index--; } if (index == 0) { return false; } int lastIndex = index; PageElementTag lastTag = null; if (contents.charAt(index - 1) == '>') { lastTag = analysis.isInTag(index - 1); if (lastTag != null) { index = lastTag.getBeginIndex(); } } int tagEndIndex = tag.getEndIndex(); while ((index > tagEndIndex) && (contents.charAt(index - 1) != '\n')) { index--; if (contents.charAt(index) == '>') { if (analysis.isInTag(index - 1, tag.getType()) != null) { return false; } } } if (index > tagEndIndex) { return false; } List<PageElementTag> tags = analysis.getTags(tag.getType()); boolean after = false; boolean hasOtherTagBefore = false; for (PageElementTag otherTag : tags) { if (!after) { if (otherTag == tag) { after = true; } else if (!otherTag.isComplete()) { hasOtherTagBefore = true; } } } if (lastTag == tag) { CheckErrorResult errorResult = createCheckErrorResult(analysis, tag.getBeginIndex(), tag.getEndIndex()); errorResult.addReplacement(""); if (hasOtherTagBefore && (tag.getParametersCount() == 0)) { errorResult.addReplacement( TagBuilder.from(tag.getName(), TagFormat.CLOSE).toString()); } errors.add(errorResult); return true; } if (lastTag != null) { CheckErrorResult errorResult = analyzeArea( analysis, tag, lastTag.getBeginIndex(), tag.getEndIndex(), !hasOtherTagBefore, ActionAlone.ALONE_NOTHING); if (errorResult != null) { errors.add(errorResult); return true; } } else { CheckErrorResult errorResult = analyzeArea( analysis, tag, tag.getBeginIndex(), lastIndex, !hasOtherTagBefore, ActionAlone.ALONE_NOTHING); if (errorResult != null) { errors.add(errorResult); return true; } } return false; }
private boolean analyzelastline( pageanalysis analysis, pageelementtag tag, collection<checkerrorresult> errors) { if (!htmltagtype.center.equals(tag.gettype()) && !htmltagtype.small.equals(tag.gettype())) { return false; } integer namespace = analysis.getpage().getnamespace(); if ((namespace == null) || (namespace.intvalue() == namespace.template)) { return false; } string contents = analysis.getcontents(); int index = contents.length(); while ((index > 0) && (contents.charat(index - 1) == '\n')) { index--; } while ((index > 0) && (contents.charat(index - 1) == ' ')) { index--; } if (index == 0) { return false; } int lastindex = index; pageelementtag lasttag = null; if (contents.charat(index - 1) == '>') { lasttag = analysis.isintag(index - 1); if (lasttag != null) { index = lasttag.getbeginindex(); } } int tagendindex = tag.getendindex(); while ((index > tagendindex) && (contents.charat(index - 1) != '\n')) { index--; if (contents.charat(index) == '>') { if (analysis.isintag(index - 1, tag.gettype()) != null) { return false; } } } if (index > tagendindex) { return false; } list<pageelementtag> tags = analysis.gettags(tag.gettype()); boolean after = false; boolean hasothertagbefore = false; for (pageelementtag othertag : tags) { if (!after) { if (othertag == tag) { after = true; } else if (!othertag.iscomplete()) { hasothertagbefore = true; } } } if (lasttag == tag) { checkerrorresult errorresult = createcheckerrorresult(analysis, tag.getbeginindex(), tag.getendindex()); errorresult.addreplacement(""); if (hasothertagbefore && (tag.getparameterscount() == 0)) { errorresult.addreplacement( tagbuilder.from(tag.getname(), tagformat.close).tostring()); } errors.add(errorresult); return true; } if (lasttag != null) { checkerrorresult errorresult = analyzearea( analysis, tag, lasttag.getbeginindex(), tag.getendindex(), !hasothertagbefore, actionalone.alone_nothing); if (errorresult != null) { errors.add(errorresult); return true; } } else { checkerrorresult errorresult = analyzearea( analysis, tag, tag.getbeginindex(), lastindex, !hasothertagbefore, actionalone.alone_nothing); if (errorresult != null) { errors.add(errorresult); return true; } } return false; }
RogueScholar/wpcleaner
[ 1, 0, 0, 0 ]
10,562
@Override public CFG createCFG() { CFG cfg = new CFG(null); BasicBlock start = new BasicBlock("PROGRAM-START", BasicBlock.NOT_REDUCIBLE); BasicBlock end = new BasicBlock("PROGRAM-END", BasicBlock.REDUCIBLE_SINGLETON); cfg.start = start; cfg.end = end; cfg.addVertex(start); cfg.addVertex(end); CFG firstCFG = body.get(0).createCFG(); cfg.addVertex(firstCFG.start); cfg.addVertex(firstCFG.end); cfg.addEdge(start, firstCFG.start); BasicBlock prev = firstCFG.end; // If there is only one node, then we would fall through the for loop, so // we just copy over all nodes in the CFG here. TODO: Don't Copy Paste if (body.size() == 1) { firstCFG.vertexSet() .stream() .forEachOrdered(block -> firstCFG .edgesOf(block) .stream() .forEachOrdered(edge -> { BasicBlock src = firstCFG.getEdgeSource(edge); BasicBlock tgt = firstCFG.getEdgeTarget(edge); cfg.addVertex(src); cfg.addVertex(tgt); cfg.addEdge(src, tgt); }) ); } for (ASTNode node : body.subList(1, body.size())) { if (node instanceof IfConditionalASTNode) { Logger.getAnonymousLogger().info(node.getClass().getName()); } CFG stmtCFG = node.createCFG(); if (stmtCFG == null) { continue; } cfg.addVertex(stmtCFG.start); cfg.addVertex(stmtCFG.end); cfg.addEdge(prev, stmtCFG.start); Logger.getAnonymousLogger().info(stmtCFG.toString()); stmtCFG.vertexSet() .stream() .forEachOrdered(block -> stmtCFG .edgesOf(block) .stream() .forEachOrdered(edge -> { BasicBlock src = stmtCFG.getEdgeSource(edge); BasicBlock tgt = stmtCFG.getEdgeTarget(edge); if (node instanceof IfConditionalASTNode) { Logger.getAnonymousLogger().info("Bridging Gap for: " + src + " and " + tgt); } cfg.addVertex(src); cfg.addVertex(tgt); cfg.addEdge(src, tgt); }) ); prev = stmtCFG.end; } cfg.addEdge(prev, end); removeTrivialNodes(cfg); Logger.getAnonymousLogger().info("Reducing..."); Set<BasicBlock> processed = new TreeSet<>(); reduceCFG(cfg, processed); // processed.clear(); // reduceCFG(cfg, processed); return cfg; }
@Override public CFG createCFG() { CFG cfg = new CFG(null); BasicBlock start = new BasicBlock("PROGRAM-START", BasicBlock.NOT_REDUCIBLE); BasicBlock end = new BasicBlock("PROGRAM-END", BasicBlock.REDUCIBLE_SINGLETON); cfg.start = start; cfg.end = end; cfg.addVertex(start); cfg.addVertex(end); CFG firstCFG = body.get(0).createCFG(); cfg.addVertex(firstCFG.start); cfg.addVertex(firstCFG.end); cfg.addEdge(start, firstCFG.start); BasicBlock prev = firstCFG.end; if (body.size() == 1) { firstCFG.vertexSet() .stream() .forEachOrdered(block -> firstCFG .edgesOf(block) .stream() .forEachOrdered(edge -> { BasicBlock src = firstCFG.getEdgeSource(edge); BasicBlock tgt = firstCFG.getEdgeTarget(edge); cfg.addVertex(src); cfg.addVertex(tgt); cfg.addEdge(src, tgt); }) ); } for (ASTNode node : body.subList(1, body.size())) { if (node instanceof IfConditionalASTNode) { Logger.getAnonymousLogger().info(node.getClass().getName()); } CFG stmtCFG = node.createCFG(); if (stmtCFG == null) { continue; } cfg.addVertex(stmtCFG.start); cfg.addVertex(stmtCFG.end); cfg.addEdge(prev, stmtCFG.start); Logger.getAnonymousLogger().info(stmtCFG.toString()); stmtCFG.vertexSet() .stream() .forEachOrdered(block -> stmtCFG .edgesOf(block) .stream() .forEachOrdered(edge -> { BasicBlock src = stmtCFG.getEdgeSource(edge); BasicBlock tgt = stmtCFG.getEdgeTarget(edge); if (node instanceof IfConditionalASTNode) { Logger.getAnonymousLogger().info("Bridging Gap for: " + src + " and " + tgt); } cfg.addVertex(src); cfg.addVertex(tgt); cfg.addEdge(src, tgt); }) ); prev = stmtCFG.end; } cfg.addEdge(prev, end); removeTrivialNodes(cfg); Logger.getAnonymousLogger().info("Reducing..."); Set<BasicBlock> processed = new TreeSet<>(); reduceCFG(cfg, processed); return cfg; }
@override public cfg createcfg() { cfg cfg = new cfg(null); basicblock start = new basicblock("program-start", basicblock.not_reducible); basicblock end = new basicblock("program-end", basicblock.reducible_singleton); cfg.start = start; cfg.end = end; cfg.addvertex(start); cfg.addvertex(end); cfg firstcfg = body.get(0).createcfg(); cfg.addvertex(firstcfg.start); cfg.addvertex(firstcfg.end); cfg.addedge(start, firstcfg.start); basicblock prev = firstcfg.end; if (body.size() == 1) { firstcfg.vertexset() .stream() .foreachordered(block -> firstcfg .edgesof(block) .stream() .foreachordered(edge -> { basicblock src = firstcfg.getedgesource(edge); basicblock tgt = firstcfg.getedgetarget(edge); cfg.addvertex(src); cfg.addvertex(tgt); cfg.addedge(src, tgt); }) ); } for (astnode node : body.sublist(1, body.size())) { if (node instanceof ifconditionalastnode) { logger.getanonymouslogger().info(node.getclass().getname()); } cfg stmtcfg = node.createcfg(); if (stmtcfg == null) { continue; } cfg.addvertex(stmtcfg.start); cfg.addvertex(stmtcfg.end); cfg.addedge(prev, stmtcfg.start); logger.getanonymouslogger().info(stmtcfg.tostring()); stmtcfg.vertexset() .stream() .foreachordered(block -> stmtcfg .edgesof(block) .stream() .foreachordered(edge -> { basicblock src = stmtcfg.getedgesource(edge); basicblock tgt = stmtcfg.getedgetarget(edge); if (node instanceof ifconditionalastnode) { logger.getanonymouslogger().info("bridging gap for: " + src + " and " + tgt); } cfg.addvertex(src); cfg.addvertex(tgt); cfg.addedge(src, tgt); }) ); prev = stmtcfg.end; } cfg.addedge(prev, end); removetrivialnodes(cfg); logger.getanonymouslogger().info("reducing..."); set<basicblock> processed = new treeset<>(); reducecfg(cfg, processed); return cfg; }
LouisJenkinsCS/DSL
[ 1, 0, 0, 0 ]
2,478
public boolean isHeld(IControllerEvent event) { return activationMap.containsKey(event); }
public boolean isHeld(IControllerEvent event) { return activationMap.containsKey(event); }
public boolean isheld(icontrollerevent event) { return activationmap.containskey(event); }
Matthewacon/mh4-hackathon
[ 0, 0, 0, 0 ]
18,874
public void setAir(final World world) { // TODO maybe see if there is a way to find the default "air" for this // world world.setBlockState(this.getPos(), Blocks.AIR.getDefaultState()); }
public void setAir(final World world) { world.setBlockState(this.getPos(), Blocks.AIR.getDefaultState()); }
public void setair(final world world) { world.setblockstate(this.getpos(), blocks.air.getdefaultstate()); }
MetaltyrantMk2/Pokecube-Issues-and-Wiki
[ 1, 0, 0, 0 ]
2,498
@PluginMethod public void writeFile(PluginCall call) { String path = call.getString("path"); String data = call.getString("data"); Boolean recursive = call.getBoolean("recursive", false); if (path == null) { Logger.error(getLogTag(), "No path or filename retrieved from call", null); call.reject("NO_PATH"); return; } if (data == null) { Logger.error(getLogTag(), "No data retrieved from call", null); call.reject("NO_DATA"); return; } String directory = getDirectoryParameter(call); if (directory != null) { if (isPublicDirectory(directory) && !isStoragePermissionGranted()) { requestAllPermissions(call, "permissionCallback"); } else { // create directory because it might not exist File androidDir = implementation.getDirectory(directory); if (androidDir != null) { if (androidDir.exists() || androidDir.mkdirs()) { // path might include directories as well File fileObject = new File(androidDir, path); if (fileObject.getParentFile().exists() || (recursive && fileObject.getParentFile().mkdirs())) { saveFile(call, fileObject, data); } else { call.reject("Parent folder doesn't exist"); } } else { Logger.error(getLogTag(), "Not able to create '" + directory + "'!", null); call.reject("NOT_CREATED_DIR"); } } else { Logger.error(getLogTag(), "Directory ID '" + directory + "' is not supported by plugin", null); call.reject("INVALID_DIR"); } } } else { // check file:// or no scheme uris Uri u = Uri.parse(path); if (u.getScheme() == null || u.getScheme().equals("file")) { File fileObject = new File(u.getPath()); // do not know where the file is being store so checking the permission to be secure // TODO to prevent permission checking we need a property from the call if (!isStoragePermissionGranted()) { requestAllPermissions(call, "permissionCallback"); } else { if ( fileObject.getParentFile() == null || fileObject.getParentFile().exists() || (recursive && fileObject.getParentFile().mkdirs()) ) { saveFile(call, fileObject, data); } else { call.reject("Parent folder doesn't exist"); } } } else { call.reject(u.getScheme() + " scheme not supported"); } } }
@PluginMethod public void writeFile(PluginCall call) { String path = call.getString("path"); String data = call.getString("data"); Boolean recursive = call.getBoolean("recursive", false); if (path == null) { Logger.error(getLogTag(), "No path or filename retrieved from call", null); call.reject("NO_PATH"); return; } if (data == null) { Logger.error(getLogTag(), "No data retrieved from call", null); call.reject("NO_DATA"); return; } String directory = getDirectoryParameter(call); if (directory != null) { if (isPublicDirectory(directory) && !isStoragePermissionGranted()) { requestAllPermissions(call, "permissionCallback"); } else { File androidDir = implementation.getDirectory(directory); if (androidDir != null) { if (androidDir.exists() || androidDir.mkdirs()) { File fileObject = new File(androidDir, path); if (fileObject.getParentFile().exists() || (recursive && fileObject.getParentFile().mkdirs())) { saveFile(call, fileObject, data); } else { call.reject("Parent folder doesn't exist"); } } else { Logger.error(getLogTag(), "Not able to create '" + directory + "'!", null); call.reject("NOT_CREATED_DIR"); } } else { Logger.error(getLogTag(), "Directory ID '" + directory + "' is not supported by plugin", null); call.reject("INVALID_DIR"); } } } else { Uri u = Uri.parse(path); if (u.getScheme() == null || u.getScheme().equals("file")) { File fileObject = new File(u.getPath()); if (!isStoragePermissionGranted()) { requestAllPermissions(call, "permissionCallback"); } else { if ( fileObject.getParentFile() == null || fileObject.getParentFile().exists() || (recursive && fileObject.getParentFile().mkdirs()) ) { saveFile(call, fileObject, data); } else { call.reject("Parent folder doesn't exist"); } } } else { call.reject(u.getScheme() + " scheme not supported"); } } }
@pluginmethod public void writefile(plugincall call) { string path = call.getstring("path"); string data = call.getstring("data"); boolean recursive = call.getboolean("recursive", false); if (path == null) { logger.error(getlogtag(), "no path or filename retrieved from call", null); call.reject("no_path"); return; } if (data == null) { logger.error(getlogtag(), "no data retrieved from call", null); call.reject("no_data"); return; } string directory = getdirectoryparameter(call); if (directory != null) { if (ispublicdirectory(directory) && !isstoragepermissiongranted()) { requestallpermissions(call, "permissioncallback"); } else { file androiddir = implementation.getdirectory(directory); if (androiddir != null) { if (androiddir.exists() || androiddir.mkdirs()) { file fileobject = new file(androiddir, path); if (fileobject.getparentfile().exists() || (recursive && fileobject.getparentfile().mkdirs())) { savefile(call, fileobject, data); } else { call.reject("parent folder doesn't exist"); } } else { logger.error(getlogtag(), "not able to create '" + directory + "'!", null); call.reject("not_created_dir"); } } else { logger.error(getlogtag(), "directory id '" + directory + "' is not supported by plugin", null); call.reject("invalid_dir"); } } } else { uri u = uri.parse(path); if (u.getscheme() == null || u.getscheme().equals("file")) { file fileobject = new file(u.getpath()); if (!isstoragepermissiongranted()) { requestallpermissions(call, "permissioncallback"); } else { if ( fileobject.getparentfile() == null || fileobject.getparentfile().exists() || (recursive && fileobject.getparentfile().mkdirs()) ) { savefile(call, fileobject, data); } else { call.reject("parent folder doesn't exist"); } } } else { call.reject(u.getscheme() + " scheme not supported"); } } }
RetoeGo/Stuby
[ 1, 0, 0, 0 ]
2,512
public MyPair<List<List<FpgaInternalMove>>,List<MyPair<FpgaInternalState,List<FpgaInternalMove>>>> getNextStates(FpgaInternalState state){ if(this.theMachine.isTerminal(state.getCompactMachineState())) { return null; } // Retrieve all legal moves List<List<CompactMove>> movesForAllRoles; try { movesForAllRoles = this.theMachine.getAllLegalMoves(state.getCompactMachineState()); } catch (MoveDefinitionException e) { GamerLogger.logError("StateMachine", "[FakeFPGALibrary] Error when getting all legal moves!"); throw new RuntimeException("StateMachine - [FakeFPGALibrary] Error when getting all legal moves!"); } List<List<FpgaInternalMove>> internalMovesForAllRoles = new ArrayList<List<FpgaInternalMove>>(); for(List<CompactMove> movesForOneRole : movesForAllRoles) { List<FpgaInternalMove> internalMovesForOneRole = new ArrayList<FpgaInternalMove>(); for(CompactMove move : movesForOneRole) { internalMovesForOneRole.add(new FpgaInternalMove(move)); } internalMovesForAllRoles.add(internalMovesForOneRole); } // Retrieve all joint moves and next states List<List<CompactMove>> allJointMoves; try { allJointMoves = this.theMachine.getLegalJointMoves(state.getCompactMachineState()); } catch (MoveDefinitionException | StateMachineException e) { GamerLogger.logError("StateMachine", "[FakeFPGALibrary] Error when getting all legal joint moves!"); throw new RuntimeException("StateMachine - [FakeFPGALibrary] Error when getting all legal joint moves!"); } List<MyPair<FpgaInternalState,List<FpgaInternalMove>>> internalJointMovesAndNextStates = new ArrayList<MyPair<FpgaInternalState,List<FpgaInternalMove>>>(); CompactMachineState nextState; if(allJointMoves == null) { System.out.println("Null joint moves"); } for(List<CompactMove> jointMove : allJointMoves) { nextState = this.theMachine.getCompactNextState(state.getCompactMachineState(), jointMove); List<FpgaInternalMove> internalJointMove = new ArrayList<FpgaInternalMove>(); for(CompactMove move : jointMove) { internalJointMove.add(new FpgaInternalMove(move)); } internalJointMovesAndNextStates.add(new MyPair<FpgaInternalState,List<FpgaInternalMove>>(new FpgaInternalState(nextState), internalJointMove)); } return new MyPair<List<List<FpgaInternalMove>>,List<MyPair<FpgaInternalState,List<FpgaInternalMove>>>>(internalMovesForAllRoles, internalJointMovesAndNextStates); }
public MyPair<List<List<FpgaInternalMove>>,List<MyPair<FpgaInternalState,List<FpgaInternalMove>>>> getNextStates(FpgaInternalState state){ if(this.theMachine.isTerminal(state.getCompactMachineState())) { return null; } List<List<CompactMove>> movesForAllRoles; try { movesForAllRoles = this.theMachine.getAllLegalMoves(state.getCompactMachineState()); } catch (MoveDefinitionException e) { GamerLogger.logError("StateMachine", "[FakeFPGALibrary] Error when getting all legal moves!"); throw new RuntimeException("StateMachine - [FakeFPGALibrary] Error when getting all legal moves!"); } List<List<FpgaInternalMove>> internalMovesForAllRoles = new ArrayList<List<FpgaInternalMove>>(); for(List<CompactMove> movesForOneRole : movesForAllRoles) { List<FpgaInternalMove> internalMovesForOneRole = new ArrayList<FpgaInternalMove>(); for(CompactMove move : movesForOneRole) { internalMovesForOneRole.add(new FpgaInternalMove(move)); } internalMovesForAllRoles.add(internalMovesForOneRole); } List<List<CompactMove>> allJointMoves; try { allJointMoves = this.theMachine.getLegalJointMoves(state.getCompactMachineState()); } catch (MoveDefinitionException | StateMachineException e) { GamerLogger.logError("StateMachine", "[FakeFPGALibrary] Error when getting all legal joint moves!"); throw new RuntimeException("StateMachine - [FakeFPGALibrary] Error when getting all legal joint moves!"); } List<MyPair<FpgaInternalState,List<FpgaInternalMove>>> internalJointMovesAndNextStates = new ArrayList<MyPair<FpgaInternalState,List<FpgaInternalMove>>>(); CompactMachineState nextState; if(allJointMoves == null) { System.out.println("Null joint moves"); } for(List<CompactMove> jointMove : allJointMoves) { nextState = this.theMachine.getCompactNextState(state.getCompactMachineState(), jointMove); List<FpgaInternalMove> internalJointMove = new ArrayList<FpgaInternalMove>(); for(CompactMove move : jointMove) { internalJointMove.add(new FpgaInternalMove(move)); } internalJointMovesAndNextStates.add(new MyPair<FpgaInternalState,List<FpgaInternalMove>>(new FpgaInternalState(nextState), internalJointMove)); } return new MyPair<List<List<FpgaInternalMove>>,List<MyPair<FpgaInternalState,List<FpgaInternalMove>>>>(internalMovesForAllRoles, internalJointMovesAndNextStates); }
public mypair<list<list<fpgainternalmove>>,list<mypair<fpgainternalstate,list<fpgainternalmove>>>> getnextstates(fpgainternalstate state){ if(this.themachine.isterminal(state.getcompactmachinestate())) { return null; } list<list<compactmove>> movesforallroles; try { movesforallroles = this.themachine.getalllegalmoves(state.getcompactmachinestate()); } catch (movedefinitionexception e) { gamerlogger.logerror("statemachine", "[fakefpgalibrary] error when getting all legal moves!"); throw new runtimeexception("statemachine - [fakefpgalibrary] error when getting all legal moves!"); } list<list<fpgainternalmove>> internalmovesforallroles = new arraylist<list<fpgainternalmove>>(); for(list<compactmove> movesforonerole : movesforallroles) { list<fpgainternalmove> internalmovesforonerole = new arraylist<fpgainternalmove>(); for(compactmove move : movesforonerole) { internalmovesforonerole.add(new fpgainternalmove(move)); } internalmovesforallroles.add(internalmovesforonerole); } list<list<compactmove>> alljointmoves; try { alljointmoves = this.themachine.getlegaljointmoves(state.getcompactmachinestate()); } catch (movedefinitionexception | statemachineexception e) { gamerlogger.logerror("statemachine", "[fakefpgalibrary] error when getting all legal joint moves!"); throw new runtimeexception("statemachine - [fakefpgalibrary] error when getting all legal joint moves!"); } list<mypair<fpgainternalstate,list<fpgainternalmove>>> internaljointmovesandnextstates = new arraylist<mypair<fpgainternalstate,list<fpgainternalmove>>>(); compactmachinestate nextstate; if(alljointmoves == null) { system.out.println("null joint moves"); } for(list<compactmove> jointmove : alljointmoves) { nextstate = this.themachine.getcompactnextstate(state.getcompactmachinestate(), jointmove); list<fpgainternalmove> internaljointmove = new arraylist<fpgainternalmove>(); for(compactmove move : jointmove) { internaljointmove.add(new fpgainternalmove(move)); } internaljointmovesandnextstates.add(new mypair<fpgainternalstate,list<fpgainternalmove>>(new fpgainternalstate(nextstate), internaljointmove)); } return new mypair<list<list<fpgainternalmove>>,list<mypair<fpgainternalstate,list<fpgainternalmove>>>>(internalmovesforallroles, internaljointmovesandnextstates); }
Lucsparidans/GGP-Project
[ 1, 0, 0, 0 ]
10,940
public void setWindow(SpectralWindow window) { // Use the same window everywhere. for (int i = 0; i < ffts.length; i++) { ffts[i].setWindow(window); // TODO review, both sides or just one iffts[i].setWindow(window); } }
public void setWindow(SpectralWindow window) { for (int i = 0; i < ffts.length; i++) { ffts[i].setWindow(window); iffts[i].setWindow(window); } }
public void setwindow(spectralwindow window) { for (int i = 0; i < ffts.length; i++) { ffts[i].setwindow(window); iffts[i].setwindow(window); } }
RubbaBoy/jsyn
[ 1, 0, 0, 0 ]
19,154
public void registBroadcastReceiver(){ mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(QuickstartPreferences.REGISTRATION_READY)){ }else if(action.equals(QuickstartPreferences.REGISTRATION_GENERATING)){ }else if(action.equals(QuickstartPreferences.REGISTRATION_COMPLETE)){ Log.d(TAG, "token is set in gcm_token"); gcm_token = intent.getStringExtra("token"); Log.d(TAG, "gcm_token: " + gcm_token); ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL("http://165.194.104.22:5000/gcm"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //implement below code if token is send to server con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); String parameter = URLEncoder.encode("register_id", "UTF-8") + "=" + URLEncoder.encode(gcm_token, "UTF-8"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(parameter); wr.flush(); BufferedReader rd = null; if (con.getResponseCode() == 200) { Log.d(TAG,"gcm_token is sent"); } else { rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.e(TAG,rd.readLine()); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Boolean aBoolean) { } }); ConnectServer.getInstance().execute(); } } }; }
public void registBroadcastReceiver(){ mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(QuickstartPreferences.REGISTRATION_READY)){ }else if(action.equals(QuickstartPreferences.REGISTRATION_GENERATING)){ }else if(action.equals(QuickstartPreferences.REGISTRATION_COMPLETE)){ Log.d(TAG, "token is set in gcm_token"); gcm_token = intent.getStringExtra("token"); Log.d(TAG, "gcm_token: " + gcm_token); ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL("http://165.194.104.22:5000/gcm"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); String parameter = URLEncoder.encode("register_id", "UTF-8") + "=" + URLEncoder.encode(gcm_token, "UTF-8"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(parameter); wr.flush(); BufferedReader rd = null; if (con.getResponseCode() == 200) { Log.d(TAG,"gcm_token is sent"); } else { rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.e(TAG,rd.readLine()); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Boolean aBoolean) { } }); ConnectServer.getInstance().execute(); } } }; }
public void registbroadcastreceiver(){ mregistrationbroadcastreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { string action = intent.getaction(); if(action.equals(quickstartpreferences.registration_ready)){ }else if(action.equals(quickstartpreferences.registration_generating)){ }else if(action.equals(quickstartpreferences.registration_complete)){ log.d(tag, "token is set in gcm_token"); gcm_token = intent.getstringextra("token"); log.d(tag, "gcm_token: " + gcm_token); connectserver.getinstance().setasnctask(new asynctask<string, void, boolean>() { @override protected boolean doinbackground(string... params) { url obj = null; try { obj = new url("http://165.194.104.22:5000/gcm"); httpurlconnection con = (httpurlconnection) obj.openconnection(); con = connectserver.getinstance().setheader(con); con.setdooutput(true); string parameter = urlencoder.encode("register_id", "utf-8") + "=" + urlencoder.encode(gcm_token, "utf-8"); outputstreamwriter wr = new outputstreamwriter(con.getoutputstream()); wr.write(parameter); wr.flush(); bufferedreader rd = null; if (con.getresponsecode() == 200) { log.d(tag,"gcm_token is sent"); } else { rd = new bufferedreader(new inputstreamreader(con.geterrorstream(), "utf-8")); log.e(tag,rd.readline()); } } catch (ioexception e) { e.printstacktrace(); } return null; } @override protected void onpostexecute(boolean aboolean) { } }); connectserver.getinstance().execute(); } } }; }
KyoungjunPark/SmartClass
[ 0, 1, 0, 0 ]
10,985
static void addChildElement( BasePropertyWriter p, Map<String, BasePropertyWriter> childElements, FlowElementsContainer process, Collection<ElementParameters> simulationParameters, List<ItemDefinition> itemDefinitions, List<RootElement> rootElements) { childElements.put(p.getElement().getId(), p); if (p.getElement() instanceof FlowElement) { // compatibility fix: boundary events should always occur at the bottom // otherwise they will be drawn at an incorrect position on load if (p instanceof BoundaryEventPropertyWriter) { process.getFlowElements().add((FlowElement) p.getElement()); } else { process.getFlowElements().add(0, (FlowElement) p.getElement()); p.getElement(); } } else if (p.getElement() instanceof Artifact) { if (process instanceof Process) { ((Process) process).getArtifacts().add((Artifact) p.getElement()); } else if (process instanceof SubProcess) { ((SubProcess) process).getArtifacts().add((Artifact) p.getElement()); } } if (p instanceof PropertyWriter) { ElementParameters sp = ((PropertyWriter) p).getSimulationParameters(); if (sp != null) { simulationParameters.add(sp); } } itemDefinitions.addAll(p.getItemDefinitions()); rootElements.addAll(p.getRootElements()); rootElements.addAll(p.getInterfaces()); }
static void addChildElement( BasePropertyWriter p, Map<String, BasePropertyWriter> childElements, FlowElementsContainer process, Collection<ElementParameters> simulationParameters, List<ItemDefinition> itemDefinitions, List<RootElement> rootElements) { childElements.put(p.getElement().getId(), p); if (p.getElement() instanceof FlowElement) { if (p instanceof BoundaryEventPropertyWriter) { process.getFlowElements().add((FlowElement) p.getElement()); } else { process.getFlowElements().add(0, (FlowElement) p.getElement()); p.getElement(); } } else if (p.getElement() instanceof Artifact) { if (process instanceof Process) { ((Process) process).getArtifacts().add((Artifact) p.getElement()); } else if (process instanceof SubProcess) { ((SubProcess) process).getArtifacts().add((Artifact) p.getElement()); } } if (p instanceof PropertyWriter) { ElementParameters sp = ((PropertyWriter) p).getSimulationParameters(); if (sp != null) { simulationParameters.add(sp); } } itemDefinitions.addAll(p.getItemDefinitions()); rootElements.addAll(p.getRootElements()); rootElements.addAll(p.getInterfaces()); }
static void addchildelement( basepropertywriter p, map<string, basepropertywriter> childelements, flowelementscontainer process, collection<elementparameters> simulationparameters, list<itemdefinition> itemdefinitions, list<rootelement> rootelements) { childelements.put(p.getelement().getid(), p); if (p.getelement() instanceof flowelement) { if (p instanceof boundaryeventpropertywriter) { process.getflowelements().add((flowelement) p.getelement()); } else { process.getflowelements().add(0, (flowelement) p.getelement()); p.getelement(); } } else if (p.getelement() instanceof artifact) { if (process instanceof process) { ((process) process).getartifacts().add((artifact) p.getelement()); } else if (process instanceof subprocess) { ((subprocess) process).getartifacts().add((artifact) p.getelement()); } } if (p instanceof propertywriter) { elementparameters sp = ((propertywriter) p).getsimulationparameters(); if (sp != null) { simulationparameters.add(sp); } } itemdefinitions.addall(p.getitemdefinitions()); rootelements.addall(p.getrootelements()); rootelements.addall(p.getinterfaces()); }
Prodaxis/kie-wb-common
[ 0, 0, 1, 0 ]
19,324
@Test public void testGetWithTwoTags() { int limit = THREAD_COUNT; // TODO How to set this? queryParameters.put("limit", Arrays.asList(String.valueOf(limit))); // TODO pick iteration and pod at random queryParameters.put("tag", Arrays.asList("iteration:1", "podname:" + workerPodNames.get(0))); logger.info("Query parameters: " + queryParameters.size()); List<Datum> traces = simpleRestClient.getTraces(queryParameters, limit); Instant testEndTime = Instant.now(); long duration = Duration.between(testStartTime, testEndTime).toMillis(); logger.info("Retrieval of " + limit + " spans in testGetWithTwoTags took " + numberFormat.format(duration) + " milliseconds"); assertNotNull(traces); assertEquals(limit, traces.size()); // TODO add more validation }
@Test public void testGetWithTwoTags() { int limit = THREAD_COUNT; queryParameters.put("limit", Arrays.asList(String.valueOf(limit))); queryParameters.put("tag", Arrays.asList("iteration:1", "podname:" + workerPodNames.get(0))); logger.info("Query parameters: " + queryParameters.size()); List<Datum> traces = simpleRestClient.getTraces(queryParameters, limit); Instant testEndTime = Instant.now(); long duration = Duration.between(testStartTime, testEndTime).toMillis(); logger.info("Retrieval of " + limit + " spans in testGetWithTwoTags took " + numberFormat.format(duration) + " milliseconds"); assertNotNull(traces); assertEquals(limit, traces.size()); }
@test public void testgetwithtwotags() { int limit = thread_count; queryparameters.put("limit", arrays.aslist(string.valueof(limit))); queryparameters.put("tag", arrays.aslist("iteration:1", "podname:" + workerpodnames.get(0))); logger.info("query parameters: " + queryparameters.size()); list<datum> traces = simplerestclient.gettraces(queryparameters, limit); instant testendtime = instant.now(); long duration = duration.between(teststarttime, testendtime).tomillis(); logger.info("retrieval of " + limit + " spans in testgetwithtwotags took " + numberformat.format(duration) + " milliseconds"); assertnotnull(traces); assertequals(limit, traces.size()); }
PikBot/jaeger-performance
[ 1, 1, 0, 0 ]
19,350
@Override public List<InputSplit> getSplits(JobContext context) throws IOException { final Configuration conf = context.getConfiguration(); final KijiURI inputTableURI = getInputTableURI(conf); final Kiji kiji = Kiji.Factory.open(inputTableURI, conf); final KijiTable table = kiji.openTable(inputTableURI.getTable()); final HTableInterface htable = HBaseKijiTable.downcast(table).openHTableConnection(); try { final List<InputSplit> splits = Lists.newArrayList(); for (KijiRegion region : table.getRegions()) { final byte[] startKey = region.getStartKey(); // TODO: a smart way to get which location is most relevant. final String location = region.getLocations().isEmpty() ? null : region.getLocations().iterator().next(); final TableSplit tableSplit = new TableSplit( htable.getTableName(), startKey, region.getEndKey(), location); splits.add(new KijiTableSplit(tableSplit, startKey)); } return splits; } finally { htable.close(); } }
@Override public List<InputSplit> getSplits(JobContext context) throws IOException { final Configuration conf = context.getConfiguration(); final KijiURI inputTableURI = getInputTableURI(conf); final Kiji kiji = Kiji.Factory.open(inputTableURI, conf); final KijiTable table = kiji.openTable(inputTableURI.getTable()); final HTableInterface htable = HBaseKijiTable.downcast(table).openHTableConnection(); try { final List<InputSplit> splits = Lists.newArrayList(); for (KijiRegion region : table.getRegions()) { final byte[] startKey = region.getStartKey(); final String location = region.getLocations().isEmpty() ? null : region.getLocations().iterator().next(); final TableSplit tableSplit = new TableSplit( htable.getTableName(), startKey, region.getEndKey(), location); splits.add(new KijiTableSplit(tableSplit, startKey)); } return splits; } finally { htable.close(); } }
@override public list<inputsplit> getsplits(jobcontext context) throws ioexception { final configuration conf = context.getconfiguration(); final kijiuri inputtableuri = getinputtableuri(conf); final kiji kiji = kiji.factory.open(inputtableuri, conf); final kijitable table = kiji.opentable(inputtableuri.gettable()); final htableinterface htable = hbasekijitable.downcast(table).openhtableconnection(); try { final list<inputsplit> splits = lists.newarraylist(); for (kijiregion region : table.getregions()) { final byte[] startkey = region.getstartkey(); final string location = region.getlocations().isempty() ? null : region.getlocations().iterator().next(); final tablesplit tablesplit = new tablesplit( htable.gettablename(), startkey, region.getendkey(), location); splits.add(new kijitablesplit(tablesplit, startkey)); } return splits; } finally { htable.close(); } }
NeoGridBR/kiji-schema
[ 1, 0, 0, 0 ]
11,228
private void onHeartClicked(MenuItem item) { ArrayList favoritesList = null; String filename = "favorites.json"; FileInputStream inputStream = null; try { inputStream = openFileInput(filename); String json = IOUtils.toString(inputStream, "UTF-8"); Gson gson = new Gson(); favoritesList = gson.fromJson(json, ArrayList.class); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } if(favoritesList == null) return; SharedPreferences sharedPreferences = getSharedPreferences("pref", Context.MODE_PRIVATE); Boolean isFavorited = sharedPreferences.getBoolean(stopName + "Favorited", false); if (!isFavorited) { //favoriting item.setIcon(R.drawable.ic_favorite_white_24dp); item.getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent), PorterDuff.Mode.SRC_IN); favoritesList.add(stopName); //TODO make sure this doesn't break anything isFavorited = true; } else { //unfavoriting item.setIcon(R.drawable.ic_favorite_border_white_24dp); item.getIcon().setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN); favoritesList.remove(stopName); isFavorited = false; } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(stopName + "Favorited", isFavorited); editor.putString(stopName, stopId); //Stores stop id value with stopName key editor.apply(); gsonFileUtils.writeListToFile(favoritesList, this); }
private void onHeartClicked(MenuItem item) { ArrayList favoritesList = null; String filename = "favorites.json"; FileInputStream inputStream = null; try { inputStream = openFileInput(filename); String json = IOUtils.toString(inputStream, "UTF-8"); Gson gson = new Gson(); favoritesList = gson.fromJson(json, ArrayList.class); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } if(favoritesList == null) return; SharedPreferences sharedPreferences = getSharedPreferences("pref", Context.MODE_PRIVATE); Boolean isFavorited = sharedPreferences.getBoolean(stopName + "Favorited", false); if (!isFavorited) { item.setIcon(R.drawable.ic_favorite_white_24dp); item.getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent), PorterDuff.Mode.SRC_IN); favoritesList.add(stopName); isFavorited = true; } else { item.setIcon(R.drawable.ic_favorite_border_white_24dp); item.getIcon().setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN); favoritesList.remove(stopName); isFavorited = false; } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(stopName + "Favorited", isFavorited); editor.putString(stopName, stopId); editor.apply(); gsonFileUtils.writeListToFile(favoritesList, this); }
private void onheartclicked(menuitem item) { arraylist favoriteslist = null; string filename = "favorites.json"; fileinputstream inputstream = null; try { inputstream = openfileinput(filename); string json = ioutils.tostring(inputstream, "utf-8"); gson gson = new gson(); favoriteslist = gson.fromjson(json, arraylist.class); inputstream.close(); } catch (ioexception e) { e.printstacktrace(); } if(favoriteslist == null) return; sharedpreferences sharedpreferences = getsharedpreferences("pref", context.mode_private); boolean isfavorited = sharedpreferences.getboolean(stopname + "favorited", false); if (!isfavorited) { item.seticon(r.drawable.ic_favorite_white_24dp); item.geticon().setcolorfilter(contextcompat.getcolor(getapplicationcontext(), r.color.coloraccent), porterduff.mode.src_in); favoriteslist.add(stopname); isfavorited = true; } else { item.seticon(r.drawable.ic_favorite_border_white_24dp); item.geticon().setcolorfilter(color.parsecolor("#ffffff"), porterduff.mode.src_in); favoriteslist.remove(stopname); isfavorited = false; } sharedpreferences.editor editor = sharedpreferences.edit(); editor.putboolean(stopname + "favorited", isfavorited); editor.putstring(stopname, stopid); editor.apply(); gsonfileutils.writelisttofile(favoriteslist, this); }
Newbhope/cu-bus
[ 0, 0, 1, 0 ]
11,229
private void getStopLocation(String stopId) { final RequestQueue queue = Volley.newRequestQueue(this); Uri stopUrlUri = Uri.parse(getStopUrl) .buildUpon() .appendQueryParameter(key_param, getResources().getString(R.string.api_key)) .appendQueryParameter(stop_param, stopId) .build(); String stopUrl = stopUrlUri.toString(); JsonObjectRequest locationRequest = new JsonObjectRequest(Request.Method.GET, stopUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { stopLatlon = new double[2]; JSONArray stopsArray = response.getJSONArray("stops"); JSONObject stop = stopsArray.getJSONObject(0); JSONArray pointsArray = stop.getJSONArray("stop_points"); JSONObject point = pointsArray.getJSONObject(0); //TODO: determine which corner I should use stopLatlon[0] = point.getDouble("stop_lat"); stopLatlon[1] = point.getDouble("stop_lon"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(locationRequest); }
private void getStopLocation(String stopId) { final RequestQueue queue = Volley.newRequestQueue(this); Uri stopUrlUri = Uri.parse(getStopUrl) .buildUpon() .appendQueryParameter(key_param, getResources().getString(R.string.api_key)) .appendQueryParameter(stop_param, stopId) .build(); String stopUrl = stopUrlUri.toString(); JsonObjectRequest locationRequest = new JsonObjectRequest(Request.Method.GET, stopUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { stopLatlon = new double[2]; JSONArray stopsArray = response.getJSONArray("stops"); JSONObject stop = stopsArray.getJSONObject(0); JSONArray pointsArray = stop.getJSONArray("stop_points"); JSONObject point = pointsArray.getJSONObject(0); stopLatlon[0] = point.getDouble("stop_lat"); stopLatlon[1] = point.getDouble("stop_lon"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(locationRequest); }
private void getstoplocation(string stopid) { final requestqueue queue = volley.newrequestqueue(this); uri stopurluri = uri.parse(getstopurl) .buildupon() .appendqueryparameter(key_param, getresources().getstring(r.string.api_key)) .appendqueryparameter(stop_param, stopid) .build(); string stopurl = stopurluri.tostring(); jsonobjectrequest locationrequest = new jsonobjectrequest(request.method.get, stopurl, null, new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { try { stoplatlon = new double[2]; jsonarray stopsarray = response.getjsonarray("stops"); jsonobject stop = stopsarray.getjsonobject(0); jsonarray pointsarray = stop.getjsonarray("stop_points"); jsonobject point = pointsarray.getjsonobject(0); stoplatlon[0] = point.getdouble("stop_lat"); stoplatlon[1] = point.getdouble("stop_lon"); } catch (jsonexception e) { e.printstacktrace(); } } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { } }); queue.add(locationrequest); }
Newbhope/cu-bus
[ 1, 0, 0, 0 ]
11,234
private void buildWeightList( List<TDataNodeInfo> onlineDataNodes, List<TRegionReplicaSet> allocatedRegions) { // TODO: The remaining disk capacity of DataNode can also be calculated into the weightList int maximumRegionNum = 0; Map<TDataNodeLocation, Integer> countMap = new HashMap<>(); for (TDataNodeInfo dataNodeInfo : onlineDataNodes) { maxId = Math.max(maxId, dataNodeInfo.getLocation().getDataNodeId()); countMap.put(dataNodeInfo.getLocation(), 0); } for (TRegionReplicaSet regionReplicaSet : allocatedRegions) { for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) { countMap.computeIfPresent(dataNodeLocation, (dataNode, count) -> (count + 1)); maximumRegionNum = Math.max(maximumRegionNum, countMap.get(dataNodeLocation)); } } weightList = new ArrayList<>(); for (Map.Entry<TDataNodeLocation, Integer> countEntry : countMap.entrySet()) { int weight = maximumRegionNum - countEntry.getValue() + 1; // Repeatedly add DataNode copies equal to the number of their weights for (int repeat = 0; repeat < weight; repeat++) { weightList.add(countEntry.getKey().deepCopy()); } } }
private void buildWeightList( List<TDataNodeInfo> onlineDataNodes, List<TRegionReplicaSet> allocatedRegions) { int maximumRegionNum = 0; Map<TDataNodeLocation, Integer> countMap = new HashMap<>(); for (TDataNodeInfo dataNodeInfo : onlineDataNodes) { maxId = Math.max(maxId, dataNodeInfo.getLocation().getDataNodeId()); countMap.put(dataNodeInfo.getLocation(), 0); } for (TRegionReplicaSet regionReplicaSet : allocatedRegions) { for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) { countMap.computeIfPresent(dataNodeLocation, (dataNode, count) -> (count + 1)); maximumRegionNum = Math.max(maximumRegionNum, countMap.get(dataNodeLocation)); } } weightList = new ArrayList<>(); for (Map.Entry<TDataNodeLocation, Integer> countEntry : countMap.entrySet()) { int weight = maximumRegionNum - countEntry.getValue() + 1; for (int repeat = 0; repeat < weight; repeat++) { weightList.add(countEntry.getKey().deepCopy()); } } }
private void buildweightlist( list<tdatanodeinfo> onlinedatanodes, list<tregionreplicaset> allocatedregions) { int maximumregionnum = 0; map<tdatanodelocation, integer> countmap = new hashmap<>(); for (tdatanodeinfo datanodeinfo : onlinedatanodes) { maxid = math.max(maxid, datanodeinfo.getlocation().getdatanodeid()); countmap.put(datanodeinfo.getlocation(), 0); } for (tregionreplicaset regionreplicaset : allocatedregions) { for (tdatanodelocation datanodelocation : regionreplicaset.getdatanodelocations()) { countmap.computeifpresent(datanodelocation, (datanode, count) -> (count + 1)); maximumregionnum = math.max(maximumregionnum, countmap.get(datanodelocation)); } } weightlist = new arraylist<>(); for (map.entry<tdatanodelocation, integer> countentry : countmap.entryset()) { int weight = maximumregionnum - countentry.getvalue() + 1; for (int repeat = 0; repeat < weight; repeat++) { weightlist.add(countentry.getkey().deepcopy()); } } }
RYH61/iotdb
[ 1, 0, 0, 0 ]
11,434
public static Connection getConnectionDB() { File dbDir = new File(CoreContext.DB_DATA_PATH); if (!dbDir.exists()) dbDir.mkdir(); Connection connection = null; try { // если базы нет, то она будет создана автоматически, // иначе будет создано подключение к существующей базе connection = DriverManager.getConnection( "jdbc:hsqldb:file:" + dbDir.getPath() + File.separator + CoreContext.DB_LIBRARY_FILE_NAME, "SA", ""); } catch (SQLException e) { // TODO change to log System.err.println("ERROR: failed to create connection with db"); e.printStackTrace(); // TODO change System.exit(1) System.exit(1); } // TODO version db // SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase( // new File(dbDir, CoreContext.DB_LIBRARY_FILE_NAME), null); // // if (db.getVersion() != version) { // db.beginTransaction(); // try { // int currVersion = db.getVersion(); // if (currVersion == 0) { // onCreate(db); // }; // onUpgrade(db, currVersion); // db.setVersion(version); // db.setTransactionSuccessful(); // } finally { // db.endTransaction(); // } // } return connection; }
public static Connection getConnectionDB() { File dbDir = new File(CoreContext.DB_DATA_PATH); if (!dbDir.exists()) dbDir.mkdir(); Connection connection = null; try { "jdbc:hsqldb:file:" + dbDir.getPath() + File.separator + CoreContext.DB_LIBRARY_FILE_NAME, "SA", ""); } catch (SQLException e) { System.err.println("ERROR: failed to create connection with db"); e.printStackTrace(); System.exit(1); } return connection; }
public static connection getconnectiondb() { file dbdir = new file(corecontext.db_data_path); if (!dbdir.exists()) dbdir.mkdir(); connection connection = null; try { "jdbc:hsqldb:file:" + dbdir.getpath() + file.separator + corecontext.db_library_file_name, "sa", ""); } catch (sqlexception e) { system.err.println("error: failed to create connection with db"); e.printstacktrace(); system.exit(1); } return connection; }
NikitaFeodonit/bqtj
[ 1, 1, 0, 0 ]
3,313
public void setOverrides(final LegacyOverridesMixin overrides) { this.overrides = overrides; }
public void setOverrides(final LegacyOverridesMixin overrides) { this.overrides = overrides; }
public void setoverrides(final legacyoverridesmixin overrides) { this.overrides = overrides; }
KellyShao/tessera
[ 0, 0, 0, 1 ]
19,819
private float getFuelAbsorptionCoefficient() { // TODO: Lookup type of fuel and get data from there return 0.5f; }
private float getFuelAbsorptionCoefficient() { return 0.5f; }
private float getfuelabsorptioncoefficient() { return 0.5f; }
RAFIWE/BigReactors-1.7.10-Fixed
[ 0, 1, 0, 0 ]
3,445
@Override public void teleopPeriodic() { SmartDashboard.putString("Robot/GamePhase", "TELEOP"); double timestamp = Timer.getFPGATimestamp(); double throttle = mControlBoard.getThrottle(); double turn = mControlBoard.getTurn(); try { if (mSuperstructure.isDriverControlled()) { DriveSignal command = ArcadeDriveHelper.arcadeDrive(mControlBoard.getThrottle(), mControlBoard.getTurn(), true /* TODO: Decide squared inputs or not */).scale(mSuperstructure.isDrivingReversed() ? -1 : 1)/*.scale(6)*/; mDrive.setOpenLoop(command); // mDrive.setVelocity(command, new DriveSignal( // command.scale(Constants.kDriveLeftKv).getLeft() + Math.copySign(Constants.kDriveLeftVIntercept, command.getLeft()), // command.scale(Constants.kDriveLeftKv).getRight() + Math.copySign(Constants.kDriveLeftVIntercept, command.getRight()) // )); if(mControlBoard.getEjectPanel()) mPanelHandler.setWantedState(PanelHandler.WantedState.EJECT); if(mControlBoard.getIntake()) mCargoIntake.setWantedState(CargoIntake.WantedState.INTAKE); if(mControlBoard.getTestButtonOne()) mCargoIntake.setWantedState(CargoIntake.WantedState.HOLD); if(mControlBoard.getEjectCargo()) mCargoIntake.setWantedState(CargoIntake.WantedState.EJECT); if(mControlBoard.getTestButtonTwo()) mPanelHandler.checkSystem("variant"); if (mControlBoard.getReverseDirection()) { mSuperstructure.reverseDrivingDirection(); } else if (mControlBoard.getDriveToSelectedTarget()) { mSuperstructure.setWantedState(Superstructure.WantedState.ALIGN_AND_INTAKE_CARGO); } else if (mControlBoard.getClimb()) { mSuperstructure.setWantedState(Superstructure.WantedState.CLIMB); } // TODO (for button person): add buttons for all superstructure wanted states } else if (mControlBoard.getReturnToDriverControl()) { mSuperstructure.setWantedState(Superstructure.WantedState.DRIVER_CONTROL); } } catch (Throwable t) { Logger.logThrowableCrash(t); throw t; } outputToSmartDashboard(); }
@Override public void teleopPeriodic() { SmartDashboard.putString("Robot/GamePhase", "TELEOP"); double timestamp = Timer.getFPGATimestamp(); double throttle = mControlBoard.getThrottle(); double turn = mControlBoard.getTurn(); try { if (mSuperstructure.isDriverControlled()) { DriveSignal command = ArcadeDriveHelper.arcadeDrive(mControlBoard.getThrottle(), mControlBoard.getTurn(), true).scale(mSuperstructure.isDrivingReversed() ? -1 : 1; mDrive.setOpenLoop(command); if(mControlBoard.getEjectPanel()) mPanelHandler.setWantedState(PanelHandler.WantedState.EJECT); if(mControlBoard.getIntake()) mCargoIntake.setWantedState(CargoIntake.WantedState.INTAKE); if(mControlBoard.getTestButtonOne()) mCargoIntake.setWantedState(CargoIntake.WantedState.HOLD); if(mControlBoard.getEjectCargo()) mCargoIntake.setWantedState(CargoIntake.WantedState.EJECT); if(mControlBoard.getTestButtonTwo()) mPanelHandler.checkSystem("variant"); if (mControlBoard.getReverseDirection()) { mSuperstructure.reverseDrivingDirection(); } else if (mControlBoard.getDriveToSelectedTarget()) { mSuperstructure.setWantedState(Superstructure.WantedState.ALIGN_AND_INTAKE_CARGO); } else if (mControlBoard.getClimb()) { mSuperstructure.setWantedState(Superstructure.WantedState.CLIMB); } } else if (mControlBoard.getReturnToDriverControl()) { mSuperstructure.setWantedState(Superstructure.WantedState.DRIVER_CONTROL); } } catch (Throwable t) { Logger.logThrowableCrash(t); throw t; } outputToSmartDashboard(); }
@override public void teleopperiodic() { smartdashboard.putstring("robot/gamephase", "teleop"); double timestamp = timer.getfpgatimestamp(); double throttle = mcontrolboard.getthrottle(); double turn = mcontrolboard.getturn(); try { if (msuperstructure.isdrivercontrolled()) { drivesignal command = arcadedrivehelper.arcadedrive(mcontrolboard.getthrottle(), mcontrolboard.getturn(), true).scale(msuperstructure.isdrivingreversed() ? -1 : 1; mdrive.setopenloop(command); if(mcontrolboard.getejectpanel()) mpanelhandler.setwantedstate(panelhandler.wantedstate.eject); if(mcontrolboard.getintake()) mcargointake.setwantedstate(cargointake.wantedstate.intake); if(mcontrolboard.gettestbuttonone()) mcargointake.setwantedstate(cargointake.wantedstate.hold); if(mcontrolboard.getejectcargo()) mcargointake.setwantedstate(cargointake.wantedstate.eject); if(mcontrolboard.gettestbuttontwo()) mpanelhandler.checksystem("variant"); if (mcontrolboard.getreversedirection()) { msuperstructure.reversedrivingdirection(); } else if (mcontrolboard.getdrivetoselectedtarget()) { msuperstructure.setwantedstate(superstructure.wantedstate.align_and_intake_cargo); } else if (mcontrolboard.getclimb()) { msuperstructure.setwantedstate(superstructure.wantedstate.climb); } } else if (mcontrolboard.getreturntodrivercontrol()) { msuperstructure.setwantedstate(superstructure.wantedstate.driver_control); } } catch (throwable t) { logger.logthrowablecrash(t); throw t; } outputtosmartdashboard(); }
MaximillianHays/2019-DeepSpace
[ 0, 1, 0, 0 ]
3,595
public ByteBuffer encode() throws IOException { // TODO: an implementation that can use more than one chunk ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (DataOutputStream os = new DataOutputStream(bout)) { /* add the data for each entry */ for (ByteBuffer entry : entries) { /* copy to temp buffer */ byte[] temp = new byte[entry.limit()]; entry.position(0); entry.get(temp); entry.position(0); /* copy to output stream */ os.write(temp); } /* write the chunk lengths */ int prev = 0; for (ByteBuffer entry : entries) { /* * since each file is stored in the only chunk, just write the * delta-encoded file size */ int chunkSize = entry.limit(); os.writeInt(chunkSize - prev); prev = chunkSize; } /* we only used one chunk due to a limitation of the implementation */ bout.write(1); /* wrap the bytes from the stream in a buffer */ byte[] bytes = bout.toByteArray(); return ByteBuffer.wrap(bytes); } }
public ByteBuffer encode() throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (DataOutputStream os = new DataOutputStream(bout)) { for (ByteBuffer entry : entries) { byte[] temp = new byte[entry.limit()]; entry.position(0); entry.get(temp); entry.position(0); os.write(temp); } int prev = 0; for (ByteBuffer entry : entries) { int chunkSize = entry.limit(); os.writeInt(chunkSize - prev); prev = chunkSize; } bout.write(1); byte[] bytes = bout.toByteArray(); return ByteBuffer.wrap(bytes); } }
public bytebuffer encode() throws ioexception { bytearrayoutputstream bout = new bytearrayoutputstream(); try (dataoutputstream os = new dataoutputstream(bout)) { for (bytebuffer entry : entries) { byte[] temp = new byte[entry.limit()]; entry.position(0); entry.get(temp); entry.position(0); os.write(temp); } int prev = 0; for (bytebuffer entry : entries) { int chunksize = entry.limit(); os.writeint(chunksize - prev); prev = chunksize; } bout.write(1); byte[] bytes = bout.tobytearray(); return bytebuffer.wrap(bytes); } }
Lmctruck30/mopar
[ 0, 1, 0, 0 ]
11,794
public ClassInfo extendedFindClass(String className) { // ClassDoc.findClass has this bug that we're working around here: // If you have a class PackageManager with an inner class PackageInfo // and you call it with "PackageInfo" it doesn't find it. return searchInnerClasses(className.split("\\."), 0); }
public ClassInfo extendedFindClass(String className) { return searchInnerClasses(className.split("\\."), 0); }
public classinfo extendedfindclass(string classname) { return searchinnerclasses(classname.split("\\."), 0); }
Keneral/ae1
[ 0, 0, 1, 0 ]
12,226
@Override public void buildFunctionIfNecessary(FunctionConf functionConf) { // Snapshot the directory before installing dependencies List<Path> beforeSnapshot = getDirectorySnapshot(functionConf); loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Copying Greengrass SDK"); copySdk(log, functionConf, resourceHelper, ioHelper); if (hasDependencies(functionConf.getBuildDirectory())) { loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Installing Python dependencies"); installDependencies(functionConf); } // Snapshot the directory after installing dependencies List<Path> afterSnapshot = getDirectorySnapshot(functionConf); List<Path> addedFiles = new ArrayList<>(afterSnapshot); addedFiles.removeAll(beforeSnapshot); loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Packaging function for AWS Lambda"); File tempFile = Try.of(() -> ioHelper.getTempFile("python-lambda-build", "zip")).get(); // Get the directories, longest named directories first List<Path> addedDirectories = addedFiles .stream() .filter(path -> path.toFile().isDirectory()) .sorted(Comparator.comparingInt(path -> path.toString().length()).reversed()) .collect(Collectors.toList()); // Get the possible Python directories (don't include *dist-info and bin) // NOTE: This is an esoteric fix for Zope being broken which breaks Twisted - https://github.com/kpdyer/fteproxy/issues/66 List<Path> possibleBrokenPythonDirectories = addedDirectories .stream() .filter(path -> !path.toString().endsWith(DIST_INFO)) .filter(path -> !path.toString().endsWith(BIN)) .filter(path -> !path.resolve(INIT_PY).toFile().exists()) .collect(Collectors.toList()); // "Touch" the file to fix this issue possibleBrokenPythonDirectories.stream() .map(path -> path.resolve(INIT_PY).toFile()) .forEach(this::touchAndIgnoreExceptions); ZipUtil.pack(functionConf.getBuildDirectory().toFile(), tempFile); moveDeploymentPackage(functionConf, tempFile); }
@Override public void buildFunctionIfNecessary(FunctionConf functionConf) { List<Path> beforeSnapshot = getDirectorySnapshot(functionConf); loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Copying Greengrass SDK"); copySdk(log, functionConf, resourceHelper, ioHelper); if (hasDependencies(functionConf.getBuildDirectory())) { loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Installing Python dependencies"); installDependencies(functionConf); } List<Path> afterSnapshot = getDirectorySnapshot(functionConf); List<Path> addedFiles = new ArrayList<>(afterSnapshot); addedFiles.removeAll(beforeSnapshot); loggingHelper.logInfoWithName(log, functionConf.getFunctionName(), "Packaging function for AWS Lambda"); File tempFile = Try.of(() -> ioHelper.getTempFile("python-lambda-build", "zip")).get(); List<Path> addedDirectories = addedFiles .stream() .filter(path -> path.toFile().isDirectory()) .sorted(Comparator.comparingInt(path -> path.toString().length()).reversed()) .collect(Collectors.toList()); List<Path> possibleBrokenPythonDirectories = addedDirectories .stream() .filter(path -> !path.toString().endsWith(DIST_INFO)) .filter(path -> !path.toString().endsWith(BIN)) .filter(path -> !path.resolve(INIT_PY).toFile().exists()) .collect(Collectors.toList()); possibleBrokenPythonDirectories.stream() .map(path -> path.resolve(INIT_PY).toFile()) .forEach(this::touchAndIgnoreExceptions); ZipUtil.pack(functionConf.getBuildDirectory().toFile(), tempFile); moveDeploymentPackage(functionConf, tempFile); }
@override public void buildfunctionifnecessary(functionconf functionconf) { list<path> beforesnapshot = getdirectorysnapshot(functionconf); logginghelper.loginfowithname(log, functionconf.getfunctionname(), "copying greengrass sdk"); copysdk(log, functionconf, resourcehelper, iohelper); if (hasdependencies(functionconf.getbuilddirectory())) { logginghelper.loginfowithname(log, functionconf.getfunctionname(), "installing python dependencies"); installdependencies(functionconf); } list<path> aftersnapshot = getdirectorysnapshot(functionconf); list<path> addedfiles = new arraylist<>(aftersnapshot); addedfiles.removeall(beforesnapshot); logginghelper.loginfowithname(log, functionconf.getfunctionname(), "packaging function for aws lambda"); file tempfile = try.of(() -> iohelper.gettempfile("python-lambda-build", "zip")).get(); list<path> addeddirectories = addedfiles .stream() .filter(path -> path.tofile().isdirectory()) .sorted(comparator.comparingint(path -> path.tostring().length()).reversed()) .collect(collectors.tolist()); list<path> possiblebrokenpythondirectories = addeddirectories .stream() .filter(path -> !path.tostring().endswith(dist_info)) .filter(path -> !path.tostring().endswith(bin)) .filter(path -> !path.resolve(init_py).tofile().exists()) .collect(collectors.tolist()); possiblebrokenpythondirectories.stream() .map(path -> path.resolve(init_py).tofile()) .foreach(this::touchandignoreexceptions); ziputil.pack(functionconf.getbuilddirectory().tofile(), tempfile); movedeploymentpackage(functionconf, tempfile); }
QuinnCiccoretti/aws-greengrass-provisioner
[ 0, 0, 0, 0 ]
20,549
private static Reporter trade(String starting_date, final String ending_date, Portfolio portfolio, Reporter reporter, String order_file_name,boolean include_trading_fees,boolean pay_dividends) { int final_time = 0; //last day must also be included Strategy strategy = new Strategy(portfolio, portfolio.getDatabase(),include_trading_fees); Long starting_time = System.currentTimeMillis(); System.out.println("Trading simulation starts: "); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //0. Write dividend dates to dividend array //todo: implement array List<String> dividend_dates = new ArrayList<>(); if (pay_dividends){dividend_dates = dividend_dates(starting_date,ending_date);} while (final_time == 0) { //TECHNICAL if (starting_date.equals(ending_date)) { final_time++; } //Check if we have data about this day in the database? Maybe it's Christmas or maybe it's the weekend. if (portfolio.getDatabase().contains_day(starting_date)) { //1. Dividend payments to other parties portfolio.exercise_dividends(starting_date); //2. Do I have any rights or obligations (Options) / Obligations(Stocks)? portfolio.exercise_obligations(starting_date,strategy.isUse_trading_fees()); //3. Strategy((1.)unemployment rate, (2.) P/E (3) moving average (4) RSI) strategy.setPortfolio(strategy.trade_all(starting_date)); //4. Pay dividends to the owners if (pay_dividends && dividend_dates.contains(starting_date)){portfolio.pay_dividends(starting_date);} } //TODO: remove the else part later else{ portfolio.exercise_obligations(starting_date,strategy.isUse_trading_fees()); portfolio.exercise_dividends(starting_date); } // todo: remove if(portfolio.get_cash_available(starting_date) < 0){System.out.println(portfolio.get_cash_available(starting_date));} reporter.report(portfolio,starting_date); starting_date = LocalDate.parse(starting_date).plusDays(1).toString(); } portfolio.order_results_to_file(order_file_name,ending_date); Long ending_time = System.currentTimeMillis(); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); System.out.println("Trading simulation ended: "); System.out.println("Simulation took " + Math.round((ending_time - starting_time) * 0.001 * 1 / 60) + " minutes to complete"); return reporter; }
private static Reporter trade(String starting_date, final String ending_date, Portfolio portfolio, Reporter reporter, String order_file_name,boolean include_trading_fees,boolean pay_dividends) { int final_time = 0; Strategy strategy = new Strategy(portfolio, portfolio.getDatabase(),include_trading_fees); Long starting_time = System.currentTimeMillis(); System.out.println("Trading simulation starts: "); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); List<String> dividend_dates = new ArrayList<>(); if (pay_dividends){dividend_dates = dividend_dates(starting_date,ending_date);} while (final_time == 0) { if (starting_date.equals(ending_date)) { final_time++; } if (portfolio.getDatabase().contains_day(starting_date)) { portfolio.exercise_dividends(starting_date); portfolio.exercise_obligations(starting_date,strategy.isUse_trading_fees()); strategy.setPortfolio(strategy.trade_all(starting_date)); if (pay_dividends && dividend_dates.contains(starting_date)){portfolio.pay_dividends(starting_date);} } else{ portfolio.exercise_obligations(starting_date,strategy.isUse_trading_fees()); portfolio.exercise_dividends(starting_date); } if(portfolio.get_cash_available(starting_date) < 0){System.out.println(portfolio.get_cash_available(starting_date));} reporter.report(portfolio,starting_date); starting_date = LocalDate.parse(starting_date).plusDays(1).toString(); } portfolio.order_results_to_file(order_file_name,ending_date); Long ending_time = System.currentTimeMillis(); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); System.out.println("Trading simulation ended: "); System.out.println("Simulation took " + Math.round((ending_time - starting_time) * 0.001 * 1 / 60) + " minutes to complete"); return reporter; }
private static reporter trade(string starting_date, final string ending_date, portfolio portfolio, reporter reporter, string order_file_name,boolean include_trading_fees,boolean pay_dividends) { int final_time = 0; strategy strategy = new strategy(portfolio, portfolio.getdatabase(),include_trading_fees); long starting_time = system.currenttimemillis(); system.out.println("trading simulation starts: "); system.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); list<string> dividend_dates = new arraylist<>(); if (pay_dividends){dividend_dates = dividend_dates(starting_date,ending_date);} while (final_time == 0) { if (starting_date.equals(ending_date)) { final_time++; } if (portfolio.getdatabase().contains_day(starting_date)) { portfolio.exercise_dividends(starting_date); portfolio.exercise_obligations(starting_date,strategy.isuse_trading_fees()); strategy.setportfolio(strategy.trade_all(starting_date)); if (pay_dividends && dividend_dates.contains(starting_date)){portfolio.pay_dividends(starting_date);} } else{ portfolio.exercise_obligations(starting_date,strategy.isuse_trading_fees()); portfolio.exercise_dividends(starting_date); } if(portfolio.get_cash_available(starting_date) < 0){system.out.println(portfolio.get_cash_available(starting_date));} reporter.report(portfolio,starting_date); starting_date = localdate.parse(starting_date).plusdays(1).tostring(); } portfolio.order_results_to_file(order_file_name,ending_date); long ending_time = system.currenttimemillis(); system.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); system.out.println("trading simulation ended: "); system.out.println("simulation took " + math.round((ending_time - starting_time) * 0.001 * 1 / 60) + " minutes to complete"); return reporter; }
KGKallasmaa/S_P500_trading_options
[ 1, 1, 0, 0 ]
12,644
public void sendMessage(long chatId, Response response) { var request = responseToSendMessageConverter.convert(response, chatId); telegramBot.execute(request, new Callback<>() { @Override public void onResponse(SendMessage sendMessage, SendResponse sendResponse) { // Do nothing } @Override public void onFailure(SendMessage sendMessage, IOException e) { log.warn("Error occurred when sending message {}, exception: {}", request, e); } }); }
public void sendMessage(long chatId, Response response) { var request = responseToSendMessageConverter.convert(response, chatId); telegramBot.execute(request, new Callback<>() { @Override public void onResponse(SendMessage sendMessage, SendResponse sendResponse) { } @Override public void onFailure(SendMessage sendMessage, IOException e) { log.warn("Error occurred when sending message {}, exception: {}", request, e); } }); }
public void sendmessage(long chatid, response response) { var request = responsetosendmessageconverter.convert(response, chatid); telegrambot.execute(request, new callback<>() { @override public void onresponse(sendmessage sendmessage, sendresponse sendresponse) { } @override public void onfailure(sendmessage sendmessage, ioexception e) { log.warn("error occurred when sending message {}, exception: {}", request, e); } }); }
MisterRnobe/sodexo-tg-bot
[ 1, 0, 0, 0 ]
12,762
public static DatabindException from(SerializerProvider ctxt, String msg, Throwable problem) { // 17-Aug-2015, tatu: As per [databind#903] this is bit problematic as // SerializerProvider instance does not currently hold on to generator... return new DatabindException(ctxt.getGenerator(), msg, problem); }
public static DatabindException from(SerializerProvider ctxt, String msg, Throwable problem) { return new DatabindException(ctxt.getGenerator(), msg, problem); }
public static databindexception from(serializerprovider ctxt, string msg, throwable problem) { return new databindexception(ctxt.getgenerator(), msg, problem); }
Migwel/jackson-databind
[ 0, 0, 1, 0 ]
12,861
private void parseMedia() { assertTypeAndAdvance(PXStylesheetTokenType.MEDIA); // TODO: support media types, NOT, and ONLY. Skipping for now while (isType(PXStylesheetTokenType.IDENTIFIER)) { advance(); } // 'and' may appear here advanceIfIsType(PXStylesheetTokenType.AND); // parse optional expressions if (isType(PXStylesheetTokenType.LPAREN)) { parseMediaExpressions(); } // parse body if (isType(PXStylesheetTokenType.LCURLY)) { try { advance(); while (currentLexeme != null && currentLexeme.getType() != PXStylesheetTokenType.EOF && !isType(PXStylesheetTokenType.RCURLY)) { parseRuleSet(); } advanceIfIsType(PXStylesheetTokenType.RCURLY, "Expected @media body closing curly brace"); } finally { // reset active media query to none currentStyleSheet.setActiveMediaQuery(null); } } }
private void parseMedia() { assertTypeAndAdvance(PXStylesheetTokenType.MEDIA); while (isType(PXStylesheetTokenType.IDENTIFIER)) { advance(); } advanceIfIsType(PXStylesheetTokenType.AND); if (isType(PXStylesheetTokenType.LPAREN)) { parseMediaExpressions(); } if (isType(PXStylesheetTokenType.LCURLY)) { try { advance(); while (currentLexeme != null && currentLexeme.getType() != PXStylesheetTokenType.EOF && !isType(PXStylesheetTokenType.RCURLY)) { parseRuleSet(); } advanceIfIsType(PXStylesheetTokenType.RCURLY, "Expected @media body closing curly brace"); } finally { currentStyleSheet.setActiveMediaQuery(null); } } }
private void parsemedia() { asserttypeandadvance(pxstylesheettokentype.media); while (istype(pxstylesheettokentype.identifier)) { advance(); } advanceifistype(pxstylesheettokentype.and); if (istype(pxstylesheettokentype.lparen)) { parsemediaexpressions(); } if (istype(pxstylesheettokentype.lcurly)) { try { advance(); while (currentlexeme != null && currentlexeme.gettype() != pxstylesheettokentype.eof && !istype(pxstylesheettokentype.rcurly)) { parseruleset(); } advanceifistype(pxstylesheettokentype.rcurly, "expected @media body closing curly brace"); } finally { currentstylesheet.setactivemediaquery(null); } } }
Pixate/pixate-freestyle-android
[ 1, 0, 0, 0 ]
21,298
private void init() { try { // TODO: detect if already have a gradle setup // TODO: later, use always same and symlink if possible to save time setupBuildFiles(); Files.createDirectories(srcFolder); Files.walkFileTree(projectHome.toPath(), new FileTransferProcessor()); } catch (Exception e) { throw new RuntimeException(e); } }
private void init() { try { setupBuildFiles(); Files.createDirectories(srcFolder); Files.walkFileTree(projectHome.toPath(), new FileTransferProcessor()); } catch (Exception e) { throw new RuntimeException(e); } }
private void init() { try { setupbuildfiles(); files.createdirectories(srcfolder); files.walkfiletree(projecthome.topath(), new filetransferprocessor()); } catch (exception e) { throw new runtimeexception(e); } }
K1UBC/BlangModel
[ 1, 0, 0, 0 ]
30,159
public <T> DynamicType.Builder<T> apply(DynamicType.Builder<T> builder) { TypeDescription description = builder.toTypeDescription(); List<MethodDescription> methods = getMethodDescriptionList(description); enhanceCasesByDynamicDefinitions(methods); builder = enhanceCasesByOverrides(builder, description, methods); if(cases.isEmpty()) return builder; Case[] cases = this.cases.toArray(new Case[this.cases.size()]); //Lets cache presence of methods per condition boolean[] hasMatchedMethods = new boolean[cases.length]; boolean[] hasOpositeMatchedMethods = new boolean[cases.length]; for (int i=0; i<cases.length; i++) { hasMatchedMethods[i] = hasMatch(methods, cases[i].getMatcher()); hasOpositeMatchedMethods[i] = hasMatch(methods, not(cases[i].getMatcher())); } BigInteger permutationsTotal = BigInteger.ONE.shiftLeft(cases.length).subtract(BigInteger.ONE); for(BigInteger currentPermutation = BigInteger.ONE; currentPermutation.compareTo(permutationsTotal)<=0; currentPermutation = currentPermutation.add(BigInteger.ONE)) { //Finding Base Implementation: mostly recently added implementation (not Advice) Implementation baseImplementation = null; for(int i=cases.length-1; i>=0; i--) { if(currentPermutation.testBit(i)) { Implementation impl = cases[i].getImplementation(); if(baseImplementation==null) baseImplementation=cases[i].getImplementation(); if(!(impl instanceof Advice)) { baseImplementation = impl; break; } } } ElementMatcher.Junction<? super MethodDescription> matcher = any(); Implementation implementation = baseImplementation; int i = cases.length-1; for(; i>=0; i--) { Case c = cases[i]; boolean caseIncluded = currentPermutation.testBit(i); // Included or excluded if(!caseIncluded) continue; //Advice will not be included in any case: moving forward if(!(caseIncluded?hasMatchedMethods[i]:hasOpositeMatchedMethods[i])) break; //No such methods at all matcher = matcher.and(caseIncluded?c.getMatcher():not(c.getMatcher())); if(caseIncluded && c.getImplementation() instanceof Advice && c.getImplementation() != baseImplementation) { implementation = ((Advice)c.getImplementation()).wrap(implementation); } } if(i<0) builder = builder.method(matcher).intercept(implementation); } return builder; }
public <T> DynamicType.Builder<T> apply(DynamicType.Builder<T> builder) { TypeDescription description = builder.toTypeDescription(); List<MethodDescription> methods = getMethodDescriptionList(description); enhanceCasesByDynamicDefinitions(methods); builder = enhanceCasesByOverrides(builder, description, methods); if(cases.isEmpty()) return builder; Case[] cases = this.cases.toArray(new Case[this.cases.size()]); boolean[] hasMatchedMethods = new boolean[cases.length]; boolean[] hasOpositeMatchedMethods = new boolean[cases.length]; for (int i=0; i<cases.length; i++) { hasMatchedMethods[i] = hasMatch(methods, cases[i].getMatcher()); hasOpositeMatchedMethods[i] = hasMatch(methods, not(cases[i].getMatcher())); } BigInteger permutationsTotal = BigInteger.ONE.shiftLeft(cases.length).subtract(BigInteger.ONE); for(BigInteger currentPermutation = BigInteger.ONE; currentPermutation.compareTo(permutationsTotal)<=0; currentPermutation = currentPermutation.add(BigInteger.ONE)) { Implementation baseImplementation = null; for(int i=cases.length-1; i>=0; i--) { if(currentPermutation.testBit(i)) { Implementation impl = cases[i].getImplementation(); if(baseImplementation==null) baseImplementation=cases[i].getImplementation(); if(!(impl instanceof Advice)) { baseImplementation = impl; break; } } } ElementMatcher.Junction<? super MethodDescription> matcher = any(); Implementation implementation = baseImplementation; int i = cases.length-1; for(; i>=0; i--) { Case c = cases[i]; boolean caseIncluded = currentPermutation.testBit(i); if(!caseIncluded) continue; if(!(caseIncluded?hasMatchedMethods[i]:hasOpositeMatchedMethods[i])) break; matcher = matcher.and(caseIncluded?c.getMatcher():not(c.getMatcher())); if(caseIncluded && c.getImplementation() instanceof Advice && c.getImplementation() != baseImplementation) { implementation = ((Advice)c.getImplementation()).wrap(implementation); } } if(i<0) builder = builder.method(matcher).intercept(implementation); } return builder; }
public <t> dynamictype.builder<t> apply(dynamictype.builder<t> builder) { typedescription description = builder.totypedescription(); list<methoddescription> methods = getmethoddescriptionlist(description); enhancecasesbydynamicdefinitions(methods); builder = enhancecasesbyoverrides(builder, description, methods); if(cases.isempty()) return builder; case[] cases = this.cases.toarray(new case[this.cases.size()]); boolean[] hasmatchedmethods = new boolean[cases.length]; boolean[] hasopositematchedmethods = new boolean[cases.length]; for (int i=0; i<cases.length; i++) { hasmatchedmethods[i] = hasmatch(methods, cases[i].getmatcher()); hasopositematchedmethods[i] = hasmatch(methods, not(cases[i].getmatcher())); } biginteger permutationstotal = biginteger.one.shiftleft(cases.length).subtract(biginteger.one); for(biginteger currentpermutation = biginteger.one; currentpermutation.compareto(permutationstotal)<=0; currentpermutation = currentpermutation.add(biginteger.one)) { implementation baseimplementation = null; for(int i=cases.length-1; i>=0; i--) { if(currentpermutation.testbit(i)) { implementation impl = cases[i].getimplementation(); if(baseimplementation==null) baseimplementation=cases[i].getimplementation(); if(!(impl instanceof advice)) { baseimplementation = impl; break; } } } elementmatcher.junction<? super methoddescription> matcher = any(); implementation implementation = baseimplementation; int i = cases.length-1; for(; i>=0; i--) { case c = cases[i]; boolean caseincluded = currentpermutation.testbit(i); if(!caseincluded) continue; if(!(caseincluded?hasmatchedmethods[i]:hasopositematchedmethods[i])) break; matcher = matcher.and(caseincluded?c.getmatcher():not(c.getmatcher())); if(caseincluded && c.getimplementation() instanceof advice && c.getimplementation() != baseimplementation) { implementation = ((advice)c.getimplementation()).wrap(implementation); } } if(i<0) builder = builder.method(matcher).intercept(implementation); } return builder; }
OrienteerBAP/Transponder
[ 0, 1, 0, 0 ]
30,162
@Ignore @Test public void testDelete() throws Exception { final Map<String, Object> headers = new HashMap<String, Object>(); // parameter type is String headers.put("CamelGoogleDrive.fileId", null); // parameter type is String headers.put("CamelGoogleDrive.parentId", null); final com.google.api.services.drive.Drive.Parents.Delete result = requestBodyAndHeaders("direct://DELETE", null, headers); assertNotNull("delete result", result); LOG.debug("delete: " + result); }
@Ignore @Test public void testDelete() throws Exception { final Map<String, Object> headers = new HashMap<String, Object>(); headers.put("CamelGoogleDrive.fileId", null); headers.put("CamelGoogleDrive.parentId", null); final com.google.api.services.drive.Drive.Parents.Delete result = requestBodyAndHeaders("direct://DELETE", null, headers); assertNotNull("delete result", result); LOG.debug("delete: " + result); }
@ignore @test public void testdelete() throws exception { final map<string, object> headers = new hashmap<string, object>(); headers.put("camelgoogledrive.fileid", null); headers.put("camelgoogledrive.parentid", null); final com.google.api.services.drive.drive.parents.delete result = requestbodyandheaders("direct://delete", null, headers); assertnotnull("delete result", result); log.debug("delete: " + result); }
NelloCarotenuto/Weakness-Detector-for-Java
[ 1, 0, 0, 0 ]
30,229
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; // the expected question for the obs in the hl7 message has to be coded Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); // hacky way to get the newly added obs and make tests on it List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
@Test public void processMessage_shouldSetValue_CodedMatchingABooleanConceptForObsIfTheAnswerIs0Or1AndQuestionDatatypeIsCoded() throws Exception { ObsService os = Context.getObsService(); String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||7^^^^||Collet^Test^Chebaskwony||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|2|NM|21^CIVIL STATUS^99DCT||1|||||||||20080206"; Assert.assertEquals("Coded", Context.getConceptService().getConcept(21).getDatatype().getName()); List<Obs> oldList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Message hl7message = parser.parse(hl7string); router.processMessage(hl7message); List<Obs> newList = os.getObservationsByPersonAndConcept(new Person(7), new Concept(21)); Obs newObservation = null; for (Obs newObs : newList) { if (!oldList.contains(newObs) && !newObs.isObsGrouping()) { newObservation = newObs; } } Assert.assertEquals(Context.getConceptService().getTrueConcept(), newObservation.getValueCoded()); }
@test public void processmessage_shouldsetvalue_codedmatchingabooleanconceptforobsiftheansweris0or1andquestiondatatypeiscoded() throws exception { obsservice os = context.getobsservice(); string hl7string = "msh|^~\\&|formentry|amrs.eld|hl7listener|amrs.eld|20080226102656||oru^r01|jqnfhkktouez8kztk6zo|p|2.5|1||||||||16^amrs.eld.formid\r" + "pid|||7^^^^||collet^test^chebaskwony||\r" + "pv1||o|1^unknown location||||1^super user (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||v\r" + "orc|re||||||||20080226102537|1^super user\r" + "obr|1|||1238^medical record observations^99dct\r" + "obx|2|nm|21^civil status^99dct||1|||||||||20080206"; assert.assertequals("coded", context.getconceptservice().getconcept(21).getdatatype().getname()); list<obs> oldlist = os.getobservationsbypersonandconcept(new person(7), new concept(21)); message hl7message = parser.parse(hl7string); router.processmessage(hl7message); list<obs> newlist = os.getobservationsbypersonandconcept(new person(7), new concept(21)); obs newobservation = null; for (obs newobs : newlist) { if (!oldlist.contains(newobs) && !newobs.isobsgrouping()) { newobservation = newobs; } } assert.assertequals(context.getconceptservice().gettrueconcept(), newobservation.getvaluecoded()); }
RuiDTLima/diffuzz
[ 1, 0, 0, 0 ]
22,244
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private static void processPendingMoveToTrash(final Context context, Store remoteStore, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } Mailbox oldMailbox = getRemoteMailboxForMessage(context, oldMessage); if (oldMailbox == null) { return; } if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } Folder remoteFolder = remoteStore.getFolder(oldMailbox.mServerId); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mServerId); if (!remoteTrashFolder.exists()) { remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } if (remoteTrashFolder.exists()) { remoteTrashFolder.open(OpenMode.READ_WRITE); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { @Override public void onMessageUidChange(Message message, String newUid) { ContentValues cv = new ContentValues(); cv.put(MessageColumns.SERVER_ID, newUid); context.getContentResolver().update(newMessage.getUri(), cv, null, null); } @Override public void onMessageNotFound(Message message) { context.getContentResolver().delete(newMessage.getUri(), null, null); } }); remoteTrashFolder.close(false); } remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private static void processpendingmovetotrash(final context context, store remotestore, mailbox newmailbox, emailcontent.message oldmessage, final emailcontent.message newmessage) throws messagingexception { if (newmessage.mserverid == null || newmessage.mserverid.equals("") || newmessage.mserverid.startswith(local_serverid_prefix)) { return; } mailbox oldmailbox = getremotemailboxformessage(context, oldmessage); if (oldmailbox == null) { return; } if (oldmailbox.mtype == mailbox.type_trash) { return; } folder remotefolder = remotestore.getfolder(oldmailbox.mserverid); if (!remotefolder.exists()) { return; } remotefolder.open(openmode.read_write); if (remotefolder.getmode() != openmode.read_write) { remotefolder.close(false); return; } message remotemessage = remotefolder.getmessage(oldmessage.mserverid); if (remotemessage == null) { remotefolder.close(false); return; } folder remotetrashfolder = remotestore.getfolder(newmailbox.mserverid); if (!remotetrashfolder.exists()) { remotetrashfolder.create(foldertype.holds_messages); } if (remotetrashfolder.exists()) { remotetrashfolder.open(openmode.read_write); if (remotetrashfolder.getmode() != openmode.read_write) { remotefolder.close(false); remotetrashfolder.close(false); return; } remotefolder.copymessages(new message[] { remotemessage }, remotetrashfolder, new folder.messageupdatecallbacks() { @override public void onmessageuidchange(message message, string newuid) { contentvalues cv = new contentvalues(); cv.put(messagecolumns.server_id, newuid); context.getcontentresolver().update(newmessage.geturi(), cv, null, null); } @override public void onmessagenotfound(message message) { context.getcontentresolver().delete(newmessage.geturi(), null, null); } }); remotetrashfolder.close(false); } remotemessage.setflag(flag.deleted, true); remotefolder.expunge(); remotefolder.close(false); }
Keneral/apackages
[ 1, 0, 0, 0 ]
14,054
@Override public void enableDebug() { // Turn on Crunch runtime error catching. //TODO: allow configurable getConfiguration().setBoolean("crunch.debug", true); }
@Override public void enableDebug() { getConfiguration().setBoolean("crunch.debug", true); }
@override public void enabledebug() { getconfiguration().setboolean("crunch.debug", true); }
KeerthiYanda91/crunch
[ 1, 0, 0, 0 ]
14,145
private Optional<DecodedJWT> authenticateRequest(HttpServletRequest req, HttpServletResponse resp) { String authHeader = StringUtil.trimToEmpty(req.getHeader("Authorization")); String authBearerToken = authHeader.replaceFirst("^Bearer ", ""); if (authHeader.isEmpty()) { LOG.warn("No Authorization header in request"); resp.setStatus(HTTP_FORBIDDEN); return Optional.empty(); } if (authBearerToken.isEmpty()) { LOG.warn("No Authorization Bearer token in request"); resp.setStatus(HTTP_FORBIDDEN); return Optional.empty(); } DecodedJWT decodedJWT = JWT.decode(authBearerToken); RSAKeyProvider keyProvider = new RSAKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) { Optional<JSONWebKey> key = jwtKeyProvider.getKey(keyId); if (!key.isPresent()) { // TODO what do? resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return null; } try { // https://github.com/auth0/jwks-rsa-java/blob/master/src/main/java/com/auth0/jwk/Jwk.java#L171 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); JSONWebKey jwk = key.get(); BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.n)); BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.e)); return (RSAPublicKey) keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); // String keyDataString = key.get().x509CertificateChain.get(0); // byte[] keyData = Base64.getDecoder().decode(keyDataString.getBytes(StandardCharsets.UTF_8)); // return (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(keyData)); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public RSAPrivateKey getPrivateKey() { return null; } @Override public String getPrivateKeyId() { return null; } }; Algorithm algorithm; switch (decodedJWT.getAlgorithm()) { case "RS256": algorithm = Algorithm.RSA256(keyProvider); break; default: resp.setStatus(HTTP_BAD_REQUEST); LOG.error("Unknown algorithm {}", decodedJWT.getAlgorithm()); return Optional.empty(); } JWTVerifier jwtVerifier = JWT.require(algorithm) .acceptLeeway(Duration.ofMinutes(5).getSeconds()) .withIssuer("https://api.botframework.com") // .withAudience(ap) TODO verify audience if the app id .build(); jwtVerifier.verify(authBearerToken); return Optional.of(decodedJWT); }
private Optional<DecodedJWT> authenticateRequest(HttpServletRequest req, HttpServletResponse resp) { String authHeader = StringUtil.trimToEmpty(req.getHeader("Authorization")); String authBearerToken = authHeader.replaceFirst("^Bearer ", ""); if (authHeader.isEmpty()) { LOG.warn("No Authorization header in request"); resp.setStatus(HTTP_FORBIDDEN); return Optional.empty(); } if (authBearerToken.isEmpty()) { LOG.warn("No Authorization Bearer token in request"); resp.setStatus(HTTP_FORBIDDEN); return Optional.empty(); } DecodedJWT decodedJWT = JWT.decode(authBearerToken); RSAKeyProvider keyProvider = new RSAKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) { Optional<JSONWebKey> key = jwtKeyProvider.getKey(keyId); if (!key.isPresent()) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return null; } try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); JSONWebKey jwk = key.get(); BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.n)); BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.e)); return (RSAPublicKey) keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public RSAPrivateKey getPrivateKey() { return null; } @Override public String getPrivateKeyId() { return null; } }; Algorithm algorithm; switch (decodedJWT.getAlgorithm()) { case "RS256": algorithm = Algorithm.RSA256(keyProvider); break; default: resp.setStatus(HTTP_BAD_REQUEST); LOG.error("Unknown algorithm {}", decodedJWT.getAlgorithm()); return Optional.empty(); } JWTVerifier jwtVerifier = JWT.require(algorithm) .acceptLeeway(Duration.ofMinutes(5).getSeconds()) .withIssuer("https://api.botframework.com") .build(); jwtVerifier.verify(authBearerToken); return Optional.of(decodedJWT); }
private optional<decodedjwt> authenticaterequest(httpservletrequest req, httpservletresponse resp) { string authheader = stringutil.trimtoempty(req.getheader("authorization")); string authbearertoken = authheader.replacefirst("^bearer ", ""); if (authheader.isempty()) { log.warn("no authorization header in request"); resp.setstatus(http_forbidden); return optional.empty(); } if (authbearertoken.isempty()) { log.warn("no authorization bearer token in request"); resp.setstatus(http_forbidden); return optional.empty(); } decodedjwt decodedjwt = jwt.decode(authbearertoken); rsakeyprovider keyprovider = new rsakeyprovider() { @override public rsapublickey getpublickeybyid(string keyid) { optional<jsonwebkey> key = jwtkeyprovider.getkey(keyid); if (!key.ispresent()) { resp.setstatus(httpservletresponse.sc_bad_request); return null; } try { keyfactory keyfactory = keyfactory.getinstance("rsa"); jsonwebkey jwk = key.get(); biginteger modulus = new biginteger(1, base64.geturldecoder().decode(jwk.n)); biginteger exponent = new biginteger(1, base64.geturldecoder().decode(jwk.e)); return (rsapublickey) keyfactory.generatepublic(new rsapublickeyspec(modulus, exponent)); } catch (invalidkeyspecexception | nosuchalgorithmexception e) { throw new runtimeexception(e); } } @override public rsaprivatekey getprivatekey() { return null; } @override public string getprivatekeyid() { return null; } }; algorithm algorithm; switch (decodedjwt.getalgorithm()) { case "rs256": algorithm = algorithm.rsa256(keyprovider); break; default: resp.setstatus(http_bad_request); log.error("unknown algorithm {}", decodedjwt.getalgorithm()); return optional.empty(); } jwtverifier jwtverifier = jwt.require(algorithm) .acceptleeway(duration.ofminutes(5).getseconds()) .withissuer("https://api.botframework.com") .build(); jwtverifier.verify(authbearertoken); return optional.of(decodedjwt); }
Mustard/chatterbox
[ 1, 1, 0, 0 ]
22,340
public List<DccdSB> getSearchBeans() { List<DccdSB> searchBeans = new ArrayList<DccdSB>(); if (!hasTridas()) return searchBeans; // just an empty list // get all the ObjectEntity's in the tree List<Entity> entities = getSubTreeAsList(); for (Entity entity : entities) { // only objects, exclude derived series if (entity instanceof ObjectEntity) { // create a bean DccdSB searchBean = new DccdObjectSB(); // fill it // first with the project info, maybe this can be done more efficiently // because same conversions are done for every Object again searchBean = fillSearchBean(searchBean); // then the object info searchBean = entity.fillSearchBean(searchBean); // all the ObjectEntities subentities must fill this bean as well // but not Objects? List<Entity> subentities = entity.getSubTreeAsList(); for (Entity subentity : subentities) { searchBean = subentity.fillSearchBean(searchBean); } // Note id should be the (system) identifier in the repository (sid) // just hoping that is is set correctly when read from the repository!!! searchBean.setDatastreamId(entity.getId());// should be the repository id for this peace of info // add to the list searchBeans.add(searchBean); } } return searchBeans; }
public List<DccdSB> getSearchBeans() { List<DccdSB> searchBeans = new ArrayList<DccdSB>(); if (!hasTridas()) return searchBeans; List<Entity> entities = getSubTreeAsList(); for (Entity entity : entities) { if (entity instanceof ObjectEntity) { DccdSB searchBean = new DccdObjectSB(); searchBean = fillSearchBean(searchBean); searchBean = entity.fillSearchBean(searchBean); List<Entity> subentities = entity.getSubTreeAsList(); for (Entity subentity : subentities) { searchBean = subentity.fillSearchBean(searchBean); } searchBean.setDatastreamId(entity.getId()) searchBeans.add(searchBean); } } return searchBeans; }
public list<dccdsb> getsearchbeans() { list<dccdsb> searchbeans = new arraylist<dccdsb>(); if (!hastridas()) return searchbeans; list<entity> entities = getsubtreeaslist(); for (entity entity : entities) { if (entity instanceof objectentity) { dccdsb searchbean = new dccdobjectsb(); searchbean = fillsearchbean(searchbean); searchbean = entity.fillsearchbean(searchbean); list<entity> subentities = entity.getsubtreeaslist(); for (entity subentity : subentities) { searchbean = subentity.fillsearchbean(searchbean); } searchbean.setdatastreamid(entity.getid()) searchbeans.add(searchbean); } } return searchbeans; }
PaulBoon/dccd-lib
[ 1, 0, 0, 0 ]
22,391
public Integer getLastmodifiedby() { return this.lastmodifiedby; }
public Integer getLastmodifiedby() { return this.lastmodifiedby; }
public integer getlastmodifiedby() { return this.lastmodifiedby; }
PLOS/named-entity.service
[ 0, 0, 1, 0 ]
22,404
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { //TODO Need a fix to make sure the value is not null String locationSetting = Utility.getPreferredLocation(getActivity()); //Sort order: Ascending by date String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; //Build the Uri needed for the query Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); //Create a cursor loader CursorLoader cursorLoader = new CursorLoader(getActivity(), weatherForLocationUri, FORECAST_COLUMNS, null, null, sortOrder); return cursorLoader; }
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String locationSetting = Utility.getPreferredLocation(getActivity()); String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); CursorLoader cursorLoader = new CursorLoader(getActivity(), weatherForLocationUri, FORECAST_COLUMNS, null, null, sortOrder); return cursorLoader; }
@override public loader<cursor> oncreateloader(int id, bundle args) { string locationsetting = utility.getpreferredlocation(getactivity()); string sortorder = weathercontract.weatherentry.column_date + " asc"; uri weatherforlocationuri = weathercontract.weatherentry.buildweatherlocationwithstartdate(locationsetting, system.currenttimemillis()); cursorloader cursorloader = new cursorloader(getactivity(), weatherforlocationuri, forecast_columns, null, null, sortorder); return cursorloader; }
SafwanAhmad/Sunshine-Version-2
[ 0, 0, 1, 0 ]
22,471
@Test public void inexistentItemTest() { String searchQuery = "awobsafhtui5we5t57zuo77izufh"; SearchResultsPage searchQueryPage = startPage.getSearchComponent().searchFor(searchQuery); String searchQueryDisplayText = searchQueryPage.getItemSearchQuery(); Assert.assertEquals(searchQueryDisplayText, searchQuery); int numResults = searchQueryPage.getResultCount(); Assert.assertEquals(numResults, 0, "Non-matching results were displayed."); }
@Test public void inexistentItemTest() { String searchQuery = "awobsafhtui5we5t57zuo77izufh"; SearchResultsPage searchQueryPage = startPage.getSearchComponent().searchFor(searchQuery); String searchQueryDisplayText = searchQueryPage.getItemSearchQuery(); Assert.assertEquals(searchQueryDisplayText, searchQuery); int numResults = searchQueryPage.getResultCount(); Assert.assertEquals(numResults, 0, "Non-matching results were displayed."); }
@test public void inexistentitemtest() { string searchquery = "awobsafhtui5we5t57zuo77izufh"; searchresultspage searchquerypage = startpage.getsearchcomponent().searchfor(searchquery); string searchquerydisplaytext = searchquerypage.getitemsearchquery(); assert.assertequals(searchquerydisplaytext, searchquery); int numresults = searchquerypage.getresultcount(); assert.assertequals(numresults, 0, "non-matching results were displayed."); }
MPDL/imeji-gui-testing
[ 0, 1, 0, 0 ]
30,799
public final Node createView(OpenedFile file, String path) { Node node = createView0(file, path); node.getProperties().put("editor", this); node.getProperties().put("file", file); // probably a memory leak node.getProperties().put("path", path); return node; }
public final Node createView(OpenedFile file, String path) { Node node = createView0(file, path); node.getProperties().put("editor", this); node.getProperties().put("file", file); node.getProperties().put("path", path); return node; }
public final node createview(openedfile file, string path) { node node = createview0(file, path); node.getproperties().put("editor", this); node.getproperties().put("file", file); node.getproperties().put("path", path); return node; }
MiniDigger/standalone-app
[ 0, 0, 1, 0 ]