text:
package helpers;

import controllers.CommentController;
import controllers.NewsController;
import controllers.SpecificVenueController;
import problemDomain.User;
import controllers.UserController;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.Object;
import java.net.URLEncoder;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import problemDomain.Comment;
import problemDomain.News;
import problemDomain.SpecificVenue;

/** UserHelper.java This Class helps our Front-end create HTML elements for Users.
 */
public class UserHelper
{
    UserController userController = lookupUserBrokerBean();
    CommentController commentController = lookupCommentControllerBean();
    NewsController newsController = lookupNewsBrokerBean();
    SpecificVenueController specificVenueController = lookupSpecificVenueBrokerBean();

    /**
     * Default Constructor
     */
    public UserHelper()
    {}

    /**
     * This method returns a Form for editing a News or Comment.
     * @param user User to check privileges for
     * @param commentID commentID of Comment to find
     * @param newsID newsID of News to find
     * @param fromMyNews redirect to MyNews flag
     * @param fromMyComments redirect to MyCOmments flag
     * @param location GoogleMaps URL
     * @return
     */
    public String editNewsOrComment(String user, String commentID, String newsID, String fromMyNews, String fromMyComments, String location)
    {
        String returnMe = "";
        String hiddenFromNews = "";
        String hiddenFromComments = "";

        if(location==null)
        {
            location="";
        }

        if(fromMyNews!=null)
        {
            hiddenFromNews = "<input type='hidden' name='fromNews' value='" + fromMyNews + "'>";
        }

        if(fromMyComments!=null)
        {
            hiddenFromComments = "<input type='hidden' name='fromComments' value='" + fromMyComments + "'>";
        }

        if(user!=null)
        {
            if(newsID!=null)
            {
                News getNews = newsController.get(Integer.parseInt(newsID));

                returnMe += "
Edit News

";
                returnMe += "
";
                returnMe += "<form action=NewsServlet method='POST'>";
                returnMe += "<input type='hidden' name='edit' value='editNews'>";
                returnMe += "<input type='hidden' value='" + getNews.getTitle() + "' name='newsTitle'>";
                returnMe += "
Text:

<textarea rows='6' cols='65' name='newsText' required>" + getNews.getText() + "</textarea>
";
                returnMe += hiddenFromNews;
                returnMe += "<input type='hidden' name='newsID' value='" + newsID + "'>";
                returnMe += "<input type='hidden' name='newsUser' value='" + getNews.getUsername() + "'>";
                returnMe += "<input type='hidden' name='newsFlag' value='" + getNews.getFlag() + "'>";
                returnMe += "<input type='hidden' name='newsRating' value='" + getNews.getRating() + "'>";
                returnMe += "
<input type='submit' value='Edit News'>
";
                returnMe += "" + getNews.getUsername() + "";
                returnMe += "</form>";
            }
            else if(commentID!=null)
            {
                Comment getComment = commentController.get(Integer.parseInt(commentID));
                SpecificVenue getSpecificVenue = specificVenueController.get(getComment.getSpecificVenueID());

                returnMe += "
";
                returnMe += "Edit Comment for: " + getSpecificVenue.getName() + "
";
                returnMe += "<form action=SVCommentServlet method='GET'>";
                returnMe += "<input type='hidden' name='edit' value='editComment'>";
                returnMe += "Text: <textarea rows='4' column='50' name='commentText' required>" + getComment.getText() + "</textarea>
";
                returnMe += hiddenFromComments;
                returnMe += "<input type='hidden' name='location' value='" + location + "'>";
                returnMe += "<input type='hidden' name='commentID' value='" + getComment.getCommentID() + "'>";
                returnMe += "<input type='hidden' name='commentVenueID' value='" + getComment.getSpecificVenueID() + "'>";
                returnMe += "<input type='hidden' name='commentUser' value='" + getComment.getUsername() + "'>";
                returnMe += "<input type='hidden' name='commentFlag' value='" + getComment.getFlag() + "'>";
                returnMe += "<input type='hidden' name='commentRating' value='" + getComment.getRating() + "'>";
                returnMe += "<input type='hidden' name='venueRating' value='" + getComment.getVenueRating() + "'>";
                returnMe += "<input type='submit' value='Edit Comment'>";
                returnMe += "" + getComment.getUsername() + "";
                returnMe += "</form>";
                returnMe += "
";
            }
        }
        return returnMe;
    }

    /**
     * This method creates a Table of Users.
     * @return a String that represents an HTML Table
     * @throws UnsupportedEncodingException
     */
    public String makeUserList() throws UnsupportedEncodingException
    {
        String returnMe = "

User List

Username	Admin	Notes	First Name	Last Name	Delete	Lock	";
        String strlock;
        String strAdmin;
        String delete;

        ArrayList<User> al = userController.getList();

        for(int i=0;i<al.size();i++)
        {
            if(al.get(i).getIsLocked())
            {
                strlock = "Unlock";
            }
            else
            {
                strlock = "lock";
            }

            if(al.get(i).isAdmin())
            {
                strAdmin = "Yes";
            }
            else
            {
                strAdmin = "No";
            }

            delete = "Delete	";

            String admin = "" + strAdmin + "";

            String lock = "" + strlock + "	";

            returnMe = returnMe + "
"
                       + al.get(i).getEmail()
                       + "	" + admin
                       + "	" + al.get(i).getNotes()
                       + "	" + al.get(i).getFirstName()
                       + "	" + al.get(i).getLastName()
                       + "	" + delete
                       + lock + "
";

        }

        //userBroker.close();

        return returnMe + "

";
    }

    /**
     * This method returns a div containing a specific User's profile options.
     * @param username the User to search for
     * @return a String that represents an HTML div
     */
    public String makeProfileOptions(String username)
    {
        String returnMe = "

Profile Options
";

        ArrayList<User> al = userController.getList();

        if(username!=null)
        {
            for(int i=0; i<al.size(); i++)
            {
                if(username.equals(al.get(i).getEmail()))
                {
                    if(al.get(i).isAdmin())
                    {
                        returnMe += "
View My Comments
";
                        returnMe += "
View My News Post
";
                        returnMe += "
View Flagged Comments
";
                        returnMe += "
View Flagged News
";
                        returnMe += "
View User List
";
                        returnMe += "
View Venue List
";
                    }
                    else
                    {
                        returnMe += "
View My Comments
";
                        returnMe += "
View My News Post
";
                    }
                }
            }
        }
        return returnMe + "
";
    }

    /**
     * This method returns a Form for creating a New User.
     * @return a String that represents an HTML Form
     */
    public String createNewUser()
    {
        String returnMe = "
";

        returnMe += "
Create User

";
        returnMe += "<form action='UserServlet' method='POST'>";
        returnMe += "
Email:

<input type='text' name='regEmail' placeholder='Email' autofocus required>

";
        returnMe += "
First Name:

<input type='text' name='regFirstName' placeholder='First Name' required>

";
        returnMe += "
Last Name:

<input type='text' name='regLastName' placeholder='Last Name' required>

";
        returnMe += "
Description:

<textarea rows='4' placeholder='Description' name='regNote'></textarea>

";
        returnMe += "
Password:

<input type='password' name='regPass' placeholder='Password' required>

";
        returnMe += "
Confirm Password:

<input type='password' name='regConfirm' placeholder='Confirm Password' required>

";
        returnMe += "
isAdmin<input type='checkbox' name='regIsAdmin' value='isAdmin'>
";
        returnMe += "
isLock<input type='checkbox' name='regIsLock' value='isLock'>
";
        returnMe += "
<input type='submit' value='Register'>

";
        returnMe += "</form>";

        return returnMe + "
";
    }

    /**
     * This method returns a Form for editing a User.
     * @param username User details to search for
     * @return a String that represents an HTML Form
     */
    public String editAccountDetails(String username)
    {
        String returnMe = "";

        ArrayList<User> al = userController.getList();

        if(username!=null)
        {
            returnMe = "
Account Details
";

            for(int i=0; i<al.size(); i++)
            {
                if(username.equals(al.get(i).getEmail()))
                {
                    returnMe += "<form action='UserServlet' method='POST'>";
                    returnMe += "
First Name:

<input type='text' name='editFirstName' value='" + al.get(i).getFirstName() + "' required>

";
                    returnMe += "
Last Name:

<input type='text' name='editLastName' value='" + al.get(i).getLastName() + "' required>

";
                    returnMe += "
Description:

<textarea rows='4' name='editNote'>" + al.get(i).getNotes() + "</textarea>

";
                    returnMe += "<input type='hidden' name='isAdmin' value='" + al.get(i).isAdmin() + "'>";
                    returnMe += "<input type='hidden' name='isLock' value='" + al.get(i).getIsLocked() + "'>";
                    returnMe += "<input type='hidden' name='username' value='" + al.get(i).getEmail() + "'>";
                    returnMe += "
Password:

<input type='password' name='editPassword' value='" + al.get(i).getPassword() + "' required>

";
                    returnMe += "
Confirm Password:

<input type='password' name='editConfirmPassword' value='" + al.get(i).getPassword() + "' required>

";
                    returnMe += "
<input type='submit' value='Save Changes'>

";
                    returnMe += "</form>";
                }
            }

            return returnMe;
        }

        return returnMe;

    }

   /********************************************************************************************************/
    /**Buchi's Mobile Method to edit
     * account details in Form
     * @param username
     * @param mode
     * @return
     */
    public String editAccountDetails(String username, String mode)
    {
        String returnMe = "";

        if(mode == "m")
        {
        ArrayList<User> al = userController.getList();

        if(username!=null)
        {
            //returnMe = "
";
            //returnMe = "	";

            for(int i=0; i<al.size(); i++)
            {
                if(username.equals(al.get(i).getEmail()))
                {
                    returnMe += "<form class='form-signin' action='UserServlet' method='POST'>";
                    returnMe+=  "
Account Details
";
                    returnMe += "
First Name	<input type='text' class='form-control' name='editFirstName' value='" + al.get(i).getFirstName() + "' required>
";
                    returnMe += "
Last Name	<input type='text' name='editLastName' class='form-control' value='" + al.get(i).getLastName() + "' required>
";
                    returnMe += "
Description	<textarea rows='4' name='editNote' class='form-control'>" + al.get(i).getNotes() + "</textarea>
";
                    returnMe += "<input type='hidden' name='isAdmin' class='form-control' value='" + al.get(i).isAdmin() + "'>";
                    returnMe += "<input type='hidden' name='isLock' class='form-control' value='" + al.get(i).getIsLocked() + "'>";
                    returnMe += "<input type='hidden' name='username' class='form-control' value='" + al.get(i).getEmail() + "'>";
                    returnMe += "
Password	<input type='password' name='editPassword' class='form-control' value='" + al.get(i).getPassword() + "' required>
";
                    returnMe += "
Confirm Password	<input type='password' class='form-control' name='editConfirmPassword' value='" + al.get(i).getPassword() + "' required>
";
                    returnMe += "
<input class='btn btn-lg btn-primary btn-block' type='submit' value='Save Changes'>

";
                    returnMe += "</form>";
                }
            }

            //return returnMe + "
";
        }
       }
        return returnMe;

    }
    /**
     * Buchi's mobile method Form to createNewUser
     * @param mode
     * @return
     */
     public String createNewUser(String mode)
    {

        String returnMe = "
";
        if(mode == "m")
        {

        returnMe += "<form action='UserServlet' class='list-form-signin' method='POST'>";
        returnMe += "
Create User
";
        returnMe += "<input type='text' class='form-control' name='regEmail' placeholder='Email' autofocus required>";
        returnMe += "<input type='text' class='form-control' name='regFirstName' placeholder='First Name' required>";
        returnMe += "<input type='text' class='form-control' name='regLastName' placeholder='Last Name' required>";
        returnMe += "<textarea rows='4' class='form-control' placeholder='Description' name='regNote'></textarea>";
        returnMe += "<input type='password' class='form-control' name='regPass' placeholder='Password' required>";
        returnMe += "<input type='password' class='form-control' name='regConfirm' placeholder='Confirm Password' required>";
        returnMe += "<input type='checkbox' class='checkbox-inline' name='regIsAdmin' value='isAdmin'>isAdmin";
        returnMe += "<input type='checkbox' class='checkbox-inline' name='regIsLock' value='isLock'>isLock";
        returnMe += "<input class='btn btn-lg btn-primary btn-block' type='submit' value='Register'>";

        returnMe += "</form>";
        }
        return returnMe + "
";
    }

     /**
      * Method to make list of users
      * @param mode
      * @return
      * @throws java.io.UnsupportedEncodingException
      */
      public String makeUserList(String mode) throws UnsupportedEncodingException
    {
        String returnMe = "

User List

Username	admin	Notes	FirstName	LastName	Delete	Lock	";
        String strlock;
        String strAdmin;
        String delete;
        if(mode == "m")
        {
        ArrayList<User> al = userController.getList();

        for(int i=0;i<al.size();i++)
        {
            if(al.get(i).getIsLocked())
            {
                strlock = "Unlock";
            }
            else
            {
                strlock = "lock";
            }

            if(al.get(i).isAdmin())
            {
                strAdmin = "Yes";
            }
            else
            {
                strAdmin = "No";
            }

            delete = "Delete	";

            String admin = "" + strAdmin + "";

            String lock = "" + strlock + "	";

            returnMe = returnMe + "
"
                       + al.get(i).getEmail()
                       + "	" + admin
                       + "	" + al.get(i).getNotes()
                       + "	" + al.get(i).getFirstName()
                       + "	" + al.get(i).getLastName()
                       + "	" + delete
                       + lock + "
";

        }

        //userBroker.close();
       }
        return returnMe + "

";
    }

      public String editNewsOrComment(String user, String commentID, String newsID, String fromMyNews, String fromMyComments, String location,String mode)
    {
        String returnMe = "";
        String hiddenFromNews = "";
        String hiddenFromComments = "";

        if(mode =="m")
        {
        if(location==null)
        {
            location="";
        }

        if(fromMyNews!=null)
        {
            hiddenFromNews = "<input type='hidden' name='fromNews' value='" + fromMyNews + "'>";
        }

        if(fromMyComments!=null)
        {
            hiddenFromComments = "<input type='hidden' name='fromComments' value='" + fromMyComments + "'>";
        }

        if(user!=null)
        {
            if(newsID!=null)
            {
                News getNews = newsController.get(Integer.parseInt(newsID));

                returnMe += "
";
                returnMe += "<form action=NewsServlet method='POST' class='form-signin'>";
                returnMe += "
Edit News
";
                returnMe += "<input type='hidden' name='edit' value='editNews'>";
                returnMe += "Title: <input type='hidden' value='" + getNews.getTitle() + "' name='newsTitle'>";
                returnMe += "Text: <textarea rows='4' class='form-control' column='50' name='newsText' required>" + getNews.getText() + "</textarea>";
                returnMe += hiddenFromNews;
                returnMe += "<input type='hidden' name='newsID' value='" + newsID + "'>";
                returnMe += "<input type='hidden' name='newsUser' value='" + getNews.getUsername() + "'>";
                returnMe += "<input type='hidden' name='newsFlag' value='" + getNews.getFlag() + "'>";
                returnMe += "<input type='hidden' name='newsRating' value='" + getNews.getRating() + "'>";
                returnMe += "<input type='submit' class='btn btn-lg btn-primary btn-block' value='Edit News'>";
                returnMe += "" + getNews.getUsername() + "";
                returnMe += "</form>";
                returnMe += "
";
            }
            else if(commentID!=null)
            {
                Comment getComment = commentController.get(Integer.parseInt(commentID));
                SpecificVenue getSpecificVenue = specificVenueController.get(getComment.getSpecificVenueID());

                returnMe += "
";
                returnMe += "<form action=SVCommentServletMobile method='POST' class='form-signin'>";
                 returnMe += "
Edit Comment for: " + getSpecificVenue.getName().toLowerCase() + "
";
                returnMe += "<input type='hidden' name='edit' value='editComment'>";
                returnMe += "Text: <textarea rows='4' class='form-control' column='50' name='commentText' required>" + getComment.getText() + "</textarea>";
                returnMe += hiddenFromComments;
                returnMe += "<input type='hidden' name='location' value='" + location + "'>";
                returnMe += "<input type='hidden' name='commentID' value='" + getComment.getCommentID() + "'>";
                returnMe += "<input type='hidden' name='commentVenueID' value='" + getComment.getSpecificVenueID() + "'>";
                returnMe += "<input type='hidden' name='commentUser' value='" + getComment.getUsername() + "'>";
                returnMe += "<input type='hidden' name='commentFlag' value='" + getComment.getFlag() + "'>";
                returnMe += "<input type='hidden' name='commentRating' value='" + getComment.getRating() + "'>";
                returnMe += "<input type='hidden' name='venueRating' value='" + getComment.getVenueRating() + "'>";
                returnMe += "<input type='submit' class='btn btn-lg btn-primary btn-block' value='Edit Comment'>";
                returnMe += "" + getComment.getUsername() + "";
                returnMe += "</form>";
                returnMe += "
";
            }
        }
       }
        return returnMe;
    }

    /**
     * This method allows for EJB injection by looking up the EJB in the JNDI.
     * @return the EJB
     */
    private UserController lookupUserBrokerBean()
    {
        try {
            Context c = new InitialContext();
            return (UserController) c.lookup("java:global/AccessibilityWebsite2/AccessibilityWebsite2-ejb/UserController!controllers.UserController");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    /**
     * This method allows for EJB injection by looking up the EJB in the JNDI.
     * @return the EJB
     */
    private NewsController lookupNewsBrokerBean()
    {
        try {
            Context c = new InitialContext();
            return (NewsController) c.lookup("java:global/AccessibilityWebsite2/AccessibilityWebsite2-ejb/NewsController!controllers.NewsController");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    /**
     * This method allows for EJB injection by looking up the EJB in the JNDI.
     * @return the EJB
     */
    private CommentController lookupCommentControllerBean() {
        try {
            Context c = new InitialContext();
            return (CommentController) c.lookup("java:global/AccessibilityWebsite2/AccessibilityWebsite2-ejb/CommentController!controllers.CommentController");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    /**
     * This method allows for EJB injection by looking up the EJB in the JNDI.
     * @return the EJB
     */
    private SpecificVenueController lookupSpecificVenueBrokerBean()
    {
        try {
            Context c = new InitialContext();
            return (SpecificVenueController) c.lookup("java:global/AccessibilityWebsite2/AccessibilityWebsite2-ejb/SpecificVenueController!controllers.SpecificVenueController");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}


text:
<?xml version="1.0" ?>
<complete>
	<option value="1">one</option>
	<option value="2">two</option>
	<option value="3">three</option>
	<option value="4">four</option>
	<option value="5">five</option>
	<option value="6">six</option>
	<option value="7" selected="1">seven</option>
	<option value="8">eight</option>
	<option value="9">nine</option>
	<option value="10">ten</option>
</complete>

redpajama_set_name: RedPajamaGithub


text:
describe('Testing curry functions', function() {

    it('Our function returns simple string', function() {
        function formString(a, b, c) {
            return a + ' ' + b + ' ' + c;
        }
        var curried = formString.curry();

        expect(curried('Hello')('cruel')('world')).toEqual('Hello cruel world');
    });

    it('Our function returns simple multiplication', function() {
        function volume(l, w, h) {
            return l * w * h;
        }
        var curried = volume.curry();

        expect(curried(1)(2)(3)).toBe(6);
        expect(curried(0)(1)(2)).toBe(0);
        expect(curried(1)(2)(0)).toBe(0);
        expect(curried(1)(2)('hello')).toBeNaN();
    });

    it('Our function return numbers sequence betwen numbers', function() {
        function writeSeq(start, end, omit) {
            var seq = [],
                i = start;
            if (start < end) {
                for (i; i < end; ++i) {
                    if (i !== omit) {
                        seq.push(i);
                    }
                }
            } else {
                for (i; i > end; --i) {
                    if (i !== omit) {
                        seq.push(i);
                    }
                }
            }
            return seq;
        }
        var curried = writeSeq.curry();

        expect(curried(0)(10)(56)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
        expect(curried(0)(5)(3)).toEqual([0, 1, 2, 4]);
        expect(curried(7)(3)(2)).toEqual([7, 6, 5, 4]);
        expect(curried(7)(3)(5)).toEqual([7, 6, 4]);
    });

    it('Our function return a find the word function inserted in the last parameter', function() {
        function findWord(phrase, word) {
            var result = false,
                wordToFind = word || undefined;
            if (wordToFind && phrase.indexOf(word) > -1) {
                result = true;
            }
            return result;
        }
        var curried = findWord.curry();

        expect(curried('Hello cruel world')('world')).toBe(true);
        expect(curried('Hello cruel world')(undefined)).toBe(false);
    });

    it('Our function return a standard set of functions for converting units of measures', function() {
        function makeConverter(toUnit, factor, offset) {
            offset = offset || 0;
            return function(input) {
                return [((offset + input) * factor).toFixed(2), toUnit].join(' ');
            };
        }
        var milesToKm = makeConverter('km', 1.60936).curry(),
            poundsToKg = makeConverter('kg', 0.45460).curry(),
            farenheitToCelsius = makeConverter('degrees C', 0.5556, -32).curry();

        expect(milesToKm(10)).toBe('16.09 km');
        expect(poundsToKg(2.5)).toBe('1.14 kg');
        expect(farenheitToCelsius(98)).toBe('36.67 degrees C');
    });
});


text:
package org.apache.shardingsphere.readwritesplitting.rule;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmFactory;
import org.apache.shardingsphere.infra.distsql.constant.ExportableConstants;
import org.apache.shardingsphere.infra.rule.event.DataSourceStatusChangedEvent;
import org.apache.shardingsphere.infra.rule.event.impl.DataSourceNameDisabledEvent;
import org.apache.shardingsphere.infra.rule.identifier.scope.SchemaRule;
import org.apache.shardingsphere.infra.rule.identifier.type.DataSourceContainedRule;
import org.apache.shardingsphere.infra.rule.identifier.type.ExportableRule;
import org.apache.shardingsphere.infra.rule.identifier.type.StatusContainedRule;
import org.apache.shardingsphere.readwritesplitting.algorithm.DynamicReadwriteSplittingType;
import org.apache.shardingsphere.readwritesplitting.algorithm.config.AlgorithmProvidedReadwriteSplittingRuleConfiguration;
import org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration;
import org.apache.shardingsphere.readwritesplitting.api.rule.ReadwriteSplittingDataSourceRuleConfiguration;
import org.apache.shardingsphere.readwritesplitting.spi.ReadwriteSplittingType;
import org.apache.shardingsphere.readwritesplitting.spi.ReplicaLoadBalanceAlgorithm;
import org.apache.shardingsphere.spi.ShardingSphereServiceLoader;
import org.apache.shardingsphere.spi.required.RequiredSPIRegistry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Map.Entry;
import java.util.function.Supplier;

/**
 * Readwrite-splitting rule.
 */
public final class ReadwriteSplittingRule implements SchemaRule, DataSourceContainedRule, StatusContainedRule, ExportableRule {

    static {
        ShardingSphereServiceLoader.register(ReplicaLoadBalanceAlgorithm.class);
        ShardingSphereServiceLoader.register(ReadwriteSplittingType.class);
    }

    private static final String DYNAMIC = "DYNAMIC";

    private static final String STATIC = "STATIC";

    private final Map<String, ReplicaLoadBalanceAlgorithm> loadBalancers = new LinkedHashMap<>();

    private final Map<String, ReadwriteSplittingDataSourceRule> dataSourceRules;

    public ReadwriteSplittingRule(final ReadwriteSplittingRuleConfiguration ruleConfig) {
        Preconditions.checkArgument(!ruleConfig.getDataSources().isEmpty(), "Replica query data source rules can not be empty.");
        ruleConfig.getLoadBalancers().forEach((key, value) -> loadBalancers.put(key, ShardingSphereAlgorithmFactory.createAlgorithm(value, ReplicaLoadBalanceAlgorithm.class)));
        dataSourceRules = new HashMap<>(ruleConfig.getDataSources().size(), 1);
        for (ReadwriteSplittingDataSourceRuleConfiguration each : ruleConfig.getDataSources()) {
            // TODO check if can not find load balancer should throw exception.
            ReplicaLoadBalanceAlgorithm loadBalanceAlgorithm = Strings.isNullOrEmpty(each.getLoadBalancerName()) || !loadBalancers.containsKey(each.getLoadBalancerName())
                    ? RequiredSPIRegistry.getRegisteredService(ReplicaLoadBalanceAlgorithm.class) : loadBalancers.get(each.getLoadBalancerName());
            dataSourceRules.put(each.getName(), new ReadwriteSplittingDataSourceRule(each, loadBalanceAlgorithm));
        }
    }

    public ReadwriteSplittingRule(final AlgorithmProvidedReadwriteSplittingRuleConfiguration ruleConfig) {
        Preconditions.checkArgument(!ruleConfig.getDataSources().isEmpty(), "Replica query data source rules can not be empty.");
        loadBalancers.putAll(ruleConfig.getLoadBalanceAlgorithms());
        dataSourceRules = new HashMap<>(ruleConfig.getDataSources().size(), 1);
        for (ReadwriteSplittingDataSourceRuleConfiguration each : ruleConfig.getDataSources()) {
            // TODO check if can not find load balancer should throw exception.
            ReplicaLoadBalanceAlgorithm loadBalanceAlgorithm = Strings.isNullOrEmpty(each.getLoadBalancerName()) || !loadBalancers.containsKey(each.getLoadBalancerName())
                    ? RequiredSPIRegistry.getRegisteredService(ReplicaLoadBalanceAlgorithm.class) : loadBalancers.get(each.getLoadBalancerName());
            dataSourceRules.put(each.getName(), new ReadwriteSplittingDataSourceRule(each, loadBalanceAlgorithm));
        }
    }

    /**
     * Get single data source rule.
     *
     * @return replica query data source rule
     */
    public ReadwriteSplittingDataSourceRule getSingleDataSourceRule() {
        return dataSourceRules.values().iterator().next();
    }

    /**
     * Find data source rule.
     *
     * @param dataSourceName data source name
     * @return replica query data source rule
     */
    public Optional<ReadwriteSplittingDataSourceRule> findDataSourceRule(final String dataSourceName) {
        return Optional.ofNullable(dataSourceRules.get(dataSourceName));
    }

    @Override
    public Map<String, Collection<String>> getDataSourceMapper() {
        Map<String, Collection<String>> result = new HashMap<>();
        for (Entry<String, ReadwriteSplittingDataSourceRule> entry : dataSourceRules.entrySet()) {
            result.putAll(entry.getValue().getDataSourceMapper());
        }
        return result;
    }

    @Override
    public void updateStatus(final DataSourceStatusChangedEvent event) {
        if (event instanceof DataSourceNameDisabledEvent) {
            for (Entry<String, ReadwriteSplittingDataSourceRule> entry : dataSourceRules.entrySet()) {
                entry.getValue().updateDisabledDataSourceNames(((DataSourceNameDisabledEvent) event).getDataSourceName(), ((DataSourceNameDisabledEvent) event).isDisabled());
            }
        }
    }

    @Override
    public Map<String, Supplier<Object>> getExportedMethods() {
        Map<String, Supplier<Object>> result = new HashMap<>(3, 1);
        result.put(ExportableConstants.EXPORTABLE_KEY_AUTO_AWARE_DATA_SOURCE, () -> exportDataSource(DYNAMIC));
        result.put(ExportableConstants.EXPORTABLE_KEY_AUTO_AWARE_DATA_SOURCE_NAME, this::exportAutoAwareDataSourceNames);
        result.put(ExportableConstants.EXPORTABLE_KEY_DATA_SOURCE, () -> exportDataSource(STATIC));
        return result;
    }

    private Map<String, Map<String, String>> exportDataSource(final String readwriteSplittingType) {
        Map<String, Map<String, String>> result = new HashMap<>(dataSourceRules.size(), 1);
        dataSourceRules.forEach((name, dataSourceRule) -> {
            if (readwriteSplittingType.equalsIgnoreCase(dataSourceRule.getReadwriteSplittingType().getType())) {
                Map<String, String> dataSources = dataSourceRule.getDataSources();
                if (!dataSources.isEmpty()) {
                    result.put(dataSourceRule.getName(), dataSources);
                }
            }
        });
        return result;
    }

    private Collection<String> exportAutoAwareDataSourceNames() {
        Collection<String> result = new ArrayList<>();
        for (ReadwriteSplittingDataSourceRule each : dataSourceRules.values()) {
            if (each.getReadwriteSplittingType() instanceof DynamicReadwriteSplittingType) {
                result.add(((DynamicReadwriteSplittingType) each.getReadwriteSplittingType()).getAutoAwareDataSourceName());
            }
        }
        return result;
    }

    @Override
    public String getType() {
        return ReadwriteSplittingRule.class.getSimpleName();
    }
}


text:
package org.hl7.fhir.utilities;

/*
 * #%L
 * HAPI FHIR - Core Library
 * %%
 * Copyright (C) 2014 - 2015 University Health Network
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.TransformerFactoryImpl;

public class Utilities {

//	 private static final String TOKEN_REGEX = "^a-z[A-Za-z0-9]*$";

  /**
     * Returns the plural form of the word in the string.
     *
     * Examples:
     *
     *

     *   inflector.pluralize("post")               #=> "posts"
     *   inflector.pluralize("octopus")            #=> "octopi"
     *   inflector.pluralize("sheep")              #=> "sheep"
     *   inflector.pluralize("words")              #=> "words"
     *   inflector.pluralize("the blue mailman")   #=> "the blue mailmen"
     *   inflector.pluralize("CamelOctopus")       #=> "CamelOctopi"
     *

     *
     *
     *
     * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
     *
     *
     * @param word the word that is to be pluralized.
     * @return the pluralized form of the word, or the word itself if it could not be pluralized
     */
    public static String pluralizeMe( String word ) {
    	Inflector inf = new Inflector();
    	return inf.pluralize(word);
    }

  	public static boolean IsInteger(String string) {
  		try {
  			int i = Integer.parseInt(string);
  			return i != i+1;
  		} catch (Exception e) {
  			return false;
  		}
  	}

  	public static boolean IsDecimal(String string) {
  		try {
  			float r = Float.parseFloat(string);
  			return r != r + 1; // just to suppress the hint
  		} catch (Exception e) {
  			return false;
  		}
  	}

	public static String camelCase(String value) {
	  return new Inflector().camelCase(value.trim().replace(" ", "_"), false);
	}

	public static String escapeXml(String doco) {
		if (doco == null)
			return "";

		StringBuilder b = new StringBuilder();
		for (char c : doco.toCharArray()) {
		  if (c == '<')
			  b.append("<");
		  else if (c == '>')
			  b.append(">");
		  else if (c == '&')
			  b.append("&");
      else if (c == '"')
        b.append(""");
		  else
			  b.append(c);
		}
		return b.toString();
	}

	public static String capitalize(String s)
	{
		if( s == null ) return null;
		if( s.length() == 0 ) return s;
		if( s.length() == 1 ) return s.toUpperCase();

		return s.substring(0, 1).toUpperCase() + s.substring(1);
	}

  public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws Exception {
    CSFile src = new CSFile(sourceFolder);
    if (!src.exists())
      throw new Exception("Folder " +sourceFolder+" not found");
    createDirectory(destFolder);

   String[] files = src.list();
   for (String f : files) {
     if (new CSFile(sourceFolder+File.separator+f).isDirectory()) {
       if (!f.startsWith(".")) // ignore .svn...
         copyDirectory(sourceFolder+File.separator+f, destFolder+File.separator+f, notifier);
     } else {
       if (notifier != null)
         notifier.copyFile(sourceFolder+File.separator+f, destFolder+File.separator+f);
       copyFile(new CSFile(sourceFolder+File.separator+f), new CSFile(destFolder+File.separator+f));
     }
   }
  }

  public static void copyFile(String source, String dest) throws IOException {
    copyFile(new File(source), new File(dest));
  }

	public static void copyFile(File sourceFile, File destFile) throws IOException {
		if(!destFile.exists()) {
			if (!new CSFile(destFile.getParent()).exists()) {
				createDirectory(destFile.getParent());
			}
			destFile.createNewFile();
		}

		FileChannel source = null;
		FileChannel destination = null;

		try {
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();
			destination.transferFrom(source, 0, source.size());
		}
		finally {
			if(source != null) {
				source.close();
			}
			if(destination != null) {
				destination.close();
			}
		}
	}

  public static boolean checkFolder(String dir, List<String> errors)
  	throws IOException
  {
	  if (!new CSFile(dir).exists()) {
      errors.add("Unable to find directory "+dir);
      return false;
    } else {
      return true;
    }
  }

  public static boolean checkFile(String purpose, String dir, String file, List<String> errors)
  	throws IOException
  {
    if (!new CSFile(dir+file).exists()) {
      errors.add("Unable to find "+purpose+" file "+file+" in "+dir);
      return false;
    } else {
      return true;
    }
  }

  public static String asCSV(List<String> strings) {
    StringBuilder s = new StringBuilder();
    boolean first = true;
    for (String n : strings) {
      if (!first)
        s.append(",");
      s.append(n);
      first = false;
    }
    return s.toString();
  }

  public static String asHtmlBr(String prefix, List<String> strings) {
    StringBuilder s = new StringBuilder();
    boolean first = true;
    for (String n : strings) {
      if (!first)
        s.append("
");
      s.append(prefix);
      s.append(n);
      first = false;
    }
    return s.toString();
  }

  public static void clearDirectory(String folder) throws IOException {
	  String[] files = new CSFile(folder).list();
	  if (files != null) {
		  for (String f : files) {
			  File fh = new CSFile(folder+File.separatorChar+f);
			  if (fh.isDirectory())
				  clearDirectory(fh.getAbsolutePath());
			  fh.delete();
		  }
	  }
  }

  public static void createDirectory(String path) throws IOException{
    new CSFile(path).mkdirs();
  }

  public static String changeFileExt(String name, String ext) {
    if (name.lastIndexOf('.') > -1)
      return name.substring(0, name.lastIndexOf('.')) + ext;
    else
      return name+ext;
  }

  public static String cleanupTextString( String contents )
  {
	  if( contents == null || contents.trim().equals("") )
		  return null;
	  else
		  return contents.trim();
  }

  public static boolean noString(String v) {
    return v == null || v.equals("");
  }

  public static byte[] saxonTransform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws Exception {
    TransformerFactory f = new net.sf.saxon.TransformerFactoryImpl();
    f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
    StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
    f.setURIResolver(new ZipURIResolver(files));
    Transformer t = f.newTransformer(xsrc);

    t.setURIResolver(new ZipURIResolver(files));
    StreamSource src = new StreamSource(new ByteArrayInputStream(source));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult res = new StreamResult(out);
    t.transform(src, res);
    return out.toByteArray();
  }

  public static byte[] transform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws Exception {
    TransformerFactory f = TransformerFactory.newInstance();
    f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
    StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
    f.setURIResolver(new ZipURIResolver(files));
    Transformer t = f.newTransformer(xsrc);

    t.setURIResolver(new ZipURIResolver(files));
    StreamSource src = new StreamSource(new ByteArrayInputStream(source));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamResult res = new StreamResult(out);
    t.transform(src, res);
    return out.toByteArray();
  }

  public static void bytesToFile(byte[] content, String filename) throws Exception {
    FileOutputStream out = new FileOutputStream(filename);
    out.write(content);
    out.close();

  }

  public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws Exception {
  	saxonTransform(xsltDir, source, xslt, dest, alt, null);
  }

  public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt, Map<String, String> params) throws Exception {
    TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl();
    f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
    StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
    f.setURIResolver(new MyURIResolver(xsltDir, alt));
    Transformer t = f.newTransformer(xsrc);
 		if (params != null) {
 			for (Map.Entry<String, String> entry : params.entrySet()) {
 				t.setParameter(entry.getKey(), entry.getValue());
 			}
  	}

    t.setURIResolver(new MyURIResolver(xsltDir, alt));
    StreamSource src = new StreamSource(new FileInputStream(source));
    StreamResult res = new StreamResult(new FileOutputStream(dest));
    t.transform(src, res);
  }

  public static void transform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws Exception {

    TransformerFactory f = TransformerFactory.newInstance();
    StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
    f.setURIResolver(new MyURIResolver(xsltDir, alt));
    Transformer t = f.newTransformer(xsrc);

    t.setURIResolver(new MyURIResolver(xsltDir, alt));
    StreamSource src = new StreamSource(new FileInputStream(source));
    StreamResult res = new StreamResult(new FileOutputStream(dest));
    t.transform(src, res);

  }

  public static String appendSlash(String definitions) {
    return definitions.endsWith(File.separator) ? definitions : definitions+File.separator;
  }

  public static String fileTitle(String file) {
    if (file == null)
      return null;
    String s = new File(file).getName();
    return s.indexOf(".") == -1? s : s.substring(0, s.indexOf("."));
  }

  public static String systemEol()
  {
	  return System.getProperty("line.separator");
  }

  public static String normaliseEolns(String value) {
    return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n");
  }

  public static String unescapeXml(String xml) throws Exception {
    if (xml == null)
      return null;

    StringBuilder b = new StringBuilder();
    int i = 0;
    while (i < xml.length()) {
      if (xml.charAt(i) == '&') {
        StringBuilder e = new StringBuilder();
        i++;
        while (xml.charAt(i) != ';') {
          e.append(xml.charAt(i));
          i++;
        }
        if (e.toString().equals("lt"))
          b.append("<");
        else if (e.toString().equals("gt"))
          b.append(">");
        else if (e.toString().equals("amp"))
          b.append("&");
        else if (e.toString().equals("quot"))
          b.append("\"");
        else if (e.toString().equals("mu"))
          b.append((char)956);
        else
          throw new Exception("unknown XML entity \""+e.toString()+"\"");
      }  else
        b.append(xml.charAt(i));
      i++;
    }
    return b.toString();
  }

  public static boolean isPlural(String word) {
    word = word.toLowerCase();
    if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word))
      return false;
    Inflector inf = new Inflector();
    return !inf.singularize(word).equals(word);
  }

  public static String padLeft(String src, char c, int len) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < len - src.length(); i++)
      s.append(c);
    s.append(src);
    return s.toString();

  }

  public static String path(String... args) {
    StringBuilder s = new StringBuilder();
    boolean d = false;
    for(String arg: args) {
      if (!d)
        d = true;
      else if (!s.toString().endsWith(File.separator))
        s.append(File.separator);
      s.append(arg);
    }
    return s.toString();
  }

//  public static void checkCase(String filename) {
//    File f = new CSFile(filename);
//    if (!f.getName().equals(filename))
//      throw new Exception("Filename  ")
//
//  }

  public static String nmtokenize(String cs) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < cs.length(); i++) {
      char c = cs.charAt(i);
      if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')
        s.append(c);
      else if (c != ' ')
        s.append("."+Integer.toString(c));
    }
    return s.toString();
  }

  public static boolean isToken(String tail) {
    if (tail == null || tail.length() == 0)
      return false;
    boolean result = isAlphabetic(tail.charAt(0));
    for (int i = 1; i < tail.length(); i++) {
    	result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_')  || (tail.charAt(i) == '[') || (tail.charAt(i) == ']'));
    }
    return result;
  }

  private static boolean isDigit(char c) {
    return (c >= '0') && (c <= '9');
  }

  private static boolean isAlphabetic(char c) {
    return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
  }

  public static String getDirectoryForFile(String filepath) {
    int i = filepath.lastIndexOf(File.separator);
    if (i == -1)
      return filepath;
    else
      return filepath.substring(0, i);
  }

  public static String appendPeriod(String s) {
    if (Utilities.noString(s))
      return s;
    if (s.endsWith("."))
      return s;
    return s.trim()+".";
  }

  public static String removePeriod(String s) {
    if (Utilities.noString(s))
      return s;
    if (s.endsWith("."))
      return s.substring(0, s.length()-1);
    return s;
  }

	public static String stripBOM(String string) {
	  return string.replace("\uFEFF", "");
  }

  public static String oidTail(String id) {
    if (id == null || !id.contains("."))
      return id;
    return id.substring(id.lastIndexOf(".")+1);
  }

  public static String escapeJava(String doco) {
    if (doco == null)
      return "";

    StringBuilder b = new StringBuilder();
    for (char c : doco.toCharArray()) {
      if (c == '\r')
        b.append("\\r");
      else if (c == '\n')
        b.append("\\n");
      else if (c == '"')
        b.append("'");
      else
        b.append(c);
    }
    return b.toString();
  }

  public static String[] splitByCamelCase(String name) {
    List<String> parts = new ArrayList<String>();
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < name.length(); i++) {
      if (i > 0 && Character.isUpperCase(name.charAt(i))) {
        parts.add(b.toString());
        b = new StringBuilder();
      }
      b.append(Character.toLowerCase(name.charAt(i)));
    }
    parts.add(b.toString());
    return parts.toArray(new String[] {} );
  }

  public static String encodeUri(String v) {
    return v.replace(" ", "%20");
  }

	public static String normalize(String s) {
		if (noString(s))
			return null;
	  StringBuilder b = new StringBuilder();
	  boolean isWhitespace = false;
	  for (int i = 0; i < s.length(); i++) {
	  	char c = s.charAt(i);
	  	if (!Character.isWhitespace(c)) {
	  		b.append(Character.toLowerCase(c));
	  		isWhitespace = false;
	  	} else if (!isWhitespace) {
	  		b.append(' ');
	  		isWhitespace = true;
	  	}
	  }
	  return b.toString().trim();
  }

  public static void copyFileToDirectory(File source, File destDir) throws IOException {
  	copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName())));
  }

	public static boolean isWhitespace(String s) {
	  boolean ok = true;
	  for (int i = 0; i < s.length(); i++)
	  	ok = ok && Character.isWhitespace(s.charAt(i));
	  return ok;

  }

  public static String URLEncode(String string) {
    try {
      return URLEncoder.encode(string, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new Error(e.getMessage());
    }
  }

  public static boolean existsInList(String value, String... array) {
    for (String s : array)
      if (value.equals(s))
          return true;
    return false;
  }

  public static String getFileNameForName(String name) {
    return name.toLowerCase();
  }

  public static void deleteTempFiles() throws IOException {
    File file = createTempFile("test", "test");
    String folder = getDirectoryForFile(file.getAbsolutePath());
    String[] list = new File(folder).list(new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.startsWith("ohfu-");
      }
    });
    if (list != null) {
      for (String n : list) {
        new File(path(folder, n)).delete();
      }
    }
  }

  public static File createTempFile(String prefix, String suffix) throws IOException {
 // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work.
    File file = File.createTempFile("ohfu-"+prefix, suffix);
    file.deleteOnExit();
    return file;
  }

	public static boolean isAsciiChar(char ch) {
		return ch >= ' ' && ch <= '~';
  }

  public static String makeUuidUrn() {
    return "urn:uuid:"+UUID.randomUUID().toString().toLowerCase();
  }

  public static boolean isURL(String s) {
    boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*");
    return ok;
 }

}


text:
<?php
namespace SocialyticsBundle\Controller;

use SocialyticsBundle\Service\Strategy\MetricNames;
use SocialyticsBundle\Service\Strategy\MetricFormatTypes;

use SocialyticsBundle\Form\ReportType;
use SocialyticsBundle\Entity\Report;
use SocialyticsBundle\Form\Model\MetricPanel;
use SocialyticsBundle\Form\MetricPanelType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class AdminController extends Controller
{
    /**
     * @Route("/admin/dashboard", name="admin_dashboard")
     * @Template()
     */
    public function dashBoardAction()
    {
        $token = $this->getToken();
        $user = $token->getUser();
        $resourceOwnerName = $token->getResourceOwnerName();

        $form = $this->createForm(new ReportType());

        return array(
            'form' => $form->createView(),
            'resourceOwnerName' => ucfirst($resourceOwnerName),
            'username' => $user->getUsername()
                );
    }

    /**
     * @Route("/admin/report/{id}", name="admin_report")
     * @Template()
     */
    public function reportAction(Request $request, $id)
    {
        $metricPanel = new MetricPanel();
        $report = $this->getDoctrine()->getManager()->getRepository('SocialyticsBundle:Report')->find($id);
        $form = $this->createForm(new MetricPanelType(MetricNames::names(),  MetricFormatTypes::names()), $metricPanel);

        $form->handleRequest($request);
        if($form->isValid())
        {
            $token = $this->getToken();
            $username = $this->getUsername($token);
            $metricFactory = $this->get('metric_factory');

            $metric = $metricFactory->create($form->getData(), $username);

            $result = $metric->calculate();

            $reportService = $this->get('report.service');
            $reportService->addMetric($report, $form->getData(), $result);

            $em = $this->getDoctrine()->getManager();
            $em->flush();

            return $this->redirect($this->generateUrl('admin_report',array('id'=>$id)));
        }

        return array('form' => $form->createView(),
                    'report'=>$report);
    }

    /**
     * @Route("/admin/store-report", name="admin_store_report", options={"expose"=true})
     * @Template()
     */
    public function storeReportAction(Request $request)
    {
        $formReport = $request->request->get('report');
        $title = $formReport['title'];
        $token = $this->getToken();
        $report = new Report();
        $report->setTitle($title);
        $report->setUsername($this->getUsername($token));
        $em = $this->getDoctrine()->getManager();
        $em->persist($report);
        $em->flush();

        return $this->redirect($this->generateUrl('admin_report',array('id'=>$report->getId())));
    }

   /**
     * @Route("/admin/reports", name="admin_reports")
     * @Template()
     */
    public function reportsAction()
    {
        $token = $this->getToken();
        $username = $this->getUsername($token);
        $reportRepository = $this->getDoctrine()->getManager()->getRepository('SocialyticsBundle:Report');

        $reportsResult = $reportRepository->findBy(array('username'=>$username));

        return array( 'reports' => $reportsResult );

    }

    private function getUsername($token)
    {
        return $token->getUser()->getUsername();
    }

    private function getToken()
    {
        return $this->get('security.token_storage')->getToken();
    }

    private function getResourceOwnerName($token)
    {
        return $token->getResourceOwnerName();
    }
}


text:
package gov.texas.tpwd.mobileranger;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class AutoCompleteManager {

    private static final String TABLE_TEXT = "text";
    private static final String COL_ID = "_id";
    private static final String COL_TYPE = "type";
    private static final String COL_VALUE = "value";
    private static final String COL_CREATE_DATE = "create_date";
    private static final String COL_UPDATE_DATE = "update_date";
    private String[] COLS = new String[]{COL_ID, COL_TYPE, COL_VALUE, COL_CREATE_DATE, COL_UPDATE_DATE};

    private Context context;
    private MySQLiteOpenHelper helper;

    public AutoCompleteManager(Context context) {
        this.context = context;
        this.helper = new MySQLiteOpenHelper();
    }

    public void createOrUpdateAsync(String type, String value) {
        new CreateOrUpdateTask(type, value).execute();
    }

    public void createOrUpdate(String type, String value) {
        SQLiteDatabase db = helper.getWritableDatabase();
        try {
            ContentValues cv = new ContentValues(4);
            cv.put(COL_TYPE, type);
            cv.put(COL_VALUE, value);
            cv.put(COL_UPDATE_DATE, System.currentTimeMillis());
            db.beginTransaction();
            int rows = db.update(TABLE_TEXT, cv, "type=? AND value=?", new String[]{type, value});
            if (rows == 0) {
                cv.put(COL_CREATE_DATE, System.currentTimeMillis());
                long id = db.insert(TABLE_TEXT, null, cv);
                Log.d("####", "insert " + id);
            } else {
                Log.d("####", "updated " + rows);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public Cursor getValuesCursor(String type, String filter) {
        SQLiteDatabase db = helper.getWritableDatabase();
        Log.d("####", "cursor " + filter);
        if (TextUtils.isEmpty(filter)) {
            return db.query(TABLE_TEXT, new String[]{COL_ID, COL_VALUE}, "type=?", new String[]{type}, null, null, "update_date DESC");
        } else {
            return db.query(TABLE_TEXT, new String[]{COL_ID, COL_VALUE}, "type=? AND value LIKE ?", new String[]{type, "%" + filter + "%"}, null, null, "update_date DESC");
        }
    }

    private class CreateOrUpdateTask extends AsyncTask<Void, Void, Void> {
        private String type;
        private String value;

        public CreateOrUpdateTask(String type, String value) {
            this.type = type;
            this.value = value;
        }

        @Override
        protected Void doInBackground(Void... params) {
            createOrUpdate(type, value);
            return null;
        }
    }

    private class MySQLiteOpenHelper extends SQLiteOpenHelper {
        private static final String NAME = "autocomplete.db";
        private static final int VERSION = 1;

        public MySQLiteOpenHelper() {
            super(context, NAME, null, VERSION, new MyDatabaseErrorHandler());
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            onUpgrade(db, 0, VERSION);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("CREATE TABLE text (_id INTEGER PRIMARY KEY, type TEXT, value TEXT, create_date INTEGER, update_date INTEGER);");
        }
    }

    private class MyDatabaseErrorHandler implements DatabaseErrorHandler {

        @Override
        public void onCorruption(SQLiteDatabase dbObj) {
            Toast.makeText(context, "Error: Database Corrupt.", Toast.LENGTH_LONG).show();
        }
    }
}


text:
DTInstances

    A DataTable directive instance is created each time a DataTable is rendered.

        Helper/Wrapper
        API
        Description

        DTInstance
        reloadData(callback, resetPaging)

                Reload the data of the DataTable.

                 This API is only available for the Ajax Renderer and Promise Renderer!

<button ng-click="showCase.reloadData()">
    Reload data
</button>

angular.module('myModule', ['datatables']).controller('MyCtrl', MyCtrl);
function MyCtrl(DTOptionsBuilder, DTColumnBuilder) {
    var vm = this;
    vm.dtOptions = DTOptionsBuilder.fromSource('...');
    vm.dtColumns = [...]
    vm.dtInstance = {};
    vm.reloadData = reloadData;

    function reloadData () {
        vm.dtInstance.reloadData();
    });
}

        DTInstance

            changeData(data)

                Depending of the using renderer, you will need to provide:

a string or an object in the parameter when using the Ajax renderer.

a promise or a function that returns a promise in the parameter when using the Promise renderer

                Change the data of the DataTable.

                 This API is only available for the Ajax Renderer and Promise Renderer!

<button ng-click="showCase.changeData()">
    Change data
</button>

angular.module('myModule', ['datatables']).controller('MyCtrl', MyCtrl);
function MyCtrl(DTOptionsBuilder, DTColumnBuilder) {
    var vm = this;
    vm.dtOptions = DTOptionsBuilder.fromSource('...');
    vm.dtColumns = [...]
    vm.dtInstance = {};
    vm.changeData = changeData;

    function changeData () {
        // For Ajax renderers
        vm.dtInstance.changeData('data.json');
        // For Promise renderers
        vm.dtInstance.changeData(function() {
            return $resource('data.json').query().$promise;
        });
    });
}

        DTInstance

            rerender()

                This method will call the renderer to re-render the table again

                 This is not the same as DataTable's draw(); API.
                It will completely remove the table, then it will re-render the table, resending the request to the server if necessarily.

<button ng-click="showCase.rerender()">
    Rerender
</button>

angular.module('myModule', ['datatables']).controller('MyCtrl', MyCtrl);
function MyCtrl(DTOptionsBuilder, DTColumnBuilder) {
    var vm = this;
    vm.dtOptions = DTOptionsBuilder.fromSource('...');
    vm.dtColumns = [...]
    vm.dtInstance = {};
    vm.rerender = rerender;

    function rerender () {
        vm.dtInstance.rerender();
    });
}


text:
angular.module("template/accordion/accordion-group.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/accordion/accordion-group.html",
    "
" +
    "
{{heading}}
" +
    "
" +
    "

" +
    "
");
}]);

angular.module("template/accordion/accordion.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/accordion/accordion.html",
    "

");
}]);

angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/alert/alert.html",
    "
" +
    "    <button type='button' class='close' ng-click='close()'>×</button>" +
    "

" +
    "
");
}]);

angular.module("template/carousel/carousel.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/carousel/carousel.html",
    "
" +
    "

" +
    "    ‹" +
    "    ›" +
    "
" +
    "");
}]);

angular.module("template/carousel/slide.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/carousel/slide.html",
    "

" +
    "");
}]);

angular.module("template/dialog/message.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/dialog/message.html",
    "
" +
    "
{{ title }}
" +
    "
" +
    "
" +
    "
{{ message }}
" +
    "
" +
    "
" +
    "   <button ng-repeat=\"btn in buttons\" ng-click=\"close(btn.result)\" class=btn ng-class=\"btn.cssClass\">{{ btn.label }}</button>" +
    "
" +
    "");
}]);

angular.module("template/pagination/pagination.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/pagination/pagination.html",
    "

" +
    "
{{previousText || 'Previous'}}
" +
    "
{{page}}
" +
    "
{{nextText || 'Next'}}
" +
    "
" +
    "
" +
    "");
}]);

angular.module("template/popover/popover.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/popover/popover.html",
    "
" +
    "

" +
    "" +
    "
" +
    "

" +
    "

" +
    "
" +
    "
" +
    "");
}]);

angular.module("template/tabs/pane.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/tabs/pane.html",
    "

" +
    "");
}]);

angular.module("template/tabs/tabs.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/tabs/tabs.html",
    "
" +
    "
" +
    "
" +
    "      {{pane.heading}}" +
    "
" +
    "
" +
    "

" +
    "
" +
    "");
}]);

angular.module("template/tooltip/tooltip-popup.html", []).run(["$templateCache", function($templateCache){
  $templateCache.put("template/tooltip/tooltip-popup.html",
    "
" +
    "

" +
    "

" +
    "
" +
    "");
}]);


text:
#ifndef SIDECAR_ZEROCONF_DOXYGEN_H // -*- C++ -*-
#define SIDECAR_ZEROCONF_DOXYGEN_H

/** \page zeroconf Zeroconf Overview

    Although the SideCar system relies on an XML configuration file to define processing stream and startup
    values for algorithms, socket connectivity information such as port and host name for data publishers and
    subscribers is not stored there. Instead, data publishers and subscribers use the Zero Configuration Networking (Zeroconf) API and a Multicast DNS (mDNS) server running on each of the hosts in the
    SideCar LAN to share connection information. The discovery process is very simple. First, a data publisher
    publishes information to the Zeroconfig system using a SideCar::Zeroconf::Publisher instance. Published
    information includes the host name and port where the service is running. For a data subscriber, it uses a
    SideCar::Zeroconf::Browser instance to locate data publishers of a particular data type. When it finds one,
    it asks the mDNS server to resolve the publisher's connection information, and when the subscriber receives
    the response, it then initiates a connection to the data publisher.

    GUI applications use the same mechanism to discover data publishers, but they can offer the user with a list
    of active publishers, and the list is dynamically updated as publishers become available or disappear. The
    SideCar::GUI::PPIDisplay and SideCar::GUI::AScope applications both rely on this Zeroconf service discovery
    to offer their users valid, up-to-date channel connection options.
*/

namespace SideCar {

/** Namespace for entities that interface with Zeroconf library.
 */
namespace Zeroconf {
}

} // end namespace SideCar

#endif


text:
local DotProduct, parent = torch.class('nn.DotProduct', 'nn.Module')

function DotProduct:__init()
   parent.__init(self)
   self.gradInput = {torch.Tensor(), torch.Tensor()}
end

function DotProduct:updateOutput(input)
   local input1, input2 = input[1], input[2]
   if input1:dim() == 1 then
      -- convert non batch input to batch input
      input1 = input1:view(1,-1)
      input2 = input2:view(1,-1)
   end
   if not self.buffer then
      self.buffer = input1.new()
   end
   self.buffer:cmul(input1, input2)
   self.output:sum(self.buffer, 2)
   self.output:resize(input1:size(1))
   return self.output
end

function DotProduct:updateGradInput(input, gradOutput)
   local v1 = input[1]
   local v2 = input[2]
   local not_batch = false

   if #self.gradInput ~= 2 then
     self.gradInput[1] = self.gradInput[1] or input[1].new()
     self.gradInput[2] = self.gradInput[2] or input[2].new()
   end

   if v1:dim() == 1 then
      v1 = v1:view(1,-1)
      v2 = v2:view(1,-1)
      not_batch = true
   end

   local gw1 = self.gradInput[1]
   local gw2 = self.gradInput[2]
   gw1:resizeAs(v1):copy(v2)
   gw2:resizeAs(v2):copy(v1)

   local go = gradOutput:view(-1,1):expandAs(v1)
   gw1:cmul(go)
   gw2:cmul(go)

   if not_batch then
      -- unbatch gradInput
      self.gradInput[1]:set(gw1:select(1,1))
      self.gradInput[2]:set(gw2:select(1,1))
   end

   return self.gradInput
end

function DotProduct:clearState()
   if self.buffer then self.buffer:set() end
   return parent.clearState(self)
end


text:
- [*Class*](#class)
  - [Definisi *class*](#definisi-class)
  - [Mendefinisikan suatu *class*](#mendefinisikan-suatu-class)
  - [Fungsi *constructor*](#fungsi-constructor)
  - [Atribut](#atribut)
    - [*Data attributes*](#data-attributes)
    - [*Methods*](#methods)
    - [*Static attributes*](#static-attributes)
  - [Objek *(instance)*](#objek-instance)
  - [Beda *class* dengan objek *(instance)*](#beda-class-dengan-objek-instance)
- [Pemrograman Berorientasi Objek (OOP)](#pemrograman-berorientasi-objek-oop)
  - [Definisi OOP](#definisi-oop)
  - [OOP dan *Software Engineering*](#oop-dan-software-engineering)

## *Class*

### Definisi *class*

***Class*** adalah sebuah prototipe yang merupakan dasar untuk pembuatan objek.
Prototipe ini mendefinisikan ciri-ciri objek, yang kemudian dapat digunakan ke
depannya.

### Mendefinisikan suatu *class*

Kita bisa **mendefinisikan sebuah *class*** baru dengan menulis seperti
berikut:

```python
class ClassName:
    # Isi dari class
```

Dalam Python, perlu dicatat bahwa **nama *class* sebaiknya ditulis dalam bentuk
CapWords (varian dari [camel case][camel case]), yang berarti huruf kapital
digunakan untuk setiap awal kata**.

### Fungsi *constructor*

Sebuah fungsi yang dipanggil untuk membuat suatu objek *(instance)* dari sebuah
*class* disebut ***constructor***. Dalam Python, *constructor* memiliki nama
tersendiri yaitu `__init__`. Kita dapat mendefinisikan fungsi `__init__` dalam
sebuah *class*, yang merupakan fungsi paling pertama yang dipanggil ketika
membuat suatu objek *(instance)* dari *class* tersebut. Jika tidak
didefinisikan, maka fungsi `__init__` secara *default* tidak akan melakukan
apa-apa selain membuat objek baru.

Kita bisa mendefinisikan fungsi `__init__` seperti berikut.

```python
class ClassName:
    def __init__(self):
        # Hal-hal yang ingin dilakukan ketika objek dibuat
```

### Atribut

**Atribut** dari suatu *class* terdiri dari ***data attributes*** dan
***methods***.

#### *Data attributes*

***Data attribute*** adalah atribut berupa variabel yang khusus terhadap sebuah
objek. Perhatikan contoh pembuatan *data attribute* pada *class* `Mobil`
berikut.

```python
class Mobil:
    def __init__(self):
        self.merek = 'BMW'
        self.pemilik = 'Paman'
        self.menyala = False
```

Pada contoh di atas, kita membuat 3 variabel yang bernama `merek`, `pemilik`,
dan `menyala`. Apabila kita ingin supaya sebuah objek `Mobil` langsung memiliki
ketiga ciri-ciri tersebut, kita masukkan hal tersebut ke dalam fungsi
`__init__`.

Perhatikan bahwa untuk setiap penulisan variabel, kita menulis `self.` terlebih
dahulu. Ini menandakan bahwa variabel tersebut merupakan bagian dari objek
`Mobil`, bukan variabel dalam fungsi `__init__`.

Tentunya, kita juga dapat membuat *class* `Mobil` sedemikian hingga beberapa
variabel ditentukan ketika membuat objek. Perhatikan modifikasi contoh pada
*class* `Mobil` berikut:

```python
class Mobil:
    def __init__(self, merek, pemilik):
        self.merek = merek
        self.pemilik = pemilik
        self.menyala = False
```

Pada modifikasi di atas, kita membuat *class* `Mobil` sedemikian hingga
variabel `merek` dan `pemilik` bebas ditentukan ketika objek dibuat, dan objek
`Mobil` dipastikan tidak `menyala` pada awal pembuatan.

#### *Methods*

***Method*** adalah atribut yang berupa fungsi. Perhatikan contoh *method*
`klakson()` pada class `Mobil` berikut.

```python
class Mobil:
    def klakson(self):
        print('TIN TIN')
```

Pada contoh di atas, kita membuat fungsi `klakson()` yang hanya akan melakukan
`print('TIN TIN')`. Perhatikan bahwa setiap *method* harus memiliki suatu
parameter sebagai parameter pertama, biasanya `self`. Parameter ini merupakan
*reference* ke objek yang memanggil *method* tersebut.
Perhatikan contoh penggunaan `self` pada *class* `Mobil` berikut.

```python
class Mobil:
    def __init__(self, merek, pemilik):
        self.merek = merek
        self.pemilik = pemilik
        self.menyala = False

    def ganti_pemilik(self, pemilik_baru):
        self.pemilik = pemilik_baru
```

Pada contoh di atas, kita membuat sebuah fungsi `ganti_pemilik` yang akan
mengubah *data attribute* `pemilik` dari objeknya.

#### *Static attributes*

Atribut tidak harus terikat pada suatu objek *(instance)*. Ada kalanya kita
tidak memerlukan suatu *instance* untuk suatu atribut, baik *data attribute*
maupun *method*, tetapi atribut tersebut masih berkaitan dengan *class*-nya.
Perhatikan contoh berikut.

```python
class Mobil:
    BANYAK_RODA = 4

    def __init__(self, merek, pemilik):
        self.merek = merek
        self.pemilik = pemilik
        self.menyala = False

    def ganti_pemilik(self, pemilik_baru):
        self.pemilik = pemilik_baru

print("Sebuah mobil memiliki", Mobil.BANYAK_RODA, "roda")
```

Pada contoh di atas, kita dapat mengakses atribut `BANYAK_RODA` tanpa perlu
membuat *instance* dari `Mobil`. Kita dapat mengakses atribut `BANYAK_RODA`
dengan `Mobil.BANYAK_RODA`. Dalam kasus ini, atribut `BANYAK_RODA` bersifat
*static*. ***Static attribute*** pada suatu *class* dimiliki oleh *class*
tersebut, bukan *instance*-nya.

Untuk membuat atribut yang *static*, cukup deklarasikan di dalam pendefinisian
*class*. Untuk konstanta, biasakan untuk menggunakan huruf kapital dengan
*underscore* sebagai pemisah kata.

Untuk *static method*, ada cara tersendiri yang digunakan untuk
mendefinisikannya. Biasanya, *function decorator* seperti
[`@staticmethod`][@staticmethod docs] atau [`@classmethod`][@classmethod docs]
digunakan untuk mendefinisikan *static method*. Namun, kalian bisa
mempelajarinya sendiri karena hal tersebut tidak dibahas di dalam mata kuliah
ini.

### Objek *(instance)*

Sebuah **objek** atau ***instance*** adalah perwujudan dari suatu *class*.
Setiap objek mempunyai nilai masing-masing untuk *data attributes*-nya. Untuk
membuat suatu objek dari suatu *class*, kita dapat memanggil *constructor*
pada *class*-nya. Untuk memanggil *constructor*, kita tidak perlu memanggil
fungsi `__init__` secara eksplisit, tetapi kita bisa memanggilnya dengan nama
dari *class* itu sendiri.
Perhatikan contoh *class* `Mobil` dan cara bekerja dengan objeknya pada kode
berikut.

```python
class Mobil:
    def __init__(self, merek, pemilik):
        self.merek = merek
        self.pemilik = pemilik
        self.menyala = False

    def klakson(self):
        print('TIN TIN')

    def ganti_pemilik(self, pemilik_baru):
        self.pemilik = pemilik_baru

    def nyalakan(self):
        self.menyala = True
        print("Mobil menyala, BRUM BRUM")

    def matikan(self):
        self.menyala = False
        print("Mobil dimatikan")

    def is_mahal(self):
        return self.merek == 'BMW'

sebuah_mobil = Mobil('BMW', 'Paman')
sebuah_mobil.ganti_pemilik('Saya sendiri')
sebuah_mobil.nyalakan()
sebuah_mobil.klakson()
sebuah_mobil.matikan()

if sebuah_mobil.is_mahal():
    print("WoOoW, mobil ini mahal!")
else:
    print("Hah, mobil pecundang.")

print("Mobil", sebuah_mobil.merek, "milik", sebuah_mobil.pemilik)
```

Coba jalankan kode di atas dan lihat keluarannya.

### Beda *class* dengan objek *(instance)*

Perhatikan analogi berikut.

> Beda *class* dengan objek *(instance)* kurang lebih sama dengan bedanya
> cetakan kue dengan kue yang dibuat.

*Class* bertindak sebagai ***template*** yang dipakai saat membuat *instance*
yang konkret. Struktur dari suatu *instance* pada mulanya akan sama dengan
struktur yang ditentukan oleh *class* yang bersangkutan. Biasanya, sebuah
*instance* disebut juga dengan objek.

Namun, dalam Python, **SEMUA** hal adalah objek, termasuk tipe data
(*integer*, *boolean*, dsb.), fungsi, **bahkan *class* itu sendiri**, dan
*instance* dari semua hal tersebut. Hal ini **tidak** seperti bahasa
pemrograman lain pada umumnya.

## Pemrograman Berorientasi Objek (OOP)

### Definisi OOP

**Pemrograman Berorientasi Objek** atau ***Object-Oriented Programming (OOP)***
adalah paradigma pemrograman yang memandang setiap program sebagai kumpulan
objek serta interaksi di antara mereka. Program dalam OOP tidak dipandang hanya
sebagai kumpulan perintah.

Dalam OOP, setiap objek merespon "pesan" yang dikirim ke objek tersebut.
Interaksi antar objek melalui pesan antar objek menggambarkan apa yang
dikerjakan di dalam program.

Dalam Python, tipe data dari sebuah objek atau nilai bisa dipandang sebagai
*class*, dan nilai tersebut merupakan *instance* dari *class*-nya, contohnya:
`list`, `dict`, `str`, dan sebagainya. Setiap *class* tersebut digunakan untuk
merepresentasikan data dengan sifat yang berbeda, dan akan merespon pesan yang
berbeda-beda untuk melakukan manipulasi data.

### OOP dan *Software Engineering*

***Software engineering*** adalah disiplin ilmu yang mempelajari cara merancang
dan mengelola kode program (yang membentuk perangkat lunak) demi menjamin
penggunaannya dalam jangka panjang.

Dalam *software engineering*, kita akan sering melakukan ***refactoring***.
*Refactoring* merupakan proses:

- mengambil kode program yang sudah ada, lalu memodifikasinya.
- membuat kode program secara keseluruhan menjadi lebih sederhana dan mudah
  dipahami.
- tidak mengubah fungsionalitas (hal sesungguhnya yang dikerjakan program),
  dan hanya mengatur wujudnya.

Dalam melakukan *refactoring* pada program yang menerapkan paradigma OOP,
biasanya diterapkan prinsip-prinsip berikut:

- ***encapsulation***: menyembunyikan detail implementasi demi membuat program
  lebih jelas dan memudahkan modifikasi di masa datang.
- ***modularity***: membuat objek secara utuh berdiri sendiri sehingga bisa
  digunakan kembali. Contoh: *module* `math`
- ***inheritance***: membuat objek baru dengan mewarisi karakteristik objek
  yang sudah ada.
- ***polymorphism***: memungkinkan suatu pesan dikirim ke sembarang objek dan
  menjadikan respons atas pesan tersebtu disesuaikan dengan tipe objek yang
  dikirimi.

Kalian akan mempelajari lebih lanjut mengenai prinsip-prinsip di atas dalam
mata kuliah **Dasar-Dasar Pemrograman 2**.

---

Diadaptasi dari:

- `Lab 8 Senin.pdf` buatan **ALD**, **DHA**, **GIL**, dan **DST**
- `ddp1-17gasal-11.pdf` buatan **Adila Alfa Krisnadhi, Ph.D.**

dengan beberapa perubahan.

[camel case]: https://en.wikipedia.org/wiki/Camel_case

[@staticmethod docs]: https://docs.python.org/3/library/functions.html#staticmethod

[@classmethod docs]: https://docs.python.org/3/library/functions.html#classmethod


text:
"""
Django settings for sbzwebsite project.
"""

import os

from django.utils.translation import ugettext_lazy as _

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Debug settings
DEBUG = False

# Email
DEFAULT_FROM_EMAIL = 'SBZ <sbz@localhost>'
EMAIL_SUBJECT_PREFIX = '[SBZ] '
SERVER_EMAIL = DEFAULT_FROM_EMAIL

# I18n/L10n
LANGUAGE_CODE = 'nl-nl'
LANGUAGES = [
    ('nl', _('Dutch')),
    ('en', _('English')),
]
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

TIME_ZONE = 'Europe/Amsterdam'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'apps.util',
    'apps.general',
    'apps.multivers',
    'apps.grolsch',
    'apps.mail',
    'apps.flowguard',
    'apps.hygiene',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'settings.wsgi.application'

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
LOGIN_URL = 'admin:login'

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

HORNET_FORBID_REMOVAL = ["supernerd@sbz.utwente.nl"]


text:
@interface TextViewController : UIViewController

@property (nonatomic, copy) NSString *text;

// Invoked on controller's completion. If NULL and is presented - invoking "dismissViewController" automatically
@property (nonatomic) void (^completion)(TextViewController *sender);

@end


text:
using System;
using Newtonsoft.Json;

namespace PcfProvider.ServiceInstance
{
	public class RootObject
	{
		public Metadata Metadata { get; set; }

		[JsonProperty("entity")]
		public PcfServiceInstance ServiceInstance { get; set; }
	}
}


text:
let express = require('express'),
    app = express(),
    defaultPort = 8080,
    PersonRepository = require('./personrepository');

class WebAPI {
    constructor(port) {
        this.port = port || defaultPort;
        this.app = app;
        this.express = express;
        this.webApiRouter = this.express.Router();
        this.personRepository = new PersonRepository()
    }

    configure() {
        // Routing: GET /api/helloworld
        this.webApiRouter.get('/helloworld', (req, res) => {
            res.setHeader('Content-Type', 'application/json');
            res.send({
                message: 'Hello World with Docker & Express',
                querystring: req.query
            })
        });

        this.webApiRouter.get('/person', (req, res) => {
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            res.setHeader('Content-Type', 'application/json');

            this.personRepository.get()
                .then(persons => res.send(persons))
                .catch(err => console.log(err));
        });

        // Routing: GET /api
        this.webApiRouter.get('/', (req, res) => {
            res.setHeader('Content-Type', 'text/plain');
            res.send('WebAPI Router works!');
        })

        // Routing: GET /
        this.app.get('/', (req, res) => {
            res.setHeader('Content-Type', 'text/plain');
            res.send('Express works!')
        })

        this.app.use('/api', this.webApiRouter);
    }

    start() {
        this.app.listen(this.port, () => {
            console.log(`Rest API listening on port ${this.port}!`);
        });
    }
}

module.exports = WebAPI;


text:
define({
  "builder": {
    "initPopup": {
      "title": "Bem-vindo a",
      "startBtn": "Iniciar"
    },
    "addEditPopup": {
      "test": "teste",
      "add": "adicionar",
      "edit": "editar",
      "editTab": "EDITAR SEPARADOR",
      "addTab": "ADICIONAR SEPARADOR",
      "organizeTabs": "ORGANIZAR SEPARADORES",
      "themeColor": "Cor do Tema",
      "location": "Localização",
      "confirmDeletion": "Confirmar a eliminação de "
    },
    "landing": {
      "lblAdd": "Que nome pretende dar à sua Shortlist?",
      "phAdd": "Introduza o seu título...",
      "lblOR": "Ou",
      "lblHelp": "Fazer uma visita guiada"
    },
    "organizePopup": {
      "title": "Organizar",
      "tab": "separador",
      "dragNDrop": "Arraste e solte separadores para organizar a sua história.",
      "lblColTitle": "Título"
    },
    "settingsLayoutOptions": {
      "title": "Ópções de layout",
      "lblDescription": "Descrição"
    },
    "addFeatureBar": {
      "add": "Adicionar",
      "import": "Importar",
      "done": "Terminado",
      "deleteFeature": "Excluir",
      "move": "Mover",
      "locateFeaturesTooltip": "Alguns lugares têm de ser localizados. Clique aqui para visualizá-los"
    },
    "detailPanelBuilder": {
      "changeLocation": "Alterar localização",
      "setLocation": "Definir Localização",
      "cancel": "Cancelar",
      "addImage": "Cliqar, ou arrastar e soltar, para adicionar uma imagem",
      "chooseImage": "SELECIONAR IMAGEM",
      "importImages": "IMPORTAR IMAGENS",
      "import": "IMPORTAR",
      "enterPlaceName": "Introduzir nome do local",
      "enterPlaceDescription": "Introduzir descrição do local",
      "unnamedPlace": "Local sem nome",
      "update": "Atualizar",
      "useLocation": "Utilizar esta localização",
      "selectAll": "Selecionar tudo",
      "imageSizeHelper": "Para melhores resultados, as imagens devem ser menores do que 400 KB. O tamanho & formato recomendado é 1000 x 750 pixeis (rácio 4:3 largura:altura) ou inferior. Imagens maiores podem reduzir o desempenho. Para obter melhores desempenhos, utilize imagens JPG comprimidas com qualidade de imagem de 80%.",
      "imageSizeHelperUpdated": "A ligação de imagem tem de começar com HTTPS.

Para melhor desempenho, o tamanho das imagens deve ser inferior a 400 KB. Para reduzir o tamanho dos ficheiros, utilize o formato JPG, guardado com 80% de qualidade de imagem. Caso a sua imagem tenha ainda mais do que 400 KB, redimensioná-la poderá reduzir ainda mais o respetivo tamanho de ficheiro: 1000 pixeis de largura x 750 pixeis de altura ( rácio largura:altura de 4:3) é a dimensão recomendada.

Caso uma imagem ligada fique lenta ou não se encontre disponível através de HTTPS, carregue-a para a sua história para obter melhores resultados.",
      "thumbnailLink": "Ligação a imagem miniatura",
      "thumbnailHelp": "A ligação da imagem de miniatura tem de começar com HTTPS.

O tamanho e formato recomendado para imagens miniatura é 280 x 210 pixeis (rácio 4:3 largura:altura). Imagens miniatura maiores podem reduzir o desempenho. Imagens miniatura com proporção de aspeto 4:3 encaixam nos respetivos mosaicos sem ser necessário recortar."
    },
    "settings": {
      "numberedPlaces": "Exibir locais com números",
      "extentSensitive": "Apenas exibir locais em separadores que se encontrem visíveis no mapa (visualizador apenas)",
      "extentSensitiveTooltip": "Esta opção apenas se aplica quando a sua Shortlist é visualizada. No Shortlist Builder, os separadores exibem sempre todos os locais, mesmo aqueles que não se encontram visíveis no mapa. Desmarque esta opção caso pretenda que os separadores exibam sempre todos os locais quando a sua Shortlist é visualizada.",
      "locateButton": "Botão Localizar",
      "locateButtonTooltip": "Permita que os seus leitores visualizem a respetiva posição atual no mapa.  Esta funcionalidade é suportada na maioria dos dispositivos e navegadores, mas o botão apenas é apresentado se partilhar a sua história como ligação HTTPS e a história não se encontrar incorporada.",
      "geocoder": "Localizador (Finder) de Endereços, Locais e Elementos",
      "bookmarks": "Marcadores",
      "bookmarksMenuName": "Nome do Menu",
      "defaultMapLocation": "Localização de mapa predefinida",
      "auto": "Auto",
      "autoTooltip": "A localização é gerida automaticamente para que todos os locais sejam visíveis",
      "custom": "Personalizar",
      "customTooltip": "Defina a localização utilizando o botão que aparece nos controlos de zoom do mapa",
      "mapLocationTooltip": "A localização que os utilizadores visualizam quando abrem a sua Shortlist",
      "bookmarksHelp": "Para ativar marcadores, feche o Shortlist Builder e depois abra o mapa web utilizado nesta Shortlist (através de Os Meus Conteúdos ou As Minhas Histórias ArcGIS) e adicione marcadores ao mesmo utilizando o ArcGIS Map Viewer.",
      "generalOptions": "Opções gerais",
      "mapOptions": "Opções de mapa",
      "changeBasemap": "Mudar mapa base",
      "saveHomeLocation": "Guardar localização inicial",
      "choose": "Escolher",
      "headerColor": "Cor do Cabeçalho"
    },
    "help": {
      "title": "AJUDA",
      "shortlistHelp1": "Bem Vindo à Story Map Shortlist Esta aplicação permite-lhe apresentar locais de interesse organizados em separadores, tornando divertida e simples a experiência de explorar aquilo que se encontra disponível numa área. Pode criar os seus locais de modo interativo com este Builder.",
      "shortlistHelp2": "Pode ainda criar uma Shortlist a partir de um mapa web ArcGIS existente, incluindo a opção para utilizar dados de pontos existentes nos mapas, como locais. Pode importar esses dados de pontos para o Shortlist Builder para posterior edição ou, caso os seus locais utilizem o esquema de dados Shortlist, derive a sua Shortlist diretamente desses dados 'tal como se encontra'. Consulte estas FAQ para obter mais informações sobre este assunto.",
      "shortlistHelp3": "Para criar uma Shortlist a partir de um mapa web,",
      "shortlistHelp4": "abra o mapa web, crie uma aplicação web a partir do mesmo e selecione Story Maps Shortlist na galeria de aplicações. Caso o seu mapa web contenha quaisquer camadas de pontos, o Shortlist Builder irá instá-lo a selecionar as camadas que pretende utilizar como locais. Caso tenha criado uma Shortlist utilizando a versão original, não alojada, da aplicação, pode migrar a sua Shortlist para esta versão alojada da aplicação seguindo os mesmos passos.",
      "shortlistHelp5": "Para obter mais informações",
      "shortlistHelp6": "Visite a secção Shortlist do site web Esri Story Maps",
      "shortlistFAQ": "FAQ sobre Shortlists",
      "shortlistBetaFeedback": "Feedback beta",
      "shortlistBetaFeedback2": "Gostaríamos de ter notícias suas! Informe-nos acerca de quaisquer problemas e de novas funcionalidades de necessite visitando o",
      "geonetForum": "fórum Story Maps na GeoNet"
    },
    "migration": {
      "migrationPattern": {
        "welcome": "Bem-vindo ao Shortlist Builder",
        "importQuestion": "O seu mapa web contém dados de ponto.  Pretende utilizar esses pontos como locais na sua Shortlist?",
        "importExplainYes": "Terá a possibilidade de editar, gerir e adicionar aos seus locais no Shortlist Builder.  É automaticamente criada uma cópia do seu mapa web, portanto os seus dados iniciais não são modificados.",
        "importExplainNo": "Os seus pontos serão exibidos no mapa da sua Shortlist, mas não serão utilizados como locais.  Ao invés, irá adicionar locais à sua Shortlist no Builder.",
        "no": "Não",
        "importOption": "Sim, importar",
        "asIsOption": "Sim, utilizá-los tal como se encontram (as-is)",
        "asIsText": "Continuará a editar e gerir os seus locais no seu mapa web, não no Shortlist Builder.  As atualizações que aplicar a esses dados refletir-se-ão automaticamente na sua Shortlist.  Esta opção requer que os seus dados utilizem este modelo.",
        "badData": "A camada de pontos que contém os seus locais não utiliza o modelo de dados necessário. Por favor, reveja os requisitos do modelo.",
        "downloadTemplate": "Transferir modelo",
        "selectPtData": "SELECIONE OS SEUS DADOS DE PONTOS",
        "multipleThemes": "A SUA CAMADA CONTÉM VÁRIOS TEMAS",
        "chooseFields": "SELECIONE OS CAMPOS A UTILIZAR PELA SHORTLIST"
      },
      "fieldPicker": {
        "nameField": "Campo que contém o nome de cada local: ",
        "descriptionField": "Campo(s) a exibir na descrição de cada local e da respetiva ordem: ",
        "urlField": "Campo que contém o URL que leva a 'Mais info' sobre cada local (opcional): ",
        "none": "nenhum",
        "imageFields": "Campos que contêm URl para imagens para cada local (opciona): ",
        "mainImageField": "Imagem principal: ",
        "thumbImageField": "Miniatura: ",
        "noImageFields": "Deixe estas definidas para nenhum, caso pretenda adicionar imagens aos seus locais no Builder.",
        "tabField": "Caso tenha um nome de campo que divide os locais na sua camada em diferentes temas, selecione o nome de campo apropriado acima."
      },
      "layerPicker": {
        "pointLayers": "Selecione a(s) camada(s) de pontos no seu mapa que pretende utilizar como locais. ",
        "layerInfo": "Caso selecione mais do que uma camada, todas têm de ter o mesmo conjunto de campos.  Cada camada que selecionar tornar-se-á num separador na sua shortlist."
      }
    }
  }
});


text:
namespace Google.Cloud.PubSub.V1.Snippets
{
    // [START pubsub_v1_generated_PublisherServiceApi_Publish_async_flattened]
    using Google.Cloud.PubSub.V1;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    public sealed partial class GeneratedPublisherServiceApiClientSnippets
    {
        /// <summary>Snippet for PublishAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task PublishAsync()
        {
            // Create client
            PublisherServiceApiClient publisherServiceApiClient = await PublisherServiceApiClient.CreateAsync();
            // Initialize request argument(s)
            string topic = "projects/[PROJECT]/topics/[TOPIC]";
            IEnumerable<PubsubMessage> messages = new PubsubMessage[]
            {
                new PubsubMessage(),
            };
            // Make the request
            PublishResponse response = await publisherServiceApiClient.PublishAsync(topic, messages);
        }
    }
    // [END pubsub_v1_generated_PublisherServiceApi_Publish_async_flattened]
}


text:
cd /mnt/phor/storm8

#touch missions.bash
#./missions.bash

touch realestate.bash
./realestate.bash

#touch attack.bash
#./attack.bash

touch friends.bash
./friends.bash


text:
<?php

namespace Tee\TeeworldsBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;

/**
 * WeaponRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class WeaponRepository extends EntityRepository
{
	public function getWeaponByGame( $game )
	{
		$qb = $this->_em->createQueryBuilder();
		$qb->select("w");
		$qb->from("TeeworldsBundle:Weapon", "w");
		$qb->where( "w.game = :game ");
		$qb->setParameter( "game", $game);

		return $qb->getQuery()->getResult();
	}

	public function getTotalWeapon()
	{
		$qb = $this->_em->createQueryBuilder();
		$qb->select("w.name as name, SUM( w.frag ) as kill ");
		$qb->from("TeeworldsBundle:Weapon", "w");
		$qb->groupBy( "w.name");
		$qb->orderBy( "kill", "DESC");

		return $qb->getQuery()->getResult( Query::HYDRATE_ARRAY );
	}
}


text:
<?php

require_once __DIR__.'/../lib/Html2Text/Html2Text.php';

class LinkTest extends PHPUnit_Framework_TestCase
{
    public $input =<<< EOT
Link text
EOT;

    public function testDoLinksAfter()
    {
        $expected_output =<<<EOT
Link text [1]

Links:
------
[1] http://example.com

EOT;

        $html2text = new \Html2Text\Html2Text($this->input, false, array('do_links' => 'table'));
        $output = $html2text->get_text();

        $this->assertEquals($expected_output, $output);
    }

    public function testDoLinksInline()
    {
        $expected_output =<<<EOT
Link text [http://example.com]
EOT;

        $html2text = new \Html2Text\Html2Text($this->input, false, array('do_links' => 'inline'));
        $output = $html2text->get_text();

        $this->assertEquals($expected_output, $output);
    }

    public function testDoLinksNone()
    {
        $expected_output =<<<EOT
Link text
EOT;

        $html2text = new \Html2Text\Html2Text($this->input, false, array('do_links' => 'none'));
        $output = $html2text->get_text();

        $this->assertEquals($output, $expected_output);
    }

    public function testDoLinksNextline()
    {
        $expected_output =<<<EOT
Link text
[http://example.com]
EOT;

        $html2text = new \Html2Text\Html2Text($this->input, false, array('do_links' => 'nextline'));
        $output = $html2text->get_text();

        $this->assertEquals($expected_output, $output);
    }
}


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';
import * as slash from 'slash';

import { APP_BASE, APP_DEST, APP_SRC, DEPENDENCIES } from '../../config';

import { templateLocals } from '../../utils';

const plugins = <any>gulpLoadPlugins();

/**
 * Executes the build process, injecting the shims and libs into the `index.hml` for the development environment.
 */
export = () => {
  return gulp.src(join(APP_SRC, 'index.html'))
    .pipe(inject('shims'))
    .pipe(inject('libs'))
    .pipe(inject('css'))
    .pipe(inject())
    .pipe(plugins.template(templateLocals()))
    .pipe(gulp.dest(APP_DEST));
};

/**
 * Injects the file with the given name.
 * @param {string} name - The file to be injected.
 */
function inject(name?: string) {
  return plugins.inject(gulp.src(getInjectablesDependenciesRef(name), { read: false }), {
    name,
    transform: transformPath()
  });
}

/**
 * Returns the injectable dependency, mapping its filename to its path.
 * @param {string} name - The dependency to be mapped.
 */
function getInjectablesDependenciesRef(name?: string) {
  return DEPENDENCIES
    .filter(dep => dep['inject'] && dep['inject'] === (name || true))
    .map(mapPath);
}

/**
 * Maps the path of the given dependency to its path according to the applications environment.
 * @param {any} dep - The dependency to be mapped.
 */
function mapPath(dep: any) {
  let envPath = dep.src;
  if (envPath.startsWith(APP_SRC) && !envPath.endsWith('.scss')) {
    envPath = join(APP_DEST, envPath.replace(APP_SRC, ''));
  } else if (envPath.startsWith(APP_SRC) && envPath.endsWith('.scss')) {
    envPath = envPath.replace(APP_SRC, APP_DEST).replace('.scss', '.css');
  }
  return envPath;
}

/**
 * Transform the path of a dependency to its location within the `dist` directory according to the applications
 * environment.
 */
function transformPath() {
  return function (filepath: string) {
    arguments[0] = join(APP_BASE, filepath) + `?${Date.now()}`;
    return slash(plugins.inject.transform.apply(plugins.inject.transform, arguments));
  };
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.pig.backend.hadoop.executionengine.physicalLayer (Pig 0.8.0-CDH3B4-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2011-02-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

org.apache.pig.backend.hadoop.executionengine.physicalLayer

Interfaces

PigLogger

PigProgressable

Classes

LogToPhyTranslationVisitor

PhysicalOperator

POPrinter

POStatus

Result

Exceptions

LogicalToPhysicalTranslatorException