How to resolve Checkstyle error: 'method def modifier ' has incorrect indentation - intellij-idea

Got a checkstyle error that states a member def modifier has incorrect indentation level 4 and is expected to be level 2.

Apart from having checkstyle as a plugin, you must download the its jar file as well, just because there you will be able to see what google and sun check file are doing to your code, and true to be told, it is kind of hard to understand checkstyle documentation, and having those files at hand will ease the process to understand what is going on.
Getting back to your question, there is a module called Indentation which has a property for basicOffset that is setting the space it waits to find when scanning your code, I'll show you an example:
<module name="TreeWalker">
<module name="Indentation">
<property name="basicOffset" value="2"/>
<property name="caseIndent" value="2"/>
</module>
XML content above shows a simple example, where I want to show you this module thing, that's why I added another property called caseIndent for same module called Indentation which resides inside TreeWalker. As you can see the basicOffset property has the number 2 as a value, then you could say, wait, the message I got said 4 and not 2. I'll explain it:
class Foo { // no space at the left side
private void fooMethod() { // a tab or 2 space at the left side
int a = 0; // 2 space from method's declaration plus 2 for this is 4
}
}
Definively you ought see the xml I mentioned before, replicate in your own with basic stuff and play around to have a better understanding. You can get more info form here.

Related

Nlog variable and log file issue with multiple log files

I created a Log File class that uses NLog with the hopes of writing to multiple log files at the same time. This seems to work fine until I add variables to the mix.
Problem
Changing the variable seems to change that variable setting for all instances of the log file instead of the particular instance I am working with.
My Code
Here is how I have the programming structured:
LogClass - Basically a wrapper to give me some additional functionality. The 'SetVariable' is what I am using to set the particular variable (called dqwAlertName)
With this log class, I am passing in the specific logger that I want to use like this:
Public iLogger as new Logger(NLog.LogManager.GetLogger("dataQualityWatcher"),True)
That statement instantiates the logging class with the "dataQualityWatcher" logger and sets Debug=True (which I simply use to allow a more verbose logging that can be turned on and off).
With that said... The statement above is ALSO within another class object:
dataQualityWatcher Class - This is a 'watcher' that is called many times over and runs continuously. If you familiar with FileSystemWatcher, it works similarly to that. It basically watches data for a specific value and raises an event.
Inside THIS class is where I instantiate the logger as mentioned above with the following code:
Public iLogger as new Logger(NLog.LogManager.GetLogger("dataQualityWatcher"), True)
iLogger.SetVariable("dqwAlertName", _AlertName)
The first line instantiates, the second line will set the variable. The Logging Class SetVariable method is pretty basic:
Public Sub SetVariable(variableName as string, value as String)
'Set variable context for the logger
NLog.LogManager.Configuration.Variables(variableName) = value
End Sub
I am using that variable within the NLog.config file in the following manner:
<variable name="LogLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss.fff tt}] [${gdc:item=location}] | ${level} | ${message}" />
<variable name="InfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss.fff tt}] ${gdc:item=SoftwareName} Version ${gdc:item=SoftwareVersion} - ${message}" />
<variable name="DebugInfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss.fff tt}] ${message}" />
<variable name="logDir" value="C:/Log/PWTester/" />
<variable name="dqwAlertName" value="" />
<targets>
<target name="dataQualityWatcher" xsi:type="File" fileName="${logDir}/LogFiles/${var:dqwAlertName}-DataQualityWatcher.log" layout="${LogLayout}" />
</targets>
<rules>
<logger name="dataQualityWatcher" minlevel="Trace" writeTo="dataQualityWatcher" />
</rules>
THE PROBLEM:
I run multiple 'watchers' (as I call them) with the following code to create that object and assign properties:
dataWatch.Add(New dataQualityWatcher(True) With {.Tags = lstTags, .AlertTimerInterval = Convert.ToInt64(intTimerMilliseconds), .AlertGroupID = Convert.ToInt64(CARow(0)), .EmailGroupID = Convert.ToInt64(CARow(1)), .CustomSubject = CARow(3), .CustomMessage = CARow(4), .AlertName = DataAlertGroupName, .Debug = blnVerboseLogging, .HistorianServer = SH})
Multiple Version Example
I run the code above where: .AlertName = {"Test1", "Test2", "Test3"}. Other parameters would also change and a new object is instantiated each time. In this example there are 3 dataQualityWatcher objects instantiated, which also instantiates 3 Logger objects.
Each time a new dataQualityWatcher object is instanciated, it instanciates a Logger, which would then write to the file. The AlertName variable is passed on through the SetVariable method above.
I would expect 3 log files to be written:
Test1-DataQualityWatcher.log
Test2-DataQualityWatcher.log
Test3-DataQualityWatcher.log
This DOES happen. However, the last dataQualityWatch object that is created will run the SetVariable method = "Test3" (in this example). Now that variable is set and all 3 Loggers will begin logging to that file (i.e., Test3-DataQualityWatcher.log).
I can only assume that there is a better way to do this with variables such that they are for the life of that particular log instance, but I can't seem to figure it out!
Thanks in advance and sorry for the VERY, VERY long post.
As far as I understand your are trying to log to multiple files, with one target.
This won't work well with the use of variables as they are static (Shared in VB.net) - so this isn't threadsafe.
Other options to do this are:
Create multiple file targets in your nlog.config and setup the right <rules>, or
Pass extra properties for every message, and use event-properties: fileName="${logDir}/LogFiles/${event-properties:dqwAlertName}-DataQualityWatcher.log", VB.NET call:
Dim theEvent As New LogEventInfo(LogLevel.Debug, "", "Pass my custom value")
theEvent.Properties("MyValue") = "My custom string".
You could write a sub class for Logger to make it less verbose. Or
Create the targets & rules programmatically (in VB.NET). See tutorial (in C#)
If performance is very important, choose for 1 or 3.

PyDev custom code complete plug-in only detects every other key stroke

I have an Eclipse plug-in that I created to add Code Completion entries. I configured Eclipse to automatically show code completion as I type (Windows | Preferences | PyDev | Editor | Code Completion | Request completion on all letter chars and '_'?). At first when I typed I kept getting the templates showing instead of my code completion entries, so I removed all the templates ( Windows | Preferences | PyDev | Templates --selected all, then "Remove"). Now when I type it works properly for every other key pressed. For example, when I type 'print', the code completion list drops down with my entries as expected when I press 'p'. However, when I press 'r', the list disappears. When I press 'i' the list shows again, but disappears when I press the next key ('n'), etc. Is this a Pydev defect, or am I doing something wrong? It works fine for the templates and other default code completion, just not for my plug-in. Here is a code snipped of a watered down version of my code:
//...
public class MyPlugin implements IPyDevCompletionParticipant
#Override
public Collection<Object> getGlobalCompletions(CompletionRequest arg0,
ICompletionState arg1) throws MisconfigurationException {
String replacementString = "{" + arg0.qualifier + "}";
int replacementOffset = arg0.documentOffset - arg0.qlen;
int replacementLength = arg0.qlen;
int cursorPosition = arg0.documentOffset;
String displayString = arg0.qualifier;
final IContextInformation contextInformation = new ContextInformation(
"displayStr", "message");
String additionalProposalInfo = "additionalProposalInfo";
final String bundle = "com.github.EclipseChameleonPlugins";
final org.eclipse.swt.graphics.Image image = new org.eclipse.swt.graphics.Image(getDisplay(), locateFile(bundle, "icons/smiley.gif").getPath());
arg0.showTemplates = false;
final CompletionProposal proposal = new CompletionProposal(
replacementString, replacementOffset, replacementLength,
cursorPosition, image, displayString, contextInformation, additionalProposalInfo);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
// ADD IT...
proposals.add(proposal);
final Collection<Object> returnProposals = new ArrayList<Object>(
proposals);
return returnProposals;
}
I have searched Google and StackOverflow, and have seen very little about code development for PyDev plug-ins, and nothing that mentions or addresses this issue.
Here are a few of the links I have looked at, but none have answered my question:
Auto-completion in PyDev
Code completion for custom modules not working with PyDev
pydev remote debuging - code completion in interactive console?
Well, plain PyDev behaves as expected for me (i.e.: the code completions appear on all the key strokes).
Now, let's see if we can track it down a bit better:
instead of removing the templates, what you should do is go to the preferences > pydev > editor > code completion (ctx insensitive and common tokens) and disable the 'use common tokens auto code completion?'.
The reference code for you to follow is: com.python.pydev.codecompletion.participant.ImportsCompletionParticipant and com.python.pydev.codecompletion.ctxinsensitive.CtxParticipant (i.e.: the IPyDevCompletionParticipant interface -- as you're doing already)
I think the main issue you're having is because you're not implementing the additional extensions for completions (to validate its context and keep it there) -- either you can make your own subclass of org.python.pydev.editor.codecompletion.AbstractPyCompletionProposalExtension2 or you can use org.python.pydev.editor.codecompletion.PyLinkedModeCompletionProposal (just constructing it with the proper parameters -- I believe it supports having a null IToken -- and you can pass an image to it which will be used if the token is null).
You should probably not mess with the CompletionRequest at that point (when it gets there to an extension it should be considered immutable -- even if it's not in reality).

C++ Builder XE2, TXMLDocument 'DTD is prohibited'

When I try to read an XML document (eagle file) with an DTD I get the error:
Project xx raised exception class EDOMParserError with message 'DTD is
prohibited'
The XML header looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE eagle SYSTEM "eagle.dtd">
If I remove the second line...
<!DOCTYPE eagle SYSTEM "eagle.dtd">
...everything works fine.
After some googling it seems like the MSXML parser have an option called ´prohibitDTD´ set to true by default (in earlier versions it was false).
However it seems not possible to set this option to false from the TXMLDocument class. One solution seems to be a recompile of the .pas library or to create the interface on my own with CoCreateInstance().
All examples I have seen out there are in Delphi and I'm having dificulties to trasnlate these to C++ Builder.
Does anyone know how to read a DTD XML document with C++ Builder XE2?
My example code...
#include <xmldoc.hpp>
_di_IXMLNode XMLObject;
TXMLDocument *XMLDocument = new TXMLDocument(this);
XMLDocument->LoadFromFile(fileName); // <----- Exception EDOMParserError
XMLObject = XMLDocument->DocumentElement;
Thank you...
XE2 introduced a native solution to this very problem: there is a global bool variable named MSXML6_ProhibitDTD declared in Xml.Win.msxmldom.hpp. You can set it to false before loading data into TXMLDocument:
#include <xmldoc.hpp>
#include <msxmldom.hpp>
MSXML6_ProhibitDTD = false;
TXMLDocument *XMLDocument = new TXMLDocument(this):
XMLDocument->LoadFromFile(fileName);
_di_IXMLNode XMLObject = XMLDocument->DocumentElement;
On a side note: it is generally not a good idea to create TXMLDocument instances dynamically like this. It is better to use the IXMLDocument interface instead:
#include <xmldoc.hpp>
#include <msxmldom.hpp>
MSXML6_ProhibitDTD = false;
_di_IXMLDocument XMLDocument = LoadXMLDocument(fileName);
_di_IXMLNode XMLObject = XMLDocument->DocumentElement;
Since the workaround with the global variable MSXML6_ProhibitDTD is deprecated and I couldn't get it to work with XE5 either, here is another solution:
As stated in the documentation, there is this method to change the DOM property
Xml.Win.Msxmldom.MSXMLDOMDocumentFactory.AddDOMProperty
Unfortunately it's not so trivial to use this...
include the header for this namespace:
#include <Xml.Win.msxmldom.hpp>
Foo::Foo()
{
//change the dom property in your constructor.
((TMSXMLDOMDocumentFactory*)Xml::Win::Msxmldom::MSXMLDOMDocumentFactory)->AddDOMProperty("ProhibitDTD", False, true);
}
and access this method. (The cast is necessary, because the MSXMLDOMDocumentFactory itself is inherited from a metaclass interface or so. I don't got the concept behind.)
inspired from a delphi blog: https://bobsotherblog.wordpress.com/2013/09/19/fixing-dtd-is-prohibited-error-in-delphi/
You need to copy MSXMLDOM.pas into your project folder, and modify it in order to fix this issue.
Change the implementation of function TMSDOMDocument.GetMSDocument to the following, and then rebuild your project.
Note you have to use IXMLDOMDocument2.setProperty instead of accessing ProhibitDTD directly, as IXMLDOMDocument2 doesn't publish ProhibitDTD.
function TMSDOMDocument.GetMSDocument: IXMLDOMDocument;
var
Doc2: IXMLDOMDocument2;
begin
Result := MSNode as IXMLDOMDocument;
if Supports(Result, IXMLDOMDocument2, Doc2) then
Doc2.setProperty('ProhibitDTD', False);
end;
Note that this will only work if you're not building with runtime packages!
This solution is from an Embarcadero forums post made by a member of TeamB; I remembered reading it, and found it in a search of those forums via CodeNewsFast - search functionality at the EMBT forums hasn't ever worked well, and a recent rebuild or reindex or something has made it even worse than before. :-)

Problem with plone.indexer and Dexterity

I wish to enable a special index, called Sectors, for a attribute ('sectors') of my Dexterity based custom content-type.
In my schema, inside types/mycontent.py I have:
class IMyContent(form.Schema):
"""
My Content
"""
sectors = schema.Set(
title=_(u"Sectors"),
description=_(u"Select some sectors"),
value_type=schema.Choice(vocabulary=vocs.sectors),
required=True,
)
(...)
I then define the index in this way, inside indexers.py
from plone.indexer.decorator import indexer
from zr.content.types.mycontent import IMyContent
#indexer(IMyContent)
def Sectors(obj):
"""Indexer for Sectors attribute.
"""
d = getattr(obj, "sectors", u"")
return d if d else None
Finally in the root package configure.zcml:
<adapter name="Sectors" factory=".indexers.Sectors"/>
However, it does not seem to work. Even after reinstalling the product, I don't see the index in portal_catalog and catalog brain object do not seem to have it either.
What am I doing wrong?
You aren't defining the catalogue index. This will just make the indexer available to be added. You require a catalog.xml in your GenericSetup profile with:
<?xml version="1.0"?>
<object name="portal_catalog" meta_type="Plone Catalog Tool">
<index name="Sectors" meta_type="KeywordIndex">
<indexed_attr value="Sectors"/>
</index>
</object>
The accepted solution may be slightly obscure, so here are a couple of clarifications:
1) Do NOT edit your global generic setup.
Unless you're doing something extremely weird, you'll have setup your site as a series of plone extensions, and have a folder structure like:
app.plugin/
app.plugin/app/
app.plugin/app/configure.zcml
app.plugin/app/profiles/
app.plugin/app/profiles/default
app.plugin/app/profiles/default/types
app.plugin/app/profiles/default/types/Folder.xml
app.plugin/app/profiles/default/types/app.mydexteritytype.xml
app.plugin/app/profiles/default/types.xml
app.plugin/app/profiles/default/portlets.xml
app.plugin/app/profiles/default/catalog.xml <---- ADD THIS
2) You don't have to have an xml block (as per the accepted solution) in catalog.xml, you can just create the index from the frontend ZMI. However, if you do this, it'll get blown away the next time you install your plugins. So you probably do want to.
3) After installing your catalog.xml, browse to the ZMI interface to portal_catalog and check that under the 'indexes' tab your index exists. If it doesn't you've messed up.
4) To build the index, you need to go the 'advanced' tab and choose rebuild.
5) The indexer greedily consumes exceptions and does not raise them (especially important for AttributeError; you may not index some values you want to be indexing), so if you want to make sure your indexer is actually running, try adding a log or print statement in it:
#indexer(IMyDexterityType)
def dummy_indexer(obj, **kw):
try:
print('indexed: %r' % obj)
return obj.title
except Exception as e:
print('index fail: %r' % e)
return ''
If nothing else you should see some output like:
2013-08-12 16:42:28 INFO GenericSetup.archetypetool Archetype tool imported.
2013-08-12 16:42:28 INFO GenericSetup.resourceregistry Stylesheet registry imported.
2013-08-12 16:42:28 INFO GenericSetup.resourceregistry Javascript registry imported.
indexed: <MyDexterityType at /Plone/test/cat-document-0>
indexed: <MyDexterityType at /Plone/test/hello>
6) grok.global_adapter() as mentioned in some of the documentation (http://developer.plone.org/reference_manuals/external/plone.app.dexterity/advanced/catalog-indexing-strategies.html?highlight=custom%20indexing#creating-custom-indexers) is about registering virtual properties, and does not mitigate the need to setup your catalog.xml.
Finally, someone's put a working example up on github here, which is extremely useful:
https://github.com/aclark4life/event_days_indexer

Magento - Trouble with setting up Model Read Adapter

I was following through on Alan Storm's tutorial on Magento's Model and ORM basics and I've run into a bit of a problem. When I get to the portion where I load from the Model for the first time I get this error "Fatal error: Call to a member function load() on a non-object...". I've reset everything already and tried again from scratch but I still get the same problem. My code looks like this:
$params = $this->getRequest()->getParams();
$blogpost = Mage::getModel('weblog/blogpost');
var_dump($blogpost);
echo("Loading the blogpost with an ID of ".$params['id']);
$blogpost->load($params['id']);
As you can see I dumped the contents of $blogpost and it shows that it is just a boolean false. My guess is that there's either a problem with the connection to the database or, for some reason, the code for Mage::getModel() didn't get installed correctly.
EDIT - Adding Code
There's so many that I just decided to pastebin them lol
app/code/local/Ahathaway/Weblog/controllers/IndexController.php
app/code/local/Ahathaway/Weblog/etc/config.xml
app/code/local/Ahathaway/Weblog/Model/Blogpost.php
app/etc/modules/Ahathaway_Weblog.xml
Your Model/Blogpost.php file should actually be Model/Mysql4/Blogpost.php, and you are missing the real Model/Blogpost.php.
My guess is that Mage cannot find your model class. Double check the module/model name and also verify if the model is in a correct place in the filesystem (it should be in app/code/local/Weblog/Model/Blogpost.php).
You also need to check if your config.xml correctly defines your model classes. It would be best if you could past your config.xml and your model class...
A quick glance reveals you're missing the model resource. Go back to the section around the following code example
File: app/code/local/Alanstormdotcom/Weblog/Model/Mysql4/Blogpost.php
class Alanstormdotcom_Weblog_Model_Mysql4_Blogpost extends Mage_Core_Model_Mysql4_Abstract{
protected function _construct()
{
$this->_init('weblog/blogpost', 'blogpost_id');
}
}