text:
package de.bruuff.primeprotect;

import com.flowpowered.math.vector.Vector3d;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import ninja.leaping.configurate.ConfigurationOptions;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.source.ConsoleSource;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.api.effect.particle.ParticleEffect;
import org.spongepowered.api.effect.particle.ParticleTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.entity.DisplaceEntityEvent;
import org.spongepowered.api.event.entity.InteractEntityEvent;
import org.spongepowered.api.event.game.state.GameStartingServerEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.scoreboard.Scoreboard;
import org.spongepowered.api.scoreboard.critieria.Criteria;
import org.spongepowered.api.scoreboard.displayslot.DisplaySlots;
import org.spongepowered.api.scoreboard.objective.Objective;
import org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes;
import org.spongepowered.api.service.ProviderExistsException;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Plugin(id = "PrimeProtect", name = "PrimeProtect", version = "0.1")
public class PrimeProtect {

    @Inject
    public Game game;

    @Inject
    public Logger logger;

    public Map<Player, Plot> showPlotTicks = new HashMap<>();
    Task showPlotTickTask;
    public Map<Player, Plot> playersEditingPlots = new HashMap<>();

    public PropertyService propertyService;
    public UserStorageService userStorageService;

    public PropertyService getPropertyService() {
        return propertyService;
    }

    public CommentedConfigurationNode mainConfig;
    public CommentedConfigurationNode localizationConfig;
    public CommentedConfigurationNode permissionConfig;
    @Inject
    @DefaultConfig(sharedRoot = false)
    private File defaultConfig;

    @Listener
    public void onStart(GameStartingServerEvent event) {
        loadConfig();
        loadCommands();
        runShowPlotTask();

        //Initializing plot management
        try {
            game.getServiceManager().setProvider(this, PropertyService.class, new PlotPropertyService(this));
        } catch (ProviderExistsException e) {
            logger.error("PropertyProvider already exists.");
            e.printStackTrace();
        }

        Optional<PropertyService> optPropertyService = game.getServiceManager().provide(PropertyService.class);
        if(optPropertyService.isPresent()){
            propertyService = optPropertyService.get();
        }else{
            logger.error("Could not get PropertyService.");
        }

        Optional<UserStorageService> optUserStorageService= game.getServiceManager().provide(UserStorageService.class);
        if(optUserStorageService.isPresent()){
            userStorageService = optUserStorageService.get();
        }else{
            logger.error("Could not get UserStorageService.");
        }

    }

    private void loadConfig(){
        //Main plot config
        ConfigurationLoader<CommentedConfigurationNode> configManager = HoconConfigurationLoader.builder().setPath(defaultConfig.toPath()).build();
        try {
            if (!defaultConfig.exists() ) {
                if(defaultConfig.createNewFile()){
                    mainConfig = configManager.createEmptyNode(ConfigurationOptions.defaults());
                    mainConfig.getNode("plots").setComment("The main config file will later hold general configuration like maximum plot sizes, economy support and stuff like that. Currently empty.");

                    configManager.save(mainConfig);
                }
            }
            mainConfig = configManager.load();
        } catch (IOException e) {
            logger.error("Could not write config file.");
        }

        //Localization config
        File localization = new File(defaultConfig.getParent() + "\\localization.conf");
        ConfigurationLoader<CommentedConfigurationNode> localizationConfigManager = HoconConfigurationLoader.builder().setPath(localization.toPath()).build();
        try {
            if (!localization.exists()) {
                if(localization.createNewFile()){
                    localizationConfig = localizationConfigManager.createEmptyNode(ConfigurationOptions.defaults());
                    localizationConfig.setComment("Change it however you like. Unknown failures should not fire, but are a fallback while in development.");
                    localizationConfig.getNode("plot", "new", "SUCCESS").setValue("Now creating new plot in %parent%.");
                    localizationConfig.getNode("plot", "new", "FAILURE_WRONG_USAGE").setValue("Could not create new plot. (Vacant plot already there.)");
                    localizationConfig.getNode("plot", "new", "FAILURE_NO_PERMISSION").setValue("Could not add vertex. (No permission)");
                    localizationConfig.getNode("plot", "new", "FAILURE").setValue("Could not create new plot. (Unknown reason)");
                    localizationConfig.getNode("plot", "exit", "SUCCESS").setValue("Aborted plot creation.");
                    localizationConfig.getNode("plot", "exit", "FAILURE").setValue("You are not claiming a plot right now.");
                    localizationConfig.getNode("plot", "add", "SUCCESS").setValue("Vertex added.");
                    localizationConfig.getNode("plot", "add", "FAILURE_NOT_FOUND").setValue("Could not add vertex. (Start a new plot first)");
                    localizationConfig.getNode("plot", "add", "FAILURE_WRONG_USAGE").setValue("Could not add vertex. (Plot has to be inside parent plot)");
                    localizationConfig.getNode("plot", "add", "FAILURE_INTERSECTS_BORDER").setValue("Could not add vertex. (Plot intersects parent plot border)");
                    localizationConfig.getNode("plot", "add", "FAILURE_BAD_ALIGNMENT").setValue("Could not add vertex. (Border can only be 45° or 90°)");
                    localizationConfig.getNode("plot", "add", "FAILURE_NO_PERMISSION").setValue("Could not add vertex. (No permission)");
                    localizationConfig.getNode("plot", "add", "FAILURE").setValue("Could not add vertex. (Unknown reason)");
                    localizationConfig.getNode("plot", "save", "SUCCESS").setValue("Plot saved.");
                    localizationConfig.getNode("plot", "save", "FAILURE_INTERSECTS_BORDER").setValue("Could not save plot. (Plot has to be inside parent plot)");
                    localizationConfig.getNode("plot", "save", "FAILURE_BAD_ALIGNMENT").setValue("Could not save plot. (Border can only be 45° or 90°)");
                    localizationConfig.getNode("plot", "save", "FAILURE").setValue("Could not save plot. (Unknown reason)");
                    localizationConfig.getNode("plot", "give", "SUCCESS").setValue("Plot given to %ownertype% %receiver%");
                    localizationConfig.getNode("plot", "give", "FAILURE_WRONG_USAGE").setValue("Could not transfer plot. (Plot already owned)");
                    localizationConfig.getNode("plot", "give", "FAILURE_DATABASE_GROUP").setValue("Could not transfer plot. (Group not found)");
                    localizationConfig.getNode("plot", "give", "FAILURE_DATABASE_PLAYER").setValue("Could not transfer plot. (Player not found)");
                    localizationConfig.getNode("plot", "give", "FAILURE_NO_PERMISSION").setValue("Could not transfer plot. (No permission)");
                    localizationConfig.getNode("plot", "give", "FAILURE").setValue("Could not transfer plot. (Unknown reason)");

                    localizationConfig.getNode("group", "new", "SUCCESS").setValue("New Group created.");
                    localizationConfig.getNode("group", "new", "FAILURE_DATABASE_GROUP").setValue("Could not create group. (Group already exists)");
                    localizationConfig.getNode("group", "new", "FAILURE").setValue("Could not create group. (Unknown reason)");
                    localizationConfig.getNode("group", "add", "SUCCESS").setValue("Player %player% added to group %group%.");
                    localizationConfig.getNode("group", "add", "FAILURE_ALREADY_THERE").setValue("Could not add player %player% to group %group%. (Player already in group)");
                    localizationConfig.getNode("group", "add", "FAILURE_DATABASE_GROUP").setValue("Could not add player %player% to group %group%. (Group not found)");
                    localizationConfig.getNode("group", "add", "FAILURE_DATABASE_PLAYER").setValue("Could not add player %player% to group %group%. (Player not found)");
                    localizationConfig.getNode("group", "add", "FAILURE").setValue("Could not add player %player% to group %group%. (Unknown reason)");
                    localizationConfig.getNode("group", "remove", "SUCCESS").setValue("Player %player% removed from group %group%.");
                    localizationConfig.getNode("group", "remove", "FAILURE_NOT_FOUND").setValue("Could not remove player %player% from group %group%. (Player not in group)");
                    localizationConfig.getNode("group", "remove", "FAILURE_DATABASE_GROUP").setValue("Could not remove player %player% from group %group%. (Group not found)");
                    localizationConfig.getNode("group", "remove", "FAILURE_DATABASE_PLAYER").setValue("Could not remove player %player% from group %group%. (Player not found)");
                    localizationConfig.getNode("group", "remove", "FAILURE").setValue("Could not remove %player% from group %group%. (Unknown reason)");

                    localizationConfig.getNode("group", "rank", "SUCCESS").setValue("Player %player% is now ranked %rank% in group %group%.");
                    localizationConfig.getNode("group", "rank", "FAILURE_NOT_FOUND").setValue("Could not rank player %player% in group %group%. (Player not in group)");
                    localizationConfig.getNode("group", "rank", "FAILURE_DATABASE_GROUP").setValue("Could not rank player %player% in group %group%. (Group not found)");
                    localizationConfig.getNode("group", "rank", "FAILURE_DATABASE_PLAYER").setValue("Could not rank player %player% in group %group%. (Player not found)");
                    localizationConfig.getNode("group", "rank", "FAILURE").setValue("Could not rank player %player% in group %group%. (Unknown reason)");

                    localizationConfig.getNode("group", "list", "SUCCESS").setValue("Groups:");
                    localizationConfig.getNode("group", "list", "FAILURE").setValue("There are no groups yet.");
                    localizationConfigManager.save(localizationConfig);
                }
            }
            localizationConfig = localizationConfigManager.load();
        } catch (IOException e) {
            logger.error("Could not write config file.");
        }

        //Permission config
        File permissions = new File(defaultConfig.getParent() + "\\permissions.conf");
        ConfigurationLoader<CommentedConfigurationNode> permissionsConfigManager = HoconConfigurationLoader.builder().setPath(permissions.toPath()).build();
        try {
            if (!permissions.exists()) {
                if(permissions.createNewFile()){
                    permissionConfig = localizationConfigManager.createEmptyNode(ConfigurationOptions.defaults());

                    permissionConfig.setComment("Define what rank the player in plot has to be at least, do do certain things. (3=operator, 2=assistant, 1=member, 0=outsider");

                    permissionConfig.getNode("plot", "build").setValue(2);
                    permissionConfig.getNode("plot", "break").setValue(2);
                    permissionConfig.getNode("plot", "entity").setValue(1);
                    permissionConfig.getNode("plot", "use").setValue(0);
                    permissionConfig.getNode("plot", "claim").setValue(2);
                    permissionConfig.getNode("plot", "give").setValue(2);
                    permissionConfig.getNode("plot", "rename").setValue(3);
                    permissionConfig.getNode("plot", "delete").setValue(3);

                    permissionConfig.getNode("group", "add").setValue(2);
                    permissionConfig.getNode("group", "list").setValue(0);
                    permissionConfig.getNode("group", "remove").setValue(3);
                    permissionConfig.getNode("group", "rank").setValue(3);

                    permissionsConfigManager.save(permissionConfig);
                }
            }
            permissionConfig = permissionsConfigManager.load();
        } catch (IOException e) {
            logger.error("Could not write config file.");
        }
    }

    private void loadCommands(){
        CommandSpec primePlotNewCmd = CommandSpec.builder().description(Texts.of("Claim a new vacant plot."))
                .permission("primeprotect.plot.claim")
                .arguments( GenericArguments.none() )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        dictionary.put("player", player.getName());
                        Response response;

                        if(playersEditingPlots.containsKey(player)) {
                            //We dont need this anymore (Not that it would hurt as it has no area)
                            this.getPropertyService().deletePlot(playersEditingPlots.get(player).getId());
                        }

                        Plot parentPlot = this.getPropertyService().getPlot(player.getLocation()); // Worst case: Wilderness

                        //Put names in dictionary for response handling
                        dictionary.put("parent", parentPlot.getDisplayName());
                        Plot plot = null;

                        if(parentPlot.getOwner().isPresent()){
                            PlotOwner parentOwner = parentPlot.getOwner().get();
                            //If you are in the current plot at least the rank it takes to claim...
                            if(parentOwner.containsUser(player.getUniqueId(), Rank.valueOf(permissionConfig.getNode("plot", "claim").getInt()))){
                                plot = this.getPropertyService().createPlot(Optional.empty(), player.getWorld(), parentPlot);
                                dictionary.put("plot", plot.getDisplayName());
                                response = plot.addPoint(new PlotPoint(player.getLocation().getBlockX(), player.getLocation().getBlockZ()));
                                showPlotTicks.put(player, plot);
                                playersEditingPlots.put(player, plot);
                                this.updateScoreboard(plot, player);
                            }else response = Response.FAILURE_NO_PERMISSION; //Player has not the right permission to claim here.
                        }else response = Response.FAILURE_WRONG_USAGE; //Only in vacant plots, so there has to be already one.
                        player.sendMessage(makeResponse(localizationConfig.getNode("plot", "new"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't claim."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primePlotExitCmd = CommandSpec.builder().description(Texts.of("Exit plot creation."))
                .permission("primeprotect.plot.claim")
                .arguments( GenericArguments.none() )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        dictionary.put("player", player.getName());
                        Response response;

                        if(playersEditingPlots.containsKey(player)) {
                            this.getPropertyService().deletePlot(playersEditingPlots.get(player).getId());
                            playersEditingPlots.remove(player);
                            showPlotTicks.remove(player);
                            this.clearScoreboard(player);
                            response = Response.SUCCESS;
                        }else response = Response.FAILURE_WRONG_USAGE;

                        player.sendMessage(makeResponse(localizationConfig.getNode("plot", "exit"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't claim."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primePlotAddCmd = CommandSpec.builder().description(Texts.of("Add vertex to a current claim"))
                .permission("primeprotect.plot.claim")
                .arguments( GenericArguments.none() )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        dictionary.put("player", player.getName());
                        Location<World> location = player.getLocation();
                        dictionary.put("location", location.toString());
                        Response response;
                        Plot parentPlot = this.getPropertyService().getPlot(player.getLocation()); // Worst case: Wilderness

                        //Put names in dictionary for response handling
                        dictionary.put("parent", parentPlot.getDisplayName());
                        if(playersEditingPlots.containsKey(player)){
                            Plot plot = playersEditingPlots.get(player);
                            dictionary.put("plot", plot.getDisplayName());
                            Optional<Plot> optParentPlot2 = plot.getParent();
                            if(optParentPlot2.isPresent()){
                                Plot parentPlot2 = optParentPlot2.get();
                                if(parentPlot.equals(parentPlot2) || parentPlot.getOwner().isPresent()){
                                    PlotOwner parentOwner = parentPlot.getOwner().get();
                                    //If you are in the current plot at least the rank it takes to claim...
                                    if(parentOwner.containsUser(player.getUniqueId(), Rank.valueOf(permissionConfig.getNode("plot", "claim").getInt()))){
                                        response = plot.addPoint(new PlotPoint(location.getBlockX(), location.getBlockZ()));
                                        showPlotTicks.put(player, plot);
                                        playersEditingPlots.put(player, plot);
                                        this.updateScoreboard(plot, player);
                                    }else response = Response.FAILURE_NO_PERMISSION; //Player has not the right permission to claim here.
                                }else response = Response.FAILURE_WRONG_USAGE; //Only in vacant plots, so there has to be already one.
                            }else response = Response.FAILURE; //You can't edit wilderness. Can't imagine how this would even happen.
                        }else response = Response.FAILURE_NOT_FOUND; //Player has to start the claiming of a new plot first.

                        player.sendMessage(makeResponse(localizationConfig.getNode("plot", "add"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't claim."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primePlotSaveCmd = CommandSpec.builder().description(Texts.of("Saves plot as vacant plot for sale to others"))
                .permission("primeprotect.plot.claim")
                .arguments( GenericArguments.none() )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        dictionary.put("player", player.getName());
                        Response response;
                        if(playersEditingPlots.containsKey(player)){
                            Plot plot = playersEditingPlots.get(player);
                            //Put names in dictionary for response handling
                            dictionary.put("plot", plot.getDisplayName());
                            if (plot.isComplete()) {
                                if (plot.isValidShape()) {
                                    this.getPropertyService().savePlot(plot);
                                    playersEditingPlots.remove(player);
                                    showPlotTicks.remove(player);
                                    this.clearScoreboard(player);
                                    response = Response.SUCCESS;
                                }else response = Response.FAILURE_INTERSECTS_BORDER; //Closing line would intersect forbidden territory
                            }else response = Response.FAILURE_BAD_ALIGNMENT; //Closing line does not align correctly
                        }else response = Response.FAILURE_WRONG_USAGE; //Player has to start the claiming of a new plot first.
                        player.sendMessage(makeResponse(localizationConfig.getNode("plot", "save"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't claim."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primePlotGiveCmd = CommandSpec.builder().description(Texts.of("Give a plot to another player or group"))
                .permission("primeprotect.plot.give")
                .arguments(GenericArguments.choices(Texts.of("ownertype"), ImmutableMap.of("player", "player", "group","group")), GenericArguments.string(Texts.of("name")) )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        Response response;
                        Map<String, String> dictionary = new HashMap<>();
                        dictionary.put("player", player.getName());
                        String receiverName = args.<String>getOne("name").get();
                        String ownerType = args.<String>getOne("ownertype").get();
                        dictionary.put("ownertype", ownerType);

                        Optional<User> optReceiverUser = userStorageService.get(receiverName);
                        Optional<Group> optReceiverGroup = this.getPropertyService().getGroup(receiverName);
                        Plot plot = this.getPropertyService().getPlot(player.getLocation());

                        if(plot.getCurrentOwner().containsUser(player.getUniqueId(), Rank.valueOf(permissionConfig.getNode("plot", "give").getInt()))){
                            if(ownerType.equals("player") && optReceiverUser.isPresent()){
                                User receiver = optReceiverUser.get();
                                dictionary.put("receiver", receiver.getName());
                                plot.setOwner(new PlotOwner(receiver.getUniqueId()));
                                this.getPropertyService().savePlot(plot);
                                response = Response.SUCCESS;
                            }else if(ownerType.equals("group") && optReceiverGroup.isPresent()){
                                Group receiver = optReceiverGroup.get();
                                dictionary.put("receiver", receiver.getName());
                                plot.setOwner(new PlotOwner(receiver));
                                this.getPropertyService().savePlot(plot);
                                response = Response.SUCCESS;
                            }else{
                                if(ownerType.equals("player")) response = Response.FAILURE_DATABASE_PLAYER; //Player not found
                                else response = Response.FAILURE_DATABASE_GROUP; //Group not found
                            }
                        }else response = Response.FAILURE_NO_PERMISSION; //You can't give away what isn't yours.

                        player.sendMessage(makeResponse(localizationConfig.getNode("plot", "give"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't do that."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primePlotCmd = CommandSpec.builder()
                .description(Texts.of("PrimeProtect Plot Management"))
                //.arguments(GenericArguments.remainingJoinedStrings(Texts.of("text")))
                .executor((src, args) -> {
                    //String choice = args.<String>getOne("action").get();
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        player.sendMessage(Texts.of("plot help"));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't use that."));
                    }
                    return CommandResult.success();
                })
                .child(primePlotNewCmd, "new", "create")
                .child(primePlotExitCmd, "exit", "abort", "break")
                .child(primePlotAddCmd, "add")
                .child(primePlotSaveCmd, "save", "done")
                .child(primePlotGiveCmd, "give")
                .build();

        CommandSpec primeGroupNewCmd = CommandSpec.builder().description(Texts.of("Create a new group"))
                .permission("primeprotect.group.new")
                .arguments( GenericArguments.onlyOne(GenericArguments.string(Texts.of("name"))) )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        String name = args.<String>getOne("name").get();
                        Map<String, String> dictionary = new HashMap<>();
                        Response response;
                        dictionary.put("player", player.getName());
                        dictionary.put("group", name);
                        Optional<Group> optExistingGroup = this.getPropertyService().getGroup(name);
                        if(!optExistingGroup.isPresent()){
                            this.getPropertyService().createGroup(name, player.getUniqueId());
                            response = Response.SUCCESS;
                        }else response = Response.FAILURE_DATABASE_GROUP; //Name already in use
                        player.sendMessage(makeResponse(localizationConfig.getNode("group", "new"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't do that."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeGroupAddCmd = CommandSpec.builder().description(Texts.of("Add a player to a group"))
                .permission("primeprotect.group.add")
                .arguments( GenericArguments.string(Texts.of("group")), GenericArguments.string(Texts.of("player")) )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Response response;
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        String groupName = args.<String>getOne("group").get();
                        dictionary.put("group", groupName);
                        String newMemberName = args.<String>getOne("player").get();
                        Optional<User> optNewMember = userStorageService.get(newMemberName);
                        if(optNewMember.isPresent()){
                            User newMember = optNewMember.get();
                            dictionary.put("player", newMember.getName());
                            Optional<Group> optGroup = this.getPropertyService().getGroup(groupName);
                            if(optGroup.isPresent()){
                                Group group = optGroup.get();
                                if(group.addUser(newMember.getUniqueId(), Rank.MEMBER)){
                                    response = Response.SUCCESS;
                                    this.getPropertyService().saveGroup(group);
                                }else response = Response.FAILURE_ALREADY_THERE; // Player already in group
                            }else response = Response.FAILURE_DATABASE_GROUP; //Could not find group
                        }else response = Response.FAILURE_DATABASE_PLAYER; //Could not find player

                        player.sendMessage(makeResponse(localizationConfig.getNode("group", "add"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't do that."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeGroupRemoveCmd = CommandSpec.builder().description(Texts.of("Remove a player from a group"))
                .permission("primeprotect.group.remove")
                .arguments( GenericArguments.string(Texts.of("group")), GenericArguments.string(Texts.of("player")) )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Response response;
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        String groupName = args.<String>getOne("group").get();
                        dictionary.put("group", groupName);
                        String memberName = args.<String>getOne("player").get();
                        Optional<User> optMember = userStorageService.get(memberName);
                        if(optMember.isPresent()){
                            User member = optMember.get();
                            dictionary.put("player", member.getName());
                            Optional<Group> optGroup = this.getPropertyService().getGroup(groupName);
                            if(optGroup.isPresent()){
                                Group group = optGroup.get();
                                if(group.removeUser(member.getUniqueId())){
                                    response = Response.SUCCESS;
                                    this.getPropertyService().saveGroup(group);
                                }else response = Response.FAILURE_NOT_FOUND; // Player not in group.
                            }else response = Response.FAILURE_DATABASE_GROUP; //Could not find group
                        }else response = Response.FAILURE_DATABASE_PLAYER; //Could not find player

                        player.sendMessage(makeResponse(localizationConfig.getNode("group", "remove"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't do that."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeGroupRankCmd = CommandSpec.builder().description(Texts.of("Rank a player in a group"))
                .permission("primeprotect.group.rank")
                .arguments( GenericArguments.string(Texts.of("group")), GenericArguments.string(Texts.of("player")), GenericArguments.choices(Texts.of("rank"), ImmutableMap.of("operator", "operator", "assistant", "assistant", "member", "member")) )
                .executor((src, args) -> {
                    if (src instanceof Player) {
                        Response response;
                        Player player = (Player) src;
                        Map<String, String> dictionary = new HashMap<>();
                        String groupName = args.<String>getOne("group").get();
                        dictionary.put("group", groupName);
                        String rankstring = args.<String>getOne("rank").get();
                        dictionary.put("rank", rankstring.toUpperCase());

                        String memberName = args.<String>getOne("player").get();
                        Optional<User> optMember = userStorageService.get(memberName);
                        if(optMember.isPresent()){
                            User member = optMember.get();
                            dictionary.put("player", member.getName());
                            Optional<Group> optGroup = this.getPropertyService().getGroup(groupName);
                            if(optGroup.isPresent()){
                                Group group = optGroup.get();
                                if(Rank.valueOf(rankstring.toUpperCase()) != null){
                                    if(group.rankUser(member.getUniqueId(), Rank.valueOf(rankstring.toUpperCase()))){
                                        response = Response.SUCCESS;
                                        this.getPropertyService().saveGroup(group);
                                    }else response = Response.FAILURE_NOT_FOUND; // Player not in group.
                                }else response = Response.FAILURE; // Could not find rank (should always be the case though
                            }else response = Response.FAILURE_DATABASE_GROUP; //Could not find group
                        }else response = Response.FAILURE_DATABASE_PLAYER; //Could not find player

                        player.sendMessage(makeResponse(localizationConfig.getNode("group", "rank"), response, dictionary));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't do that."));
                    }
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeGroupCmd = CommandSpec.builder()
                .description(Texts.of("PrimeProtect info"))
                .executor((src, args) -> {
                    src.sendMessage(Texts.of("group help"));
                    return CommandResult.success();
                })
                .child(primeGroupNewCmd, "new")
                .child(primeGroupAddCmd, "add")
                .child(primeGroupRemoveCmd, "remove")
                .child(primeGroupRankCmd, "rank")
                .build();

        CommandSpec primeReloadCmd = CommandSpec.builder()
                .description(Texts.of("PrimeProtect reload"))
                .executor((src, args) -> {
                    loadConfig();
                    src.sendMessage(Texts.of("Config reloaded."));
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeInfoCmd = CommandSpec.builder()
                .description(Texts.of("PrimeProtect info"))
                .executor((src, args) -> {
                    src.sendMessage(Texts.of("*PrimeProtect info page.*"));
                    return CommandResult.success();
                })
                .build();

        CommandSpec primeCmd = CommandSpec.builder()
                .description(Texts.of("Prime help page"))
                //.arguments(GenericArguments.remainingJoinedStrings(Texts.of("text")))
                .executor((src, args) -> {
                    //String choice = args.<String>getOne("action").get();
                    if (src instanceof Player) {
                        Player player = (Player) src;
                        player.sendMessage(Texts.of("general help"));
                    } else if (src instanceof ConsoleSource) {
                        src.sendMessage(Texts.of("You are a console and can't use that."));
                    }
                    return CommandResult.success();
                })
                .child(primePlotCmd, "plot")
                .child(primeGroupCmd, "group")
                .child(primeReloadCmd, "reload")
                .child(primeInfoCmd, "info")
                .build();
        game.getCommandManager().register(this, primeCmd, "prime");
    }

    public Text makeResponse(CommentedConfigurationNode responseNode, Response response, Map<String, String> dictionary){
        String responseString;
        Text responseText;
        if(responseNode.getNode(response.toString()).getString() != null) {
            responseString = responseNode.getNode(response.toString()).getString();
        }else if(responseNode.getNode("FAILURE").getString() != null) {
            responseString = responseNode.getNode("FAILURE").getString();
        }else{
            responseString = "Command executed (check localization file!).";
        }

        for (Map.Entry<String, String> entry : dictionary.entrySet()){
            responseString = responseString.replaceAll("%" + entry.getKey() +  "%", entry.getValue());
        }

        if(response.toString().startsWith("SUCCESS")) {
            responseText = Texts.of(TextColors.GREEN, responseString);
        }else{
            responseText = Texts.of(TextColors.RED, responseString);
        }
        return responseText;
    }

    @Listener
    public void onMove(DisplaceEntityEvent.TargetPlayer event){
        if(!(event.getFromTransform().getPosition().getFloorX() == event.getToTransform().getPosition().getFloorX())
                || !(event.getFromTransform().getPosition().getFloorZ() == event.getToTransform().getPosition().getFloorZ()) ){

            Plot plotFrom = propertyService.getPlot(event.getFromTransform().getPosition(), event.getTargetEntity().getWorld());
            Plot plotTo = propertyService.getPlot(event.getToTransform().getPosition(), event.getTargetEntity().getWorld());

            if(plotFrom.getId() != plotTo.getId()){
                String message = "" + plotTo.getDisplayName();
                List<Plot> plotFromParentChain = plotFrom.getParentChain();
                for(Plot ancestor: plotTo.getParentChain()){
                    if(plotFromParentChain.contains(ancestor)) break; //If that happens, all further down the line must also be the same, so skip mentioning it.

                    message = ancestor.getDisplayName() + " -> " + message;
                }
                event.getTargetEntity().sendMessage(Texts.of(TextColors.GRAY , "~ " + message));
            }
        }
    }

    @Listener
    public void onBlockChange(ChangeBlockEvent event){
        Optional<Player> playerOptional = event.getCause().first(Player.class);
        Optional<BlockSnapshot> blockOptional = event.getCause().first(BlockSnapshot.class);
        if(!playerOptional.isPresent()) return;
        Player player = playerOptional.get();

        //Still have to test how powerful this is. I might be cancelling to much right now.

        //Fluids cause a lot of updates, allow all for now and revisit later.
        if(blockOptional.isPresent()){
            if(blockOptional.get().getState().getType().equals(BlockTypes.FLOWING_WATER) || blockOptional.get().getState().getType().equals(BlockTypes.FLOWING_LAVA)){
                return;
            }
        }

        event.getTransactions().stream()
                .filter(transaction -> transaction.getOriginal().getLocation().isPresent())
                .filter(transaction -> !checkPermission(transaction.getOriginal().getLocation().get(), player))
                .forEach(transaction -> {
            transaction.setValid(false);
            player.sendMessage(Texts.of(TextColors.RED, "You are not allowed to do this."));
        });
    }

    @Listener
    public void onEntityInteract(InteractEntityEvent event){
        Optional<Player> playerOptional = event.getCause().first(Player.class);
        if(!playerOptional.isPresent()) return;
        Player player = playerOptional.get();
        if(!checkPermission(event.getTargetEntity().getLocation(), player)){
            player.sendMessage(Texts.of(TextColors.RED, "You are not allowed to do this."));
            event.setCancelled(true);
        }
    }

    private boolean checkPermission(Location<World> location, User user){
        Plot plot = this.getPropertyService().getPlot(location);
        PlotOwner plotOwner;
        if(plot.getOwner().isPresent()) {
            plotOwner = plot.getOwner().get();
        }else{ //Vacent lot, check parent
            if(plot.getParent().isPresent()){
                if(plot.getParent().get().getOwner().isPresent()){
                    plotOwner = plot.getParent().get().getOwner().get();
                }else{
                    return false; //Something is bugged.
                }
            }else{
                plotOwner = new PlotOwner(Group.everyone());
            }

        }
        return plotOwner.containsUser(user.getUniqueId(), Rank.valueOf(permissionConfig.getNode("plot", "place").getInt()));
    }

    public void runShowPlotTask(){
        if(showPlotTickTask != null) showPlotTickTask.cancel();
        Task.Builder taskBuilder = game.getScheduler().createTaskBuilder();

        showPlotTickTask = taskBuilder.execute(() -> {
            for (Map.Entry<Player, Plot> entry : showPlotTicks.entrySet()) {
                showPlot(entry.getValue(), entry.getKey());
            }
        }).interval(200, TimeUnit.MILLISECONDS).name("PlotBorderVisualizer").submit(this);
    }

    private void showPlot(Plot plot, Player player){
        ParticleEffect.Builder pe_builder =  game.getRegistry().createBuilder(ParticleEffect.Builder.class);
        World world = player.getWorld();
        for(PlotLine plotLine: plot.getBorderBlocksLines()){
            player.spawnParticles(pe_builder.type(ParticleTypes.FIREWORKS_SPARK).motion(new Vector3d(0,-0.1,0)).count(1).build(), world.getLocation(plotLine.getP1().getX(), player.getLocation().getBlockY()+3, plotLine.getP1().getZ()).getPosition(), 10);
            double x_m = (plotLine.getP1().getX() + plotLine.getP2().getX())/2;
            double z_m = (plotLine.getP1().getZ() + plotLine.getP2().getZ())/2;
            player.spawnParticles(pe_builder.type(ParticleTypes.FIREWORKS_SPARK).motion(new Vector3d(0,-0.1,0)).count(1).build(), world.getLocation(x_m, player.getLocation().getBlockY()+3, z_m).getPosition(), 10);
        }
        for(PlotPoint vertex: plot.getVertices()){
            Location<World> currentLocation = world.getLocation(vertex.getX() + 0.5, player.getLocation().getBlockY()-1.5, vertex.getZ() + 0.5);
            for(int i = -5; i <= 5; i++){
                player.spawnParticles(pe_builder.type(ParticleTypes.SMOKE_LARGE).motion(new Vector3d(0,0.01,0)).count(1).build(), currentLocation.getPosition().add(0,i,0), 10);
            }
        }
    }

    public void updateScoreboard(Plot plot, Player player){
        Scoreboard scoreboard = player.getScoreboard();
        Optional<Objective> optObjective = scoreboard.getObjective("plot");
        if(optObjective.isPresent()) scoreboard.removeObjective(optObjective.get());

        Objective obj = game.getRegistry().createBuilder(Objective.Builder.class).name("plot").criterion(Criteria.DUMMY).objectiveDisplayMode(ObjectiveDisplayModes.INTEGER).displayName(Texts.of(TextColors.YELLOW, "Plot Editor")).build();
        for(PlotPoint vertex: plot.getVertices()){
            if(vertex.equals(plot.getVertices().get(plot.getVertices().size() - 1) ) && !plot.isComplete() ){
                obj.getScore(Texts.of(TextColors.RED, vertex.toString())).setScore(0);
            }else{
                obj.getScore(Texts.of(TextColors.GREEN, vertex.toString())).setScore(0);
            }
        }
        scoreboard.addObjective(obj);
        scoreboard.addObjective(obj, DisplaySlots.SIDEBAR);
    }

    public void clearScoreboard(Player player){
        Scoreboard scoreboard = player.getScoreboard();
        Optional<Objective> optObjective = scoreboard.getObjective("plot");
        if(optObjective.isPresent()) scoreboard.removeObjective(optObjective.get());
    }

}


text:
import math

from .Observation import Observation

class Humidity(object):

  def __init__(self, air_temp, dew_point):
    ''' both must be temperature objects
        100*(EXP((17.625*TD)/(243.04+TD))/EXP((17.625*T)/(243.04+T))) '''
    try:
      self.humidity = 100*(math.exp((17.625*float(dew_point))/(243.04+float(dew_point)))/math.exp((17.625*float(air_temp))/(243.04+float(air_temp))))
      self.humidity = round(self.humidity)
    except:
      self.humidity = "MISSING"

  def __str__(self):
    return str(self.humidity)

  def __eq__(self, other_value):
    if self.humidity == other_value:
      return True
    return False

  def get_numeric(self):
      if self.humidity == "MISSING":
          return float('NaN')
      else:
          return self.humidity

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.siyeh.ig.style;

import com.intellij.codeInspection.ex.InspectionElementsMergerBase;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Bas Leijdekkers
 */
public class ConstantOnWrongSideOfComparisonInspectionMerger extends InspectionElementsMergerBase {

  @NonNls private static final String CONSTANT_ON_LHS = "ConstantOnLHSOfComparison";
  @NonNls private static final String CONSTANT_ON_RHS = "ConstantOnRHSOfComparison";

  @NotNull
  @Override
  public String getMergedToolName() {
    return "ConstantOnWrongSideOfComparison";
  }

  @Override
  public String @NotNull [] getSourceToolNames() {
    return new String[] {
      CONSTANT_ON_LHS,
      CONSTANT_ON_RHS
    };
  }

  @Override
  public String @NotNull [] getSuppressIds() {
    return new String[] {
      "ConstantOnLeftSideOfComparison",
      "ConstantOnRightSideOfComparison"
    };
  }

  @Override
  protected boolean isEnabledByDefault(@NotNull String sourceToolName) {
    return false;
  }

  @Override
  protected boolean writeMergedContent(@NotNull Element toolElement) {
    // merged tool is not enabled by default, so always needs to be written when either of the source tools were enabled
    return Boolean.parseBoolean(toolElement.getAttributeValue("enabled", "false"));
  }

  @Override
  protected Element transformElement(@NotNull String sourceToolName, @NotNull Element sourceElement, @NotNull Element toolElement) {
    if (CONSTANT_ON_LHS.equals(sourceToolName) && Boolean.parseBoolean(sourceElement.getAttributeValue("enabled", "false"))) {
      toolElement.setAttribute("enabled", "true");
    }
    else if (CONSTANT_ON_RHS.equals(sourceToolName)
             && !Boolean.parseBoolean(toolElement.getAttributeValue("enabled", "false"))
             && Boolean.parseBoolean(sourceElement.getAttributeValue("enabled", "false"))) {
      toolElement.addContent(new Element("option").setAttribute("name", "myConstantShouldGoLeft").setAttribute("value", "false"));
      toolElement.setAttribute("enabled", "true");
    }
    return toolElement;
  }
}


text:
//
//  YPHomeController.m
//  YPMTHD
//
//  Created by 胡云鹏 on 15/11/29.
//  Copyright © 2015年 tyiti. All rights reserved.
//

#import "YPHomeController.h"
#import "YPHomeTopItem.h"

@interface YPHomeController ()

@end

@implementation YPHomeController

static NSString * const reuseIdentifier = @"Cell";

- (instancetype)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    return [self initWithCollectionViewLayout:layout];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    /**
     *  tableView self.view == self.tableView
     *  collectionView self.view == self.collectionView.superview
     */

    self.collectionView.backgroundColor = YPLightGrayColor;

    // Register cell classes
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    // 设置导航栏内容
    [self setupLeftNav];
    [self setupRightNav];
}

#pragma mark - 设置导航栏内容 -
- (void)setupLeftNav
{
    // 1.LOGO
    UIBarButtonItem *logo = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_meituan_logo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:nil action:nil];

    logo.enabled = NO;

    // 2.类别
    YPHomeTopItem *categoryItem = [YPHomeTopItem item];
    [categoryItem addTarget:self action:@selector(categoryClick)];

    UIBarButtonItem *category = [[UIBarButtonItem alloc] initWithCustomView:categoryItem];

    // 3.地区
    YPHomeTopItem *districtItem = [YPHomeTopItem item];
    [districtItem addTarget:self action:@selector(districtClick)];

    UIBarButtonItem *district = [[UIBarButtonItem alloc] initWithCustomView:districtItem];

    // 4.排序
    YPHomeTopItem *sortItem = [YPHomeTopItem item];
    [sortItem addTarget:self action:@selector(sortClick)];

    UIBarButtonItem *sort = [[UIBarButtonItem alloc] initWithCustomView:sortItem];

    self.navigationItem.leftBarButtonItems = @[logo,category,district,sort];
}

- (void)setupRightNav
{
    UIBarButtonItem *map = [UIBarButtonItem itemWithTarget:nil action:nil image:@"icon_map" highImage:@"icon_map_highlighted"];
    map.customView.width = 60;

    UIBarButtonItem *search = [UIBarButtonItem itemWithTarget:nil action:nil image:@"icon_search" highImage:@"icon_search_highlighted"];
    search.customView.width = 60;

    self.navigationItem.rightBarButtonItems = @[map,search];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#warning Incomplete implementation, return the number of sections
    return 0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of items
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    // Configure the cell

    return cell;
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {

}
*/

#pragma mark - 功能性方法 -
- (void)categoryClick
{
    YPLog(@"categoryClick");
}

- (void)districtClick
{
    YPLog(@"districtClick");
}

- (void)sortClick
{
    YPLog(@"sortClick");
}

@end


text:
<!---
This file is reset every time a new release is done. The contents of this file are for the currently unreleased version.

Example Note:

## Example Heading
Details about the thing that changed that needs to get included in the Release Notes in markdown.
-->

# Ohai Release Notes:

## Amazon EC2

- Windows instances running Amazon created AMIs will now be automatically detected as running in AWS
- Linux AWS detect has been improved and false detection of systems running in other clouds have been resolved.

## Packages Plugin

The packages plugin no longer requires Ohai configuration to enable the plugin. Any existing configuration will be ignored and can be removed.

## Shell Out Timeout

Plugins that shellout via the shell_out helper will now timeout after 30 seconds to prevent hung runs. The helper also includes the ability to change this time if necessary in your own plugins.


text:
#include <getopt.h>
#include <inttypes.h>		/* For PRIu64 */
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "2api.h"
#include "2common.h"
#include "2rsa.h"
#include "2sysincludes.h"
#include "futility.h"
#include "host_common.h"
#include "host_key21.h"
#include "kernel_blob.h"
#include "util_misc.h"
#include "vb1_helper.h"

/* Command line options */
enum {
	OPT_MODE_VBLOCK = 1000,
	OPT_MODE_VERIFY,
	OPT_KEYBLOCK,
	OPT_SIGNPUBKEY,
	OPT_SIGNPRIVATE,
	OPT_VERSION,
	OPT_FV,
	OPT_KERNELKEY,
	OPT_FLAGS,
	OPT_HELP,
};

static const struct option long_opts[] = {
	{"vblock", 1, 0, OPT_MODE_VBLOCK},
	{"verify", 1, 0, OPT_MODE_VERIFY},
	{"keyblock", 1, 0, OPT_KEYBLOCK},
	{"signpubkey", 1, 0, OPT_SIGNPUBKEY},
	{"signprivate", 1, 0, OPT_SIGNPRIVATE},
	{"version", 1, 0, OPT_VERSION},
	{"fv", 1, 0, OPT_FV},
	{"kernelkey", 1, 0, OPT_KERNELKEY},
	{"flags", 1, 0, OPT_FLAGS},
	{"help", 0, 0, OPT_HELP},
	{NULL, 0, 0, 0}
};

/* Print help and return error */
static void print_help(int argc, char *argv[])
{
	printf("\nUsage:  " MYNAME " %s <--vblock|--verify> <file> [OPTIONS]\n"
	       "\n"
	       "For '--vblock <file>', required OPTIONS are:\n"
	       "\n"
	       "  --keyblock <file>           Keyblock in .keyblock format\n"
	       "  --signprivate <file>"
	       "        Signing private key in .vbprivk format\n"
	       "  --version <number>          Firmware version\n"
	       "  --fv <file>                 Firmware volume to sign\n"
	       "  --kernelkey <file>          Kernel subkey in .vbpubk format\n"
	       "\n"
	       "optional OPTIONS are:\n"
	       "  --flags <number>            Preamble flags (defaults to 0)\n"
	       "\n"
	       "For '--verify <file>', required OPTIONS are:\n"
	       "\n"
	       "  --signpubkey <file>"
	       "         Signing public key in .vbpubk format\n"
	       "  --fv <file>                 Firmware volume to verify\n"
	       "\n"
	       "For '--verify <file>', optional OPTIONS are:\n"
	       "  --kernelkey <file>"
	       "          Write the kernel subkey to this file\n\n",
	       argv[0]);
}

/* Create a firmware .vblock */
static int do_vblock(const char *outfile, const char *keyblock_file,
		     const char *signprivate, uint32_t version,
		     const char *fv_file, const char *kernelkey_file,
		     uint32_t preamble_flags)
{
	struct vb2_keyblock *keyblock = NULL;
	struct vb2_private_key *signing_key = NULL;
	struct vb2_packed_key *kernel_subkey = NULL;
	struct vb2_signature *body_sig = NULL;
	struct vb2_fw_preamble *preamble = NULL;
	uint8_t *fv_data = NULL;
	int retval = 1;

	if (!outfile) {
		FATAL("Must specify output filename\n");
		goto vblock_cleanup;
	}
	if (!keyblock_file || !signprivate || !kernelkey_file) {
		FATAL("Must specify all keys\n");
		goto vblock_cleanup;
	}
	if (!fv_file) {
		FATAL("Must specify firmware volume\n");
		goto vblock_cleanup;
	}

	/* Read the keyblock and keys */
	keyblock = vb2_read_keyblock(keyblock_file);
	if (!keyblock) {
		FATAL("Error reading keyblock.\n");
		goto vblock_cleanup;
	}

	signing_key = vb2_read_private_key(signprivate);
	if (!signing_key) {
		FATAL("Error reading signing key.\n");
		goto vblock_cleanup;
	}

	kernel_subkey = vb2_read_packed_key(kernelkey_file);
	if (!kernel_subkey) {
		FATAL("Error reading kernel subkey.\n");
		goto vblock_cleanup;
	}

	/* Read and sign the firmware volume */
	uint32_t fv_size;
	if (VB2_SUCCESS != vb2_read_file(fv_file, &fv_data, &fv_size))
		goto vblock_cleanup;
	if (!fv_size) {
		FATAL("Empty firmware volume file\n");
		goto vblock_cleanup;
	}
	body_sig = vb2_calculate_signature(fv_data, fv_size, signing_key);
	if (!body_sig) {
		FATAL("Error calculating body signature\n");
		goto vblock_cleanup;
	}

	/* Create preamble */
	preamble = vb2_create_fw_preamble(version, kernel_subkey, body_sig,
					  signing_key, preamble_flags);
	if (!preamble) {
		FATAL("Error creating preamble.\n");
		goto vblock_cleanup;
	}

	/* Write the output file */
	FILE *f = fopen(outfile, "wb");
	if (!f) {
		FATAL("Can't open output file %s\n", outfile);
		goto vblock_cleanup;
	}
	int i = ((1 != fwrite(keyblock, keyblock->keyblock_size, 1, f)) ||
		 (1 != fwrite(preamble, preamble->preamble_size, 1, f)));
	fclose(f);
	if (i) {
		FATAL("Can't write output file %s\n", outfile);
		unlink(outfile);
		goto vblock_cleanup;
	}

	/* Success */
	retval = 0;

vblock_cleanup:
	if (keyblock)
		free(keyblock);
	if (signing_key)
		free(signing_key);
	if (kernel_subkey)
		free(kernel_subkey);
	if (fv_data)
		free(fv_data);
	if (body_sig)
		free(body_sig);
	if (preamble)
		free(preamble);

	return retval;
}

static int do_verify(const char *infile, const char *signpubkey,
		     const char *fv_file, const char *kernelkey_file)
{
	uint8_t workbuf[VB2_FIRMWARE_WORKBUF_RECOMMENDED_SIZE]
		__attribute__((aligned(VB2_WORKBUF_ALIGN)));
	struct vb2_workbuf wb;
	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));

	uint32_t now = 0;

	uint8_t *pubkbuf = NULL;
	uint8_t *blob = NULL;
	uint8_t *fv_data = NULL;
	int retval = 1;

	if (!infile || !signpubkey || !fv_file) {
		FATAL("Must specify filename, signpubkey, and fv\n");
		goto verify_cleanup;
	}

	/* Read public signing key */
	uint32_t pubklen;
	struct vb2_public_key sign_key;
	if (VB2_SUCCESS != vb2_read_file(signpubkey, &pubkbuf, &pubklen)) {
		fprintf(stderr, "Error reading signpubkey.\n");
		goto verify_cleanup;
	}
	if (VB2_SUCCESS != vb2_unpack_key_buffer(&sign_key, pubkbuf, pubklen)) {
		fprintf(stderr, "Error unpacking signpubkey.\n");
		goto verify_cleanup;
	}

	/* Read blob */
	uint32_t blob_size;
	if (VB2_SUCCESS != vb2_read_file(infile, &blob, &blob_size)) {
		FATAL("Error reading input file\n");
		goto verify_cleanup;
	}

	/* Read firmware volume */
	uint32_t fv_size;
	if (VB2_SUCCESS != vb2_read_file(fv_file, &fv_data, &fv_size)) {
		FATAL("Error reading firmware volume\n");
		goto verify_cleanup;
	}

	/* Verify keyblock */
	struct vb2_keyblock *keyblock = (struct vb2_keyblock *)blob;
	if (VB2_SUCCESS !=
	    vb2_verify_keyblock(keyblock, blob_size, &sign_key, &wb)) {
		FATAL("Error verifying keyblock.\n");
		goto verify_cleanup;
	}

	now += keyblock->keyblock_size;

	printf("Keyblock:\n");
	printf("  Size:                %d\n", keyblock->keyblock_size);
	printf("  Flags:               %d (ignored)\n",
	       keyblock->keyblock_flags);

	struct vb2_packed_key *packed_key = &keyblock->data_key;
	printf("  Data key algorithm:  %d %s\n", packed_key->algorithm,
	       vb2_get_crypto_algorithm_name(packed_key->algorithm));
	printf("  Data key version:    %d\n", packed_key->key_version);
	printf("  Data key sha1sum:    %s\n",
	       packed_key_sha1_string(packed_key));

	struct vb2_public_key data_key;
	if (VB2_SUCCESS !=
	    vb2_unpack_key(&data_key, &keyblock->data_key)) {
		fprintf(stderr, "Error parsing data key.\n");
		goto verify_cleanup;
	}

	/* Verify preamble */
	struct vb2_fw_preamble *pre2 = (struct vb2_fw_preamble *)(blob + now);
	if (VB2_SUCCESS !=
	    vb2_verify_fw_preamble(pre2, blob_size - now, &data_key, &wb)) {
		FATAL("Error2 verifying preamble.\n");
		goto verify_cleanup;
	}
	now += pre2->preamble_size;

	uint32_t flags = pre2->flags;
	if (pre2->header_version_minor < 1)
		flags = 0;  /* Old 2.0 structure didn't have flags */

	printf("Preamble:\n");
	printf("  Size:                  %d\n", pre2->preamble_size);
	printf("  Header version:        %d.%d\n",
	       pre2->header_version_major, pre2->header_version_minor);
	printf("  Firmware version:      %d\n", pre2->firmware_version);

	struct vb2_packed_key *kernel_subkey = &pre2->kernel_subkey;
	printf("  Kernel key algorithm:  %d %s\n", kernel_subkey->algorithm,
	       vb2_get_crypto_algorithm_name(kernel_subkey->algorithm));
	printf("  Kernel key version:    %d\n", kernel_subkey->key_version);
	printf("  Kernel key sha1sum:    %s\n",
	       packed_key_sha1_string(kernel_subkey));
	printf("  Firmware body size:    %d\n", pre2->body_signature.data_size);
	printf("  Preamble flags:        %d\n", flags);

	/* TODO: verify body size same as signature size */

	/* Verify body */
	if (flags & VB2_FIRMWARE_PREAMBLE_USE_RO_NORMAL) {
		printf("Preamble requests USE_RO_NORMAL;"
		       " skipping body verification.\n");
	} else if (VB2_SUCCESS ==
		   vb2_verify_data(fv_data, fv_size, &pre2->body_signature,
				   &data_key, &wb)) {
		printf("Body verification succeeded.\n");
	} else {
		FATAL("Error verifying firmware body.\n");
		goto verify_cleanup;
	}

	if (kernelkey_file &&
	    VB2_SUCCESS != vb2_write_packed_key(kernelkey_file,
						kernel_subkey)) {
		FATAL("Unable to write kernel subkey\n");
		goto verify_cleanup;
	}

	/* Success */
	retval = 0;

verify_cleanup:
	if (pubkbuf)
		free(pubkbuf);
	if (blob)
		free(blob);
	if (fv_data)
		free(fv_data);

	return retval;
}

static int do_vbutil_firmware(int argc, char *argv[])
{

	char *filename = NULL;
	char *keyblock_file = NULL;
	char *signpubkey = NULL;
	char *signprivate = NULL;
	uint32_t version = 0;
	char *fv_file = NULL;
	char *kernelkey_file = NULL;
	uint32_t preamble_flags = 0;
	int mode = 0;
	int parse_error = 0;
	char *e;
	int i;

	while ((i = getopt_long(argc, argv, "", long_opts, NULL)) != -1) {
		switch (i) {
		case '?':
			/* Unhandled option */
			printf("Unknown option\n");
			parse_error = 1;
			break;
		case OPT_HELP:
			print_help(argc, argv);
			return !!parse_error;

		case OPT_MODE_VBLOCK:
		case OPT_MODE_VERIFY:
			mode = i;
			filename = optarg;
			break;

		case OPT_KEYBLOCK:
			keyblock_file = optarg;
			break;

		case OPT_SIGNPUBKEY:
			signpubkey = optarg;
			break;

		case OPT_SIGNPRIVATE:
			signprivate = optarg;
			break;

		case OPT_FV:
			fv_file = optarg;
			break;

		case OPT_KERNELKEY:
			kernelkey_file = optarg;
			break;

		case OPT_VERSION:
			version = strtoul(optarg, &e, 0);
			if (!*optarg || (e && *e)) {
				printf("Invalid --version\n");
				parse_error = 1;
			}
			break;

		case OPT_FLAGS:
			preamble_flags = strtoul(optarg, &e, 0);
			if (!*optarg || (e && *e)) {
				printf("Invalid --flags\n");
				parse_error = 1;
			}
			break;
		}
	}

	if (parse_error) {
		print_help(argc, argv);
		return 1;
	}

	switch (mode) {
	case OPT_MODE_VBLOCK:
		return do_vblock(filename, keyblock_file, signprivate, version,
				 fv_file, kernelkey_file, preamble_flags);
	case OPT_MODE_VERIFY:
		return do_verify(filename, signpubkey, fv_file, kernelkey_file);
	default:
		fprintf(stderr, "Must specify a mode.\n");
		print_help(argc, argv);
		return 1;
	}
}

DECLARE_FUTIL_COMMAND(vbutil_firmware, do_vbutil_firmware, VBOOT_VERSION_1_0,
		      "Verified boot firmware utility");


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/html; charset=utf-8"/>
    <title>Statistics of orphan in UD_Italian-ParlaMint</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Italian-ParlaMint: Relations: orphan

This relation is universal.

1 nodes (0%) are attached to their parents as orphan.

1 instances of orphan (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.

The following 1 pairs of parts of speech are connected with orphan: <tt>PRON</tt>-<tt>PRON</tt> (1; 100% instances).

# visual-style 38	bgColor:blue
# visual-style 38	fgColor:white
# visual-style 37	bgColor:blue
# visual-style 37	fgColor:white
# visual-style 37 38 orphan	color:blue
1	Abbiamo	avere	AUX	VA	Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin	3	aux	_	_
2	ben	bene	ADV	B	_	3	advmod	_	_
3	presente	presente	ADJ	A	Number=Sing	0	root	_	_
4	la	il	DET	RD	Definite=Def|Gender=Fem|Number=Sing|PronType=Art	5	det	_	_
5	necessità	necessità	NOUN	S	Gender=Fem	3	obj	_	_
6	di	di	ADP	E	_	7	mark	_	_
7	tenere	tenere	VERB	V	VerbForm=Inf	5	acl	_	_
8	distinto	distinto	ADJ	A	Gender=Masc|Number=Sing	7	xcomp	_	_
9	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	10	det	_	SpaceAfter=No
10	istituto	istituto	NOUN	S	Gender=Masc|Number=Sing	7	obj	_	_
11	di	di	ADP	E	_	13	case	_	_
12	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	13	det	_	_
13	affidamento	affidamento	NOUN	S	Gender=Masc|Number=Sing	10	nmod	_	_
14	da	da	ADP	E	_	15	case	_	_
15	quello	quello	PRON	PD	Gender=Masc|Number=Sing|PronType=Dem	7	obl	_	_
16	di	di	ADP	E	_	18	case	_	_
17	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	18	det	_	_
18	adozione	adozione	NOUN	S	Gender=Fem|Number=Sing	15	nmod	_	SpaceAfter=No
19	,	,	PUNCT	FF	_	22	punct	_	_
20	che	che	PRON	PR	PronType=Rel	22	nsubj	_	_
21	non	non	ADV	BN	PronType=Neg	22	advmod	_	_
22	hanno	avere	VERB	V	Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin	18	acl	_	_
23	soltanto	soltanto	ADV	B	_	25	advmod	_	_
24	come	come	ADP	E	_	25	case	_	_
25	elemento	elemento	NOUN	S	Gender=Masc|Number=Sing	22	obl	_	_
26	di	di	ADP	E	_	27	case	_	_
27	distinzione	distinzione	NOUN	S	Gender=Fem|Number=Sing	25	nmod	_	_
28	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	29	det	_	SpaceAfter=No
29	uno	uno	PRON	PI	Gender=Masc|Number=Sing|PronType=Ind	22	dep	_	_
30	il	il	DET	RD	Definite=Def|Gender=Masc|Number=Sing|PronType=Art	31	det	_	_
31	valore	valore	NOUN	S	Gender=Masc|Number=Sing	22	obj	_	_
32	di	di	ADP	E	_	34	case	_	_
33	la	il	DET	RD	Definite=Def|Gender=Fem|Number=Sing|PronType=Art	34	det	_	_
34	temporaneità	temporaneità	NOUN	S	Gender=Fem	31	nmod	_	_
35	e	e	CCONJ	CC	_	37	cc	_	_
36	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	37	det	_	SpaceAfter=No
37	altro	altro	PRON	PI	Gender=Masc|Number=Sing|PronType=Ind	22	conj	_	_
38	quello	quello	PRON	PD	Gender=Masc|Number=Sing|PronType=Dem	37	orphan	_	_
39	di	di	ADP	E	_	41	case	_	_
40	la	il	DET	RD	Definite=Def|Gender=Fem|Number=Sing|PronType=Art	41	det	_	_
41	stabilità	stabilità	NOUN	S	Gender=Fem	38	nmod	_	SpaceAfter=No
42	,	,	PUNCT	FF	_	46	punct	_	_
43	ma	ma	CCONJ	CC	_	46	cc	_	_
44	vogliamo	volere	AUX	VM	Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin	46	aux	_	_
45	anche	anche	ADV	B	_	46	advmod	_	_
46	cogliere	cogliere	VERB	V	VerbForm=Inf	3	conj	_	_
47	pienamente	pienamente	ADV	B	_	46	advmod	_	_
48	il	il	DET	RD	Definite=Def|Gender=Masc|Number=Sing|PronType=Art	49	det	_	_
49	carattere	carattere	NOUN	S	Gender=Masc|Number=Sing	46	obj	_	_
50	sociale	sociale	ADJ	A	Number=Sing	49	amod	_	_
51	di	di	ADP	E	_	52	case	_	_
52	umanità	umanità	NOUN	S	Gender=Fem	49	nmod	_	_
53	e	e	CCONJ	CC	_	55	cc	_	_
54	di	di	ADP	E	_	55	case	_	_
55	generosità	generosità	NOUN	S	Gender=Fem	52	conj	_	_
56	che	che	PRON	PR	PronType=Rel	59	obj	_	_
57	l'	il	DET	RD	Definite=Def|Number=Sing|PronType=Art	58	det	_	SpaceAfter=No
58	affidamento	affidamento	NOUN	S	Gender=Masc|Number=Sing	59	nsubj	_	_
59	esprime	esprimere	VERB	V	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin	49	acl	_	SpaceAfter=No
60	.	.	PUNCT	FS	_	3	punct	_	SpacesAfter=\n

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<?php

namespace Spa\BackendBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * User
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @var integer
     */
    private $id;

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

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

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

    /**
     * @var boolean
     */
    private $isActive;

    /**
     * @var \DateTime
     */
    private $createdAt;

    /**
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * @var \DateTime
     */
    private $lastLogin;

    public function __construct()
    {
        $this->isActive = true;
        //$this->salt = md5(uniqid(null, true));
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return array('ROLE_USER');
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
    }

    /**
     * @see \Serializable::serialize()
     */
    public function serialize()
    {
        return serialize(array(
            $this->id,
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        list (
            $this->id,
        ) = unserialize($serialized);
    }

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

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

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

    /**
     * Set salt
     *
     * @param string $salt
     * @return User
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;

        return $this;
    }

    /**
     * Get salt
     *
     * @return string
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = sha1($password);

        return $this;
    }

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

    /**
     * Set isActive
     *
     * @param string $isActive
     * @return User
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return string
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return User
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return User
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set lastLogin
     *
     * @param \DateTime $updatedAt
     * @return User
     */
    public function setLastLogin($lastLogin)
    {
        $this->lastLogin = $lastLogin;

        return $this;
    }

    /**
     * Get lastLogin
     *
     * @return \DateTime
     */
    public function getLastLogin()
    {
        return $this->lastLogin;
    }

    /**
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function updatedTimestamps()
    {
        $this->setUpdatedAt(new \DateTime('now'));

        if ($this->getCreatedAt() == null) {
            $this->setCreatedAt(new \DateTime('now'));
        }
    }

     public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    public function isEnabled()
    {
        return $this->isActive;
    }
}


text:
<?php if (!defined('APPLICATION')) exit();

if (is_object($this->_Message)) {
   echo '
_Message->CssClass == '' ? '' : ' '.$this->_Message->CssClass).'">';
   $Session = Gdn::Session();
   if ($this->_Message->AllowDismiss == '1' && $Session->IsValid()) {
      echo Anchor('×', '/dashboard/message/dismiss/'.$this->_Message->MessageID.'/'.$Session->TransientKey().'?Target='.$this->_Sender->SelfUrl, 'Dismiss');
   }

   echo Gdn_Format::To($this->_Message->Content, 'Html');
   echo '
';
}


text:
#pragma once
#include <aws/worklink/WorkLink_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WorkLink
{
namespace Model
{
  class AWS_WORKLINK_API RestoreDomainAccessResult
  {
  public:
    RestoreDomainAccessResult();
    RestoreDomainAccessResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    RestoreDomainAccessResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace WorkLink
} // namespace Aws


text:
UPDATE database_instance SET master_port=22294 where port not in (22293, 22294);
-- topology:
--
-- 22293
-- + 22294
--   + 22295
--   + 22296
--   + 22297
--
UPDATE database_instance SET data_center='seattle', physical_environment='prod';
UPDATE database_instance SET data_center='ny', physical_environment='prod' where port in (22294, 22295);
UPDATE database_instance SET data_center='sf', physical_environment='prod' where port in (22297);

INSERT INTO candidate_database_instance (hostname, port, promotion_rule) VALUES ('testhost', 22294, 'prefer_not');
INSERT INTO candidate_database_instance (hostname, port, promotion_rule) VALUES ('testhost', 22295, 'neutral');
INSERT INTO candidate_database_instance (hostname, port, promotion_rule) VALUES ('testhost', 22297, 'neutral');


text:
function Voice(notes) {
  this._unsungNotes = notes.slice();
  this._nextNoteStart = new Fraction(0, 1);
  this._singing = Note.nullObjectStart;
}

Voice.prototype
.advanceTime = function(time) {
  if(time.lessThan(this._nextNoteStart)) {
    // continue sinning same note
  } else if(this._unsungNotes.length === 0) {
    this._singing = null;
  } else {
    var sing = this._unsungNotes.shift();
    this._nextNoteStart = sing.addTime(this._nextNoteStart);
    this._singing = sing;
  }
  return this._singing;
};

Voice.prototype
.nextNoteStartTimeMin = function(fraction) {
  return this._nextNoteStart.min(fraction);
};


text:
<?php

namespace Achillesp\Matryoshka\Test;

/**
 * @coversCacheable
 */
class CacheableTest extends TestCase
{
    /** @test */
    public function it_gets_a_unique_cache_key_for_an_eloquent_model()
    {
        // I need an eloquent model instance
        // and that model needs to use the Cacheable trait.
        $model = $this->makePost();

        // and I need to verify the returned value.
        $this->assertSame(
            'Achillesp\Matryoshka\Test\Models\Post/1-'.$model->updated_at->timestamp,
            $model->getCacheKey()
        );
    }
}


text:
using QuantConnect.Securities;
using System;

namespace QuantConnect.ToolBox.RandomDataGenerator
{
    /// <summary>
    /// Defines a type capable of producing random values for use in random data generation
    /// </summary>
    /// <remarks>
    /// Any parameters referenced as a percentage value are always in 'percent space', meaning 1 is 1%.
    /// </remarks>
    public interface IRandomValueGenerator
    {
        /// <summary>
        /// Randomly return a <see cref="bool"/> value with the specified odds of being true
        /// </summary>
        /// <param name="percentOddsForTrue">The percent odds of being true in percent space, so 10 => 10%</param>
        /// <returns>True or false</returns>
        bool NextBool(double percentOddsForTrue);

        /// <summary>
        /// Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0
        /// </summary>
        /// <returns>A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.</returns>
        double NextDouble();

        /// <summary>
        /// Returns a random integer that is within a specified range.
        /// </summary>
        /// <param name="minValue">the inclusive lower bound of the random number returned</param>
        /// <param name="maxValue">the exclusive upper bound of the random number returned</param>
        /// <returns>A 32-bit signed integer greater than or equal to minValue and less than maxValue.</returns>
        int NextInt(int minValue, int maxValue);

        /// <summary>
        /// Returns a non-negative random integer that is less than the specified maximum.
        /// </summary>
        /// <param name="maxValue">the exclusive upper bound of the random number to be generated.</param>
        /// <returns>A 32-bit signed integer that is greater than or equal to 0, and less than maxValue.</returns>
        int NextInt(int maxValue);

        /// <summary>
        /// Generates a random <see cref="DateTime"/> between the specified <paramref name="minDateTime"/> and
        /// <paramref name="maxDateTime"/>. <paramref name="dayOfWeek"/> is optionally specified to force the
        /// result to a particular day of the week
        /// </summary>
        /// <param name="minDateTime">The minimum date time, inclusive</param>
        /// <param name="maxDateTime">The maximum date time, inclusive</param>
        /// <param name="dayOfWeek">Optional. The day of week to force</param>
        /// <returns>A new <see cref="DateTime"/> within the specified range and optionally of the specified day of week</returns>
        DateTime NextDate(DateTime minDateTime, DateTime maxDateTime, DayOfWeek? dayOfWeek);

        /// <summary>
        /// Generates a random <see cref="decimal"/> suitable as a price. This should observe minimum price
        /// variations if available in <see cref="SymbolPropertiesDatabase"/>, and if not, truncating to 2
        /// decimal places.
        /// </summary>
        /// <exception cref="ArgumentException">Throw when the <paramref name="referencePrice"/> or <paramref name="maximumPercentDeviation"/>
        /// is less than or equal to zero.</exception>
        /// <param name="securityType">The security type the price is being generated for</param>
        /// <param name="market">The market of the security the price is being generated for</param>
        /// <param name="referencePrice">The reference price used as the mean of random price generation</param>
        /// <param name="maximumPercentDeviation">The maximum percent deviation. This value is in percent space,
        ///     so a value of 1m is equal to 1%.</param>
        /// <returns>A new decimal suitable for usage as price within the specified deviation from the reference price</returns>
        decimal NextPrice(SecurityType securityType, string market, decimal referencePrice, decimal maximumPercentDeviation);

    }
}


text:
package org.batfish.datamodel.matchers;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.Nonnull;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpSpace;
import org.batfish.datamodel.IpWildcard;
import org.batfish.datamodel.matchers.IpSpaceMatchersImpl.ContainsIp;
import org.batfish.datamodel.matchers.IpSpaceMatchersImpl.Intersects;
import org.batfish.datamodel.matchers.IpSpaceMatchersImpl.SubsetOf;
import org.batfish.datamodel.matchers.IpSpaceMatchersImpl.SupersetOf;

public class IpSpaceMatchers {

  private IpSpaceMatchers() {}

  /** Provides a matcher that matches if the {@link IpSpace} contains the specified {@link Ip}. */
  public static ContainsIp containsIp(@Nonnull Ip ip) {
    return new ContainsIp(ip, ImmutableMap.of());
  }

  /**
   * Provides a matcher that matches if the {@link IpSpace} contains the specified {@link Ip} given
   * the specified named IpSpace definitions.
   */
  public static ContainsIp containsIp(@Nonnull Ip ip, @Nonnull Map<String, IpSpace> namedIpSpaces) {
    return new ContainsIp(ip, namedIpSpaces);
  }

  public static Intersects intersects(@Nonnull IpWildcard ipWildcard) {
    return new Intersects(ipWildcard);
  }

  public static SubsetOf subsetOf(@Nonnull IpWildcard ipWildcard) {
    return new SubsetOf(ipWildcard);
  }

  public static SupersetOf supersetOf(@Nonnull IpWildcard ipWildcard) {
    return new SupersetOf(ipWildcard);
  }
}


text:
{% extends "dashboards/widgets/widget-base-template.html" %}
{% block widget-title %}
    {{ widget.name }}
{% endblock %}
{% block widget-content %}

{% endblock %}
{% block widget-footer %}
{% endblock %}
{% block script %}

{% endblock %}


text:
<?php

namespace Proxies\__CG__\Diagomail\AppBundle\Entity;

/**
 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
 */
class EmailStatus extends \Diagomail\AppBundle\Entity\EmailStatus implements \Doctrine\ORM\Proxy\Proxy
{
    /**
     * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
     *      three parameters, being respectively the proxy object to be initialized, the method that triggered the
     *      initialization process and an array of ordered parameters that were passed to that method.
     *
     * @see \Doctrine\Common\Persistence\Proxy::__setInitializer
     */
    public $__initializer__;

    /**
     * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
     *
     * @see \Doctrine\Common\Persistence\Proxy::__setCloner
     */
    public $__cloner__;

    /**
     * @var boolean flag indicating if this object was already initialized
     *
     * @see \Doctrine\Common\Persistence\Proxy::__isInitialized
     */
    public $__isInitialized__ = false;

    /**
     * @var array properties to be lazy loaded, with keys being the property
     *            names and values being their default values
     *
     * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
     */
    public static $lazyPropertiesDefaults = [];

    /**
     * @param \Closure $initializer
     * @param \Closure $cloner
     */
    public function __construct($initializer = null, $cloner = null)
    {

        $this->__initializer__ = $initializer;
        $this->__cloner__      = $cloner;
    }

    /**
     *
     * @return array
     */
    public function __sleep()
    {
        if ($this->__isInitialized__) {
            return ['__isInitialized__', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'id', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'name', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'description', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'emailLog'];
        }

        return ['__isInitialized__', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'id', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'name', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'description', '' . "\0" . 'Diagomail\\AppBundle\\Entity\\EmailStatus' . "\0" . 'emailLog'];
    }

    /**
     *
     */
    public function __wakeup()
    {
        if ( ! $this->__isInitialized__) {
            $this->__initializer__ = function (EmailStatus $proxy) {
                $proxy->__setInitializer(null);
                $proxy->__setCloner(null);

                $existingProperties = get_object_vars($proxy);

                foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
                    if ( ! array_key_exists($property, $existingProperties)) {
                        $proxy->$property = $defaultValue;
                    }
                }
            };

        }
    }

    /**
     *
     */
    public function __clone()
    {
        $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []);
    }

    /**
     * Forces initialization of the proxy
     */
    public function __load()
    {
        $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []);
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setInitialized($initialized)
    {
        $this->__isInitialized__ = $initialized;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setInitializer(\Closure $initializer = null)
    {
        $this->__initializer__ = $initializer;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __getInitializer()
    {
        return $this->__initializer__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     */
    public function __setCloner(\Closure $cloner = null)
    {
        $this->__cloner__ = $cloner;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific cloning logic
     */
    public function __getCloner()
    {
        return $this->__cloner__;
    }

    /**
     * {@inheritDoc}
     * @internal generated method: use only when explicitly handling proxy specific loading logic
     * @static
     */
    public function __getLazyProperties()
    {
        return self::$lazyPropertiesDefaults;
    }

    /**
     * {@inheritDoc}
     */
    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int)  parent::getId();
        }

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []);

        return parent::getId();
    }

    /**
     * {@inheritDoc}
     */
    public function setName($name)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setName', [$name]);

        return parent::setName($name);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getName', []);

        return parent::getName();
    }

    /**
     * {@inheritDoc}
     */
    public function setDescription($description)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'setDescription', [$description]);

        return parent::setDescription($description);
    }

    /**
     * {@inheritDoc}
     */
    public function getDescription()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getDescription', []);

        return parent::getDescription();
    }

    /**
     * {@inheritDoc}
     */
    public function addEmailLog(\Diagomail\AppBundle\Entity\EmailLog $emailLog)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'addEmailLog', [$emailLog]);

        return parent::addEmailLog($emailLog);
    }

    /**
     * {@inheritDoc}
     */
    public function removeEmailLog(\Diagomail\AppBundle\Entity\EmailLog $emailLog)
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'removeEmailLog', [$emailLog]);

        return parent::removeEmailLog($emailLog);
    }

    /**
     * {@inheritDoc}
     */
    public function getEmailLog()
    {

        $this->__initializer__ && $this->__initializer__->__invoke($this, 'getEmailLog', []);

        return parent::getEmailLog();
    }

}


text: A container providing an API for working with individual players.


text:
layout: page
title: Mahoney Inc. Show
date: 2016-05-24
author: Andrew Aguirre
tags: weekly links, java
status: published
summary: Ut fermentum mi sit amet.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 07/25/2016
  endDate: 07/29/2016
  ctyhocn: ELMHHHX
  groupCode: MIS
published: true
---
Fusce viverra nulla lacus, a ultricies felis tincidunt id. Morbi ut pulvinar lectus, in tincidunt ipsum. Vivamus eget metus mi. Pellentesque luctus augue sed quam mollis iaculis. Vivamus ac mollis eros, ut consequat eros. Donec eu ullamcorper est. Sed fringilla congue consectetur. Sed ut magna et metus tempor tempor. In at risus in arcu facilisis auctor. Sed ac ipsum ac diam egestas ullamcorper. Integer id porttitor augue. Fusce mattis velit tellus, quis bibendum elit lacinia ut.
Fusce at ipsum a ex laoreet luctus vel ac mauris. Nullam ut erat eget arcu dapibus sollicitudin. Vivamus finibus dolor a dui sagittis, eu placerat justo lacinia. Nulla consequat, dolor a laoreet ultrices, erat enim porttitor massa, quis eleifend dolor leo vel neque. Vivamus arcu turpis, ornare vel mollis et, dapibus sit amet dolor. Aenean a tempus nibh. Maecenas quis purus non quam fringilla viverra.

1 Nam vel massa eu orci efficitur varius non sit amet libero.

Proin at orci augue. Suspendisse ut laoreet nibh, sit amet molestie neque. Maecenas turpis nunc, efficitur a dui vel, vehicula euismod libero. Etiam iaculis eros leo. Suspendisse pellentesque eu purus eget convallis. Nunc nec sem eget tellus gravida faucibus a non arcu. Vestibulum sapien odio, consectetur sit amet suscipit sed, imperdiet ut ipsum. Maecenas efficitur sapien eros, et posuere elit tincidunt ac. Donec blandit lorem ut odio pharetra rutrum. Donec nec gravida tellus.
Pellentesque laoreet neque ac ipsum sagittis, id euismod est feugiat. Curabitur mattis dui sit amet finibus hendrerit. Etiam risus dolor, dapibus ut lobortis et, sagittis eu sem. Vestibulum ac tempus odio. Morbi convallis quam ex, non faucibus ipsum malesuada vel. Sed in porttitor enim. Morbi at magna quis risus interdum pulvinar imperdiet in diam. Fusce laoreet eros turpis, id tincidunt libero efficitur ut. Nunc ac consectetur nisi, ac egestas odio.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

define([
  'underscore',
  'backbone'
], function(_, Backbone) {
    var LevelModel = Backbone.Model.extend({
        urlRoot: "http://localhost:8080/practica/webresources/edu.poli.prap.pp.data.level/",
        idAttribute: 'idlevel',
        defaults: {
            name: "",
            points: ""
        },
        toViewJson: function () {
            var result = this.toJSON(); // displayName property is used to render item in the list
            result.displayName = this.get('name');
            return result;
        },
        isNew: function () {
            // default isNew() method imlementation is
            // based on the 'id' initialization which
            // sometimes is required to be initialized.
            // So isNew() is rediefined here
            return this.notSynced;
        },
        sync: function (method, model, options) {
            options || (options = {});
            var errorHandler = {
                error: function (jqXHR, textStatus, errorThrown) {
                    // TODO: put your error handling code here
                    // If you use the JS client from the different domain
                    // (f.e. locally) then Cross-origin resource sharing
                    // headers has to be set on the REST server side.
                    // Otherwise the JS client has to be copied into the
                    // some (f.e. the same) Web project on the same domain
                    alert('Unable to fulfil the request');
                }}

            if (method == 'create') {
                options.url = 'http://localhost:8080/practica/webresources/edu.poli.prap.pp.data.level/';
            }
            var result = Backbone.sync(method, model, _.extend(options, errorHandler));
            return result;
        }

    });

    return LevelModel;

});


text:
@import Appstax;
#import "AXQuery.h"
#import "AppstaxInternals.h"

@interface AXQueryTests : XCTestCase
@property AXQuery *query;
@end

@implementation AXQueryTests

- (void)setUp {
    [super setUp];
    [Appstax setAppKey:@"test-api-key" baseUrl:@"http://localhost:3000/"];
    _query = [AXQuery query];
}

- (void)tearDown {
    [super tearDown];
}

- (void)testShouldCreateEmptyQuery {
    XCTAssertEqualObjects(_query.queryString, @"");
}

- (void)testShouldCreateSimpleQueryWithString {
    _query = [[AXQuery alloc] initWithQueryString:@"foo='bar'"];
    XCTAssertEqualObjects(_query.queryString, @"foo='bar'");
}

- (void)testShouldQueryStringEquals {
    [_query string:@"zoo" equals:@"baz"];
    XCTAssertEqualObjects(_query.queryString, @"zoo='baz'");
}

- (void)testShoulQueryStringContains {
    [_query string:@"mooz" contains:@"oo"];
    XCTAssertEqualObjects(_query.queryString, @"mooz like '%oo%'");
}

- (void)testShouldQueryObjectHasRelationForSingleObject {
    AXObject *object = [AXObject create:@"foo" properties:@{@"sysObjectId":@"1234"}];
    [_query relation:@"bar" hasObject:object];
    XCTAssertEqualObjects(_query.queryString, @"bar has ('1234')");
}

- (void)testShouldQueryObjectHasRelationForMultipleObjects {
    AXObject *object1 = [AXObject create:@"foo" properties:@{@"sysObjectId":@"1234"}];
    AXObject *object2 = [AXObject create:@"foo" properties:@{@"sysObjectId":@"5678"}];
    [_query relation:@"bar" hasObjects:@[object1, object2]];
    XCTAssertEqualObjects(_query.queryString, @"bar has ('1234','5678')");
}

- (void)testShoulJoinPredicatesWithAndByDefault {
    [_query string:@"zoo" equals:@"baz"];
    [_query string:@"mooz" contains:@"oo"];
    XCTAssertEqualObjects(_query.queryString, @"zoo='baz' and mooz like '%oo%'");
}

- (void)testShouldJointPredicatesWithOrWhenSpecified {
    [_query string:@"zoo" equals:@"baz"];
    [_query string:@"mooz" contains:@"oo"];
    [_query setLogicalOperator:@"or"];
    XCTAssertEqualObjects(_query.queryString, @"zoo='baz' or mooz like '%oo%'");
}

@end


text:
/*eslint-disable */
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  //inLine: true,
  historyApiFallback: true,
  contentBase:'./static',
  stats: {
    colors: true
  }
}).listen(3000, 'localhost', function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log('Listening at localhost:3000');
});