text:
package com.google.inject;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import java.lang.annotation.Annotation;

import com.google.common.reflect.TypeToken;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.AnnotatedConstantBindingBuilder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.Message;
import com.google.inject.spi.ProvisionListener;

/**
 * A support class for {@link Module}s which reduces repetition and results in a
 * more readable configuration. Simply extend this class, implement
 * {@link #configure()}, and call the inherited methods which mirror those found
 * in {@link Binder}. For example:
 *
 * <pre>
 * public class MyModule extends AbstractModule {
 *     protected void configure() {
 *         bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
 *         bind(CreditCardPaymentService.class);
 *         bind(PaymentService.class).to(CreditCardPaymentService.class);
 *         bindConstant().annotatedWith(Names.named("port")).to(8080);
 *     }
 * }
 * </pre>
 *
 * @author crazybob@google.com (Bob Lee)
 */
public abstract class AbstractModule implements Module {

    Binder binder;

    @Override
    public final synchronized void configure(Binder binder) {
        checkState(this.binder == null, "Re-entry is not allowed.");

        this.binder = checkNotNull(binder, "binder");
        try {
            configure();
        } finally {
            this.binder = null;
        }
    }

    /**
     * Configures a {@link Binder} via the exposed methods.
     */
    protected abstract void configure();

    /**
     * Gets direct access to the underlying {@code Binder}.
     */
    protected Binder binder() {
        checkState(binder != null,
                "The binder can only be used inside configure()");
        return binder;
    }

    /**
     * @see Binder#bindScope(Class, Scope)
     */
    protected void bindScope(Class<? extends Annotation> scopeAnnotation,
            Scope scope) {
        binder().bindScope(scopeAnnotation, scope);
    }

    /**
     * @see Binder#bind(Key)
     */
    protected <T> LinkedBindingBuilder<T> bind(Key<T> key) {
        return binder().bind(key);
    }

    /**
     * @see Binder#bind(TypeLiteral)
     */
    protected <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) {
        return binder().bind(typeLiteral);
    }

    /**
     * @see Binder#bind(Class)
     */
    protected <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) {
        return binder().bind(clazz);
    }

    /**
     * @see Binder#bindConstant()
     */
    protected AnnotatedConstantBindingBuilder bindConstant() {
        return binder().bindConstant();
    }

    /**
     * @see Binder#install(Module)
     */
    protected void install(Module module) {
        binder().install(module);
    }

    /**
     * @see Binder#addError(String, Object[])
     */
    protected void addError(String message, Object... arguments) {
        binder().addError(message, arguments);
    }

    /**
     * @see Binder#addError(Throwable)
     */
    protected void addError(Throwable t) {
        binder().addError(t);
    }

    /**
     * @see Binder#addError(Message)
     * @since 2.0
     */
    protected void addError(Message message) {
        binder().addError(message);
    }

    /**
     * @see Binder#requestInjection(Object)
     * @since 2.0
     */
    protected void requestInjection(Object instance) {
        binder().requestInjection(instance);
    }

    /**
     * @see Binder#requestStaticInjection(Class[])
     */
    protected void requestStaticInjection(Class<?>... types) {
        binder().requestStaticInjection(types);
    }

    /**
     * Adds a dependency from this module to {@code key}. When the injector is
     * created, Guice will report an error if {@code key} cannot be injected.
     * Note that this requirement may be satisfied by implicit binding, such as
     * a public no-arguments constructor.
     *
     * @since 2.0
     */
    protected void requireBinding(Key<?> key) {
        binder().getProvider(key);
    }

    /**
     * Adds a dependency from this module to {@code type}. When the injector is
     * created, Guice will report an error if {@code type} cannot be injected.
     * Note that this requirement may be satisfied by implicit binding, such as
     * a public no-arguments constructor.
     *
     * @since 2.0
     */
    protected void requireBinding(Class<?> type) {
        binder().getProvider(type);
    }

    /**
     * @see Binder#getProvider(Key)
     * @since 2.0
     */
    protected <T> Provider<T> getProvider(Key<T> key) {
        return binder().getProvider(key);
    }

    /**
     * @see Binder#getProvider(Class)
     * @since 2.0
     */
    protected <T> Provider<T> getProvider(Class<T> type) {
        return binder().getProvider(type);
    }

    /**
     * @see Binder#currentStage()
     * @since 2.0
     */
    protected Stage currentStage() {
        return binder().currentStage();
    }

    /**
     * @see Binder#getMembersInjector(Class)
     * @since 2.0
     */
    protected <T> MembersInjector<T> getMembersInjector(Class<T> type) {
        return binder().getMembersInjector(type);
    }

    /**
     * @see Binder#getMembersInjector(TypeLiteral)
     * @since 2.0
     */
    protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) {
        return binder().getMembersInjector(type);
    }

    /**
     * @see Binder#bindListener(Matcher, ProvisionListener...)
     * @since 4.0
     */
    protected void bindListener(Matcher<? super TypeToken<?>> typeMatcher,
            ProvisionListener... listener) {
        binder().bindListener(typeMatcher, listener);
    }
}

redpajama_set_name: RedPajamaGithub


text:
  A method for making async operations cancellable

## Installation

[![component](https://component.jit.su/component-badge.svg)](https://component.jit.su/refer/ForbesLindesay/cancellation)

    $ component install ForbesLindesay/cancellation

NPM:

    $ npm install cancellation

## API

### tokenSource()

  Returns a new CancellationTokenSource:

```javascript
var tokenSource = require('cancellation');
var source = tokenSource();
callAsyncOperation(arg1, arg2, arg3, source.token);
setTimeout(function () {
  source.cancel('Operation timed out');
}, 1000);
```

### tokenSource.empty

  Returns an 'empty' CancellationToken (one that will never be cancelled).

```javascript
var tokenSource = require('cancellation');
function asyncOperation(arg1, arg2, arg3, cancellationToken) {
  cancellationToken = cancellationToken || tokenSource.empty;

  //Continue with function knowing there is a cancellation token
}
```

### CancellationToken.isCancelled()

  Returns true if the token has been cancelled:

```javascript
//In ES6
function asyncOperation(cancellationToken) {
  return spawn(function* () {
    while(!cancellationToken.isCancelled()) {
      yield NextAsyncOp();
    }
  })
}
```

### CancellationToken.throwIfCancelled()

  Throws the rejection reason if the token has been cancelled:

```javascript
//In ES6
function asyncOperation(cancellationToken) {
  return spawn(function* () {
    while(true) {
      cancellationToken.throwIfCancelled()
      yield NextAsyncOp();
    }
  })
}
```

### CancellationToken.onCancelled(cb)

  Calls cb when the cancellation token is cancelled (this is probably currently the most useful of these methods).

```javascript
function get(url, cancellationToken) {
  var def = defer();

  var req = request(url, function (err, res) {
    if (err) def.reject(err);
    else def.resolve(res);
  });

  cancellationToken
    .onCancelled(function (reason) {
      def.reject(reason);
      req.abort();
    });

  return def.promise;
}
```

## License

  MIT


text:
package ru.job4j.optimization;

import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.Matchers.is;

/**
 * Class OptimizationTest.
 *
 * @author Ponkin Aleksey
 * @version 1.0.0
 * @since 22.04.2018.
 */
public class OptimizationTest {
    Optimization optimization = new Optimization();

    /**
     * Test when optimization with one thousand N then check time executing.
     */
    @Test
    public void whenOptimizationWithOneThousandNThenCheckTimeExecuting() {
        Long start = System.currentTimeMillis();
        optimization.setDbName("./src/main/java/ru/job4j/optimization/optimization.db");
        optimization.setN(1_000);
        optimization.start();
        Long timeJob = System.currentTimeMillis() - start;
        int expectedTimeJob = 300_000;
        assertTrue(timeJob < expectedTimeJob);
    }

    /**
     * Test when optimization with one thousand N then check sum N.
     */
    @Test
    public void whenOptimizationWithOneThousandNThenCheckSumN() {
        optimization.setDbName("./src/main/java/ru/job4j/optimization/optimization.db");
        optimization.setN(1_000);
        Long result = optimization.start();
        Long expcted = 500500L;
        assertThat(result, is(expcted));
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 35(4): 429 (1943)

#### Original name
Claudopus cyaneus Murrill

### Remarks
null


text:
'use strict';

angular.module('getAgileApp')
    .factory('StoryService', function (firebaseRef, syncData, ColumnService) {
        return {
            draftStory: function(boardId) {
                return firebaseRef('stories/' + boardId).push();
            },
            addStory: function(boardId, story) {
                var column = ColumnService.getFirstColumn(boardId);

                column.$on('loaded', function() {
                    var columnId = column.$getIndex(0)[0];
                    var ref = firebaseRef('stories/' + boardId);
                    story.columnId = columnId;
                    var newStory = ref.push();
                    newStory.set(story);
                });

            },
            getStory: function(boardId, storyId) {
                return syncData('stories/' + boardId + '/' + storyId);
            },
            getStories: function(boardId) {
                return syncData('stories/' + boardId);
            },
            deleteStory: function(boardId, storyId) {
                syncData('stories/' + boardId + '/' + storyId).$remove();
            },
            progressStory: function(boardId, columnId, storyId) {
                var self = this;
                var nextColumn = ColumnService.getNextColumn(boardId, columnId);

                nextColumn.$on('loaded', function() {
                    var nextColumnId = nextColumn.$getIndex()[1];
                    var story = self.getStory(boardId, storyId);
                    story.$on('loaded', function() {
                        var ref = firebaseRef('stories/' + boardId + '/' + storyId);
                        ref.update({ 'columnId' : nextColumnId });
                    });
                });
            },
            regressStory: function(boardId, columnId, storyId) {
                var self = this;
                var previousColumn = ColumnService.getPreviousColumn(boardId, columnId);

                previousColumn.$on('loaded', function() {
                    var previousColumnId = previousColumn.$getIndex()[0];
                    var story = self.getStory(boardId, storyId);
                    story.$on('loaded', function() {
                        var ref = firebaseRef('stories/' + boardId + '/' + storyId);
                        ref.update({ 'columnId' : previousColumnId });
                    });
                });
            }
        };
    });


text:
package gov.nih.nci.cbiit.cmts.ui.mapping;

import gov.nih.nci.cbiit.cmts.core.AttributeMeta;
import gov.nih.nci.cbiit.cmts.core.ElementMeta;
import gov.nih.nci.cbiit.cmts.util.CdeBrowserLauncher;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.applet.Applet;
import java.net.URL;

import javax.swing.*;
import javax.swing.border.TitledBorder;

public class CDEPropertyPanel extends JPanel implements ActionListener {

    private ElementMeta meta;
    private JLabel label1;
    private JLabel label2;
    private JLabel metaPublicId;
    private JLabel metaVersion;
    private JButton cdeElementLink;
    private boolean hasOwnData;

    public CDEPropertyPanel ()
    {
        super(new BorderLayout());
        initUI();
    }

    private void initUI()
    {
        JPanel centerPanel = new JPanel(new GridBagLayout());
        Insets insets = new Insets(2, 2, 2, 2);
        label1=new JLabel("Public ID");
        metaPublicId=new JLabel("");
        centerPanel.add(label1,new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0) );

        centerPanel.add(metaPublicId, new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));

        label2=new JLabel("Version");
        metaVersion=new JLabel("");
        centerPanel.add(label2,new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0) );

        centerPanel.add(metaVersion, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));

        //cdeElementLink=new JButton("caDSR Element Details");

        cdeElementLink=new JButton("caDSR Element Details");

        cdeElementLink.setForeground(Color.BLUE);

        cdeElementLink.addActionListener(this);
        cdeElementLink.setEnabled(false);
        cdeElementLink.setBorder(null);
        cdeElementLink.setHorizontalTextPosition(AbstractButton.LEADING);//.LEADING);
        //cdeElementLink.setSize((int)(this.getSize().getWidth() / 0.8), 30);
        cdeElementLink.setVisible(false);
        label1.setVisible(false);
        label2.setVisible(false);
//		add(cdeLinkLabel,new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
//				GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0) );

        //add(cdeElementLink, new GridBagConstraints(0, 2, 3, 1, 1.0, 0.0,
        //        GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));
        add(centerPanel, BorderLayout.CENTER);
        add(cdeElementLink, BorderLayout.SOUTH);

        TitledBorder titledBorder = BorderFactory.createTitledBorder("CDE Information");
        setBorder(titledBorder);
     }

    public ElementMeta getMeta() {
        return meta;
    }

    public void setMeta(ElementMeta meta) {
        if (meta==null)
            return;

        if (!meta.isCDE_Element())
        {
            hasOwnData = false;
            cdeElementLink.setVisible(false);
            label1.setVisible(false);
            label2.setVisible(false);
            return;
        }

        String pID = null;
        String ver = null;
        for (AttributeMeta attrMeta:meta.getAttrData())
        {
            if (attrMeta.getName().equals("PUBLICID")) pID = attrMeta.getFixedValue();
            else if (attrMeta.getName().equals("VERSION")) ver = attrMeta.getFixedValue();
        }

        hasOwnData = true;
        cdeElementLink.setVisible(true);
        label1.setVisible(true);
        label2.setVisible(true);

        metaPublicId.setText(pID);
        cdeElementLink.setEnabled(true);
        metaVersion.setText(ver);

        //this.repaint();
    }

    public boolean doesHaveOwnData()
    {
        return hasOwnData;
    }

    public void updateSelection(Object selectedItem)
    {
        metaPublicId.setText("");
        metaVersion.setText(null);
        cdeElementLink.setVisible(false);
        label1.setVisible(false);
        label2.setVisible(false);
        cdeElementLink.setEnabled(false);
        hasOwnData = false;
        if (selectedItem==null)
            return;

        if(selectedItem instanceof ElementMeta)
            setMeta((ElementMeta)selectedItem);
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        boolean isFrame = true;
        Applet applet = null;
        Container container = this.getParent();
        while(container != null)
        {
            if (container instanceof Frame)
            {
                isFrame = true;
                break;
            }
            else if (container instanceof Applet)
            {
                isFrame = false;
                applet = (Applet) container;
                break;
            }
            container = container.getParent();
        }

        if (applet != null)
        {
            try
            {         applet.getAppletContext().showDocument(new URL("https://cdebrowser.nci.nih.gov/CDEBrowser/search?elementDetails=9&FirstTimer=0&PageId=ElementDetailsGroup&publicId="+metaPublicId.getText()+"&version="+metaVersion.getText()), "_blank");
                //applet.getAppletContext().showDocument(new URL("javascript:window.open('https://cdebrowser.nci.nih.gov/CDEBrowser/search?elementDetails=9&FirstTimer=0&PageId=ElementDetailsGroup&publicId="+metaPublicId.getText()+"&version="+metaVersion.getText()+"', 'caDSR Element Details', 'width=1000,height=700,scrollbars=yes,menubar=no,toolbar=no,titlebar=no,location=no,status=no')"));
            }
            catch(Exception me)
            {
                applet = null;
            }
        }

        if (applet == null)
            CdeBrowserLauncher.BrowseCDE(metaPublicId.getText(), metaVersion.getText());

    }

}


text:
package com.lee.game.gdx.spine.superspineboy;

import com.esotericsoftware.spine.Animation;
import com.esotericsoftware.spine.AnimationState;
import com.esotericsoftware.spine.AnimationState.TrackEntry;
import com.esotericsoftware.spine.Skeleton;

/** The view class for an enemy or player that moves around the map. */
class CharacterView {
	View view;
	Model model;
	Skeleton skeleton;
	AnimationState animationState;

	CharacterView (View view) {
		this.view = view;
		model = view.model;
	}

	boolean setAnimation (View.StateView state, boolean force) {
		// Changes the current animation on track 0 of the AnimationState, if needed.
		Animation animation = state.animation;
		TrackEntry current = animationState.getCurrent(0);
		Animation oldAnimation = current == null ? null : current.getAnimation();
		if (force || oldAnimation != animation) {
			if (state.animation == null) return true;
			TrackEntry entry = animationState.setAnimation(0, state.animation, state.loop);
			if (oldAnimation != null) entry.setTrackTime(state.startTimes.get(oldAnimation, state.defaultStartTime));
			if (!state.loop) entry.setTrackEnd(Float.MAX_VALUE);
			return true;
		}
		return false;
	}
}


text:
import Ember from 'ember';
import { test } from 'ember-qunit';
import Util from 'ember-cli-pagination/util';

module("TruncatePages");

test("normal values", function() {
  function isPresent(val) {
    equal(Util.isBlank(val),false);
  }

  function isBlank(val) {
    equal(Util.isBlank(val),true);
  }

  isPresent(1);
  isPresent(5);
  isPresent("abc");
  isPresent(0);

  isBlank("");
  isBlank(null);
  isBlank(undefined);
});


text:
package net.glowstone;

import com.google.common.base.Optional;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import net.glowstone.console.Console;
import net.glowstone.entity.EntityIdManager;
import net.glowstone.entity.player.GlowPlayer;
import net.glowstone.inventory.CraftingManager;
import net.glowstone.io.PlayerDataService;
import net.glowstone.io.anvil.AnvilWorldStorageProvider;
import net.glowstone.net.GlowNetworkServer;
import net.glowstone.net.SessionRegistry;
import net.glowstone.net.query.QueryServer;
import net.glowstone.net.rcon.RconServer;
import net.glowstone.plugin.PluginLoader;
import net.glowstone.plugin.PluginRegistrar;
import net.glowstone.service.scheduler.GlowScheduler;
import net.glowstone.service.scheduler.WorldScheduler;
import net.glowstone.status.GlowFavicon;
import net.glowstone.util.GlowHelpMap;
import net.glowstone.util.SecurityUtils;
import net.glowstone.util.ServerConfig;
import net.glowstone.util.ShutdownMonitorThread;
import net.glowstone.util.bans.GlowBanList;
import net.glowstone.util.bans.UuidListFile;
import net.glowstone.world.GlowWorld;
import org.apache.commons.lang3.Validate;
import org.spongepowered.api.Server;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.network.ChannelListener;
import org.spongepowered.api.network.ChannelRegistrationException;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.chat.ChatTypes;
import org.spongepowered.api.text.sink.MessageSink;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.util.command.source.ConsoleSource;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.WorldCreationSettings;
import org.spongepowered.api.world.storage.ChunkLayout;
import org.spongepowered.api.world.storage.WorldProperties;

import javax.imageio.ImageIO;
import java.io.File;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.KeyPair;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The core class of the Glowstone server.
 */
public final class GlowServer implements Server {

    /**
     * The logger for this class.
     */
    public static final Logger logger = Logger.getLogger("Minecraft");

    /**
     * The game version supported by the server.
     */
    public static final String GAME_VERSION = "1.8";

    /**
     * The protocol version supported by the server.
     */
    public static final int PROTOCOL_VERSION = 47;

    /**
     * A list of all the active {@link net.glowstone.net.GlowSession}s.
     */
    private final SessionRegistry sessions = new SessionRegistry();

    /**
     * The console manager of this server.
     */
    private final Console consoleManager = new Console(this);

    /**
     * The help map for the server.
     */
    private final GlowHelpMap helpMap = new GlowHelpMap(this);

    /**
     * The crafting manager for this server.
     */
    private final CraftingManager craftingManager;

    /**
     * The configuration for the server.
     */
    private final ServerConfig config;

    /**
     * The list of OPs on the server.
     */
    private final UuidListFile opsList;

    /**
     * The list of players whitelisted on the server.
     */
    private final UuidListFile whitelist;

    /**
     * The game
     */
    private final GlowGame game;

    /**
     * The BanList for player names.
     */
    private GlowBanList nameBans;

    /**
     * The BanList for IP addresses.
     */
    private GlowBanList ipBans;

    /**
     * The EntityIdManager for this server.
     */
    private final EntityIdManager entityIdManager = new EntityIdManager();

    /**
     * The world this server is managing.
     */
    private final WorldScheduler worlds;

    /**
     * The task scheduler used by this server.
     */
    private final GlowScheduler scheduler;

    /**
     * Whether the server is shutting down
     */
    private boolean isShuttingDown = false;

    /**
     * Whether the whitelist is in effect.
     */
    private boolean whitelistEnabled;

    /**
     * The size of the area to keep protected around the spawn point.
     */
    private int spawnRadius;

    /**
     * The ticks until a player who has not played the game has been kicked, or 0.
     */
    private int idleTimeout;

    /**
     * A RSA key pair used for encryption and authentication
     */
    private final KeyPair keyPair = SecurityUtils.generateKeyPair();

    /**
     * The network server used for network communication
     */
    private final GlowNetworkServer networkServer = new GlowNetworkServer(this);

    /**
     * The query server for this server, or null if disabled.
     */
    private QueryServer queryServer;

    /**
     * The Rcon server for this server, or null if disabled.
     */
    private RconServer rconServer;

    /**
     * The default icon, usually blank, used for the server list.
     */
    private GlowFavicon defaultIcon;

    /**
     * The server port.
     */
    private int port;

    /**
     * A set of all online players.
     */
    private final Set<GlowPlayer> onlinePlayers = new HashSet<>();

    /**
     * A view of all online players.
     */
    private final Set<GlowPlayer> onlineView = Collections.unmodifiableSet(onlinePlayers);

    private final MessageSink broadcastSink;

    /**
     * Creates a new server.
     */
    public GlowServer(GlowGame game, ServerConfig config) {
        this.game = game;
        this.scheduler = game.getScheduler();
        this.worlds = scheduler.getWorldScheduler();
        this.craftingManager = new CraftingManager(game.getRegistry().getRecipeRegistry());
        this.config = config;
        // stuff based on selected config directory
        opsList = new UuidListFile(config.getFile("ops.json"));
        whitelist = new UuidListFile(config.getFile("whitelist.json"));
        //nameBans = new GlowBanList(this, BanList.Type.NAME);
        //ipBans = new GlowBanList(this, BanList.Type.IP);

        loadConfig();

        this.broadcastSink = new MessageSink() {
            @Override
            public Iterable<CommandSource> getRecipients() {
                return (Collection) getOnlinePlayers();
            }
        };
    }

    /**
     * Starts this server.
     */
    public void start() {
        // Determine console mode and start reading input
        consoleManager.startConsole(config.getBoolean(ServerConfig.Key.USE_JLINE));
        consoleManager.startFile(config.getString(ServerConfig.Key.LOG_FILE));

        if (getProxySupport()) {
            if (getOnlineMode()) {
                logger.warning("Proxy support is enabled, but online mode is enabled.");
            } else {
                logger.info("Proxy support is enabled.");
            }
        } else if (!getOnlineMode()) {
            logger.warning("The server is running in offline mode! Only do this if you know what you're doing.");
        }

        // Load player lists
        opsList.load();
        whitelist.load();
        nameBans.load();
        ipBans.load();

        // Start loading plugins
        //TODO
        PluginLoader loader = new PluginLoader(new File(config.getString(ServerConfig.Key.PLUGIN_FOLDER)));
        List<Class<?>> plugins = loader.load();
        PluginRegistrar registrar = new PluginRegistrar(game);
        registrar.register(plugins);
        //game.getEventManager().post();

        // Create worlds
        //TODO

        // Finish loading plugins
        //TODO

        scheduler.start();

    }

    public void bindAll() throws BindException {
        bind();
        bindQuery();
        bindRcon();
    }

    /**
     * Binds this server to the address specified in the configuration.
     */
    private void bind() throws BindException {
        SocketAddress address = getBindAddress(ServerConfig.Key.SERVER_PORT);

        logger.info("Binding to address: " + address + "...");
        ChannelFuture future = networkServer.bind(address);
        Channel channel = future.awaitUninterruptibly().channel();
        if (!channel.isActive()) {
            Throwable cause = future.cause();
            if (cause instanceof BindException) {
                throw (BindException) cause;
            }
            throw new RuntimeException("Failed to bind to address", cause);
        }

        logger.info("Successfully bound to: " + channel.localAddress());
        port = ((InetSocketAddress) channel.localAddress()).getPort();
    }

    /**
     * Binds the query server to the address specified in the configuration.
     */
    private void bindQuery() {
        if (!config.getBoolean(ServerConfig.Key.QUERY_ENABLED)) {
            return;
        }

        SocketAddress address = getBindAddress(ServerConfig.Key.QUERY_PORT);
        queryServer = new QueryServer(this, config.getBoolean(ServerConfig.Key.QUERY_PLUGINS));

        logger.info("Binding query to address: " + address + "...");
        ChannelFuture future = queryServer.bind(address);
        Channel channel = future.awaitUninterruptibly().channel();
        if (!channel.isActive()) {
            logger.warning("Failed to bind query. Address already in use?");
        }
    }

    /**
     * Binds the rcon server to the address specified in the configuration.
     */
    private void bindRcon() {
        if (!config.getBoolean(ServerConfig.Key.RCON_ENABLED)) {
            return;
        }

        SocketAddress address = getBindAddress(ServerConfig.Key.RCON_PORT);
        rconServer = new RconServer(this, config.getString(ServerConfig.Key.RCON_PASSWORD));

        logger.info("Binding rcon to address: " + address + "...");
        ChannelFuture future = rconServer.bind(address);
        Channel channel = future.awaitUninterruptibly().channel();
        if (!channel.isActive()) {
            logger.warning("Failed to bind rcon. Address already in use?");
        }
    }

    /**
     * Get the SocketAddress to bind to for a specified service.
     * @param portKey The configuration key for the port to use.
     * @return The SocketAddress
     */
    private SocketAddress getBindAddress(ServerConfig.Key portKey) {
        String ip = config.getString(ServerConfig.Key.SERVER_IP);
        int port = config.getInt(portKey);
        if (ip.length() == 0) {
            return new InetSocketAddress(port);
        } else {
            return new InetSocketAddress(ip, port);
        }
    }

    /**
     * Load the server configuration.
     */
    private void loadConfig() {
        config.load();

        // modifiable values
        spawnRadius = config.getInt(ServerConfig.Key.SPAWN_RADIUS);
        whitelistEnabled = config.getBoolean(ServerConfig.Key.WHITELIST);
        idleTimeout = config.getInt(ServerConfig.Key.PLAYER_IDLE_TIMEOUT);
        craftingManager.initialize();

        // server icon
        defaultIcon = new GlowFavicon(null);
        try {
            File file = config.getFile("server-icon.png");
            if (file.isFile()) {
                defaultIcon = new GlowFavicon(ImageIO.read(file));
            }
        } catch (Exception e) {
            logger.log(Level.WARNING, "Failed to load server-icon.png", e);
        }
    }

    /**
     * Reloads the server, refreshing settings and plugin information
     */
    public void reload() {
        try {
            // Reload relevant configuration
            loadConfig();
            opsList.load();
            whitelist.load();
            nameBans.load();
            ipBans.load();

            // Reset crafting
            craftingManager.resetRecipes();

            // Load plugins
            //TODO
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "Uncaught error while reloading", ex);
        }
    }

    public String toString() {
        return "GlowServer{name=" + getName() + ",version=" + getVersion() + ",minecraftVersion=" + GAME_VERSION + "}";
    }

    ////////////////////////////////////////////////////////////////////////////
    // Access to internals

    /**
     * Gets the session registry.
     * @return The {@link SessionRegistry}.
     */
    public SessionRegistry getSessionRegistry() {
        return sessions;
    }

    /**
     * Gets the entity id manager.
     * @return The {@link EntityIdManager}.
     */
    public EntityIdManager getEntityIdManager() {
        return entityIdManager;
    }

    /**
     * Returns the list of OPs on this server.
     */
    public UuidListFile getOpsList() {
        return opsList;
    }

    /**
     * Returns the list of whitelisted players on this server.
     */
    public UuidListFile getWhitelist() {
        return whitelist;
    }

    /**
     * Returns the folder where configuration files are stored
     */
    public File getConfigDir() {
        return config.getDirectory();
    }

    /**
     * Return the crafting manager.
     * @return The server's crafting manager.
     */
    public CraftingManager getCraftingManager() {
        return craftingManager;
    }

    /**
     * The key pair generated at server start up
     * @return The key pair generated at server start up
     */
    public KeyPair getKeyPair() {
        return keyPair;
    }

    /**
     * Returns the player data service attached to the first world.
     * @return The server's player data service.
     */
    public PlayerDataService getPlayerDataService() {
        return worlds.getWorlds().get(0).getStorageProvider().getPlayerDataService();
    }

    /**
     * Get the threshold to use for network compression defined in the config.
     * @return The compression threshold, or -1 for no compression.
     */
    public int getCompressionThreshold() {
        return config.getInt(ServerConfig.Key.COMPRESSION_THRESHOLD);
    }

    /**
     * Get whether worlds should keep their spawns loaded by default.
     * @return Whether to keep spawns loaded by default.
     */
    public boolean keepSpawnLoaded() {
        return config.getBoolean(ServerConfig.Key.PERSIST_SPAWN);
    }

    /**
     * Get whether parsing of data provided by a proxy is enabled.
     * @return True if a proxy is providing data to use.
     */
    public boolean getProxySupport() {
        return config.getBoolean(ServerConfig.Key.PROXY_SUPPORT);
    }

    /**
     * Get whether to use color codes in Rcon responses.
     * @return True if color codes will be present in Rcon responses
     */
    public boolean useRconColors() {
        return config.getBoolean(ServerConfig.Key.RCON_COLORS);
    }

    /**
     * Get the resource pack url for this server, or {@code null} if not set.
     * @return The url of the resource pack to use, or {@code null}
     */
    public String getResourcePackURL() {
        return config.getString(ServerConfig.Key.RESOURCE_PACK);
    }

    /**
     * Get the resource pack hash for this server, or the empty string if not set.
     * @return The hash of the resource pack, or the empty string
     */
    public String getResourcePackHash() {
        return config.getString(ServerConfig.Key.RESOURCE_PACK_HASH);
    }

    /**
     * Get whether achievements should be announced.
     * @return True if achievements should be announced in chat.
     */
    public boolean getAnnounceAchievements() {
        return config.getBoolean(ServerConfig.Key.ANNOUNCE_ACHIEVEMENTS);
    }

    /**
     * Sets a player as being online internally.
     * @param player player to set online/offline
     * @param online whether the player is online or offline
     */
    public void setPlayerOnline(GlowPlayer player, boolean online) {
        Validate.notNull(player);
        if (online) {
            onlinePlayers.add(player);
        } else {
            onlinePlayers.remove(player);
        }
    }

    public int getViewDistance() {
        return 3; //TODO
    }

    public GlowGame getGame() {
        return game;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Static server properties

    public String getName() {
        return "Glowstone";
    }

    public String getVersion() {
        return getClass().getPackage().getImplementationVersion();
    }

    public String getBukkitVersion() {
        return getClass().getPackage().getSpecificationVersion();
    }

    public Logger getLogger() {
        return logger;
    }

    public boolean isPrimaryThread() {
        return scheduler.isPrimaryThread();
    }

    @Override
    public Collection<Player> getOnlinePlayers() {
        return (Collection) onlineView;
    }

    @Override
    public Optional<Player> getPlayer(String name) {
        //TODO: best match or exact?
        name = name.toLowerCase();
        Player bestPlayer = null;
        int bestDelta = -1;
        for (Player player : getOnlinePlayers()) {
            if (player.getName().toLowerCase().startsWith(name)) {
                int delta = player.getName().length() - name.length();
                if (bestPlayer == null || delta < bestDelta) {
                    bestPlayer = player;
                }
            }
        }
        return Optional.fromNullable(bestPlayer);
    }

    @Override
    public Optional<Player> getPlayer(UUID uuid) {
        for (Player player : getOnlinePlayers()) {
            if (player.getUniqueId().equals(uuid)) {
                return Optional.of(player);
            }
        }
        return Optional.absent();
    }

    @Override
    public Optional<World> getWorld(String name) {
        return (Optional) Optional.fromNullable(worlds.getWorld(name));
    }

    @Override
    public Optional<World> loadWorld(String worldName) {
        if (worlds.getWorld(worldName) != null) {
            return Optional.of((World) worlds.getWorld(worldName));
        }

        GlowWorld world = new GlowWorld(this, null, new AnvilWorldStorageProvider(new File(config.getString(ServerConfig.Key.WORLD_FOLDER))));
        return Optional.of((World) world);
    }

    @Override
    public Optional<World> loadWorld(UUID uniqueId) {
        return null;
    }

    @Override
    public Optional<World> loadWorld(WorldProperties properties) {
        return loadWorld(properties.getUniqueId());
    }

    @Override
    public Optional<WorldProperties> getWorldProperties(String worldName) {
        return null;
    }

    @Override
    public Optional<WorldProperties> getWorldProperties(UUID uniqueId) {
        return null;
    }

    @Override
    public boolean unloadWorld(World world) {
        if (world instanceof GlowWorld) {
            GlowWorld glowWorld = (GlowWorld) world;
            if (glowWorld.unload())
                return worlds.removeWorld(glowWorld);
        }

        return false;
    }

    @Override
    public Optional<WorldProperties> createWorld(WorldCreationSettings settings) {
        return null;
    }

    @Override
    public boolean saveWorldProperties(WorldProperties properties) {
        return false;
    }

    @Override
    public ChunkLayout getChunkLayout() {
        return null;
    }

    @Override
    public int getRunningTimeTicks() {
        return 0;
    }

    @Override
    public MessageSink getBroadcastSink() {
        return broadcastSink;
    }

    public void broadcastMessage(Text message) {
        for (Player player : onlineView)
            player.sendMessage(ChatTypes.CHAT, message);
    }

    @Override
    public Optional<InetSocketAddress> getBoundAddress() {
        return null;
    }

    @Override
    public Optional<World> getWorld(UUID uid) {
        for (GlowWorld world : worlds.getWorlds()) {
            if (uid.equals(world.getUniqueId())) {
                return (Optional) Optional.of(world);
            }
        }
        return Optional.absent();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<World> getWorlds() {
        // Shenanigans needed to cast List<GlowWorld> to List<World>
        return (List) worlds.getWorlds();
    }

    @Override
    public Collection<WorldProperties> getUnloadedWorlds() {
        return null;
    }

    @Override
    public Collection<WorldProperties> getAllWorldProperties() {
        return null;
    }

    /**
     * INTERNAL USE ONLY
     * Add a world to the internal world collection.
     * @param world The world to add.
     */
    public void addWorld(GlowWorld world) {
        worlds.addWorld(world);
    }

    @Override
    public boolean hasWhitelist() {
        return whitelistEnabled;
    }

    @Override
    public void setHasWhitelist(boolean enabled) {
        whitelistEnabled = enabled;
        config.set(ServerConfig.Key.WHITELIST, whitelistEnabled);
        config.save();
    }

    @Override
    public boolean getOnlineMode() {
        return config.getBoolean(ServerConfig.Key.ONLINE_MODE);
    }

    @Override
    public int getMaxPlayers() {
        return config.getInt(ServerConfig.Key.MAX_PLAYERS);
    }

    @Override
    public Text getMotd() {
        return null;
    }

    @Override
    public ConsoleSource getConsole() {
        return consoleManager.getConsoleSource();
    }

    public void shutdown() {
        shutdown(null);
    }

    @Override
    public void shutdown(Text kickMessage) {
        // Just in case this gets called twice
        if (isShuttingDown) {
            return;
        }
        isShuttingDown = true;
        logger.info("The server is shutting down...");

        // Disable plugins
        //TODO

        // Kick all players (this saves their data too)
        for (GlowPlayer player : onlineView) {
            player.kick(kickMessage);
        }

        // Stop the network servers - starts the shutdown process
        // It may take a second or two for Netty to totally clean up
        networkServer.shutdown();
        if (queryServer != null) {
            queryServer.shutdown();
        }
        if (rconServer != null) {
            rconServer.shutdown();
        }

        // Save worlds
        for (World world : getWorlds()) {
            logger.info("Saving world: " + world.getName());
            unloadWorld(world);
        }

        // Stop scheduler and console
        scheduler.stop();
        consoleManager.stop();

        // Wait for a while and terminate any rogue threads
        new ShutdownMonitorThread().start();
    }

    @Override
    public void registerChannel(Object plugin, ChannelListener listener, String channel) throws ChannelRegistrationException {

    }

    @Override
    public List<String> getRegisteredChannels() {
        return null;
    }

}


text:
title: Advanced Barcode Recognition Features in PHP
type: docs
weight: 10
url: /java/advanced-barcode-recognition-features-in-php/
---

**This section includes the following topics:**

- [Get all Possible 1D Barcodes from an Image in PHP](/barcode/java/get-all-possible-1d-barcodes-from-an-image-in-php-html/)
- [Get BarCode Recognition Quality in Percent in PHP](/barcode/java/get-barcode-recognition-quality-in-percent-in-php-html/)
- [Getting Barcode Region Information from the Image in PHP](/barcode/java/getting-barcode-region-information-from-the-image-in-php-html/)
- [Marking Barcode Regions in an Image in PHP](/barcode/java/marking-barcode-regions-in-an-image-in-php-html/)
- [Read Barcode from Specific Region of Image in PHP](/barcode/java/read-barcode-from-specific-region-of-image-in-php-html/)
- [Switch Barcode Recognition Modes According to the Requirement in PHP](/barcode/java/switch-barcode-recognition-modes-according-to-the-requirement-in-php-html/)


text: `npm run start` to build, `npm run server` to view locally.


text:
import urllib2
from bs4 import BeautifulSoup

def getPoubelles():
	dico = dict()
	i=1
	try:
		url = urllib2.urlopen('http://www.portesessonne.fr/Vivre-et-entreprendre/Dechets/Quand-sortir-mes-poubelles', "BuildingType=1&LoadStreetsUrl=%2Fsdform%2Fload_street&City=2&Street=219&SubitRequestSmallButton=")
	except IOError:
		print("Impossible de récupérer les données pour les poubelles.")
		return None
	else:
		soup = BeautifulSoup(url.read())
		for td in soup.find_all('td'):
			dico[i] = td.string.encode("utf-8")
			i = i+1
		return dico

if __name__ == '__main__':
	dico = getPoubelles()
	if dico is not None:
		for elm in dico.values():
			print(elm)


text:
<?php

namespace Magento\Catalog\Model\Product\ProductList;

use Magento\TestFramework\Helper\ObjectManager;

class ToolbarTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Toolbar
     */
    protected $toolbarModel;

    /**
     * @var \Magento\Framework\Stdlib\CookieManagerInterface |\PHPUnit_Framework_MockObject_MockObject
     */
    protected $cookieManagerMock;

    /**
     * @var \Magento\Framework\App\Request\Http |\PHPUnit_Framework_MockObject_MockObject
     */
    protected $requestMock;

    /**
     * Set up
     */
    public function setUp()
    {
        $this->cookieManagerMock = $this->getMock('Magento\Framework\Stdlib\CookieManagerInterface');
        $this->requestMock = $this->getMockBuilder('Magento\Framework\App\Request\Http')
            ->disableOriginalConstructor()
            ->getMock();
        $this->toolbarModel = (new ObjectManager($this))->getObject(
            'Magento\Catalog\Model\Product\ProductList\Toolbar',
            [
                'cookieManager' => $this->cookieManagerMock,
                'request' => $this->requestMock,
            ]
        );
    }

    /**
     * @dataProvider stringParamProvider
     * @param $param
     */
    public function testGetOrder($param)
    {
        $this->cookieManagerMock->expects($this->once())
            ->method('getCookie')
            ->with(Toolbar::ORDER_COOKIE_NAME)
            ->will($this->returnValue($param));
        $this->assertEquals($param, $this->toolbarModel->getOrder());
    }

    /**
     * @dataProvider stringParamProvider
     * @param $param
     */
    public function testGetDirection($param)
    {
        $this->cookieManagerMock->expects($this->once())
            ->method('getCookie')
            ->with(Toolbar::DIRECTION_COOKIE_NAME)
            ->will($this->returnValue($param));
        $this->assertEquals($param, $this->toolbarModel->getDirection());
    }

    /**
     * @dataProvider stringParamProvider
     * @param $param
     */
    public function testGetMode($param)
    {
        $this->cookieManagerMock->expects($this->once())
            ->method('getCookie')
            ->with(Toolbar::MODE_COOKIE_NAME)
            ->will($this->returnValue($param));
        $this->assertEquals($param, $this->toolbarModel->getMode());
    }

    /**
     * @dataProvider stringParamProvider
     * @param $param
     */
    public function testGetLimit($param)
    {
        $this->cookieManagerMock->expects($this->once())
            ->method('getCookie')
            ->with(Toolbar::LIMIT_COOKIE_NAME)
            ->will($this->returnValue($param));
        $this->assertEquals($param, $this->toolbarModel->getLimit());
    }

    /**
     * @dataProvider intParamProvider
     * @param $param
     */
    public function testGetCurrentPage($param)
    {
        $this->requestMock->expects($this->once())
            ->method('getParam')
            ->with(Toolbar::PAGE_PARM_NAME)
            ->will($this->returnValue($param));
        $this->assertEquals($param, $this->toolbarModel->getCurrentPage());
    }

    public function testGetCurrentPageNoParam()
    {
        $this->requestMock->expects($this->once())
            ->method('getParam')
            ->with(Toolbar::PAGE_PARM_NAME)
            ->will($this->returnValue(false));
        $this->assertEquals(1, $this->toolbarModel->getCurrentPage());
    }

    public function stringParamProvider()
    {
        return [
            ['stringParam']
        ];
    }

    public function intParamProvider()
    {
        return [
            ['2'],
            [3]
        ];
    }
}


text:
class WhatThePatchException(Exception):
    pass

class HunkException(WhatThePatchException):
    def __init__(self, msg, hunk=None):
        self.hunk = hunk
        if hunk is not None:
            super(HunkException, self).__init__(
                "{msg}, in hunk #{n}".format(msg=msg, n=hunk)
            )
        else:
            super(HunkException, self).__init__(msg)

class ApplyException(WhatThePatchException):
    pass

class SubprocessException(ApplyException):
    def __init__(self, msg, code):
        super(SubprocessException, self).__init__(msg)
        self.code = code

class HunkApplyException(HunkException, ApplyException, ValueError):
    pass

class ParseException(HunkException, ValueError):
    pass


text:
+++
title = "ExcludedVolume"
weight = 400000
+++

# ExcludedVolume

A simple excluded volume potential.

{{<katex display>}}
U(r) = \epsilon\left(\frac{\sigma}{r}\right)^{12}
{{</katex>}}

## Example

```toml
[[forcefields.global]]
interaction = "Pair"
potential   = "ExcludedVolume"

ignore.particles_within.bond    = 3
ignore.particles_within.contact = 1

spatial_partition.type = "CellList"
spatial_partition.margin = 0.2

cutoff     = 2.5
epsilon    = 0.2
parameters = [
    {index = 0, radius = 2.0}
]
```

## Input Reference

- `cutoff`: Floating (Optional. By default, 2.)
  - Cutoff distance relative to the {{<katex>}} \sigma_{ij} {{</katex>}}.
- `epsilon`: Floating
  - It determines the strength of the potential.
- `index`: Integer
  - The index of the particle. The index is 0-based.
- `offset`: Integer (Optional. By default, 0)
  - Offset for the index.
- `radius`: Floating
  - It determines the effective size of the particle.
  - {{<katex>}} \sigma {{</katex>}} in the above equation is a sum of the radii.


text:
package org.apache.hyracks.util.bytes;

import java.io.IOException;

public class HexPrinter {
    public enum Case {
        LOWER_CASE('a'),
        UPPER_CASE('A');

        private final char a;

        Case(char a) {
            this.a = a;
        }
    }

    public static byte hex(int i, Case c) {
        return (byte) (i < 10 ? i + '0' : i + (c.a - 10));
    }

    public static Appendable printHexString(byte[] bytes, int start, int length, Appendable appendable)
            throws IOException {
        for (int i = 0; i < length; ++i) {
            appendable.append((char) hex((bytes[start + i] >>> 4) & 0x0f, Case.UPPER_CASE));
            appendable.append((char) hex((bytes[start + i] & 0x0f), Case.UPPER_CASE));
        }
        return appendable;
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spi.classloader;

import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorIndexHandle;
import com.facebook.presto.spi.ConnectorIndexResolver;
import com.facebook.presto.spi.ConnectorResolvedIndex;
import com.facebook.presto.spi.ConnectorTableHandle;
import com.facebook.presto.spi.ConnectorIndex;
import com.facebook.presto.spi.TupleDomain;

import java.util.List;
import java.util.Set;

import static java.util.Objects.requireNonNull;

public class ClassLoaderSafeConnectorIndexResolver
        implements ConnectorIndexResolver
{
    private final ConnectorIndexResolver delegate;
    private final ClassLoader classLoader;

    public ClassLoaderSafeConnectorIndexResolver(ConnectorIndexResolver delegate, ClassLoader classLoader)
    {
        this.delegate = requireNonNull(delegate, "delegate is null");
        this.classLoader = requireNonNull(classLoader, "classLoader is null");
    }

    @Override
    public ConnectorResolvedIndex resolveIndex(ConnectorTableHandle tableHandle, Set<ColumnHandle> indexableColumns, TupleDomain<ColumnHandle> tupleDomain)
    {
        try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
            return delegate.resolveIndex(tableHandle, indexableColumns, tupleDomain);
        }
    }

    @Override
    public ConnectorIndex getIndex(ConnectorIndexHandle indexHandle, List<ColumnHandle> lookupSchema, List<ColumnHandle> outputSchema)
    {
        try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(classLoader)) {
            return delegate.getIndex(indexHandle, lookupSchema, outputSchema);
        }
    }
}


text:
Given a string, return its encoding defined as follows:

First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
for example, "aabbbc" is divided into ["aa", "bbb", "c"]
Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character
for example, substring "bbb" is replaced by "3b"
Finally, all the new strings are concatenated together in the same order and a new string is returned.

SUBSTRING

A substring of a string S is another string S' that occurs in S. For example, "Fights" is a substring of "CodeFights", but "CoFi" isn't.

Example

For s = "aabbbc", the output should be lineEncoding(s) = "2a3bc".

Input/Output

[time limit] 4000ms (py)

[input] string s (String consisting of lowercase English letters.)

Constraints: 4 ≤ s.length ≤ 15.

[output] string (Encoded version of s.)

Solution:

import re
def lineEncoding(s):
    grub = [ m.group(0) for m in re.finditer(r"(\w)\1*", s )]
    numb = 0
    out  = []
    for i in grub:
        numb += 1
        if len(i) > 1:
            out.append(grub[numb-1].replace(grub[numb-1], str(len(i))+i[0]))
        else:
            out.append(i)
    return ''.join(out)

Result Tests:

>>>
s = "aabbbc"
>>> lineEncoding(s)
"2a3bc"
>>>
>>> s = "abbcabb"
>>> lineEncoding(s)
"a2bca2b"
>>>
>>> s = "abcd"
>>> lineEncoding(s)
"abcd"
>>>


text:
<!DOCTYPE html>

This test ensures WebKit adjusts the selection under document mutation.

 Examples are from:
 http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Mutation


text:
module.exports = {
  plugins: ['lodash'],
  rules: {
    // Disallow named imports: import { foo } from 'lodash';
    // Only allow: import foo from 'lodash/foo';
    // @see https://github.com/wix/eslint-plugin-lodash/blob/HEAD/docs/rules/import-scope.md
    'lodash/import-scope': [2, 'method'],
  },
};


text:
//  ConvertObjectOriented.cpp (c) 1998-2006 Kari Laitinen

//  http://www.naturalprogramming.com

//  2006-06-11  File created.
//  2006-06-11  Last modification.

//  This is an object-oriented version of program Convert.cpp.
//  This is not presented in the C++ book. This version corresponds
//  to the programs Convert.java, Convert.cs and Convert.py that
//  are available at http://www.naturalprogramming.com

#include  <iostream.h>
#include  <string.h>
#include  <stdlib.h>

class  Conversion
{
protected:
   char    first_unit[ 20 ] ;
   char    second_unit[ 20 ] ;
   double  conversion_constant ;

public:
   Conversion()  {}  // default constructor

   Conversion( char  given_first_unit[],
               char  given_second_unit[],
               double  given_conversion_constant )
   {
      strcpy( first_unit, given_first_unit ) ;
      strcpy( second_unit, given_second_unit ) ;
      conversion_constant  =  given_conversion_constant ;
   }

   void convert( char   given_unit[],
                 double amount_to_convert )
   {
      if ( strstr( first_unit, given_unit ) )
      {
         cout << "\n  " << amount_to_convert << " " << first_unit
              << " is " << amount_to_convert * conversion_constant
              << " " << second_unit ;
      }

      if ( strstr( second_unit, given_unit ) )
      {
         cout << "\n  " << amount_to_convert << " "  << second_unit
              << " is " << amount_to_convert / conversion_constant
              << " " << first_unit ;
      }
   }
} ;

int main( int    number_of_command_line_arguments,
          char*  command_line_arguments[] )
{
   Conversion conversion_table[ 13 ] ;

   conversion_table[ 0 ] = Conversion("meters", "yards", 1.093613 );
   conversion_table[ 1 ] = Conversion("meters", "feet",  3.280840 );
   conversion_table[ 2 ] = Conversion("miles",  "kilometers",1.609344);
   conversion_table[ 3 ] = Conversion("inches", "centimeters", 2.54 );
   conversion_table[ 4 ] = Conversion("acres",  "hectares", 0.4046873);
   conversion_table[ 5 ] = Conversion("pounds", "kilograms",0.4535924);
   conversion_table[ 6 ] = Conversion("ounces", "grams",    28.35 );
   conversion_table[ 7 ] = Conversion("gallons (U.S.)","liters", 3.785);
   conversion_table[ 8 ] = Conversion("gallons (Br.)", "liters", 4.546);
   conversion_table[ 9 ] = Conversion("pints (U.S.)",  "liters", 0.473);
   conversion_table[ 10 ]= Conversion("pints (Br.)",   "liters", 0.568);
   conversion_table[ 11 ]= Conversion("joules",       "calories",4.187);
   conversion_table[ 12 ]= Conversion("lightyears",   "kilometers",
                                                              9.461e12 ) ;
   char unit_from_user[ 20 ] ;
   int  amount_to_convert ;

   int  number_of_conversions_in_table = sizeof( conversion_table ) /
                                         sizeof( Conversion ) ;

   if ( number_of_command_line_arguments  ==  3 )
   {
      strcpy( unit_from_user, command_line_arguments[ 1 ] ) ;
      amount_to_convert  =  atoi( command_line_arguments[ 2 ] ) ;
   }
   else
   {
      cout  <<  "\n Give the unit to convert from: " ;
      cin   >>  unit_from_user ;
      cout  <<  " Give the amount to convert:   " ;
      cin   >>  amount_to_convert ;
   }

   for ( int conversion_index  =  0 ;
             conversion_index  <  number_of_conversions_in_table ;
             conversion_index  ++ )
   {
      conversion_table[ conversion_index ].convert( unit_from_user,
                                                    amount_to_convert ) ;
   }
}


text:
The server component. Remember to add your username and password to match what you set up in the app

The following directory is added to your server.


text:
package com.hazelcast.client.replicatedmap;

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientNetworkConfig;
import com.hazelcast.client.properties.ClientProperty;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.replicatedmap.ReplicatedMap;
import com.hazelcast.cluster.Address;
import com.hazelcast.replicatedmap.ReplicatedMapCantBeCreatedOnLiteMemberException;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import static com.hazelcast.test.HazelcastTestSupport.assertClusterSizeEventually;
import static com.hazelcast.test.Accessors.getAddress;
import static com.hazelcast.test.HazelcastTestSupport.randomMapName;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ClientReplicatedMapLiteMemberTest {

    private TestHazelcastFactory factory;

    private ClientConfig smartClientConfig;
    private ClientConfig dummyClientConfig;

    @Before
    public void init() {
        factory = new TestHazelcastFactory();
        smartClientConfig = new ClientConfig();
        dummyClientConfig = new ClientConfig();
        dummyClientConfig.getNetworkConfig().setSmartRouting(false);
    }

    @After
    public void destroy() {
        factory.terminateAll();
    }

    @Test
    public void testReplicatedMapIsCreatedBySmartClient() {
        testReplicatedMapCreated(2, 1, smartClientConfig);
    }

    @Test
    public void testReplicatedMapIsCreatedByDummyClient() {
        testReplicatedMapCreated(2, 1, dummyClientConfig);
    }

    @Test(expected = ReplicatedMapCantBeCreatedOnLiteMemberException.class)
    public void testReplicatedMapNotCreatedOnOnlyLiteMembersBySmartClient() {
        testReplicatedMapCreated(2, 0, smartClientConfig);
    }

    @Test(expected = ReplicatedMapCantBeCreatedOnLiteMemberException.class)
    public void testReplicatedMapNotCreatedOnOnlyLiteMembersByDummyClient() {
        testReplicatedMapCreated(2, 0, dummyClientConfig);
    }

    @Test(expected = ReplicatedMapCantBeCreatedOnLiteMemberException.class)
    public void testReplicatedMapNotCreatedOnSingleLiteMemberBySmartClient() {
        testReplicatedMapCreated(1, 0, smartClientConfig);
    }

    @Test(expected = ReplicatedMapCantBeCreatedOnLiteMemberException.class)
    public void testReplicatedMapNotCreatedOnSingleLiteMemberByDummyClient() {
        testReplicatedMapCreated(1, 0, dummyClientConfig);
    }

    private void testReplicatedMapCreated(int numberOfLiteNodes, int numberOfDataNodes, ClientConfig clientConfig) {
        createNodes(numberOfLiteNodes, numberOfDataNodes);

        HazelcastInstance client = factory.newHazelcastClient(clientConfig);
        assertNotNull(client.getReplicatedMap(randomMapName()));
    }

    @Test
    public void testReplicatedMapPutBySmartClient() {
        createNodes(3, 1);

        HazelcastInstance client = factory.newHazelcastClient();
        ReplicatedMap<Object, Object> map = client.getReplicatedMap(randomMapName());
        assertNull(map.put(1, 2));
    }

    @Test
    public void testReplicatedMapPutByDummyClient() throws UnknownHostException {
        List<HazelcastInstance> instances = createNodes(3, 1);
        configureDummyClientConnection(instances.get(0));

        HazelcastInstance client = factory.newHazelcastClient(dummyClientConfig);

        ReplicatedMap<Object, Object> map = client.getReplicatedMap(randomMapName());
        map.put(1, 2);
    }

    private void configureDummyClientConnection(HazelcastInstance instance) throws UnknownHostException {
        Address memberAddress = getAddress(instance);
        dummyClientConfig.setProperty(ClientProperty.SHUFFLE_MEMBER_LIST.getName(), "false");
        ClientNetworkConfig networkConfig = dummyClientConfig.getNetworkConfig();
        networkConfig.addAddress(memberAddress.getHost() + ":" + memberAddress.getPort());
    }

    private List<HazelcastInstance> createNodes(int numberOfLiteNodes, int numberOfDataNodes) {
        List<HazelcastInstance> instances = new ArrayList<HazelcastInstance>();

        Config liteConfig = new Config().setLiteMember(true);
        for (int i = 0; i < numberOfLiteNodes; i++) {
            instances.add(factory.newHazelcastInstance(liteConfig));
        }

        for (int i = 0; i < numberOfDataNodes; i++) {
            instances.add(factory.newHazelcastInstance());
        }

        int clusterSize = numberOfLiteNodes + numberOfDataNodes;
        for (HazelcastInstance instance : instances) {
            assertClusterSizeEventually(clusterSize, instance);
        }

        return instances;
    }
}


text:
package com.microsoft.azure.management.datafactory.v2018_06_01.implementation;

import com.microsoft.azure.management.datafactory.v2018_06_01.DataFlowDebugCommandResponse;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;

class DataFlowDebugCommandResponseImpl extends WrapperImpl<DataFlowDebugCommandResponseInner> implements DataFlowDebugCommandResponse {
    private final DataFactoryManager manager;
    DataFlowDebugCommandResponseImpl(DataFlowDebugCommandResponseInner inner, DataFactoryManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public DataFactoryManager manager() {
        return this.manager;
    }

    @Override
    public String data() {
        return this.inner().data();
    }

    @Override
    public String status() {
        return this.inner().status();
    }

}


text:
@interface STKEventPool (RZImport) <RZImportable>

@end


text:
  #define _BOOST_CSTDFLOAT_LIMITS_2014_01_09_HPP_

  #include <boost/math/cstdfloat/cstdfloat_types.hpp>

  #if defined(BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T) && defined(BOOST_MATH_USE_FLOAT128) && !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT)

    #include <limits>

    // Define the name of the global quadruple-precision function to be used for
    // calculating quiet_NaN() in the specialization of std::numeric_limits<>.
    #if defined(BOOST_INTEL)
      #define BOOST_CSTDFLOAT_FLOAT128_SQRT   __sqrtq
    #elif defined(__GNUC__)
      #define BOOST_CSTDFLOAT_FLOAT128_SQRT   sqrtq
    #endif

    // Forward declaration of the quadruple-precision square root function.
    extern "C" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SQRT(boost::math::cstdfloat::detail::float_internal128_t) throw();

    namespace std
    {
      template<>
      class numeric_limits<boost::math::cstdfloat::detail::float_internal128_t>
      {
      public:
        BOOST_STATIC_CONSTEXPR bool                                                 is_specialized           = true;
        static                 boost::math::cstdfloat::detail::float_internal128_t  (min) () BOOST_NOEXCEPT  { return BOOST_CSTDFLOAT_FLOAT128_MIN; }
        static                 boost::math::cstdfloat::detail::float_internal128_t  (max) () BOOST_NOEXCEPT  { return BOOST_CSTDFLOAT_FLOAT128_MAX; }
        static                 boost::math::cstdfloat::detail::float_internal128_t  lowest() BOOST_NOEXCEPT  { return -(max)(); }
        BOOST_STATIC_CONSTEXPR int                                                  digits                   = 113;
        BOOST_STATIC_CONSTEXPR int                                                  digits10                 = 33;
        BOOST_STATIC_CONSTEXPR int                                                  max_digits10             = 36;
        BOOST_STATIC_CONSTEXPR bool                                                 is_signed                = true;
        BOOST_STATIC_CONSTEXPR bool                                                 is_integer               = false;
        BOOST_STATIC_CONSTEXPR bool                                                 is_exact                 = false;
        BOOST_STATIC_CONSTEXPR int                                                  radix                    = 2;
        static                 boost::math::cstdfloat::detail::float_internal128_t  epsilon    ()            { return BOOST_CSTDFLOAT_FLOAT128_EPS; }
        static                 boost::math::cstdfloat::detail::float_internal128_t  round_error()            { return BOOST_FLOAT128_C(0.5); }
        BOOST_STATIC_CONSTEXPR int                                                  min_exponent             = -16381;
        BOOST_STATIC_CONSTEXPR int                                                  min_exponent10           = static_cast<int>((min_exponent * 301L) / 1000L);
        BOOST_STATIC_CONSTEXPR int                                                  max_exponent             = +16384;
        BOOST_STATIC_CONSTEXPR int                                                  max_exponent10           = static_cast<int>((max_exponent * 301L) / 1000L);
        BOOST_STATIC_CONSTEXPR bool                                                 has_infinity             = true;
        BOOST_STATIC_CONSTEXPR bool                                                 has_quiet_NaN            = true;
        BOOST_STATIC_CONSTEXPR bool                                                 has_signaling_NaN        = false;
        BOOST_STATIC_CONSTEXPR float_denorm_style                                   has_denorm               = denorm_absent;
        BOOST_STATIC_CONSTEXPR bool                                                 has_denorm_loss          = false;
        static                 boost::math::cstdfloat::detail::float_internal128_t  infinity     ()          { return BOOST_FLOAT128_C(1.0) / BOOST_FLOAT128_C(0.0); }
        static                 boost::math::cstdfloat::detail::float_internal128_t  quiet_NaN    ()          { return ::BOOST_CSTDFLOAT_FLOAT128_SQRT(BOOST_FLOAT128_C(-1.0)); }
        static                 boost::math::cstdfloat::detail::float_internal128_t  signaling_NaN()          { return BOOST_FLOAT128_C(0.0); }
        static                 boost::math::cstdfloat::detail::float_internal128_t  denorm_min   ()          { return BOOST_FLOAT128_C(0.0); }
        BOOST_STATIC_CONSTEXPR bool                                                 is_iec559                = true;
        BOOST_STATIC_CONSTEXPR bool                                                 is_bounded               = false;
        BOOST_STATIC_CONSTEXPR bool                                                 is_modulo                = false;
        BOOST_STATIC_CONSTEXPR bool                                                 traps                    = false;
        BOOST_STATIC_CONSTEXPR bool                                                 tinyness_before          = false;
        BOOST_STATIC_CONSTEXPR float_round_style                                    round_style              = round_to_nearest;
      };
    } // namespace std

  #endif // Not BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT (i.e., the user would like to have libquadmath support)

#endif // _BOOST_CSTDFLOAT_LIMITS_2014_01_09_HPP_


text:
/**
 **************************************************************************
 * File Name    : at32f4xx_i2c.h
 * Description  : at32f4xx I2C header file
 * Date         : 2018-10-08
 * Version      : V1.0.5
 **************************************************************************
 */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __AT32F4xx_I2C_H
#define __AT32F4xx_I2C_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "at32f4xx.h"

/** @addtogroup at32f4xx_StdPeriph_Driver
  * @{
  */

/** @addtogroup I2C
  * @{
  */

/** @defgroup I2C_Exported_Types
  * @{
  */

/**
  * @brief  I2C Init structure definition
  */

typedef struct
{
    uint32_t I2C_BitRate;           /*!< Specifies the clock frequency.
                                         This parameter must be set to a value lower than 400kHz */

    uint16_t I2C_Mode;              /*!< Specifies the I2C mode.
                                         This parameter can be a value of @ref I2C_mode */

    uint16_t I2C_FmDutyCycle;       /*!< Specifies the I2C fast mode duty cycle.
                                         This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */

    uint16_t I2C_OwnAddr1;          /*!< Specifies the first device own address.
                                         This parameter can be a 7-bit or 10-bit address. */

    uint16_t I2C_Ack;               /*!< Enables or disables the acknowledgement.
                                         This parameter can be a value of @ref I2C_acknowledgement */

    uint16_t I2C_AddrMode;          /*!< Specifies if 7-bit or 10-bit address is acknowledged.
                                         This parameter can be a value of @ref I2C_acknowledged_address */
} I2C_InitType;

/**
  * @}
  */

/** @defgroup I2C_Exported_Constants
  * @{
  */

#if defined (AT32F413xx) || defined (AT32F415xx)
#define IS_I2C_ALL_PERIPH(PERIPH)       (((PERIPH) == I2C1) || \
                                         ((PERIPH) == I2C2))
#elif defined (AT32F403xx) || defined (AT32F403Axx) || \
      defined (AT32F407xx)
#define IS_I2C_ALL_PERIPH(PERIPH)       (((PERIPH) == I2C1) || \
                                         ((PERIPH) == I2C2) || \
                                         ((PERIPH) == I2C3))
#endif

/** @defgroup I2C_mode
  * @{
  */

#define I2C_Mode_I2CDevice              ((uint16_t)0x0000)
#define I2C_Mode_SMBusDevice            ((uint16_t)0x0002)
#define I2C_Mode_SMBusHost              ((uint16_t)0x000A)
#define IS_I2C_MODE(MODE)               (((MODE) == I2C_Mode_I2CDevice) || \
                                         ((MODE) == I2C_Mode_SMBusDevice) || \
                                         ((MODE) == I2C_Mode_SMBusHost))
/**
  * @}
  */

/** @defgroup I2C_duty_cycle_in_fast_mode
  * @{
  */

#define I2C_FmDutyCycle_16_9            ((uint16_t)0x4000) /*!< I2C fast mode Tlow/Thigh = 16/9 */
#define I2C_FmDutyCycle_2_1             ((uint16_t)0xBFFF) /*!< I2C fast mode Tlow/Thigh = 2 */
#define IS_I2C_FM_DUTY_CYCLE(CYCLE)     (((CYCLE) == I2C_FmDutyCycle_16_9) || \
                                         ((CYCLE) == I2C_FmDutyCycle_2_1))
/**
  * @}
  */

/** @defgroup I2C_acknowledgement
  * @{
  */

#define I2C_Ack_Enable                  ((uint16_t)0x0400)
#define I2C_Ack_Disable                 ((uint16_t)0x0000)
#define IS_I2C_ACK_STATE(STATE)         (((STATE) == I2C_Ack_Enable) || \
                                         ((STATE) == I2C_Ack_Disable))
/**
  * @}
  */

/** @defgroup I2C_transfer_direction
  * @{
  */

#define  I2C_Direction_Transmit         ((uint8_t)0x00)
#define  I2C_Direction_Receive          ((uint8_t)0x01)
#define IS_I2C_DIRECTION(DIRECTION)     (((DIRECTION) == I2C_Direction_Transmit) || \
                                         ((DIRECTION) == I2C_Direction_Receive))
/**
  * @}
  */

/** @defgroup I2C_acknowledged_address
  * @{
  */

#define I2C_AddrMode_7bit               ((uint16_t)0x4000)
#define I2C_AddrMode_10bit              ((uint16_t)0xC000)
#define IS_I2C_ADDR_MODE(MODE)          (((MODE) == I2C_AddrMode_7bit) || \
                                         ((MODE) == I2C_AddrMode_10bit))
/**
  * @}
  */

/** @defgroup I2C_registers
  * @{
  */

#define I2C_Register_CTRL1              ((uint8_t)0x00)
#define I2C_Register_CTRL2              ((uint8_t)0x04)
#define I2C_Register_OADDR1             ((uint8_t)0x08)
#define I2C_Register_OADDR2             ((uint8_t)0x0C)
#define I2C_Register_DT                 ((uint8_t)0x10)
#define I2C_Register_STS1               ((uint8_t)0x14)
#define I2C_Register_STS2               ((uint8_t)0x18)
#define I2C_Register_CLKCTRL            ((uint8_t)0x1C)
#define I2C_Register_TMRISE             ((uint8_t)0x20)
#define IS_I2C_REGISTER(REGISTER)       (((REGISTER) == I2C_Register_CTRL1)  || \
                                         ((REGISTER) == I2C_Register_CTRL2)  || \
                                         ((REGISTER) == I2C_Register_OADDR1) || \
                                         ((REGISTER) == I2C_Register_OADDR2) || \
                                         ((REGISTER) == I2C_Register_DT)     || \
                                         ((REGISTER) == I2C_Register_STS1)   || \
                                         ((REGISTER) == I2C_Register_STS2)   || \
                                         ((REGISTER) == I2C_Register_CLKCTRL)|| \
                                         ((REGISTER) == I2C_Register_TMRISE))
/**
  * @}
  */

/** @defgroup I2C_SMBus_alert_pin_level
  * @{
  */

#define I2C_SMBusAlert_Low              ((uint16_t)0x2000)
#define I2C_SMBusAlert_High             ((uint16_t)0xDFFF)
#define IS_I2C_SMBUS_ALERT(ALERT)       (((ALERT) == I2C_SMBusAlert_Low) || \
                                         ((ALERT) == I2C_SMBusAlert_High))
/**
  * @}
  */

/** @defgroup I2C_PEC_position
  * @{
  */

#define I2C_PECPosition_Next            ((uint16_t)0x0800)
#define I2C_PECPosition_Current         ((uint16_t)0xF7FF)
#define IS_I2C_PEC_POSITION(POSITION)   (((POSITION) == I2C_PECPosition_Next) || \
                                         ((POSITION) == I2C_PECPosition_Current))
/**
  * @}
  */

/** @defgroup I2C_NCAK_position
  * @{
  */

#define I2C_NACKPosition_Next           ((uint16_t)0x0800)
#define I2C_NACKPosition_Current        ((uint16_t)0xF7FF)
#define IS_I2C_NACK_POSITION(POSITION)  (((POSITION) == I2C_NACKPosition_Next) || \
                                         ((POSITION) == I2C_NACKPosition_Current))
/**
  * @}
  */

/** @defgroup I2C_interrupts_definition
  * @{
  */

#define I2C_INT_BUF                     ((uint16_t)0x0400)
#define I2C_INT_EVT                     ((uint16_t)0x0200)
#define I2C_INT_ERR                     ((uint16_t)0x0100)
#define IS_I2C_CONFIG_INT(INT)          ((((INT) & (uint16_t)0xF8FF) == 0x00) && ((INT) != 0x00))
/**
  * @}
  */

/** @defgroup I2C_interrupts_definition
  * @{
  */

#define I2C_INT_SMBALERTF               ((uint32_t)0x01008000)
#define I2C_INT_TIMOUT                  ((uint32_t)0x01004000)
#define I2C_INT_PECERR                  ((uint32_t)0x01001000)
#define I2C_INT_OVRUN                   ((uint32_t)0x01000800)
#define I2C_INT_ACKFAIL                 ((uint32_t)0x01000400)
#define I2C_INT_ARLOST                  ((uint32_t)0x01000200)
#define I2C_INT_BUSERR                  ((uint32_t)0x01000100)
#define I2C_INT_TDE                     ((uint32_t)0x06000080)
#define I2C_INT_RDNE                    ((uint32_t)0x06000040)
#define I2C_INT_STOPF                   ((uint32_t)0x02000010)
#define I2C_INT_ADDR10F                 ((uint32_t)0x02000008)
#define I2C_INT_BTFF                    ((uint32_t)0x02000004)
#define I2C_INT_ADDRF                   ((uint32_t)0x02000002)
#define I2C_INT_STARTF                  ((uint32_t)0x02000001)

#define IS_I2C_CLEAR_INT(INT)           ((((INT) & (uint16_t)0x20FF) == 0x00) && ((INT) != (uint16_t)0x00))

#define IS_I2C_GET_INT(INT)             (((INT) == I2C_INT_SMBALERTF) || ((INT) == I2C_INT_TIMOUT) || \
                                         ((INT) == I2C_INT_PECERR)    || ((INT) == I2C_INT_OVRUN)  || \
                                         ((INT) == I2C_INT_ACKFAIL)   || ((INT) == I2C_INT_ARLOST) || \
                                         ((INT) == I2C_INT_BUSERR)    || ((INT) == I2C_INT_TDE)    || \
                                         ((INT) == I2C_INT_RDNE)      || ((INT) == I2C_INT_STOPF)  || \
                                         ((INT) == I2C_INT_ADDR10F)   || ((INT) == I2C_INT_BTFF)   || \
                                         ((INT) == I2C_INT_ADDRF)     || ((INT) == I2C_INT_STARTF))
/**
  * @}
  */

/** @defgroup I2C_flags_definition
  * @{
  */

/**
  * @brief  SR2 register flags
  */

#define I2C_FLAG_DUALF                  ((uint32_t)0x00800000)
#define I2C_FLAG_SMBHOSTADDRF           ((uint32_t)0x00400000)
#define I2C_FLAG_SMBDEFTADDRF           ((uint32_t)0x00200000)
#define I2C_FLAG_GCADDRF                ((uint32_t)0x00100000)
#define I2C_FLAG_TRF                    ((uint32_t)0x00040000)
#define I2C_FLAG_BUSYF                  ((uint32_t)0x00020000)
#define I2C_FLAG_MSF                    ((uint32_t)0x00010000)

/**
  * @brief  SR1 register flags
  */

#define I2C_FLAG_SMBALERTF              ((uint32_t)0x10008000)
#define I2C_FLAG_TIMOUT                 ((uint32_t)0x10004000)
#define I2C_FLAG_PECERR                 ((uint32_t)0x10001000)
#define I2C_FLAG_OVRUN                  ((uint32_t)0x10000800)
#define I2C_FLAG_ACKFAIL                ((uint32_t)0x10000400)
#define I2C_FLAG_ARLOST                 ((uint32_t)0x10000200)
#define I2C_FLAG_BUSERR                 ((uint32_t)0x10000100)
#define I2C_FLAG_TDE                    ((uint32_t)0x10000080)
#define I2C_FLAG_RDNE                   ((uint32_t)0x10000040)
#define I2C_FLAG_STOPF                  ((uint32_t)0x10000010)
#define I2C_FLAG_ADDR10F                ((uint32_t)0x10000008)
#define I2C_FLAG_BTFF                   ((uint32_t)0x10000004)
#define I2C_FLAG_ADDRF                  ((uint32_t)0x10000002)
#define I2C_FLAG_STARTF                 ((uint32_t)0x10000001)

#define IS_I2C_CLEAR_FLAG(FLAG)         ((((FLAG) & (uint16_t)0x20FF) == 0x00) && ((FLAG) != (uint16_t)0x00))

#define IS_I2C_GET_FLAG(FLAG)           (((FLAG) == I2C_FLAG_DUALF)        || ((FLAG) == I2C_FLAG_SMBHOSTADDRF) || \
                                         ((FLAG) == I2C_FLAG_SMBDEFTADDRF) || ((FLAG) == I2C_FLAG_GCADDRF)      || \
                                         ((FLAG) == I2C_FLAG_TRF)          || ((FLAG) == I2C_FLAG_BUSYF)        || \
                                         ((FLAG) == I2C_FLAG_MSF)          || ((FLAG) == I2C_FLAG_SMBALERTF)    || \
                                         ((FLAG) == I2C_FLAG_TIMOUT)       || ((FLAG) == I2C_FLAG_PECERR)       || \
                                         ((FLAG) == I2C_FLAG_OVRUN)        || ((FLAG) == I2C_FLAG_ACKFAIL)      || \
                                         ((FLAG) == I2C_FLAG_ARLOST)       || ((FLAG) == I2C_FLAG_BUSERR)       || \
                                         ((FLAG) == I2C_FLAG_TDE)          || ((FLAG) == I2C_FLAG_RDNE)         || \
                                         ((FLAG) == I2C_FLAG_STOPF)        || ((FLAG) == I2C_FLAG_ADDR10F)      || \
                                         ((FLAG) == I2C_FLAG_BTFF)         || ((FLAG) == I2C_FLAG_ADDRF)        || \
                                         ((FLAG) == I2C_FLAG_STARTF))
/**
  * @}
  */

/** @defgroup I2C_Events
  * @{
  */

/*========================================

                     I2C Master Events (Events grouped in order of communication)
                                                        ==========================================*/
/**
  * @brief  Communication start
  *
  * After sending the START condition (I2C_GenerateSTART() function) the master
  * has to wait for this event. It means that the Start condition has been correctly
  * released on the I2C bus (the bus is free, no other devices is communicating).
  *
  */
/* --EV5 */
#define  I2C_EVENT_MASTER_START_GENERATED               ((uint32_t)0x00030001)  /* BUSY, MSL and SB flag */

/**
  * @brief  Address Acknowledge
  *
  * After checking on EV5 (start condition correctly released on the bus), the
  * master sends the address of the slave(s) with which it will communicate
  * (I2C_Send7bitAddress() function, it also determines the direction of the communication:
  * Master transmitter or Receiver). Then the master has to wait that a slave acknowledges
  * his address. If an acknowledge is sent on the bus, one of the following events will
  * be set:
  *
  *  1) In case of Master Receiver (7-bit addressing): the I2C_EVENT_MASTER_ADDRESS_WITH_RECEIVER
  *     event is set.
  *
  *  2) In case of Master Transmitter (7-bit addressing): the I2C_EVENT_MASTER_ADDRESS | I2C_EVENT_MASTER_TRANSMITTER
  *     is set
  *
  *  3) In case of 10-Bit addressing mode, the master (just after generating the START
  *  and checking on EV5) has to send the header of 10-bit addressing mode (I2C_SendData()
  *  function). Then master should wait on EV9. It means that the 10-bit addressing
  *  header has been correctly sent on the bus. Then master should send the second part of
  *  the 10-bit address (LSB) using the function I2C_Send7bitAddress(). Then master
  *  should wait for event EV6.
  *
  */

/* --EV6 */
#define  I2C_EVENT_MASTER_ADDRESS                       ((uint32_t)0x00070002)  /* BUSY, MSL, ADDR and TRF flags */
#define  I2C_EVENT_MASTER_TRANSMITTER                   ((uint32_t)0x00000080)  /* TDE flags */
#define  I2C_EVENT_MASTER_ADDRESS_WITH_RECEIVER         ((uint32_t)0x00030002)  /* BUSY, MSL and ADDR flags */
/* --EV9 */
#define  I2C_EVENT_MASTER_ADDRESS10_GENERATED           ((uint32_t)0x00030008)  /* BUSY, MSL and ADD10 flags */

/**
  * @brief Communication events
  *
  * If a communication is established (START condition generated and slave address
  * acknowledged) then the master has to check on one of the following events for
  * communication procedures:
  *
  * 1) Master Receiver mode: The master has to wait on the event EV7 then to read
  *    the data received from the slave (I2C_ReceiveData() function).
  *
  * 2) Master Transmitter mode: The master has to send data (I2C_SendData()
  *    function) then to wait on event EV8 or EV8_2.
  *    These two events are similar:
  *     - EV8 means that the data has been written in the data register and is
  *       being shifted out.
  *     - EV8_2 means that the data has been physically shifted out and output
  *       on the bus.
  *     In most cases, using EV8 is sufficient for the application.
  *     Using EV8_2 leads to a slower communication but ensure more reliable test.
  *     EV8_2 is also more suitable than EV8 for testing on the last data transmission
  *     (before Stop condition generation).
  *
  *  @note In case the  user software does not guarantee that this event EV7 is
  *  managed before the current byte end of transfer, then user may check on EV7
  *  and BTF flag at the same time (ie. (I2C_EVENT_MASTER_DATA_RECEIVED | I2C_FLAG_BTFF)).
  *  In this case the communication may be slower.
  *
  */

/* Master RECEIVER mode -----------------------------*/
/* --EV7 */
#define  I2C_EVENT_MASTER_DATA_RECEIVED                 ((uint32_t)0x00030040)  /* BUSY, MSL and RXNE flags */

/* Master TRANSMITTER mode --------------------------*/
/* --EV8 */
#define I2C_EVENT_MASTER_DATA_TRANSMITTING              ((uint32_t)0x00070080) /* TRA, BUSY, MSL, TXE flags */
/* --EV8_2 */
#define  I2C_EVENT_MASTER_DATA_TRANSMITTED              ((uint32_t)0x00070084)  /* TRA, BUSY, MSL, TXE and BTF flags */

/*========================================

                     I2C Slave Events (Events grouped in order of communication)
                                                        ==========================================*/

/**
  * @brief  Communication start events
  *
  * Wait on one of these events at the start of the communication. It means that
  * the I2C peripheral detected a Start condition on the bus (generated by master
  * device) followed by the peripheral address. The peripheral generates an ACK
  * condition on the bus (if the acknowledge feature is enabled through function
  * I2C_AcknowledgeConfig()) and the events listed above are set :
  *
  * 1) In normal case (only one address managed by the slave), when the address
  *   sent by the master matches the own address of the peripheral (configured by
  *   I2C_OwnAddress1 field) the I2C_EVENT_SLAVE_XXX_ADDRESS_MATCHED event is set
  *   (where XXX could be TRANSMITTER or RECEIVER).
  *
  * 2) In case the address sent by the master matches the second address of the
  *   peripheral (configured by the function I2C_OwnAddress2Config() and enabled
  *   by the function I2C_DualAddressCmd()) the events I2C_EVENT_SLAVE_XXX_SECONDADDRESS_MATCHED
  *   (where XXX could be TRANSMITTER or RECEIVER) are set.
  *
  * 3) In case the address sent by the master is General Call (address 0x00) and
  *   if the General Call is enabled for the peripheral (using function I2C_GeneralCallCmd())
  *   the following event is set I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED.
  *
  */

/* --EV1  (all the events below are variants of EV1) */
/* 1) Case of One Single Address managed by the slave */
#define  I2C_EVENT_SLAVE_ADDRESS_RECEIVER_MATCHED          ((uint32_t)0x00020002) /* BUSY and ADDR flags */
#define  I2C_EVENT_SLAVE_ADDRESS_TRANSMITTER_MATCHED       ((uint32_t)0x00060082) /* TRA, BUSY, TXE and ADDR flags */

/* 2) Case of Dual address managed by the slave */
#define  I2C_EVENT_SLAVE_SECONDADDRESS_RECEIVER_MATCHED    ((uint32_t)0x00820000)  /* DUALF and BUSY flags */
#define  I2C_EVENT_SLAVE_SECONDADDRESS_TRANSMITTER_MATCHED ((uint32_t)0x00860080)  /* DUALF, TRA, BUSY and TXE flags */

/* 3) Case of General Call enabled for the slave */
#define  I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED        ((uint32_t)0x00120000)  /* GENCALL and BUSY flags */

/**
  * @brief  Communication events
  *
  * Wait on one of these events when EV1 has already been checked and:
  *
  * - Slave RECEIVER mode:
  *     - EV2: When the application is expecting a data byte to be received.
  *     - EV4: When the application is expecting the end of the communication: master
  *       sends a stop condition and data transmission is stopped.
  *
  * - Slave Transmitter mode:
  *    - EV3: When a byte has been transmitted by the slave and the application is expecting
  *      the end of the byte transmission. The two events I2C_EVENT_SLAVE_DATA_TRANSMITTED and
  *      I2C_EVENT_SLAVE_DATA_TRANSMITTING are similar. The second one can optionally be
  *      used when the user software doesn't guarantee the EV3 is managed before the
  *      current byte end of transfer.
  *    - EV3_2: When the master sends a NACK in order to tell slave that data transmission
  *      shall end (before sending the STOP condition). In this case slave has to stop sending
  *      data bytes and expect a Stop condition on the bus.
  *
  *  @note In case the  user software does not guarantee that the event EV2 is
  *  managed before the current byte end of transfer, then user may check on EV2
  *  and BTF flag at the same time (ie. (I2C_EVENT_SLAVE_DATA_RECEIVED | I2C_FLAG_BTFF)).
  * In this case the communication may be slower.
  *
  */

/* Slave RECEIVER mode --------------------------*/
/* --EV2 */
#define  I2C_EVENT_SLAVE_DATA_RECEIVED                     ((uint32_t)0x00020040)  /* BUSY and RXNE flags */
/* --EV4  */
#define  I2C_EVENT_SLAVE_STOP_DETECTED                     ((uint32_t)0x00000010)  /* STOPF flag */

/* Slave TRANSMITTER mode -----------------------*/
/* --EV3 */
#define  I2C_EVENT_SLAVE_DATA_TRANSMITTED                  ((uint32_t)0x00060084)  /* TRA, BUSY, TXE and BTF flags */
#define  I2C_EVENT_SLAVE_DATA_TRANSMITTING                 ((uint32_t)0x00060080)  /* TRA, BUSY and TXE flags */
/* --EV3_2 */
#define  I2C_EVENT_SLAVE_ACK_FAILURE_DETECTED              ((uint32_t)0x00000400)  /* AF flag */

/*===========================      End of Events Description           ==========================================*/

#define IS_I2C_EVENT(EVENT)     (((EVENT) == I2C_EVENT_SLAVE_ADDRESS_TRANSMITTER_MATCHED)           || \
                                 ((EVENT) == I2C_EVENT_SLAVE_ADDRESS_RECEIVER_MATCHED)              || \
                                 ((EVENT) == I2C_EVENT_SLAVE_SECONDADDRESS_TRANSMITTER_MATCHED)     || \
                                 ((EVENT) == I2C_EVENT_SLAVE_SECONDADDRESS_RECEIVER_MATCHED)        || \
                                 ((EVENT) == I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED)            || \
                                 ((EVENT) == I2C_EVENT_SLAVE_DATA_RECEIVED)                         || \
                                 ((EVENT) == (I2C_EVENT_SLAVE_DATA_RECEIVED | I2C_FLAG_DUALF))      || \
                                 ((EVENT) == (I2C_EVENT_SLAVE_DATA_RECEIVED | I2C_FLAG_GCADDRF))    || \
                                 ((EVENT) == I2C_EVENT_SLAVE_DATA_TRANSMITTED)                      || \
                                 ((EVENT) == (I2C_EVENT_SLAVE_DATA_TRANSMITTED | I2C_FLAG_DUALF))   || \
                                 ((EVENT) == (I2C_EVENT_SLAVE_DATA_TRANSMITTED | I2C_FLAG_GCADDRF)) || \
                                 ((EVENT) == I2C_EVENT_SLAVE_STOP_DETECTED)                         || \
                                 ((EVENT) == I2C_EVENT_MASTER_START_GENERATED)                      || \
                                 ((EVENT) == I2C_EVENT_MASTER_ADDRESS)                              || \
                                 ((EVENT) == I2C_EVENT_MASTER_TRANSMITTER)                          || \
                                 ((EVENT) == I2C_EVENT_MASTER_ADDRESS_WITH_RECEIVER)                || \
                                 ((EVENT) == I2C_EVENT_MASTER_DATA_RECEIVED)                        || \
                                 ((EVENT) == I2C_EVENT_MASTER_DATA_TRANSMITTED)                     || \
                                 ((EVENT) == I2C_EVENT_MASTER_DATA_TRANSMITTING)                    || \
                                 ((EVENT) == I2C_EVENT_MASTER_ADDRESS10_GENERATED)                  || \
                                 ((EVENT) == I2C_EVENT_SLAVE_ACK_FAILURE_DETECTED))
/**
  * @}
  */

/** @defgroup I2C_own_address1
  * @{
  */

#define IS_I2C_OWN_ADDRESS1(ADDRESS1)       ((ADDRESS1) <= 0x3FF)
/**
  * @}
  */

/** @defgroup I2C_clock_speed
  * @{
  */

#define IS_I2C_BIT_RATE(RATE)               (((RATE) >= 0x1) && ((RATE) <= 400000))
/**
  * @}
  */

/**
  * @}
  */

/** @defgroup I2C_Exported_Macros
  * @{
  */

/**
  * @}
  */

/** @defgroup I2C_Exported_Functions
  * @{
  */

void I2C_DeInit(I2C_Type* I2Cx);
void I2C_Init(I2C_Type* I2Cx, I2C_InitType* I2C_InitStruct);
void I2C_StructInit(I2C_InitType* I2C_InitStruct);
void I2C_Cmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_DMACmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_DMALastTransferCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_GenerateSTART(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_GenerateSTOP(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_AcknowledgeConfig(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_OwnAddress2Config(I2C_Type* I2Cx, uint8_t Address);
void I2C_DualAddressCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_GeneralCallCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_INTConfig(I2C_Type* I2Cx, uint16_t I2C_INT, FunctionalState NewState);
void I2C_SendData(I2C_Type* I2Cx, uint8_t Data);
uint8_t I2C_ReceiveData(I2C_Type* I2Cx);
void I2C_Send7bitAddress(I2C_Type* I2Cx, uint8_t Address, uint8_t I2C_Direction);
uint16_t I2C_ReadRegister(I2C_Type* I2Cx, uint8_t I2C_Register);
void I2C_SoftwareResetCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_NACKPositionConfig(I2C_Type* I2Cx, uint16_t I2C_NACKPosition);
void I2C_SMBusAlertConfig(I2C_Type* I2Cx, uint16_t I2C_SMBusAlert);
void I2C_TransmitPEC(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_PECPositionConfig(I2C_Type* I2Cx, uint16_t I2C_PECPosition);
void I2C_CalculatePEC(I2C_Type* I2Cx, FunctionalState NewState);
uint8_t I2C_GetPEC(I2C_Type* I2Cx);
void I2C_ARPCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_StretchClockCmd(I2C_Type* I2Cx, FunctionalState NewState);
void I2C_FastModeDutyCycleConfig(I2C_Type* I2Cx, uint16_t I2C_DutyCycle);

/**
 * @brief
 ****************************************************************************************
 *
 *                         I2C State Monitoring Functions
 *
 ****************************************************************************************
 * This I2C driver provides three different ways for I2C state monitoring
 *  depending on the application requirements and constraints:
 *
 *
 * 1) Basic state monitoring:
 *    Using I2C_CheckEvent() function:
 *    It compares the status registers (SR1 and SR2) content to a given event
 *    (can be the combination of one or more flags).
 *    It returns SUCCESS if the current status includes the given flags
 *    and returns ERROR if one or more flags are missing in the current status.
 *    - When to use:
 *      - This function is suitable for most applications as well as for startup
 *      activity since the events are fully described in the product reference manual
 *      (RM0008).
 *      - It is also suitable for users who need to define their own events.
 *    - Limitations:
 *      - If an error occurs (ie. error flags are set besides to the monitored flags),
 *        the I2C_CheckEvent() function may return SUCCESS despite the communication
 *        hold or corrupted real state.
 *        In this case, it is advised to use error interrupts to monitor the error
 *        events and handle them in the interrupt IRQ handler.
 *
 *        @note
 *        For error management, it is advised to use the following functions:
 *          - I2C_INTConfig() to configure and enable the error interrupts (I2C_INT_ERR).
 *          - I2Cx_ER_IRQHandler() which is called when the error interrupt occurs.
 *            Where x is the peripheral instance (I2C1, I2C2 ...)
 *          - I2C_GetFlagStatus() or I2C_GetINTStatus() to be called into I2Cx_ER_IRQHandler()
 *            in order to determine which error occurred.
 *          - I2C_ClearFlag() or I2C_ClearITPendingBit() and/or I2C_SoftwareResetCmd()
 *            and/or I2C_GenerateStop() in order to clear the error flag and source,
 *            and return to correct communication status.
 *
 *
 *  2) Advanced state monitoring:
 *     Using the function I2C_GetLastEvent() which returns the image of both status
 *     registers in a single word (uint32_t) (Status Register 2 value is shifted left
 *     by 16 bits and concatenated to Status Register 1).
 *     - When to use:
 *       - This function is suitable for the same applications above but it allows to
 *         overcome the limitations of I2C_GetFlagStatus() function (see below).
 *         The returned value could be compared to events already defined in the
 *         library (at32f4xx_i2c.h) or to custom values defined by user.
 *       - This function is suitable when multiple flags are monitored at the same time.
 *       - At the opposite of I2C_CheckEvent() function, this function allows user to
 *         choose when an event is accepted (when all events flags are set and no
 *         other flags are set or just when the needed flags are set like
 *         I2C_CheckEvent() function).
 *     - Limitations:
 *       - User may need to define his own events.
 *       - Same remark concerning the error management is applicable for this
 *         function if user decides to check only regular communication flags (and
 *         ignores error flags).
 *
 *
 *  3) Flag-based state monitoring:
 *     Using the function I2C_GetFlagStatus() which simply returns the status of
 *     one single flag (ie. I2C_FLAG_RDNE ...).
 *     - When to use:
 *        - This function could be used for specific applications or in debug phase.
 *        - It is suitable when only one flag checking is needed (most I2C events
 *          are monitored through multiple flags).
 *     - Limitations:
 *        - When calling this function, the Status register is accessed. Some flags are
 *          cleared when the status register is accessed. So checking the status
 *          of one Flag, may clear other ones.
 *        - Function may need to be called twice or more in order to monitor one
 *          single event.
 *
 */

/**
 *
 *  1) Basic state monitoring
 *******************************************************************************
 */
ErrorStatus I2C_CheckEvent(I2C_Type* I2Cx, uint32_t I2C_EVENT);
/**
 *
 *  2) Advanced state monitoring
 *******************************************************************************
 */
uint32_t I2C_GetLastEvent(I2C_Type* I2Cx);
/**
 *
 *  3) Flag-based state monitoring
 *******************************************************************************
 */
FlagStatus I2C_GetFlagStatus(I2C_Type* I2Cx, uint32_t I2C_FLAG);
/**
 *
 *******************************************************************************
 */

void I2C_ClearFlag(I2C_Type* I2Cx, uint32_t I2C_FLAG);
ITStatus I2C_GetINTStatus(I2C_Type* I2Cx, uint32_t I2C_INT);
void I2C_ClearITPendingBit(I2C_Type* I2Cx, uint32_t I2C_INT);

#ifdef __cplusplus
}
#endif

#endif /*__AT32F4xx_I2C_H */
/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */