text:
package io.netty.handler.codec.bytes;

import io.netty.buffer.ChannelBuffer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.MessageToMessageDecoder;

/**
 * Decodes a received {@link ChannelBuffer} into an array of bytes.
 * A typical setup for TCP/IP would be:
 *

 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder",
 *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
 * pipeline.addLast("bytesDecoder",
 *                  new {@link ByteArrayDecoder}());
 *
 * // Encoder
 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
 * pipeline.addLast("bytesEncoder", new {@link ByteArrayEncoder}());
 *

 * and then you can use an array of bytes instead of a {@link ChannelBuffer}
 * as a message:
 *

 * void messageReceived({@link ChannelHandlerContext} ctx, {@link MessageEvent} e) {
 *     byte[] bytes = (byte[]) e.getMessage();
 *     ...
 * }
 *

 */
public class ByteArrayDecoder extends MessageToMessageDecoder<ChannelBuffer, byte[]> {

    @Override
    public boolean isDecodable(Object msg) throws Exception {
        return msg instanceof ChannelBuffer;
    }

    @Override
    public byte[] decode(ChannelInboundHandlerContext<ChannelBuffer> ctx, ChannelBuffer msg) throws Exception {
        byte[] array;
        if (msg.hasArray()) {
            if (msg.arrayOffset() == 0 && msg.readableBytes() == msg.capacity()) {
                // we have no offset and the length is the same as the capacity. Its safe to reuse the array without copy it first
                array = msg.array();
            } else {
                // copy the ChannelBuffer to a byte array
                array = new byte[msg.readableBytes()];
                msg.getBytes(0, array);
            }
        } else {
            // copy the ChannelBuffer to a byte array
            array = new byte[msg.readableBytes()];
            msg.getBytes(0, array);
        }

        return array;
    }
}


text:
public class Counter {
    int count;

    public int getCount() { return count; }
    public void addToCount(int n) { count += n; }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ardverk.daap.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.ardverk.daap.DaapAudioResponse;
import org.ardverk.daap.DaapConfig;
import org.ardverk.daap.DaapRequest;
import org.ardverk.daap.DaapStreamException;
import org.ardverk.daap.Song;

/**
 * DaapAudioResponse.
 *
 * @author Roger Kapsi
 */
public class DaapAudioResponseNIO extends DaapAudioResponse {

    private ByteBuffer headerBuffer;
    private FileChannel fileChannel;
    private DaapConnectionNIO connection;

    public DaapAudioResponseNIO(DaapRequest request, Song song, File file,
            long pos, long end) throws IOException {
        this(request, song, new FileInputStream(file), pos, end);
    }

    /** Creates a new instance of DaapAudioResponse */
    public DaapAudioResponseNIO(DaapRequest request, Song song,
            FileInputStream in, long pos, long end) {
        super(request, song, in, pos, end);

        headerBuffer = ByteBuffer.wrap(header);
        this.connection = (DaapConnectionNIO) request.getConnection();

        fileChannel = in.getChannel();
    }

    public boolean hasRemaining() {
        if (headerBuffer.hasRemaining())
            return true;
        else
            return (pos < end);
    }

    public boolean write() throws IOException {

        if (headerBuffer.hasRemaining()) {

            try {

                connection.getWriteChannel().write(headerBuffer);

                if (headerBuffer.hasRemaining() == true) {
                    return false;
                }

            } catch (IOException err) {
                close();
                throw err;
            }
        }

        try {
            return stream();
        } catch (IOException err) {
            throw new DaapStreamException(err);
        }
    }

    private boolean stream() throws IOException {

        if (pos < end) {

            if (!connection.getWriteChannel().isOpen()) {
                close();
                return true;

            } else {

                // Stream...
                try {
                    DaapConfig config = request.getServer().getConfig();
                    pos += fileChannel.transferTo(pos, config.getBufferSize(),
                            connection.getWriteChannel());

                    if (pos >= end) {
                        close();
                        return true;
                    } else {
                        return false;
                    }

                } catch (IOException err) {
                    close();
                    throw err;
                }

            }

        } else {
            return true;
        }
    }

    protected void close() throws IOException {
        super.close();
        fileChannel.close();
    }
}


text:
from cloudmesh_base.base import HEADING
from cloudmesh_pbs.database import pbs_db, pbs_shelve
import os

class TestDatabase:

    filename = "pbs.db"

    def setup(self):
        # HEADING()
        self.db = pbs_db(self.filename, pbs_shelve)

    def teardown(self):
        # HEADING()
        pass

    """
    @classmethod
    def setup_class(cls):
        print ("setup_class() before any methods in this class")

    @classmethod
    def teardown_class(cls):
        print ("teardown_class() after any methods in this class")
     """
    def test_clear(self):
        HEADING()
        self.db.clear()
        assert not os.path.isfile(self.filename)

    def test_set(self):
        HEADING()
        self.db["element"] = "test"
        assert self.db['element'] == "test"


text:
from types import SimpleNamespace as NS

from .coord_cartesian import coord_cartesian

class coord_flip(coord_cartesian):
    """
    Flipped cartesian coordinates

    The horizontal becomes vertical, and vertical becomes
    horizontal. This is primarily useful for converting
    geoms and statistics which display y conditional
    on x, to x conditional on y.

    Parameters
    ----------
    xlim : None | (float, float)
        Limits for x axis. If None, then they are
        automatically computed.
    ylim : None | (float, float)
        Limits for y axis. If None, then they are
        automatically computed.
    expand : bool
        If `True`, expand the coordinate axes by
        some factor. If `False`, use the limits
        from the data.
    """

    def labels(self, label_lookup):
        return flip_labels(coord_cartesian.labels(
            self, label_lookup))

    def transform(self, data, panel_params, munch=False):
        data = flip_labels(data)
        return coord_cartesian.transform(self, data,
                                         panel_params,
                                         munch=munch)

    def setup_panel_params(self, scale_x, scale_y):
        panel_params = coord_cartesian.setup_panel_params(
            self, scale_x, scale_y)
        return flip_labels(panel_params)

    def setup_layout(self, layout):
        # switch the scales
        x, y = 'SCALE_X', 'SCALE_Y'
        layout[x], layout[y] = layout[y].copy(), layout[x].copy()
        return layout

    def range(self, panel_params):
        """
        Return the range along the dimensions of the coordinate system
        """
        # Defaults to providing the 2D x-y ranges
        return NS(x=panel_params.y.range,
                  y=panel_params.x.range)

def flip_labels(obj):
    """
    Rename fields x to y and y to x

    Parameters
    ----------
    obj : dict_like | types.SimpleNamespace
        Object with labels to rename
    """
    def sub(a, b):
        """
        Substitute all keys that start with a to b
        """
        for label in list(obj.keys()):
            if label.startswith(a):
                new_label = b+label[1:]
                obj[new_label] = obj.pop(label)

    if hasattr(obj, 'keys'):  # dict or dataframe
        sub('x', 'z')
        sub('y', 'x')
        sub('z', 'y')
    elif hasattr(obj, 'x') and hasattr(obj, 'y'):
        obj.x, obj.y = obj.y, obj.x

    return obj


text:
.arrangeable-files {
  padding: 10px 10px 0;
  border: 1px solid #e8e8e8;
  margin-bottom: 10px;
}

.arrangeable-files .default .header {
  margin-bottom: 4px;
}

.arrangeable-files .default .header button {
  font-size: 12px;
  text-transform: uppercase;
  background: #6ed2dd;
  color: #fff;
  border: 0 none;
  padding: 3px 15px;
}

.arrangeable-files .default .row {
  background: white;
}

.arrangeable-files .overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 20px;
  background: #F2FAFA;
  overflow: auto;
}

.arrangeable-files .overlay > button {
  margin-top: 20px;
  font-size: 12px;
  text-transform: uppercase;
  background: #6ed2dd;
  color: #fff;
  border: 0 none;
  padding: 6px 25px;
}


text:
package com.alibaba.druid.bvt.pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import junit.framework.TestCase;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Assert;

import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.pool.vendor.MockExceptionSorter;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import com.alibaba.druid.support.logging.Log4jImpl;
import com.alibaba.druid.support.logging.LogFactory;

public class AsyncCloseTest3 extends TestCase {

    protected DruidDataSource dataSource;
    private ExecutorService   connExecutor;
    private ExecutorService   closeExecutor;

    final AtomicInteger       errorCount = new AtomicInteger();

    private Logger            log;
    private Level             oldLevel;

    protected void setUp() throws Exception {
        log = ((Log4jImpl) LogFactory.getLog(DruidDataSource.class)).getLog();
        oldLevel = log.getLevel();
        log.setLevel(Level.FATAL);

        dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mock:");
//        dataSource.setAsyncCloseConnectionEnable(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setMaxActive(16);

        dataSource.getProxyFilters().add(new FilterAdapter() {

            @Override
            public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql)
                                                                                throws SQLException {
                throw new SQLException();
            }
        });

        dataSource.setExceptionSorter(new MyExceptionSorter());
        dataSource.init();

        connExecutor = Executors.newFixedThreadPool(2);
        closeExecutor = Executors.newFixedThreadPool(2);

    }

    protected void tearDown() throws Exception {
        dataSource.close();
        log.setLevel(oldLevel);
    }

    public void test_0() throws Exception {
        for (int i = 0; i < 16; ++i) {
            loop();
            System.out.println("loop " + i + " done.");
        }
    }

    public static class MyExceptionSorter extends MockExceptionSorter {

        @Override
        public boolean isExceptionFatal(SQLException e) {
            return true;
        }
    }

    class CloseTask implements Runnable {

        private Connection     conn;
        private CountDownLatch latch;

        public CloseTask(Connection conn, CountDownLatch latch){
            this.conn = conn;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                conn.close();
            } catch (SQLException e) {
                errorCount.incrementAndGet();
            } finally {
                latch.countDown();
            }
        }

    }

    protected void loop() throws InterruptedException {
        dataSource.shrink();
        Assert.assertEquals(0, dataSource.getActiveCount());
        Assert.assertEquals(0, dataSource.getPoolingCount());

        final int COUNT = 1024 * 128;
        final CountDownLatch closeLatch = new CountDownLatch(COUNT * 2);
        final CountDownLatch execLatch = new CountDownLatch(COUNT);

        Runnable connTask = new Runnable() {

            @Override
            public void run() {
                try {
                    DruidPooledConnection conn = dataSource.getConnection();
                    Statement stmt = conn.createStatement();

                    CloseTask closeTask = new CloseTask(conn, closeLatch);

                    closeExecutor.submit(closeTask);
                    closeExecutor.submit(closeTask); // dup close

                    try {
                        stmt.execute("select 1");
                    } finally {
                        stmt.close();
                        conn.close();
                    }
                } catch (SQLException e) {
                    errorCount.incrementAndGet();
                } finally {
                    execLatch.countDown();
                }
            }
        };

        for (int i = 0; i < COUNT; ++i) {
            connExecutor.submit(connTask);
        }

        execLatch.await();
        closeLatch.await();
        Assert.assertEquals(0, dataSource.getActiveCount());
    }
}


text:
from watcher._i18n import _
from watcher.decision_engine.strategy.strategies import base

class Actuator(base.UnclassifiedStrategy):
    """Actuator

    Actuator that simply executes the actions given as parameter

    This strategy allows anyone to create an action plan with a predefined
    set of actions. This strategy can be used for 2 different purposes:

    - Test actions
    - Use this strategy based on an event trigger to perform some explicit task

    """

    @classmethod
    def get_name(cls):
        return "actuator"

    @classmethod
    def get_display_name(cls):
        return _("Actuator")

    @classmethod
    def get_translatable_display_name(cls):
        return "Actuator"

    @classmethod
    def get_schema(cls):
        # Mandatory default setting for each element
        return {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
                "actions": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "action_type": {
                                "type": "string"
                            },
                            "resource_id": {
                                "type": "string"
                            },
                            "input_parameters": {
                                "type": "object",
                                "properties": {},
                                "additionalProperties": True
                            }
                        },
                        "required": [
                            "action_type", "input_parameters"
                        ],
                        "additionalProperties": True,
                    }
                }
            },
            "required": [
                "actions"
            ]
        }

    @classmethod
    def get_config_opts(cls):
        """Override base class config options as do not use datasource """

        return []

    @property
    def actions(self):
        return self.input_parameters.get('actions', [])

    def pre_execute(self):
        self._pre_execute()

    def do_execute(self, audit=None):
        for action in self.actions:
            self.solution.add_action(**action)

    def post_execute(self):
        pass


text:
package fr.openwide.core.showcase.web.application.navigation.link;

import org.apache.wicket.model.IModel;

import fr.openwide.core.showcase.core.business.user.model.User;
import fr.openwide.core.showcase.web.application.navigation.model.TestIconResourceReferenceModel;
import fr.openwide.core.wicket.more.link.descriptor.IImageResourceLinkDescriptor;
import fr.openwide.core.wicket.more.link.descriptor.builder.LinkDescriptorBuilder;
import fr.openwide.core.wicket.more.link.factory.AbstractLinkFactory;

public final class LinkFactory extends AbstractLinkFactory {

	private static final LinkFactory INSTANCE = new LinkFactory();

	private LinkFactory() { }

	public static LinkFactory get() {
		return INSTANCE;
	}

	/**
	 * Juste un bricolage pour tester le IImageResourceLinkDescriptor.
	 */
	public IImageResourceLinkDescriptor testImage(final IModel<Boolean> booleanModel, IModel<User> userModel) {
		return LinkDescriptorBuilder.start()
				.map("unusedUserParameter", userModel, User.class).mandatory()
				.imageResource(new TestIconResourceReferenceModel(booleanModel));
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

  <title>Substring matching attribute selector (end)</title>

  <link rel="first" href="css3-modsel-1.html" title="Groups of selectors">
  <link rel="prev" href="css3-modsel-9.html" title="Substring matching attribute selector (beginning)">
  <link rel="next" href="css3-modsel-11.html" title="Substring matching attribute selector (contains)">
  <link rel="last" href="css3-modsel-d5e.html" title="NEGATED :indeterminate with :checked">
  <link rel="up" href="./index.html">
  <link rel="top" href="../../index.html">

This paragraph should have a green background because
its title attribute ends with "bar"


text:
#if defined(_WIN32)
#define __WIN32__
#endif

#include <erl_driver.h>
#include <erl_interface.h>
#include <string.h>
#include <dns_sd.h>

#define DNSSD_CMD_ENUM		0
#define DNSSD_CMD_BROWSE	1
#define DNSSD_CMD_RESOLVE	2
#define DNSSD_CMD_REGISTER	3
#define DNSSD_CMD_QUERY_RECORD	4

typedef struct _dnssd_drv_t {
  DNSServiceRef sd_ref;
  ErlDrvPort erl_port;
  ErlDrvTermData term_port;
  ErlDrvTermData term_ok;
  ErlDrvTermData term_error;
  ErlDrvTermData term_enumerate;
  ErlDrvTermData term_browse;
  ErlDrvTermData term_resolve;
  ErlDrvTermData term_register;
  ErlDrvTermData term_query_record;
#ifdef __WIN32__
  WSAEVENT event;
#endif
} dnssd_drv_t;

/* Driver Callbacks */
static ErlDrvData start(ErlDrvPort port, char* cmd);
static void stop(ErlDrvData handle);
static ErlDrvSSizeT call(ErlDrvData drv_data,
			 unsigned int command,
			 char *buf,
			 ErlDrvSizeT len,
			 char **rbuf,
			 ErlDrvSizeT rlen,
			 unsigned int *flags);
static void ready_io(ErlDrvData handle, ErlDrvEvent ev);
static void send_error(ErlDrvData edd, DNSServiceErrorType err);

/* DNSSD API Callbacks */
static void DNSSD_API EnumReply(DNSServiceRef sd_ref,
				DNSServiceFlags flags,
				uint32_t ifIndex,
				DNSServiceErrorType err,
				const char * domain,
				void * context);

static void DNSSD_API BrowseReply(DNSServiceRef sd_ref,
				  DNSServiceFlags flags,
				  uint32_t ifIndex,
				  DNSServiceErrorType err,
				  const char * name,
				  const char * regtype,
				  const char * domain,
				  void * context);

static void DNSSD_API ResolveReply(DNSServiceRef sd_ref,
				   DNSServiceFlags flags,
				   uint32_t ifIndex,
				   DNSServiceErrorType err,
				   const char * fullname,
				   const char * hosttarget,
				   uint16_t port,
				   uint16_t txtLen,
				   const unsigned char * txtRecord,
				   void * context);

static void DNSSD_API RegisterReply (DNSServiceRef sd_ref,
				     DNSServiceFlags flags,
				     DNSServiceErrorType err,
				     const char * name,
				     const char * regtype,
				     const char * domain,
				     void * context);

static void DNSSD_API QueryRecordReply(DNSServiceRef sdRef,
				       DNSServiceFlags flags,
				       uint32_t interfaceIndex,
				       DNSServiceErrorType err,
				       const char *fullname,
				       uint16_t rrtype,
				       uint16_t rrclass,
				       uint16_t rdlen,
				       const void *rdata,
				       uint32_t ttl,
				       void *context);

static ErlDrvEntry dnssd_driver_entry = {
    NULL,                             /* init */
    start,                            /* startup */
    stop,                             /* shutdown */
    NULL,                             /* output */
    ready_io,                         /* ready_input */
    ready_io,                         /* ready_output */
    "dnssd_drv",                      /* the name of the driver */
    NULL,                             /* finish */
    NULL,                             /* handle */
    NULL,                             /* control */
    NULL,                             /* timeout */
    NULL,                             /* process */
    NULL,                             /* ready_async */
    NULL,                             /* flush */
    call,                             /* call */
    NULL,                             /* event */
    ERL_DRV_EXTENDED_MARKER,          /* ERL_DRV_EXTENDED_MARKER */
    ERL_DRV_EXTENDED_MAJOR_VERSION,   /* ERL_DRV_EXTENDED_MAJOR_VERSION */
    ERL_DRV_EXTENDED_MINOR_VERSION,   /* ERL_DRV_EXTENDED_MINOR_VERSION */
    0,                                /* ERL_DRV_FLAGs */
    NULL,
    NULL
};

DRIVER_INIT(dnssd_driver) {
  return &dnssd_driver_entry;
}

static ErlDrvData start(ErlDrvPort port, char* cmd) {
  dnssd_drv_t* retval = (dnssd_drv_t*) driver_alloc(sizeof(dnssd_drv_t));
  retval->sd_ref = NULL;
  retval->erl_port = port;
  retval->term_port = driver_mk_port(port);
  retval->term_ok = driver_mk_atom("ok");
  retval->term_error = driver_mk_atom("error");
  retval->term_enumerate = driver_mk_atom("enumerate");
  retval->term_browse = driver_mk_atom("browse");
  retval->term_resolve = driver_mk_atom("resolve");
  retval->term_register = driver_mk_atom("register");
  retval->term_query_record = driver_mk_atom("query_record");
  return (ErlDrvData) retval;
}

static void stop(ErlDrvData edd) {
  dnssd_drv_t* dd = (dnssd_drv_t*) edd;
#ifdef __WIN32__
  if (dd->event) {
    driver_select(dd->erl_port, dd->event, DO_READ, 0);
    WSAEventSelect(DNSServiceRefSockFD(dd->sd_ref), NULL, 0);
  }
  if (dd->sd_ref) {
    DNSServiceRefDeallocate(dd->sd_ref);
  }
#else
  if (dd->sd_ref) {
    driver_select(dd->erl_port,
		  (ErlDrvEvent)(size_t) DNSServiceRefSockFD(dd->sd_ref),
		  DO_READ,
		  0);
    DNSServiceRefDeallocate(dd->sd_ref);
  }
#endif
  driver_free(dd);
}

static ErlDrvSSizeT call(ErlDrvData edd, unsigned int cmd, char *buf,
			 ErlDrvSizeT len, char **rbuf, ErlDrvSizeT rlen,
			 unsigned int *flags) {
  dnssd_drv_t* dd = (dnssd_drv_t*) edd;
  int version, out_len, index, rindex, local_only;
  DNSServiceErrorType err;
  char* out_atom_text;
  ei_term arg, name, type, domain, txt, host, hostport;
  char *name_tmp, *type_tmp, *domain_tmp, *txt_tmp, *host_tmp;

  /* don't allow reuse */
  if (dd->sd_ref) return -1;

  index = 0;
  dd->sd_ref = NULL;

  ei_decode_version(buf, &index, &version);
  ei_decode_ei_term(buf, &index, &arg);

  if (cmd == DNSSD_CMD_ENUM)  {
    if (arg.ei_type == ERL_ATOM_EXT) {
      if (strncmp(arg.value.atom_name, "browse", 6) == 0) {
	// init for enum browse
	err = DNSServiceEnumerateDomains(&dd->sd_ref,
					 kDNSServiceFlagsBrowseDomains,
					 kDNSServiceInterfaceIndexAny,
					 (DNSServiceDomainEnumReply) EnumReply,
					 dd);
      } else if (strncmp(arg.value.atom_name,"reg", 3) == 0) {
	// init for enum reg
	err = DNSServiceEnumerateDomains(&dd->sd_ref,
					 kDNSServiceFlagsRegistrationDomains,
					 kDNSServiceInterfaceIndexAny,
					 (DNSServiceDomainEnumReply) EnumReply,
					 dd);
      } else {
	goto badarg;
      }
    } else {
      goto badarg;
    }
  } else if (cmd == DNSSD_CMD_BROWSE) {
    if (arg.ei_type != ERL_SMALL_TUPLE_EXT || arg.arity != 2) goto badarg;
    /* decode type */
    ei_decode_ei_term(buf, &index, &type);
    if (type.ei_type != ERL_BINARY_EXT) goto badarg;
    index += 5; // skip tag + 4 byte size
    type_tmp = (char*)driver_alloc(type.size + 1);
    memset(type_tmp, 0, type.size + 1);
    memcpy(type_tmp, buf + index, type.size);
    index += type.size;
    /* decode domain */
    ei_decode_ei_term(buf, &index, &domain);
    if (domain.ei_type != ERL_BINARY_EXT) {
      driver_free(type_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    domain_tmp = (char *) driver_alloc(domain.size + 1);
    memset(domain_tmp, 0, domain.size + 1);
    memcpy(domain_tmp, buf + index, domain.size);
    err = DNSServiceBrowse(&dd->sd_ref,
			   0, // Flags
			   kDNSServiceInterfaceIndexAny,
			   type_tmp,
			   domain_tmp,
			   (DNSServiceBrowseReply) BrowseReply,
			   dd);
    driver_free(type_tmp);
    driver_free(domain_tmp);
  } else if (cmd == DNSSD_CMD_RESOLVE) {
    if (arg.ei_type != ERL_SMALL_TUPLE_EXT || arg.arity != 3) goto badarg;
    /* decode name */
    ei_decode_ei_term(buf, &index, &name);
    if (name.ei_type != ERL_BINARY_EXT) goto badarg;
    index += 5; // skip tag + 4 byte size
    name_tmp = (char *) driver_alloc(name.size + 1);
    memset(name_tmp, 0, name.size + 1);
    memcpy(name_tmp, buf + index, name.size);
    index += name.size;
    /* decode type */
    ei_decode_ei_term(buf, &index, &type);
    if (type.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    type_tmp = (char *) driver_alloc(type.size + 1);
    memset(type_tmp, 0, type.size + 1);
    memcpy(type_tmp, buf + index, type.size);
    index += type.size;
    /* decode domain */
    ei_decode_ei_term(buf, &index, &domain);
    if (domain.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      driver_free(type_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    domain_tmp = (char *) driver_alloc(domain.size + 1);
    memset(domain_tmp, 0, domain.size + 1);
    memcpy(domain_tmp, buf + index, domain.size);
    /* start op */
    err = DNSServiceResolve(&dd->sd_ref,
			    0, // Flags
			    kDNSServiceInterfaceIndexAny,
			    name_tmp,
			    type_tmp,
			    domain_tmp,
			    (DNSServiceResolveReply) ResolveReply,
			    dd);
    driver_free(name_tmp);
    driver_free(type_tmp);
    driver_free(domain_tmp);
  } else if (cmd == DNSSD_CMD_REGISTER) {
    if (arg.ei_type != ERL_SMALL_TUPLE_EXT || arg.arity != 6) goto badarg;
    /* decode name */
    ei_decode_ei_term(buf, &index, &name);
    if (name.ei_type != ERL_BINARY_EXT) goto badarg;
    index += 5; // skip tag + 4 byte size
    name_tmp = (char *) driver_alloc(name.size + 1);
    memset(name_tmp, 0, name.size + 1);
    memcpy(name_tmp, buf + index, name.size);
    index += name.size;
    /* decode type */
    ei_decode_ei_term(buf, &index, &type);
    if (type.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    type_tmp = (char *) driver_alloc(type.size + 1);
    memset(type_tmp, 0, type.size + 1);
    memcpy(type_tmp, buf + index, type.size);
    index += type.size;
    /* decode domain */
    ei_decode_ei_term(buf, &index, &domain);
    if (domain.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      driver_free(type_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    domain_tmp = (char *) driver_alloc(domain.size + 1);
    memset(domain_tmp, 0, domain.size + 1);
    memcpy(domain_tmp, buf + index, domain.size);
    index += domain.size;
    /* decode host */
    ei_decode_ei_term(buf, &index, &host);
    if (host.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      driver_free(type_tmp);
      driver_free(domain_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    host_tmp = (char *) driver_alloc(host.size + 1);
    memset(host_tmp, 0, host.size + 1);
    memcpy(host_tmp, buf + index, host.size);
    index += host.size;
    /* decode port */
    ei_decode_ei_term(buf, &index, &hostport);
    if (hostport.ei_type != ERL_INTEGER_EXT &&
	hostport.ei_type != ERL_SMALL_INTEGER_EXT) {
      driver_free(name_tmp);
      driver_free(type_tmp);
      driver_free(domain_tmp);
      driver_free(host_tmp);
      goto badarg;
    }
    /* decode txt */
    ei_decode_ei_term(buf, &index, &txt);
    if (txt.ei_type != ERL_BINARY_EXT) {
      driver_free(name_tmp);
      driver_free(type_tmp);
      driver_free(domain_tmp);
      driver_free(host_tmp);
      goto badarg;
    }
    index += 5; // skip tag + 4 byte size
    txt_tmp = (char *) driver_alloc(txt.size + 1);
    memset(txt_tmp, 0, txt.size + 1);
    memcpy(txt_tmp, buf + index, txt.size);
    local_only = (0 == strcmp("localhost", host_tmp));
    err = DNSServiceRegister(&dd->sd_ref,
			     0, // Flags
			     local_only ? -1 : 0, // Interface: local / any
			     name_tmp,
			     type_tmp,
			     local_only ? "local" : domain_tmp,
			     host_tmp,
			     htons(hostport.value.i_val),
			     txt.size,
			     txt_tmp,
			     (DNSServiceRegisterReply) RegisterReply,
			     dd);
    driver_free(name_tmp);
    driver_free(type_tmp);
    driver_free(domain_tmp);
    driver_free(host_tmp);
    driver_free(txt_tmp);
  } else if (cmd == DNSSD_CMD_QUERY_RECORD) {
    if (arg.ei_type != ERL_SMALL_TUPLE_EXT || arg.arity != 2) goto badarg;
    /* decode domain */
    ei_decode_ei_term(buf, &index, &domain);
    if (domain.ei_type != ERL_BINARY_EXT) goto badarg;
    index += 5; // skip tag + 4 byte size
    domain_tmp = (char *) driver_alloc(domain.size + 1);
    memset(domain_tmp, 0, domain.size + 1);
    memcpy(domain_tmp, buf + index, domain.size);
    index += domain.size;
    /* decode rtype */
    ei_decode_ei_term(buf, &index, &type);
    if (type.ei_type != ERL_SMALL_INTEGER_EXT) {
      driver_free(domain_tmp);
      goto badarg;
    }
    err = DNSServiceQueryRecord(&dd->sd_ref,
			        0, // Flags
			        kDNSServiceInterfaceIndexAny,
			        domain_tmp,
			        (uint16_t) type.value.i_val,
			        kDNSServiceClass_IN,
			        (DNSServiceQueryRecordReply) QueryRecordReply,
			        dd);
    driver_free(domain_tmp);
  } else {
    goto badarg;
  }
  rindex = 0;
  out_len = 0;
  ei_encode_version(NULL, &out_len);
  if (err == kDNSServiceErr_NoError) {
#ifdef __WIN32__
    dd->event = WSACreateEvent();
    WSAEventSelect(DNSServiceRefSockFD(dd->sd_ref), dd->event, FD_READ);
    driver_select(dd->erl_port, dd->event, ERL_DRV_READ, 1);
#else
    driver_select(dd->erl_port,
		  (ErlDrvEvent)(size_t) DNSServiceRefSockFD(dd->sd_ref),
		  ERL_DRV_READ,
		  1);
#endif
    out_atom_text = "ok";
    ei_encode_atom(NULL, &out_len, out_atom_text);
    if(rlen < out_len) {
      *rbuf = driver_alloc(out_len);
      rlen = out_len;
    }
    ei_encode_version(*rbuf, &rindex);
    ei_encode_atom(*rbuf, &rindex, out_atom_text);
    return out_len;
  } else {
    out_atom_text = "error";
    ei_encode_tuple_header(NULL, &out_len, 2);
    ei_encode_atom(NULL, &out_len, out_atom_text);
    ei_encode_long(NULL, &out_len, 1337);
    if(rlen < out_len) {
      *rbuf = driver_alloc(out_len);
      rlen = out_len;
    }
    ei_encode_version(*rbuf, &rindex);
    ei_encode_tuple_header(*rbuf, &rindex, 2);
    ei_encode_atom(*rbuf, &rindex, out_atom_text);
    ei_encode_long(*rbuf, &rindex, (long) err);
    return out_len;
  }
 badarg:
  return -1;
}

static void ready_io(ErlDrvData edd, ErlDrvEvent ev)
{
  dnssd_drv_t* dd = (dnssd_drv_t*) edd;
  DNSServiceErrorType err;
#ifdef __WIN32__
  WSAResetEvent(dd->event);
#endif
  err = DNSServiceProcessResult(dd->sd_ref);
  if (err != kDNSServiceErr_NoError) {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_error,
			     ERL_DRV_INT, err,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

static void DNSSD_API EnumReply(DNSServiceRef sd_ref,
				DNSServiceFlags flags,
				uint32_t ifIndex,
				DNSServiceErrorType err,
				const char * domain,
				void * context)
{
  dnssd_drv_t* dd = (dnssd_drv_t*) context;
  if (err != kDNSServiceErr_NoError) {
    send_error(context, err);
  } else {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_enumerate,
			     ERL_DRV_INT, flags,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) domain, strlen(domain),
			     ERL_DRV_TUPLE, 2,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

static void DNSSD_API BrowseReply(DNSServiceRef sd_ref,
				  DNSServiceFlags flags,
				  uint32_t ifIndex,
				  DNSServiceErrorType err,
				  const char * name,
				  const char * regtype,
				  const char * domain,
				  void * context
				  )
{
  dnssd_drv_t* dd = (dnssd_drv_t*) context;
  if (err != kDNSServiceErr_NoError) {
    send_error(context, err);
  } else {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_browse,
			     ERL_DRV_INT, flags,
			     ERL_DRV_INT, ifIndex,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) name, strlen(name),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) regtype, strlen(regtype),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) domain, strlen(domain),
			     ERL_DRV_TUPLE, 5,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

static void DNSSD_API ResolveReply(DNSServiceRef sd_ref,
				   DNSServiceFlags flags,
				   uint32_t ifIndex,
				   DNSServiceErrorType err,
				   const char * fullname,
				   const char * hosttarget,
				   uint16_t port,
				   uint16_t txtLen,
				   const unsigned char * txtRecord,
				   void * context)
{
  dnssd_drv_t* dd = (dnssd_drv_t*) context;
  if (err != kDNSServiceErr_NoError) {
    send_error(context, err);
  } else {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_resolve,
			     ERL_DRV_INT, flags,
			     ERL_DRV_INT, ifIndex,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) fullname, strlen(fullname),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) hosttarget, strlen(hosttarget),
			     ERL_DRV_INT, ntohs(port),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) txtRecord, txtLen,
			     ERL_DRV_TUPLE, 6,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

static void DNSSD_API RegisterReply (DNSServiceRef sd_ref,
				     DNSServiceFlags flags,
				     DNSServiceErrorType err,
				     const char * name,
				     const char * regtype,
				     const char * domain,
				     void * context)
{
  dnssd_drv_t* dd = (dnssd_drv_t*) context;
  if (err != kDNSServiceErr_NoError) {
    send_error(context, err);
  } else {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_register,
			     ERL_DRV_INT, flags,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) name, strlen(name),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) regtype, strlen(regtype),
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) domain, strlen(domain),
			     ERL_DRV_TUPLE, 4,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

static void DNSSD_API QueryRecordReply(DNSServiceRef sdRef,
				       DNSServiceFlags flags,
				       uint32_t ifIndex,
				       DNSServiceErrorType err,
				       const char *fullname,
				       uint16_t rrtype,
				       uint16_t rrclass,
				       uint16_t rdlen,
				       const void *rdata,
				       uint32_t ttl,
				       void *context)
{
  dnssd_drv_t* dd = (dnssd_drv_t*) context;
  if (err != kDNSServiceErr_NoError) {
    send_error(context, err);
  } else {
    ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			     ERL_DRV_ATOM, dd->term_query_record,
			     ERL_DRV_INT, flags,
			     ERL_DRV_INT, ifIndex,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) fullname, strlen(fullname),
			     ERL_DRV_UINT, (uint32_t) rrtype,
			     ERL_DRV_UINT, (uint32_t) rrclass,
			     ERL_DRV_BUF2BINARY, (ErlDrvTermData) rdata, rdlen,
			     ERL_DRV_TUPLE, 6,
			     ERL_DRV_TUPLE, 3};
    erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
  }
}

void send_error(ErlDrvData edd, DNSServiceErrorType err) {
  dnssd_drv_t* dd = (dnssd_drv_t*) edd;
  ErlDrvTermData spec[] = {ERL_DRV_PORT, dd->term_port,
			   ERL_DRV_ATOM, dd->term_error,
			   ERL_DRV_INT, (ErlDrvTermData) errno,
			   ERL_DRV_TUPLE, 3};
  erl_drv_output_term(driver_mk_port(dd->erl_port), spec, sizeof(spec) / sizeof(spec[0]));
}


text:
requirejs.config({
    baseUrl: 'lib',
    paths: {
        scripts: '../scripts'
    }
});

// The mm core namespace
var $mm = $mm || {};

define([],    // place holder. no dependencies yet.
function () {
  var remote = $mm.remote  = $mm.remote || {};

  // ==========================================================================================================================================
  // WebSocket remote
  // ==========================================================================================================================================
  remote.websocket = function websocket(props) {
    this.events = ['close', 'open', 'message', 'error'];
    this.readystates = {
      0: 'CONNECTING',
      1: 'OPEN',
      2: 'CLOSING',
      3: 'CLOSED'
    };

    var self = this;
    props = props || {};

    // If the caller has not defined a WS URL, then try to sniff one out
    if(props.remoteUrl==null) {
      if(document!=null) {
        this.remoteUrl = props.remoteUrl || 'ws://' + document.location.host + '/ws';
      } else if (self != null && self.location != null ) {
        this.remoteUrl = props.remoteUrl || 'ws://' + self.location.host + '/ws';
      } else {
        throw new Error("Failed to autolocate WebSocket URL. No document, no worker global scope. Please specify 'remoteUrl' in passed props");
      }
    } else {
      this.remoteUrl = props.remoteUrl;
    }

    this.clientid = props.clientid;
    this.onsession = props.onsession;

    console.info("Requested Session (self): c: %s, fx: %s", self.clientid, self.onsession);

    // ======================================
    // Define event handler arrays
    // ======================================
    this.onclose = []; if(props.onclose!=null) this.onclose.push([].concat(props.onclose));
    this.onopen = []; if(props.onopen!=null) this.onopen.push([].concat(props.onopen));
    this.onerror = []; if(props.onerror!=null) this.onerror.push([].concat(props.onerror));
    this.onmessage = []; if(props.onmessage!=null) this.onmessage.push([].concat(props.onmessage));

    // ======================================
    // Create the websocket
    // ======================================
    this.ws = new WebSocket(this.remoteUrl);

    // ======================================
    // Attach the defined event listeners
    // ======================================
    this.ws.onclose = function(evt) {
      console.info("ws closed");
      delete self.sessionid;
      for(index in self.onclose) {
	      self.onclose[index](evt, self);
      }
    }
    this.ws.onerror = function(evt) {
      console.error("ws error:", evt);
      for(index in self.onerror) {
	      self.onerror[index](evt, self);
      }
    }
    this.ws.onopen = function(evt) {
      console.info("ws open");
      for(index in self.onopen) {
	      self.onopen[index](evt, self);
      }
    }
    this.ws.onmessage = function(evt) {
      console.info("ws message: [%s]", evt.data);
      var parsed = JSON.parse(evt.data);
      if(self.sessionid==null) {
        try {
          if(parsed.sessionid) {
            var SESSIONID = parseInt(parsed.sessionid);
            self.onsession(self.clientid, SESSIONID);
            self.sessionid = SESSIONID;
          }
        } catch (e) {}
      }
      var response = {
        sessionid: self.sessionid,
        data: parsed
      }
      for(index in self.onmessage) {
	      self.onmessage[index](response, self);
      }
    }

    // ======================================
    // Add new event listeners
    // ======================================
    this.addListener = function(event, listener) {
      if(event != null && listener != null) {
        if(self.events.indexOf(event)==-1) throw new Error("Invalid event type: [" + event + "]. Valid events are: [" + this.events.join(", ") + "]");
        var listeners = [].concat(listener);
        for(index in listeners) {
          if(listeners[index] != null && listeners[index] instanceof Function) {
            this[event] = listeners[index];
          }
        }
      }
    }

    // ======================================
    // Remove registered event listeners
    // ======================================
    this.removeListener = function(event, listener) {
      if(event != null && listener != null) {
        if(self.events.indexOf(event)==-1) throw new Error("Invalid event type: [" + event + "]. Valid events are: [" + this.events.join(", ") + "]");
        var listeners = [].concat(listener);
        for(index in listeners) {
          var idx = this[event].indexOf(listeners[index]);
          if(idx > -1) {
            this[event].splice(idx, 1);
          }
        }
      }
    }

    // ======================================
    // Other ops
    // ======================================
    this.send = function(msg) {
      this.ws.send(msg);
    }

    this.close = function() {
      this.ws.close();
    }

    this.state = function() {
      return this.ws.readyState;
    }

    this.toString = function() {
      return "[remote:websocket]:" + this.remoteUrl + "  [" + readystates[this.ws.readyState] + "]";
    }

  }

  $mm.remote.remotes = [];

  for(var p in $mm.remote) {
    if($mm.remote[p] instanceof Function) {
      $mm.remote.remotes.push($mm.remote[p].name);
    }
  }

  console.info("Available Remotes: [%s]", $mm.remote.remotes.join(", "));

});


text:
layout: projects
title: Projects
permalink: /projects/
---

Nothing here yet


text:
using Microsoft.AspNetCore.Mvc.ApplicationModels;

namespace ApplicationModelWebSite;

public class ApplicationDescription : IApplicationModelConvention
{
    private readonly string _description;

    public ApplicationDescription(string description)
    {
        _description = description;
    }

    public void Apply(ApplicationModel application)
    {
        application.Properties["description"] = _description;
    }
}


text:
layout: updates/post
title: "DevTools Digest: Aggregated Timeline Details, Color Palettes and More"
published_on: 2015-08-24
updated_on: 2015-08-24
authors:
  - pbakaus
tags:
  - devtools
  - digest
  - update
description: "Find out which third-party scripts cause perf issues with the Aggregated Details in Timeline, how to choose consistent colors with the new color palette and much more."
featured_image: /web/updates/images/2015-08-24-devtools-digest/featured.jpg
---

It's been a feature-rich month in Chrome Canary. Read on to learn which third party
scripts cause perf issues on your site with the
[Aggregated Details in Timeline](#heading=h.ygoxqwis9ean), how to choose
consistent colors with the [new color palette](#heading=h.pty4fqjm0wri), how to
simulate conference WiFi with [customizable network
profiles](#heading=h.jlf8cle6q2eq) and how to get more out of the DevTools UI
with the [new main menu](#heading=h.i5v8nj67xss6) and [better
tooltips](#heading=h.mtnvakflivsg).

- - -

## Better blame perf issues: Aggregated details in Timeline

![Aggregated Details in Timeline](/web/updates/images/2015-08-24-devtools-digest/aggregated_details.png)

On today's websites we are using more and more beacons, analytics, social,
font-loading and advertising services from third parties, sometimes a [few too
many](https://www.youtube.com/watch?v=TBIM9zPuL-k). To ensure this doesn't
happen and to give you visibility into the problem, we are introducing
aggregated details to the Timeline.

In the **Aggregated Details** tab, you can focus on just costly functions or the
entire call tree, then break down the selected data by domain, sub-domain or
distinct URLs. For example, in the above Timeline of a page load, you can now
attribute slow-downs easily to third party scripts coming from domains such as
facebook.net or twitter.com.

## New, dedicated main menu

<img src="/web/updates/images/2015-08-24-devtools-digest/new_main_menu.png" alt="New main menu" style="float: left;max-width: 230px;margin-right: 1em;margin-bottom: 1em;width: 40%;">To unclutter the main toolbar, we've moved drawer, settings and docking icons
into a new, dedicated main menu.

In particular docking got much simpler. Instead of having to long-press on the
previous icon, each docking position features it's own icon.

In addition to docking, we've added quick access file search, shortcuts and help
(which leads to [our new
homepage](/web/tools/chrome-devtools/)).

## Discover DevTools through improved tooltips

![New Tooltips](/web/updates/images/2015-08-24-devtools-digest/tooltips.png)

We've got lots of buttons in DevTools, and we know that not all of them are
self-explaining. We've now made discovering actions and their shortcuts easier
by replacing the system-native tooltips with custom, platform-consistent
tooltips.

The new tooltips appears much more quickly and includes keyboard shortcuts (if
there is one).

## Create custom network throttling profiles

![Custom Network Profiles](/web/updates/images/2015-08-24-devtools-digest/network_throttling_profiles.png)

If the default options for the Network Throttler are too limiting for your use
cases, and you need a "Conference WiFi" option or, for the sake of nostalgia,
want to go old school and emulate a ["110 Baud" line](https://en.wikipedia.org/wiki/Bell_101),
I have good news for you. We've added a new Settings panel that allows you to
do any of those things.

## Automatic, Material and custom color palettes

{% animation /web/updates/images/2015-08-24-devtools-digest/color_palettes.mp4 %}

Whether you want to recreate [the colors of
magic](http://www.colourlovers.com/blog/2008/04/19/octarine-the-imaginary-color-of-magic)
or work with an [existing color
palette](https://www.google.com/design/spec/style/color.html), the improved
Colorpicker helps you to pick a consistent color palette for your site.

By clicking on the little switcher icon next to the palette, you can choose from
the following:

1. **Page Colors** — This palette is auto-generated from the colors we find
   in your CSS, making it a great option if you're extending an existing site.
1. **Material Design** — The [Material Design
   palette](https://www.google.com/design/spec/style/color.html) offers
   beautiful colors out of the box and is an ideal choice when starting a
   new project. Right now you'll find all of the primary colors but we're
   bringing all shades to it soon.
1. **Custom** — That's your own playground. Add new colors by picking one
   in the picker, then click the "plus" icon next to the palette. Reorder by dragging
   them around and right-click to reveal more options, such as remove.

[Tell us what you
think](https://twitter.com/intent/tweet?text=%40ChromeDevTools), and how we
could extend the color story further.

## The best of the rest

* Requests made using the **fetch() API** are now shown in the Network Panel
* **Automatic panel layouting** ensures that when you resize your DevTools
  panels adapt to the new space constraints.
* **Inspect Element & Device Mode** has a set of new icons.
* **Attributes in the DOM panel** are now differently colored even when the node
  is highlighted. (They where all white before.)
* **Hidden elements** (activated by pressing "h" on a selected DOM node) now show
  a grey circle indicator on the left, and **DOM breakpoints** do the same with
  a blue circle. (This is analogous to the orange indicators we already have for
  forcing an element state like :hover).

- - -

As always, [let us know what you think via
Twitter](https://twitter.com/intent/tweet?text=%40ChromeDevTools) or the
comments below, and submit bugs to [crbug.com/new](https://crbug.com/new).

Until next month!
Paul Bakaus & the DevTools team


text:
package org.jboss.logmanager;

import java.util.Map;

/**
 * Mapped diagnostic context.  This is a thread-local map used to hold loggable information.
 */
public final class MDC {

    private MDC() {}

    private static final Holder mdc = new Holder();

    /**
     * Get the value for a key, or {@code null} if there is no mapping.
     *
     * @param key the key
     * @return the value
     */
    public static String get(String key) {
        final Object value = getObject(key);
        return value == null ? null : value.toString();
    }

    /**
     * Get the value for a key, or {@code null} if there is no mapping.
     *
     * @param key the key
     * @return the value
     */
    public static Object getObject(String key) {
        return mdc.get().get(key);
    }

    /**
     * Set the value of a key, returning the old value (if any) or {@code null} if there was none.
     *
     * @param key the key
     * @param value the new value
     * @return the old value or {@code null} if there was none
     */
    public static String put(String key, String value) {
        final Object oldValue = putObject(key, value);
        return oldValue == null ? null : oldValue.toString();
    }

    /**
     * Set the value of a key, returning the old value (if any) or {@code null} if there was none.
     *
     * @param key the key
     * @param value the new value
     * @return the old value or {@code null} if there was none
     */
    public static Object putObject(String key, Object value) {
        if (key == null) {
            throw new NullPointerException("key is null");
        }
        if (value == null) {
            throw new NullPointerException("value is null");
        }
        return mdc.get().put(key, value);
    }

    /**
     * Remove a key.
     *
     * @param key the key
     * @return the old value or {@code null} if there was none
     */
    public static String remove(String key) {
        final Object oldValue = removeObject(key);
        return oldValue == null ? null : oldValue.toString();
    }

    /**
     * Remove a key.
     *
     * @param key the key
     * @return the old value or {@code null} if there was none
     */
    public static Object removeObject(String key) {
        return mdc.get().remove(key);
    }

    /**
     * Get a copy of the MDC map.  This is a relatively expensive operation.
     *
     * @return a copy of the map
     */
    public static Map<String, String> copy() {
        return fastCopy();
    }

    static FastCopyHashMap<String, String> fastCopy() {
        final FastCopyHashMap<String, String> result = new FastCopyHashMap<String, String>();
        for (Map.Entry<String, Object> entry : mdc.get().entrySet()) {
            result.put(entry.getKey(), entry.getValue().toString());
        }
        return result;
    }

    /**
     * Get a copy of the MDC map.  This is a relatively expensive operation.
     *
     * @return a copy of the map
     */
    public static Map<String, Object> copyObject() {
        return fastCopyObject();
    }

    static FastCopyHashMap<String, Object> fastCopyObject() {
        return mdc.get().clone();
    }

    /**
     * Clear the current MDC map.
     */
    public static void clear() {
        mdc.get().clear();
    }

    private static final class Holder extends InheritableThreadLocal<FastCopyHashMap<String, Object>> {

        @Override
        protected FastCopyHashMap<String, Object> childValue(final FastCopyHashMap<String, Object> parentValue) {
            return new FastCopyHashMap<String, Object>(parentValue);
        }

        @Override
        protected FastCopyHashMap<String, Object> initialValue() {
            return new FastCopyHashMap<String, Object>();
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.securityinsights.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.securityinsights.fluent.models.RelationInner;

/** An instance of this class provides access to all the operations defined in BookmarkRelationsClient. */
public interface BookmarkRelationsClient {
    /**
     * Gets all bookmark relations.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return all bookmark relations as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<RelationInner> list(String resourceGroupName, String workspaceName, String bookmarkId);

    /**
     * Gets all bookmark relations.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param filter Filters the results, based on a Boolean condition. Optional.
     * @param orderby Sorts the results. Optional.
     * @param top Returns only the first n results. Optional.
     * @param skipToken Skiptoken is only used if a previous operation returned a partial result. If a previous response
     *     contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that
     *     specifies a starting point to use for subsequent calls. Optional.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return all bookmark relations as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<RelationInner> list(
        String resourceGroupName,
        String workspaceName,
        String bookmarkId,
        String filter,
        String orderby,
        Integer top,
        String skipToken,
        Context context);

    /**
     * Gets a bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a bookmark relation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    RelationInner get(String resourceGroupName, String workspaceName, String bookmarkId, String relationName);

    /**
     * Gets a bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a bookmark relation along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<RelationInner> getWithResponse(
        String resourceGroupName, String workspaceName, String bookmarkId, String relationName, Context context);

    /**
     * Creates the bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @param relation The relation model.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents a relation between two resources.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    RelationInner createOrUpdate(
        String resourceGroupName, String workspaceName, String bookmarkId, String relationName, RelationInner relation);

    /**
     * Creates the bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @param relation The relation model.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents a relation between two resources along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<RelationInner> createOrUpdateWithResponse(
        String resourceGroupName,
        String workspaceName,
        String bookmarkId,
        String relationName,
        RelationInner relation,
        Context context);

    /**
     * Delete the bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    void delete(String resourceGroupName, String workspaceName, String bookmarkId, String relationName);

    /**
     * Delete the bookmark relation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param bookmarkId Bookmark ID.
     * @param relationName Relation Name.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<Void> deleteWithResponse(
        String resourceGroupName, String workspaceName, String bookmarkId, String relationName, Context context);
}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>所有类</title>
<meta name="date" content="2017-08-07">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

所有类

AuditSdk

AuditSdk.LogBuilder

PropType


text:
<?php

	session_start();

	require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."lib".DIRECTORY_SEPARATOR."classloader.php");
	require_once(dirname(__FILE__).DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."config.php");

	//Array of errors
	$errors = array();

	///////////
	//Infos //
	///////////

	//Id
	if(isset($_POST['id']) && filter_var($_POST['id'], FILTER_VALIDATE_INT)){
		$id = intval($_POST['id']);
	}
	else{
		$id = null;
	}

	//Name
	if(isset($_POST['name']) && strlen($_POST['name']) > 0){
		$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
	}
	else{
		$errors[] = 'Missing name';
	}

	//Category
	if(isset($_POST['category']) && strlen($_POST['category']) > 0){
		$category_name = filter_var($_POST['category'], FILTER_SANITIZE_STRING);

		$category = CategoryDao::getByName($category_name);

		if($category == null){
			$errors[] = 'Category '.$category_name.' does\'t exists';
		}

	}
	else{
		$errors[] = 'Missing category';
	}

	//If there is some error, output them now and stop
	if(count($errors) > 0){
		echo json_encode(array('errors' => $errors));
		die();
	}

	$element = new Element($id, $name, $category);

	//Description
	if(isset($_POST['description']) && strlen($_POST['description']) > 0 && $element){
		$description = filter_var($_POST['description'], FILTER_SANITIZE_STRING);
		$element->setDescription($description);
	}

	//we need all elements to create link and to check the name is not taken
	$allElements = ElementDao::getAll();

	if($element->getId() == null){
		foreach ($allElements as $knowElement) {
			if($knowElement->getName() == $element->getName()){
				$errors[] = 'Name '.$element->getName().' already used';
				echo json_encode(array('errors' => $errors));
				die();
			}
		}
	}

	//////////
	//Costs //
	//////////

        if(isset($_POST['costs']) && is_array($_POST['costs'])){
		foreach ($_POST['costs'] as $post_costs) {
			//link_id
			$cost_id = null;
			if(filter_var($post_costs['cost_id'], FILTER_VALIDATE_INT)){
				$cost_id = intval($post_costs['cost_id']);
			}

			//Target name
			$element_to_pay = null;
			if(isset($post_costs['element_to_pay_id']) && strlen($post_costs['element_to_pay_id']) > 0){
				$element_to_pay_id = filter_var($post_costs['element_to_pay_id'], FILTER_SANITIZE_STRING);
				if($element_to_pay_id == $element->getId()){
					$errors[] = 'Element can\'t be use to pay himself';
				}
				else if(array_key_exists($element_to_pay_id, $allElements)){
					$cost = new Cost($cost_id, $element, $allElements[$element_to_pay_id], null, null);
				}
				else{
					$errors[] = 'Element '.$element_to_pay_id.' doesn\'t exists';
				}
			}

			//Scaling
			if(isset($post_costs['scaling_id']) && strlen($post_costs['scaling_id']) > 0 && $cost){
				$scalingId = filter_var($post_costs['scaling_id'], FILTER_VALIDATE_INT);
				$cost->setScaling(CostScalingDao::getById($scalingId));
			}

                        //Base quantity
			if(isset($post_costs['base_quantity']) && strlen($post_costs['base_quantity']) > 0 && $cost){
				$baseQuantity = filter_var($post_costs['base_quantity'], FILTER_VALIDATE_INT);
				$cost->setBaseQuantity($baseQuantity);
			}

			if($cost)
				$element->addCost($cost);
		}
	}

	//////////
	//Need //
	//////////

	if(isset($_POST['need']) && is_array($_POST['need'])){
		foreach ($_POST['need'] as $post_need) {
			//link_id
			$link_id = null;
			if(filter_var($post_need['link_id'], FILTER_VALIDATE_INT)){
				$link_id = intval($post_need['link_id']);
			}

			//Target name
			$need = null;
			if(isset($post_need['target_id']) && strlen($post_need['target_id']) > 0){
				$target_id = filter_var($post_need['target_id'], FILTER_SANITIZE_STRING);
				if($target_id == $element->getId()){
					$errors[] = 'Element can\'t needs himself';
				}
				else if(array_key_exists($target_id, $allElements)){
					$need = new Need($link_id, $allElements[$target_id]);
				}
				else{
					$errors[] = 'Element '.$target_id.' doesn\'t exists';
				}
			}

			//Conditions
			if(isset($post_need['conditions']) && strlen($post_need['conditions']) > 0 && $need){
				$conditions = filter_var($post_need['conditions'], FILTER_SANITIZE_STRING);
				$need->setConditions($conditions);
			}

			if($need)
				$element->addNeed($need);
		}
	}

	///////////
	//Allow //
	///////////

	if(isset($_POST['allow']) && is_array($_POST['allow'])){
		foreach ($_POST['allow'] as $post_allow) {
			//link_id
			$link_id = null;
			if(filter_var($post_allow['link_id'], FILTER_VALIDATE_INT)){
				$link_id = intval($post_allow['link_id']);
			}

			//Target name
			$allow = null;
			if(isset($post_allow['target_id']) && strlen($post_allow['target_id']) > 0){
				$target_id = filter_var($post_allow['target_id'], FILTER_SANITIZE_STRING);
				if($target_id == $element->getId()){
					$errors[] = 'Element can\'t allows himself';
				}
				else if(array_key_exists($target_id, $allElements)){
					$allow = new Allow($link_id, $allElements[$target_id]);
				}
				else{
					$errors[] = 'Element '.$target_id.' doesn\'t exists';
				}
			}

			//Conditions
			if(isset($post_allow['conditions']) && strlen($post_allow['conditions']) > 0 && $allow){
				$conditions = filter_var($post_allow['conditions'], FILTER_SANITIZE_STRING);
				$allow->setConditions($conditions);
			}

			if($allow)
				$element->addAllow($allow);
		}
	}

	////////////
	//Extend //
	////////////

	//Extend
	if(isset($_POST['extend']) && is_array($_POST['extend'])){
		$post_extend = $_POST['extend'];

		//link_id
		$link_id = null;
		if(filter_var($post_extend['link_id'], FILTER_VALIDATE_INT)){
			$link_id = intval($post_extend['link_id']);
		}

		//Target name
		$extend = null;
		if(isset($post_extend['target_id']) && strlen($post_extend['target_id']) > 0){
			$target_id = filter_var($post_extend['target_id'], FILTER_SANITIZE_STRING);
			if($target_id == $element->getId()){
				$errors[] = 'Element can\'t extends himself';
			}
			else if(array_key_exists($target_id, $allElements)){
				$extend = new Extend($link_id, $allElements[$target_id]);
			}
			else{
				$errors[] = 'Element '.$target_id.' doesn\'t exists';
			}
		}

		//Conditions
		if(isset($post_extend['conditions']) && strlen($post_extend['conditions']) > 0 && $extend){
			$conditions = filter_var($post_extend['conditions'], FILTER_SANITIZE_STRING);
			$extend->setConditions($conditions);
		}

		if($extend)
			$element->setExtend($extend);
	}

	//ExtendedBy
	if(isset($_POST['extendedby']) && is_array($_POST['extendedby'])){
		foreach ($_POST['extendedby'] as $post_extendedby) {
			//link_id
			$link_id = null;
			if(filter_var($post_extendedby['link_id'], FILTER_VALIDATE_INT)){
				$link_id = intval($post_extendedby['link_id']);
			}

			//Target name
			$extendedBy = null;
			if(isset($post_extendedby['target_id']) && strlen($post_extendedby['target_id']) > 0){
				$target_id = filter_var($post_extendedby['target_id'], FILTER_SANITIZE_STRING);
				if($target_id == $element->getId()){
					$errors[] = 'Element can\'t be extented by himself';
				}
				else if(array_key_exists($target_id, $allElements)){
					$extendedBy = new ExtendedBy($link_id, $allElements[$target_id]);
				}
				else{
					$errors[] = 'Element '.$target_id.' doesn\'t exists';
				}
			}

			//Conditions
			if(isset($post_extendedby['conditions']) && strlen($post_extendedby['conditions']) > 0 && $extendedBy){
				$conditions = filter_var($post_extendedby['conditions'], FILTER_SANITIZE_STRING);
				$extendedBy->setConditions($conditions);
			}

			if($extendedBy)
				$element->addExtension($extendedBy);
		}
	}

	////////////
	//Evolve //
	////////////

	//Regress
	if(isset($_POST['regress']) && is_array($_POST['regress'])){
		$post_regress = $_POST['regress'];

		//link_id
		$link_id = null;
		if(filter_var($post_regress['link_id'], FILTER_VALIDATE_INT)){
			$link_id = intval($post_regress['link_id']);
		}

		//Target name
		$regress = null;
		if(isset($post_regress['target_id']) && strlen($post_regress['target_id']) > 0){
			$target_id = filter_var($post_regress['target_id'], FILTER_SANITIZE_STRING);
			if($target_id == $element->getId()){
				$errors[] = 'Element can\'t evolves from himself';
			}
			else if(array_key_exists($target_id, $allElements)){
				$regress = new Regress($link_id, $allElements[$target_id]);
			}
			else{
				$errors[] = 'Element '.$target_id.' doesn\'t exists';
			}
		}

		//Conditions
		if(isset($post_regress['conditions']) && strlen($post_regress['conditions']) > 0 && $regress){
			$conditions = filter_var($post_regress['conditions'], FILTER_SANITIZE_STRING);
			$regress->setConditions($conditions);
		}

		if($regress)
			$element->setRegress($regress);
	}

	//Evolve into
	if(isset($_POST['evolve']) && is_array($_POST['evolve'])){
		foreach ($_POST['evolve'] as $post_evolve) {
			//link_id
			$link_id = null;
			if(filter_var($post_evolve['link_id'], FILTER_VALIDATE_INT)){
				$link_id = intval($post_evolve['link_id']);
			}

			//Target name
			$evolve = null;
			if(isset($post_evolve['target_id']) && strlen($post_evolve['target_id']) > 0){
				$target_id = filter_var($post_evolve['target_id'], FILTER_SANITIZE_STRING);
				if($target_id == $element->getId()){
					$errors[] = 'Element can\'t evolves into himself';
				}
				else if(array_key_exists($target_id, $allElements)){
					$evolve = new Evolve($link_id, $allElements[$target_id]);
				}
				else{
					$errors[] = 'Element '.$target_id.' doesn\'t exists';
				}
			}

			//Conditions
			if(isset($post_evolve['conditions']) && strlen($post_evolve['conditions']) > 0 && $evolve){
				$conditions = filter_var($post_evolve['conditions'], FILTER_SANITIZE_STRING);
				$evolve->setConditions($conditions);
			}

			if($evolve)
				$element->addEvolution($evolve);
		}
	}

	////////////////
	//Processing //
	////////////////

	if(count($errors) > 0){
		echo json_encode(array('errors' => $errors));
	}
	else{

		if($element->getId() != null){

			ElementDao::update($element);
			$message =  "Element ".$element->getName()." saved!";
		}
		else{
			ElementDao::insert($element);
			$message = "Element ".$element->getName()." created!";
		}

		echo json_encode(array('redirect' => $GLOBALS['dns']."?page=elements_list", 'message' => $message));
	}
?>


text:
{% load replace %}

{% spaceless %}

Creation
{% for key, value in creation.items %}
	{% if not "Original_source" in key and not "Creation_tool" in key %}

				{{ key|rep }}: {{ value }}

	{% endif %}
{% endfor %}

{% if "Original_source" in creation %}
	Original Sources
{% endif %}

		{% for key, value in creation.items %}
			{% if "Original_source" in key %}
				{% include "repository/resource_view/target_resource.html" with target=value title="Original Source" level="list" %}
			{% endif %}
		{% endfor %}

{% if "Creation_tool" in creation %}
	Creation Tools
{% endif %}

		{% for key, value in creation.items %}
			{% if "Creation_tool" in key %}
				{% include "repository/resource_view/target_resource.html" with target=value title="Creation Tool" level="list" %}
			{% endif %}
		{% endfor %}

{% endspaceless %}


text:
package com.twitter.sdk.android.tweetui;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.models.Tweet;

/**
 * TweetTimelineListAdapter is a ListAdapter which can provide Timeline Tweets to ListViews.
 */
public class TweetTimelineListAdapter extends TimelineListAdapter<Tweet> {
    protected Callback<Tweet> actionCallback;
    protected final int styleResId;
    protected TweetUi tweetUi;

    /**
     * Constructs a TweetTimelineListAdapter for the given Tweet Timeline.
     * @param context the context for row views.
     * @param timeline a Timeline<Tweet> providing access to Tweet data items.
     * @throws java.lang.IllegalArgumentException if context is null
     */
    public TweetTimelineListAdapter(Context context, Timeline<Tweet> timeline) {
        this(context, timeline, R.style.tw__TweetLightStyle, null);
    }

    TweetTimelineListAdapter(Context context, Timeline<Tweet> timeline, int styleResId,
                             Callback<Tweet> cb) {
        this(context, new TimelineDelegate<>(timeline), styleResId, cb, TweetUi.getInstance());
    }

    TweetTimelineListAdapter(Context context, TimelineDelegate<Tweet> delegate, int styleResId,
                             Callback<Tweet> cb, TweetUi tweetUi) {
        super(context, delegate);
        this.styleResId = styleResId;
        this.actionCallback = new ReplaceTweetCallback(delegate, cb);
        this.tweetUi = tweetUi;
    }

    /**
     * Returns a CompactTweetView by default. May be overridden to provide another view for the
     * Tweet item. If Tweet actions are enabled, be sure to call setOnActionCallback(actionCallback)
     * on each new subclass of BaseTweetView to ensure proper success and failure handling
     * for Tweet actions (favorite, unfavorite).
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        final Tweet tweet = getItem(position);
        if (rowView == null) {
            final BaseTweetView tv = new CompactTweetView(context, tweet, styleResId);
            tv.setOnActionCallback(actionCallback);
            rowView = tv;
        } else {
            ((BaseTweetView) rowView).setTweet(tweet);
        }
        return rowView;
    }

    /*
     * On success, sets the updated Tweet in the TimelineDelegate to replace any old copies
     * of the same Tweet by id.
     */
    static class ReplaceTweetCallback extends Callback<Tweet> {
        TimelineDelegate<Tweet> delegate;
        Callback<Tweet> cb;

        ReplaceTweetCallback(TimelineDelegate<Tweet> delegate, Callback<Tweet> cb) {
            this.delegate = delegate;
            this.cb = cb;
        }

        @Override
        public void success(Result<Tweet> result) {
            delegate.setItemById(result.data);
            if (cb != null) {
                cb.success(result);
            }
        }

        @Override
        public void failure(TwitterException exception) {
            if (cb != null) {
                cb.failure(exception);
            }
        }
    }

    /**
     * TweetTimelineListAdapter Builder
     */
    public static class Builder {
        private Context context;
        private Timeline<Tweet> timeline;
        private Callback<Tweet> actionCallback;
        private TimelineFilter timelineFilter;
        private int styleResId = R.style.tw__TweetLightStyle;

        /**
         * Constructs a Builder.
         * @param context Context for Tweet views.
         */
        public Builder(Context context) {
            this.context = context;
        }

        /**
         * Sets the Tweet timeline data source.
         * @param timeline Timeline of Tweets
         */
        public Builder setTimeline(Timeline<Tweet> timeline) {
            this.timeline = timeline;
            return this;
        }

        /**
         * Sets the Tweet view style by resource id.
         * @param styleResId resource id of the Tweet view style
         */
        public Builder setViewStyle(int styleResId) {
            this.styleResId = styleResId;
            return this;
        }

        /**
         * Sets the callback to call when a Tweet action is performed on a Tweet view.
         * @param actionCallback called when a Tweet action is performed.
         */
        public Builder setOnActionCallback(Callback<Tweet> actionCallback) {
            this.actionCallback = actionCallback;
            return this;
        }

        /**
         * Sets the TimelineFilter used to filter tweets from timeline.
         * @param timelineFilter timelineFilter for timeline
         */
        public Builder setTimelineFilter(TimelineFilter timelineFilter) {
            this.timelineFilter = timelineFilter;
            return this;
        }

        /**
         * Builds a TweetTimelineListAdapter from Builder parameters.
         * @return a TweetTimelineListAdpater
         */
        public TweetTimelineListAdapter build() {
            if (timelineFilter == null) {
                return new TweetTimelineListAdapter(context, timeline, styleResId, actionCallback);
            } else {
                final FilterTimelineDelegate delegate =
                        new FilterTimelineDelegate(timeline, timelineFilter);
                return new TweetTimelineListAdapter(context, delegate, styleResId, actionCallback,
                        TweetUi.getInstance());
            }
        }
    }
}


text:
copyright:
 years: 2015, 2016

---

# Registrazione di dispositivi

{: #cordova_register}

Per registrare un dispositivo con il Push Notification Service, richiama il metodo.

Copia e incolla il seguente frammento di codice nella tua applicazione Cordova per registrare
                    un dispositivo.

```
	var success = function(message) { console.log("Success: " + message); };
	var failure = function(message) { console.log("Error: " + message); };
	MFPPush.registerDevice({}, success, failure);
```

## Android
{: #cordova_register_android}
Android non utilizza il parametro delle impostazioni. Se stai soltanto creando un'applicazione Android, invia un oggetto vuoto; ad esempio:

```
	MFPPush.registerDevice({}, success, failure);
	MFPPush.unregisterDevice(success, failure);
```

##	iOS
{: #cordova_register_ios}
Se vuoi personalizzare le proprietà di avviso, badge e audio,
                    aggiungi il seguente frammento di codice JavaScript alla parte web della tua applicazione
                    Cordova.

```
	var settings = {
	   ios: {
	       alert: true,
	       badge: true,
	       sound: true
	   }
	}
	MFPPush.registerDevice(settings, success, failure);
```

##JavaScript
{: #cordova_register_js}

```
MFPPush.registerDevice({}, success, failure);
```

Puoi accedere ai contenuti del parametro di risposta con esito positivo in Javascript utilizzando JSON.parse:
**var token = JSON.parse(response).token**

Le chiavi disponibili sono le seguenti: `token`, `userId` e `deviceId`.

Il seguente frammento di codice JavaScript mostra come inizializzare il tuo Bluemix Mobile Services client SDK, registra un dispositivo ed è in ascolto per le notifiche push. Inserisci questo codice nel tuo file Javascript.

```
//Registra il token di dispositivo presso il Bluemix Push Notification Service
funcapplication(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
  CDVMFPPush.sharedInstance().didRegisterForRemoteNotifications(deviceToken)
}
```

```
//Gestisci l'errore in caso di registrazione del token di dispositivo presso APNS non riuscita
funcapplication(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSErrorPointer){
CDVMFPPush.sharedInstance().didFailToRegisterForRemoteNotifications(error)
}
```

in **onDeviceReady: function()**.

```
onDeviceReady: function() {
     app.receivedEvent('deviceready');
     BMSClient.initialize("https://http://myroute_mybluemix.net","my_appGuid");
     var success = function(message) { console.log("Success: " + message); };
     var failure = function(message) { console.log("Error: " + message); };
     var settings = {
         ios: {
             alert: true,
	       badge: true,
	       sound: true
	   }
     };
     MFPPush.registerDevice(settings, success, failure);
     var notification = function(notif){
         alert (notif.message);
     };
     MFPPush.registerNotificationsCallback(notification);

 }
```

## Objective-C
{: #cordova_register_objective}
Aggiungi il seguente frammento di codice Objective-C alla classe delegato della tua applicazione

```
	// Registra il token dispositivo con Bluemix Push Notification Service
	- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
	  [[CDVMFPPush sharedInstance] didRegisterForRemoteNotifications:deviceToken];
	}
	// Gestisci l'errore in caso di registrazione del token di dispositivo presso APNS non riuscita
	- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
	   [[CDVMFPPush sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
	}
```

##Swift
{: #cordova_register_swift}
Aggiungi il seguente frammento di codice Swift alla classe delegato della tua applicazione.

```
funcapplication(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
   CDVMFPPush.sharedInstance().didRegisterForRemoteNotifications(deviceToken)
}
//Gestisci l'errore in caso di registrazione del token di dispositivo presso APNS non riuscita
funcapplication(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSErrorPointer){
CDVMFPPush.sharedInstance().didFailToRegisterForRemoteNotifications(error)
}
```

##Passi successivi
{: #cordova_register_next}

1. Crea il tuo progetto e quindi eseguilo utilizzando i seguenti comandi:

	* Android - **cordova build android**  e quindi **cordova run android**

	* iOS - **cordova build ios** e quindi **cordova run ios**
1. [Ricezione di notifiche di push sui dispositivi](t_cordova_receive.html).


text:
<?php

declare(strict_types=1);

namespace Kreta\PhpCsFixerConfig;

use PhpCsFixer\Config;
use PhpCsFixer\Fixer\Comment\HeaderCommentFixer;

final class KretaConfig extends Config
{
    const HEADER = <<<EOF
This file is part of the Kreta package.

(c) Beñat Espiña <benatespina@gmail.com>
(c) Gorka Laucirica <gorka.lauzirika@gmail.com>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

    private $isPhpSpec;

    public function __construct($isPhpSpec = false)
    {
        parent::__construct('kreta');
        $this->setRiskyAllowed(true);
        $this->isPhpSpec = $isPhpSpec;
    }

    public function getRules() : array
    {
        $rules = [
            '@Symfony'                                    => true,
            '@Symfony:risky'                              => true,
            'array_syntax'                                => [
                'syntax' => 'short',
            ],
            'binary_operator_spaces'                      => [
                'align_double_arrow' => true,
                'align_equals'       => false,
            ],
            'blank_line_after_opening_tag'                => true,
            'blank_line_before_return'                    => true,
            'cast_spaces'                                 => true,
            'class_keyword_remove'                        => false,
            'combine_consecutive_unsets'                  => true,
            'concat_space'                                => [
                'spacing' => 'one',
            ],
            'declare_equal_normalize'                     => true,
            'declare_strict_types'                        => true,
            'ereg_to_preg'                                => true,
            'function_typehint_space'                     => true,
            'general_phpdoc_annotation_remove'            => true,
            'hash_to_slash_comment'                       => true,
            'header_comment'                              => [
                'header'      => self::HEADER,
                'commentType' => HeaderCommentFixer::HEADER_COMMENT,
                'location'    => 'after_open',
            ],
            'include'                                     => true,
            'is_null'                                     => [
                'use_yoda_style' => true,
            ],
            'linebreak_after_opening_tag'                 => true,
            'lowercase_cast'                              => true,
            'mb_str_functions'                            => true,
            'method_separation'                           => true,
            'modernize_types_casting'                     => true,
            'native_function_casing'                      => true,
            'native_function_invocation'                  => false,
            'new_with_braces'                             => true,
            'no_alias_functions'                          => true,
            'no_blank_lines_after_class_opening'          => true,
            'no_blank_lines_after_phpdoc'                 => true,
            'no_blank_lines_before_namespace'             => false,
            'no_empty_comment'                            => true,
            'no_empty_phpdoc'                             => true,
            'no_empty_statement'                          => true,
            'no_extra_consecutive_blank_lines'            => [
                'break',
                'continue',
                'curly_brace_block',
                'extra',
                'parenthesis_brace_block',
                'return',
                'square_brace_block',
                'throw',
                'use',
                'useTrait',
            ],
            'no_leading_import_slash'                     => true,
            'no_leading_namespace_whitespace'             => true,
            'no_mixed_echo_print'                         => [
                'use' => 'echo',
            ],
            'no_multiline_whitespace_around_double_arrow' => true,
            'no_multiline_whitespace_before_semicolons'   => true,
            'no_php4_constructor'                         => true,
            'no_short_bool_cast'                          => true,
            'no_short_echo_tag'                           => true,
            'no_singleline_whitespace_before_semicolons'  => true,
            'no_spaces_around_offset'                     => true,
            'no_trailing_comma_in_list_call'              => true,
            'no_trailing_comma_in_singleline_array'       => true,
            'no_unneeded_control_parentheses'             => true,
            'no_unreachable_default_argument_value'       => true,
            'no_unused_imports'                           => true,
            'no_useless_else'                             => true,
            'no_useless_return'                           => false,
            'no_whitespace_before_comma_in_array'         => true,
            'no_whitespace_in_blank_line'                 => true,
            'normalize_index_brace'                       => true,
            'not_operator_with_space'                     => false,
            'not_operator_with_successor_space'           => false,
            'object_operator_without_whitespace'          => true,
            'ordered_class_elements'                      => false,
            'ordered_imports'                             => true,
            'php_unit_construct'                          => false,
            'php_unit_dedicate_assert'                    => false,
            'php_unit_fqcn_annotation'                    => true,
            'php_unit_strict'                             => false,
            'pow_to_exponentiation'                       => false,
            'pre_increment'                               => true,
            'protected_to_private'                        => true,
            'psr0'                                        => false,
            'psr4'                                        => true,
            'random_api_migration'                        => true,
            'return_type_declaration'                     => [
                'space_before' => 'one',
            ],
            'self_accessor'                               => true,
            'semicolon_after_instruction'                 => true,
            'short_scalar_cast'                           => true,
            'silenced_deprecation_error'                  => false,
            'simplified_null_return'                      => false,
            'single_blank_line_before_namespace'          => true,
            'single_quote'                                => true,
            'space_after_semicolon'                       => true,
            'standardize_not_equals'                      => true,
            'strict_comparison'                           => true,
            'strict_param'                                => true,
            'ternary_operator_spaces'                     => true,
            'ternary_to_null_coalescing'                  => true,
            'trailing_comma_in_multiline_array'           => true,
            'trim_array_spaces'                           => true,
            'unary_operator_spaces'                       => true,
            'whitespace_after_comma_in_array'             => true,
        ];

        if (true === $this->isPhpSpec) {
            $rules = array_merge($rules, [
                'visibility_required' => false,
            ]);
        }

        return $rules;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Click Me!</string>
    <string name="app_name">PdfViewerBindingTest</string>
</resources>


text:
@interface VehicleDetailFormController : UITableViewController
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) id detailItem;
@property(nonatomic, strong) EntityAttributeField* carNameCell;
@property(nonatomic, strong) EntityAttributeField* postalCodeCell;
@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 2020-06-04
 * Time: 10:22
 */

namespace Enhavo\Bundle\AppBundle\Tests\Action\Type;

use Enhavo\Bundle\AppBundle\Action\Action;
use Enhavo\Bundle\AppBundle\Action\ActionLanguageExpression;
use Enhavo\Bundle\AppBundle\Action\Type\PreviewActionType;
use Enhavo\Bundle\AppBundle\Tests\Mock\ResourceMock;
use Enhavo\Bundle\AppBundle\Tests\Mock\RouterMock;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class PreviewActionTypeTest extends TestCase
{
    private function createDependencies()
    {
        $dependencies = new PreviewActionTypeDependencies();
        $dependencies->translator = $this->getMockBuilder(TranslatorInterface::class)->getMock();
        $dependencies->actionLanguageExpression = $this->getMockBuilder(ActionLanguageExpression::class)->disableOriginalConstructor()->getMock();
        $dependencies->router = new RouterMock();
        return $dependencies;
    }

    private function createInstance(PreviewActionTypeDependencies $dependencies)
    {
        return new PreviewActionType(
            $dependencies->translator,
            $dependencies->actionLanguageExpression,
            $dependencies->router
        );
    }

    public function testCreateViewData()
    {
        $dependencies = $this->createDependencies();
        $dependencies->translator->method('trans')->willReturnCallback(function ($value) {return $value;});
        $type = $this->createInstance($dependencies);

        $action = new Action($type, [
            'route' => 'preview_route',
        ]);

        $viewData = $action->createViewData(new ResourceMock());

        $this->assertEquals('preview-action', $viewData['component']);
        $this->assertEquals('label.preview', $viewData['label']);
        $this->assertEquals('/preview_route?id=1', $viewData['url']);
    }

    public function testType()
    {
        $dependencies = $this->createDependencies();
        $type = $this->createInstance($dependencies);
        $this->assertEquals('preview', $type->getType());
    }
}

class PreviewActionTypeDependencies
{
    /** @var TranslatorInterface|\PHPUnit_Framework_MockObject_MockObject */
    public $translator;
    /** @var ActionLanguageExpression|\PHPUnit_Framework_MockObject_MockObject */
    public $actionLanguageExpression;
    /** @var RouterInterface|\PHPUnit_Framework_MockObject_MockObject */
    public $router;
}


text:
package org.dnd5spellbook;

/**
 * Class containing application-wide constants
 */
public class Constants {
    public static final String DND_SPELLS_ASSETS_PATH = "dndbundle";
}


text:
const fs = require('fs')
const events = require('events')
const WebSocket = require('ws')

const pairingPayload = require('./pairingPayload.json')

const lgtv = new events.EventEmitter()
let requestId = 0
let lgtvSocket
let pointerSocket
let waitingForResponse = {}
let subscribtions = {}
let keyFile = './client-key'

const onConnected = () => {
  lgtv.emit('connected')
  if (fs.existsSync(keyFile)) {
    pairingPayload['client-key'] = fs.readFileSync(keyFile, 'utf8')
  }
  lgtvSocket.send(JSON.stringify({
    type: 'register',
    payload: pairingPayload
  }))
}

const onClosed = () => {
  lgtv.emit('close')
  subscribtions = {}
  waitingForResponse = {}
  lgtvSocket.removeListener('open', onConnected)
  lgtvSocket.removeListener('close', onClosed)
  lgtvSocket.removeListener('error', onError)
  lgtvSocket.removeListener('message', onMessage)
  lgtvSocket = undefined
}

const onError = (error) => lgtv.emit('error', error)

const onRegistered = (payload) => {
  lgtv.emit('registered')
  if (pairingPayload['client-key'] === undefined) {
    fs.writeFile(keyFile, payload['client-key'], (err) => {
      if (err) {
        lgtv.emit('error', new Error(err))
      }
    })
  }
}

const onMessage = (message) => {
  try {
    message = JSON.parse(message)
  } catch (e) {
    lgtv.emit('error', new Error(e))
    return
  }
  if (message.type === 'registered') {
    onRegistered(message.payload)
  } else {
    if (waitingForResponse[message.id] !== undefined) {
      // TODO: Reject on error response
      waitingForResponse[message.id].resolve(message.payload)
      delete waitingForResponse[message.id]
    } else if (subscribtions[message.id] !== undefined) {
      // TODO: Remove subscribtion on error response?
      subscribtions[message.id](message.payload)
    }
  }
}

lgtv.connect = ({host, port, clientKeyFile}) => {
  if (lgtvSocket && lgtvSocket.readyState !== WebSocket.CLOSED) {
    subscribtions = {}
    waitingForResponse = {}
    lgtvSocket.removeListener('open', onConnected)
    lgtvSocket.removeListener('close', onClosed)
    lgtvSocket.removeListener('error', onError)
    lgtvSocket.removeListener('message', onMessage)
    lgtvSocket.terminate()
    lgtvSocket = undefined
  }
  lgtv.emit('connecting')
  keyFile = clientKeyFile
  lgtvSocket = new WebSocket(`lgtvSockets://${host}:${port || 3000}`, { rejectUnauthorized: false })
  lgtvSocket.on('open', onConnected)
  lgtvSocket.on('close', onClosed)
  lgtvSocket.on('error', onError)
  lgtvSocket.on('message', onMessage)
}

lgtv.close = () => {
  if (lgtvSocket && lgtvSocket.readyState !== WebSocket.CLOSED) {
    lgtvSocket.terminate()
  }
}

lgtv.request = (data) => new Promise((resolve, reject) => {
  if (lgtvSocket === undefined || lgtvSocket.readyState !== WebSocket.OPEN) {
    reject(new Error('Not connected.'))
    return
  }
  if (typeof data === 'string') {
    data = { uri: data }
  }
  data.type = 'request'
  data.id = (requestId += 1)
  data.payload = data.payload || {}
  lgtvSocket.send(JSON.stringify(data), (error) => {
    if (error) reject(error)
    else waitingForResponse[data.id] = {resolve, reject, time: new Date()}
  })
})

lgtv.subscribe = (data, callback) => {
  if (lgtvSocket === undefined || lgtvSocket.readyState !== WebSocket.OPEN) {
    lgtv.emit('error', new Error('Not connected.'))
    return
  }
  if (typeof data === 'string') {
    data = { uri: data }
  }
  data.type = 'subscribe'
  data.id = (requestId += 1)
  data.payload = data.payload || {}
  lgtvSocket.send(JSON.stringify(data), (error) => {
    if (error) lgtv.emit('error', new Error(error))
    else subscribtions[data.id] = callback
  })
}

// Pointer Input

const getPointerInputSocket = () => new Promise(async (resolve, reject) => {
  if (pointerSocket && pointerSocket.readyState === WebSocket.OPEN) {
    resolve(pointerSocket)
    return
  }

  const onError = (error) => {
    pointerSocket.removeListener('open', onOpen)
    pointerSocket.removeListener('error', onError)
    reject(error)
  }

  const onOpen = () => {
    pointerSocket.removeListener('open', onOpen)
    pointerSocket.removeListener('error', onError)
    resolve(pointerSocket)
  }

  const onClosed = () => {
    pointerSocket.removeListener('close', onClosed)
    pointerSocket = undefined
  }

  try {
    const response = await lgtv.request('ssap://com.webos.service.networkinput/getPointerInputSocket')
    pointerSocket = new WebSocket(response.socketPath, { rejectUnauthorized: false })
    pointerSocket.on('open', onOpen)
    pointerSocket.on('error', onError)
    pointerSocket.on('close', onClosed)
  } catch (error) {
    reject(error)
  }
})

lgtv.button = (button) => new Promise(async (resolve, reject) => {
  try {
    const socket = await getPointerInputSocket()
    socket.send(`type:button\nname:${button}\n\n`, (error) => {
      if (error) reject(error)
      else resolve()
    })
  } catch (error) {
    reject(error)
  }
})

lgtv.move = (x, y) => new Promise(async (resolve, reject) => {
  try {
    const socket = await getPointerInputSocket()
    socket.send(`type:move\ndx:${x}\ndy:${y}\ndown:0\n\n`, (error) => {
      if (error) reject(error)
      else resolve()
    })
  } catch (error) {
    reject(error)
  }
})

lgtv.scroll = (value) => new Promise(async (resolve, reject) => {
  try {
    const socket = await getPointerInputSocket()
    socket.send(`type:scroll\ndx:0\ndy:${value}\ndown:0\n\n`, (error) => {
      if (error) reject(error)
      else resolve()
    })
  } catch (error) {
    reject(error)
  }
})

lgtv.click = (value) => new Promise(async (resolve, reject) => {
  try {
    const socket = await getPointerInputSocket()
    socket.send(`type:click\n\n`, (error) => {
      if (error) reject(error)
      else resolve()
    })
  } catch (error) {
    reject(error)
  }
})

module.exports = lgtv