text:
package util

import (
	"net"
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

// SliceContains checks if slice contains value
func SliceContains(slice []string, item string) bool {
	set := make(map[string]struct{}, len(slice))
	for _, s := range slice {
		set[s] = struct{}{}
	}
	_, ok := set[item]
	return ok
}

// GetPorts will split the string of comma separated ports and return a list of ports
func GetPorts(ports string) ([]string, error) {
	portList := strings.Split(ports, ",")
	// Handle no port case
	if portList[0] == "" {
		return nil, nil
	}

	for _, port := range portList {
		err := verifyPort(port)

		if err != nil {
			return nil, errors.Wrap(err, "invalid port specified")
		}
	}

	return portList, nil
}

// verifyPort will make sure the port is numeric and within the correct range
func verifyPort(port string) error {
	if port == "" {
		return nil
	}
	portNum, err := strconv.ParseInt(port, 10, 64) //nolint:gomnd
	if err != nil {
		return errors.Wrap(err, "failed to parse port as number")
	}
	if portNum < 0 || portNum > 65535 {
		return errors.Errorf("Port is either below 0 or greater than 65535: %s", port)
	}

	return nil
}

// ensure IP string is in CIDR notation
func cidrNotation(ip string) string {
	if !strings.Contains(ip, "/") {
		return ip + "/32"
	}
	return ip
}

// ParseCIDR Parse IP string to IPNet
func ParseCIDR(ip string) (*net.IPNet, error) {
	cidr := cidrNotation(ip)
	_, ipNet, err := net.ParseCIDR(cidr)
	if err != nil {
		return nil, errors.Wrap(err, "failed to parse CIDR")
	}
	return ipNet, nil
}


text:
package sgdi.pr3.grupo03.situacion1.menus.film;

import sgdi.pr3.grupo03.shared.ConsoleUtil;
import sgdi.pr3.grupo03.situacion1.DBHelper;
import sgdi.pr3.grupo03.situacion1.menus.Menu;
import sgdi.pr3.grupo03.situacion1.menus.control.ChooseAction;
import sgdi.pr3.grupo03.situacion1.menus.control.MainMenu;
import sgdi.pr3.grupo03.situacion1.model.Film;

public class ModifyFilm extends Menu<String> {

	@Override
	public String draw() {
		System.out
				.println("Inserta el nombre de la película que vas a modificar.");

		return ConsoleUtil.getString();
	}

	@Override
	public void input(String filmTitle) {
		Film film = DBHelper.getFilmByTitle(filmTitle);
		if (film == null) {
			System.out
					.println("No se ha encontrado ninguna película con ese título.");
			controller.setMenu(ChooseAction.class, Film.class);
		} else {
			try {

				Film modifiedFilm = ConsoleUtil.modifyObject(film, Film.class);
				if (!DBHelper.updateFilm(modifiedFilm)) {
					System.out
							.println("La película no se ha modificado correctamente.");
					controller.setMenu(ChooseAction.class, Film.class);
					return;
				} else {
					System.out.println("Película modificada correctamente.");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			controller.setMenu(MainMenu.class);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
@import JRSwizzle;

@implementation UIView (JLInit)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSError *error;
        BOOL result = [[self class] jr_swizzleMethod:@selector(init) withMethod:@selector(jl_init) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }

        result = [[self class] jr_swizzleMethod:@selector(initWithCoder:) withMethod:@selector(jl_initWithCoder:) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }

        result = [[self class] jr_swizzleMethod:@selector(initWithFrame:) withMethod:@selector(jl_initWithFrame:) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }

        result = [[self class] jr_swizzleMethod:@selector(layoutSubviews) withMethod:@selector(jl_layoutSubviews) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }
    });
}

- (instancetype)jl_init {
    id obj = [self jl_init];
    if (obj) {
        if ([obj respondsToSelector:@selector(initView)]) {
            [obj initView];
        }
    }
    return obj;
}

- (instancetype)jl_initWithCoder:(NSCoder *)aDecoder {
    id obj = [self jl_initWithCoder:aDecoder];
    if (self) {
        if ([obj respondsToSelector:@selector(initView)]) {
            [obj initView];
        }
    }
    return obj;
}

- (instancetype)jl_initWithFrame:(CGRect)frame {
    id obj = [self jl_initWithFrame:frame];
    if (self) {
        if ([obj respondsToSelector:@selector(initView)]) {
            [obj initView];
        }
    }
    return obj;
}

- (void)jl_layoutSubviews {
    [self jl_layoutSubviews];

    if ([self respondsToSelector:@selector(setupLayoutConstraint)]) {
        [self setupLayoutConstraint];
    }
}
@end


text:
package org.apache.hadoop.net;

import java.io.IOException;

/**
 * Exception thrown by HopsSSLSocketFactory in case of
 * missing certificate
 */
public class SSLCertificateException extends IOException {
  private static final long serialVersionUID = 1L;

  public SSLCertificateException() {
    super();
  }

  public SSLCertificateException(String message) {
    super(message);
  }

  public SSLCertificateException(Throwable cause) {
    super(cause);
  }

  public SSLCertificateException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
<?xml version="1.0"?>
<ruleset name="Benjamin ruleset"
    xmlns="http://pmd.sf.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sf.net/ruleset/2.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd">

  <description>Additional production code ruleset</description>

  <exclude-pattern>.*/src/test/.*</exclude-pattern>

  <rule ref="rulesets/java/optimizations.xml"/>
  <rule ref="rulesets/java/comments.xml"/>
  <rule ref="rulesets/java/comments.xml/CommentSize">
    <properties>
      <property name="maxLineLength" value="100"/>
      <!-- Default limit of 6 isn't quite reasonable -->
      <!-- Also, the rule counts @returns, @throws, @param as lines -->
      <property name="maxLines" value="15"/>
    </properties>
  </rule>
</ruleset>


text:
Sequel.migration do
  change do
    add_column :albums, :country_name, String
  end
end


text:
package com.jorisaerts.eclipse.rcp.environment.eclipse.debug.internal;

import java.util.function.BiConsumer;
import java.util.function.Function;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.widgets.Composite;

/**
 * Borrowed code...
 */
public class TextGetSetEditingSupport<T> extends EditingSupport {
	private final Function<T, String> getter;
	private final BiConsumer<T, String> setter;
	private final ColumnViewer viewer;

	public TextGetSetEditingSupport(final ColumnViewer viewer, final Function<T, String> getter, final BiConsumer<T, String> setter) {
		super(viewer);
		this.viewer = viewer;
		this.getter = getter;
		this.setter = setter;

	}

	@Override
	protected CellEditor getCellEditor(final Object element) {
		return new TextCellEditor((Composite) getViewer().getControl());

	}

	@Override
	protected boolean canEdit(final Object element) {
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Object getValue(final Object element) {
		return getter.apply((T) element);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void setValue(final Object element, final Object value) {
		setter.accept((T) element, (String) value);
		viewer.update(element, null);

	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>RNAlib-2.1.9: /home/mescalin/ronny/WORK/ViennaRNA/H/MEA.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

RNAlib-2.1.9

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

Functions

MEA.h File Reference

Computes a MEA (maximum expected accuracy) structure.
More...

   Include dependency graph for MEA.h:

<map name="_2home_2mescalin_2ronny_2WORK_2ViennaRNA_2H_2MEA_8h" id="_2home_2mescalin_2ronny_2WORK_2ViennaRNA_2H_2MEA_8h">
<area shape="rect" id="node2" href="data__structures_8h.html" title="All datastructures and typedefs shared among the Vienna RNA Package can be found here." alt="" coords="40,96,160,123"/><area shape="rect" id="node3" href="energy__const_8h.html" title="energy_const.h" alt="" coords="46,171,153,197"/></map>

Go to the source code of this file.

Functions

float 	MEA (plist *p, char *structure, double gamma)

 	Computes a MEA (maximum expected accuracy) structure.  More...

Detailed Description

Computes a MEA (maximum expected accuracy) structure.

Function Documentation

          float MEA
          (
          plist *
          p,

          char *
          structure,

          double
          gamma

          )

Computes a MEA (maximum expected accuracy) structure.

The algorithm maximizes the expected accuracy

 Higher values of  result in more base pairs of lower probability and thus higher sensitivity. Low values of  result in structures containing only highly likely pairs (high specificity). The code of the MEA function also demonstrates the use of sparse dynamic programming scheme to reduce the time and memory complexity of folding.

H

MEA.h

Generated on Thu Feb 5 2015 15:05:32 for RNAlib-2.1.9 by

     1.8.3.1


text:
package org.assertj.core.api;

import static org.assertj.core.error.ShouldAccept.shouldAccept;
import static org.assertj.core.error.ShouldNotAccept.shouldNotAccept;

import java.util.function.Predicate;

import org.assertj.core.internal.Iterables;
import org.assertj.core.presentation.PredicateDescription;
import org.assertj.core.util.VisibleForTesting;

/**
 * Assertions for {@link Predicate}.
 *
 * @param <PRIMITIVE_PREDICATE> the actual type
 * @param <PRIMITIVE> the type of the wrapped variable in one of the special predicates
 *
 * @author Filip Hrisafov
 */
abstract class AbstractPredicateLikeAssert<SELF extends AbstractPredicateLikeAssert<SELF, PRIMITIVE_PREDICATE, PRIMITIVE>, PRIMITIVE_PREDICATE, PRIMITIVE>
    extends AbstractAssert<SELF, PRIMITIVE_PREDICATE> {

  @VisibleForTesting
  Iterables iterables = Iterables.instance();

  @VisibleForTesting
  Predicate<PRIMITIVE> primitivePredicate;

  protected AbstractPredicateLikeAssert(PRIMITIVE_PREDICATE actual, Predicate<PRIMITIVE> wrappedPredicate,
                                        Class<?> selfType) {
    super(actual, selfType);
    this.primitivePredicate = wrappedPredicate;
  }

  protected SELF acceptsInternal(PRIMITIVE value) {
    isNotNull();
    if (!primitivePredicate.test(value))
      throwAssertionError(shouldAccept(primitivePredicate, value, PredicateDescription.GIVEN));
    return myself;
  }

  protected SELF rejectsInternal(PRIMITIVE value) {
    isNotNull();
    if (primitivePredicate.test(value))
      throwAssertionError(shouldNotAccept(primitivePredicate, value, PredicateDescription.GIVEN));
    return myself;
  }

  protected SELF acceptsAllInternal(Iterable<? extends PRIMITIVE> values) {
    isNotNull();
    iterables.assertAllMatch(info, values, primitivePredicate, PredicateDescription.GIVEN);
    return myself;
  }

  protected SELF rejectsAllInternal(Iterable<? extends PRIMITIVE> values) {
    isNotNull();
    iterables.assertNoneMatch(info, values, primitivePredicate, PredicateDescription.GIVEN);
    return myself;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
using OmniSharp.Roslyn;

namespace OmniSharp
{
    public partial class OmnisharpController
    {
        [HttpPost("gotodefinition")]
        public async Task<GotoDefinitionResponse> GotoDefinition(GotoDefinitionRequest request)
        {
            var quickFixes = new List<QuickFix>();

            var document = _workspace.GetDocument(request.FileName);
            var response = new GotoDefinitionResponse();
            if (document != null)
            {
                var semanticModel = await document.GetSemanticModelAsync();
                var syntaxTree = semanticModel.SyntaxTree;
                var sourceText = await document.GetTextAsync();
                var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
                var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);

                if (symbol != null)
                {
                    var location = symbol.Locations.First();

                    if (location.IsInSource)
                    {
                        var lineSpan = symbol.Locations.First().GetMappedLineSpan();
                        response = new GotoDefinitionResponse
                        {
                            FileName = lineSpan.Path,
                            Line = lineSpan.StartLinePosition.Line + 1,
                            Column = lineSpan.StartLinePosition.Character + 1
                        };
                    }
                    else if (location.IsInMetadata && request.WantMetadata)
                    {
                        var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(request.Timeout));
                        var metadataDocument = await MetadataHelper.GetDocumentFromMetadata(document.Project, symbol, cancellationSource.Token);
                        if (metadataDocument != null)
                        {
                            cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(request.Timeout));
                            var metadataLocation = await MetadataHelper.GetSymbolLocationFromMetadata(symbol, metadataDocument, cancellationSource.Token);
                            var lineSpan = metadataLocation.GetMappedLineSpan();

                            response = new GotoDefinitionResponse
                            {
                                Line = lineSpan.StartLinePosition.Line + 1,
                                Column = lineSpan.StartLinePosition.Character + 1,
                                MetadataSource = new MetadataSource()
                                {
                                    AssemblyName = symbol.ContainingAssembly.Name,
                                    ProjectName = document.Project.Name,
                                    TypeName = MetadataHelper.GetSymbolName(symbol)
                                },
                            };
                        }
                    }
                }
            }

            return response;
        }
    }
}


text:
//
// Copyright (C) 2006-2012 Christoph Sommer <christoph.sommer@uibk.ac.at>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

#ifndef __INET_TRACISCENARIOMANAGER_H
#define __INET_TRACISCENARIOMANAGER_H

#include <utility>
#include <map>
#include <list>
#include <sstream>
#include <iomanip>

#include <omnetpp.h>

#include "inet/common/INETDefs.h"
#include "inet/common/geometry/common/Coord.h"
#include "inet/common/ModuleAccess.h"

#ifdef WITH_TRACI

namespace inet {

/**
 * @brief
 * Creates and moves nodes controlled by a TraCI server.
 *
 * If the server is a SUMO road traffic simulation, you can use the
 * TraCIScenarioManagerLaunchd module and sumo-launchd.py script instead.
 *
 * All nodes created thus must have a TraCIMobility submodule.
 *
 * See the Veins website <a href="http://veins.car2x.org/"> for a tutorial, documentation, and publications </a>.
 *
 * @author Christoph Sommer, David Eckhoff, Falko Dressler, Zheng Yao, Tobias Mayer, Alvaro Torres Cortes, Luca Bedogni
 *
 * @see TraCIMobility
 * @see TraCIScenarioManagerLaunchd
 *
 */
class INET_API TraCIScenarioManager : public cSimpleModule
{
  public:
    /**
     * TraCI compatible color container
     */
    struct Color
    {
        Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) : red(red), green(green), blue(blue), alpha(alpha) {}
        uint8_t red;
        uint8_t green;
        uint8_t blue;
        uint8_t alpha;
    };

    enum VehicleSignal {
        VEH_SIGNAL_UNDEF = -1,
        VEH_SIGNAL_NONE = 0,
        VEH_SIGNAL_BLINKER_RIGHT = 1,
        VEH_SIGNAL_BLINKER_LEFT = 2,
        VEH_SIGNAL_BLINKER_EMERGENCY = 4,
        VEH_SIGNAL_BRAKELIGHT = 8,
        VEH_SIGNAL_FRONTLIGHT = 16,
        VEH_SIGNAL_FOGLIGHT = 32,
        VEH_SIGNAL_HIGHBEAM = 64,
        VEH_SIGNAL_BACKDRIVE = 128,
        VEH_SIGNAL_WIPER = 256,
        VEH_SIGNAL_DOOR_OPEN_LEFT = 512,
        VEH_SIGNAL_DOOR_OPEN_RIGHT = 1024,
        VEH_SIGNAL_EMERGENCY_BLUE = 2048,
        VEH_SIGNAL_EMERGENCY_RED = 4096,
        VEH_SIGNAL_EMERGENCY_YELLOW = 8192
    };

    ~TraCIScenarioManager();
    virtual int numInitStages() const { return NUM_INIT_STAGES; }
    virtual void initialize(int stage);
    virtual void finish();
    virtual void handleMessage(cMessage *msg);
    virtual void handleSelfMsg(cMessage *msg);

    std::pair<uint32_t, std::string> commandGetVersion();
    void commandSetSpeedMode(std::string nodeId, int32_t bitset);
    void commandSetSpeed(std::string nodeId, double speed);
    void commandNewRoute(std::string nodeId, std::string roadId);
    void commandSetVehicleParking(std::string nodeId);
    std::string commandGetEdgeId(std::string nodeId);
    std::string commandGetCurrentEdgeOnRoute(std::string nodeId);
    std::string commandGetLaneId(std::string nodeId);
    double commandGetLanePosition(std::string nodeId);
    std::list<std::string> commandGetPlannedEdgeIds(std::string nodeId);
    std::string commandGetRouteId(std::string nodeId);
    std::list<std::string> commandGetRouteEdgeIds(std::string routeId);
    void commandChangeRoute(std::string nodeId, std::string roadId, double travelTime);
    double commandDistanceRequest(Coord position1, Coord position2, bool returnDrivingDistance);
    void commandStopNode(std::string nodeId, std::string roadId, double pos, uint8_t laneid, double radius, double waittime);
    void commandSetTrafficLightProgram(std::string trafficLightId, std::string program);
    void commandSetTrafficLightPhaseIndex(std::string trafficLightId, int32_t index);
    std::list<std::string> commandGetPolygonIds();
    std::string commandGetPolygonTypeId(std::string polyId);
    std::list<Coord> commandGetPolygonShape(std::string polyId);
    void commandSetPolygonShape(std::string polyId, std::list<Coord> points);
    void commandAddPolygon(std::string polyId, std::string polyType, const Color& color, bool filled, int32_t layer, std::list<Coord> points);
    std::list<std::string> commandGetLaneIds();
    std::list<Coord> commandGetLaneShape(std::string laneId);
    std::string commandGetLaneEdgeId(std::string laneId);
    double commandGetLaneLength(std::string laneId);
    double commandGetLaneMaxSpeed(std::string laneId);
    double commandGetLaneMeanSpeed(std::string laneId);
    std::list<std::string> commandGetJunctionIds();
    Coord commandGetJunctionPosition(std::string junctionId);
    bool commandAddVehicle(std::string vehicleId, std::string vehicleTypeId, std::string routeId, std::string laneId, float emitPosition, float emitSpeed);

    const std::map<std::string, cModule *>& getManagedHosts()
    {
        return hosts;
    }

  protected:
    /**
     * Coord equivalent for storing TraCI coordinates
     */
    struct TraCICoord
    {
        TraCICoord() : x(0), y(0) {}
        TraCICoord(double x, double y) : x(x), y(y) {}
        double x;
        double y;
    };

    /**
     * Byte-buffer that stores values in TraCI byte-order
     */
    class TraCIBuffer
    {
      public:
        TraCIBuffer() : buf()
        {
            buf_index = 0;
        }

        TraCIBuffer(std::string buf) : buf(buf)
        {
            buf_index = 0;
        }

        template<typename T> T read()
        {
            T buf_to_return;
            unsigned char *p_buf_to_return = reinterpret_cast<unsigned char *>(&buf_to_return);

            if (isBigEndian()) {
                for (size_t i = 0; i < sizeof(buf_to_return); ++i) {
                    if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
                    p_buf_to_return[i] = buf[buf_index++];
                }
            }
            else {
                for (size_t i = 0; i < sizeof(buf_to_return); ++i) {
                    if (eof()) throw cRuntimeError("Attempted to read past end of byte buffer");
                    p_buf_to_return[sizeof(buf_to_return) - 1 - i] = buf[buf_index++];
                }
            }

            return buf_to_return;
        }

        template<typename T> void write(T inv)
        {
            unsigned char *p_buf_to_send = reinterpret_cast<unsigned char *>(&inv);

            if (isBigEndian()) {
                for (size_t i = 0; i < sizeof(inv); ++i) {
                    buf += p_buf_to_send[i];
                }
            }
            else {
                for (size_t i = 0; i < sizeof(inv); ++i) {
                    buf += p_buf_to_send[sizeof(inv) - 1 - i];
                }
            }
        }

        template<typename T> T read(T& out)
        {
            out = read<T>();
            return out;
        }

        template<typename T> TraCIBuffer& operator>>(T& out)
        {
            out = read<T>();
            return *this;
        }

        template<typename T> TraCIBuffer& operator<<(const T& inv)
        {
            write(inv);
            return *this;
        }

        bool eof() const
        {
            return buf_index == buf.length();
        }

        void set(std::string buf)
        {
            this->buf = buf;
            buf_index = 0;
        }

        void clear()
        {
            set("");
        }

        std::string str() const
        {
            return buf;
        }

        std::string hexStr() const
        {
            std::stringstream ss;
            for (std::string::const_iterator i = buf.begin() + buf_index; i != buf.end(); ++i) {
                if (i != buf.begin()) ss << " ";
                ss << std::hex << std::setw(2) << std::setfill('0') << (int)(uint8_t)*i;
            }
            return ss.str();
        }

      protected:
        bool isBigEndian()
        {
            short a = 0x0102;
            unsigned char *p_a = reinterpret_cast<unsigned char *>(&a);
            return p_a[0] == 0x01;
        }

        std::string buf;
        size_t buf_index;
    };

    simtime_t connectAt;    /**< when to connect to TraCI server (must be the initial timestep of the server) */
    simtime_t firstStepAt;    /**< when to start synchronizing with the TraCI server (-1: immediately after connecting) */
    simtime_t updateInterval;    /**< time interval of hosts' position updates */
    std::string moduleType;    /**< module type to be used in the simulation for each managed vehicle */
    std::string moduleName;    /**< module name to be used in the simulation for each managed vehicle */
    std::string moduleDisplayString;    /**< module displayString to be used in the simulation for each managed vehicle */
    std::string host;
    int port;
    bool autoShutdown;    /**< Shutdown module as soon as no more vehicles are in the simulation */
    int margin;
    double penetrationRate;
    std::list<std::string> roiRoads;    /**< which roads (e.g. "hwy1 hwy2") are considered to consitute the region of interest, if not empty */
    std::list<std::pair<TraCICoord, TraCICoord> > roiRects;    /**< which rectangles (e.g. "0,0-10,10 20,20-30,30) are considered to consitute the region of interest, if not empty */

    void *socketPtr;
    TraCICoord netbounds1;    /* network boundaries as reported by TraCI (x1, y1) */
    TraCICoord netbounds2;    /* network boundaries as reported by TraCI (x2, y2) */

    size_t nextNodeVectorIndex;    /**< next OMNeT++ module vector index to use */
    std::map<std::string, cModule *> hosts;    /**< vector of all hosts managed by us */
    std::set<std::string> unEquippedHosts;
    std::set<std::string> subscribedVehicles;    /**< all vehicles we have already subscribed to */
    uint32_t activeVehicleCount;    /**< number of vehicles reported as active by TraCI server */
    bool autoShutdownTriggered;
    cMessage *connectAndStartTrigger;    /**< self-message scheduled for when to connect to TraCI server and start running */
    cMessage *executeOneTimestepTrigger;    /**< self-message scheduled for when to next call executeOneTimestep */

    uint32_t getCurrentTimeMs();    /**< get current simulation time (in ms) */

    void executeOneTimestep();    /**< read and execute all commands for the next timestep */

    void connect();
    virtual void init_traci();

    void addModule(std::string nodeId, std::string type, std::string name, std::string displayString, const Coord& position, std::string road_id = "", double speed = -1, double angle = -1);
    cModule *getManagedModule(std::string nodeId);    /**< returns a pointer to the managed module named moduleName, or 0 if no module can be found */
    void deleteModule(std::string nodeId);

    bool isModuleUnequipped(std::string nodeId);    /**< returns true if this vehicle is Unequipped */

    /**
     * returns whether a given position lies within the simulation's region of interest.
     * Modules are destroyed and re-created as managed vehicles leave and re-enter the ROI
     */
    bool isInRegionOfInterest(const TraCICoord& position, std::string road_id, double speed, double angle);

    /**
     * sends a single command via TraCI, checks status response, returns additional responses
     */
    TraCIBuffer queryTraCI(uint8_t commandId, const TraCIBuffer& buf = TraCIBuffer());

    /**
     * sends a single command via TraCI, expects no reply, returns true if successful
     */
    TraCIScenarioManager::TraCIBuffer queryTraCIOptional(uint8_t commandId, const TraCIBuffer& buf, bool& success, std::string *errorMsg = 0);

    /**
     * returns byte-buffer containing a TraCI command with optional parameters
     */
    std::string makeTraCICommand(uint8_t commandId, TraCIBuffer buf = TraCIBuffer());

    /**
     * sends a message via TraCI (after adding the header)
     */
    void sendTraCIMessage(std::string buf);

    /**
     * receives a message via TraCI (and strips the header)
     */
    std::string receiveTraCIMessage();

    /**
     * commonly employed technique to get string values via TraCI
     */
    std::string genericGetString(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId);
    Coord genericGetCoord(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId);
    double genericGetDouble(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId);
    std::list<std::string> genericGetStringList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId);
    std::list<Coord> genericGetCoordList(uint8_t commandId, std::string objectId, uint8_t variableId, uint8_t responseId);

    /**
     * convert TraCI coordinates to OMNeT++ coordinates
     */
    Coord traci2omnet(TraCICoord coord) const;

    /**
     * convert OMNeT++ coordinates to TraCI coordinates
     */
    TraCICoord omnet2traci(Coord coord) const;

    /**
     * convert TraCI angle to OMNeT++ angle (in rad)
     */
    double traci2omnetAngle(double angle) const;

    /**
     * convert OMNeT++ angle (in rad) to TraCI angle
     */
    double omnet2traciAngle(double angle) const;

    void subscribeToVehicleVariables(std::string vehicleId);
    void unsubscribeFromVehicleVariables(std::string vehicleId);
    void processSimSubscription(std::string objectId, TraCIBuffer& buf);
    void processVehicleSubscription(std::string objectId, TraCIBuffer& buf);
    void processSubcriptionResult(TraCIBuffer& buf);
};

template<> void TraCIScenarioManager::TraCIBuffer::write(std::string inv);
template<> std::string TraCIScenarioManager::TraCIBuffer::read();

} // namespace inet

#endif    // WITH_TRACI

#endif // ifndef __INET_TRACISCENARIOMANAGER_H


text:
/**
 *
 */
package org.eclipse.php.internal.ui.actions;

import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.wst.sse.ui.internal.debug.ManageBreakpointAction;

/**
 * Manage breakpoint action that supports external files.
 *
 * @author shalom
 *
 */
public class ManageExternalBreakpointAction extends ManageBreakpointAction {

	/**
	 * @param editor
	 * @param rulerInfo
	 */
	public ManageExternalBreakpointAction(ITextEditor editor,
			IVerticalRuler rulerInfo) {
		super(editor, rulerInfo);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.wst.sse.ui.internal.debug.BreakpointRulerAction#hasMarkers()
	 */
	protected boolean hasMarkers() {
		return ExternalBreakpointActionHelper.hasMarkers(getTextEditor(),
				getResource(), getDocument(), getAnnotationModel(),
				getRulerInfo());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.wst.sse.ui.internal.debug.BreakpointRulerAction#getMarkers()
	 */
	protected IMarker[] getMarkers() {
		return ExternalBreakpointActionHelper.getMarkers(getTextEditor(),
				getResource(), getDocument(), getAnnotationModel(),
				getRulerInfo());
	}
}


text:
<form class="form-horizontal container loginForm" action="/" method="POST" name="loginForm" role="form" class="form-horizontal">
    <fieldset>
        <legend>Please enter JIRA login information and supplemental parameters</legend>

            Name:

                <input name="username" ng-model="username" type="text" class="form-control" id="input-username" placeholder="Name" required>

Please enter your JIRA login

            Password:

                <input name="password" ng-model="password" type="password"  class="form-control" id="input-password" placeholder="Password" required>

            JQL Query:

                <textarea name="jqlquery" ng-model="jqlquery" type="text" class="form-control" id="input-jql" placeholder="JQL Query" required/>

            Add single label:

                <input name="labelstoadd" ng-model="labelstoadd"
                       ng-disabled="labelstodelete.length > 0 ||
                       watcherstoadd.length > 0 ||
                       watcherstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-add" placeholder="Label">

            Delete single label:

                <input name="labelstodelete" ng-model="labelstodelete"
                       ng-disabled="labelstoadd.length > 0 ||
                       watcherstoadd.length > 0 ||
                       watcherstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-delete" placeholder="Label">

            Add watcher:

                <input name="watcherstoadd" ng-model="watcherstoadd"
                       ng-disabled="labelstoadd.length > 0 ||
                       labelstodelete.length > 0 ||
                       watcherstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-wadd" placeholder="Watcher name">

            Delete watcher:

                <input name="watcherstodelete" ng-model="watcherstodelete"
                       ng-disabled="labelstoadd.length > 0 ||
                       watcherstoadd.length > 0 ||
                       labelstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-wdelete" placeholder="Watcher name">

            Update assignee:

                <input name="assigneename" ng-model="assigneename"
                       ng-disabled="labelstoadd.length > 0 ||
                       watcherstoadd.length > 0 ||
                       labelstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       watcherstodelete.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-assignee" placeholder="Assignee name">

            Update priority:

                <input name="priorityname" ng-model="priorityname"
                       ng-disabled="labelstoadd.length > 0 ||
                       watcherstoadd.length > 0 ||
                       labelstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       epicstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       watcherstodelete.length > 0"
                       type="text" class="form-control" id="input-label-priority" placeholder="Priority name">

            Add Epic/Theme:

                <input name="epicstoadd" ng-model="epicstoadd"
                       ng-disabled="labelstoadd.length > 0 ||
                       labelstodelete.length > 0 ||
                       watcherstoadd.length > 0 ||
                       watcherstodelete.length > 0 ||
                       assigneename.length > 0 ||
                       epicstodelete.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-epicadd" placeholder="Epic/Theme name">

            Delete Epic/Theme:

                <input name="epicstodelete" ng-model="epicstodelete"
                       ng-disabled="labelstoadd.length > 0 ||
                       watcherstoadd.length > 0 ||
                       watcherstodelete.length > 0 ||
                       labelstodelete.length > 0 ||
                       epicstoadd.length > 0 ||
                       assigneename.length > 0 ||
                       priorityname.length > 0"
                       type="text" class="form-control" id="input-label-epicdelete" placeholder="Epic/Theme name">

Please make sure you checked your JQL and labels twice before pressing button below.

            This application does not check labels and JQL for validness.

            Only you responsible for final result and will have to perform tonns of manual work restoring labels in case of error.

                <button id="updatebtn" type="submit" class="btn btn-primary" ng-disabled="loginForm.$invalid" data-loading-text="Updating data right now...">Update</button>

    </fieldset>
</form>


text:
require 'rails_helper'

feature 'Question 0' do
  xscenario do
    visit q0_questions_path

    rows = all('.answer tr')
    within rows[1] do
      col_texts = all('td').map(&:text).last(2)
      expect(col_texts).to eq %w(Alice Design)
    end
    within rows[2] do
      col_texts = all('td').map(&:text).last(2)
      expect(col_texts).to eq %w(Bob Design)
    end
    within rows[3] do
      col_texts = all('td').map(&:text).last(2)
      expect(col_texts).to eq %w(Chris Finance)
    end
    within rows[4] do
      col_texts = all('td').map(&:text).last(2)
      expect(col_texts).to eq ['Dave', '']
    end

    assert_sql_count
  end
end


text:
/*************************************************************************/
/*  control_editor_plugin.h                                              */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef CONTROL_EDITOR_PLUGIN_H
#define CONTROL_EDITOR_PLUGIN_H

#include "editor/editor_plugin.h"
#include "scene/gui/box_container.h"
#include "scene/gui/check_box.h"
#include "scene/gui/control.h"
#include "scene/gui/label.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/option_button.h"
#include "scene/gui/panel_container.h"
#include "scene/gui/texture_rect.h"

class ControlPositioningWarning : public MarginContainer {
	GDCLASS(ControlPositioningWarning, MarginContainer);

	Control *control_node = nullptr;

	PanelContainer *bg_panel = nullptr;
	GridContainer *grid = nullptr;
	TextureRect *title_icon = nullptr;
	TextureRect *hint_icon = nullptr;
	Label *title_label = nullptr;
	Label *hint_label = nullptr;
	Control *hint_filler_left = nullptr;
	Control *hint_filler_right = nullptr;

	void _update_warning();
	void _update_toggler();
	virtual void gui_input(const Ref<InputEvent> &p_event) override;

protected:
	void _notification(int p_notification);

public:
	void set_control(Control *p_node);

	ControlPositioningWarning();
};

class EditorPropertyAnchorsPreset : public EditorProperty {
	GDCLASS(EditorPropertyAnchorsPreset, EditorProperty);
	OptionButton *options;

	void _option_selected(int p_which);

protected:
	virtual void _set_read_only(bool p_read_only) override;

public:
	void setup(const Vector<String> &p_options);
	virtual void update_property() override;
	EditorPropertyAnchorsPreset();
};

class EditorPropertySizeFlags : public EditorProperty {
	GDCLASS(EditorPropertySizeFlags, EditorProperty);

	enum FlagPreset {
		SIZE_FLAGS_PRESET_FILL,
		SIZE_FLAGS_PRESET_SHRINK_BEGIN,
		SIZE_FLAGS_PRESET_SHRINK_CENTER,
		SIZE_FLAGS_PRESET_SHRINK_END,
		SIZE_FLAGS_PRESET_CUSTOM,
	};

	OptionButton *flag_presets;
	CheckBox *flag_expand;
	VBoxContainer *flag_options;
	Vector<CheckBox *> flag_checks;

	bool vertical = false;

	bool keep_selected_preset = false;

	void _preset_selected(int p_which);
	void _expand_toggled();
	void _flag_toggled();

protected:
	virtual void _set_read_only(bool p_read_only) override;

public:
	void setup(const Vector<String> &p_options, bool p_vertical);
	virtual void update_property() override;
	EditorPropertySizeFlags();
};

class EditorInspectorPluginControl : public EditorInspectorPlugin {
	GDCLASS(EditorInspectorPluginControl, EditorInspectorPlugin);

public:
	virtual bool can_handle(Object *p_object) override;
	virtual void parse_group(Object *p_object, const String &p_group) override;
	virtual bool parse_property(Object *p_object, const Variant::Type p_type, const String &p_path, const PropertyHint p_hint, const String &p_hint_text, const uint32_t p_usage, const bool p_wide = false) override;
};

class ControlEditorToolbar : public HBoxContainer {
	GDCLASS(ControlEditorToolbar, HBoxContainer);

	UndoRedo *undo_redo;
	EditorSelection *editor_selection;

	enum MenuOption {
		ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT,
		ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT,
		ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT,
		ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT,
		ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT,
		ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT,
		ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP,
		ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM,
		ANCHORS_AND_OFFSETS_PRESET_CENTER,
		ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE,
		ANCHORS_AND_OFFSETS_PRESET_WIDE,

		ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO,

		ANCHORS_PRESET_TOP_LEFT,
		ANCHORS_PRESET_TOP_RIGHT,
		ANCHORS_PRESET_BOTTOM_LEFT,
		ANCHORS_PRESET_BOTTOM_RIGHT,
		ANCHORS_PRESET_CENTER_LEFT,
		ANCHORS_PRESET_CENTER_RIGHT,
		ANCHORS_PRESET_CENTER_TOP,
		ANCHORS_PRESET_CENTER_BOTTOM,
		ANCHORS_PRESET_CENTER,
		ANCHORS_PRESET_TOP_WIDE,
		ANCHORS_PRESET_LEFT_WIDE,
		ANCHORS_PRESET_RIGHT_WIDE,
		ANCHORS_PRESET_BOTTOM_WIDE,
		ANCHORS_PRESET_VCENTER_WIDE,
		ANCHORS_PRESET_HCENTER_WIDE,
		ANCHORS_PRESET_WIDE,

		// Offsets Presets are not currently in use.
		OFFSETS_PRESET_TOP_LEFT,
		OFFSETS_PRESET_TOP_RIGHT,
		OFFSETS_PRESET_BOTTOM_LEFT,
		OFFSETS_PRESET_BOTTOM_RIGHT,
		OFFSETS_PRESET_CENTER_LEFT,
		OFFSETS_PRESET_CENTER_RIGHT,
		OFFSETS_PRESET_CENTER_TOP,
		OFFSETS_PRESET_CENTER_BOTTOM,
		OFFSETS_PRESET_CENTER,
		OFFSETS_PRESET_TOP_WIDE,
		OFFSETS_PRESET_LEFT_WIDE,
		OFFSETS_PRESET_RIGHT_WIDE,
		OFFSETS_PRESET_BOTTOM_WIDE,
		OFFSETS_PRESET_VCENTER_WIDE,
		OFFSETS_PRESET_HCENTER_WIDE,
		OFFSETS_PRESET_WIDE,

		CONTAINERS_H_PRESET_FILL,
		CONTAINERS_H_PRESET_FILL_EXPAND,
		CONTAINERS_H_PRESET_SHRINK_BEGIN,
		CONTAINERS_H_PRESET_SHRINK_CENTER,
		CONTAINERS_H_PRESET_SHRINK_END,
		CONTAINERS_V_PRESET_FILL,
		CONTAINERS_V_PRESET_FILL_EXPAND,
		CONTAINERS_V_PRESET_SHRINK_BEGIN,
		CONTAINERS_V_PRESET_SHRINK_CENTER,
		CONTAINERS_V_PRESET_SHRINK_END,
	};

	TextureRect *anchor_layouts_icon;
	MenuButton *anchor_presets_menu;
	PopupMenu *anchors_popup;
	TextureRect *container_layouts_icon;
	MenuButton *container_h_presets_menu;
	MenuButton *container_v_presets_menu;

	Button *anchor_mode_button;

	bool anchors_mode = false;

	void _set_anchors_preset(Control::LayoutPreset p_preset);
	void _set_anchors_and_offsets_preset(Control::LayoutPreset p_preset);
	void _set_anchors_and_offsets_to_keep_ratio();
	void _set_container_h_preset(Control::SizeFlags p_preset);
	void _set_container_v_preset(Control::SizeFlags p_preset);

	Vector2 _anchor_to_position(const Control *p_control, Vector2 anchor);
	Vector2 _position_to_anchor(const Control *p_control, Vector2 position);

	void _button_toggle_anchor_mode(bool p_status);

	bool _is_node_locked(const Node *p_node);
	List<Control *> _get_edited_controls(bool retrieve_locked = false, bool remove_controls_if_parent_in_selection = true);
	void _popup_callback(int p_op);
	void _selection_changed();

protected:
	void _notification(int p_notification);

	static ControlEditorToolbar *singleton;

public:
	bool is_anchors_mode_enabled() { return anchors_mode; };

	static ControlEditorToolbar *get_singleton() { return singleton; }

	ControlEditorToolbar();
};

class ControlEditorPlugin : public EditorPlugin {
	GDCLASS(ControlEditorPlugin, EditorPlugin);

	ControlEditorToolbar *toolbar;

public:
	virtual String get_name() const override { return "Control"; }

	ControlEditorPlugin();
};

#endif //CONTROL_EDITOR_PLUGIN_H


text:
'use strict';

import Server from './configs/server';

const server = new Server(__dirname);
server.start();


text:
package com.haoxitech.canzhaopin.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangtao on 16/3/10.
 */
public class DataBaseHelper {

    private static final String LOG_TAG = "SQLite";

    private static SQLiteDatabase sqLiteDatabase;

    private final static String DIR_PATH = "/data/data/com.haoxitech.canzhaopin/databases/";

    private final static String DB_PATH = "/data/data/com.haoxitech.canzhaopin/databases/zipArea.db";

    public DataBaseHelper() {

    }

    public static void openDB() {
        try {
            sqLiteDatabase = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.CONFLICT_IGNORE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int create(String sql, Object... args) {

        if (sql == null)
            return 0;
        if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
            openDB();
        }
        if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
            return 0;
        }
        try {
            sqLiteDatabase.execSQL(sql, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }
        return -1;
    }

    /**
     * 执行insert语句
     *
     * @param sql
     *            insert语句
     * @param args
     *            要插入的数据
     * @return
     */
    public static int insert(String sql, Object... args) {

        if (sql == null)
            return 0;
        if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
            openDB();
        }
        if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
            return 0;
        }
        try {
            sqLiteDatabase.execSQL(sql, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }
        return -1;
    }

    /**
     * 执行select语句
     *
     * @param sql
     *            select语句
     * @param args
     *            参数
     * @return 一个数据集合List
     */
    public static List<Map<String, Object>> select(String sql, Object... args) {

        Cursor cursor = null;
        try {
            if (sql == null)
                return null;

            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                openDB();
            }
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Map<String, Object> map;
            String[] _args = new String[0];
            if (args != null) {
                _args = new String[args.length];

                for (int i = 0; i < args.length; i++) {
                    _args[i] = (args[i] == null ? "null" : args[i].toString());

                }
            }

            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                return null;
            }
            cursor = sqLiteDatabase.rawQuery(sql, _args);
            String[] columnNames = cursor.getColumnNames();

            if (cursor != null) {
                if (cursor.moveToFirst()) {

                    for (int i = 0; i < cursor.getCount(); i++) {
                        map = new HashMap<String, Object>();

                        for (int j = 0; j < cursor.getColumnCount(); j++) {

                            map.put(columnNames[j], cursor.getString(j));
                        }

                        cursor.moveToNext();

                        list.add(map);
                    }

                    if (list != null) {
                        return list;
                    }

                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);

        } finally {

            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e) {
                }
            }
        }
        return null;
    }

    /**
     * 执行selectUnique语句
     *
     * @param sql
     *            selectUnique语句
     * @param args
     *            参数
     * @return 唯一一条数据
     */
    public static Map<String, Object> selectUnique(String sql, Object... args) {
        if (sql == null)
            return null;
        Cursor cursor = null;
        try {
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                openDB();
            }
            Map<String, Object> map = new HashMap<String, Object>();
            String[] _args = new String[0];
            if (args != null) {
                _args = new String[args.length];

                for (int i = 0; i < args.length; i++) {
                    _args[i] = (args[i] == null ? "null" : args[i].toString());

                }
            }
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                return null;
            }
            cursor = sqLiteDatabase.rawQuery(sql, _args);
            String[] columnNames = cursor.getColumnNames();
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    for (int j = 0; j < cursor.getColumnCount(); j++) {
                        map.put(columnNames[j], cursor.getString(j));
                    }

                    if (map != null) {
                        return map;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

    /**
     * 执行update语句
     *
     * @param sql
     *            update语句
     * @param args
     *            参数
     * @return
     */
    public static int update(String sql, Object... args) {
        if (sql == null)
            return 0;
        try {
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                openDB();
            }
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                return 0;
            }
            sqLiteDatabase.execSQL(sql, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }
        return -1;
    }

    /**
     * 执行drop语句
     *
     * @param sql
     *            drop语句
     * @param args
     *            参数
     * @return
     */
    public static int drop(String sql, Object... args) {
        if (sql == null)
            return 0;
        try {
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                openDB();
            }
            if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
                return 0;
            }
            sqLiteDatabase.execSQL(sql, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }
        return -1;
    }

    /**
     * 执行delete语句
     *
     * @param sql
     *            delete语句
     * @param args
     *            参数
     * @return
     */
    public static int delete(String sql, Object... args) {
        if (sqLiteDatabase == null || !sqLiteDatabase.isOpen()) {
            openDB();
        }
        try {
            sqLiteDatabase.execSQL(sql, args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeDb();
        }
        return -1;
    }

    /**
     * 关闭数据库
     */
    public static void closeDb() {

        if (sqLiteDatabase != null) {
            sqLiteDatabase.close();
        }

    }

    /**
     * 将数据库写入到指定路径下
     *
     * @param context
     *            上下文
     * @throws IOException
     *             IO流异常
     */
    public static void copyDataBase(Context context, String filename)
            throws IOException {

        String tagPath = DIR_PATH;
        File dbFile = new File(tagPath + filename);
        if (dbFile.exists()) {
            return;
        }

        InputStream is = context.getAssets().open(filename);
        OutputStream os = null;
        File filePath = new File(tagPath);

        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        try {
            String outFileName = tagPath + filename;
            os = new FileOutputStream(outFileName);
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = is.read(b)) != -1) {
                os.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            is.close();
            os.close();
        }
    }
}


text:
<% if (modules === 'webpack' || modules === 'systemjs' || framework === 'angular1') { -%>
const conf = require('./gulp.conf');
<% } -%>
<% if (modules === 'inject') { -%>
const listFiles = require('./karma-files.conf');
<% } -%>
<% if (modules === 'systemjs' && framework === 'angular2') { -%>
const glob = require('glob');
<% } -%>

module.exports = function (config) {
  const configuration = <%- json(karmaConf, 2) %>;

  config.set(configuration);
};


text:
package org.apache.zookeeper.book.mine.step2;

import org.apache.zookeeper.*;
import org.apache.zookeeper.book.ChildrenCache;
import org.apache.zookeeper.book.recovery.RecoveredAssignments;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Random;

public class Master implements Watcher {

    private static final Logger LOG = LoggerFactory.getLogger(Master.class);

    enum MasterStates {RUNNING, ELECTED, NOTELECTED};

    private volatile MasterStates state = MasterStates.RUNNING;

    private ZooKeeper zk;
    private String hostPort;

    private Random random = new Random(this.hashCode());
    private String serverId = Integer.toHexString(random.nextInt());

    private ChildrenCache workersCache;
    private ChildrenCache tasksCache;

    private volatile boolean connected = false;
    private volatile boolean expired = false;

    public boolean isConnected() {
        return connected;
    }

    public boolean isExpired() {
        return expired;
    }

    /**
     * Creates a new master instance.
     *
     * @param hostPort
     */
    Master(String hostPort) {
        this.hostPort = hostPort;
    }

    /**
     * Creates a new ZooKeeper session.
     *
     * @throws IOException
     */
    void startZK() throws IOException {
        zk = new ZooKeeper(hostPort, 15000, this);
    }

    /**
     * close the zookeeper session.
     *
     * @throws InterruptedException
     */
    void stopZK() throws InterruptedException {
        zk.close();
    }

    /**
     * This method implements the process method of the
     * Watcher interface. We use it to deal with the
     * different states of a session.
     *
     * @param e new session event to be processed
     */
    public void process(WatchedEvent e) {
        System.out.println("Processing event: " + e.toString());

        if (Event.EventType.None == e.getType()) {
            switch (e.getState()) {
                case SyncConnected:
                    connected = true;

                    break;
                case Disconnected:
                    connected = false;

                    break;
                case Expired:
                    expired = true;
                    connected = false;

                    break;
                default:
                    System.out.println("Watcher eventType: " + e.getState());
                    break;

            }
        }
    }

    /**
     * returns true if there is a master.
     *
     * @return
     */
    public void checkMaster() {
        zk.getData("/master",
                false,
                masterCheckCallback,
                null);
    }

    AsyncCallback.DataCallback masterCheckCallback = new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    checkMaster();

                    break;
                case NONODE:
                    runForMaster();

                    break;
                case OK:
                    if (serverId.equals(new String(data))) {
                        state = MasterStates.ELECTED;
                        takeLeadership();
                    } else {
                        state = MasterStates.NOTELECTED;
                        masterExits();
                    }

                    break;
                default:
                    System.out.println("checkMaster default." + KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    /**
     * Tries to create a /master lock znode acquire leadership.
     *
     */
    public void runForMaster() {
        System.out.println("Running for master.");
        zk.create("/master",
                serverId.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL,
                masterCreateCallback,
                null);

    }

    AsyncCallback.StringCallback masterCreateCallback = new AsyncCallback.StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    checkMaster();
                    break;

                case OK:
                    state = MasterStates.ELECTED;
                    takeLeadership();
                    break;

                case NODEEXISTS:
                    state = MasterStates.NOTELECTED;
                    masterExits();
                    break;

                default:
                    state = MasterStates.NOTELECTED;
                    System.out.println("Someting went wrong when running for master.");
            }
            System.out.println("back: I'm " + (MasterStates.ELECTED == state ? "" : "not ") + "the leader " + serverId);
        }

    };

    private void takeLeadership() {
        System.out.println("Going for list of workers");
        getWorkers();

        // TODO: 2017/3/16
        new RecoveredAssignments(zk).recover(new RecoveredAssignments.RecoveryCallback() {
            @Override
            public void recoveryComplete(int rc, List<String> tasks) {
                if (RecoveredAssignments.RecoveryCallback.FAILED == rc) {
                    System.out.println("Recovery of assigned tasks failed.");
                } else {
                    System.out.println("Assigning recovered tasks.");
                    getTasks();
                }
            }
        });

    }

    public void bootstrap() {
        createParent("/workers", new byte[0]);
        createParent("/assign", new byte[0]);
        createParent("/tasks", new byte[0]);
        createParent("/status", new byte[0]);
    }

    private void createParent(String path, byte[] data) {
        zk.create(path,
                data,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT,
                createParentCallback,
                data);
    }

    AsyncCallback.StringCallback createParentCallback = new AsyncCallback.StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    createParent(path, (byte[]) ctx);
                    break;

                case OK:
                    System.out.println("parent znode " + path + " created");
                    break;

                case NODEEXISTS:
                    System.out.println("Parent already registered: " + path);
                    break;
                default:
                    System.out.println("something went wrong:" + KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    public void masterExits() {
        zk.exists("/master",
                masterExitsWatcher,
                masterExitsCallback,
                null);
    }

    Watcher masterExitsWatcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType().equals(Event.EventType.NodeDeleted)) {
                assert "/master".equals(event.getPath());
                runForMaster();
            }
        }
    };

    AsyncCallback.StatCallback masterExitsCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    masterExits();
                    break;

                case OK:
                    if (stat != null) {
                        runForMaster();
                    }
                    break;
                case NONODE:
                    state = MasterStates.RUNNING;
                    runForMaster();
                    System.out.println("It sounds like the previous is gone. so let's run for master again.");
                default:
                    System.out.println("default. " + KeeperException.Code.get(rc));
                    checkMaster();
            }
        }
    };

    public void getWorkers() {
        zk.getChildren("/workers",
                        workersChangeWatcher,
                        workersGetChildrenCallback,
                        null);
    }

    Watcher workersChangeWatcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.NodeChildrenChanged) {
                assert "/workers".equals(event.getPath());

                getWorkers();
            }
        }
    };

    AsyncCallback.ChildrenCallback workersGetChildrenCallback = new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    getWorkers();

                    break;
                case OK:
                    System.out.println("success get a list of workers:" + children.size());
                    reassignAndSet(children);

                    break;
                default:
                    System.out.println("getChild failed." + KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    private void reassignAndSet(List<String> children) {
        List<String> toProcess;

        if (workersCache == null) {
            workersCache = new ChildrenCache(children);
            toProcess = null;
        } else {
            System.out.println("Removing and setting.");
            toProcess = workersCache.removedAndSet(children);
        }

        if (toProcess != null) {
            for (String worker : toProcess) {
                getAbsentWorkerTasks(worker);
            }
        }
    }

    private void getAbsentWorkerTasks(String worker) {
        zk.getChildren("/assign/" + worker, false, workerAssignmentCallback, null);
    }

    AsyncCallback.ChildrenCallback workerAssignmentCallback = new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    getAbsentWorkerTasks(path);

                    break;
                case OK:
                    System.out.println("Successfully got a list of assignment:" + children.size() + " tasks.");

                    /**
                     * Reassign the tasks of the absent worker.
                     */
                    for (String task : children) {
                        getDataReassign(path + "/" + task, task);
                    }

                    break;
                default:
                    System.out.println("getChildren faild. " + KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }

    };

    /*
     ************************************************
     * Recovery of tasks assigned to absent worker. *
     ************************************************
     */

    /**
     * Get reassign task data.
     * @param path Path of assign task
     * @param task Task name excluding the path prefix
     */
    private void getDataReassign(String path, String task) {
        zk.getData(path,
                false,
                getDataReassignCallback,
                task);
    }

    AsyncCallback.DataCallback getDataReassignCallback = new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    getDataReassign(path, (String) ctx);

                    break;
                case OK:
                    recreateTask(new RecreateTaskCtx(path, (String) ctx, data));

                    break;
                default:
                    System.out.println("Something went wrong when getting data." + KeeperException.create(KeeperException.Code.get(rc), path));

            }
        }

    };

    class RecreateTaskCtx {
        String path;
        String task;
        byte[] data;

        public RecreateTaskCtx(String path, String task, byte[] data) {
            this.path = path;
            this.task = task;
            this.data = data;
        }
    }

    private void recreateTask(RecreateTaskCtx ctx) {
        zk.create("/tasks/" + ctx.task,
                ctx.data,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT,
                recreateTaskCallback,
                ctx);
    }

    AsyncCallback.StringCallback recreateTaskCallback = new AsyncCallback.StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    recreateTask((RecreateTaskCtx) ctx);

                    break;
                case OK:
                    deleteAssignment(((RecreateTaskCtx) ctx).path);

                    break;
                case NODEEXISTS:

                    // TODO: 2017/3/13
                    recreateTask((RecreateTaskCtx) ctx);
                    break;
                default:
                    System.out.println("Something went wrong when recreating task.");
            }
        }
    };

    private void deleteAssignment(String path) {
        zk.delete(path, -1, taskDeletionCallback, null);
    }

    AsyncCallback.VoidCallback taskDeletionCallback = new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    deleteAssignment(path);

                    break;
                case OK:
                    System.out.println("Task coreectly deleted: " + path);

                    break;
                default:
                    System.out.println("Fail to delete task data "
                            + KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    private void getTasks() {
        zk.getChildren("/tasks",
                taskChangeWatcher,
                taskGetChildrenCallback,
                null);
    }

    Watcher taskChangeWatcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (Event.EventType.NodeChildrenChanged == event.getType()) {
                assert "/tasks".equals(event.getPath());
                getTasks();
            }
        }
    };

    AsyncCallback.ChildrenCallback taskGetChildrenCallback = new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    getTasks();

                    break;
                case OK:
                    List<String> toProcess;
                    if (tasksCache == null) {
                        tasksCache = new ChildrenCache(children);

                        toProcess = children;
                    } else {
                        toProcess = tasksCache.addedAndSet(children);
                    }

                    if (toProcess != null) {
                        assignTasks(toProcess);
                    }

                    break;
                default:
                    System.out.println("getTaskChildren failed. " + KeeperException.create(KeeperException.Code.get(rc), path));

            }
        }
    };

    private void assignTasks(List<String> toProcess) {
        for (String task : toProcess) {
            getTaskData(task);
        }
    }

    private void getTaskData(String task) {
        zk.getData("/tasks/" + task,
                false,
                taskDataCallback,
                task);
    }

    AsyncCallback.DataCallback taskDataCallback = new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    getTaskData((String) ctx);

                    break;
                case OK:
                    /*
                     * Choose worker at random.
                     */
                    List<String> list = workersCache.getList();
                    String designateWorker = list.get(random.nextInt(list.size()));

                    /*
                     * Assign task to randomly chosen worker.
                     */
                    String assignmentPath = "/assign/" + designateWorker + "/" + (String) ctx;
                    System.out.println("Assignment path: " + assignmentPath);
                    createAssignment(assignmentPath, data);

                    break;
                default:
                    System.out.println("Error when trying to get task data." +
                        KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    private void createAssignment(String path, byte[] data) {
        zk.create(path,
                data,
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT,
                assignTasksCallback,
                data);
    }

    AsyncCallback.StringCallback assignTasksCallback = new AsyncCallback.StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    createAssignment(path, (byte[]) ctx);

                    break;
                case OK:
                    System.out.println("Task assigned correctly: " + name);
                    deleteTask(name.substring(name.lastIndexOf("/") + 1));

                    break;
                case NODEEXISTS:
                    System.out.println("Task already assigned");

                    break;
                default:
                    System.out.println("Error when trying to assign task." +
                        KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }

    };

    private void deleteTask(String name) {
        zk.delete("/tasks/" + name, -1, taskDeleteCallback, name);
    }

    AsyncCallback.VoidCallback taskDeleteCallback = new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            switch (KeeperException.Code.get(rc)) {
                case CONNECTIONLOSS:
                    deleteTask((String) ctx);

                    break;
                case OK:
                    System.out.println("Successfully deleted " + path);

                    break;
                case NONODE:
                    System.out.println("Task has been deleted already.");

                    break;
                default:
                    System.out.println("Something went wrong here. " +
                        KeeperException.create(KeeperException.Code.get(rc), path));
            }
        }
    };

    /**
     * Main method providing an example of how to run the master.
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception {

        /**
         * step_1 创建一个Zookeeper会话
         */
        Master m = new Master(args[0]);
        m.startZK();

        /**
         * step_2
         */
        while(m.isConnected()) {
            Thread.sleep(100);
        }

        /**
         * step_3 初始化元数据
         */
        m.bootstrap();

        /**
         * step_4 竞争Master主节点及后续处理
         */
        m.runForMaster();

        /**
         * step_5 判定zk回话是否过期
         */
        while (!m.isExpired()) {
            Thread.sleep(1000);
        }

        m.stopZK();

    }

}


text:
/* Challenge #6 forks and clones
Code by Perrin Clark
BlackGuyCoding@gmail.com
https://www.nodeschool.io */

//this challenge requires you to fork a project from GitHub.com and clone it locally//


text:
- A working git installation
- Access to GitHub that allows you cloning of public repositories
- A working and somewhat current maven installation (tested with Maven 3.2.3)

**Note** that there is no "developer build".

## Release build

### Set a release version:

    mvn versions:set -DnewVersion=1.0
    mvn versions:commit

### Build the release bits and push them to Maven Central

There is no "Maven site" for this project. This is a "build container" project, and does not have Maven site metrics or
static code analysis results.

Run the Maven release build and push the bits to Maven Central:

    mvn clean deploy

Or (for automated builds on a single-user machine):

    mvn deploy -P release -Dgpg.passphrase=keyPassphrase

Then go to the [Sonatype staging repo](https://oss.sonatype.org/) and promote the build.

### Commit release version change to git and tag

    mvn clean
    git status
    git add . -A
    git commit -m "Build Tools Release 1.0 prep"
    git tag -a BT-1.0 -m "Build Tools Release 1.0"

### Push to GitHub

    git push


text:
package org.codehaus.groovy.classgen.asm.sc;

import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.classgen.AsmClassGenerator;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.classgen.asm.*;
import org.codehaus.groovy.transform.sc.StaticCompilationMetadataKeys;
import org.codehaus.groovy.transform.sc.StaticCompilationVisitor;
import org.codehaus.groovy.transform.stc.StaticTypesMarker;
import org.objectweb.asm.ClassVisitor;

/**
 * An alternative {@link org.codehaus.groovy.classgen.asm.WriterController} which handles static types and method
 * dispatch. In case of a "mixed mode" where only some methods are annotated with {@link groovy.transform.TypeChecked}
 * then this writer will delegate to the classic writer controller.
 *
 * @author Cedric Champeau
 */
public class StaticTypesWriterController extends DelegatingController {

    protected boolean isInStaticallyCheckedMethod;
    private StaticTypesCallSiteWriter callSiteWriter;
    private StaticTypesStatementWriter statementWriter;
    private StaticTypesTypeChooser typeChooser;
    private StaticInvocationWriter invocationWriter;
    private BinaryExpressionMultiTypeDispatcher binaryExprHelper;
    private UnaryExpressionHelper unaryExpressionHelper;
    private ClosureWriter closureWriter;

    public StaticTypesWriterController(WriterController normalController) {
        super(normalController);
        isInStaticallyCheckedMethod = false;
    }

    @Override
    public void init(final AsmClassGenerator asmClassGenerator, final GeneratorContext gcon, final ClassVisitor cv, final ClassNode cn) {
        super.init(asmClassGenerator, gcon, cv, cn);
        this.callSiteWriter = new StaticTypesCallSiteWriter(this);
        this.statementWriter = new StaticTypesStatementWriter(this);
        this.typeChooser = new StaticTypesTypeChooser();
        this.invocationWriter = new StaticInvocationWriter(this);
        this.binaryExprHelper = new StaticTypesBinaryExpressionMultiTypeDispatcher(this);
        this.closureWriter = new StaticTypesClosureWriter(this);
        this.unaryExpressionHelper = new StaticTypesUnaryExpressionHelper(this);
    }

    @Override
    public void setMethodNode(final MethodNode mn) {
        updateStaticCompileFlag(mn);
        super.setMethodNode(mn);
    }

    private void updateStaticCompileFlag(final MethodNode mn) {
        ClassNode classNode = getClassNode();
        AnnotatedNode node = mn;
        if (classNode.implementsInterface(ClassHelper.GENERATED_CLOSURE_Type)) {
            node = classNode.getOuterClass();
        }

        isInStaticallyCheckedMethod = mn != null && (
                StaticCompilationVisitor.isStaticallyCompiled(node)
                        || classNode.implementsInterface(ClassHelper.GENERATED_CLOSURE_Type)&&classNode.getNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE)!=null);

/*      if (isInStaticallyCheckedMethod) {
            System.out.println("Entering statically compiled method: "+mn.getDeclaringClass()+"#"+mn);
        } else if (mn!=null) {
            System.out.println("Entering dynamically compiled method: "+mn.getDeclaringClass()+"#"+mn);
        }*/
    }

    @Override
    public void setConstructorNode(final ConstructorNode cn) {
        updateStaticCompileFlag(cn);
        super.setConstructorNode(cn);
    }

    @Override
    public boolean isFastPath() {
        if (isInStaticallyCheckedMethod) return true;
        return super.isFastPath();
    }

    @Override
    public CallSiteWriter getCallSiteWriter() {
        MethodNode methodNode = getMethodNode();
        if (methodNode !=null && methodNode.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION)==Boolean.TRUE) {
            return super.getCallSiteWriter();
        }
        if (isInStaticallyCheckedMethod) {
            return callSiteWriter;
        }
        return super.getCallSiteWriter();
    }

    public CallSiteWriter getRegularCallSiteWriter() {
        return super.getCallSiteWriter();
    }

    @Override
    public StatementWriter getStatementWriter() {
        if (isInStaticallyCheckedMethod) {
            return statementWriter;
        } else {
            return super.getStatementWriter();
        }
    }

    @Override
    public TypeChooser getTypeChooser() {
        if (isInStaticallyCheckedMethod) {
            return typeChooser;
        } else {
            return super.getTypeChooser();
        }
    }

    @Override
    public InvocationWriter getInvocationWriter() {
        if (isInStaticallyCheckedMethod) {
            return invocationWriter;
        } else {
            return super.getInvocationWriter();
        }
    }

    public InvocationWriter getRegularInvocationWriter() {
        return super.getInvocationWriter();
    }

    @Override
    public BinaryExpressionHelper getBinaryExpressionHelper() {
        if (isInStaticallyCheckedMethod) {
            return binaryExprHelper;
        } else {
            return super.getBinaryExpressionHelper();
        }
    }

    @Override
    public UnaryExpressionHelper getUnaryExpressionHelper() {
        if (isInStaticallyCheckedMethod) {
            return unaryExpressionHelper;
        }
        return super.getUnaryExpressionHelper();
    }

    @Override
    public ClosureWriter getClosureWriter() {
        if (isInStaticallyCheckedMethod) {
            return closureWriter;
        }
        return super.getClosureWriter();
    }
}


text:
title: Success.flatMap - Kotlin utilities
---

[Kotlin utilities](../../index.html) / [it.czerwinski.kotlin.util](../index.html) / [Success](index.html) / [flatMap](./flat-map.html)

# flatMap

`fun <R> flatMap(transform: (`[`T`](index.html#T)`) -> `[`Try`](../-try/index.html)`<`[`R`](flat-map.html#R)`>): `[`Try`](../-try/index.html)`<`[`R`](flat-map.html#R)`>`

Overrides [Try.flatMap](../-try/flat-map.html)

Maps value of a [Success](index.html) to a new [Try](../-try/index.html) using [transform](../-try/flat-map.html#it.czerwinski.kotlin.util.Try$flatMap(kotlin.Function1((it.czerwinski.kotlin.util.Try.T, it.czerwinski.kotlin.util.Try((it.czerwinski.kotlin.util.Try.flatMap.R)))))/transform) or returns the same [Try](../-try/index.html) if this is a [Failure](../-failure/index.html).

### Parameters

`transform` - Function transforming value of a [Success](index.html) to a [Try](../-try/index.html).

**Return**
[Try](../-try/index.html) returned by [transform](../-try/flat-map.html#it.czerwinski.kotlin.util.Try$flatMap(kotlin.Function1((it.czerwinski.kotlin.util.Try.T, it.czerwinski.kotlin.util.Try((it.czerwinski.kotlin.util.Try.flatMap.R)))))/transform) or this object if this is a [Failure](../-failure/index.html).


text:
<?php

namespace Models;

class Admin {

    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $password;

    /**
     * @var string
     */
    private $email;
    /*
     *----------------------------------------------------------------------------------------------------------------------
     *                                        MODEL FUNCTIONS
     *----------------------------------------------------------------------------------------------------------------------
     */

    function __construct()
    {
    }

     /**
     * Obtient la notation sous forme de tableau
     *
     * @return array
     */
    public function toArray()
    {
        return array(
            "Nom d'utilisateur" => $this->getUsername(),
            "Mot de passe" => $this->getPassword(),
        );
    }

    /**
     * Sauve l'objet en base de données
     *
     * @return bool
     */
    public function save()
    {
        $db = DBConnection::getInstance();

        $query = $db->prepare("INSERT INTO admins (username, password, mail) VALUES (?, ?, ?)");
        $success = $query->execute([$this->getUsername(), $this->getPassword(), $this->getEmail()]);

        if ($success) {
            $this->setId($db->lastInsertId());
        }

        return $success;
    }

    /**
     * @param $username
     * @param $password
     * @return bool
     * @throws \InvalidArgumentException
     */
    public function logIn($username, $password){
        $user = self::getByUsername($username);

        if((sha1($password) == $user->getPassword()) === false)
            throw new \InvalidArgumentException("Erreur mot de passe !");

        return true;
    }

    /*
    *----------------------------------------------------------------------------------------------------------------------
    *                                      DB QUERIES
    *----------------------------------------------------------------------------------------------------------------------
    */

    public static function getByUsername($username){
        $db = DBConnection::getInstance();

        $query = $db->prepare("SELECT * FROM admins WHERE username LIKE ?");
        $success = $query->execute(["$username"]);
        if($success === false)
            throw new \InvalidArgumentException("Le nom d'utilisateur spécifié n'existe pas !");

       return $query->fetchObject("\\Models\\Admin");
    }

    /*
     * ------------------------------------------------------------------------------------------------------------------
     *                  GETTERS & SETTERS
     *------------------------------------------------------------------------------------------------------------------
     */

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $password
     * @throws \InvalidArgumentException
     */
    public function setPassword($password)
    {
        if(empty($password))
            throw new \InvalidArgumentException("Le mot de passe ne peut pas être vide !");
        if(!preg_match("#^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\\d]){1,})(?=(.*[\\W]){1,})(?!.*\\s).{6,}$#",$password))
            throw new \InvalidArgumentException(
                "Le mot de passe doit être composé de : " . "

                    - au moins 6 caractères

                    - au moins une lettre minuscule(a-z)

                    - au moins une lettre majuscule(A-Z)

                    - au moins un chiffre(0-9)

                    - au moins un symbole spécial (@,!,?,...)");

        $password = sha1($password);
        $this->password = $password;
    }

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

    /**
     * @param string $username
     * @throws \InvalidArgumentException
     */
    public function setUsername($username)
    {
        if(preg_match('![^a-z0-9]!i', $username))
            throw new \InvalidArgumentException("Le mot d'utilisateur ne peut contenir que des lettres miniscules et des chiffres !");

        $this->username = $username;
    }

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

    /**
     * @param mixed $email
     * @throws \InvalidArgumentException
     */
    public function setEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
            throw new \InvalidArgumentException("L'adresse mail n'est pas correcte !");

        $this->email = $email;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

}


text:
'use strict'

var run = require('tapdance')

var fortune = require('../lib')
var createMethod = fortune.methods.create

require('./integration/adapters/memory')

run(function (assert, comment) {
  var timestamp
  var store = fortune({
    model: {
      name: { type: String },
      junk: { type: Object }
    }
  })

  comment('can run in browser')

  return store.connect()
  .then(function (store) {
    assert(store instanceof fortune, 'instantiation works')
    assert(store.common, 'common dependencies exist')

    return store.adapter.delete('model')
  })
  .then(function () {
    return Promise.all([
      store.request({
        type: 'model',
        method: createMethod,
        payload: [
          { id: 'x-1', name: 'foo' },
          { id: 'x-2', name: 'bar' }
        ]
      }),
      store.request({
        type: 'model',
        method: createMethod,
        payload: [
          { id: 'x-3', name: 'baz' },
          { id: 'x-4', name: 'qux' }
        ]
      })
    ])
  })
  .then(function () {
    assert(true, 'can handle concurrent requests')

    return store.request({
      type: 'model',
      ids: [ 'x-1', 'x-2', 'x-3', 'x-4' ]
    })
  })
  .then(function (response) {
    var i, j, k, obj = { junk: {} }

    assert(response.payload.records.length === 4, 'find works')

    for (i = 100; i--;) {
      obj.junk[i] = {}
      for (j = 100; j--;) {
        obj.junk[i][j] = {}
        for (k = 100; k--;)
          obj.junk[i][j][k] = Math.random()
      }
    }

    comment('giant object')
    timestamp = Date.now()

    return store.request({
      type: 'model',
      method: createMethod,
      payload: [ obj ]
    })
  })
  .then(function () {
    comment('operation took ' + (Date.now() - timestamp) + ' ms')
    assert(true, 'giant object stored')
    return store.disconnect()
  })
})


text:
'use strict';

var EventEmitter = require('events').EventEmitter;
var debug        = require('debug')('nock.socket');
var util = require('util');

module.exports = Socket;

function Socket(options) {
  if (!(this instanceof Socket)) {
    return new Socket(options);
  }

  EventEmitter.apply(this);

  options = options || {};

  if (options.proto === 'https') {
    this.authorized = true;
  }

  this.writable = true;
  this.readable = true;

  this.setNoDelay = noop;
  this.setKeepAlive = noop;
  this.destroy = noop;
  this.resume = noop;

  // totalDelay that has already been applied to the current
  // request/connection, timeout error will be generated if
  // it is timed-out.
  this.totalDelayMs = 0;
  // Maximum allowed delay. Null means unlimited.
  this.timeoutMs = null;
}
util.inherits(Socket, EventEmitter);

Socket.prototype.setTimeout = function setTimeout(timeoutMs, fn) {
  this.timeoutMs = timeoutMs;
  this.timeoutFunction = fn;
};

Socket.prototype.applyDelay = function applyDelay(delayMs) {
  this.totalDelayMs += delayMs;

  if (this.timeoutMs && this.totalDelayMs > this.timeoutMs) {
    debug('socket timeout');
    if (this.timeoutFunction) {
      this.timeoutFunction();
    }
    else {
      this.emit('timeout');
    }
  }

};

Socket.prototype.getPeerCertificate = function getPeerCertificate() {
  return new Buffer((Math.random() * 10000 + Date.now()).toString()).toString('base64');
};

function noop() {}


text:
const socket = require('socket.io-client')
const argv = require('argv')

argv.version('v0.1');
argv.info('Artificial Intelligence for the Zappy project');
const args = argv.option([
    {
        name: 'hub',
        type: 'string',
        description: 'Name of the hub',
        example: "--hub=\"hub1\""
    },
    {
        name: 'name',
        short: 'n',
        type: 'string',
        description: 'Name of the team',
        example: "--name=\"team1\" or -n=\"team1\""
    },
    {
        name: 'host',
        short: 'h',
        type: 'string',
        description: 'Name of the host',
        example: "--host=\"127.0.0.1\" or -h=\"127.0.0.1\""
    },
    {
        name: 'port',
        short: 'p',
        type: 'int',
        description: 'Port number',
        example: "--port=3001 or -p=3001"
    },
]).run()

const port = args.options.port || 3001
const host = args.options.host || 'localhost'

if (!args.options.hub || !args.options.hub.length || !args.options.name || !args.options.name.length) {
    argv.help()
    process.exit(1)
}

const io = socket.connect(`http://${host}:${port}`)

module.exports = { io }

const { start } = require('./start')

io.on('connect', () => {
    console.log(`connected to http://${host}:${port}`)
    io.emit('join', { hubName: args.options.hub, team: args.options.name })
})

let hasStarted = false

io.on('start', () => {
    !hasStarted && start()
     hasStarted = true
})

io.on('forkStart', () => {
    !hasStarted && start()
    hasStarted = true
})


text:
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          <a class="navbar-brand" href="<?=base_url()?>blog/dashboard">100startups

<a href="<?=base_url()?>blog/dashboard">მთავარი

<a href="<?=base_url()?>blog/dashboard/article?type=add">სტატიის დამატება

<a href="<?=base_url()?>blog/dashboard/article?type=view">ჩემი სტატიები

              გამარჯობა,
              <?=$this->db->get_where('blog_users', array('id' => $this->session->userdata('blogger_id')))->result()[0]->fname;?>

<a href="<?=base_url()?>blog/dashboard/profile?type=view">ჩემი პროფილი

<a href="<?=base_url()?>blog/dashboard/profile?type=edit">პროფილის რედაქტირება

<a href="<?=base_url()?>blog/dashboard/logout?type=now">გამოსვლა

<?=$dashSubView;?>


text:
  <md-toolbar md-scroll-shrink>

My Messages

  </md-toolbar>

  <md-content style="height: 600px;" md-theme="altTheme">

      <md-subheader class="md-primary">Unread Messages</md-subheader>
      <md-list layout-padding>
        <md-list-item class="md-3-line" ng-repeat="message in messages">

{{message.what}}

{{message.who}}

                {{message.notes}}

        </md-list-item>
      </md-list>

      <md-subheader class="md-warn">Late Messages</md-subheader>
      <md-list layout="column" layout-padding>
        <md-list-item class="md-3-line" ng-repeat="message in messages">

{{message.what}}

{{message.who}}

              {{message.notes}}

        </md-list-item>
      </md-list>

      <md-subheader>Read Messages</md-subheader>
      <md-list layout="column" layout-padding>
        <md-list-item class="md-3-line" ng-repeat="message in messages">

{{message.what}}

{{message.who}}

              {{message.notes}}

        </md-list-item>
      </md-list>

      <md-subheader class="md-accent">Archived messages</md-subheader>
      <md-list layout="column" layout-padding>
        <md-list-item class="md-3-line" ng-repeat="message in messages">

{{message.what}}

{{message.who}}

              {{message.notes}}

        </md-list-item>
      </md-list>

  </md-content>