text:
/*
 * RemoveAllDAckDunitTest.java
 *
 * Created on September 15, 2005, 5:51 PM
 */
package org.apache.geode.internal.cache;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Properties;

import org.junit.Test;

import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.CacheWriter;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.util.CacheWriterAdapter;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;

/**
 * Adapted from RemoveAllDAckDUnitTest
 */

public class RemoveAllDAckDUnitTest extends JUnit4DistributedTestCase { // TODO: reformat

  static Cache cache;
  static Properties props = new Properties();
  static Properties propsWork = new Properties();
  static DistributedSystem ds = null;
  static Region region;
  static boolean beforeDestroy = false;
  static int beforeDestroyRemoveAllcounter = 0;

  static boolean flag = false;

  @Override
  public final void postSetUp() throws Exception {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    vm0.invoke(() -> RemoveAllDAckDUnitTest.createCacheForVM0());
    vm1.invoke(() -> RemoveAllDAckDUnitTest.createCacheForVM1());
    LogWriterUtils.getLogWriter().fine("Cache created successfully");
  }

  @Override
  public final void preTearDown() throws Exception {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    vm0.invoke(() -> RemoveAllDAckDUnitTest.closeCache());
    vm1.invoke(() -> RemoveAllDAckDUnitTest.closeCache());
  }

  public static void createCacheForVM0() throws Exception {
    ds = (new RemoveAllDAckDUnitTest()).getSystem(props);
    cache = CacheFactory.create(ds);
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    RegionAttributes attr = factory.create();
    region = cache.createRegion("map", attr);
  }

  public static void createCacheForVM1() throws Exception {
    CacheWriter aWriter = new BeforeDestroyCallback();
    ds = (new RemoveAllDAckDUnitTest()).getSystem(props);
    cache = CacheFactory.create(ds);
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    factory.setCacheWriter(aWriter);
    RegionAttributes attr = factory.create();
    region = cache.createRegion("map", attr);
  }

  public static void closeCache() throws Exception {
    // getLogWriter().fine("closing cache cache cache cache cache 33333333");
    cache.close();
    ds.disconnect();
    // getLogWriter().fine("closed cache cache cache cache cache 44444444");
  }

  // test methods

  @Test
  public void testRemoveAllRemoteVM() {
    // Test PASS.
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);

    Object[] objArr = new Object[1];
    for (int i = 0; i < 3; i++) {
      objArr[0] = "" + i;
      vm0.invoke(RemoveAllDAckDUnitTest.class, "putMethod", objArr);
    }
    vm0.invoke(() -> RemoveAllDAckDUnitTest.removeAllMethod());
    flag = vm1.invoke(() -> RemoveAllDAckDUnitTest.getFlagVM1());
    assertEquals(true, flag);

    vm1.invoke(new CacheSerializableRunnable("temp1") {
      @Override
      public void run2() throws CacheException {
        assertEquals(2, beforeDestroyRemoveAllcounter);
      }
    });

  }// end of test case1

  public static Object putMethod(Object ob) {
    Object obj = null;
    try {
      if (ob != null) {
        String str = "first";
        obj = region.put(ob, str);
      }
    } catch (Exception ex) {
      Assert.fail("Failed while region.put", ex);
    }
    return obj;
  }// end of putMethod

  public static void removeAllMethod() {
    assertEquals(3, region.size());
    ArrayList l = new ArrayList();
    for (int i = 0; i < 2; i++) {
      l.add("" + i);
    }
    region.removeAll(l, "removeAllCallback");
    assertEquals(1, region.size());
  }

  static class BeforeDestroyCallback extends CacheWriterAdapter {
    @Override
    public void beforeDestroy(EntryEvent event) {
      beforeDestroyRemoveAllcounter++;
      assertEquals(true, event.getOperation().isRemoveAll());
      assertEquals("removeAllCallback", event.getCallbackArgument());
      LogWriterUtils.getLogWriter().fine("*******BeforeDestroy*****");
      beforeDestroy = true;
    }
  }

  public static boolean getFlagVM1() {
    return beforeDestroy;
  }

}// end of class


text:
package org.apache.ignite.spi.discovery.zk.internal;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.events.Event;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.spi.discovery.zk.ZookeeperDiscoverySpi;
import org.apache.ignite.spi.discovery.zk.ZookeeperDiscoverySpiMBean;
import org.apache.ignite.spi.discovery.zk.ZookeeperDiscoverySpiTestUtil;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.zookeeper.ZkTestClientCnxnSocketNIO;
import org.junit.Test;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.ignite.events.EventType.EVT_CLIENT_NODE_DISCONNECTED;
import static org.apache.ignite.events.EventType.EVT_CLIENT_NODE_RECONNECTED;

/**
 * Tests for Zookeeper SPI discovery.
 */
public class ZookeeperDiscoveryClientDisconnectTest extends ZookeeperDiscoverySpiTestBase {
    /** */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        // we reduce fealure detection tp speedup failure detection on catch(Exception) clause in createTcpClient().
        cfg.setFailureDetectionTimeout(2000);
        cfg.setClientFailureDetectionTimeout(2000);

        return cfg;
    }

    /**
     * Test reproduces failure in case of client resolution failure
     * {@link org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi#createTcpClient} from server side, further
     * client reconnect and proper grid work.
     *
     * @throws Exception If failed.
     */
    @Test
    public void testClientReconnects() throws Exception {
        blockCommSpi = true;

        Ignite srv1 = startGrid("server1-block");

        helper.clientModeThreadLocal(true);

        IgniteEx cli = startGrid("client-block");

        IgniteCache<Object, Object> cache = cli.getOrCreateCache(DEFAULT_CACHE_NAME);

        cache.put(1, 1);

        assertEquals(cache.get(1), 1);

        assertEquals(1, srv1.cluster().forClients().nodes().size());

        MBeanServer srv = ManagementFactory.getPlatformMBeanServer();

        IgniteEx ignite = grid("server1-block");

        ObjectName spiName = U.makeMBeanName(ignite.context().igniteInstanceName(), "SPIs",
            ZookeeperDiscoverySpi.class.getSimpleName());

        ZookeeperDiscoverySpiMBean bean = JMX.newMBeanProxy(srv, spiName, ZookeeperDiscoverySpiMBean.class);

        assertNotNull(bean);

        assertEquals(0, bean.getCommErrorProcNum());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testConnectionCheck() throws Exception {
        final int NODES = 5;

        startGridsMultiThreaded(NODES);

        for (int i = 0; i < NODES; i++) {
            Ignite node = ignite(i);

            TcpCommunicationSpi spi = (TcpCommunicationSpi)node.configuration().getCommunicationSpi();

            List<ClusterNode> nodes = new ArrayList<>(node.cluster().nodes());

            BitSet res = spi.checkConnection(nodes).get();

            for (int j = 0; j < NODES; j++)
                assertTrue(res.get(j));
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testReconnectDisabled_ConnectionLost() throws Exception {
        clientReconnectDisabled = true;

        startGrid(0);

        sesTimeout = 3000;
        testSockNio = true;
        helper.clientMode(true);

        Ignite client = startGrid(1);

        final CountDownLatch latch = new CountDownLatch(1);

        client.events().localListen(new IgnitePredicate<Event>() {
            @Override public boolean apply(Event evt) {
                latch.countDown();

                return false;
            }
        }, EventType.EVT_NODE_SEGMENTED);

        ZkTestClientCnxnSocketNIO nio = ZkTestClientCnxnSocketNIO.forNode(client);

        nio.closeSocket(true);

        try {
            ZookeeperDiscoverySpiTestHelper.waitNoAliveZkNodes(log,
                zkCluster.getConnectString(),
                Collections.singletonList(ZookeeperDiscoverySpiTestHelper.aliveZkNodePath(client)),
                10_000);
        }
        finally {
            nio.allowConnect();
        }

        assertTrue(latch.await(10, SECONDS));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testServersLeft_FailOnTimeout() throws Exception {
        startGrid(0);

        final int CLIENTS = 5;

        joinTimeout = 3000;

        helper.clientMode(true);

        startGridsMultiThreaded(1, CLIENTS);

        waitForTopology(CLIENTS + 1);

        final CountDownLatch latch = new CountDownLatch(CLIENTS);

        for (int i = 0; i < CLIENTS; i++) {
            Ignite node = ignite(i + 1);

            node.events().localListen(new IgnitePredicate<Event>() {
                @Override public boolean apply(Event evt) {
                    latch.countDown();

                    return false;
                }
            }, EventType.EVT_NODE_SEGMENTED);
        }

        stopGrid(getTestIgniteInstanceName(0), true, false);

        assertTrue(latch.await(10, SECONDS));

        evts.clear();
    }

    /**
     *
     */
    @Test
    public void testStartNoServers_FailOnTimeout() {
        joinTimeout = 3000;

        helper.clientMode(true);

        long start = System.currentTimeMillis();

        Throwable err = GridTestUtils.assertThrows(log, new Callable<Void>() {
            @Override public Void call() throws Exception {
                startGrid(0);

                return null;
            }
        }, IgniteCheckedException.class, null);

        assertTrue(System.currentTimeMillis() >= start + joinTimeout);

        IgniteSpiException spiErr = X.cause(err, IgniteSpiException.class);

        assertNotNull(spiErr);
        assertTrue(spiErr.getMessage().contains("Failed to connect to cluster within configured timeout"));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartNoServer_WaitForServers1() throws Exception {
        startNoServer_WaitForServers(0);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartNoServer_WaitForServers2() throws Exception {
        startNoServer_WaitForServers(10_000);
    }

    /**
     * @param joinTimeout Join timeout.
     * @throws Exception If failed.
     */
    private void startNoServer_WaitForServers(long joinTimeout) throws Exception {
        this.joinTimeout = joinTimeout;

        IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Void>() {
            @Override public Void call() throws Exception {
                helper.clientModeThreadLocal(true);

                startGrid(0);

                return null;
            }
        });

        U.sleep(3000);

        helper.waitSpi(getTestIgniteInstanceName(0), spis);

        helper.clientModeThreadLocal(false);

        startGrid(1);

        fut.get();

        waitForTopology(2);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisconnectOnServersLeft_1() throws Exception {
        disconnectOnServersLeft(1, 1);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisconnectOnServersLeft_2() throws Exception {
        disconnectOnServersLeft(5, 1);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisconnectOnServersLeft_3() throws Exception {
        disconnectOnServersLeft(1, 10);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisconnectOnServersLeft_4() throws Exception {
        disconnectOnServersLeft(5, 10);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisconnectOnServersLeft_5() throws Exception {
        joinTimeout = 10_000;

        disconnectOnServersLeft(5, 10);
    }

    /**
     * @param srvs Number of servers.
     * @param clients Number of clients.
     * @throws Exception If failed.
     */
    private void disconnectOnServersLeft(int srvs, int clients) throws Exception {
        startGridsMultiThreaded(srvs);

        helper.clientMode(true);

        startGridsMultiThreaded(srvs, clients);

        for (int i = 0; i < GridTestUtils.SF.applyLB(5, 2); i++) {
            info("Iteration: " + i);

            final CountDownLatch disconnectLatch = new CountDownLatch(clients);
            final CountDownLatch reconnectLatch = new CountDownLatch(clients);

            IgnitePredicate<Event> p = new IgnitePredicate<Event>() {
                @Override public boolean apply(Event evt) {
                    if (evt.type() == EVT_CLIENT_NODE_DISCONNECTED) {
                        log.info("Disconnected: " + evt);

                        disconnectLatch.countDown();
                    }
                    else if (evt.type() == EVT_CLIENT_NODE_RECONNECTED) {
                        log.info("Reconnected: " + evt);

                        reconnectLatch.countDown();

                        return false;
                    }

                    return true;
                }
            };

            for (int c = 0; c < clients; c++) {
                Ignite client = ignite(srvs + c);

                assertTrue(client.configuration().isClientMode());

                client.events().localListen(p, EVT_CLIENT_NODE_DISCONNECTED, EVT_CLIENT_NODE_RECONNECTED);
            }

            log.info("Stop all servers.");

            GridTestUtils.runMultiThreaded(new IgniteInClosure<Integer>() {
                @Override public void apply(Integer threadIdx) {
                    stopGrid(getTestIgniteInstanceName(threadIdx), true, false);
                }
            }, srvs, "stop-server");

            ZookeeperDiscoverySpiTestHelper.waitReconnectEvent(log, disconnectLatch);

            evts.clear();

            helper.clientMode(false);

            log.info("Restart servers.");

            startGridsMultiThreaded(0, srvs);

            ZookeeperDiscoverySpiTestHelper.waitReconnectEvent(log, reconnectLatch);

            waitForTopology(srvs + clients);

            log.info("Reconnect finished.");
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartNoZk() throws Exception {
        stopZkCluster();

        sesTimeout = 30_000;

        zkCluster = ZookeeperDiscoverySpiTestUtil.createTestingCluster(3);

        try {
            final AtomicInteger idx = new AtomicInteger();

            IgniteInternalFuture fut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
                @Override public Void call() throws Exception {
                    startGrid(idx.getAndIncrement());

                    return null;
                }
            }, 5, "start-node");

            U.sleep(5000);

            assertFalse(fut.isDone());

            zkCluster.start();

            fut.get();

            waitForTopology(5);
        }
        finally {
            zkCluster.start();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
# metacarattere
metacarattere is a small matcher for URLs with colon placeholders.

- [Installation](#installation)
- [Usage](#usage)
    - [Loading it](#loading-it)
    - [`metacarattere()` - The exposed function](#the-exposed-function)
    - [`.match()` - Match an URL](#match-an-url)
    - [`.parse()` - Parse an URL](#parse-an-url)
    - [`.build()` - Replace placeholders](#replace-placeholders)
    - [`.getPattern()` - Get the pattern](#get-the-pattern)
    - [`.getPlaceholders()` - Get the placeholders](#get-the-placeholders)
    - [`.getExpression()` - Get the compiled expression](#get-the-compiled-expression)
- [Naming](#naming)
- [Try it](#try-it)

## Installation

You can install metacarattere for your node.js (or CommonJS in general) project
with `npm`:

```shell
npm install metacarattere
```

You also can install it with `bower` for your front-end (or AMD in general) project:

```shell
bower install metacarattere
```

## Usage

### Loading it
Depending on your project structure, metacarattere is exposed in different ways.

* If you are in a browser environment without any module loader a global `metacarattere`
function will be exposed (as `window.metacarattere`).
* If you use a module loader such as require.js in your front-end application, you
can load metacarattere like any other module.
* If you are in a node.js environment, metacarattere can be required as usual.

### The exposed function
`metacarattere` is a constructor function that takes a pattern.

```javascript
var metacarattere = function(pattern) { /*...*/ }
```

If no pattern is given, the created object will not match
any URL so that `matches()` will always return `false` and `parse()` will
always return `null`.
However, it won't throw any exception.

### Match an URL

The `matches()` function can be used to test if the given URL matches
the object's pattern.

```javascript
var metacarattere = require('metacarattere');

var pattern = new metacarattere("/api/:version/:collection/:store/:resource");

pattern.matches('/api/v1/users/max/card');          // true
pattern.matches('/api/v2/store/users/max/card');    // false
pattern.matches();                                  // false
pattern.matches('');                                // false
```

### Parse an URL

The `parse()` function takes an URL and returns an object with key-value-mappings
if the URL matches the pattern. Otherwise, `null` is returned.

```javascript
var metacarattere = require('metacarattere');

var pattern = new metacarattere("/api/:version/:collection/:store/:resource");
var pretty = function(obj) { return JSON.stringify(obj, null, 4); };
var values;

values = pattern.parse('/api/v1/users/max/card');
console.log( pretty(values) );
/*
{
    "version": "v1",
    "collection": "users",
    "store": "max",
    "resource": "card"
}
*/

values = pattern.parse('/api/v1/users/max');
console.log( values );
/*
null
*/

values = pattern.parse('/api/v7.9/cloud/files/database');
console.log( pretty(values) );
/*
{
    "version": "v7.9",
    "collection": "cloud",
    "store": "files",
    "resource": "database"
}
*/
```

### Replace placeholders
If you need to replace placeholders of the pattern with values you can use the
`.build()` function. Given an object with key-value-mappings it will return a
new pattern with replaced values. This also works with partly replacements.

```javascript
var m     = new metacarattere('/:service/:name/:version');
var api   = new metacarattere( m.build({'service':'api'}) );
var apiV2 = new metacarattere( api.build({'version': 'v2'}) );

api.getPattern();   // /api/:name/:version
apiV2.getPattern(); // /api/:name/:v2
```

`.build()` will return `null` if the pattern is invalid or if you do not submit a valid object.

### Get the pattern

The original pattern given to the constructor function can be retrieved using the
`getPattern()` function.

```javascript
new metacarattere('/api/:version/:document').getPattern();  // '/api/:version/:document'
new metacarattere().getPattern();   // undefined
new metacarattere(null).getPattern();   // null
```

### Get the placeholders
The placeholders defined in the pattern can be accessed using `getPlaceholders()`.

```javascript
new metacarattere('/api/:version/:document').getPlaceholders();  // ['version','document']
new metacarattere().getPlaceholders();  // [ ]
new metacarattere(null).getPlaceholders();   // [ ]
```

### Get the compiled expression
If it is required to get the compiled regular expression for the pattern the
`getExpression()` can be used to get it.

```javascript
new metacarattere('/:version/:key/:abc').getExpression();       // ^/([^\/]+)/([^\/]+)/([^\/]+)$
new metacarattere('').getExpression();  // ^$
new metacarattere().getExpression();    // ^(?!)$
```

## Naming

metacarattere is the Italian word for *Wild card*.

## Try it

There is a [JSBin](http://jsbin.com/setuzu/edit?js,console) that automatically
uses the latest version of metacarattere and can be used to play around with it.


text:
import {
  app,
  Menu,
  MenuItemConstructorOptions,
  session,
  shell,
} from 'electron';

import { isLinux, isMac, isWindowsOS } from '../common/env';
import { i18n, LocaleType } from '../common/i18n';
import { logger } from '../common/logger';
import {
  analytics,
  AnalyticsActions,
  AnalyticsElements,
  MenuActionTypes,
} from './analytics-handler';
import { autoLaunchInstance as autoLaunch } from './auto-launch-controller';
import { CloudConfigDataTypes, config, IConfig } from './config-handler';
import { gpuRestartDialog, titleBarChangeDialog } from './dialog-handler';
import { exportCrashDumps, exportLogs } from './reports-handler';
import {
  registerConsoleMessages,
  unregisterConsoleMessages,
  updateAlwaysOnTop,
} from './window-actions';
import { ICustomBrowserWindow, windowHandler } from './window-handler';
import { reloadWindow, windowExists, zoomIn, zoomOut } from './window-utils';

export const menuSections = {
  about: 'about',
  edit: 'edit',
  view: 'view',
  window: 'window',
  help: 'help',
};

const windowsAccelerator = {
  ...{
    close: 'Ctrl+W',
    copy: 'Ctrl+C',
    cut: 'Ctrl+X',
    minimize: 'Ctrl+M',
    paste: 'Ctrl+V',
    pasteAndMatchStyle: 'Ctrl+Shift+V',
    redo: 'Ctrl+Y',
    resetZoom: 'Ctrl+0',
    selectAll: 'Ctrl+A',
    togglefullscreen: 'F11',
    undo: 'Ctrl+Z',
    zoomIn: 'Ctrl+=',
    zoomOut: 'Ctrl+-',
  },
};

const macAccelerator = {
  ...{
    zoomIn: 'CommandOrControl+Plus',
    zoomOut: 'CommandOrControl+-',
  },
};

let {
  minimizeOnClose,
  launchOnStartup,
  alwaysOnTop: isAlwaysOnTop,
  bringToFront,
  memoryRefresh,
  isCustomTitleBar,
  devToolsEnabled,
} = config.getConfigFields([
  'minimizeOnClose',
  'launchOnStartup',
  'alwaysOnTop',
  'bringToFront',
  'memoryRefresh',
  'isCustomTitleBar',
  'devToolsEnabled',
]) as IConfig;
let initialAnalyticsSent = false;

const menuItemsArray = Object.keys(menuSections)
  .map((key) => menuSections[key])
  .filter((value) => (isMac ? true : value !== menuSections.about));

export class AppMenu {
  private menu: Electron.Menu | undefined;
  private menuList: Electron.MenuItemConstructorOptions[];
  private locale: LocaleType;
  private cloudConfig: IConfig | {};

  private readonly menuItemConfigFields: string[];
  private disableGpu: boolean;
  private enableRendererLogs: boolean;

  constructor() {
    this.menuList = [];
    this.locale = i18n.getLocale();
    this.menuItemConfigFields = [
      'minimizeOnClose',
      'launchOnStartup',
      'alwaysOnTop',
      'bringToFront',
      'memoryRefresh',
      'isCustomTitleBar',
      'devToolsEnabled',
    ];
    this.cloudConfig = config.getFilteredCloudConfigFields(
      this.menuItemConfigFields,
    );
    this.disableGpu = config.getConfigFields(['disableGpu']).disableGpu;
    this.enableRendererLogs = config.getConfigFields([
      'enableRendererLogs',
    ]).enableRendererLogs;
    this.buildMenu();
    // send initial analytic
    if (!initialAnalyticsSent) {
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.MINIMIZE_ON_CLOSE,
        minimizeOnClose === CloudConfigDataTypes.ENABLED,
      );
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.AUTO_LAUNCH_ON_START_UP,
        launchOnStartup === CloudConfigDataTypes.ENABLED,
      );
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.ALWAYS_ON_TOP,
        isAlwaysOnTop === CloudConfigDataTypes.ENABLED,
      );
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.FLASH_NOTIFICATION_IN_TASK_BAR,
        bringToFront === CloudConfigDataTypes.ENABLED,
      );
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.REFRESH_APP_IN_IDLE,
        memoryRefresh === CloudConfigDataTypes.ENABLED,
      );
      this.sendAnalytics(
        AnalyticsElements.MENU,
        MenuActionTypes.HAMBURGER_MENU,
        isMac || isLinux
          ? false
          : isCustomTitleBar === CloudConfigDataTypes.ENABLED,
      );
    }
    initialAnalyticsSent = true;
  }

  /**
   * Builds the menu items for all the menu
   */
  public buildMenu(): void {
    // updates the global variables
    this.updateGlobals();

    this.menuList = menuItemsArray.reduce(
      (map: Electron.MenuItemConstructorOptions, key: string) => {
        map[key] = this.buildMenuKey(key);
        return map;
      },
      this.menuList || {},
    );

    const template = Object.keys(this.menuList).map(
      (key) => this.menuList[key],
    );

    this.menu = Menu.buildFromTemplate(template);
    logger.info(`app-menu: built menu from the provided template`);
    Menu.setApplicationMenu(this.menu);
    logger.info(`app-menu: set application menu`);

    // Remove the default menu for window
    // as we use custom popup menu
    if (isWindowsOS) {
      const mainWindow = windowHandler.getMainWindow();
      if (mainWindow && windowExists(mainWindow)) {
        mainWindow.setMenuBarVisibility(false);
      }
    }
  }

  /**
   * Rebuilds the application menu on locale changes
   *
   * @param locale {LocaleType}
   */
  public update(locale: LocaleType): void {
    if (this.locale !== locale) {
      logger.info(`app-menu: updating the menu for locale ${locale}`);
      this.buildMenu();
      this.locale = locale;
    }
  }

  /**
   * Updates the global variables
   */
  public updateGlobals(): void {
    const configData = config.getConfigFields(
      this.menuItemConfigFields,
    ) as IConfig;
    minimizeOnClose = configData.minimizeOnClose;
    launchOnStartup = configData.launchOnStartup;
    isAlwaysOnTop = configData.alwaysOnTop;
    bringToFront = configData.bringToFront;
    memoryRefresh = configData.memoryRefresh;
    isCustomTitleBar = configData.isCustomTitleBar;
    devToolsEnabled = configData.devToolsEnabled;

    // fetch updated cloud config
    this.cloudConfig = config.getFilteredCloudConfigFields(
      this.menuItemConfigFields,
    );
  }

  /**
   * Displays popup application at the x,y coordinates
   *
   * @param opts {Electron.PopupOptions}
   */
  public popupMenu(opts: Electron.PopupOptions): void {
    if (!this.menu) {
      logger.error(`app-menu: tried popup menu, but failed, menu not defined`);
      return;
    }
    this.menu.popup(opts);
  }

  /**
   * Builds menu items based on key provided
   *
   * @param key {string}
   */
  public buildMenuKey(key: string): Electron.MenuItemConstructorOptions {
    switch (key) {
      case menuSections.about:
        return this.buildAboutMenu();
      case menuSections.edit:
        return this.buildEditMenu();
      case menuSections.view:
        return this.buildViewMenu();
      case menuSections.window:
        return this.buildWindowMenu();
      case menuSections.help:
        return this.buildHelpMenu();
      default:
        throw new Error(`app-menu: Invalid ${key}`);
    }
  }

  /**
   * Builds menu items for about symphony section
   */
  private buildAboutMenu(): Electron.MenuItemConstructorOptions {
    logger.info(`app-menu: building about menu`);
    return {
      id: menuSections.about,
      label: app.getName(),
      submenu: [
        {
          label: i18n.t('About Symphony')(),
          click(_menuItem, focusedWindow) {
            const windowName = focusedWindow
              ? (focusedWindow as ICustomBrowserWindow).winName
              : '';
            windowHandler.createAboutAppWindow(windowName);
          },
        },
        this.buildSeparator(),
        { label: i18n.t('Services')(), role: 'services' },
        this.buildSeparator(),
        { label: i18n.t('Hide Symphony')(), role: 'hide' },
        { label: i18n.t('Hide Others')(), role: 'hideOthers' },
        { label: i18n.t('Show All')(), role: 'unhide' },
        this.buildSeparator(),
        { label: i18n.t('Quit Symphony')(), role: 'quit' },
      ],
    };
  }

  /**
   * Builds menu items for edit section
   */
  private buildEditMenu(): Electron.MenuItemConstructorOptions {
    logger.info(`app-menu: building edit menu`);
    const menu = {
      label: i18n.t('Edit')(),
      submenu: [
        this.assignRoleOrLabel({ role: 'undo', label: i18n.t('Undo')() }),
        this.assignRoleOrLabel({ role: 'redo', label: i18n.t('Redo')() }),
        this.buildSeparator(),
        this.assignRoleOrLabel({ role: 'cut', label: i18n.t('Cut')() }),
        this.assignRoleOrLabel({ role: 'copy', label: i18n.t('Copy')() }),
        this.assignRoleOrLabel({ role: 'paste', label: i18n.t('Paste')() }),
        this.assignRoleOrLabel({
          role: 'pasteAndMatchStyle',
          label: i18n.t('Paste and Match Style')(),
        }),
        this.assignRoleOrLabel({ role: 'delete', label: i18n.t('Delete')() }),
        this.assignRoleOrLabel({
          role: 'selectAll',
          label: i18n.t('Select All')(),
        }),
      ],
    };

    if (isMac) {
      menu.submenu.push(this.buildSeparator(), {
        label: i18n.t('Speech')(),
        submenu: [
          { label: i18n.t('Start Speaking')(), role: 'startSpeaking' },
          { label: i18n.t('Stop Speaking')(), role: 'stopSpeaking' },
        ],
      });
    }
    return menu;
  }

  /**
   * Builds menu items for view section
   */
  private buildViewMenu(): Electron.MenuItemConstructorOptions {
    logger.info(`app-menu: building view menu`);

    const zoomInAccelerator = isMac
      ? macAccelerator.zoomIn
      : isWindowsOS || isLinux
      ? windowsAccelerator.zoomIn
      : '';
    const zoomOutAccelerator = isMac
      ? macAccelerator.zoomOut
      : isWindowsOS || isLinux
      ? windowsAccelerator.zoomOut
      : '';
    return {
      label: i18n.t('View')(),
      submenu: [
        {
          accelerator: 'CmdOrCtrl+R',
          click: (_item, focusedWindow) =>
            focusedWindow
              ? reloadWindow(focusedWindow as ICustomBrowserWindow)
              : null,
          label: i18n.t('Reload')(),
        },
        this.buildSeparator(),
        this.assignRoleOrLabel({
          role: 'resetZoom',
          label: i18n.t('Actual Size')(),
        }),
        this.zoomMenuBuilder(zoomInAccelerator, 'Zoom In', zoomIn, 'zoomIn'),
        this.zoomMenuBuilder(
          zoomOutAccelerator,
          'Zoom Out',
          zoomOut,
          'zoomOut',
        ),
        this.buildSeparator(),
        this.assignRoleOrLabel({
          role: 'togglefullscreen',
          label: i18n.t('Toggle Full Screen')(),
        }),
      ],
    };
  }

  /**
   * Builds menu items for window section
   */
  private buildWindowMenu(): Electron.MenuItemConstructorOptions {
    logger.info(`app-menu: building window menu`);

    const {
      alwaysOnTop: isAlwaysOnTopCC,
      minimizeOnClose: minimizeOnCloseCC,
      launchOnStartup: launchOnStartupCC,
      bringToFront: bringToFrontCC,
      memoryRefresh: memoryRefreshCC,
      isCustomTitleBar: isCustomTitleBarCC,
    } = this.cloudConfig as IConfig;

    const submenu: MenuItemConstructorOptions[] = [
      this.assignRoleOrLabel({ role: 'minimize', label: i18n.t('Minimize')() }),
      this.assignRoleOrLabel({ role: 'close', label: i18n.t('Close')() }),
      this.buildSeparator(),
      {
        checked: launchOnStartup === CloudConfigDataTypes.ENABLED,
        click: async (item) => {
          if (item.checked) {
            autoLaunch.enableAutoLaunch();
          } else {
            autoLaunch.disableAutoLaunch();
          }
          launchOnStartup = item.checked
            ? CloudConfigDataTypes.ENABLED
            : CloudConfigDataTypes.NOT_SET;
          await config.updateUserConfig({ launchOnStartup });
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.AUTO_LAUNCH_ON_START_UP,
            item.checked,
          );
        },
        label: i18n.t('Auto Launch On Startup')(),
        type: 'checkbox',
        visible: !isLinux,
        enabled:
          !launchOnStartupCC ||
          launchOnStartupCC === CloudConfigDataTypes.NOT_SET,
      },
      {
        checked: isAlwaysOnTop === CloudConfigDataTypes.ENABLED,
        click: async (item) => {
          isAlwaysOnTop = item.checked
            ? CloudConfigDataTypes.ENABLED
            : CloudConfigDataTypes.NOT_SET;
          await updateAlwaysOnTop(item.checked, true);
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.ALWAYS_ON_TOP,
            item.checked,
          );
        },
        label: i18n.t('Always on Top')(),
        type: 'checkbox',
        visible: !isLinux,
        enabled:
          !isAlwaysOnTopCC || isAlwaysOnTopCC === CloudConfigDataTypes.NOT_SET,
      },
      {
        checked: minimizeOnClose === CloudConfigDataTypes.ENABLED,
        click: async (item) => {
          minimizeOnClose = item.checked
            ? CloudConfigDataTypes.ENABLED
            : CloudConfigDataTypes.NOT_SET;
          await config.updateUserConfig({ minimizeOnClose });
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.MINIMIZE_ON_CLOSE,
            item.checked,
          );
        },
        label: i18n.t('Minimize on Close')(),
        type: 'checkbox',
        enabled:
          !minimizeOnCloseCC ||
          minimizeOnCloseCC === CloudConfigDataTypes.NOT_SET,
      },
      {
        checked: bringToFront === CloudConfigDataTypes.ENABLED,
        click: async (item) => {
          bringToFront = item.checked
            ? CloudConfigDataTypes.ENABLED
            : CloudConfigDataTypes.NOT_SET;
          await config.updateUserConfig({ bringToFront });
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.FLASH_NOTIFICATION_IN_TASK_BAR,
            item.checked,
          );
        },
        label: isWindowsOS
          ? i18n.t('Flash Notification in Taskbar')()
          : i18n.t('Bring to Front on Notifications')(),
        type: 'checkbox',
        enabled:
          !bringToFrontCC || bringToFrontCC === CloudConfigDataTypes.NOT_SET,
      },
      this.buildSeparator(),
      {
        label:
          isCustomTitleBar === CloudConfigDataTypes.DISABLED ||
          isCustomTitleBar === CloudConfigDataTypes.NOT_SET
            ? i18n.t('Enable Hamburger menu')()
            : i18n.t('Disable Hamburger menu')(),
        visible: isWindowsOS,
        click: () => {
          titleBarChangeDialog(
            isCustomTitleBar === CloudConfigDataTypes.DISABLED
              ? CloudConfigDataTypes.ENABLED
              : CloudConfigDataTypes.DISABLED,
          );
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.HAMBURGER_MENU,
            isCustomTitleBar === CloudConfigDataTypes.ENABLED,
          );
        },
        enabled:
          !isCustomTitleBarCC ||
          isCustomTitleBarCC === CloudConfigDataTypes.NOT_SET,
      },
      {
        checked: memoryRefresh === CloudConfigDataTypes.ENABLED,
        click: async (item) => {
          memoryRefresh = item.checked
            ? CloudConfigDataTypes.ENABLED
            : CloudConfigDataTypes.NOT_SET;
          await config.updateUserConfig({ memoryRefresh });
          this.sendAnalytics(
            AnalyticsElements.MENU,
            MenuActionTypes.REFRESH_APP_IN_IDLE,
            item.checked,
          );
        },
        label: i18n.t('Refresh app when idle')(),
        type: 'checkbox',
        enabled:
          !memoryRefreshCC || memoryRefreshCC === CloudConfigDataTypes.NOT_SET,
      },
      {
        click: async (_item, focusedWindow) => {
          if (focusedWindow && !focusedWindow.isDestroyed()) {
            const defaultSession = session.defaultSession;
            if (defaultSession) {
              await defaultSession.clearCache();
              reloadWindow(focusedWindow as ICustomBrowserWindow);
            }
          }
        },
        label: i18n.t('Clear cache and Reload')(),
      },
      this.buildSeparator(),
    ];

    if (isWindowsOS) {
      submenu.push({
        role: 'quit',
        visible: isWindowsOS,
        label: i18n.t('Quit Symphony')(),
      });
    }

    return {
      label: i18n.t('Window')(),
      role: 'window',
      submenu,
    };
  }

  /**
   * Builds menu items for help section
   */
  private buildHelpMenu(): Electron.MenuItemConstructorOptions {
    logger.info(`app-menu: building help menu`);
    let showLogsLabel: string = i18n.t('Show Logs in Explorer')();
    if (isMac) {
      showLogsLabel = i18n.t('Show Logs in Finder')();
    }
    if (isLinux) {
      showLogsLabel = i18n.t('Show Logs in File Manager')();
    }

    let showCrashesLabel: string = i18n.t('Show crash dump in Explorer')();
    if (isMac) {
      showCrashesLabel = i18n.t('Show crash dump in Finder')();
    }
    if (isLinux) {
      showCrashesLabel = i18n.t('Show crash dump in File Manager')();
    }
    const { devToolsEnabled: isDevToolsEnabledCC } = this
      .cloudConfig as IConfig;

    return {
      label: i18n.t('Help')(),
      role: 'help',
      submenu: [
        {
          click: () => shell.openExternal(i18n.t('Help Url')()),
          label: i18n.t('Symphony Help')(),
        },
        {
          click: () => shell.openExternal(i18n.t('Symphony Url')()),
          label: i18n.t('Learn More')(),
        },
        {
          label: i18n.t('Troubleshooting')(),
          submenu: [
            {
              click: async () => exportLogs(),
              label: showLogsLabel,
            },
            {
              click: () => exportCrashDumps(),
              label: showCrashesLabel,
            },
            {
              label: i18n.t('Toggle Developer Tools')(),
              accelerator: isMac ? 'Alt+Command+I' : 'Ctrl+Shift+I',
              visible:
                (typeof isDevToolsEnabledCC === 'boolean' &&
                  isDevToolsEnabledCC) ||
                devToolsEnabled,
              click(_item, focusedWindow) {
                if (!focusedWindow || !windowExists(focusedWindow)) {
                  return;
                }
                if (devToolsEnabled) {
                  focusedWindow.webContents.toggleDevTools();
                  return;
                }
              },
            },
            {
              label: this.disableGpu
                ? i18n.t('Enable GPU')()
                : i18n.t('Disable GPU')(),
              click: () => {
                gpuRestartDialog(!this.disableGpu);
              },
            },
            {
              label: i18n.t('Enable Renderer Logs')(),
              type: 'checkbox',
              checked: this.enableRendererLogs,
              click: async () => {
                if (this.enableRendererLogs) {
                  this.enableRendererLogs = false;
                  unregisterConsoleMessages();
                } else {
                  this.enableRendererLogs = true;
                  registerConsoleMessages();
                }
                const enableRendererLogs = this.enableRendererLogs;
                await config.updateUserConfig({ enableRendererLogs });
                logger.info(
                  'New value for enableRendererLogs: ' +
                    this.enableRendererLogs,
                );
              },
            },
          ],
        },
        {
          label: i18n.t('About Symphony')(),
          visible: isWindowsOS || isLinux,
          click(_menuItem, focusedWindow) {
            const windowName = focusedWindow
              ? (focusedWindow as ICustomBrowserWindow).winName
              : '';
            windowHandler.createAboutAppWindow(windowName);
          },
        },
      ],
    };
  }

  /**
   * Builds menu item separator
   */
  private buildSeparator(): Electron.MenuItemConstructorOptions {
    return { type: 'separator' };
  }

  /**
   * Sets respective accelerators w.r.t roles for the menu template
   *
   * @param role {String} The action of the menu item
   * @param label {String} Menu item name
   * @return {Object}
   * @return {Object}.role The action of the menu item
   * @return {Object}.accelerator keyboard shortcuts and modifiers
   */
  private assignRoleOrLabel({
    role,
    label,
  }: MenuItemConstructorOptions): MenuItemConstructorOptions {
    logger.info(
      `app-menu: assigning role & label respectively for ${role} & ${label}`,
    );
    if (isLinux) {
      return label ? { role, label } : { role };
    }

    if (isMac) {
      return label
        ? { role, label, accelerator: role ? macAccelerator[role] : '' }
        : { role, accelerator: role ? macAccelerator[role] : '' };
    }

    if (isWindowsOS) {
      return label
        ? { role, label, accelerator: role ? windowsAccelerator[role] : '' }
        : { role, accelerator: role ? windowsAccelerator[role] : '' };
    }

    return label ? { role, label } : { role };
  }

  /**
   * Sends analytics events
   *
   * @param element {AnalyticsElements}
   * @param type {MenuActionTypes}
   * @param result {Boolean}
   */
  private sendAnalytics(
    element: AnalyticsElements,
    type: MenuActionTypes,
    result: boolean,
  ): void {
    analytics.track({
      element,
      action_type: type,
      action_result: result
        ? AnalyticsActions.ENABLED
        : AnalyticsActions.DISABLED,
    });
  }

  /**
   * Build zoom menu for view section
   */
  private zoomMenuBuilder(
    accelerator: string,
    label: string,
    action: () => void,
    role: MenuItemConstructorOptions['role'],
  ): MenuItemConstructorOptions {
    if (windowHandler.isMana) {
      return {
        accelerator,
        label: i18n.t(label)(),
        click: (_item, focusedWindow) => (focusedWindow ? action() : null),
      };
    } else {
      return this.assignRoleOrLabel({ role, label: i18n.t(label)() });
    }
  }
}


text:
<!doctype html>
<html>
	<head>
        <title></title>
	</head>
<body>

    <!--ko with:One-->
    <input type="text" data-bind="value: Name, valueUpdate:'afterkeydown'" placeholder="First name">
    <input type="text" data-bind="value: LastName, valueUpdate:'afterkeydown'" placeholder="First name">
    <!--/ko -->
    <!--ko with:Two-->
    <input type="text" data-bind="value: Name, valueUpdate:'afterkeydown'" placeholder="First name">
    <input type="text" data-bind="value: LastName, valueUpdate:'afterkeydown'" placeholder="First name">
    <!--/ko -->

    <button data-bind="command: MakeSelf">MakeSelf</button>
    <button data-bind="command: Duplicate">Duplicate</button>
</body>

</html>


text:
using namespace sql;
JournalConferenceInfo::JournalConferenceInfo()
{
	//do nothing
}

JournalConferenceInfo::JournalConferenceInfo(int _ID, string& _name, double _score, int _index, double _percent, string& _alias)
	:ID(_ID),
	name(_name),
	score(_score),
	index(_index),
	percent(_percent),
	alias(_alias)
{
}

JConfMap::JConfMap()
{

	load();
	this->loadImpact();
}
JConfMap::~JConfMap()
{

}
JConfMap* JConfMap::getInstance()
{
	static JConfMap instance;

	return &instance;
}

string JConfMap::getName(int id)
{
	if(id != -1)
	{
		auto iter = jconfhash.find(id);

		if(iter == jconfhash.end())
		{
			return "";
		}
		return iter->second->name;
	}
	return "";
}

string JConfMap::getAlias(int id)
{
	if(id != -1)
	{
		auto iter = jconfhash.find(id);

		if(iter == jconfhash.end())
		{
			return "";
		}
		return iter->second->alias;
	}
	else
		return "";
}

double JConfMap::getScore(int id)
{
	if(id != -1)
	{
		auto iter = jconfhash.find(id);

		if(iter == jconfhash.end())
		{
			return 0.0;
		}
		return iter->second->score;
	}
	else
		return 0.0;
}

double JConfMap::getScoreByName(const string& name)
{
	int id = getIdByName(name);
	return getScore(id);
}

int JConfMap::getIdByName(string name)
{
	strutils::trim(name);
	if(name.length()>0)
	{
		strutils::to_lower(name);
		auto iter = jconfnamehash.find(name);

		if(iter!= jconfnamehash.end())
		{
			return iter->second->ID;
		}
		else
			return -1;
	}
	else
	{
		return -1;
	}
}

bool JConfMap::containsConf(string name)
{
	strutils::trim(name);
	if(name.length()==0)
		return false;
	auto iter = jconfnamehash.find(name);

	if(iter!= jconfnamehash.end())
	{
		return true;
	}
	else
	{
		return false;
	}
}

JournalConferenceInfo* JConfMap::getJConf(int id)
{
	if(id != -1)
	{
		auto iter = jconfhash.find(id);

		if(iter == jconfhash.end())
		{
			return NULL;
		}
		return iter->second;
	}
	else
		return NULL;
}

int JConfMap::getSize()
{
	return jconfhash.size();
}

void JConfMap::destroy()
{
	for (auto iter = jconfhash.begin(); iter != jconfhash.end(); ++iter)
	{
		delete iter->second;
	}
}

double JConfMap::getImpact(int id)
{
	auto iter = this->impact_factor.find(id);
	if(iter != this->impact_factor.end())
		return iter->second;
	return 0.0;
}

void JConfMap::load()
{
	Connection* conn = NULL;
	Statement *stmt = NULL;
	ResultSet* rs = NULL;

	try
	{
		conn = ConnectionPool::getInstance()->getConnection();
		stmt = conn->createStatement();

		rs = stmt->executeQuery(this->sql);
		int id = -1;
		size_t count;
		string name;
		string alias;
		double score = 0.0;

		typedef pair<int, JournalConferenceInfo*> Int_JConf;
		typedef pair<string, JournalConferenceInfo*> Str_JConf;

		// rehash to prevent memory copy
		count = rs->rowsCount();
		this->jconfhash.rehash(count);
		this->jconfnamehash.rehash(count);

		while(rs->next())
		{
			id = rs->getInt(1);
			name = rs->getString(2);
			alias = rs->getString(3);
			score = rs->getDouble(4);
			if(score<0.05)
				score = 0.05;
			JournalConferenceInfo* jconf = new JournalConferenceInfo(id, name, score, -1, 0.0, alias);
			jconfhash.insert(Int_JConf(id, jconf));

			strutils::trim(name);
			strutils::to_lower(name);
			jconfnamehash.insert(Str_JConf(name, jconf));

			strutils::trim(alias);
			if(alias.length()>0)
			{
				strutils::to_lower(alias);
				jconfnamehash.insert(Str_JConf(alias, jconf));
			}
		}
		ConnectionPool::close(conn,stmt,rs);
	}
	catch (sql::SQLException &e)
	{
		LOG(ERROR) << boost::str(boost::format("# ERR: SQLException in  %1% %2%") % __FILE__ %__FUNCTION__);
		LOG(ERROR) << boost::str(boost::format("%1% error code %2%") %e.what() % e.getErrorCode());
	}
	LOG(INFO) << boost::str(boost::format("JConfMap init finish Size: %1%") % jconfhash.size());
}

void JConfMap::loadImpact()
{
	Connection* conn = NULL;
	Statement *stmt = NULL;
	ResultSet* rs = NULL;
	string sql_str("select conf_id, score from conference_rank where year=0 and (type=5 or type=6)");
	try
	{
		conn = ConnectionPool::getInstance()->getConnection();
		stmt = conn->createStatement();

		rs = stmt->executeQuery(sql_str);

		// rehash to prevent memory copy
		size_t count = rs->rowsCount();
		this->impact_factor.rehash(count);

		while(rs->next())
		{
			this->impact_factor[rs->getInt(1)]=rs->getDouble(2);
		}
		ConnectionPool::close(conn,stmt,rs);
	}
	catch (sql::SQLException &e)
	{
		LOG(ERROR) << boost::str(boost::format("# ERR: SQLException in  %1% %2%") % __FILE__ %__FUNCTION__);
		LOG(ERROR) << boost::str(boost::format("%1% error code %2%") %e.what() % e.getErrorCode());
	}
	LOG(INFO) << boost::str(boost::format("JConfMap Impact factor init finish Size: %1%") % impact_factor.size());
}

bool JConfMap::getConfWithPrefix(vector<JournalConferenceInfo*>& results, string prefix)
{
	if(prefix.empty() || prefix[0]=='#')
	{
		for (auto pair : jconfhash)
		{
			results.push_back(pair.second);
		}
		goto end;
	}

	//deal with
	if(prefix[0]=='!')
	{
		for (auto pair : jconfnamehash)
		{
			if(!((pair.first[0]>='0'&&pair.first[0]<='9')||(pair.first[0]>='a'&&pair.first[0]<='z')||(pair.first[0]>='A'&&pair.first[0]<='Z')))
			{
				results.push_back(pair.second);
			}
		}
		goto end;
	}

	boost::to_lower(prefix);
	for (auto pair : jconfnamehash)
	{
		if(boost::starts_with(boost::to_lower_copy(pair.first), prefix))
		{
			results.push_back(pair.second);
		}
	}
end:
	return true;
}

const string JConfMap::tableName("jconf");
const string JConfMap::sql("select id, name, alias, score from jconf");


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin_model extends CI_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->database('joyo_admin');
	}

	function get_admin_by_username($username) {
		$sql = "SELECT id, username, password, opTime, isAdmin FROM admin WHERE username = ? LIMIT 1";

		$query = $this->db->query($sql, array($username));

		$data =  $query->result_object();

		if (empty($data)) {
			return NULL;
		} else {
			return $data[0];
		}
	}

	public function get_admin_list() {
		$sql = "SELECT id, username, password, opTime, isAdmin FROM admin WHERE username != 'admin'";
		$query = $this->db->query($sql);
		return $query->result_object();
	}

	public function save_user($data) {
		return $this->db->insert('admin', $data);
	}

	public function delete_admin($username) {
		$this->db->where('username', $username);
		return $this->db->delete('admin');
	}

	public function update_admin($username, $data) {
		$this->db->where('username', $username);
		return $this->db->update('admin', $data);
	}
}
/* End of file admin_model.php */
/* Location: ./application/models/admin_model.php */


text:
/* jslint node: true */
'use strict';

var User = require('../models/user');
var pwd = require('pwd');
var sanitize = require('sanitizer').sanitize;

function UserController(UserService) {

  // public

  function list(req, res, next) {
    UserService.find(function done(err, users) {
      if (err) {
        return next(err);
      }
      res.render('blog/admin/users', {
        title: 'Administración de usuarios',
        section:'blog',
        users: users
      });
    });
  }

  function show(req, res) {
    res.render('blog/admin/user', {
      title: 'Nuevo usuario',
      section:'blog',
      user: undefined
    });
  }

  function create(req, res, next) {
    var username = sanitize(req.body.username);
    var password = sanitize(req.body.password);

    UserService.findByUsername(username, function done(err, user) {
      if (err) {
        return next(err);
      }
      if (user) {
        return next(new Error('The user already exists'));
      }

      pwd.hash(password, function done(err, salt, hash) {
        var user = new User();

        user.username = username;
        user.salt = salt;
        user.hash = hash;

        user.save(function done(err) {
          if (err) {
            return next(err);
          }
          res.redirect('/blog/admin/users/' + user.username);
        });
      });
    });
  }

  function retrieve(req, res, next) {
    var username = req.params.username ? req.params.username[0] : null;

    UserService.findByUsername(username, function done(err, user) {
      if (err) {
        return next(err);
      }
      res.render('blog/admin/user', {
        title: 'Edición usuario',
        section:'blog',
        user: user
      });
    });
  }

  function update(req, res, next) {
    var oldUsername = req.params.username ? req.params.username[0] : null;
    var newUsername = sanitize(req.body.username);
    var newpassword = sanitize(req.body.password);

    UserService.findByUsername(oldUsername, function done(err, user) {
      if (err) {
        return next(err);
      }

      function save(user) {
        user.save(function done(err) {
          if (err) {
            return next(err);
          }
          res.redirect('/blog/admin/users/' + user.username);
        });
      }

      user.username = newUsername;
      if (newpassword) {
        pwd.hash(newpassword, function done(err, salt, hash) {
          user.salt = salt;
          user.hash = hash;

          save(user);
        });
      } else {
        save(user);
      }
    });
  }

  // expose API
  return {
    'create': create,
    'list': list,
    'show': show,
    'retrieve': retrieve,
    'update': update
  };
}

module.exports = UserController;


text:
package org.assertj.core.api;

/**
 * Provides helper methods for navigating a list property in a generated assertion class so we can chain assertions
 * through deeply nested models more easily.
 *
 * @since 2.5.0 / 3.5.0
 */
//@format:off
public class FactoryBasedNavigableIterableAssert<SELF extends FactoryBasedNavigableIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>,
                                                 ACTUAL extends Iterable<? extends ELEMENT>,
                                                 ELEMENT,
                                                 ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
       extends AbstractIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> {
// @format:on

  private AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory;

  public FactoryBasedNavigableIterableAssert(ACTUAL actual, Class<?> selfType,
                                             AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) {
    super(actual, selfType);
    this.assertFactory = assertFactory;
  }

  @Override
  public ELEMENT_ASSERT toAssert(ELEMENT value, String description) {
    return assertFactory.createAssert(value).as(description);
  }

  @SuppressWarnings("unchecked")
  @Override
  protected SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable) {
    return (SELF) new FactoryBasedNavigableIterableAssert<>(iterable, FactoryBasedNavigableIterableAssert.class, assertFactory);
  }
}


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

		<title>jQuery lightbox clone - prettyPhoto - by Stephane Caron</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

		<link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" title="prettyPhoto main stylesheet" charset="utf-8" />

			IMAGE API CALLS: Open | Previous | Next | Close

			MIXED API CALLS: Open | Previous | Next | Close

prettyPhoto

This page has been made for testing purpose only. It covers all the basic things you can handle in prettyPhoto.

For complete documentation, please refer to the official website: http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/

		<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/zrdEHvREfdI&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="opaque"></param><embed src="http://www.youtube.com/v/zrdEHvREfdI&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344" wmode="opaque"></embed></object>

Gallery

Gallery 2

Picture alone

Flash

Flash alone

Youtube video

Vimeo video

Movies (.mov)

Movies (.mov) alone

Unusual sizes

Wide image (3000 x 1500)

High image (1500 x 3000)

Huge image (3000 x 3000)

Iframe

Google.ca

Facebook

Twitter

Mixed gallery

Google.ca

Inline content

Inline content 1

Inline content 2

Inline content 3

Google.ca

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Custom content

Google Maps

Ads


text:
#ifndef VC_COMMON_X86_PREFETCHES_H_
#define VC_COMMON_X86_PREFETCHES_H_

#include <xmmintrin.h>
#include "macros.h"

namespace Vc_VERSIONED_NAMESPACE
{
namespace Common
{

#if defined(Vc_IMPL_MIC)
static constexpr int exclusive_hint = 0x4;
#else
static constexpr int exclusive_hint = 0;
#endif

// TODO: support AMD's prefetchw with correct flags and checks via cpuid

template <typename ExclusiveOrShared = Vc::Shared>
Vc_INTRINSIC void prefetchForOneRead(const void *addr)
{
    if (std::is_same<ExclusiveOrShared, Vc::Shared>::value) {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)), _MM_HINT_NTA);
    } else {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)),
                     static_cast<decltype(_MM_HINT_NTA)>(_MM_HINT_NTA | exclusive_hint));
    }
}
template <typename ExclusiveOrShared = Vc::Shared>
Vc_INTRINSIC void prefetchClose(const void *addr)
{
    if (std::is_same<ExclusiveOrShared, Vc::Shared>::value) {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)), _MM_HINT_T0);
    } else {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)),
                     static_cast<decltype(_MM_HINT_T0)>(_MM_HINT_T0 | exclusive_hint));
    }
}
template <typename ExclusiveOrShared = Vc::Shared>
Vc_INTRINSIC void prefetchMid(const void *addr)
{
    if (std::is_same<ExclusiveOrShared, Vc::Shared>::value) {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)), _MM_HINT_T1);
    } else {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)),
                     static_cast<decltype(_MM_HINT_T1)>(_MM_HINT_T1 | exclusive_hint));
    }
}
template <typename ExclusiveOrShared = Vc::Shared>
Vc_INTRINSIC void prefetchFar(const void *addr)
{
    if (std::is_same<ExclusiveOrShared, Vc::Shared>::value) {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)), _MM_HINT_T2);
    } else {
        _mm_prefetch(static_cast<char *>(const_cast<void *>(addr)),
                     static_cast<decltype(_MM_HINT_T2)>(_MM_HINT_T2 | exclusive_hint));
    }
}

/*handlePrefetch/handleLoadPrefetches/handleStorePrefetches{{{*/
namespace
{
template<size_t L1, size_t L2, bool UseExclusivePrefetch> Vc_INTRINSIC void handlePrefetch(const void *addr_, typename std::enable_if<L1 != 0 && L2 != 0, void *>::type = nullptr)
{
    const char *addr = static_cast<const char *>(addr_);
    prefetchClose<typename std::conditional<UseExclusivePrefetch, Vc::Exclusive, Vc::Shared>::type>(addr + L1);
    prefetchMid  <typename std::conditional<UseExclusivePrefetch, Vc::Exclusive, Vc::Shared>::type>(addr + L2);
}
template<size_t L1, size_t L2, bool UseExclusivePrefetch> Vc_INTRINSIC void handlePrefetch(const void *addr_, typename std::enable_if<L1 == 0 && L2 != 0, void *>::type = nullptr)
{
    const char *addr = static_cast<const char *>(addr_);
    prefetchMid  <typename std::conditional<UseExclusivePrefetch, Vc::Exclusive, Vc::Shared>::type>(addr + L2);
}
template<size_t L1, size_t L2, bool UseExclusivePrefetch> Vc_INTRINSIC void handlePrefetch(const void *addr_, typename std::enable_if<L1 != 0 && L2 == 0, void *>::type = nullptr)
{
    const char *addr = static_cast<const char *>(addr_);
    prefetchClose<typename std::conditional<UseExclusivePrefetch, Vc::Exclusive, Vc::Shared>::type>(addr + L1);
}
template<size_t L1, size_t L2, bool UseExclusivePrefetch> Vc_INTRINSIC void handlePrefetch(const void *, typename std::enable_if<L1 == 0 && L2 == 0, void *>::type = nullptr)
{
}

template<typename Flags> Vc_INTRINSIC void handleLoadPrefetches(const void *    , Flags, typename Flags::EnableIfNotPrefetch = nullptr) {}
template<typename Flags> Vc_INTRINSIC void handleLoadPrefetches(const void *addr, Flags, typename Flags::EnableIfPrefetch    = nullptr)
{
    // load prefetches default to Shared unless Exclusive was explicitely selected
    handlePrefetch<Flags::L1Stride, Flags::L2Stride, Flags::IsExclusivePrefetch>(addr);
}

template<typename Flags> Vc_INTRINSIC void handleStorePrefetches(const void *    , Flags, typename Flags::EnableIfNotPrefetch = nullptr) {}
template<typename Flags> Vc_INTRINSIC void handleStorePrefetches(const void *addr, Flags, typename Flags::EnableIfPrefetch    = nullptr)
{
    // store prefetches default to Exclusive unless Shared was explicitely selected
    handlePrefetch<Flags::L1Stride, Flags::L2Stride, !Flags::IsSharedPrefetch>(addr);
}

} // anonymous namespace
/*}}}*/

}  // namespace Common

using Common::prefetchForOneRead;
using Common::prefetchClose;
using Common::prefetchMid;
using Common::prefetchFar;
}  // namespace Vc

#endif // VC_COMMON_X86_PREFETCHES_H_

// vim: foldmethod=marker


text:
@interface RNSegment : NSObject <RCTBridgeModule>

@end


text:
<?php

namespace App\Validation\Exceptions;

class ObjectTypeException extends ValidationException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must be an object',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not be an object',
        ],
    ];
}


text:
#ifndef _native_h_
#define _native_h_

#ifdef GENERATE_NATIVE_CODE

#include "syn68k_private.h"
#include "../native/i386/host-native.h"
#include "block.h"

/* Define a type for a bit mask for host registers.  Each host register
 * will get one bit in this mask.
 */
#if NUM_HOST_REGS <= 8
typedef uint8 host_reg_mask_t;
#elif NUM_HOST_REGS <= 16
typedef uint16 host_reg_mask_t;
#else  /* NUM_HOST_REGS > 16 */
typedef uint32 host_reg_mask_t;
#endif /* NUM_HOST_REGS > 16 */

#define NUM_GUEST_REGS 16
typedef uint16 guest_reg_mask_t;

/* This enum describes the different types of register caching requests. */
typedef enum
{
  REQUEST_REG,           /* Needs host reg, cache if necessary.         */
  REQUEST_SPARE_REG,     /* Give me any spare reg, value unimportant.   */
} request_type_t;

/* Host registers may not always be left in canonical "native" byte order.
 * For efficiency, we lazily perform certain transformations like
 * byte swapping and offsetting.  Registers in memory slots are _always_
 * in MAP_NATIVE byte order.
 */
typedef enum
{
  MAP_NATIVE,       /* Host byte order.                                */
  MAP_OFFSET,       /* Host byte order, but offset by a constant.      */
#ifdef LITTLEENDIAN
  MAP_SWAP16,       /* Host byte order but with low two bytes swapped. */
  MAP_SWAP32,       /* All four bytes are swapped.                     */
#endif  /* LITTLEENDIAN */
} value_mapping_t;

#define MAP_NATIVE_MASK (1L << MAP_NATIVE)
#define MAP_OFFSET_MASK (1L << MAP_OFFSET)
#ifdef LITTLEENDIAN
# define MAP_SWAP16_MASK (1L << MAP_SWAP16)
# define MAP_SWAP32_MASK (1L << MAP_SWAP32)
#endif  /* LITTLEENDIAN */

#ifdef LITTLEENDIAN
# define MAP_ALL_MASK \
(MAP_NATIVE_MASK | MAP_OFFSET_MASK | MAP_SWAP16_MASK | MAP_SWAP32_MASK)
#else
# define MAP_ALL_MASK (MAP_NATIVE_MASK | MAP_OFFSET_MASK)
#endif

#ifdef LITTLEENDIAN
#define ROS_DIRTY_BIT 4
#else  /* !LITTLEENDIAN */
#define ROS_DIRTY_BIT 2
#endif /* !LITTLEENDIAN */

typedef enum
{
  ROS_NATIVE       = MAP_NATIVE,
  ROS_OFFSET       = MAP_OFFSET,
#ifdef LITTLEENDIAN
  ROS_SWAP16       = MAP_SWAP16,
  ROS_SWAP32       = MAP_SWAP32,
#endif /* LITTLEENDIAN */
  ROS_NATIVE_DIRTY = MAP_NATIVE | ROS_DIRTY_BIT,
  ROS_OFFSET_DIRTY = MAP_OFFSET | ROS_DIRTY_BIT,
#ifdef LITTLEENDIAN
  ROS_SWAP16_DIRTY = MAP_SWAP16 | ROS_DIRTY_BIT,
  ROS_SWAP32_DIRTY = MAP_SWAP32 | ROS_DIRTY_BIT,
#endif /* LITTLEENDIAN */
  ROS_UNTOUCHED,
  ROS_UNTOUCHED_DIRTY,   /* Same mapping as before, but now it's dirty. */
  ROS_INVALID,
} reg_output_state_t;

/* This describes constraints for how to transform an input
 * register operand to either a host register or a pointer to the memory
 * slot for that register.  If you can't match the constraints, you can't
 * generate native code from this descriptor.
 */
typedef struct
{
#ifdef __GNUC__
  BOOL legitimate_p  :1;  /* 0 ==> dummy entry that just terminates array.  */
#else   /* !__GNUC__ */
  uint8 legitimate_p :1;
#endif  /* !__GNUC__ */
  uint8 add8_p             :1;  /* Add 8 to this operand? (address register)*/
  uint8 operand_num        :2;  /* Which operand contains the guest reg #.  */
  uint8 acceptable_mapping :4;  /* Bit mask of acceptable value_mapping_t's.*/

  /* Information about the register on input. */
#ifdef __GNUC__
  request_type_t request_type :8;  /* See above enum for what this means. */
  reg_output_state_t output_state :8;
#else   /* !__GNUC__ */
  uint8 request_type;
  uint8 output_state;
#endif  /* !__GNUC__ */

  host_reg_mask_t regset;       /* Specifies set of allowable host regs.    */
} reg_operand_info_t;

#define MAX_REG_OPERANDS 2
#define MAX_COMPILE_FUNCS 5

#define USE_SCRATCH_REG       (-1)
#define USE_BLOCK             (-2)
#define USE_ZERO              (-3)
#define USE_MINUS_ONE         (-4)
#define USE_M68K_PC           (-5)
#define USE_M68K_PC_PLUS_TWO  (-6)
#define USE_M68K_PC_PLUS_FOUR (-7)
#define USE_0xFFFF            (-8)

#define MAX_M68K_OPERANDS 4

typedef struct
{
  int8 operand_num[MAX_M68K_OPERANDS];
} oporder_t;

typedef struct
{
#ifdef RUNTIME
  int (*func)();   /* Returns nonzero->abort. */
#else  /* !RUNTIME */
  char *func;
#endif /* !RUNTIME */
  oporder_t order;
} compile_func_t;

typedef struct _guest_code_descriptor_t
{
#ifndef RUNTIME
  const char *name;    /* Used while programmatically generating these. */
  BOOL static_p;
#endif
  reg_operand_info_t reg_op_info[MAX_REG_OPERANDS + 1];
  uint8 cc_in;                  /* Bit mask: must be cached on input.    */
  uint8 cc_out;                 /* Bit mask: valid & cached on output.   */
  host_reg_mask_t scratch_reg;  /* If nonzero, allocate a scratch reg.   */
  compile_func_t compile_func[MAX_COMPILE_FUNCS];
#ifdef RUNTIME
  const
#endif
  struct _guest_code_descriptor_t *next;  /* Next in linked list. */
} guest_code_descriptor_t;

#define NO_REG (-1)

typedef struct
{
  int8 host_reg;       /* Which host register cached in, or NO_REG.          */
#ifdef __GNUC__
  value_mapping_t mapping :8; /* If cached, how to map value to canon value. */
  BOOL dirty_without_offset_p :8; /* Must be spilled even if nonzero offset? */
#else  /* !__GNUC__ */
  uint8 mapping;
  uint8 dirty_without_offset_p;
#endif /* !__GNUC__ */
  int32 offset;        /* Add to reg to get canon value if ST_OFFSET.        */
} guest_reg_status_t;

typedef struct
{
  guest_reg_status_t guest_reg_status[NUM_GUEST_REGS];
  int8 host_reg_to_guest_reg[NUM_HOST_REGS]; /* Might be NO_REG.           */
  uint8 cached_cc;    /* CC bits that are cached. */
  uint8 dirty_cc;     /* CC bits that are dirty.  */
} cache_info_t;

#define COMMON_ARGS \
cache_info_t *c, host_code_t **codep, unsigned cc_spill_if_changed, \
unsigned cc_to_compute, int scratch_reg

#define COMMON_TYPES \
cache_info_t *, host_code_t **, unsigned, unsigned, int

#define COMMON_ARG_NAMES \
c, codep, cc_spill_if_changed, cc_to_compute, scratch_reg

extern void native_code_init (void);
extern void host_native_code_init (void);
extern void host_backpatch_native_to_synth_stub (Block *b,
						 host_code_t *stub,
						 uint32 *synth_opcode);
#ifdef SYNCHRONOUS_INTERRUPTS
extern void host_backpatch_check_interrupt_stub (Block *b, host_code_t *stub);
#endif
extern BOOL generate_native_code (const guest_code_descriptor_t *first_desc,
				  cache_info_t *cache_info,
				  const int32 *orig_operands,
				  host_code_t **code,
				  uint8 cc_input, uint8 cc_live,
				  uint8 cc_to_set,
				  BOOL ends_block_p, Block *block,
				  const uint16 *m68k_code);
extern int host_setup_cached_reg (COMMON_ARGS, int guest_reg,
				  unsigned acceptable_mappings,
				  host_reg_mask_t acceptable_regs);
extern int host_movel_reg_reg (COMMON_ARGS, int32 src_reg, int32 dst_reg);

#ifndef host_alloc_reg
extern int host_alloc_reg (cache_info_t *c, host_code_t **code,
			   unsigned cc_spill_if_changed,
			   host_reg_mask_t legal);
#endif

#ifndef host_cache_reg
extern void host_cache_reg (cache_info_t *c, host_code_t **code,
			    unsigned cc_spill_if_changed,
			    int guest_reg, int host_reg);
#endif

#ifndef host_unoffset_reg
extern void host_unoffset_reg (cache_info_t *c, host_code_t **code,
			       unsigned cc_spill_if_changed,
			       int guest_reg);
#endif

#ifndef host_unoffset_regs
extern void host_unoffset_regs (cache_info_t *c, host_code_t **code,
				unsigned cc_spill_if_changed);
#endif

#ifndef host_spill_reg
extern inline void host_spill_reg (cache_info_t *c, host_code_t **code,
				   unsigned cc_dont_touch, int guest_reg);
#endif

#ifndef host_spill_regs
extern void host_spill_regs (cache_info_t *c, host_code_t **code,
			     unsigned cc_spill_if_changed);
#endif

#ifndef host_spill_cc_bits
extern void host_spill_cc_bits (cache_info_t *c, host_code_t **code,
				unsigned cc);
#endif

extern void make_dirty_regs_native (cache_info_t *c, host_code_t **codep,
				    unsigned cc_spill_if_changed);

#define SPILL_CC_BITS(c, code, cc) \
     do { if (cc) host_spill_cc_bits (c, code, cc); } while (0)

#ifdef LITTLEENDIAN
extern int host_swap16       (COMMON_ARGS, int32 host_reg);
extern int host_swap16_to_32 (COMMON_ARGS, int32 host_reg);
extern int host_swap32       (COMMON_ARGS, int32 host_reg);
extern int host_swap32_to_16 (COMMON_ARGS, int32 host_reg);
#else  /* !LITTLEENDIAN */
#define host_swap16(COMMON_ARG_NAMES)        0
#define host_swap16_to_32(COMMON_ARG_NAMES)  0
#define host_swap32(COMMON_ARG_NAMES)        0
#define host_swap32_to_16(COMMON_ARG_NAMES)  0
#endif /* !LITTLEENDIAN */

#define HOST_CODE_T_BITS (sizeof (host_code_t) * 8)

extern cache_info_t empty_cache_info;

#define NATIVE_START_BYTE_OFFSET   (sizeof (void *) + sizeof (Block *))
#define NATIVE_CODE_TRIED(b) \
  (*(Block **)((b)->compiled_code + PTR_WORDS) == NULL)

extern host_code_t native_to_synth_stub[];

#ifdef SYNCHRONOUS_INTERRUPTS
extern host_code_t check_interrupt_stub[];
#endif

#define NATIVE_PREAMBLE_WORDS \
((((CHECK_INTERRUPT_STUB_BYTES + NATIVE_TO_SYNTH_STUB_BYTES + 1) / 2) + 1) \
 & ~1)

#endif  /* GENERATE_NATIVE_CODE */

#endif  /* !native_h_ */


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>An Exploration in Clam Gardens</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                Clam Gardens

                Home

                About

                Understanding Clam Gardens

                Clam Gardens and Archaeology

                Clam Gardens, Culture and Community

                Locating Clam Gardens

                Glossary

Clam Gardens:

An Exploration of Shellfish Mariculture on the Northwest Coast of North America

            Find Out More

Locating Clam Gardens

Clam gardens are a highly visible archaeological feature that are still being used today. Since they are highly visible, they can be seen from satellite imaging, and therefore can be found using a program like google earth. You can download the program here for free and search for clam gardens yourself, however please remember that these features are important in many different ways, and should not be disrespected. Please exercise caution and be considerate of whose cultural property you are viewing. We hope that this will generate interest in clam gardens as well as awareness of the amount of clam gardens that exist on the coast.

 Here is a map showing regions on the southern coast of British Columbia where clam gardens have been recorded. These regions have an abundance of known clam gardens due to concentrated research efforts, however, this map does not represent the full geographic range or knowledge of clam gardens on the Northwest Coast.

 This is what a clam garden looks like from above.


text:
author: slowe
categories: Information
comments: true
date: 2011-01-20T15:16:52Z
slug: clearing-up-the-bad-reputation-of-vmwares-paravirtualized-drivers
tags:
- Networking
- Storage
- Virtualization
- VMware
- vSphere
title: Clearing Up the Bad Reputation of VMware's Paravirtualized Drivers
url: /2011/01/20/clearing-up-the-bad-reputation-of-vmwares-paravirtualized-drivers/
wordpress_id: 2222
---

In 2009, not too long after the release of VMware vSphere 4.0, I blogged about the use of PVSCSI and VMXNET3; specifically, I mentioned [reasons not to use PVSCSI and VMXNET3][1]. A lot has changed since then, so---prompted by a reader who shall remain nameless but knows who he/she is---I thought it might be prudent or useful to post a brief update.

While vSphere 4.0 did not support either PVSCSI or VMXNET3 for use with VMware Fault Tolerance (FT), those restrictions were lifted with the release of VMware vSphere 4.1. This was mentioned a couple of times in the comments to the original article, but I did want to clarify it so that readers knew for sure. For more information, see pages 35 and 36 of the [VMware vSphere 4.1 Availability Guide](http://www.vmware.com/pdf/vsphere4/r41/vsp_41_availability.pdf). PVSCSI is not explicitly called out there, but it also isn't mentioned; VMXNET3 is specifically called out as supported with VMware FT.

In addition, the recommendation against using PVSCSI with low I/O workloads was also removed with vSphere 4.1. See the brief note in the Solution section of [this VMware KB article](http://kb.vmware.com/kb/1017652).

Feel free to post any corrections or clarifications in the comments. In particular, if you have links to articles or documents with explicit mention of support for these paravirtualized drivers, feel free to share them for the benefit of all readers. Thanks!

[1]: {{< relref "2009-07-05-another-reason-not-to-use-pvscsi-or-vmxnet3.md" >}}


text:
<?php
include "base.php";
printHead();
$result = $mysqli->query("SELECT * FROM ".$prefix."Book WHERE UserID = '".$AccountID."' ORDER BY ID ASC");
?>

			Photobooks

		<form action="photobooks" method="post" class="box">

Create new Photobook:

			<input type="hidden" name="type" value="add-photobook"/>
			<input type="text" name="photobook-name" value="Photobook Name"/>
			<input type="submit" value="Create"/>
		</form>

My Photobooks

<?php
while($row = $result->fetch_object()){
	if($row->Name == ''){$row->Name = 'Unnamed Photobook';}
echo '
			ID.'" target="_blank" class="box">

'.$row->Name.'

				Bild.'" class="gallerynopic"/>

			ID.'" class="boxicon">

';
}
?>

<?php
printFoot();
?>