text:
package de.tum.in.www1.exerciseapp.service;

import de.tum.in.www1.exerciseapp.domain.*;
import de.tum.in.www1.exerciseapp.domain.util.PatchedIMSPOXRequest;
import de.tum.in.www1.exerciseapp.exception.JiraException;
import de.tum.in.www1.exerciseapp.repository.LtiOutcomeUrlRepository;
import de.tum.in.www1.exerciseapp.repository.LtiUserIdRepository;
import de.tum.in.www1.exerciseapp.repository.ResultRepository;
import de.tum.in.www1.exerciseapp.repository.UserRepository;
import de.tum.in.www1.exerciseapp.security.AuthoritiesConstants;
import de.tum.in.www1.exerciseapp.security.JiraAuthenticationProvider;
import de.tum.in.www1.exerciseapp.security.SecurityUtils;
import de.tum.in.www1.exerciseapp.service.util.RandomUtil;
import de.tum.in.www1.exerciseapp.web.rest.dto.LtiLaunchRequestDTO;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.imsglobal.lti.launch.LtiOauthVerifier;
import org.imsglobal.lti.launch.LtiVerificationException;
import org.imsglobal.lti.launch.LtiVerificationResult;
import org.imsglobal.lti.launch.LtiVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class LtiService {

    private final Logger log = LoggerFactory.getLogger(LtiService.class);

    @Value("${artemis.lti.oauth-key}")
    private String OAUTH_KEY;

    @Value("${artemis.lti.oauth-secret}")
    private String OAUTH_SECRET;

    @Value("${artemis.lti.user-prefix}")
    private String USER_PREFIX = "";

    @Value("${artemis.lti.user-group-name}")
    private String USER_GROUP_NAME = "lti";

    private UserService userService;
    private UserRepository userRepository;
    private LtiOutcomeUrlRepository ltiOutcomeUrlRepository;
    private ResultRepository resultRepository;
    private PasswordEncoder passwordEncoder;
    private Optional<JiraAuthenticationProvider> jiraAuthenticationProvider;
    private LtiUserIdRepository ltiUserIdRepository;
    private HttpServletResponse response;

    public HashMap<String, Pair<LtiLaunchRequestDTO, Exercise>> launchRequestForSession = new HashMap<>();

    public LtiService(UserService userService, UserRepository userRepository, LtiOutcomeUrlRepository ltiOutcomeUrlRepository, ResultRepository resultRepository, PasswordEncoder passwordEncoder, Optional<JiraAuthenticationProvider> jiraAuthenticationProvider, LtiUserIdRepository ltiUserIdRepository, HttpServletResponse response) {
        this.userService = userService;
        this.userRepository = userRepository;
        this.ltiOutcomeUrlRepository = ltiOutcomeUrlRepository;
        this.resultRepository = resultRepository;
        this.passwordEncoder = passwordEncoder;
        this.jiraAuthenticationProvider = jiraAuthenticationProvider;
        this.ltiUserIdRepository = ltiUserIdRepository;
        this.response = response;
    }

    /**
     * Handles LTI launch requests.
     *
     * @param launchRequest The launch request, sent by LTI consumer
     * @param exercise      Exercise to launch
     * @throws JiraException
     * @throws AuthenticationException
     */
    public void handleLaunchRequest(LtiLaunchRequestDTO launchRequest, Exercise exercise) throws JiraException, AuthenticationException {

        // Authenticate the the LTI user
        Optional<Authentication> auth = authenticateLtiUser(launchRequest);

        if (auth.isPresent()) {
            // Authentication was successful

            SecurityContextHolder.getContext().setAuthentication(auth.get());

            onSuccessfulLtiAuthentication(launchRequest, exercise);

        } else  {

            /*
             *
             * None of the  auth methods were successful.
             * -> Map the launchRequest to the Session ID
             * -> If the user signs in manually later, we use it in LtiAuthenticationSuccessListener
             *
             */

            // Find (new) session ID
            String sessionId = null;
            if(response.containsHeader("Set-Cookie")) {
                for(String cookie: response.getHeaders("Set-Cookie")){
                    if(cookie.contains("JSESSIONID")) {
                        Pattern pattern = Pattern.compile("=(.*?);");
                        Matcher matcher = pattern.matcher(response.getHeader("Set-Cookie"));
                        if (matcher.find()) {
                            sessionId = matcher.group(1);
                        }
                        break;
                    }
                }
            }
            if(sessionId == null) {
                WebAuthenticationDetails authDetails = (WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
                log.debug("Remembering launchRequest for session ID {}", authDetails.getSessionId());
                sessionId = authDetails.getSessionId();
            }

            // Found it. Remember the launch request for later login.
            if(sessionId != null) {
                log.debug("Remembering launchRequest for session ID {}", sessionId);
                launchRequestForSession.put(sessionId, Pair.of(launchRequest, exercise));
            }

        }

    }

    /**
     * Handler for successful LTI auth
     * Saves the LTI outcome url and permanently maps the LTI user id to the user
     *
     * @param launchRequest The launch request, sent by LTI consumer
     * @param exercise      Exercise to launch
     */
    public void onSuccessfulLtiAuthentication(LtiLaunchRequestDTO launchRequest, Exercise exercise) {
        // Auth was successful
        User user = userService.getUser();

        // Make sure user is added to group for this exercise
        addUserToExerciseGroup(user, exercise);

        // Save LTI user ID to automatically sign in the next time
        saveLtiUserId(user, launchRequest.getUser_id());

        // Save LTI outcome url
        saveLtiOutcomeUrl(user, exercise, launchRequest.getLis_outcome_service_url(), launchRequest.getLis_result_sourcedid());
    }

    /**
     * Signs in the LTI user into the exercise app. Therefore it creates an user, if necessary.
     *
     * @param launchRequest The launch request, sent by LTI consumer
     * @return
     * @throws JiraException
     * @throws AuthenticationException
     */
    private Optional<Authentication> authenticateLtiUser(LtiLaunchRequestDTO launchRequest) throws JiraException, AuthenticationException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (SecurityUtils.isAuthenticated()) {
            /**
             * 1. Case:
             * User is already signed in. We are done here.
             *
             */
            return Optional.of(auth);
        }

        /**
         * If the LTI launch is used from edX studio, edX sends dummy data. (id="student")
         * Catch this case here.
         */
        if(launchRequest.getUser_id().equals("student")) {
            throw new InternalAuthenticationServiceException("Invalid username sent by launch request. Please do not launch the exercise from edX studio. Use 'Preview' instead.");
        }

        String email = launchRequest.getLis_person_contact_email_primary() != null ? launchRequest.getLis_person_contact_email_primary() : launchRequest.getUser_id() + "@lti.exercisebruegge.in.tum.de";
        String username = this.USER_PREFIX + (launchRequest.getLis_person_sourcedid() != null ? launchRequest.getLis_person_sourcedid() : launchRequest.getUser_id());
        String fullname = launchRequest.getLis_person_sourcedid() != null ? launchRequest.getLis_person_sourcedid() : launchRequest.getUser_id();

        // Check if there is an existing mapping for the user ID
        Optional<LtiUserId> ltiUserId = ltiUserIdRepository.findByLtiUserId(launchRequest.getUser_id());

        if(ltiUserId.isPresent()) {
            /*
             * 2. Case:
             * Existing mapping for LTI user id
             *
             */
            User user = ltiUserId.get().getUser();
            // Authenticate
            return Optional.of(new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))));
        }

        // Check if lookup by email is enabled
        if (launchRequest.getCustom_lookup_user_by_email() == true) {

            /*
             * 3. Case:
             * Lookup JIRA user with the LTI email address.
             * Sign in as this user.
             *
             */

            // check if an JIRA user with this email address exists
            Optional<String> jiraLookupByEmail = jiraAuthenticationProvider.get().getUsernameForEmail(email);

            if (jiraLookupByEmail.isPresent()) {
                log.debug("Signing in as {}", jiraLookupByEmail.get());
                User user = jiraAuthenticationProvider.get().getOrCreateUser(new UsernamePasswordAuthenticationToken(jiraLookupByEmail.get(), ""), true);

                return Optional.of(new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))));
            }
        }
        // Check if an existing user is required
        if (launchRequest.getCustom_require_existing_user() == false) {

            /*
             * 4. Case:
             * Create new user
             *
             */

            User user = userRepository.findOneByLogin(username).orElseGet(() -> {
                User newUser = userService.createUser(username, "", USER_GROUP_NAME, fullname, email, null, "en");

                // add user to LTI group
                newUser.setGroups(new ArrayList<>(Arrays.asList(USER_GROUP_NAME)));

                // set random password
                String randomEncryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
                newUser.setPassword(randomEncryptedPassword);

                userRepository.save(newUser);

                log.debug("Created user {}", username);

                return newUser;
            });

            // Make sure the user is activated
            if (!user.getActivated()) {
                userService.activateRegistration(user.getActivationKey());
            }

            log.debug("Signing in as {}", username);
            return Optional.of(new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))));

        }

        return Optional.empty();

    }

    /**
     * Add an user to the exercise group
     *
     * @param user
     * @param exercise
     */
    private void addUserToExerciseGroup(User user, Exercise exercise) {
        String courseGroup = exercise.getCourse().getStudentGroupName();
        if (!user.getGroups().contains(courseGroup)) {
            List<String> groups = user.getGroups();
            groups.add(courseGroup);
            user.setGroups(groups);
            userRepository.save(user);

            // try to sync with JIRA
            try {
                jiraAuthenticationProvider.get().addUserToGroup(user.getLogin(), courseGroup);
            } catch (JiraException e) {
            /*
                This might throw exceptions, for example if the group does not exist on JIRA.
                We can safely ignore them.
            */
            }

        }
    }

    /**
     * Save the LTO outcome url
     *
     * @param user
     * @param exercise
     * @param url
     */
    private void saveLtiOutcomeUrl(User user, Exercise exercise, String url, String sourcedId) {

        if (url == null || url.isEmpty()) {
            return;
        }

        LtiOutcomeUrl ltiOutcomeUrl = ltiOutcomeUrlRepository.findByUserAndExercise(user, exercise).orElseGet(() -> {
            LtiOutcomeUrl newLtiOutcomeUrl = new LtiOutcomeUrl();
            newLtiOutcomeUrl.setUser(user);
            newLtiOutcomeUrl.setExercise(exercise);
            return newLtiOutcomeUrl;
        });
        ltiOutcomeUrl.setUrl(url);
        ltiOutcomeUrl.setSourcedId(sourcedId);
        ltiOutcomeUrlRepository.save(ltiOutcomeUrl);
    }

    /**
     * Save the User <-> LTI User ID mapping
     *
     * @param user
     * @param ltiUserIdString
     */
    private void saveLtiUserId(User user, String ltiUserIdString) {

        if (ltiUserIdString == null || ltiUserIdString.isEmpty()) {
            return;
        }

        LtiUserId ltiUserId = ltiUserIdRepository.findByUser(user).orElseGet(() -> {
            LtiUserId newltiUserId = new LtiUserId();
            newltiUserId.setUser(user);
            return newltiUserId;
        });
        ltiUserId.setLtiUserId(ltiUserIdString);
        ltiUserIdRepository.save(ltiUserId);
    }

    /**
     * Checks if a LTI request is correctly signed via OAuth with the secret
     *
     * @param request The request to check
     * @return True if the request is valid, otherwise false
     */
    public Boolean verifyRequest(HttpServletRequest request) {

        LtiVerifier ltiVerifier = new LtiOauthVerifier();
        Boolean success = false;
        try {
            LtiVerificationResult ltiResult = ltiVerifier.verify(request, this.OAUTH_SECRET);
            success = ltiResult.getSuccess();
            if (!success) {
                log.error("Lti signature verification failed: " + ltiResult.getMessage());
            }
        } catch (LtiVerificationException e) {
            log.error("Lti signature verification failed. ", e);
        }
        return success;

    }

    /**
     * This method is pinged on new build results.
     * It sends an message to the LTI consumer with the new score.
     *
     * @param participation
     */
    public void onNewBuildResult(Participation participation) {

        // Get the LTI outcome URL
        Optional<LtiOutcomeUrl> ltiOutcomeUrl = ltiOutcomeUrlRepository.findByUserAndExercise(participation.getStudent(), participation.getExercise());

        if (ltiOutcomeUrl.isPresent()) {

            String score = "0.00";

            // Get the latest result
            Optional<Result> latestResult = resultRepository.findFirstByParticipationIdOrderByCompletionDateDesc(participation.getId());

            if (latestResult.isPresent() && latestResult.get().getScore() != null) {
                // LTI scores needs to be formatted as String between "0.00" and "1.00"
                score = String.format(Locale.ROOT, "%.2f", latestResult.get().getScore().floatValue() / 100);
            }

            log.debug("Reporting to LTI consumer: Score {} for Participation {}", score, participation);

            try {
                // Using PatchedIMSPOXRequest until they fixed the problem: https://github.com/IMSGlobal/basiclti-util-java/issues/27
                HttpPost request = PatchedIMSPOXRequest.buildReplaceResult(ltiOutcomeUrl.get().getUrl(), OAUTH_KEY, OAUTH_SECRET, ltiOutcomeUrl.get().getSourcedId(), score, null, false);
                HttpClient client = HttpClientBuilder.create().build();
                HttpResponse response = client.execute(request);
                String responseString = new BasicResponseHandler().handleResponse(response);
                log.info("Response from LTI consumer: {}", responseString);
                if (response.getStatusLine().getStatusCode() >= 400) {
                    throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());
                }
            } catch (Exception e) {
                log.error("Reporting to LTI consumer failed: {}", e);
            }

        }

    }

    /**
     * Handle launch request which was initiated earlier by a LTI consumer
     *
     * @param sessionId
     */
    public void handleLaunchRequestForSession(String sessionId) {
        if(launchRequestForSession.containsKey(sessionId)) {

            log.debug("Found LTI launchRequest for session ID {}", sessionId);

            LtiLaunchRequestDTO launchRequest = launchRequestForSession.get(sessionId).getLeft();
            Exercise exercise = launchRequestForSession.get(sessionId).getRight();

            onSuccessfulLtiAuthentication(launchRequest, exercise);

            // clean up
            launchRequestForSession.remove(sessionId);

        }
    }

}


text:
App = window.App = Em.Application.create({
  VERSION: '0.1',

  loadTemplate: function(name) {
    return $.get('templates/' + name + '.hbs').then(function(src) {
      Ember.TEMPLATES[name] = Ember.Handlebars.compile(src);
    });
  }
});

App.Router.map(function() {
  this.resource("example1", { path: "/" });
  this.resource("example2", { path: "/example2" });
});

App.initializer({
  name: "templates",

  initialize: function(container, application) {

    application.deferReadiness();

    var promises = [];
    promises.push(application.loadTemplate('application'));
    promises.push(application.loadTemplate('example1'));
    promises.push(application.loadTemplate('example2'));

    Ember.RSVP.all(promises).then(function() {
      application.advanceReadiness();
    })
  }
});

redpajama_set_name: RedPajamaGithub


text:
namespace Krypton.LibProtocol.Member.Expression
{
    /// <summary>
    /// An interface used by objects that represent an expression
    /// </summary>
    public interface IExpression
    {
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Lista de usuários</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


text:
package com.craftmend.openaudiomc.generic.networking.handlers;

import com.craftmend.openaudiomc.generic.networking.abstracts.PayloadHandler;
import com.craftmend.openaudiomc.generic.networking.client.objects.player.ClientConnection;
import com.craftmend.openaudiomc.generic.networking.interfaces.Authenticatable;
import com.craftmend.openaudiomc.generic.networking.payloads.in.ClientChangedVolumePayload;

public class ClientChangedVolumeHandler extends PayloadHandler<ClientChangedVolumePayload> {

    @Override
    public void onReceive(ClientChangedVolumePayload payload) {
        Authenticatable authenticatable = findSession(payload.getClient());
        if (authenticatable instanceof ClientConnection) {
            ((ClientConnection) authenticatable).updatedVolume(payload.getVolume());
        } else {
            // you don't even have volume
            authenticatable.kickConnection();
        }
    }
}


text:
Search Npm Packages

Searches when typing stops. Caches for 30 seconds.

<input type="text" (keyup)="search(getValue($event))" id="name" placeholder="Search"/>

<input type="checkbox" id="refresh" [checked]="withRefresh" (click)="toggleRefresh()">
with refresh

    {{package.name}} v.{{package.version}} -
    {{package.description}}


text:
/*
 * @(#)ComboBoxDemo.java	1.10 03/01/23
 */

import javax.accessibility.AccessibleRelation;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

/**
 * JComboBox Demo
 *
 * @version 1.10 01/23/03
 * @author Jeff Dinkins
 */
public class ComboBoxDemo extends DemoModule implements ActionListener {

    Face face;
    JLabel faceLabel;

    JComboBox hairCB;
    JComboBox eyesCB;
    JComboBox mouthCB;

    JComboBox presetCB;

    Hashtable parts = new Hashtable();

    /**
     * main method allows us to run as a standalone demo.
     */
    public static void main(String[] args) {
	ComboBoxDemo demo = new ComboBoxDemo(null);
	demo.mainImpl();
    }

    /**
     * ComboBoxDemo Constructor
     */
    public ComboBoxDemo(SwingSet2 swingset) {
	// Set the title for this demo, and an icon used to represent this
	// demo inside the SwingSet2 app.
	super(swingset, "ComboBoxDemo", "toolbar/JComboBox.gif");

	createComboBoxDemo();
    }

    public void createComboBoxDemo() {
	JPanel demo = getDemoPanel();

	JPanel demoPanel = getDemoPanel();
	demoPanel.setLayout(new BoxLayout(demoPanel, BoxLayout.Y_AXIS));

	JPanel innerPanel = new JPanel();
	innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));

	demoPanel.add(Box.createRigidArea(VGAP20));
	demoPanel.add(innerPanel);
	demoPanel.add(Box.createRigidArea(VGAP20));

	innerPanel.add(Box.createRigidArea(HGAP20));

	// Create a panel to hold buttons
	JPanel comboBoxPanel = new JPanel() {
		public Dimension getMaximumSize() {
		    return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
		}
	};
	comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS));

	comboBoxPanel.add(Box.createRigidArea(VGAP15));

	JLabel l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.presets")));
	l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
	presetCB = (JComboBox) comboBoxPanel.add(createPresetComboBox());
	presetCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
	l.setLabelFor(presetCB);
	comboBoxPanel.add(Box.createRigidArea(VGAP30));

	l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.hair_description")));
	l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
	hairCB = (JComboBox) comboBoxPanel.add(createHairComboBox());
	hairCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
	l.setLabelFor(hairCB);
	comboBoxPanel.add(Box.createRigidArea(VGAP15));

	l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.eyes_description")));
	l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
	eyesCB = (JComboBox) comboBoxPanel.add(createEyesComboBox());
	eyesCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
	l.setLabelFor(eyesCB);
	comboBoxPanel.add(Box.createRigidArea(VGAP15));

	l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.mouth_description")));
	l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
	mouthCB = (JComboBox) comboBoxPanel.add(createMouthComboBox());
	mouthCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
	l.setLabelFor(mouthCB);
	comboBoxPanel.add(Box.createRigidArea(VGAP15));

        // Fill up the remaining space
        comboBoxPanel.add(new JPanel(new BorderLayout()));

	// Create and place the Face.

	face = new Face();
	JPanel facePanel = new JPanel();
	facePanel.setLayout(new BorderLayout());
	facePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));

	faceLabel = new JLabel(face);
	facePanel.add(faceLabel, BorderLayout.CENTER);
	// Indicate that the face panel is controlled by the hair, eyes and
	// mouth combo boxes.
	Object [] controlledByObjects = new Object[3];
	controlledByObjects[0] = hairCB;
	controlledByObjects[1] = eyesCB;
	controlledByObjects[2] = mouthCB;
	AccessibleRelation controlledByRelation =
            new AccessibleRelation(AccessibleRelation.CONTROLLED_BY_PROPERTY,
				   controlledByObjects);
	facePanel.getAccessibleContext().getAccessibleRelationSet().add(controlledByRelation);

	// Indicate that the hair, eyes and mouth combo boxes are controllers
        // for the face panel.
	AccessibleRelation controllerForRelation =
            new AccessibleRelation(AccessibleRelation.CONTROLLER_FOR_PROPERTY,
                                   facePanel);
	hairCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);
	eyesCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);
	mouthCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);

	// add buttons and image panels to inner panel
	innerPanel.add(comboBoxPanel);
	innerPanel.add(Box.createRigidArea(HGAP30));
	innerPanel.add(facePanel);
	innerPanel.add(Box.createRigidArea(HGAP20));

	// load up the face parts
	addFace("brent",     getString("ComboBoxDemo.brent"));
	addFace("georges",   getString("ComboBoxDemo.georges"));
	addFace("hans",      getString("ComboBoxDemo.hans"));
	addFace("howard",    getString("ComboBoxDemo.howard"));
	addFace("james",     getString("ComboBoxDemo.james"));
	addFace("jeff",      getString("ComboBoxDemo.jeff"));
	addFace("jon",       getString("ComboBoxDemo.jon"));
	addFace("lara",      getString("ComboBoxDemo.lara"));
	addFace("larry",     getString("ComboBoxDemo.larry"));
	addFace("lisa",      getString("ComboBoxDemo.lisa"));
	addFace("michael",   getString("ComboBoxDemo.michael"));
	addFace("philip",    getString("ComboBoxDemo.philip"));
	addFace("scott",     getString("ComboBoxDemo.scott"));

	// set the default face
	presetCB.setSelectedIndex(0);
    }

    void addFace(String name, String i18n_name) {
	ImageIcon i;
	String i18n_hair = getString("ComboBoxDemo.hair");
	String i18n_eyes = getString("ComboBoxDemo.eyes");
	String i18n_mouth = getString("ComboBoxDemo.mouth");

	parts.put(i18n_name, name); // i18n name lookup
	parts.put(name, i18n_name); // reverse name lookup

	i = createImageIcon("combobox/" + name + "hair.jpg", i18n_name + i18n_hair);
	parts.put(name +  "hair", i);

	i = createImageIcon("combobox/" + name + "eyes.jpg", i18n_name + i18n_eyes);
	parts.put(name +  "eyes", i);

	i = createImageIcon("combobox/" + name + "mouth.jpg", i18n_name + i18n_mouth);
	parts.put(name +  "mouth", i);
    }

    Face getFace() {
	return face;
    }

    JComboBox createHairComboBox() {
	JComboBox cb = new JComboBox();
	fillComboBox(cb);
	cb.addActionListener(this);
	return cb;
    }

    JComboBox createEyesComboBox() {
	JComboBox cb = new JComboBox();
	fillComboBox(cb);
	cb.addActionListener(this);
	return cb;
    }

    JComboBox createNoseComboBox() {
	JComboBox cb = new JComboBox();
	fillComboBox(cb);
	cb.addActionListener(this);
	return cb;
    }

    JComboBox createMouthComboBox() {
	JComboBox cb = new JComboBox();
	fillComboBox(cb);
	cb.addActionListener(this);
	return cb;
    }

    JComboBox createPresetComboBox() {
	JComboBox cb = new JComboBox();
	cb.addItem(getString("ComboBoxDemo.preset1"));
	cb.addItem(getString("ComboBoxDemo.preset2"));
	cb.addItem(getString("ComboBoxDemo.preset3"));
	cb.addItem(getString("ComboBoxDemo.preset4"));
	cb.addItem(getString("ComboBoxDemo.preset5"));
	cb.addItem(getString("ComboBoxDemo.preset6"));
	cb.addItem(getString("ComboBoxDemo.preset7"));
	cb.addItem(getString("ComboBoxDemo.preset8"));
	cb.addItem(getString("ComboBoxDemo.preset9"));
	cb.addItem(getString("ComboBoxDemo.preset10"));
	cb.addActionListener(this);
	return cb;
    }

    void fillComboBox(JComboBox cb) {
	cb.addItem(getString("ComboBoxDemo.brent"));
	cb.addItem(getString("ComboBoxDemo.georges"));
	cb.addItem(getString("ComboBoxDemo.hans"));
	cb.addItem(getString("ComboBoxDemo.howard"));
	cb.addItem(getString("ComboBoxDemo.james"));
	cb.addItem(getString("ComboBoxDemo.jeff"));
	cb.addItem(getString("ComboBoxDemo.jon"));
	cb.addItem(getString("ComboBoxDemo.lara"));
	cb.addItem(getString("ComboBoxDemo.larry"));
	cb.addItem(getString("ComboBoxDemo.lisa"));
	cb.addItem(getString("ComboBoxDemo.michael"));
	cb.addItem(getString("ComboBoxDemo.philip"));
	cb.addItem(getString("ComboBoxDemo.scott"));
    }

    public void actionPerformed(ActionEvent e) {
	if(e.getSource() == hairCB) {
	    String name = (String) parts.get((String) hairCB.getSelectedItem());
	    face.setHair((ImageIcon) parts.get(name + "hair"));
	    faceLabel.repaint();
	} else if(e.getSource() == eyesCB) {
	    String name = (String) parts.get((String) eyesCB.getSelectedItem());
	    face.setEyes((ImageIcon) parts.get(name + "eyes"));
	    faceLabel.repaint();
	} else if(e.getSource() == mouthCB) {
	    String name = (String) parts.get((String) mouthCB.getSelectedItem());
	    face.setMouth((ImageIcon) parts.get(name + "mouth"));
	    faceLabel.repaint();
	} else if(e.getSource() == presetCB) {
	    String hair = null;
	    String eyes = null;
	    String mouth = null;
	    switch(presetCB.getSelectedIndex()) {
	       case 0:
		   hair = (String) parts.get("philip");
		   eyes = (String) parts.get("howard");
		   mouth = (String) parts.get("jeff");
		   break;
	       case 1:
		   hair = (String) parts.get("jeff");
		   eyes = (String) parts.get("larry");
		   mouth = (String) parts.get("philip");
		   break;
	       case 2:
		   hair = (String) parts.get("howard");
		   eyes = (String) parts.get("scott");
		   mouth = (String) parts.get("hans");
		   break;
	       case 3:
		   hair = (String) parts.get("philip");
		   eyes = (String) parts.get("jeff");
		   mouth = (String) parts.get("hans");
		   break;
	       case 4:
		   hair = (String) parts.get("brent");
		   eyes = (String) parts.get("jon");
		   mouth = (String) parts.get("scott");
		   break;
	       case 5:
		   hair = (String) parts.get("lara");
		   eyes = (String) parts.get("larry");
		   mouth = (String) parts.get("lisa");
		   break;
	       case 6:
		   hair = (String) parts.get("james");
		   eyes = (String) parts.get("philip");
		   mouth = (String) parts.get("michael");
		   break;
	       case 7:
		   hair = (String) parts.get("philip");
		   eyes = (String) parts.get("lisa");
		   mouth = (String) parts.get("brent");
		   break;
	       case 8:
		   hair = (String) parts.get("james");
		   eyes = (String) parts.get("philip");
		   mouth = (String) parts.get("jon");
		   break;
	       case 9:
		   hair = (String) parts.get("lara");
		   eyes = (String) parts.get("jon");
		   mouth = (String) parts.get("scott");
		   break;
	    }
	    if(hair != null) {
		hairCB.setSelectedItem(hair);
		eyesCB.setSelectedItem(eyes);
		mouthCB.setSelectedItem(mouth);
		faceLabel.repaint();
	    }
	}
    }

    class Face implements Icon {
	ImageIcon hair;
	ImageIcon eyes;
	ImageIcon mouth;

	void setHair(ImageIcon i) {
	    hair = i;
	}

	void setEyes(ImageIcon i) {
	    eyes = i;
	}

	void setMouth(ImageIcon i) {
	    mouth = i;
	}

	public void paintIcon(Component c, Graphics g, int x, int y) {
	    int height = y;
	    x = c.getWidth()/2 - getIconWidth()/2;

	    if(hair != null) {
		hair.paintIcon(c, g, x, height);   height += hair.getIconHeight();
	    }

	    if(eyes != null) {
		eyes.paintIcon(c, g, x, height);   height += eyes.getIconHeight();
	    }

	    if(mouth != null) {
		mouth.paintIcon(c, g, x, height);
	    }
	}

	public int getIconWidth() {
	    return 344;
	}

	public int getIconHeight() {
	    return 455;
	}
    }
}


text:
export * from './baseobject/IDatable'
export * from './baseobject/BaseObject'
export * from './command/Command'
export * from './command/CommandErrorCode'
export * from './command/CommandEvent'
export * from './command/CallbackExecutionCommand'
export * from './command/CallbackWithPromiseExecutionCommand'
export * from './command/QueueCommand'
export * from './command/QueueCommandErrorCode'
export * from './command/QueueCommandEvent'
export * from './datastructure/associativearray/AssociativeArray'
export * from './datastructure/associativearray/AssociativeArrayEvent'
export * from './datastructure/Dictionary'
export * from './event/eventdispatcher/BaseEventDispatcher'
export * from './event/eventlistenerhelper/EventListenerHelper'
export * from './event/eventlistenerhelper/EventListenerHelperItemVO'
export * from './event/eventlistenerhelper/IDefaultEventDispatcher'
export * from './event/eventlistenerhelper/IEventDispatcher'
export * from './event/eventlistenerhelper/IEventEmitter'
export * from './event/eventlistenerhelper/IEventListenerCallback'
export * from './event/tools/EventsHelperTools'
export * from './lock/Lock'
export * from './logger/BaseLoggerItem'
export * from './logger/ConsoleLoggerItem'
export * from './logger/Logger'
export * from './objectspool/ObjectsPool'
export * from './other/IConstructor'
export * from './other/IFunctionArguments'
export * from './TestCoreClass'
export * from './tools/ArrayTools'
export * from './tools/MatrixTools'
export * from './tools/function/FunctionTools'
export * from './tools/function/IDelayedFunctionVO'
export * from './tools/keyboard/JSKeyboardEvent'
export * from './tools/keyboard/KeyboardTools'
export * from './tools/MixinTools'
export * from './tools/NumberTools'
export * from './tools/AngleTools'
export * from './tools/ObjectTools'
export * from './tools/StringTools'
export * from './tools/UniqueTools'
export * from './tools/windows/JSWindowEvent'


text:
Given(/^that I am on the home page$/) do
  visit 'index.html'
end

Then(/^I should see "(.*?)"$/) do |content|
  page.should have_content content
end

When(/^I click on "(.*?)"$/) do |link|
  page.should have_content link
  click_link link
end

Given(/^the following contact exists:$/) do |table|
  # table is a Cucumber::Ast::Table
  #pending # this would be written into the database if we were testing with one
end

When(/^I go to User Info Page$/) do
  visit 'users.html'
end

When(/^I go to Events Page$/) do
  visit 'events.html'
end

When(/^I fill in (.*?) with "(.*?)"$/) do |name, value|
  fill_in(name, :with => value)
end

When(/^I hit the (.*?) button$/) do |button|
  click_button button
end

Then(/^I change "(.*?)" with "(.*?)"$/) do |arg1, arg2|
  pending # express the regexp above with the code you wish you had
end

Then(/^I should not see "(.*?)"$/) do |arg1|
  page.should_not have_content content
end

When(/^I go to the timetable page for "(.*?)"$/) do |arg1|
  visit 'timetable.html'
end

Then(/^I change avaliable time with "(.*?)"$/) do |arg1|
  pending # express the regexp above with the code you wish you had
end

When(/^I go to the user page$/) do
  visit 'user.html'
end

Then(/^I check the timetable with "(.*?)"    \# upload\?$/) do |arg1|
  pending # express the regexp above with the code you wish you had
end


text:
import log4js = require('log4js');
import Atom = require('./atom');

var logger = log4js.getLogger();

var HELLO = 'helo';
var OLLEH = 'oleh';
var HELLO_AGENT = 'agnt';
var HELLO_OS_TYPE = 'ostp';
var HELLO_SESSION_ID = 'sid\0';
var HELLO_PORT = 'port';
var HELLO_PING = 'ping';
var HELLO_VERSION = 'ver\0';
var HELLO_BC_ID = 'bcid';
//var OLLEH_PONG = 'pong';
var OLLEH_REMOTE_IP = 'rip\0';
//var OLLEH_DISABLE = 'dis\0';

var QUIT = 'quit';

export function toName(simpleName: string) {
    switch (simpleName) {
        case HELLO:
            return 'hello';
        case OLLEH:
            return 'olleh';
        case QUIT:
            return 'quit';
        default:
            logger.warn('Unsupported name: ' + simpleName);
            return simpleName;
    }
}

export function createHello(
    agent: string,
    osType: number,
    sessionId: Buffer,
    port: number,
    ping: number,
    version: number,
    bcId: Buffer
    ) {
    var atom = Atom.createContainer(HELLO);
    atom.pushStringContent(HELLO_AGENT, agent);
    atom.pushIntContent(HELLO_OS_TYPE, osType);
    atom.pushGuidContent(HELLO_SESSION_ID, sessionId);
    atom.pushShortContent(HELLO_PORT, port);
    atom.pushShortContent(HELLO_PING, ping);
    atom.pushIntContent(HELLO_VERSION, version);
    atom.pushGuidContent(HELLO_BC_ID, bcId);
    return atom;
}

export function createOlleh(
    agent: string,
    sessionId: Buffer,
    port: number,
    remoteIp: number,
    version: number
    ) {
    var atom = Atom.createContainer(OLLEH);
    atom.pushStringContent(HELLO_AGENT, agent);
    atom.pushGuidContent(HELLO_SESSION_ID, sessionId);
    atom.pushShortContent(HELLO_PORT, port);
    //atom.pushShortContent(HELLO_PONG, pong);
    atom.pushIntContent(OLLEH_REMOTE_IP, remoteIp);
    atom.pushIntContent(HELLO_VERSION, version);
    return atom;
}

export function createQuit() {
    return Atom.createIntContent(QUIT, 0);
}


text:
#pragma once

#include "SocketAddress.h"

namespace meshy {
	/// 原始socket的封装
	class Socket {
	public:
		Socket(NativeSocket nativeSocket = 0, SocketAddress const& address = {});
		virtual ~Socket();

		NativeSocket GetNativeSocket()const;
		SocketAddress const& GetSocketAddress()const;
		void SetSocketAddress(SocketAddress const& address) {
			m_socketAddress = address;
		}

		/// @return socket的类型是SOCK_STREAM还是SOCK_DGRAM
		int type()const;
		int sendbuf()const;
		int recvbuf()const;

		int sendbuf(int new_size);
		int recvbuf(int new_size);
		/// 关闭nagle算法,传输大文件时关闭,默认是开启状态
		/// @param value true关闭nagle算法,false开启nagle算法
		int nodelay(bool value);
		int ReuseAddr();
		static NativeSocket CreateNativeSocket();

		/// 如果optval不是int类型,需要修改这代码和返回值
		/// @param level: SOL_SOCKET, IPPROTO_IP, IPPROTO_TCP
		int getsockopt(int level, int optname)const;
		int setsockopt(int level, int optname, int optval);
	protected:
		void close();
		void SetNativeSocket(NativeSocket nativeSocket);
		/// 对于监听socket,表示绑定的地址,其他则表示对方的地址
		SocketAddress	m_socketAddress;
	private:
		NativeSocket		m_nativeSocket;
	};
}


text:
use base::ParseState;

pub fn ToParseState<'a>( bytes: &'a [u8] ) -> ParseState<'a> {
  ParseState { input: bytes, offset: 0 }
}

macro_rules! input_state( ( $ex:expr ) => ( {
      use base::ParseState;
      ParseState { input: $ex.as_bytes(), offset: 0 }
    } ) );


text:
===============
django-lockdown
===============

.. image:: https://github.com/Dunedan/django-lockdown/workflows/CI/badge.svg
    :target: https://github.com/Dunedan/django-lockdown/actions
    :alt: Build Status
.. image:: https://coveralls.io/repos/Dunedan/django-lockdown/badge.svg
    :target: https://coveralls.io/r/Dunedan/django-lockdown
    :alt: Test Coverage
.. image:: https://img.shields.io/pypi/v/django-lockdown.svg
    :target: https://pypi.org/project/django-lockdown/
    :alt: Latest Version

``django-lockdown`` is a reusable Django application for locking down an entire
site (or particular views), with customizable date ranges and preview
authorization.

Installation
============

Install from PyPI with ``easy_install`` or ``pip``::

    pip install django-lockdown

To use ``django-lockdown`` in your Django project:

1. Add ``'lockdown'`` to your ``INSTALLED_APPS``.
   If you want to use one of ``django-lockdowns`` default lock down forms,
   you'll additionally have to ensure that you have enabled
   ``django.contrib.auth`` as part of to your ``INSTALLED_APPS``.

2. To enable admin preview of locked-down sites or views with
   passwords, set the `LOCKDOWN_PASSWORDS`_ setting to a tuple of one or
   more plain-text passwords.

3. Protect the entire site by using middleware, or protect individual views
   by applying a decorator to them.

For more advanced customization of admin preview authorization, see
the `LOCKDOWN_FORM`_ setting.

Dependencies
------------

``django-lockdown`` requires `Python`_ 3.6 or later and `Django`_ 2.2 or later.

As an alternative to CPython `PyPy`_ 3.5 and 3.6 are supported as well.

.. _Python: https://www.python.org/
.. _Django: https://www.djangoproject.com/
.. _PyPy: https://pypy.org/

Usage
=====

Using the middleware
--------------------

To lock down the entire site, add the lockdown middleware to your middlewares::

    MIDDLEWARE = [
        # ...
        'lockdown.middleware.LockdownMiddleware',
    ]

Optionally, you may also add URL regular expressions to a
`LOCKDOWN_URL_EXCEPTIONS`_ setting.

Using the decorator
-------------------

- Import the decorator::

    from lockdown.decorators import lockdown

- Apply the decorator to individual views you want to protect. For example::

    @lockdown()
    def secret_page(request):
        # ...

The decorator accepts seven arguments:

``form``
  The form to use for providing an admin preview, rather than the form
  referenced by `LOCKDOWN_FORM`_. Note that this must be an actual form class,
  not a module reference like the setting.

``until_date``
  The date to use rather than the date provided by `LOCKDOWN_UNTIL`_.

``after_date``
  The date to use rather than the date provided by `LOCKDOWN_AFTER`_.

``logout_key``
  A preview logout key to use, rather than the one provided by
  `LOCKDOWN_LOGOUT_KEY`_.

``session_key``
  The session key to use, rather than the one provided by
  `LOCKDOWN_SESSION_KEY`_.

``url_exceptions``
  A list of regular expressions for which matching urls can bypass the lockdown
  (rather than using those defined in `LOCKDOWN_URL_EXCEPTIONS`_).

``remote_addr_exceptions``
 A list of IP-addresses or IP-subnets for which matching URLs can bypass the
 lockdown (rather than using those defined in
 `LOCKDOWN_REMOTE_ADDR_EXCEPTIONS`_).

``extra_context``
  A dictionary of context data that will be added to the default context data
  passed to the template.

Any further keyword arguments are passed to the admin preview form. The default
form accepts one argument:

``passwords``
  A tuple of passwords to use, rather than the ones provided by
  `LOCKDOWN_PASSWORDS`_.

Settings
========

LOCKDOWN_ENABLED
----------------

An optional boolean value that, if set to False, disables
``django-lockdown`` globally. Defaults to True (lock down enabled).

LOCKDOWN_PASSWORDS
------------------

One or more plain-text passwords which allow the previewing of the site or
views protected by django-lockdown::

    LOCKDOWN_PASSWORDS = ('letmein', 'beta')

If this setting is not provided (and the default `LOCKDOWN_FORM`_ is being
used), there will be no admin preview for locked-down pages.

If a `LOCKDOWN_FORM`_ other than the default is used, this setting has no
effect.

LOCKDOWN_URL_EXCEPTIONS
-----------------------

An optional list/tuple of regular expressions to be matched against incoming
URLs. If a URL matches a regular expression in this list, it will not be
locked. For example::

    LOCKDOWN_URL_EXCEPTIONS = (
        r'^/about/$',   # unlock /about/
        r'\.json$',   # unlock JSON API
    )

LOCKDOWN_VIEW_EXCEPTIONS
------------------------

An optional list of regular expressions to be matched against the
resolved views of incoming requests. If the URL of an incoming request
resolves to one of the views in the list, it will not be locked.
That's useful if you want to lock down a whole site using the middleware,
but want to whitelist some localized URLs.

For example::

    from yourapp import one_view_to_unlock, another_view_to_unlock

    LOCKDOWN_VIEW_EXCEPTIONS = [
        one_view_to_unlock,
        another_view_to_unlock
    ]

LOCKDOWN_REMOTE_ADDR_EXCEPTIONS
-------------------------------

An optional list of IP-addresses or IP-subnets to be matched against the
requesting IP-address (from `requests.META['REMOTE_ADDR']`). If the
requesting IP-address is in this list, it will not be locked. For example::

    LOCKDOWN_REMOTE_ADDR_EXCEPTIONS = [
        '127.0.0.1',
        '::1',
    ]

LOCKDOWN_TRUSTED_PROXIES
-------------------------------

A list of trusted proxy IP-addresses to be used in conjunction with
`LOCKDOWN_REMOTE_ADDR_EXCEPTIONS` when a reverse-proxy or load balancer is used.
If the requesting IP address is from the trusted proxies list the last address from
the `X-Forwared-For` header (from `requests.META['HTTP_X_FORWARDED_FOR']`) will be
checked against `LOCKDOWN_REMOTE_ADDR_EXCEPTIONS` and locked or unlocked accordingly.

For example::

    LOCKDOWN_TRUSTED_PROXIES = [
        '172.17.0.1',
    ]

    LOCKDOWN_REMOTE_ADDR_EXCEPTIONS = [
        '172.17.0.5',
    ]

LOCKDOWN_UNTIL
--------------

Used to lock the site down up until a certain date. Set to a
``datetime.datetime`` object.

If neither ``LOCKDOWN_UNTIL`` nor `LOCKDOWN_AFTER`_ is provided (the default),
the site or views will always be locked.

LOCKDOWN_AFTER
--------------

Used to lock the site down after a certain date. Set to a ``datetime.datetime``
object.

See also: `LOCKDOWN_UNTIL`_.

LOCKDOWN_LOGOUT_KEY
-------------------

A key which, if provided in the query string of a locked URL, will log out the
user from the preview.

LOCKDOWN_FORM
-------------

The default lockdown form allows admin preview by entering a preset
plain-text password (checked, by default, against the `LOCKDOWN_PASSWORDS`_
setting). To set up more advanced methods of authenticating access to
locked-down pages, set ``LOCKDOWN_FORM`` to the Python dotted path to a Django
``Form`` subclass. This form will be displayed on the lockout page. If the form
validates when submitted, the user will be allowed access to locked pages::

    LOCKDOWN_FORM = 'path.to.my.CustomLockdownForm'

A form for authenticating against ``django.contrib.auth`` users is provided
with django-lockdown (use ``LOCKDOWN_FORM = 'lockdown.forms.AuthForm'``). It
accepts two keyword arguments (in the ``lockdown`` decorator):

``staff_only``
  Only allow staff members to preview. Defaults to ``True`` (but the default
  can be provided as a `LOCKDOWN_AUTHFORM_STAFF_ONLY`_ setting).

``superusers_only``
  Only allow superusers to preview. Defaults to ``False`` (but the default
  can be provided as a `LOCKDOWN_AUTHFORM_SUPERUSERS_ONLY`_ setting).

LOCKDOWN_AUTHFORM_STAFF_ONLY
----------------------------

If using ``lockdown.forms.AuthForm`` and this setting is ``True``, only staff
users will be allowed to preview (True by default).

Has no effect if not using ``lockdown.forms.AuthForm``.

LOCKDOWN_AUTHFORM_SUPERUSERS_ONLY
---------------------------------

If using ``lockdown.forms.AuthForm`` and this setting is ``True``, only
superusers will be allowed to preview (False by default). Has no effect if not
using ``lockdown.forms.AuthForm``.

LOCKDOWN_SESSION_KEY
--------------------

Once a client is authorized for admin preview, they will continue to
be authorized for the remainder of their browsing session (using
Django's built-in session support). ``LOCKDOWN_SESSION_KEY`` defines
the session key used; the default is ``'lockdown-allow'``.

Templates
=========

``django-lockdown`` uses a single template, ``lockdown/form.html``. The
default template displays a simple "coming soon" message and the
preview authorization form, if a password via `LOCKDOWN_PASSWORDS`_ is set.

If you want to use a different template, you can use Djangos template
`loaders`_ to specify a path inside your project to search for templates,
before searching for templates included in ``django-lockdown``.

In your overwritten template the lockdown preview form is available in the
template context as ``form``.

.. _loaders: https://docs.djangoproject.com/en/2.1/ref/templates/api/#template-loaders


text:
var types = require('../data/record-types');

/**
* Creates an record of a given record type
*
* @param  {Number} typeId id of the record type to create
* @return {Object} data model of the new record. Model is not save to server yet.
*/
function createType(typeId){
	// Get type
	var type = types[typeId];

  var record = {
    type: typeId,
  };

  // Fill with default values
  type.variableTypes.forEach(function(varType){
    switch(varType.valType){
      case 1: // int, fallthrough
      case 2: // float
        record[varType.name] = 0;
        break;
      case 3: // time
        record[varType.name] = Math.floor(Date.now()/1000);
        break;
      case 4: // string
        record[varType.name] = '';
    }
  });

  return record;
}

module.exports.createType = createType;


text:
namespace Orchard.Services {
    public interface IHtmlFilter : IDependency {
        string ProcessContent(string text, string flavor);
    }
}


text:
class GURL;
class Profile;

namespace gfx {
class ImageSkia;
}

namespace web_app {

class FileUtilsWrapper;
class WebAppIconManager;

SkBitmap CreateSquareIcon(int size_px, SkColor solid_color);

void AddGeneratedIcon(std::map<SquareSizePx, SkBitmap>* icon_bitmaps,
                      int size_px,
                      SkColor solid_color);

void AddIconToIconsMap(const GURL& icon_url,
                       int size_px,
                       SkColor solid_color,
                       IconsMap* icons_map);

void AddEmptyIconToIconsMap(const GURL& icon_url, IconsMap* icons_map);

bool AreColorsEqual(SkColor expected_color,
                    SkColor actual_color,
                    int threshold);

base::FilePath GetAppIconsAnyDir(Profile* profile, const AppId& app_id);

base::FilePath GetAppIconsMaskableDir(Profile* profile, const AppId& app_id);

base::FilePath GetOtherIconsDir(Profile* profile, const AppId& app_id);

// Performs blocking IO and decompression.
bool ReadBitmap(FileUtilsWrapper* utils,
                const base::FilePath& file_path,
                SkBitmap* bitmap);

base::span<const int> GetIconSizes();

bool ContainsOneIconOfEachSize(
    const std::map<SquareSizePx, SkBitmap>& icon_bitmaps);

void ExpectImageSkiaRep(const gfx::ImageSkia& image_skia,
                        float scale,
                        SquareSizePx size_px,
                        SkColor color);

blink::Manifest::ImageResource CreateSquareImageResource(
    const GURL& src,
    int size_px,
    const std::vector<IconPurpose>& purposes);

// Performs blocking IO and decompression.
std::map<SquareSizePx, SkBitmap> ReadPngsFromDirectory(
    FileUtilsWrapper* file_utils,
    const base::FilePath& icons_dir);

struct GeneratedIconsInfo {
  GeneratedIconsInfo();
  GeneratedIconsInfo(const GeneratedIconsInfo&);
  GeneratedIconsInfo(IconPurpose purpose,
                     std::vector<SquareSizePx> sizes_px,
                     std::vector<SkColor> colors);
  ~GeneratedIconsInfo();

  IconPurpose purpose;
  std::vector<SquareSizePx> sizes_px;
  std::vector<SkColor> colors;
};

apps::IconInfo CreateIconInfo(const GURL& icon_base_url,
                              IconPurpose purpose,
                              SquareSizePx size_px);

void AddIconsToWebAppInstallInfo(
    WebAppInstallInfo* install_info,
    const GURL& icons_base_url,
    const std::vector<GeneratedIconsInfo>& icons_info);

void IconManagerWriteGeneratedIcons(
    WebAppIconManager& icon_manager,
    const AppId& app_id,
    const std::vector<GeneratedIconsInfo>& icons_info);

// Synchronous read of an app icon pixel.
SkColor IconManagerReadAppIconPixel(WebAppIconManager& icon_manager,
                                    const AppId& app_id,
                                    SquareSizePx size_px,
                                    int x = 0,
                                    int y = 0);

}  // namespace web_app

#endif  // CHROME_BROWSER_WEB_APPLICATIONS_TEST_WEB_APP_ICON_TEST_UTILS_H_


text:
package org.compass.gps.device.jpa.entities;

import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.persistence.EntityManagerFactoryImpl;
import org.apache.openjpa.persistence.OpenJPAPersistence;
import org.compass.core.mapping.ResourceMapping;
import org.compass.gps.device.jpa.JpaGpsDevice;
import org.compass.gps.device.jpa.JpaGpsDeviceException;
import org.compass.gps.spi.CompassGpsInterfaceDevice;

/**
 * A specilized version that works with OpenJPA. This class should be used instead of
 * {@link org.compass.gps.device.jpa.entities.DefaultJpaEntitiesLocator} since it works with both openjpa xml files and annotatios.
 *
 * @author kimchy
 */
public class OpenJPAJpaEntitiesLocator implements JpaEntitiesLocator {

    protected Log log = LogFactory.getLog(getClass());

    private ClassLoader classLoader;

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public EntityInformation[] locate(EntityManagerFactory entityManagerFactory, JpaGpsDevice device)
            throws JpaGpsDeviceException {

        CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps();

        // TODO this should use OpenJPAEnitiyManagerFactorySPI, here for backward compatability with pre 1.0
        EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) OpenJPAPersistence.cast(entityManagerFactory);

        ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>();

        // pre initalize the class meta data
        EntityManager entityManager = emf.createEntityManager();
        entityManager.close();

        Collection<Class> classes = emf.getConfiguration().getMetaDataRepositoryInstance().loadPersistentTypes(true, classLoader);
        for (Class clazz : classes) {
            ClassMetaData classMetaData = emf.getConfiguration().getMetaDataRepositoryInstance().getMetaData(clazz, classLoader, true);
            String entityname = classMetaData.getDescribedType().getName();
            if (!gps.hasMappingForEntityForIndex((entityname))) {
                if (log.isDebugEnabled()) {
                    log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out");
                }
                continue;
            }

            if (shouldFilter(entityname, classMetaData, device)) {
                continue;
            }
            ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname);
            EntityInformation entityInformation = new EntityInformation(clazz, entityname, resourceMapping.getSubIndexHash().getSubIndexes());
            entitiesList.add(entityInformation);
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityname + "] will be indexed");
            }
        }
        return entitiesList.toArray(new EntityInformation[entitiesList.size()]);
    }

    /**
     * Returns true if the entity name needs to be filtered.
     *
     *
Implementation filteres out inherited OpenJPA mappings, since the select query
     * for the base class will cover any inherited classes as well.
     *
     *
Note, that this method is called after it has been verified that the class has
     * Compass mappings (either directly, or indirectly by an interface or a super class).
     *
     * @param entityname    The name of the entity
     * @param classMetadata The OpenJPA class meta data.
     * @param device        The Jpa Gps device
     * @return true if the entity should be filtered out, false if not.
     */
    protected boolean shouldFilter(String entityname, ClassMetaData classMetadata, JpaGpsDevice device) {
        Class<?> clazz = classMetadata.getDescribedType();
        // if it is inherited, do not add it to the classes to index, since the "from [entity]"
        // query for the base class will return results for this class as well
        if (classMetadata.getMappedPCSuperclassMetaData() != null) {
            Class superClass = classMetadata.getMappedPCSuperclassMetaData().getDescribedType();
            // only filter out classes that their super class has compass mappings
            if (superClass != null
                    && ((CompassGpsInterfaceDevice) device.getGps()).hasMappingForEntityForIndex(superClass)) {
                if (log.isDebugEnabled()) {
                    log.debug("Entity [" + entityname + "] is inherited and super class ["
                            + superClass + "] has compass mapping, filtering it out");
                }
                return true;
            }
        }
        return false;
    }
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.vmmigration.v1alpha1.model;

/**
 * A policy for scheduling replications.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Migrate to Virtual Machines API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class SchedulePolicy extends com.google.api.client.json.GenericJson {

  /**
   * The idle duration between replication stages.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String idleDuration;

  /**
   * A flag to indicate whether to skip OS adaptation during the replication sync. OS adaptation is
   * a process where the VM's operating system undergoes changes and adaptations to fully function
   * on Compute Engine.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean skipOsAdaptation;

  /**
   * The idle duration between replication stages.
   * @return value or {@code null} for none
   */
  public String getIdleDuration() {
    return idleDuration;
  }

  /**
   * The idle duration between replication stages.
   * @param idleDuration idleDuration or {@code null} for none
   */
  public SchedulePolicy setIdleDuration(String idleDuration) {
    this.idleDuration = idleDuration;
    return this;
  }

  /**
   * A flag to indicate whether to skip OS adaptation during the replication sync. OS adaptation is
   * a process where the VM's operating system undergoes changes and adaptations to fully function
   * on Compute Engine.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getSkipOsAdaptation() {
    return skipOsAdaptation;
  }

  /**
   * A flag to indicate whether to skip OS adaptation during the replication sync. OS adaptation is
   * a process where the VM's operating system undergoes changes and adaptations to fully function
   * on Compute Engine.
   * @param skipOsAdaptation skipOsAdaptation or {@code null} for none
   */
  public SchedulePolicy setSkipOsAdaptation(java.lang.Boolean skipOsAdaptation) {
    this.skipOsAdaptation = skipOsAdaptation;
    return this;
  }

  @Override
  public SchedulePolicy set(String fieldName, Object value) {
    return (SchedulePolicy) super.set(fieldName, value);
  }

  @Override
  public SchedulePolicy clone() {
    return (SchedulePolicy) super.clone();
  }

}


text:
<?php
/**
 * Gender
 *
 * PHP version 7.2
 *
 * @category Class
 * @package  ChannelEngine\Merchant\ApiClient
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * ChannelEngine Merchant API
 *
 * ChannelEngine API for merchants
 *
 * The version of the OpenAPI document: 2.9.9
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 5.1.1
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace ChannelEngine\Merchant\ApiClient\Model;
use \ChannelEngine\Merchant\ApiClient\ObjectSerializer;

/**
 * Gender Class Doc Comment
 *
 * @category Class
 * @package  ChannelEngine\Merchant\ApiClient
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class Gender
{
    /**
     * Possible values of this enum
     */
    const MALE = 'MALE';
    const FEMALE = 'FEMALE';
    const NOT_APPLICABLE = 'NOT_APPLICABLE';

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public static function getAllowableEnumValues()
    {
        return [
            self::MALE,
            self::FEMALE,
            self::NOT_APPLICABLE,
        ];
    }
}


text:
require 'rails_helper'

describe UserPolicy do
  let!(:ordinary_user) { FactoryGirl.create(:user) }
  let!(:admin_user) { FactoryGirl.create(:admin_user) }

  describe 'scope' do
    subject(:policy_scope) do
      # The user variable is set within each example group.
      UserPolicy::Scope.new(user, User.all).resolve
    end

    # Users with :user see no records
    context 'given a user with :user role' do
      let(:user) { ordinary_user }
      it 'do not list any users' do
        expect(policy_scope).to eq []
      end
    end

    context 'given a user with :admin role' do
      let(:user) { admin_user }
      it 'lists all users' do
        expect(policy_scope).to include(ordinary_user, admin_user)
      end
    end
  end

  describe 'policies' do
    subject { UserPolicy.new(logged_in_user, record) }
    # Pundit policies take a model instead of a record when there isn't a
    # record (e.g., within the #new action)
    let(:record) { User }

    context 'given an unauthenticated user' do
      let(:logged_in_user) { nil }

      %i[new create show edit update destroy].each do |method|
        it { is_expected.not_to permit(method) }
      end
    end

    context 'given a user with :user role' do
      let(:logged_in_user) { ordinary_user }

      %i[new create show edit update destroy].each do |method|
        it { is_expected.not_to permit(method) }
      end
    end

    context 'given a user with :admin role' do
      let(:logged_in_user) { admin_user }

      %i[new create show edit update destroy].each do |method|
        it { is_expected.to permit(method) }
      end
    end
  end
end


text:
modal-id: 1
modal-type: planning
date: 2014-07-18
fa-icon: plane
project-date: April 2014
title: Getting here
caption: come
---

Flying

 Vista is about halfway between Orange County and San Diego. We recommend either the Santa Ana/Orange County/John Wayne airport (SNA)
    or San Diego airport (SAN). Both are about an hour from the Wood Shed. Los Angeles (LAX) is also an option,
    but is further away, about 2 hours from the Wood Shed.

 Getting around

    If you fly into San Diego, you can take the Coaster train to Oceanside or Carlsbad Village and then you can cab/Lyft
    it to Vista from there (~20 minutes). Otherwise, we would recommend renting a car or taking Lyft (or Uber, if you
    must). Public transportation exists but is not super efficient.


text:
.. index::
   single: Symfony Framework Best Practices

The Symfony Framework Best Practices
====================================

The Symfony Framework is well-known for being *really* flexible and is used
to build micro-sites, enterprise applications that handle billions of connections
and even as the basis for *other* frameworks. Since its release in July 2011,
the community has learned a lot about what's possible and how to do things *best*.

These community resources - like blog posts or presentations - have created
an unofficial set of recommendations for developing Symfony applications.
Unfortunately, a lot of these recommendations are unneeded for web applications.
Much of the time, they unnecessarily overcomplicate things and don't follow the
original pragmatic philosophy of Symfony.

What is this Guide About?
-------------------------

This guide aims to fix that by describing the **best practices for developing
web apps with the Symfony full-stack Framework**. These are best practices that
fit the philosophy of the framework as envisioned by its original creator
`Fabien Potencier`_.

.. note::

    **Best practice** is a noun that means *"a well defined procedure that is
    known to produce near-optimum results"*. And that's exactly what this
    guide aims to provide. Even if you don't agree with every recommendation,
    we believe these will help you build great applications with less complexity.

This guide is **specially suited** for:

* Websites and web applications developed with the full-stack Symfony Framework.

For other situations, this guide might be a good **starting point** that you can
then **extend and fit to your specific needs**:

* Bundles shared publicly to the Symfony community;
* Advanced developers or teams who have created their own standards;
* Some complex applications that have highly customized requirements;
* Bundles that may be shared internally within a company.

We know that old habits die hard and some of you will be shocked by some
of these best practices. But by following these, you'll be able to develop
apps faster, with less complexity and with the same or even higher quality.
It's also a moving target that will continue to improve.

Keep in mind that these are **optional recommendations** that you and your
team may or may not follow to develop Symfony applications. If you want to
continue using your own best practices and methodologies, you can of course
do it. Symfony is flexible enough to adapt to your needs. That will never
change.

Who this Book Is for (Hint: It's not a Tutorial)
------------------------------------------------

Any Symfony developer, whether you are an expert or a newcomer, can read this
guide. But since this isn't a tutorial, you'll need some basic knowledge of
Symfony to follow everything. If you are totally new to Symfony, welcome!
Start with :doc:`The Quick Tour </quick_tour/the_big_picture>` tutorial first.

We've deliberately kept this guide short. We won't repeat explanations that
you can find in the vast Symfony documentation, like discussions about Dependency
Injection or front controllers. We'll solely focus on explaining how to do
what you already know.

The Application
---------------

In addition to this guide, a sample application has been developed with all these
best practices in mind. This project, called the Symfony Demo application, can
be obtained through the Symfony Installer. First, `download and install`_ the
installer and then execute this command to download the demo application:

.. code-block:: bash

    $ symfony demo

**The demo application is a simple blog engine**, because that will allow us to
focus on the Symfony concepts and features without getting buried in difficult
implementation details. Instead of developing the application step by step in
this guide, you'll find selected snippets of code through the chapters.

Don't Update Your Existing Applications
---------------------------------------

After reading this handbook, some of you may be considering refactoring your
existing Symfony applications. Our recommendation is sound and clear: **you
should not refactor your existing applications to comply with these best
practices**. The reasons for not doing it are various:

* Your existing applications are not wrong, they just follow another set of
  guidelines;
* A full codebase refactorization is prone to introduce errors in your
  applications;
* The amount of work spent on this could be better dedicated to improving
  your tests or adding features that provide real value to the end users.

.. _`Fabien Potencier`: https://connect.sensiolabs.com/profile/fabpot
.. _`download and install`: https://symfony.com/download


text:
from asciimatics.effects import Effect
from asciimatics.exceptions import StopApplication, NextScene

class MockEffect(Effect):
    """
    Dummy Effect use for some UTs.
    """
    def __init__(self, count=10, stop=True, swallow=False, next_scene=None,
                 frame_rate=1, stop_frame=5, **kwargs):
        """
        :param count: When to stop effect
        :param stop: Whether to stop the application or skip to next scene.
        :param swallow: Whether to swallow any events or not.
        :param next_scene: The next scene to move to (if stop=False)
        :param frame_rate: The frame rate for updates.
        """
        super(MockEffect, self).__init__(None, **kwargs)
        self.stop_called = False
        self.reset_called = False
        self.event_called = False
        self.save_called = False
        self.update_called = False
        self._count = count
        self._stop = stop
        self._swallow = swallow
        self._next_scene = next_scene
        self._frame_rate = frame_rate

        # Ugly hack to stop clash with underlying Effect definition.  Sorry.
        self._my_stop_frame = stop_frame

    @property
    def stop_frame(self):
        self.stop_called = True
        return self._my_stop_frame

    @property
    def frame_update_count(self):
        return self._frame_rate

    def _update(self, frame_no):
        self.update_called = True
        self._count -= 1
        if self._count <= 0:
            if self._stop:
                raise StopApplication("End of test")
            else:
                raise NextScene(self._next_scene)

    def reset(self):
        self.reset_called = True

    def process_event(self, event):
        self.event_called = True
        return None if self._swallow else event

    def save(self):
        self.save_called = True


text:
layout: article
title: "First board assembled and powered-up, update / 1"
categories: articles
author: plinio_seniore
excerpt: "Marco has just powered the RS485 board."
tags: [arduino, ethermania, rs485, relay]
modified: 2013-12-05
image:
  feature:
  teaser: 2013-12/firstpowerup-teaser.jpg
ads: false
redirect_from: "2013/12/first-board-assembled-and-powered-up.html"
---

Starting from a [software CAD and a 3D rendering](http://www.souliss.net/2013/09/3d-rendering-for-new-rs-485-boards.html), the LED board is now a prototype. At time of the picture the board was powered and the bootloader installed.

The on-board switching regulator is working fine and the next step is the test of the MOSFET drivers using the shift-registers, that way was inspired by ShiftPWM and allow a single ATmega328 to drive the 12 sink output (2.5A) channels.
After it will be the time for the RS485 driver and then we will start testing the boards with Souliss.

![](http://souliss.net/images/2013-12/firstpowerup.JPG?raw=true)

The board carry-out a large current value (up to 30 A) and for that reason has two ground planes connected in a single point, where the LED power supply will close its loop.

This is probably the first single board that is born with the idea of a complete tool for LED lighting in an house. It will support the new auto-detection feature introduced in [release Alpha 5](http://www.souliss.net/2013/11/lets-jump-in-alpha-5.html) giving multiple control of all the strips around the house with a single point of control.

Here the first power-up of a couple of LED strips, then we will move to heavy load of the board and communication on the bus.


text:
/**
 * Autogenerated by Thrift for thrift/compiler/test/fixtures/lazy_deserialization/src/simple.thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated @nocommit
 */
#pragma once

#include "thrift/compiler/test/fixtures/lazy_deserialization/gen-cpp2/simple_metadata.h"
#include <thrift/lib/cpp2/visitation/visit_union.h>

namespace apache {
namespace thrift {
namespace detail {

} // namespace detail
} // namespace thrift
} // namespace apache


text:
.github/workflows/ci.yml

TODO: The rest..


text:
<?php

namespace Greg\Orm\Dialect;

class MysqlDialect extends SqlDialect
{
    /**
     * @param string $sql
     *
     * @return string
     */
    public function lockForUpdate(string $sql): string
    {
        return $sql . ' FOR UPDATE';
    }

    /**
     * @param string $sql
     *
     * @return string
     */
    public function lockForShare(string $sql): string
    {
        return $sql . ' FOR SHARE';
    }

    public function concat(array $values, string $delimiter = ''): string
    {
        if (count($values) > 1) {
            if ($delimiter) {
                return 'concat_ws(' . $delimiter . ', ' . implode(', ', $values) . ')';
            }

            return 'concat(' . implode(', ', $values) . ')';
        }

        return array_shift($values);
    }
}


text:
package rr.meta;

public class InterruptInfo extends OperationInfo {

	public InterruptInfo(int id, SourceLocation loc, MethodInfo enclosing) {
		super(id, loc, "interrupt", enclosing);
	}

	@Override
	protected String computeKey() {
		return MetaDataInfoKeys.getInterruptKey(this.getLoc());
	}

	@Override
	public void accept(MetaDataInfoVisitor v) {
		v.visit(this);
	}

}


text:
<?php

namespace vova07\users\controllers;

use vova07\users\models\frontend\ActivationForm;
use vova07\users\models\frontend\RecoveryConfirmationForm;
use vova07\users\models\frontend\RecoveryForm;
use vova07\users\models\frontend\ResendForm;
use vova07\users\models\frontend\User;
use vova07\users\models\LoginForm;
use vova07\users\models\Profile;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;
use yii\widgets\ActiveForm;
use Yii;

/**
 * Controller only for guest users.
 */
class GuestController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['?']
                    ]
                ]
            ]
        ];
    }

    /**
     * Sign Up page.
     * If record will be successful created, user will be redirected to home page.
     */
    public function actionSignup()
    {
        $user = new User(['scenario' => 'signup']);
        $profile = new Profile();

        if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
            if ($user->validate() && $profile->validate()) {
                $user->populateRelation('profile', $profile);
                if ($user->save(false)) {
                    if ($this->module->requireEmailConfirmation === true) {
                        Yii::$app->session->setFlash(
                            'success',
                            Yii::t(
                                'users',
                                'FRONTEND_FLASH_SUCCESS_SIGNUP_WITHOUT_LOGIN',
                                [
                                    'url' => Url::toRoute('resend')
                                ]
                            )
                        );
                    } else {
                        Yii::$app->user->login($user);
                        Yii::$app->session->setFlash(
                            'success',
                            Yii::t('users', 'FRONTEND_FLASH_SUCCESS_SIGNUP_WITH_LOGIN')
                        );
                    }
                    return $this->goHome();
                } else {
                    Yii::$app->session->setFlash('danger', Yii::t('users', 'FRONTEND_FLASH_FAIL_SIGNUP'));
                    return $this->refresh();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($user);
            }
        }

        return $this->render(
            'signup',
            [
                'user' => $user,
                'profile' => $profile
            ]
        );
    }

    /**
     * Resend page.
     * Resend email confirmation token.
     */
    public function actionResend()
    {
        $model = new ResendForm();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                if ($model->resend()) {
                    Yii::$app->session->setFlash('success', Yii::t('users', 'FRONTEND_FLASH_SUCCESS_RESEND'));
                    return $this->goHome();
                } else {
                    Yii::$app->session->setFlash('danger', Yii::t('users', 'FRONTEND_FLASH_FAIL_RESEND'));
                    return $this->refresh();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

        return $this->render(
            'resend',
            [
                'model' => $model
            ]
        );
    }

    /**
     * Log In page.
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            $this->goHome();
        }

        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                if ($model->login()) {
                    return $this->goBack();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

        return $this->render(
            'login',
            [
                'model' => $model
            ]
        );
    }

    /**
     * Activation page.
     * Activate a new user.
     *
     * @param string $key Activation token.
     */
    public function actionActivation($key)
    {
        $model = new ActivationForm(['secure_key' => $key]);

        if ($model->validate() && $model->activation()) {
            Yii::$app->session->setFlash('success', Yii::t('users', 'FRONTEND_FLASH_SUCCESS_ACTIVATION'));
        } else {
            Yii::$app->session->setFlash('danger', Yii::t('users', 'FRONTEND_FLASH_FAIL_ACTIVATION'));
        }

        return $this->goHome();
    }

    /**
     * Recovery page.
     * Request password recovery.
     */
    public function actionRecovery()
    {
        $model = new RecoveryForm();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                if ($model->recovery()) {
                    Yii::$app->session->setFlash('success', Yii::t('users', 'FRONTEND_FLASH_SUCCESS_RECOVERY'));
                    return $this->goHome();
                } else {
                    Yii::$app->session->setFlash('danger', Yii::t('users', 'FRONTEND_FLASH_FAIL_RECOVERY'));
                    return $this->refresh();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

        return $this->render(
            'recovery',
            [
                'model' => $model
            ]
        );
    }

    /**
     * Recovery confirmation page.
     * Confirm password recovery request.
     *
     * @param string $key Confirmation token
     */
    public function actionRecoveryConfirmation($key)
    {
        $model = new RecoveryConfirmationForm(['secure_key' => $key]);

        if (!$model->isValidSecureKey()) {
            Yii::$app->session->setFlash(
                'danger',
                Yii::t('users', 'FRONTEND_FLASH_FAIL_RECOVERY_CONFIRMATION_WITH_INVALID_KEY')
            );
            return $this->goHome();
        }

        if ($model->load(Yii::$app->request->post())) {
            if ($model->validate()) {
                if ($model->recovery()) {
                    Yii::$app->session->setFlash(
                        'success',
                        Yii::t('users', 'FRONTEND_FLASH_SUCCESS_RECOVERY_CONFIRMATION')
                    );
                    return $this->goHome();
                } else {
                    Yii::$app->session->setFlash(
                        'danger',
                        Yii::t('users', 'FRONTEND_FLASH_FAIL_RECOVERY_CONFIRMATION')
                    );
                    return $this->refresh();
                }
            } elseif (Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

        return $this->render(
            'recovery-confirmation',
            [
                'model' => $model
            ]
        );

    }
}


text:
#pragma once

#include "Tool.h"
#include "phonelib.h"

struct CallStateMsg
{
	int account_id;
	int call_id;
	string src;
	string dst;
	PHONELIB_CALL_STATE state;
	int sipcode;
	string response;
};

struct RegStateMsg
{
	int account_id;
	PHONELIB_REG_STATE state;
	int sipcode;
	string response;
};

class SipphoneClient
{
private:
	int m_account_id;
	int m_call_id;
	bool m_is_initial;
	bool m_is_register;
	bool m_is_talking;
	Logger m_Logger;

public:
	void process_reg_state(int account_id, PHONELIB_REG_STATE state, int sip_response_code, const char *sip_response_desc);
	void process_call_state(int account_id, int call_id, const char *srcnum, const char *dstnum, PHONELIB_CALL_STATE state, int sip_response_code, const char *sip_response_desc);

public:
	SipphoneClient(void);
	~SipphoneClient(void);
	int SipInitial();
	int SipUnInitial();
	int SipRegister(const char *server, int server_port, const char *sip_account, const char *sip_password, int timeout);
	int SipUnRegister();
	int SipMakecall(const char *dest);
	int SipAnswercall();
	int SipHangupcall();
	int SipHoldcall();
	int SipUnholdcall();
	int SipSenddtmf(const char *dtmf);
};


text:
/**
 * @file   CivetWebExtension.cpp
 * @brief  CivetWebExtension class implementation.
 * @author zer0
 * @date   2019-06-17
 */

#include <libtbag/http/CivetWebExtension.hpp>
#include <libtbag/string/StringUtils.hpp>

#include <cassert>
#include <sstream>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace http {

int mg_write_string(mg_connection * conn, std::string const & text)
{
    return mg_write(conn, text.c_str(), text.size());
}

std::string getRequestLine(mg_connection const * conn)
{
    assert(conn != nullptr);
    std::stringstream ss;
    ss << mg_get_request_info(conn)->request_method << SP
       << mg_get_request_info(conn)->request_uri << SP
       << HTTP << "/" << mg_get_request_info(conn)->http_version;
    return ss.str();
}

HttpUniqueHeaders getHeaders(mg_connection const * conn, bool lower_key)
{
    assert(conn != nullptr);

    auto const size = mg_get_request_info(conn)->num_headers;
    auto const * headers = mg_get_request_info(conn)->http_headers;
    assert(headers != nullptr);

    HttpUniqueHeaders result;
    for (auto i = 0; i < size; ++i) {
        std::string name;
        if (headers[i].name != nullptr) {
            if (lower_key) {
                name = libtbag::string::lower(headers[i].name);
            } else {
                name = headers[i].name;
            }
            std::string value;
            if (headers[i].value != nullptr) {
                value = headers[i].value;
            }
            result.emplace(std::move(name), std::move(value));
        }
    }
    return result;
}

TBAG_CONSTEXPR static std::size_t TEMP_BUFFER_SIZE = (4*1024);

std::string getBody(mg_connection * conn)
{
    assert(conn != nullptr);

    auto const content_length = mg_get_request_info(conn)->content_length;
    if (content_length <= 0) {
        return {};
    }

    std::stringstream ss;
    std::size_t total_read_size = 0;
    char buffer[TEMP_BUFFER_SIZE] = {0,};

    while (total_read_size < static_cast<std::size_t>(content_length)) {
        auto remaining_size = static_cast<std::size_t>(content_length) - total_read_size;
        if (remaining_size > TEMP_BUFFER_SIZE) {
            remaining_size = TEMP_BUFFER_SIZE;
        }

        auto const read_size = mg_read(conn, buffer, remaining_size);
        if (read_size <= 0) {
            break;
        }

        ss.write(buffer, read_size);
        total_read_size += read_size;
    }

    return ss.str();
}

Json::Value getJsonBody(mg_connection * conn)
{
    return libtbag::dom::json::getJsonValue(getBody(conn));
}

} // namespace http

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------


text:
<?php  namespace Palmabit\Library\ImportExport;

use ArrayIterator;
use Palmabit\Library\ImportExport\Reader;
use SplFileObject;

/**
 * Class DbCsvFileReader
 *
 * @author jacopo beschi j.beschi@palmabit.com
 */
class CsvFileReader extends Reader
{
  /**
   * @var \SplFileObject
   */
  protected $spl_file_object;
  /**re
   *
   * @var string
   */
  protected $delimiter = ";";
  /**
   * @var Array
   */
  protected $columns_name;

  /**
   * Open stream from a source
   *      A source can be anything: for instance a db, a file, or a socket
   *
   * @param String $path
   * @return void
   * @throws \Palmabit\Library\Exceptions\CannotOpenFileException
   */
  public function open($path)
  {
    $this->convertToLF($path);
    $this->spl_file_object = new SplFileObject($path);
    $this->spl_file_object->setCsvControl($this->delimiter);
    $this->columns_name = $this->spl_file_object->fgetcsv();
  }

  /**
   * Reads a single element from the source
   *    then return a Object instance
   *
   * @return \StdClass|false object instance
   */
  public function readElement()
  {
    $csv_line_data = $this->spl_file_object->fgetcsv();
    if($csv_line_data)
    {
      $csv_line_data[0] = $this->convertToUtf8($csv_line_data);
      if($this->isValidLine($csv_line_data))
      {
        $csv_line         = array_combine($this->columns_name, $csv_line_data);
        // we cast it to StdClass
        return (object)$csv_line;
      }
    }

    return false;
  }

  /**
   * @param $csv_line_data
   * @return mixed
   */
  protected function isValidLine($csv_line_data)
  {
    return $csv_line_data[0] && ! empty($csv_line_data[0]);
  }

  /**
   * Read all the objects from the source
   *
   * @return \ArrayIterator
   */
  public function readElements()
  {
    $iterator = new ArrayIterator;
    do
    {
      $object = $this->readElement();
      if($object) $iterator->append($object);
    } while((boolean)$object);

    $this->objects = $iterator;
    return $this->objects;
  }

  /**
   * @return string
   */
  public function getDelimiter()
  {
    return $this->delimiter;
  }

  /**
   * @param string $delimiter
   */
  public function setDelimiter($delimiter)
  {
    $this->delimiter = $delimiter;
  }

  /**
   * @param $csv_line_data
   * @return bool|mixed|string
   */
  protected function convertToUtf8($csv_line_data)
  {
    return mb_convert_encoding($csv_line_data[0], "UTF-8");
  }

  protected function convertToLF($path)
  {
    $cr   = "\r"; // Carriage Return: Mac
    $lf   = "\n"; // Line Feed: Unix
    $crlf = "\r\n"; // Carriage Return and Line Feed: Windows

    $text = file_get_contents($path);

    $text = $this->convertCharacters($cr, $lf, $text);
    $text = $this->convertCharacters($crlf, $lf, $text);

    file_put_contents($path, $text);
  }

  /**
   * @param $cr
   * @param $lf
   * @param $text
   * @return mixed
   */
  protected function convertCharacters($cr, $lf, $text)
  {
    return str_replace($cr, $lf, $text);
  }
}


text:
namespace BooCompiler.Tests
{
	using NUnit.Framework;

	[TestFixture]
	public class GeneratorsIntegrationTestFixture : AbstractCompilerTestCase
	{

		[Test]
		public void generator_calling_external_super_with_arguments_2()
		{
			RunCompilerTestCase(@"generator-calling-external-super-with-arguments-2.boo");
		}

		[Test]
		public void generator_calling_external_super_with_arguments()
		{
			RunCompilerTestCase(@"generator-calling-external-super-with-arguments.boo");
		}

		[Test]
		public void generator_calling_super_with_arguments_2()
		{
			RunCompilerTestCase(@"generator-calling-super-with-arguments-2.boo");
		}

		[Test]
		public void generator_calling_super_with_arguments()
		{
			RunCompilerTestCase(@"generator-calling-super-with-arguments.boo");
		}

		[Test]
		public void generator_calling_super()
		{
			RunCompilerTestCase(@"generator-calling-super.boo");
		}

		[Test]
		public void generator_of_static_class_is_transient()
		{
			RunCompilerTestCase(@"generator-of-static-class-is-transient.boo");
		}

		[Test]
		public void generator_of_transient_class_is_transient()
		{
			RunCompilerTestCase(@"generator-of-transient-class-is-transient.boo");
		}

		[Test]
		public void generators_1()
		{
			RunCompilerTestCase(@"generators-1.boo");
		}

		[Test]
		public void generators_10()
		{
			RunCompilerTestCase(@"generators-10.boo");
		}

		[Test]
		public void generators_11()
		{
			RunCompilerTestCase(@"generators-11.boo");
		}

		[Test]
		public void generators_12()
		{
			RunCompilerTestCase(@"generators-12.boo");
		}

		[Test]
		public void generators_13()
		{
			RunCompilerTestCase(@"generators-13.boo");
		}

		[Test]
		public void generators_14()
		{
			RunCompilerTestCase(@"generators-14.boo");
		}

		[Test]
		public void generators_15()
		{
			RunCompilerTestCase(@"generators-15.boo");
		}

		[Test]
		public void generators_16()
		{
			RunCompilerTestCase(@"generators-16.boo");
		}

		[Test]
		public void generators_17()
		{
			RunCompilerTestCase(@"generators-17.boo");
		}

		[Test]
		public void generators_18()
		{
			RunCompilerTestCase(@"generators-18.boo");
		}

		[Test]
		public void generators_19()
		{
			RunCompilerTestCase(@"generators-19.boo");
		}

		[Test]
		public void generators_2()
		{
			RunCompilerTestCase(@"generators-2.boo");
		}

		[Test]
		public void generators_20()
		{
			RunCompilerTestCase(@"generators-20.boo");
		}

		[Test]
		public void generators_21()
		{
			RunCompilerTestCase(@"generators-21.boo");
		}

		[Test]
		public void generators_3()
		{
			RunCompilerTestCase(@"generators-3.boo");
		}

		[Test]
		public void generators_4()
		{
			RunCompilerTestCase(@"generators-4.boo");
		}

		[Test]
		public void generators_5()
		{
			RunCompilerTestCase(@"generators-5.boo");
		}

		[Test]
		public void generators_6()
		{
			RunCompilerTestCase(@"generators-6.boo");
		}

		[Test]
		public void generators_7()
		{
			RunCompilerTestCase(@"generators-7.boo");
		}

		[Test]
		public void generators_8()
		{
			RunCompilerTestCase(@"generators-8.boo");
		}

		[Test]
		public void generators_9()
		{
			RunCompilerTestCase(@"generators-9.boo");
		}

		[Ignore("BOO-759 - generic generator methods are not supported")][Test]
		public void generic_generator_1()
		{
			RunCompilerTestCase(@"generic-generator-1.boo");
		}

		[Test]
		public void label_issue_1()
		{
			RunCompilerTestCase(@"label-issue-1.boo");
		}

		[Test]
		public void list_generators_1()
		{
			RunCompilerTestCase(@"list-generators-1.boo");
		}

		[Test]
		public void list_generators_2()
		{
			RunCompilerTestCase(@"list-generators-2.boo");
		}

		[Test]
		public void list_generators_3()
		{
			RunCompilerTestCase(@"list-generators-3.boo");
		}

		[Test]
		public void list_generators_4()
		{
			RunCompilerTestCase(@"list-generators-4.boo");
		}

		[Test]
		public void list_generators_5()
		{
			RunCompilerTestCase(@"list-generators-5.boo");
		}

		[Test]
		public void to_string()
		{
			RunCompilerTestCase(@"to-string.boo");
		}

		[Test]
		public void yield_1()
		{
			RunCompilerTestCase(@"yield-1.boo");
		}

		[Test]
		public void yield_10()
		{
			RunCompilerTestCase(@"yield-10.boo");
		}

		[Test]
		public void yield_11()
		{
			RunCompilerTestCase(@"yield-11.boo");
		}

		[Test]
		public void yield_12()
		{
			RunCompilerTestCase(@"yield-12.boo");
		}

		[Test]
		public void yield_13()
		{
			RunCompilerTestCase(@"yield-13.boo");
		}

		[Test]
		public void yield_14()
		{
			RunCompilerTestCase(@"yield-14.boo");
		}

		[Test]
		public void yield_15()
		{
			RunCompilerTestCase(@"yield-15.boo");
		}

		[Test]
		public void yield_16()
		{
			RunCompilerTestCase(@"yield-16.boo");
		}

		[Test]
		public void yield_17()
		{
			RunCompilerTestCase(@"yield-17.boo");
		}

		[Test]
		public void yield_2()
		{
			RunCompilerTestCase(@"yield-2.boo");
		}

		[Test]
		public void yield_3()
		{
			RunCompilerTestCase(@"yield-3.boo");
		}

		[Test]
		public void yield_4()
		{
			RunCompilerTestCase(@"yield-4.boo");
		}

		[Test]
		public void yield_5()
		{
			RunCompilerTestCase(@"yield-5.boo");
		}

		[Test]
		public void yield_6()
		{
			RunCompilerTestCase(@"yield-6.boo");
		}

		[Test]
		public void yield_7()
		{
			RunCompilerTestCase(@"yield-7.boo");
		}

		[Test]
		public void yield_8()
		{
			RunCompilerTestCase(@"yield-8.boo");
		}

		[Test]
		public void yield_9()
		{
			RunCompilerTestCase(@"yield-9.boo");
		}

		[Test]
		public void yield_null_as_IEnumerator()
		{
			RunCompilerTestCase(@"yield-null-as-IEnumerator.boo");
		}

		[Test]
		public void yield_null()
		{
			RunCompilerTestCase(@"yield-null.boo");
		}

		override protected string GetRelativeTestCasesPath()
		{
			return "integration/generators";
		}
	}
}


text:
/*
 * Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    ///
    /// Container for the parameters to the ReplaceNetworkAclAssociation operation.
    /// Changes which network ACL a subnet is associated with. By default when you create
    /// a subnet, it's automatically associated with the default network ACL. For more information
    /// about network ACLs, see Network
    /// ACLs in the Amazon Virtual Private Cloud User Guide.
    ///
    public partial class ReplaceNetworkAclAssociationRequest : AmazonEC2Request
    {
        private string _associationId;
        private string _networkAclId;

        ///
        /// Gets and sets the property AssociationId.
        /// <para>
        /// The ID of the current association between the original network ACL and the subnet.
        /// </para>
        ///
        public string AssociationId
        {
            get { return this._associationId; }
            set { this._associationId = value; }
        }

        // Check to see if AssociationId property is set
        internal bool IsSetAssociationId()
        {
            return this._associationId != null;
        }

        ///
        /// Gets and sets the property NetworkAclId.
        /// <para>
        /// The ID of the new network ACL to associate with the subnet.
        /// </para>
        ///
        public string NetworkAclId
        {
            get { return this._networkAclId; }
            set { this._networkAclId = value; }
        }

        // Check to see if NetworkAclId property is set
        internal bool IsSetNetworkAclId()
        {
            return this._networkAclId != null;
        }

    }
}


text:
define(['knockout'],
    function (ko) {
        var vm = {
            userName:ko.observable(""),
            password:ko.observable(""),
            confirmPassword:ko.observable(""),
            register:register
        };

        return vm;

        function register(){

        }
    }
);


text:
local lu = require 'luaunit'

lu.test("Basic test.", function()

end)

--[[

lu.test("Description", function()

end, { setUp = function() end })

lu.test("Description", function()

end, { setUp = function() end, tearDown = function() end})

local suite = {}

suite.setUp = function()
end

suite.tearDown = function()
end

suite.basicTest1 = function()
end

suite.basicTest = {
    description = "",
    func = function()
    end
}

lu.run(suite)
]]

lu.run()


text:
package edu.sampleu.kim.api.reference;

import org.junit.Test;

/**
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class ReferenceCampusTypeBlanketAppBkMrkAft extends ReferenceCampusTypeBlanketAppAftBase {

    @Override
    public String getBookmarkUrl() {
        return BOOKMARK_URL;
    }

    @Test
    public void testReferenceCampusTypeBlanketAppBookmark() throws Exception {
        testReferenceCampusTypeBlanketAppBookmark(this);
    }
}