Check if a string has a word in javascript (and not just substring) : non-regex version

    Pure javascript (non-regex) version:
  1. /**
  2. * Find if string has a word
  3. * */
  4. function checkStringHasWord(substr,str){
  5. console.log("Finding word : "+substr+" from string : "+str);
  6. str = str.toLowerCase();
  7. substr = substr.toLowerCase();
  8. console.log("Str length : "+str.length);
  9. var idx=str.indexOf(substr);
  10. if(strcmp(substr,str)==0){console.log("equal");return true;}
  11. var rightIdx=idx+substr.length;
  12. //equal
  13. if(idx>0 && idx+substr.length<str.length){
  14. //middle
  15. console.log("middle");
  16. console.log(str[idx-1]);
  17. console.log(str[idx+substr.length]);
  18. return isNonChar(str[idx-1]) && isNonChar(str[idx+substr.length]);
  19. }
  20. else if(idx==0){
  21. //left
  22. console.log("left");
  23. //console.log("right idx:"+rightIdx);
  24. console.log(str[rightIdx]);
  25. return isNonChar(str[rightIdx]);
  26. }
  27. else if(idx+substr.length==str.length){
  28. //right
  29. console.log("right");
  30. console.log(str[idx-1]);
  31. return isNonChar(str[idx-1]);
  32. }
  33. else{
  34. return false;
  35. }
  36. }
  37. function strcmp(a, b)
  38. {
  39. return (a < b ? -1 : (a > b ? 1 : 0));
  40. }
  41. function isNonChar(chr){
  42. var matcher = new RegExp("\\W", "i");
  43. return matcher.test(chr);
  44. }
  45. /**
  46. * Tests
  47. * */
  48. function test(){
  49. console.log(checkStringHasWord("gre","gre"));//true
  50. console.log(checkStringHasWord("gre","congres"));//false
  51. console.log(checkStringHasWord("gre","gresdfg"));//false
  52. console.log(checkStringHasWord("gre","ojfsdgre"));//false
  53. console.log(checkStringHasWord("gre","gre:math"));//true
  54. console.log(checkStringHasWord("gre","gre-math"));//true
  55. console.log(checkStringHasWord("gre","gre math"));//true
  56. console.log(checkStringHasWord("gre"," gre "));//true
  57. console.log(checkStringHasWord("gre","jkggdfgdh"));//false
  58. console.log(checkStringHasWord("gre","jddfgL:GRE"));//true
  59. console.log(checkStringHasWord("sat","SSAT 2"));//true
  60. }

Short Code(Regex version):
Equivalent regex pattern "/btext/b"

Getting started with Google App Engine Java SDK with Netbeans 7.2 / Netbeans 7.4

Download the SDK:

1. Download app engine java sdk from https://developers.google.com/appengine/downloads:
https://commondatastorage.googleapis.com/appengine-sdks/featured/appengine-java-sdk-1.9.5.zip

extract (e.g. into /usr/local/gae/)

Install Google App Engine NetBeans Plugin:

  1. Start NetBeans
  2. Make note of NetBeans version number
  3. Click Tools -> Plugins
  4. Select the Settings tab
  5. Click the Add button
  6. Type “App Engine” (without the quotes) into the Name field
  7. Paste https://kenai.com/projects/nbappengine/downloads/download/NetBeans7.2/updates.xml (7.2 worked for me with 7.4.You can browse which packages a re available athttps://kenai.com/projects/nbappengine/downloads)
  8. Click 'OK' and navigate to Available Plugins tab.
  9. Check the plugin Google App Engine Support 1.0
  10. Click the Install button

Configure App Engine server in Netbeans:

  1. Click on the Services tab next to Projects and Files
  2. Right-click on Servers and click Add
  3. Select Google App Engine and Click Next
  4. Select the location you unzipped the Google App Engine SDK(/usr/local/gae/)
  5. Click Next
  6. Unless you have another service running on port 8080 and port 8765 leave the default port values(I would suggest using other ports like 9090 & 9765).
  7. Click Finish

Create Your App

Create your app engine application at http://appengine.google.com/start/createapp .You will be able to visit your site at 'http://yourappname.appspot.com' after you create an app and deploy your web app with App Engine.

Run the Guestbook Sample App

We are almost done! To test the install and ensure everything runs properly, let’s try running the included Guestbook sample app.
  1. Start NetBeans
  2. Click File -> New Project
  3. Under Samples, select Google App Engine -> Guestbook
  4. Click Next
  5. Enter the location in which you’d like to store this project
  6. Click Finish
  7. Now navigate to  /WEB-INF/appengine-web.xml file
  8. Simply put:
    <threadsafe>true</threadsafe>
    and set your application name in the file.
    Like this:
        <?xml version="1.0" encoding="UTF-8"?>
    <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>YOURAPPNAME</application>
    <version>1</version>
    <threadsafe>true</threadsafe>
    
  9. Don't forget to repace YOURAPPNAME with the app name you created at https://appengine.google.com/
  10. Click the Run button (looks like a green Play button in the toolbar).
  11. Observe App Engine logs on Output tab.The last line should be: [java] INFO: Dev App Server is now running
  12. You have run it locally successfully.Browse to http://localhost:8080/ or http://localhost:9090/ or http://localhost:YOURPORTNUMBER/
  13. You should see a page like this : http://mohifirstapp.appspot.com/
  14. Right click your project and choose Deploy to Google App engine.
  15. Enter your email and password.
  16. Browse to https://appengine.google.com/ to see your application status.
  17. browse to your app http://YOURAPPNAME.appspot.com

References:

Spring 3 : Reading .properties file

1. You may want to create a new spring project first.You can try it here:http://www.mkyong.com/spring3/spring-3-hello-world-example/

2. Create a new .properties file in your src/main/resources dir:
my.properties
-------------------
key1             value1
key2             value2

3.Create a new bean in your spring-context file(e.g. SpringBeans.xml).Simply put this:
<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>

4. And then in your java code:
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
            Properties mcls=(Properties) context.getBean("myProperties");
            System.out.println(mcls.getProperty("key1"));
            System.out.println(mcls.getProperty("key2"));
Output:

value1
value2
5.In case of web app.You can try this code in your controller:

private static XmlBeanFactory beanFactory = new XmlBeanFactory(
new ClassPathResource("SpringBeans.xml"));
Properties mcls=(Properties) context.getBean("myProperties");

Simplest way to run/test a php function in Laravel-4 ( Helloworld unit testing! )

Install phpunit:
1. Go to the root directory of your project (where the 'artisan' file is located).
2. Open 'composer.json. Include phpunit dependency in the JSON.
 Save and close the file. After adding the file content should look like:
  1. {
  2. "name": "laravel/laravel",
  3. "description": "The Laravel Framework.",
  4. "keywords": ["framework", "laravel"],
  5. "license": "MIT",
  6. "require": {
  7. "laravel/framework": "4.0.*",
  8. "geoip/geoip": "~1.14"
  9. },
  10. "require-dev": {
  11. "phpunit/phpunit": "3.7.*"
  12. },
  13. "autoload": {
  14. "classmap": [
  15. "app/commands",
  16. "app/controllers",
  17. "app/models",
  18. "app/database/migrations",
  19. "app/database/seeds",
  20. "app/tests/TestCase.php"
  21. ]
  22. },
  23. "scripts": {
  24. "post-install-cmd": [
  25. "php artisan optimize"
  26. ],
  27. "post-update-cmd": [
  28. "php artisan clear-compiled",
  29. "php artisan optimize"
  30. ],
  31. "post-create-project-cmd": [
  32. "php artisan key:generate"
  33. ]
  34. },
  35. "config": {
  36. "preferred-install": "dist"
  37. },
  38. "minimum-stability": "dev"
  39. }

3. Run the following command in that directory :
 
  1. composer update

 and wait for completion.

4. Now after that run the command "vendor\bin\phpunit" ("vendor/bin/phpunit" for linux)
 for running default tests
On Windows run:
  1. vendor\bin\phpunit
On Linux run:
  1. vendor/bin/phpunit
You will see something like this:


PHPUnit 3.7.29 by Sebastian Bergmann.

Configuration read from YOUR_PROJECT_DIR\phpunit.xml

.

Time: 188 ms, Memory: 5.50Mb

←[30;42m←[2KOK (1 test, 1 assertion)
←[0m←[2K

7. Now go to the directory YOUR_PROJECT_DIR/app/tests/
8. Open the file 'ExampleTest.php'. It's content should look something like this:

  1. <?php
  2. class ExampleTest extends TestCase {
  3. /**
  4. * A basic functional test example.
  5. *
  6. * @return void
  7. */
  8. public function testBasicExample()
  9. {
  10. $crawler = $this->client->request('GET', '/');
  11. $this->assertTrue($this->client->getResponse()->isOk());
  12. }
  13. }
  14. 7. Now write your own test function and call it in testBasicExample():
  15. class ExampleTest extends TestCase {
  16. /**
  17. * A basic functional test example.
  18. *
  19. * @return void
  20. */
  21. public function testBasicExample()
  22. {
  23. $crawler = $this->client->request('GET', '/');
  24. $this->assertTrue($this->client->getResponse()->isOk());
  25. self::my_test();//your method
  26. }
  27. public function my_test()
  28. {
  29. echo 'Hi I want to show you some test results :)';
  30. }
  31. }

8. Save and close the file and run again 'vendor\bin\phpunit'.And you will see output like this:

PHPUnit 3.7.29 by Sebastian Bergmann.

Configuration read from F:\laravel\laravelScrapbook\phpunit.xml

.Hi I want to show you test results :)

Time: 172 ms, Memory: 5.50Mb

←[30;42m←[2KOK (1 test, 1 assertion)
←[0m←[2K

UVa-12750 Keep Rafa at Chelsea

//Java Solution
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
class Main
{
 

    public static void main (String args[])  // entry point from OS
    {
        Main myWork = new Main();  // create a dynamic instance
        myWork.Begin();            // the true entry point
    }

    void Begin()
    {
 try
 {
// Scanner sc=new Scanner(new File("in.txt"));
Scanner sc=new Scanner(System.in);
PrintWriter pr=new PrintWriter(System.out);
   //default delimiter : "\\s+"
    // that means spaces , tabs , newlines(form feeds , carriage returns)
    // are skipped
//            while(sc.hasNext())
// {
// //take input
// }
int t=0;
t=sc.nextInt();
for(int i=1;i<=t;i++)
{
int n=sc.nextInt();
//got no of matches
int canStay=0;
int deathLimit=3;
int curDeathLimit=0;
for(int j=1;j<=n;j++){
String r=sc.next();
if(curDeathLimit<deathLimit){
if(r.compareTo("W")==0){
curDeathLimit=0;
}
else if(r.compareTo("D")==0 || r.compareTo("L")==0){
curDeathLimit++;
}
canStay++;
}
}
System.out.print("Case "+i+": ");
if(curDeathLimit<deathLimit) {System.out.println("Yay! Mighty Rafa persists!");}
else{
System.out.println(canStay);}
}
pr.close();
sc.close();
}
 catch(Exception e)
 {
// e.printStackTrace();
  System.exit(0);
 }
    }
}

Creating/registering new user in Crowd with Crowd REST java client

Put the dependecy in your pom.xml

<dependency>
<groupId>com.atlassian.crowd.client</groupId>
<artifactId>atlassian-crowd-rest-client</artifactId>
<version>1.1</version>
</dependency>

In your java code:
  1. import com.atlassian.crowd.embedded.api.PasswordCredential;
  2. import com.atlassian.crowd.exception.ApplicationPermissionException;
  3. import com.atlassian.crowd.exception.GroupNotFoundException;
  4. import com.atlassian.crowd.exception.InvalidAuthenticationException;
  5. import com.atlassian.crowd.exception.OperationFailedException;
  6. import com.atlassian.crowd.model.user.*;
  7. import com.atlassian.crowd.exception.UserNotFoundException;
  8. import com.atlassian.crowd.service.client.CrowdClient;
  9. import com.atlassian.crowd.integration.rest.service.factory.RestCrowdClientFactory;
  10. import com.atlassian.crowd.service.client.ClientPropertiesImpl;
  11. import com.atlassian.crowd.service.client.ClientResourceLocator;

public static int registerNewUser(String userName, String emailAddress, String password) {
//your crowd server settings
   String url = "http://auth.staging.company.com/crowd/";//crowd base url
   String applicationName = "appincrowd";
   String applicationPass = "apppassword";
   String groupName = "usergroup";//a user group under the app
   

   CrowdClient client = new RestCrowdClientFactory().newInstance(url, applicationName, applicationPass);
//initialze crowd client

   UserTemplate ut = new UserTemplate(userName);

   ut.setActive(true);//make it active
   ut.setEmailAddress(emailAddress);
   ut.setName(userName);
   PasswordCredential p = new PasswordCredential(password, false);
   client.addUser(ut, p);
   client.addUserToGroup(userName, groupName);//now add user to that group
}


Setting Crowd configuration with properties :
Instead of hard-coded crowd configuration we should read them from a properties file:
Properties crowdProp=//properties from your bean
 
   ClientPropertiesImpl newCrowdClient=ClientPropertiesImpl.newInstanceFromProperties(crowdProp);
   CrowdClient client = new RestCrowdClientFactory().newInstance(newCrowdClient);