JSLint4Java usage - wrapper

JSLint4Java is a Java wrapper for JSLint. I need something like this for use in my GWT project, but the only way to use JSLint4Java seems to be from command line or with an ANT task. Does anyone know if there is any way to just import the JARs and use them in a project? When I try adding them to the GWT WAR folder, I get lots of errors like 'xxx cannot be resolved to a type'.
Thanks.

Yes you can import the jar and use it like this :
import com.googlecode.jslint4java.Issue;
import com.googlecode.jslint4java.JSLint;
import com.googlecode.jslint4java.JSLintBuilder;
import com.googlecode.jslint4java.JSLintResult;
public static void lint(final String filePath) throws FileNotFoundException, IOException {
String fileContent = Streams.read(new FileInputStream(new File(filePath))));
JSLintBuilder builder = new JSLintBuilder();
JSLint jsLint = builder.fromDefault();
JSLintResult result = jsLint.lint("test.js", fileContent);
for (Issue issue : result.getIssues()) {
System.out.println(issue.toString());
}
}

Related

How to use Google translate for free? Maybe you have some analogs [duplicate]

If I pass a string (either in English or Arabic) as an input to the Google Translate API, it should translate it into the corresponding other language and give the translated string to me.
I read the same case in a forum but it was very hard to implement for me.
I need the translator without any buttons and if I give the input string it should automatically translate the value and give the output.
Can you help out?
You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:
var mock = {
parameter:{
q:'hello',
source:'en',
target:'fr'
}
};
function doGet(e) {
e = e || mock;
var sourceText = ''
if (e.parameter.q){
sourceText = e.parameter.q;
}
var sourceLang = '';
if (e.parameter.source){
sourceLang = e.parameter.source;
}
var targetLang = 'en';
if (e.parameter.target){
targetLang = e.parameter.target;
}
var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});
return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}
2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
3) Use this java code for testing your API:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Translator {
public static void main(String[] args) throws IOException {
String text = "Hello world!";
//Translated text: Hallo Welt!
System.out.println("Translated text: " + translate("en", "de", text));
}
private static String translate(String langFrom, String langTo, String text) throws IOException {
// INSERT YOU URL HERE
String urlStr = "https://your.google.script.url" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard
Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.
About java-google-translate-text-to-speech
Api unofficial with the main features of Google Translate in Java.
Easy to use!
It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:
Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Bună ziua!"
It's free!
As #r0ast3d correctly said:
Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.
This is correct: just see the official page:
Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.
BUT, java-google-translate-text-to-speech is FREE!
Example!
I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech
Generate your own API key here. Check out the documentation here.
You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.
Below is a quick start example which translates two English strings to Spanish:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;
public class QuickstartSample
{
public static void main(String[] arguments) throws IOException, GeneralSecurityException
{
Translate t = new Translate.Builder(
GoogleNetHttpTransport.newTrustedTransport()
, GsonFactory.getDefaultInstance(), null)
// Set your application name
.setApplicationName("Stackoverflow-Example")
.build();
Translate.Translations.List list = t.new Translations().list(
Arrays.asList(
// Pass in list of strings to be translated
"Hello World",
"How to use Google Translate from Java"),
// Target language
"ES");
// TODO: Set your API-Key from https://console.developers.google.com/
list.setKey("your-api-key");
TranslationsListResponse response = list.execute();
for (TranslationsResource translationsResource : response.getTranslations())
{
System.out.println(translationsResource.getTranslatedText());
}
}
}
Required maven dependencies for the code snippet:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-translate</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>LATEST</version>
</dependency>
I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com
import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
Configuration.startMaximized = true;
open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
String[] strings = /some strings to translate
for (String data: strings) {
$x("//textarea[#id='source']").clear();
$x("//textarea[#id='source']").sendKeys(data);
String translation = $x("//span[#class='tlid-translation translation']").getText();
}
}
}
You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.

Adding Apache POI 4.0.1 library not sufficient to use XSSFWorkbook

I am using the following tutorial to realize a Selenium Keyword Driven Framework : http://toolsqa.com/selenium-webdriver/keyword-driven-framework/set-excel-apache-poi/
For the part which ask to create an "util" package with an ExcelUtils class, I followed the instructions which begin by adding a jar to the project libraries.
This jar is for the library apache-poi-4.0.1 : poi-4.0.1.jar.
But even with this library and it's attached source, classes XSSFWorkbook, XSSFSheet and XSSFCell do not exist.
So my question is, which part of the tutorial I am missing? Or which library I am missing?
I am using Eclipse Oxygen with the JRE JavaSE-1.8
Package utils;
import java.io.FileInputStream;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
//This method is to set the File path and to open the Excel file
//Pass Excel Path and SheetName as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
//This method is to read the test data from the Excel cell
//In this we are passing parameters/arguments as Row Num and Col Num
public static String getCellData(int RowNum, int ColNum) throws Exception{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
}
}
You are missing the below piece of code
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
I finally found a solution.
I had to download 5 other libraries :
poi-examples-4.0.1
poi-excelant-4.0.1
poi-ooxml-4.0.1
poi-ooxml-schemas-4.0.1
poi-scratchpad-4.0.1
After that, I can use XSSF classes.
You need the poi-ooxml dependency as well.
This is how it looks in Gradle, just change $apachePoiVersion to the version you want.
implementation "org.apache.poi:poi:$apachePoiVersion"
implementation "org.apache.poi:poi-ooxml:$apachePoiVersion"

Minecraft modding 1.7.10 setTextureName not working

I am making a new mod and my block textures work fine but my item textures dont
i need assistance on this because i just started to code java
This Is My Script:
package com.HaydenMod.item;
import com.HaydenMod.lib.RefStrings;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class DiamondShard {
public static void MainRegistery(){
intializeItem();
registerItem();
}
public static Item Dshard;
public static void intializeItem(){
Dshard = new Item().setUnlocalizedName("Dshard").setCreativeTab(CreativeTabs.tabMaterials).setTextureName(RefStrings.MODID + ":Diamond_Shard").setMaxStackSize(16);
}
public static void registerItem(){
GameRegistry.registerItem(Dshard, Dshard.getUnlocalizedName());
}
}
Try
.setTextureName(RefStrings.MODID + ":" + "Diamond_Shard")
If it dosn't work can you attach a pastebin with the error log
YourItemName= new Item().setUnlocalizedName("YourItemName").setTextureName("yourModFile:YourtextureImageNAme").setCreativeTab(TheCreativeTabYouWantToPutItIn);
This is what is used and it works perfectly. The TextureName has to be exactly the same as the TextureName in the source folder.
For example, my TextureName is blah.png and in my source folder. When calling it, should write it as setTextureName("yourModFile:blah").

Sonar Custom Widget

I created a widget using the source code available in github. Now I'm using that widget in SonarQube V5.3. This is where I got the source code from:
https://github.com/SonarSource/sonar-examples/tree/master/plugins/sonar-reference-plugin
When I use this widget it is showing up the same data across multiple projects. I would like to know if there is any way I can display different data for different projects. Please share your ideas. Below is the code that displays the ruby widget
import org.sonar.api.web.AbstractRubyTemplate;
import org.sonar.api.web.Description;
import org.sonar.api.web.RubyRailsWidget;
import org.sonar.api.web.UserRole;
import org.sonar.api.web.WidgetCategory;
import org.sonar.api.web.WidgetProperties;
import org.sonar.api.web.WidgetProperty;
import org.sonar.api.web.WidgetPropertyType;
import org.sonar.api.batch.CheckProject;
import org.sonar.api.resources.Project;
#UserRole(UserRole.USER)
#Description("Sample")
#WidgetCategory("Sample")
#WidgetProperties({
#WidgetProperty(key = "Index",type=WidgetPropertyType.TEXT
),
})
public class OneMoreRubyWidget extends AbstractRubyTemplate implements RubyRailsWidget {
#Override
public String getId() {
return "Sample";
}
#Override
public String getTitle() {
return "Sample";
}
#Override
protected String getTemplatePath() {
return "/example/Index.html.erb";
}
}
Thank you so much in advance
You haven't specified global scope for your widget (#WidgetScope("GLOBAL")) in the .java file, so this is a question of what's in your .erb file.
This Widget Lab property widget should give you some pointers. Specifically: you want to pick up #project in your widget, and query with #project.uuid. Here's another project-level widget for comparison.
You should be aware, though, that SonarSource is actively working to remove Ruby from the platform, so at some future date, you'll probably end up re-writing your widgets (likely in pure JavaScript).

Creating new live-templates with import statements in IntelliJ IDEA

Here is the Eclipse template that I want to port:
${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
My current version in IDEA is as follows:
private static final Logger LOG = Logger.getLogger($CLASS_NAME$.class);$END$
where $CLASS_NAME$ is configured to use className() as its expression.
Unfortunately, I don't find any documentation on adding the import statement. Is there somehing equivalent to Eclipse ${:import(...)}?
According to this post, it is intended to use only full-qualified expressions. I tried it out and this worked for me:
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger($CLASS_NAME$.class);$END$
IDEA automatically shortens it and adds the necessary import statements:
import org.apache.log4j.Logger;
// ...
private static final Logger LOG = Logger.getLogger(MyClass.class);
If you want to try yourself, note that you first have to define CLASS_NAME as className() via Edit variables. Also make sure that you allowed your Live Template for Java declarations via Change (at the bottom). Here is a screenshot with the final setup:
Just to save a little time for new visitors here: the accepted answer now needs some changes.
Go to Settings -> Editor -> Live Templates, select others, add a template:
private static final org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger($CLASS_NAME$.class);$END$
Then, press Edit Variables on the left and set expression for CLASS_NAME to className().
After all, set context on the bottom to Java -> Declaration (and Groovy -> Declaration if desired).
Imports will be magically generated on insert.
Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}
For apache commons logging use:
private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog($CLASS_NAME$.class);$END$