text:
package ru.programpark.hikari.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;

/**
 * This is the proxy class for java.sql.Statement.
 *
 * @author Brett Wooldridge
 */
abstract class GenericStatementProxy<T extends Statement> implements Statement
{

   protected static final Logger LOGGER = LoggerFactory.getLogger(GenericStatementProxy.class);
   protected final ConnectionProxy connection;
   final ArrayDeque<Record> invocationQueue;
   protected T delegate;
   protected T delegate2;
   protected Record tailRecord;

   private boolean isClosed;

   protected GenericStatementProxy(ConnectionProxy connection, T statement)
   {
      this.connection = connection;
      this.delegate = statement;
      this.invocationQueue = new ArrayDeque<Record>(5);
   }

   protected final SQLException checkException(SQLException e)
   {
      return connection.checkException(e);
   }

   protected final void checkException2(SQLException sqle) throws SQLException
   {
      if (LOGGER.isTraceEnabled())
         LOGGER.trace(getClass().getName() + ".checkException2", sqle);
      if (delegate2 != null) {
         try {
            delegate2.close();
         }
         catch (SQLException e) {
            e.printStackTrace(); // todo ???
         }
         delegate2 = null;
      }
      connection.checkException2(sqle);
   }

   protected final boolean isFallbackMode()
   {
      return delegate2 == null;
   }

   final void drainQueue()
   {
      if (invocationQueue.size() == 0) return;
      Queue<Record> connectionQueue = connection.invocationQueue;
      Iterator<Record> iterator = invocationQueue.iterator();
      while (iterator.hasNext()) {
         Record record = iterator.next();
         connectionQueue.add(record);
         iterator.remove();
      }
   }

   private final int getConnectionId()
   {
      return System.identityHashCode(connection);
   }

   private final int getStatementId()
   {
      return System.identityHashCode(this);
   }

   protected final void invoked(String methodName, Object... args)
   {
      invocationQueue.add(tailRecord = new Record(getConnectionId(), getStatementId(), this.getClass(), methodName, args));
      if (LOGGER.isTraceEnabled())
         LOGGER.trace(tailRecord.toString());
   }

   // **********************************************************************
   //                 Overridden java.sql.Statement Methods
   // **********************************************************************

   /**
    * {@inheritDoc}
    */
   @Override
   public void close() throws SQLException
   {
      if (isClosed) {
         return;
      }

      isClosed = true;
      connection.untrackStatement(this);

      try {
         delegate.close();
         if (delegate2 != null)
            try {
               delegate2.close();
            }
            catch (SQLException e) {
               e.printStackTrace(); // todo ???
            }

         if (isFallbackMode()) drainQueue();
      }
      catch (SQLException e) {
         throw checkException(e);
      }
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public Connection getConnection() throws SQLException
   {
      return connection;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public boolean execute(String sql) throws SQLException
   {
      connection.markCommitStateDirty();
      boolean result = delegate.execute(sql);
      if (!isFallbackMode())
         try {
            delegate2.execute(sql);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public boolean execute(String sql, int autoGeneratedKeys) throws SQLException
   {
      connection.markCommitStateDirty();
      boolean result = delegate.execute(sql, autoGeneratedKeys);
      if (!isFallbackMode())
         try {
            delegate2.execute(sql, autoGeneratedKeys);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   @DontRecord
   public ResultSet executeQuery(String sql) throws SQLException
   {
      connection.markCommitStateDirty();
      ResultSet resultSet = delegate.executeQuery(sql);
      // todo check if always 'select'
      return ProxyFactory.getProxyResultSet(connection, resultSet);
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public int executeUpdate(String sql) throws SQLException
   {
      connection.markCommitStateDirty();
      int result = delegate.executeUpdate(sql);
      if (!isFallbackMode())
         try {
            delegate2.executeUpdate(sql);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public int[] executeBatch() throws SQLException
   {
      connection.markCommitStateDirty();
      int[] result = delegate.executeBatch();
      try {
         if (!isFallbackMode()) delegate2.executeBatch();
      }
      catch (SQLException e) {
         checkException2(e);
      }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException
   {
      connection.markCommitStateDirty();
      int result = delegate.executeUpdate(sql, autoGeneratedKeys);
      if (!isFallbackMode())
         try {
            delegate2.executeUpdate(sql, autoGeneratedKeys);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public int executeUpdate(String sql, int[] columnIndexes) throws SQLException
   {
      connection.markCommitStateDirty();
      int result = delegate.executeUpdate(sql, columnIndexes);
      if (!isFallbackMode())
         try {
            delegate2.executeUpdate(sql, columnIndexes);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public int executeUpdate(String sql, String[] columnNames) throws SQLException
   {
      connection.markCommitStateDirty();
      int result = delegate.executeUpdate(sql, columnNames);
      if (!isFallbackMode())
         try {
            delegate2.executeUpdate(sql, columnNames);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public boolean execute(String sql, int[] columnIndexes) throws SQLException
   {
      connection.markCommitStateDirty();
      boolean result = delegate.execute(sql, columnIndexes);
      if (!isFallbackMode())
         try {
            delegate2.execute(sql, columnIndexes);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public boolean execute(String sql, String[] columnNames) throws SQLException
   {
      connection.markCommitStateDirty();
      boolean result = delegate.execute(sql, columnNames);
      if (!isFallbackMode())
         try {
            delegate2.execute(sql, columnNames);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public long[] executeLargeBatch() throws SQLException
   {
      connection.markCommitStateDirty();
      long[] result = delegate.executeLargeBatch();
      try {
         delegate.executeLargeBatch();
      }
      catch (SQLException e) {
         checkException2(e);
      }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public long executeLargeUpdate(String sql) throws SQLException
   {
      connection.markCommitStateDirty();
      long result = delegate.executeLargeUpdate(sql);
      if (!isFallbackMode())
         try {
            delegate2.executeLargeUpdate(sql);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException
   {
      connection.markCommitStateDirty();
      long result = delegate.executeLargeUpdate(sql, autoGeneratedKeys);
      if (!isFallbackMode())
         try {
            delegate2.executeLargeUpdate(sql, autoGeneratedKeys);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException
   {
      connection.markCommitStateDirty();
      long result = delegate.executeLargeUpdate(sql, columnIndexes);
      if (!isFallbackMode())
         try {
            delegate2.executeLargeUpdate(sql, columnIndexes);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException
   {
      connection.markCommitStateDirty();
      long result = delegate.executeLargeUpdate(sql, columnNames);
      if (!isFallbackMode())
         try {
            delegate2.executeLargeUpdate(sql, columnNames);
         }
         catch (SQLException e) {
            checkException2(e);
         }
      return result;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public ResultSet getResultSet() throws SQLException
   {
      final ResultSet resultSet = delegate.getResultSet();
      //todo check if always 'select'
      if (resultSet != null) {
         return ProxyFactory.getProxyResultSet(connection, resultSet);
      }
      return null;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   @SuppressWarnings("unchecked")
   public final <T> T unwrap(Class<T> iface) throws SQLException
   {
      if (iface.isInstance(delegate)) {
         return (T) delegate;
      }
      else if (delegate instanceof Wrapper) {
         return (T) delegate.unwrap(iface);
      }

      throw new SQLException("Wrapped statement is not an instance of " + iface);
   }

}


text:
package com.intellij.refactoring.move.moveInner;

import com.intellij.java.refactoring.JavaRefactoringBundle;
import com.intellij.lang.Language;
import com.intellij.lang.jvm.JvmLanguage;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.PsiReference;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandlerDelegate;
import com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler;
import com.intellij.refactoring.move.moveMembers.MoveMembersHandler;
import com.intellij.refactoring.util.RadioUpDownListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

public class MoveInnerToUpperOrMembersHandler extends MoveHandlerDelegate {
  @Override
  public boolean canMove(final PsiElement[] elements, @Nullable final PsiElement targetContainer, @Nullable PsiReference reference) {
    if (elements.length != 1) return false;
    PsiElement element = elements [0];
    return isStaticInnerClass(element);
  }

  private static boolean isStaticInnerClass(final PsiElement element) {
    return element instanceof PsiClass && element.getParent() instanceof PsiClass &&
           ((PsiClass) element).hasModifierProperty(PsiModifier.STATIC);
  }

  @Override
  public void doMove(final Project project, final PsiElement[] elements, final PsiElement targetContainer, final MoveCallback callback) {
    SelectInnerOrMembersRefactoringDialog dialog = new SelectInnerOrMembersRefactoringDialog((PsiClass)elements[0], project);
    if (!dialog.showAndGet()) {
      return;
    }
    MoveHandlerDelegate delegate = dialog.getRefactoringHandler();
    if (delegate != null) {
      delegate.doMove(project, elements, targetContainer, callback);
    }
  }

  @Override
  public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference,
                           final Editor editor) {
    if (isStaticInnerClass(element) && !JavaMoveClassesOrPackagesHandler.isReferenceInAnonymousClass(reference)) {
      final PsiElement targetContainer = LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext);
      PsiClass aClass = (PsiClass)element;
      SelectInnerOrMembersRefactoringDialog dialog = new SelectInnerOrMembersRefactoringDialog(aClass, project);
      if (dialog.showAndGet()) {
        final MoveHandlerDelegate moveHandlerDelegate = dialog.getRefactoringHandler();
        if (moveHandlerDelegate != null) {
          moveHandlerDelegate.doMove(project, new PsiElement[]{aClass}, targetContainer, null);
        }
      }
      return true;
    }
    return false;
  }

  @Override
  public boolean supportsLanguage(@NotNull Language language) {
    return language instanceof JvmLanguage;
  }

  @Nullable
  @Override
  public String getActionName(PsiElement @NotNull [] elements) {
    return JavaRefactoringBundle.message("move.inner.class.action.name");
  }

  private static class SelectInnerOrMembersRefactoringDialog extends DialogWrapper {
    private JRadioButton myRbMoveInner;
    private JRadioButton myRbMoveMembers;
    private final String myClassName;

    SelectInnerOrMembersRefactoringDialog(final PsiClass innerClass, Project project) {
      super(project, true);
      setTitle(RefactoringBundle.message("select.refactoring.title"));
      myClassName = innerClass.getName();
      init();
    }

    @Override
    protected JComponent createNorthPanel() {
      return new JLabel(RefactoringBundle.message("what.would.you.like.to.do"));
    }

    @Override
    public JComponent getPreferredFocusedComponent() {
      return myRbMoveInner;
    }

    @Override
    protected String getDimensionServiceKey() {
      return "#com.intellij.refactoring.move.MoveHandler.SelectRefactoringDialog";
    }

    @Override
    protected JComponent createCenterPanel() {
      JPanel panel = new JPanel(new BorderLayout());
      myRbMoveInner = new JRadioButton();
      myRbMoveInner.setText(JavaRefactoringBundle.message("move.inner.class.to.upper.level", myClassName));
      myRbMoveInner.setSelected(true);
      myRbMoveMembers = new JRadioButton();
      myRbMoveMembers.setText(JavaRefactoringBundle.message("move.inner.class.to.another.class", myClassName));

      ButtonGroup gr = new ButtonGroup();
      gr.add(myRbMoveInner);
      gr.add(myRbMoveMembers);

      new RadioUpDownListener(myRbMoveInner, myRbMoveMembers);

      Box box = Box.createVerticalBox();
      box.add(Box.createVerticalStrut(5));
      box.add(myRbMoveInner);
      box.add(myRbMoveMembers);
      panel.add(box, BorderLayout.CENTER);
      return panel;
    }

    @Nullable
    public MoveHandlerDelegate getRefactoringHandler() {
      if (myRbMoveInner.isSelected()) {
        return new MoveInnerToUpperHandler();
      }
      if (myRbMoveMembers.isSelected()) {
        return new MoveMembersHandler();
      }
      return null;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
/* https://github.com/jdh11235/JSchunks */

function nudge(elmID) {
	var elm = document.getElementById(elmID);
	var oldStyle = getComputedStyle(elm).marginTop;
	var newStyle = (+oldStyle.substring(0, 1) + 1) + oldStyle.substring(1, oldStyle.length);
	elm.style.marginTop = newStyle;
}

function attachNudge(elmID, event) {
	function nudgeID() { nudge(elmID) };
	document.getElementById(elmID).addEventListener(event, nudgeID, false);
}

/* example */
attachNudge('logo_homepage_link', 'mouseover');


text:
import path from 'node:path'
import child from 'node:child_process'
import { expect, test, vi } from 'vitest'

import LocalRunner from '../src/index.js'

vi.mock('@wdio/logger', () => import(path.join(process.cwd(), '__mocks__', '@wdio/logger')))

vi.mock('child_process', () => {
    const childProcessMock = {
        on: vi.fn(),
        send: vi.fn(),
        kill: vi.fn()
    }

    return {
        default: { fork: vi.fn().mockReturnValue(childProcessMock) }
    }
})

test('should fork a new process', () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {
        outputDir: '/foo/bar',
        runnerEnv: { FORCE_COLOR: 1 }
    } as any)
    const worker = runner.run({
        cid: '0-5',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: {},
        caps: {},
        specs: ['/foo/bar.test.js'],
        execArgv: [],
        retries: 0
    })
    const childProcess = worker.childProcess
    worker.emit = vi.fn()

    expect(worker.isBusy).toBe(true)
    expect(vi.mocked(child.fork).mock.calls[0][0].endsWith('run.js')).toBe(true)

    const { env } = vi.mocked(child.fork).mock.calls[0][2]! as any
    expect(env.WDIO_LOG_PATH).toMatch(/(\\|\/)foo(\\|\/)bar(\\|\/)wdio-0-5\.log/)
    expect(env.FORCE_COLOR).toBe(1)
    expect(childProcess?.on).toHaveBeenCalled()

    expect(childProcess?.send).toHaveBeenCalledWith({
        args: {},
        caps: {},
        cid: '0-5',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        retries: 0,
        specs: ['/foo/bar.test.js']
    })

    worker.postMessage('runAgain', { foo: 'bar' })
})

test('should shut down worker processes', async () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {
        outputDir: '/foo/bar',
        runnerEnv: { FORCE_COLOR: 1 }
    } as any)
    const worker1 = runner.run({
        cid: '0-4',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: {},
        caps: {},
        specs: ['/foo/bar2.test.js'],
        execArgv: [],
        retries: 0
    })
    const worker2 = runner.run({
        cid: '0-5',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: {},
        caps: {},
        specs: ['/foo/bar.test.js'],
        execArgv: [],
        retries: 0
    })
    setTimeout(() => {
        worker1.isBusy = false
        setTimeout(() => {
            worker2.isBusy = false
        }, 260)
    }, 260)

    const before = Date.now()
    await runner.shutdown()
    const after = Date.now()

    expect(after - before).toBeGreaterThanOrEqual(750)
    const call1: any = vi.mocked(worker1.childProcess?.send)!.mock.calls.pop()![0]
    expect(call1.cid).toBe('0-5')
    expect(call1.command).toBe('endSession')
    const call2: any = vi.mocked(worker1.childProcess?.send)!.mock.calls.pop()![0]
    expect(call2.cid).toBe('0-4')
    expect(call2.command).toBe('endSession')
})

test('should avoid shutting down if worker is not busy', async () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {
        outputDir: '/foo/bar',
        runnerEnv: { FORCE_COLOR: 1 }
    } as any)

    runner.run({
        cid: '0-8',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: { sessionId: 'abc' },
        caps: {},
        specs: ['/foo/bar2.test.js'],
        execArgv: [],
        retries: 0
    })
    runner.workerPool['0-8'].isBusy = false

    await runner.shutdown()

    expect(runner.workerPool['0-8']).toBeFalsy()
})

test('should shut down worker processes in watch mode - regular', async () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {
        outputDir: '/foo/bar',
        runnerEnv: { FORCE_COLOR: 1 },
        watch: true,
    } as any)

    const worker = runner.run({
        cid: '0-6',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: { sessionId: 'abc' },
        caps: {},
        specs: ['/foo/bar2.test.js'],
        execArgv: [],
        retries: 0
    })
    runner.workerPool['0-6'].sessionId = 'abc'
    runner.workerPool['0-6'].server = { host: 'foo' }
    runner.workerPool['0-6'].caps = { browser: 'chrome' } as any

    setTimeout(() => {
        worker.isBusy = false
    }, 260)

    const before = Date.now()
    await runner.shutdown()
    const after = Date.now()

    expect(after - before).toBeGreaterThanOrEqual(300)

    const call: any = vi.mocked(worker.childProcess?.send)!.mock.calls.pop()![0]
    expect(call.cid).toBe('0-6')
    expect(call.command).toBe('endSession')
    expect(call.args.watch).toBe(true)
    expect(call.args.isMultiremote).toBeFalsy()
    expect(call.args.config.sessionId).toBe('abc')
    expect(call.args.config.host).toEqual('foo')
    expect(call.args.caps).toEqual({ browser: 'chrome' })
})

test('should shut down worker processes in watch mode - mutliremote', async () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {
        outputDir: '/foo/bar',
        runnerEnv: { FORCE_COLOR: 1 },
        watch: true,
    } as any)

    const worker = runner.run({
        cid: '0-7',
        command: 'run',
        configFile: '/path/to/wdio.conf.js',
        args: {},
        caps: {},
        specs: ['/foo/bar.test.js'],
        execArgv: [],
        retries: 0
    })
    runner.workerPool['0-7'].isMultiremote = true
    runner.workerPool['0-7'].instances = { foo: { sessionId: '123' } }
    runner.workerPool['0-7'].caps = {
        foo: {
            capabilities: { browser: 'chrome' }
        }
    } as any

    setTimeout(() => {
        worker.isBusy = false
    }, 260)

    const before = Date.now()
    await runner.shutdown()
    const after = Date.now()

    expect(after - before).toBeGreaterThanOrEqual(300)

    const call: any = vi.mocked(worker.childProcess?.send)!.mock.calls.pop()![0]
    expect(call.cid).toBe('0-7')
    expect(call.command).toBe('endSession')
    expect(call.args.watch).toBe(true)
    expect(call.args.isMultiremote).toBe(true)
    expect(call.args.instances).toEqual({ foo: { sessionId: '123' } })
    expect(call.args.caps).toEqual({ foo: { capabilities: { browser: 'chrome' } } })
})

test('should avoid shutting down if worker is not busy', async () => {
    const runner = new LocalRunner('/path/to/wdio.conf.js', {} as any)
    expect(runner.initialise()).toBe(undefined)
})


text:
#include <aws/frauddetector/model/ExternalModelSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace FraudDetector
{
namespace Model
{

ExternalModelSummary::ExternalModelSummary() :
    m_modelEndpointHasBeenSet(false),
    m_modelSource(ModelSource::NOT_SET),
    m_modelSourceHasBeenSet(false)
{
}

ExternalModelSummary::ExternalModelSummary(JsonView jsonValue) :
    m_modelEndpointHasBeenSet(false),
    m_modelSource(ModelSource::NOT_SET),
    m_modelSourceHasBeenSet(false)
{
  *this = jsonValue;
}

ExternalModelSummary& ExternalModelSummary::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("modelEndpoint"))
  {
    m_modelEndpoint = jsonValue.GetString("modelEndpoint");

    m_modelEndpointHasBeenSet = true;
  }

  if(jsonValue.ValueExists("modelSource"))
  {
    m_modelSource = ModelSourceMapper::GetModelSourceForName(jsonValue.GetString("modelSource"));

    m_modelSourceHasBeenSet = true;
  }

  return *this;
}

JsonValue ExternalModelSummary::Jsonize() const
{
  JsonValue payload;

  if(m_modelEndpointHasBeenSet)
  {
   payload.WithString("modelEndpoint", m_modelEndpoint);

  }

  if(m_modelSourceHasBeenSet)
  {
   payload.WithString("modelSource", ModelSourceMapper::GetNameForModelSource(m_modelSource));
  }

  return payload;
}

} // namespace Model
} // namespace FraudDetector
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Wasteland Boots"</title>
		<link>http://bvs.wikidot.com/forum/t-172601/wasteland-boots</link>
		<description>Posts in the discussion thread "Wasteland Boots"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:48:56 +0000</lastBuildDate>

				</channel>
</rss>


text:
namespace stock_logic {

StockFactory* StockFactory::instance_ = NULL;

StockFactory*
StockFactory::GetInstance() {
  if (instance_ == NULL)
    instance_ = new StockFactory();
  return instance_;
}

void StockFactory::FreeInstance() {
  delete instance_;
  instance_ = NULL;
}

StockFactory::StockFactory() {
  Init();
}

StockFactory::~StockFactory() {
}

void StockFactory::Init() {
  stock_usr_mgr_ = stock_logic::StockUserEngine::GetVIPUserManager();
}

void StockFactory::InitParam(config::FileConfig* config) {

  //StockRedisDB::GetPtr()->InitReids(config);
  stock_db_ = new stock_logic::StockDB(config);
  stock_usr_mgr_->Init(stock_db_);
  OnUpdateStockHistData();
  //OnUpdateYieldDataFromDB();
  std::map<int, YieldInfoUnit>& hs300_yields_info = stock_usr_mgr_
      ->stock_user_cache_->get_hs300_yield_data();
  int min_visit_time = 0;
  std::map<int, YieldInfoUnit>::iterator iter = hs300_yields_info.begin();
  for (; iter != hs300_yields_info.end(); iter++) {
    int trade_time = iter->first;
    LOG_MSG2("hs300_yields_infotrade_time=%d",
             trade_time);
    stock_usr_mgr_->UpdateIndustryYieldInfo(trade_time);
    stock_usr_mgr_->stock_user_cache_->update_max_visit_time(trade_time);
    if (0 == min_visit_time)
      min_visit_time = trade_time;
    if (trade_time < min_visit_time)
      min_visit_time = trade_time;
  }
  if (0 != min_visit_time)
    stock_usr_mgr_->stock_user_cache_->set_min_visit_data_time(min_visit_time);
  int max_visit_time = stock_usr_mgr_->stock_user_cache_->max_visit_data_time();
  stock_db_->FectchStockVisitData(min_visit_time,
                                  max_visit_time,
                                  stock_usr_mgr_->stock_user_cache_->stock_total_info_);
  TimeUpdateWeekMonthData();
  int current_trade_time = 0;
  stock_usr_mgr_->UpdateIndustryPriceInfo(current_trade_time);
  stock_usr_mgr_->UpdateIndustryJson();
  OnUpdateEventsData();

  this->OnUpdateOfflineVisitData();
  //this->Attach(new ObserverTest());
  this->Attach(new OffLineVisitStockObserver(this));
  this->Attach(new CustomWeightObserver(this));
  //this->Attach(new StockRealInfoObserver(this));
  //this->Attach(new StockHistRedisObserver(this));
  this->Attach(new HistEventsObserver(this));
  this->Attach(new IndustryStockHotRankObserver());
  //this->Attach(new ChaliStrategy(this));
  this->Attach(new HotRankOneHundredStrategy(this));
  this->Attach(new HotRankFiftyHundredStrategy(this));
  this->Attach(new StockAccountManager(this));
}
void StockFactory::Dest() {
  stock_logic::StockUserEngine::FreeVIPUserEngine();
  stock_logic::StockUserEngine::FreeVIPUserManager();
}

void StockFactory::OnVIPGetLimitData(const int socket,
                                     base_logic::DictionaryValue* dict,
                                     george_logic::PacketHead* packet) {
  std::string limit_data_json;
  std::string format = "json";
  dict->GetString(L"format", &format);
  stock_usr_mgr_->GetLimitData(limit_data_json, format);
  LOG_MSG2("limit_data_json=%s", limit_data_json.c_str());
  if ("jsonp" == format) {
    std::string limit_data_jsonp = "";
    stock_logic::net_reply::VIPNewsList* vip_list =
        new stock_logic::net_reply::VIPNewsList();
    StockUtil::Instance()->filter_character(limit_data_json, '\r');
    StockUtil::Instance()->filter_character(limit_data_json, '\n');
    vip_list->set_string_value(L"jsonp_result", limit_data_json);
    StockUtil::Instance()->wrap_jsonp_serialize(vip_list,
                                                packet->attach_field(),
                                                limit_data_json,
                                                limit_data_jsonp);
    limit_data_json = limit_data_jsonp;
    StockUtil::Instance()->filter_character(limit_data_json, '\\');
    StockUtil::Instance()->filter_redundant_quotes(limit_data_json);
  }
  base_logic::LogicComm::SendFull(socket, limit_data_json.c_str(),
                                  limit_data_json.length());
}

void StockFactory::OnVIPGetHotDiagramData(const int socket,
                                          base_logic::DictionaryValue* dict,
                                          george_logic::PacketHead* packet) {

  std::string type = "";
  std::string stock_code = "";
  bool r = false;
  LOG_MSG2("dict.size=%d", dict->size());
  if (dict->GetString(L"stock_code", &stock_code)) {
    LOG_MSG2("stock_code=%s", stock_code.c_str());
  } else
    LOG_MSG("get stock_code failed");
  if (dict->GetString(L"type1", &type))
    LOG_MSG2("type=%s", type.c_str());
  else
    LOG_MSG("get type failed");
  std::string industry_name = "";
  r = dict->GetString(L"event", &industry_name);
  std::string encode_industry_name = "";
  if (true == r) {
    base::BasicUtil::UrlDecode(industry_name, encode_industry_name);
    LOG_MSG2("get industry=%s", encode_industry_name.c_str());
    industry_name = encode_industry_name;
  }

  std::string cycle_type = "day";
  r = dict->GetString(L"cycle_type", &cycle_type);
  std::string format = "json";
  dict->GetString(L"format", &format);

  std::string classify = "industry";
  r = dict->GetString(L"classify", &classify);
  if (true == r) {
    LOG_MSG2("get classify=%s", classify.c_str());
  }

  std::string start_date = ",2016-05-01";
  r = dict->GetString(L"start_date", &start_date);
  if (true == r) {
    LOG_MSG2("get start_date=%s", start_date.c_str());
  }
  if (start_date.size() > 1)
    start_date.erase(start_date.begin());

  std::string end_date = StockUtil::Instance()->get_current_day_str();
  r = dict->GetString(L"end_date", &end_date);
  if (true == r) {
    if (end_date.size() > 1)
      end_date.erase(end_date.begin());
    LOG_MSG2("get end_date=%s", end_date.c_str());
  }

  std::string name = "null";
  r = dict->GetString(L"name", &name);
  if (true == r) {
    LOG_MSG2("get name=%s", name.c_str());
    Observer* ob = this->GetObserverByName(name);
    if (NULL != ob) {
      ob->Process(socket, dict);
      return;
    }
  }

  if ("industry" == type)
    //TODO 行业热力图
    ProcessHotDiagramIndustryData(socket, cycle_type, format, packet, dict);
  else if ("event" == type) {
    //事件排行榜
    ProcessHotDiagramEventData(socket, packet, dict);
  } else if ("" != industry_name) {
    //返回事件,行业和概念日收益率
    industry_name += classify;
    ProcessEventYieldByName(socket,
                            start_date,
                            end_date,
                            industry_name,
                            packet,
                            cycle_type,
                            name);
    //ProcessHotDiagramByIndustry(socket, cycle_type, industry_name);
  } else if ("" != stock_code) {
    if (stock_code.size() > 1)
      stock_code.erase(stock_code.begin());
    ProcessStockKLine(socket,
                      stock_code,
                      format,
                      packet,
                      dict,
                      cycle_type,
                      start_date,
                      end_date,
                      name);
  }
  LOG_MSG("OnVIPGetHotDiagramData end");
}

void StockFactory::ProcessEventYieldByName(int socket, std::string& start_date,
                                           std::string& end_date,
                                           std::string& industry_name,
                                           george_logic::PacketHead* packet,
                                           std::string& cycle_type,
                                           std::string& name) {
  std::string yield_json = "";
  if (stock_usr_mgr_->GetYieldJsonByName(cycle_type,
                                         start_date,
                                         end_date,
                                         industry_name,
                                         yield_json,
                                         name)) {
    base_logic::LogicComm::SendFull(socket, yield_json.c_str(),
                                    yield_json.length());
  }
  return;
}

void StockFactory::ProcessHotDiagramEventData(
    int socket, george_logic::PacketHead* packet,
    base_logic::DictionaryValue* dict) {
  std::string event_json = stock_usr_mgr_->GetEventHotDiagram();
  LOG_MSG2("event_json=%s", event_json.c_str());
  base_logic::LogicComm::SendFull(socket, event_json.c_str(),
                                  event_json.length());
}

//YGTODO 更改json字符串取值位置
void StockFactory::ProcessHotDiagramIndustryData(
    int socket, std::string type, std::string format,
    george_logic::PacketHead* packet, base_logic::DictionaryValue* dict) {
  std::string industry_json = stock_usr_mgr_->GetIndustryHotDiagram(type,
                                                                    format);
  LOG_MSG2("industry_json=%s",industry_json.c_str());
  if ("jsonp" == format) {
    std::string industry_jsonp = "";
    stock_logic::net_reply::VIPNewsList* vip_list =
        new stock_logic::net_reply::VIPNewsList();
    StockUtil::Instance()->filter_character(industry_json, '\r');
    StockUtil::Instance()->filter_character(industry_json, '\n');
    vip_list->set_string_value(L"jsonp_result", industry_json);
    StockUtil::Instance()->wrap_jsonp_serialize(vip_list,
                                                packet->attach_field(),
                                                industry_json, industry_jsonp);
    industry_json = industry_jsonp;
    LOG_MSG2("industry_json=%s",industry_json.c_str());
    StockUtil::Instance()->filter_character(industry_json, '\\');
    StockUtil::Instance()->filter_redundant_quotes(industry_json);
  }
  base_logic::LogicComm::SendFull(socket, industry_json.c_str(),
                                  industry_json.length());
}

void StockFactory::ProcessHotDiagramByIndustry(int socket, std::string type,
                                               std::string industry_name) {
  std::string stocks_json = stock_usr_mgr_->GetStocksHotDiagram(type,
                                                                industry_name);
  LOG_MSG2("stocks_json=%s", stocks_json.c_str());
  base_logic::LogicComm::SendFull(socket, stocks_json.c_str(),
                                  stocks_json.length());
}

void StockFactory::ProcessStockKLine(int socket,
                                     std::string stock_code,
                                     std::string format,
                                     george_logic::PacketHead* packet,
                                     base_logic::DictionaryValue* dict,
                                     std::string& cycle_type,
                                     std::string& start_date,
                                     std::string& end_date,
                                     std::string& name) {
  LOG_MSG2("format=%s,cycle_type=%s,start_date=%s,end_date=%s,name=%s",
           format.c_str(),
           cycle_type.c_str(),
           start_date.c_str(),
           end_date.c_str(),
           name.c_str());
  std::string stock_kline = stock_usr_mgr_->GetStockKLineByCode(stock_code,
                                                                format,
                                                                cycle_type,
                                                                start_date,
                                                                end_date,
                                                                name);
  LOG_MSG2("stock_kline=%s,stock_code=%s", stock_kline.c_str(),stock_code.c_str());
  if ("jsonp" == format) {
    std::string stock_kline_jsonp = "";
    stock_logic::net_reply::VIPNewsList* vip_list =
        new stock_logic::net_reply::VIPNewsList();
    StockUtil::Instance()->filter_character(stock_kline, '\r');
    StockUtil::Instance()->filter_character(stock_kline, '\n');
    vip_list->set_string_value(L"jsonp_result", stock_kline);
    StockUtil::Instance()->wrap_jsonp_serialize(vip_list,
                                                packet->attach_field(),
                                                stock_kline, stock_kline_jsonp);
    stock_kline = stock_kline_jsonp;
    StockUtil::Instance()->filter_character(stock_kline, '\\');
    StockUtil::Instance()->filter_redundant_quotes(stock_kline);
  }
  base_logic::LogicComm::SendFull(socket, stock_kline.c_str(),
                                  stock_kline.length());
}

void StockFactory::OnUpdateRealtimeStockInfo() {
  stock_usr_mgr_->UpdateRealtimeStockInfo();
  LOG_MSG("UpdateIndustryPriceInfo in OnUpdateRealtimeStockInfo");
  int current_trade_time = 0;
  stock_usr_mgr_->UpdateIndustryPriceInfo(current_trade_time);
  stock_usr_mgr_->UpdateIndustryVolume();
  stock_usr_mgr_->UpdateIndustryJson();
}

void StockFactory::OnUpdateStockHistData() {
  LOG_MSG("OnUpdateStockHistData");
  stock_usr_mgr_->UpdateStockHistData();
  stock_usr_mgr_->UpdateStockKLine();
  stock_usr_mgr_->UpdateIndustryHistData();
  //stock_usr_mgr_->UpdateIndustryKLine();TODO 缓存数据
}

void StockFactory::OnUpdateStockKLineData() {
  //如果有新的K线,则更新个股json
  LOG_MSG("OnUpdateStockKLineData");
  if (stock_usr_mgr_->UpdateStockDayKLineData())
    stock_usr_mgr_->UpdateStockKLine();
}

void StockFactory::OnUpdateEventsData() {
  stock_usr_mgr_->UpdateEventsData();
}

void StockFactory::OnUpdateYieldDataFromDB() {
  stock_usr_mgr_->UpdateYieldDataFromDB();
}

void StockFactory::OnUpdateYieldDataToDB() {
  stock_usr_mgr_->UpdateYieldDataToDB();
}

void StockFactory::OnDeleteOldYieldData() {
  stock_usr_mgr_->DeleteOldYieldData();
}

void StockFactory::OnLoadCustom_Event() {
  stock_usr_mgr_->LoadCustomEvent();
}

void StockFactory::TimeUpdateWeekMonthData() {
  LOG_MSG("TimeUpdateWeekMonthData");
  int current_trade_time = 0;
  stock_usr_mgr_->UpdateWeekMonthData();
  stock_usr_mgr_->UpdateIndustryPriceInfo(current_trade_time);
}

void StockFactory::OnUpdateOfflineVisitData() {
  LOG_MSG("OnUpdateOfflineVisitData");
  stock_usr_mgr_->UpdateOfflineVisitData();
}

void StockFactory::TimeWriteLimitData(int current_trade_time) {
  LOG_MSG("TimeWriteLimitData");
  stock_usr_mgr_->WriteLimitData(current_trade_time);
  stock_usr_mgr_->UpdateIndustryPriceInfo(current_trade_time);
  stock_usr_mgr_->UpdateStockVisitData(current_trade_time);
  //stock_usr_mgr_->UpdateIndustryVisitData(current_trade_time);
  //stock_usr_mgr_->UpdateEventsYield(current_trade_time);
}

void StockFactory::TimeDeleteOldLimitData() {
  LOG_MSG("TimeDeleteOldLimitData");
  stock_usr_mgr_->DeleteOldEventsData();
}

void StockFactory::OnUpdateLimitData() {
  LOG_MSG("OnUpdateLimitData");
  stock_usr_mgr_->UpdateLimitData();
}

bool StockFactory::CheckStockValid(std::string& stock_code) {
  STOCKINFO_MAP& stock_map = this->GetStockInfoMap();
  STOCKINFO_MAP::iterator iter = stock_map.find(stock_code);
  if (iter != stock_map.end())
    return true;
  else
    return false;
}

StockUserCache* StockFactory::GetCache() {
  return stock_usr_mgr_->stock_user_cache_;
}

STOCKINFO_MAP& StockFactory::GetStockInfoMap() {
  StockUserCache* cache = this->GetCache();
  return cache->stock_total_info_;
}

StockTotalInfo& StockFactory::GetTotalInfoByCode(std::string& stock_code) {
  STOCKINFO_MAP& stock_map = this->GetStockInfoMap();
  return stock_map[stock_code];
}

StockBasicInfo& StockFactory::GetBasicInfoByCode(std::string& stock_code) {
  STOCKINFO_MAP& stock_map = this->GetStockInfoMap();
  return stock_map[stock_code].basic_info_;
}

std::map<std::string, HistDataPerDay>& StockFactory::GetHistDataByCode(std::string stock_code) {
  StockTotalInfo& stock_total_info = this->GetTotalInfoByCode(stock_code);
  return stock_total_info.hist_data_info_.stock_hist_data_;
}

bool StockFactory::GetHistDataByDate(std::string stock_code, std::string date, HistDataPerDay& hist_data) {
  std::map<std::string, HistDataPerDay>& map =
      this->GetHistDataByCode(stock_code);
  std::map<std::string, HistDataPerDay>::iterator iter =
      map.find(date);
  if (iter != map.end()) {
    hist_data = iter->second;
    return true;
  }
  else
    return false;
}

std::map<std::string, DataPerDay>& StockFactory::GetDataPerDayByCode(std::string stock_code) {
  StockBasicInfo& basic_info = this->GetBasicInfoByCode(stock_code);
  return basic_info.data_per_day_;
}

std::map<std::string, BasicIndustryInfo>& StockFactory::GetIndustryMap() {
  StockUserCache* cache = this->GetCache();
  return cache->industry_info_.industry_info_map_;
}

BasicIndustryInfo& StockFactory::getBasicIndustryInfoByName(std::string& industry_name) {
  std::map<std::string, BasicIndustryInfo>& industry_map =
      this->GetIndustryMap();
  return industry_map[industry_name];
}

}


text:
namespace llvm {

class MachineDominanceFrontier : public MachineFunctionPass {
  ForwardDominanceFrontierBase<MachineBasicBlock> Base;
public:
  typedef DominatorTreeBase<MachineBasicBlock> DomTreeT;
  typedef DomTreeNodeBase<MachineBasicBlock> DomTreeNodeT;
  typedef DominanceFrontierBase<MachineBasicBlock>::DomSetType DomSetType;
  typedef DominanceFrontierBase<MachineBasicBlock>::iterator iterator;
  typedef DominanceFrontierBase<MachineBasicBlock>::const_iterator const_iterator;

  void operator=(const MachineDominanceFrontier &) = delete;
  MachineDominanceFrontier(const MachineDominanceFrontier &) = delete;

  static char ID;

  MachineDominanceFrontier();

  DominanceFrontierBase<MachineBasicBlock> &getBase() {
    return Base;
  }

  inline const std::vector<MachineBasicBlock*> &getRoots() const {
    return Base.getRoots();
  }

  MachineBasicBlock *getRoot() const {
    return Base.getRoot();
  }

  bool isPostDominator() const {
    return Base.isPostDominator();
  }

  iterator begin() {
    return Base.begin();
  }

  const_iterator begin() const {
    return Base.begin();
  }

  iterator end() {
    return Base.end();
  }

  const_iterator end() const {
    return Base.end();
  }

  iterator find(MachineBasicBlock *B) {
    return Base.find(B);
  }

  const_iterator find(MachineBasicBlock *B) const {
    return Base.find(B);
  }

  iterator addBasicBlock(MachineBasicBlock *BB, const DomSetType &frontier) {
    return Base.addBasicBlock(BB, frontier);
  }

  void removeBlock(MachineBasicBlock *BB) {
    return Base.removeBlock(BB);
  }

  void addToFrontier(iterator I, MachineBasicBlock *Node) {
    return Base.addToFrontier(I, Node);
  }

  void removeFromFrontier(iterator I, MachineBasicBlock *Node) {
    return Base.removeFromFrontier(I, Node);
  }

  bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
    return Base.compareDomSet(DS1, DS2);
  }

  bool compare(DominanceFrontierBase<MachineBasicBlock> &Other) const {
    return Base.compare(Other);
  }

  bool runOnMachineFunction(MachineFunction &F) override;

  void releaseMemory() override;

  void getAnalysisUsage(AnalysisUsage &AU) const override;
};

}

#endif


text:
import cProfile
import pstats

class Profiler:

    def __init__(self, sortby=None):
        self.profiler = None
        self.sortby = sortby or ('cumtime',)

    def __enter__(self):
        self.profiler = cProfile.Profile()
        self.profiler.enable()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.profiler.disable()
        self.write_stats()

    def write_stats(self):
        p = pstats.Stats(self.profiler)
        p.strip_dirs().sort_stats(*self.sortby).print_stats()


text:
use strict;

use O2::Context;
my $context = new O2::Context();
use O2::Mgr::UniversalManager;

die "usage: $0 objectId objectId...\n" unless @ARGV;
my $universalM = new O2::Mgr::UniversalManager(context=>$context);
foreach my $objectId (@ARGV) {
    my $object = $universalM->getObjectById($objectId);
    print $object->getMetaClassName(),' - ',$object->getMetaName(),"\n";
}


text:
![alt tag](https://cloud.githubusercontent.com/assets/5885065/6759256/e6181a36-cefb-11e4-8e17-4840746f120a.jpg)

### Table of Content

1. Introduction
2. Installation
2. Full Documenation
3. Like it / Hate it
4. References

### Introduction

   **["algo"] [web1]** is a cohesive Python Module for Algorithms. This library is an experimental collection of diverse useful algorithms from different fields of Computer Science implemented in Python. You can find the actual implementation of provided algorithms in algo.py file.
   <img src="https://cloud.githubusercontent.com/assets/5885065/5642960/fbc4d352-9606-11e4-91fb-5f5c458b52d0.png"
 alt="algo Logo" title="algo" align="right" />

   This is the Official Documentation of algo module. This API provides an implementation of different algorithms.  The algorithms library defines functions for a variety of purposes (e.g. data structures, searching, sorting, counting, manipulating data) that operate on ranges of elements. Provided algorithms were collected after one year research that analyzed the most commonly used algoithms in Software Engineering. The module was created in order to help Python developers to easily utilize those frequently used algorithms without having to implement them. Written algorithms include topics from different subfields of Computer Science. The current version of the module contains 50 algorithms. We are planning to increase the number of algorithms in the second version of this API.  It is important to note that the license of algo module is distributed under [Apache Licese] [web2].

### Installation

   In order to fully use the algo module firstly download the whole package from the following link: https://github.com/Rafa1994/Python-algo-Module (click on "Download zip" on the right side). Then open the terminal and go to the directory where the module package is located. After that run this command from terminal:
###### python setup.py sdist
   For Windows, open a command prompt windows (Start ‣ Accessories) and change the command to:
###### setup.py sdist
   Finally in the same package directory type this following command:
###### python setup.py install

### Full Documentation

##### TREE STRUCTURES

##### a) Trees
Tree(entry, left = None, right = None) : -  Creates a General Structure for Tree. A Tree is a non-linear abstract data type or data structure that simulates a hierarchical tree structure, with a root value and subtrees of children, represented as a set of linked nodes.

   1. Tree method: tree_print() - Gives the visualised structure of the tree created by Tree class.

   2. Function: swap_tree(tree) - Swaps the left and right branches of a tree.

   3. Function: traversal(tree) - Traverses the tree in order to get all elements in some sort of list.

   4. Function: tree_to_list(tree) - Saves all data in tree in the list.

   5. Function: equal_trees(t1, t2) - Checks if trees t1 and t2 are equal.

   6. Function: tree_size(t) - Returns the number of elements in a tree t.

   7. Function: tree_height(t) - Returns the height of a tree t.

##### b) Binary Trees
Binary_Tree(data = None), self.left = None, self.right = None : - Creates a structure for Binary Tree. A binary search tree (BST) is a node-based binary tree data structure which has the following properties: a) The left subtree of a node contains only nodes with keys less than the node's key, b) The right subtree of a node contains only nodes with keys greater than the node's key, c) Both the left and right subtrees must also be binary search trees.

   1. Binary_Tree method: insert(self, data) - Inserts new node with data.

   2. Binary_Tree method: lookup(self, data, parent = None) - Looks up a node containing data and returns also its parent.

   3. Binary_Tree method: delete(self, data) - Deletes a node containing data from binary tree.

   4. Binary_Tree method: children_count(self) - Counts the number of nodes in a tree.

   5. Binary_Tree method: print_tree(self) - Prints the content of the Binary tree.

   6. Binary_Tree method: compare_trees(self, node) -  Compates two binary trees.

   7. Binary_Tree method: tree_data(self) - A generator that gets a binary tree node data.

##### SORTING ALGORITHMS
A sorting algorithm is an algorithm that puts elements of a list(lst) in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) which require input data to be in sorted lists(lst).

   1. Bubble_Sort(lst) - For description read: http://en.wikipedia.org/wiki/Bubble_sort

   2. Short_Bubble(lst) - Faster version of Bubble Sort.

   3. Selection_Sort(lst) - For description read: http://en.wikipedia.org/wiki/Selection_sort

   4. Insertion_Sort(lst) - For description read: http://en.wikipedia.org/wiki/Insertion_sort

   5. Shell_Sort(lst) - For description read: http://en.wikipedia.org/wiki/Shellsort

   6. Merge_Sort(lst) - For description read: http://en.wikipedia.org/wiki/Merge_sort

   7. Quick_Sort(lst) - For descritopn read: http://en.wikipedia.org/wiki/Quicksort

##### HASHING ALGORITHMS
Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value.

   1. Hash(string) - Hashing function that converts a string value to an integer value.

   2. Fast_Hash(string) - A faster version of Hash(string) function.

##### NUMBER THEORY
Number theory is a branch of pure mathematics devoted primarily to the study of the integers, sometimes called "The Queen of Mathematics" because of its foundational place in the discipline. Number theorists study prime numbers as well as the properties of objects made out of integers or defined as generalizations of the integers.

   1. is_prime(num) - Checks whether a given number num is a prime number or not.

   2. primes(limit) - Gives the list of all prime numbers less that the limit. Read http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

   3. Prime_Factorization(x) - Gives a list of all prime factors of the number x.

   4. fib(n) - Generates the n-th Fibonacci number in a fast way.

   5. LCM(a, b) - Counts the LCM for numbers a and b. For description read: http://en.wikipedia.org/wiki/Least_common_multiple

   6. Count_Totatives(n) - Counts the totatives a number n. Read: http://en.wikipedia.org/wiki/Totative

   7. GCD(a,b) - Counts the GCD for numbers a and b. For description read: http://en.wikipedia.org/wiki/Greatest_common_divisor

   8. Factor(n) - Provides all the factors of the number n.

   9. Pell_Equations(n, k) - Returns the list of first k solutions of the Pell's equation ( x^2 - n*(y^2) = 1 ).

   10. perfect(n) - Checks whether the number n is a perfect number or not. Read: http://en.wikipedia.org/wiki/Perfect_number

##### SEARCHING ALGORITHMS
In computer science, a search algorithm is an algorithm for finding an item with specified properties among a collection of items. The items may be stored individually as records in a database; or may be elements of a search space defined by a mathematical formula or procedure.

   1. Binary_Search(seq, key) - Finds the position of given input key in a sequence seq. Read: http://en.wikipedia.org/wiki/Binary_search_algorithm

   2. DFS(graph, start, path = []) - Implementation of DFS for traversing and searching the graph. Read: http://en.wikipedia.org/wiki/Depth-first_search

   3. KMP(string, word) - Searches the substring word in a string. Read: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

   4. BMH(text, pattern) - Searches a substring pattern in a text. Read: http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

   5. RKS(substring, string) - Finds any one of a set of pattern strings in a text. Read: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm

##### DATA ALGORITHMS

   1. shuffle(seq) - Shuffles all the items in the list.

   2. jaccard_index(dataset_1, dataset_2) - Calculates Jaccard similarity coefficient for two datasets. Read more: http://en.wikipedia.org/wiki/Jaccard_index

   3. Levenshtein_distance(s1, s2) - Measure the distance between two sequences. Read more: http://en.wikipedia.org/wiki/Levenshtein_distance

   4. find_max_subarray(numbers) - Finds the contiguous subarray within a one-dimensional array of numbers which has the largest sum.

   5. permutations(l) - A generator that retursn all the permutations of the given list l.

   6. is_polindrom(string) - Checks whether the given string is a polindrom or not.

   7. Most_Common(lst) - Identifies the most common element in the given list lst.

   8. is_Anagram(s1,s2) - Checks whether strings s1 and s2 are anagrams or not.

   9. Find_Nonrepeat(s) - Finds the first nonrepeated character in the string s.

   10. atoi(str) - Converts str into an integer, and returns that integer.

   11. Weighted_Random(W) - Generate random integers given a list W of integers.

   12. Hamming_Distance(str1, str2) - Calculates the distance between two strings of equal length. Read more: http://en.wikipedia.org/wiki/Hamming_distance

### Like it / Hate it

   This API has been written by [Rafayel Mkrtchyan] [web3]. For additional comments and suggestions you can contact rafamian@berkeley.edu. I don't claim to be perfect so if you find a bug in this library, please send me an email preferably with a test that revealed that error so that I know what I need to fix.

### References

   1. http://rosettacode.org

   2. http://markmiyashita.com/cs61a/sp14

   3. http://www.laurentluce.com

   4. https://github.com/nryoung/algorithms

   5. http://interactivepython.org/runestone/static/pythonds/SortSearch/sorting.html

[web1]: https://github.com/MicBrain/Python-algo-Module
[web2]: http://www.apache.org/licenses/LICENSE-2.0
[web3]: https://www.linkedin.com/in/rafayelmkrtchyan


text:
package acceptance.example.test;

import acceptance.example.production.WeatherApplication;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.MappingBuilder;
import com.github.tomakehurst.wiremock.http.RequestListener;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import io.github.theangrydev.fluentbdd.yatspec.WriteOnlyTestItems;
import io.github.theangrydev.thinhttpclient.apache.ApacheHttpClient;
import io.github.theangrydev.thinhttpclient.api.Request;
import io.github.theangrydev.thinhttpclient.api.RequestBuilder;
import io.github.theangrydev.thinhttpclient.api.Response;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static io.github.theangrydev.thinhttpclient.apache.ApacheHttpClient.apacheHttpClient;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;

public class TestInfrastructure {

    private static final String SYSTEM_NAME = "WeatherApplication";
    private static final WireMockServer WIREMOCK;
    private static final RequestListenerHolder REQUEST_LISTENER_HOLDER = new RequestListenerHolder();

    private final WriteOnlyTestItems writeOnlyTestItems;

    private WeatherApplication weatherApplication;

    private List<InteractionToListenFor> interactionsToListenFor = new ArrayList<>();

    static {
        WIREMOCK = new WireMockServer(wireMockConfig().port(1235));
        WIREMOCK.addMockServiceRequestListener(REQUEST_LISTENER_HOLDER);
        WIREMOCK.start();
    }

    public TestInfrastructure(WriteOnlyTestItems writeOnlyTestItems) {
        this.writeOnlyTestItems = writeOnlyTestItems;
    }

    public String serverBaseUrl() {
        return weatherApplication.baseUrl();
    }

    public void setUp() {
        WIREMOCK.resetAll();
        REQUEST_LISTENER_HOLDER.delegate = this::recordInteraction;

        String wireMockServerUrl = format("http://localhost:%d", WIREMOCK.port());
        weatherApplication = new WeatherApplication(1234, wireMockServerUrl);
        weatherApplication.start();
    }

    public void tearDown() throws IOException {
        weatherApplication.stop();
        Files.delete(Paths.get("access.log"));
    }

    public Response execute(Request request) {
        try {
            return apacheHttpClient().execute(request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void givenThat(String dependencyName, MappingBuilder mappingBuilder) {
        WIREMOCK.givenThat(mappingBuilder);
        interactionsToListenFor.add(new InteractionToListenFor(dependencyName, mappingBuilder));
    }

    private void recordInteraction(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) {
        List<InteractionToListenFor> matches = interactionsToListenFor.stream()
                .filter(interactionToListenFor -> interactionToListenFor.matches(request))
                .collect(toList());
        if (matches.isEmpty()) {
            throw new IllegalStateException(format("Found an interaction that was not listened for. Request: %s%n%nResponse: %s%n", request, response));
        }
        if (matches.size() > 1) {
            throw new IllegalStateException(format("Found an interaction that was listened for multiple times. Request: %s%n%nResponse: %s%n", request, response));
        }
        String dependencyName = matches.get(0).dependencyName;
        recordOutgoingRequest(dependencyName, request);
        recordIncomingResponse(dependencyName, response);
    }

    public void recordIncomingRequest(String caller, Request request) {
        writeOnlyTestItems.addToCapturedInputsAndOutputs(format("%s from %s to %s", request.method, caller, SYSTEM_NAME), request);
    }

    public void recordOutgoingResponse(String caller, Response response) {
        writeOnlyTestItems.addToCapturedInputsAndOutputs(format("%s from %s to %s", response.status, SYSTEM_NAME, caller), response);
    }

    public void recordOutgoingRequest(String dependencyName, com.github.tomakehurst.wiremock.http.Request request) {
        writeOnlyTestItems.addToCapturedInputsAndOutputs(format("%s from %s to %s", request.getMethod().getName(), SYSTEM_NAME, dependencyName), request);
    }

    public void recordIncomingResponse(String dependencyName, com.github.tomakehurst.wiremock.http.Response response) {
        writeOnlyTestItems.addToCapturedInputsAndOutputs(format("%s from %s to %s", response.getStatus(), dependencyName, SYSTEM_NAME), response);
    }

    public void verifyThat(RequestPatternBuilder requestPatternBuilder) {
        WIREMOCK.verify(1, requestPatternBuilder);
    }

    private static class RequestListenerHolder implements RequestListener {
        RequestListener delegate;

        @Override
        public void requestReceived(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) {
            delegate.requestReceived(request, response);
        }
    }

    private static class InteractionToListenFor {
        final String dependencyName;
        final MappingBuilder mappingBuilder;

        private InteractionToListenFor(String dependencyName, MappingBuilder mappingBuilder) {
            this.dependencyName = dependencyName;
            this.mappingBuilder = mappingBuilder;
        }

        boolean matches(com.github.tomakehurst.wiremock.http.Request request) {
            return mappingBuilder.build().getRequest().match(request).isExactMatch();
        }
    }
}


text:
struct A;

a = __builtin_offsetof(struct A, a); // CHECK: error: offsetof() on incomplete type 'struct A'


text:
package com.longkaiwen.wozhuangyuan.view;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.json.JSONObject;
import com.longkaiwen.wozhuangyuan.R;
import com.longkaiwen.wozhuangyuan.ui.DetailInfoActivity;
import com.longkaiwen.wozhuangyuan.util.ImageDownLoad;
import com.longkaiwen.wozhuangyuan.util.MyApplication;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

/**
 * ʵÏÖÂÖ²¥¹ã¸æ½çÃæµÄ×Ô¶¨Òåview
 * @author longkaiwen
 *
 */

@SuppressLint("HandlerLeak")
public class SlideShowView extends FrameLayout {

    //×Ô¶¯ÂÖ²¥ÆôÓÿª¹Ø
    private final static boolean isAutoPlay = true;

    //×Ô¶¨ÒåÂÖ²¥Í¼µÄ×ÊÔ´
    private List<String> imageUrls = new ArrayList<String>();

    private List<String> id = new ArrayList<String>();

    private List<String> levels = new ArrayList<String>();

    //·ÅÂÖ²¥Í¼Æ¬µÄImageView µÄlist
    private List<ImageView> imageViewsList;
    //·ÅÔ²µãµÄViewµÄlist
    private List<View> dotViewsList;

    private ViewPager viewPager;
    //µ±Ç°ÂÖ²¥Ò³
    private int currentItem  = 0;
    //¶¨Ê±ÈÎÎñ
    private ScheduledExecutorService scheduledExecutorService;

    private Context context;

    private ImageDownLoad imageDownLoad;

    //Handler
    private Handler handler = new Handler(){

        @SuppressLint("HandlerLeak")
		@Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }

    };

    public SlideShowView(Context context) {
        this(context,null);
    }
    public SlideShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;

        imageDownLoad = new ImageDownLoad(context);

        initData();
        if(isAutoPlay){
            startPlay();
        }

    }
    /**
     * ¿ªÊ¼ÂÖ²¥Í¼Çл»
     */
    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 2, 4, TimeUnit.SECONDS);
    }
    /**
     * ³õ'»¯Ïà¹ØData
     */
    private void initData(){
        imageViewsList = new ArrayList<ImageView>();
        dotViewsList = new ArrayList<View>();

        // Ò»²½ÈÎÎñ»ñȡͼƬ
        new GetListTask().execute("");
    }
    /**
     * ³õ'»¯ViewsµÈUI
     */
    private void initUI(final Context context){
    	if(imageUrls == null || imageUrls.size() == 0)
    		return;

        LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);

        LinearLayout dotLayout = (LinearLayout)findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();

        // Èȵã¸öÊýÓëͼƬÌØÊâÏàµÈ
        for (int i = 0; i < imageUrls.size(); i++) {
        	ImageView view =  new ImageView(context);
        	view.setTag(imageUrls.get(i));
        	view.setScaleType(ScaleType.FIT_XY);
        	imageViewsList.add(view);

        	ImageView dotView =  new ImageView(context);
        	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        	params.leftMargin = 4;
			params.rightMargin = 4;
			dotLayout.addView(dotView, params);
        	dotViewsList.add(dotView);
		}

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setFocusable(true);

        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());

    }

    /**
     * Ìî³äViewPagerµÄÒ³ÃæÊÊÅäÆ÷
     *
     */
    private class MyPagerAdapter extends PagerAdapter{

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView(imageViewsList.get(position));
        }

        @Override
        public Object instantiateItem(View container, final int position) {

        	ImageView imageView = imageViewsList.get(position);

        	final String picIdString = id.get(position);

        	final String level = levels.get(position);

        	imageDownLoad.loadBitmap(imageView, imageView.getTag()+"");

//        	´Ë´¦ÊµÏÖÒ³Ãæµã»÷ÌøתµÄ¹¦ÄÜ
            imageView.setOnClickListener(new OnClickListener() {

    			@Override
    			public void onClick(View v) {

//    				±ÜÃâ¹ý¿ìµã»÷
    				if (MyApplication.isFastClick()) {

    					return;

    				}
    				Intent intent = new Intent();

    				intent.putExtra("fruit_id", picIdString);

    				intent.putExtra("level", level);

    				intent.setClass(context, DetailInfoActivity.class);

    				context.startActivity(intent);

    			}
    		});

            ((ViewPager)container).addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }

    }
    /**
     * ViewPagerµÄ¼àÌýÆ÷
     * µ±ViewPagerÖÐÒ³ÃæµÄ״̬·¢Éú¸Ä±äʱµ÷ÓÃ
     *
     */
    private class MyPageChangeListener implements OnPageChangeListener{

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
            case 1:// ÊÖÊÆ»¬¶¯£¬¿ÕÏÐÖÐ
                isAutoPlay = false;
                break;
            case 2:// ½çÃæÇл»ÖÐ
                isAutoPlay = true;
                break;
            case 0:// »¬¶¯½áÊø£¬¼´Çл»Íê±Ï»òÕß¼ÓÔØÍê±Ï
                // µ±Ç°Îª×îºóÒ»ÕÅ£¬´Ëʱ´ÓÓÒÏò×󻬣¬ÔòÇл»µ½µÚÒ»ÕÅ
                if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                    viewPager.setCurrentItem(0);
                }
                // µ±Ç°ÎªµÚÒ»ÕÅ£¬´Ëʱ´Ó×óÏòÓÒ»¬£¬ÔòÇл»µ½×îºóÒ»ÕÅ
                else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                    viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                }
                break;
        }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int pos) {

            currentItem = pos;
            for(int i=0;i < dotViewsList.size();i++){
                if(i == pos){
                    ((View)dotViewsList.get(pos)).setBackgroundResource(R.drawable.page_now);
                }else {
                    ((View)dotViewsList.get(i)).setBackgroundResource(R.drawable.page);
                }
            }
        }

    }

    /**
     *Ö´ÐÐÂÖ²¥Í¼Çл»ÈÎÎñ
     *
     */
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            synchronized (viewPager) {
                currentItem = (currentItem+1)%imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }

    }

    /**
     * Ïú»ÙImageView×ÊÔ´£¬»ØÊÕÄÚ´æ
     *
     */
    public void destoryBitmaps() {

        for (int i = 0; i < imageViewsList.size(); i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                //½â³ýdrawable¶ÔviewµÄÒýÓÃ
                drawable.setCallback(null);
            }
        }
    }

	/**
	 * Òì²½ÈÎÎñ,»ñȡͼƬURl£¬ÕâÀï²»ÖªµÀΪʲôʹÓÃvolley¿ò¼ÜµÄʱºòÒ»Ö±³öÏÖÎÊÌâ
	 * ͼƬµÄposition»á³ÖÐøÔö´ó
	 *
	 */
	class GetListTask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {

				HttpURLConnection connection = null;
				try {
					URL url = new URL("http://115.28.51.71/pic_url_test.php");
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8*1000);
					connection.setReadTimeout(8*1000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine())!=null) {
						response.append(line);
					}

					Log.i("head picture", response.toString());

					JSONObject rjObject = new JSONObject(response.toString());

					int num = Integer.parseInt(rjObject.getString("num"));

					for (int i = 0; i < num; i++) {

						JSONObject jObject = rjObject.getJSONObject(i+"");

						String urlString = jObject.getString("picture_url");

						String picIdString = jObject.getString("fruit_id");

						String levelString = jObject.getString("level");

						id.add(picIdString);

						levels.add(levelString);

						imageUrls.add(urlString);

					}

				}catch(Exception e){
					e.printStackTrace();
					return false;
				}
				return true;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) {
		        initUI(context);
			}
		}
	}

}


text:
layout:     post
title:      "Java代理机制与hook"
subtitle:   ""
date:       2016-05-01
author:     "goIntoAction"
header-img: "img/post-bg.jpg"
tags:
    - android插件化
---

Java中代理分为静态代理与动态代理。
静态代理非常简单,uml图如下

![o_proxy-pattern-cl.png](/img/in-post/proxy-and-hook//o_proxy-pattern-cl.png)

就是创建一个代理类,与真实类继承自同一接口,代理类持有真实类的引用,在外部调用代理类,代理类可以在调用真实类的前后加上自己的逻辑。其中接口类可以省略,代理类直接继承自真实类。

    // 抽象角色:
    abstract public class Subject {
        abstract public void  request();
    }

    // 真实角色:实现了Subject的request()方法
    public class  RealSubject  extends  Subject  {
      public  RealSubject()  { }

      public void  request()  {
         System.out.println( " From real subject. " );
        }
    }

    // 代理角色:
    public class  ProxySubject  extends  Subject  {
      // 以真实角色作为代理角色的属性
      private  Subject realSubject;

      public  ProxySubject(Subject realSubject)  {this.realSubject = realSubject }

      // 该方法封装了真实对象的request方法
      public void  request()  {
         preRequest();
         realSubject.request();  // 此处执行真实对象的request方法
         postRequest();
      }
      ...
    }

    // 客户端调用:
    RealSubject real = new RealSubject();
    Subject sub = new  ProxySubject(real);
    Sub.request();

静态代理虽然简单,但缺点明显,如果真实类中有多个方法需要代理,每个方法都要去实现,增加了代码维护的复杂度。所以jdk提供了动态代理的机制。

![o_proxy-pattern-java1.png](/img/in-post/proxy-and-hook/o_proxy-pattern-java1.png)

    public  interface Subject {
      abstract  public  void request();
    }

    // 具体角色RealSubject:
    public  class RealSubject implements Subject {
      public RealSubject() {}

      public  void request() {
        System.out.println( " From real subject. " );
     }

    }

    // 代理处理器:
    import java.lang.reflect.Method;
    import java.lang.reflect.InvocationHandler;

    public  class DynamicSubject implements InvocationHandler {
      private Object sub;
      public DynamicSubject() {}

      public DynamicSubject(Object obj) {
        sub = obj;
      }

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println( " before calling "  + method);
        method.invoke(sub,args);

        System.out.println( " after calling "  + method);
        return  null ;
      }
    }
	//调用
    RealSubject rs = new RealSubject(); // 在这里指定被代理类
    InvocationHandler ds = new DynamicSubject(rs);
    Class cls = rs.getClass();
    Subject subject = (Subject) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),ds );
    subject.request();

动态代理是使用反射去调用真实类,处理代理的逻辑都在InvocationHandler实现类的invoke方法中,比静态代理好维护。但是jdk的动态代理机制必须基于接口,Proxy.newProxyInstance方法必须传入一个接口,在非接口实现类中,只能使用静态代理,或使用第三方方案,例如CGLIB库。

在了解了java的代理机制后,我们就能用它来对android做点什么了,先来个简单的,我们可以在AActivity中启动BActivity,并利用代理机制,在BActivity启动前输出一些日志。在hook之前我们先要弄明白Activity启动流程,通过阅读老罗的文章[Android应用程序内部启动Activity过程(startActivity)的源代码分析](http://blog.csdn.net/luoshengyang/article/details/6703247)和源码,我们可以知道startActivity最后会调用到ActivityThread的成员变量mInstrumentation的execStartActivity方法,因为Instrumentation没有实现接口,所以这里我们只能使用静态代理。

先写一个Instrumentation子类作为代理类

    public class MyInstrumentation extends Instrumentation {
        private static final String TAG = "zeng";
        private Instrumentation mSuper;
        public MyInstrumentation(Instrumentation instrumentation){
            mSuper = instrumentation;
        }
        public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
            Log.d(TAG, "\n执行了startActivity, 参数如下: \n" + "who = [" + who + "], " +
                    "\ncontextThread = [" + contextThread + "], \ntoken = [" + token + "], " +
                    "\ntarget = [" + target + "], \nintent = [" + intent +
                    "], \nrequestCode = [" + requestCode + "], \noptions = [" + options + "]");
            try {
                Method execStartActivityMethod = Instrumentation.class.getDeclaredMethod("execStartActivity", Context.class,IBinder.class,IBinder.class,Activity.class,Intent.class,int.class,Bundle.class);
                execStartActivityMethod.setAccessible(true);
                return (ActivityResult) execStartActivityMethod.invoke(mSuper,who,contextThread,token,target,intent,requestCode,options);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }
	}

再写一个Application类,并在attachBaseContext方法中实现hook,这个方法是应用启动,ActivityThread创建Application对象并绑定Context时调用。

	@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
            currentActivityThreadMethod.setAccessible(true);
            Object currentActivityThread = currentActivityThreadMethod.invoke(null);

            Field instrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
            instrumentationField.setAccessible(true);
            Instrumentation instrumentation = (Instrumentation) instrumentationField.get(currentActivityThread);
            instrumentationField.set(currentActivityThread,new MyInstrumentation(instrumentation));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

然后我们在AActivity中启动BActivity,就会看到MyInstrumentation.execStartActivity输出的log。


text:
package org.pocketserver.net.packet.play;

import org.pocketserver.net.Packet;
import org.pocketserver.net.PacketRegistry;

import io.netty.buffer.ByteBuf;

public class PacketPlayMobEffect extends Packet {
    private long entityId;
    private byte eventId;
    private byte effectId;
    private byte amplifier;
    private byte particles;
    private int duration;

    public PacketPlayMobEffect() {
        super(PacketRegistry.DefaultPacketType.MOB_EFFECT);
    }

    public PacketPlayMobEffect(long entityId, byte eventId, byte effectId, byte amplifier, byte particles, int
        duration) {
        super(PacketRegistry.DefaultPacketType.MOB_EFFECT);
        this.entityId = entityId;
        this.eventId = eventId;
        this.effectId = effectId;
        this.amplifier = amplifier;
        this.particles = particles;
        this.duration = duration;
    }

    @Override
    public void write(ByteBuf buf) throws Exception {
        buf.writeLong(entityId);
        buf.writeByte(eventId);
        buf.writeByte(effectId);
        buf.writeByte(amplifier);
        buf.writeByte(particles);
        buf.writeInt(duration);
    }

    @Override
    public void read(ByteBuf buf) throws Exception {
        entityId = buf.readLong();
        eventId = buf.readByte();
        effectId = buf.readByte();
        amplifier = buf.readByte();
        particles = buf.readByte();
        duration = buf.readInt();
    }
}