text:
module Network.API.Builder.API (
  -- * API
    API
  , APIT
  -- ** Running the API
  , execAPI
  , runAPI
  , runRoute
  , sendRoute
  , routeResponse
  , routeRequest
  -- ** Lifting
  , liftExcept
  , liftEither
  , liftManager
  , liftBuilder
  , liftState
  -- ** Changing the @Builder@ within the API
  , name
  , baseURL
  , customizeRoute
  , customizeRequest ) where

import Network.API.Builder.Builder
import Network.API.Builder.Error
import Network.API.Builder.Receive
import Network.API.Builder.Routes
import Network.API.Builder.Send

import Data.Bifunctor
import Control.Exception
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Data.ByteString.Lazy (ByteString)
import Data.Text (Text)
import Network.HTTP.Client
import Network.HTTP.Client.TLS

-- | Main API type. @s@ is the API's internal state, @e@ is the API's custom error type,
--   and @a@ is the result when the API runs. Based on the @APIT@ transformer.
type API s e a = APIT s e IO a

-- | Main API transformer type. @s@ is the API's internal state, @e@ is the API's custom error type,
--   and @a@ is the result when the API runs.
type APIT s e m a = ExceptT (APIError e) (ReaderT Manager (StateT Builder (StateT s m))) a

-- | Lifts an action that works on an @API@ to an action that works on an @API@.
--   This function is provided solely for future-proofing in the case that more transformers
--   need to be stacked on top - it's implemented simply as @id@ for the moment.
liftExcept :: Monad m => ExceptT (APIError e) (ReaderT Manager (StateT Builder (StateT s m))) a -> APIT s e m a
liftExcept = id

{-# DEPRECATED liftEither "Use liftExcept" #-}
-- | Identical to 'liftExcept', provided for (almost) compatibility.
liftEither :: Monad m => ExceptT (APIError e) (ReaderT Manager (StateT Builder (StateT s m))) a -> APIT s e m a
liftEither = id

-- | Lifts an action that works on a @Manager@ to one that works on an @API@.
liftManager :: Monad m => ReaderT Manager (StateT Builder (StateT s m)) a -> APIT s e m a
liftManager = lift

-- | Lifts an action that operates on a @Builder@ to one that works on an @API@. Useful
--   mainly for gaining access to a @Builder@ from inside an @API@.
liftBuilder :: Monad m => StateT Builder (StateT s m) a -> APIT s e m a
liftBuilder = lift . lift

-- | Lifts an action on an @API@'s state type @s@ to one that works on the @API@. Good
--   for messing with the state from inside the @API@.
liftState :: Monad m => StateT s m a -> APIT s e m a
liftState = lift . lift . lift

-- | Runs an @API@ by executing its transformer stack and dumping it all into @IO@. Only returns the actual result.
execAPI :: MonadIO m
       => Builder -- ^ initial @Builder@ for the @API@
       -> s -- ^ initial state @s@ for the @API@
       -> APIT s e m a -- ^ the actual @API@ to run
       -> m (Either (APIError e) a) -- ^ IO action that returns either an error or the result
execAPI b s api = do
  m <- liftIO $ newManager tlsManagerSettings
  (res, _, _) <- runAPI b m s api
  return res

-- | Runs an @API@ by executing its transformer stack and dumping it all into @IO@.
-- | Returns the actual result as well as the final states of the @Builder@ and custom state @s@.
runAPI :: MonadIO m
       => Builder -- ^ initial @Builder@ for the @API@
       -> Manager -- ^ manager for working with conduit functions
       -> s -- ^ initial state @s@ for the @API@
       -> APIT s e m a -- ^ the actual @API@ to run
       -> m (Either (APIError e) a, Builder, s) -- ^ IO action that returns either an error or the result, as well as the final states
runAPI b m s api = do
  ((res, b'), s') <- runStateT (runStateT (runReaderT (runExceptT api) m) b) s
  return (res, b', s')

-- | Runs a @Route@. Infers the type to convert to from the JSON with the @a@ in @API@,
--   and infers the error type from @e@.
runRoute :: (Receivable a, ErrorReceivable e, MonadIO m) => Route -> APIT s e m a
runRoute = sendRoute ()

-- | Runs a @Route@, but only returns the response and does nothing towards
--   decoding the response.
routeResponse :: (MonadIO m, ErrorReceivable e) => Route -> APIT s e m (Response ByteString)
routeResponse = sendRoute ()

eitherOr :: Maybe a -> b -> Either b a
a `eitherOr` b =
  case a of
    Just x -> Right x
    Nothing -> Left b

sendRoute :: (MonadIO m, Sendable t, ErrorReceivable e, Receivable r) => t -> Route -> APIT s e m r
sendRoute s r = do
  builder <- liftBuilder get
  manager <- liftManager ask
  req <- ExceptT $ return $ send builder r s `eitherOr` InvalidURLError
  response <- liftIO $ try $ httpLbs req manager
  res <- ExceptT $ return $ first HTTPError response
  ExceptT $ return $ receive res

-- | Try to construct a @Request@ from a @Route@ (with the help of the @Builder@). Returns @Nothing@ if
--   the URL is invalid or there is another error with the @Route@.
routeRequest :: Builder -> Route -> Maybe Request
routeRequest b route = send b route ()

-- | Modify the @name@ of the @Builder@ from inside an API. Using this is probably not the best idea,
--   it's nice if the @Builder@'s name is stable at least.
name :: Monad m => Text -> APIT s e m ()
name t = liftBuilder $ modify (\b -> b { _name = t })

-- | Modify the @baseURL@ of the @Builder@ from inside an API.
--   Can be useful for changing the API's endpoints for certain requests.
baseURL :: Monad m => Text -> APIT s e m ()
baseURL t = liftBuilder $ modify (\b -> b { _baseURL = t })

-- | Modify every @Route@ before it runs. Useful for adding extra params to every query,
--   for example.
customizeRoute :: Monad m => (Route -> Route) -> APIT s e m ()
customizeRoute f = liftBuilder $ modify (\b -> b { _customizeRoute = f })

-- | Modify every @Request@ before the API fetches it. Useful for adding headers to every request,
--   for example.
customizeRequest :: Monad m => (Request -> Request) -> APIT s e m ()
customizeRequest f = liftBuilder $ modify (\b -> b { _customizeRequest = f })


text:
function hello()
    print "Hello World"
end

function get1()
    return 1
end

function getPi()
    return 3.14
end

function factorial(x)
    if (x == 0 ) then
        return 1
    else
        return x * factorial(x-1)
    end

end

function pow(x, y)
    local result = x

    for i=1, (y-1) do
        result = result * x
    end

    return result
end

redpajama_set_name: RedPajamaGithub


text:
一款简洁的第三方饭否客户端

## 截屏

## 依赖
- [Cocoapods](https://github.com/CocoaPods/CocoaPods) 0.39.0 +
- iOS 9.0+
- Xcode 7.3+

## 构建
饭斯基使用[Cocoapods](https://github.com/CocoaPods/CocoaPods)构建

## URL Schemes
- fansky://compose 快速发饭
- fansky://search 搜索

## 许可证

This code is distributed under the terms and conditions of the MIT license.

```
Copyright (C) 2016 Zhiya Zang

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```


text:
import { each } from 'lodash';
import { createElement, PureComponent } from 'react';
import Button from '../../boundless-button/index';
import Progress from '../';

export default class ProgressDemo extends PureComponent {
    state = {
        barProgress: 0,
        meterProgress: 0,
    }

    componentDidMount() {
        each(this.refs, (value, key) => this.updateProgress(key));
    }

    componentWillUnmount() {
        window.clearTimeout(this.barTimerHandle);
        window.clearTimeout(this.meterTimerHandle);
    }

    updateProgress(type) {
        if (this.state[`${type}Progress`] < 100) {
            this[`${type}TimerHandle`] = window.setTimeout(() => {
                this.setState({ [`${type}Progress`]: this.state[`${type}Progress`] + 1 }, () => {
                    this.updateProgress(type);
                });
            }, 35);
        }
    }

    resetProgress(type) {
        window.clearTimeout(this[`${type}TimerHandle`]);

        this.setState({ [`${type}Progress`]: 0 }, () => { this.updateProgress(type); });
    }

    render() {
        return (

Horizontal Progress Bar

                    <Progress
                        ref='bar'
                        aria-label={`${this.state.barProgress}% complete`}
                        progress={`${this.state.barProgress}%`} />
                    <Button
                        onPressed={this.resetProgress.bind(this, 'bar')}
                        style={{ marginTop: '1rem' }}>
                        Reset
                    </Button>

Filling Progress Meter

                    <Progress
                        ref='meter'
                        id='progress-meter'
                        aria-label={`${this.state.meterProgress}% complete`}
                        progress={`${this.state.meterProgress}%`}
                        tweenProperty='height' />
                    <Button
                        onPressed={this.resetProgress.bind(this, 'meter')}
                        style={{ marginTop: '1rem' }}>
                        Reset
                    </Button>

Indeterminate Progress Bar

                    <Progress
                        ref='indeterminate'
                        aria-label={'Processing...'} />

        );
    }
}


text:
#import <ReactCommon/RCTTurboModule.h>

namespace facebook {
namespace react {

/**
 * Provide the TurboModule class for the given name.
 */
Class RNTesterTurboModuleClassProvider(const char *name);

/**
 * Provide a pure C++ instance of a TurboModule, specific to this app.
 */
std::shared_ptr<TurboModule> RNTesterTurboModuleProvider(const std::string &name, std::shared_ptr<CallInvoker> jsInvoker);

/**
 * Provide an instance of a ObjCTurboModule, given the ObjC instance, specific to this app.
 */
std::shared_ptr<TurboModule> RNTesterTurboModuleProvider(const std::string &name,
                                                         id<RCTTurboModule> instance,
                                                         std::shared_ptr<CallInvoker> jsInvoker,
                                                         std::shared_ptr<CallInvoker> nativeInvoker,
                                                         id<RCTTurboModulePerformanceLogger> perfLogger);

} // namespace react
} // namespace facebook


text:
'use strict';

load("test/mjsunit/wasm/wasm-module-builder.js");

// Basic tests.

const outOfUint32RangeValue = 1e12;
const kV8MaxWasmTableSize = 10000000;

function assertTableIsValid(table, length) {
  assertSame(WebAssembly.Table.prototype, table.__proto__);
  assertSame(WebAssembly.Table, table.constructor);
  assertTrue(table instanceof Object);
  assertTrue(table instanceof WebAssembly.Table);
  assertEquals(length, table.length);
}

(function TestConstructor() {
  assertTrue(WebAssembly.Table instanceof Function);
  assertSame(WebAssembly.Table, WebAssembly.Table.prototype.constructor);
  assertTrue(WebAssembly.Table.prototype.grow instanceof Function);
  assertTrue(WebAssembly.Table.prototype.get instanceof Function);
  assertTrue(WebAssembly.Table.prototype.set instanceof Function);
  let desc = Object.getOwnPropertyDescriptor(WebAssembly.Table.prototype, 'length');
  assertTrue(desc.get instanceof Function);
  assertSame(undefined, desc.set);

  assertThrows(() => new WebAssembly.Table(), TypeError);
  assertThrows(() => new WebAssembly.Table(1), TypeError);
  assertThrows(() => new WebAssembly.Table(""), TypeError);

  assertThrows(() => new WebAssembly.Table({}), TypeError);
  assertThrows(() => new WebAssembly.Table({initial: 10}), TypeError);

  assertThrows(() => new WebAssembly.Table({element: 0, initial: 10}), TypeError);
  assertThrows(() => new WebAssembly.Table({element: "any", initial: 10}), TypeError);

  assertThrows(() => new WebAssembly.Table(
    {element: "anyfunc", initial: -1}), TypeError);
  assertThrows(() => new WebAssembly.Table(
    {element: "anyfunc", initial: outOfUint32RangeValue}), TypeError);

  assertThrows(() => new WebAssembly.Table(
    {element: "anyfunc", initial: 10, maximum: -1}), TypeError);
  assertThrows(() => new WebAssembly.Table(
    {element: "anyfunc", initial: 10, maximum: outOfUint32RangeValue}), TypeError);
  assertThrows(() => new WebAssembly.Table(
    {element: "anyfunc", initial: 10, maximum: 9}), RangeError);

  let table;
  table = new WebAssembly.Table({element: "anyfunc", initial: 1});
  assertTableIsValid(table, 1);
  assertEquals(null, table.get(0));
  assertEquals(undefined, table[0]);

  table = new WebAssembly.Table({element: "anyfunc", initial: "2"});
  assertTableIsValid(table, 2);
  assertEquals(null, table.get(0));
  assertEquals(null, table.get(1));
  assertEquals(undefined, table[0]);
  assertEquals(undefined, table[1]);

  table = new WebAssembly.Table({element: "anyfunc", initial: {valueOf() { return "1" }}});
  assertTableIsValid(table, 1);
  assertEquals(null, table.get(0));
  assertEquals(undefined, table[0]);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0, maximum: 10});
  assertTableIsValid(table, 0);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0,  maximum: "10"});
  assertTableIsValid(table, 0);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0, maximum: {valueOf() { return "10" }}});
  assertTableIsValid(table, 0);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0, maximum: undefined});
  assertTableIsValid(table, 0);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0, maximum: 1000000});
  assertTableIsValid(table, 0);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0, maximum: kV8MaxWasmTableSize});
  assertTableIsValid(table, 0);

  assertThrows(
    () => new WebAssembly.Table(
      {element: "anyfunc", initial: 0, maximum: kV8MaxWasmTableSize + 1}),
    RangeError, /above the upper bound/);
})();

(function TestMaximumIsReadOnce() {
  var a = true;
  var desc = {element: "anyfunc", initial: 10};
  Object.defineProperty(desc, 'maximum', {get: function() {
    if (a) {
      a = false;
      return 16;
    }
    else {
      // Change the return value on the second call so it throws.
      return -1;
    }
  }});
  let table = new WebAssembly.Table(desc);
  assertTableIsValid(table, 10);
})();

(function TestMaximumDoesHasProperty() {
  var hasPropertyWasCalled = false;
  var desc = {element: "anyfunc", initial: 10};
  var proxy = new Proxy({maximum: 16}, {
    has: function(target, name) { hasPropertyWasCalled = true; }
  });
  Object.setPrototypeOf(desc, proxy);
  let table = new WebAssembly.Table(desc);
  assertTableIsValid(table, 10);
})();

(function TestLength() {
  for (let i = 0; i < 10; ++i) {
    let table = new WebAssembly.Table({element: "anyfunc", initial: i});
    assertEquals(i, table.length);
  }

  assertThrows(() => WebAssembly.Table.prototype.length.call([]), TypeError);
})();

(function TestGet() {
  let table = new WebAssembly.Table({element: "anyfunc", initial: 10});

  for (let i = 0; i < table.length; ++i) {
    assertEquals(null, table.get(i));
    assertEquals(null, table.get(String(i)));
  }
  for (let key of [0.4, "", []]) {
    assertEquals(null, table.get(key));
  }
  for (let key of [-1, NaN, {}, () => {}]) {
    assertThrows(() => table.get(key), TypeError);
  }
  for (let key of [table.length, table.length * 10]) {
    assertThrows(() => table.get(key), RangeError);
  }
  assertThrows(() => table.get(Symbol()), TypeError);
  assertThrows(() => WebAssembly.Table.prototype.get.call([], 0), TypeError);
})();

(function TestSet() {
  let builder = new WasmModuleBuilder;
  builder.addExport("host", builder.addImport("test", "f", kSig_v_v));
  builder.addExport("wasm", builder.addFunction("", kSig_v_v).addBody([]));
  let {wasm, host} = builder.instantiate({test: {f() {}}}).exports;

  let table = new WebAssembly.Table({element: "anyfunc", initial: 10});

  for (let f of [wasm, host]) {
    for (let i = 0; i < table.length; ++i) table.set(i, null);
    for (let i = 0; i < table.length; ++i) {
      assertSame(null, table.get(i));
      assertSame(undefined, table.set(i, f));
      assertSame(f, table.get(i));
      assertSame(undefined, table[i]);
    }

    for (let i = 0; i < table.length; ++i) table.set(i, null);
    for (let i = 0; i < table.length; ++i) {
      assertSame(null, table.get(i));
      assertSame(undefined, table.set(String(i), f));
      assertSame(f, table.get(i));
      assertSame(undefined, table[i]);
    }

    for (let key of [0.4, "", []]) {
      assertSame(undefined, table.set(0, null));
      assertSame(undefined, table.set(key, f));
      assertSame(f, table.get(0));
      assertSame(undefined, table[key]);
    }
    for (let key of [NaN, {}, () => {}]) {
      assertSame(undefined, table[key]);
      assertThrows(() => table.set(key, f), TypeError);
    }

    assertThrows(() => table.set(-1, f), TypeError);
    for (let key of [table.length, table.length * 10]) {
      assertThrows(() => table.set(key, f), RangeError);
    }

    assertThrows(() => table.set(0), TypeError);
    for (let val of [undefined, 0, "", {}, [], () => {}]) {
      assertThrows(() => table.set(0, val), TypeError);
    }

    assertThrows(() => table.set(Symbol(), f), TypeError);
    assertThrows(() => WebAssembly.Table.prototype.set.call([], 0, f),
                 TypeError);
  }
})();

(function TestIndexing() {
  let builder = new WasmModuleBuilder;
  builder.addExport("host", builder.addImport("test", "f", kSig_v_v));
  builder.addExport("wasm", builder.addFunction("", kSig_v_v).addBody([]));
  let {wasm, host} = builder.instantiate({test: {f() {}}}).exports;

  let table = new WebAssembly.Table({element: "anyfunc", initial: 10});

  for (let f of [wasm, host, () => {}, 5, {}, ""]) {
    for (let i = 0; i < table.length; ++i) table[i] = f;
    for (let i = 0; i < table.length; ++i) {
      assertSame(null, table.get(i));
      assertSame(f, table[i]);
    }

    for (let key of [NaN, {}, () => {}]) {
      assertSame(f, table[key] = f);
      assertSame(f, table[key]);
      assertThrows(() => table.get(key), TypeError);
    }
    for (let key of [0.4, "", []]) {
      assertSame(f, table[key] = f);
      assertSame(f, table[key]);
      assertSame(null, table.get(key));
    }
  }
})();

(function TestGrow() {
  let builder = new WasmModuleBuilder;
  builder.addExport("host", builder.addImport("test", "f", kSig_v_v));
  builder.addExport("wasm", builder.addFunction("", kSig_v_v).addBody([]));
  let {wasm, host} = builder.instantiate({test: {f() {}}}).exports;

  function init(table) {
    for (let i = 0; i < 5; ++i) table.set(i, wasm);
    for (let i = 15; i < 20; ++i) table.set(i, host);
  }
  function check(table) {
    for (let i = 0; i < 5; ++i) assertSame(wasm, table.get(i));
    for (let i = 6; i < 15; ++i) assertSame(null, table.get(i));
    for (let i = 15; i < 20; ++i) assertSame(host, table.get(i));
    for (let i = 21; i < table.length; ++i) assertSame(null, table.get(i));
  }

  let table = new WebAssembly.Table({element: "anyfunc", initial: 20});
  init(table);
  check(table);
  table.grow(0);
  check(table);
  table.grow(10);
  check(table);
  assertThrows(() => table.grow(-10), TypeError);

  table = new WebAssembly.Table({element: "anyfunc", initial: 20, maximum: 25});
  init(table);
  check(table);
  table.grow(0);
  check(table);
  table.grow(5);
  check(table);
  table.grow(0);
  check(table);
  assertThrows(() => table.grow(1), RangeError);
  assertThrows(() => table.grow(-10), TypeError);

  assertThrows(() => WebAssembly.Table.prototype.grow.call([], 0), TypeError);

  table = new WebAssembly.Table(
    {element: "anyfunc", initial: 0, maximum: kV8MaxWasmTableSize});
  table.grow(kV8MaxWasmTableSize);
  assertThrows(() => table.grow(1), RangeError);

  table = new WebAssembly.Table({element: "anyfunc", initial: 0});
  table.grow({valueOf: () => {table.grow(2); return 1;}});
  assertEquals(3, table.length);
})();


text:
import sys
import os.path
import subprocess
from collections import defaultdict
import traceback
import json

from PyQt5.QtCore import (
    QObject,
    QThread,
    QTimer,
    QPoint,
    QRect,
    QSize,
    Qt,
    pyqtSignal,
)
from PyQt5.QtGui import (
    QIcon,
    QPixmap,
)
import patricia
import polytaxis_monitor.common as ptcommon
import appdirs

from .qtwrapper import *
from .common import *
from .settings import res

# TODO
# element types to vars
# save queries

# tag editor
# launcher editor

one_file = '{one-file}'
all_files = '{all-files}'

icon_size = QSize(24, 24)
icon_remove = None
icons = {}

eltype_labels = {
    'inc': 'include',
    'exc': 'exclude',
    'sort_asc': 'sort ascending',
    'sort_desc': 'sort descending',
    'sort_rand': 'randomize',
    'col': 'show column',
}

known_columns = patricia.trie()

elements = []
drag_targets = []

def to_gen(outer):
    return outer()

unwrap_root = os.path.join(
    appdirs.user_data_dir('polytaxis-unwrap', 'zarbosoft'),
    'mount',
)

def unwrap(path):
    return os.path.join(unwrap_root, path[1:])

def collapse(callback):
    timer = QTimer()
    timer.setSingleShot(True)
    timer.setInterval(200)
    def out(*pargs, **kwargs):
        out.pargs = pargs
        out.kwargs = kwargs
        timer.start()
    out.stop = lambda: timer.stop()
    timer.timeout.connect(lambda: callback(*out.pargs, **out.kwargs))
    return out

class DragTarget(QFrame):
    dropped = pyqtSignal()

    def __init__(self, *pargs, parent=None, **kwargs):
        super(DragTarget, self).__init__(*pargs, **kwargs)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        self.setProperty('drag-hover', True)
        self.style().unpolish(self)
        self.style().polish(self)
        self.update()
        event.accept()

    def dragLeaveEvent(self, event):
        self.setProperty('drag-hover', False)
        self.style().unpolish(self)
        self.style().polish(self)
        self.update()
        super().dragLeaveEvent(event)

    def dropEvent(self, event):
        self.dropped.emit()

@enable_drag
class ElementButton(LayoutPushButton):
    pass

class ElementBuilder(QObject):
    worker_result = pyqtSignal(int, list)

    def __init__(self):
        super(ElementBuilder, self).__init__()
        self.element = None
        self.worker = None

        self.query_unique = 0
        self.text = None
        self.label = QLabel(tags=['builder-label'])
        self.entry = QLineEdit(tags=['builder-entry'])
        self.entry_layout = QHBoxLayout(tags=['builder-head-layout'])
        self.entry_layout.addWidget(self.label)
        self.entry_layout.addWidget(self.entry)
        self.results = QListWidget(tags=['builder-list'])
        layout = QVBoxLayout(tags=['builder-layout'])
        layout.addLayout(self.entry_layout)
        layout.addWidget(self.results)
        self.outer_widget = QFrame(tags=['builder-widget'])
        self.outer_widget.setLayout(layout)

        suppress_row_select = [False]

        @self.entry.textEdited.connect
        def edited(text):
            self.element.set_value(text)
            self.element.last_query = text
            self.change_query()

        @self.results.currentTextChanged.connect
        def selected(text):
            if suppress_row_select[0]:
                return
            if not text:
                return
            self.element.set_value(text)
            self.entry.setText(text)

        @self.worker_result.connect
        def handle_result(unique, values):
            if unique != self.query_unique:
                return
            for row, value in enumerate(values):
                self.results.addItem(value)
                if value == self.text:
                    suppress_row_select[0] = True
                    self.results.setCurrentRow(row)
                    suppress_row_select[0] = False

    @collapse
    def _reset_query(self):
        self.query_unique += 1
        self.text = self.entry.text()
        if self.element.type in ('sort_asc', 'sort_desc', 'sort_rand', 'col'):
            for row, column in enumerate(known_columns.iter(self.element.last_query)):
                self.results.addItem(column)
                if column == self.text:
                    self.results.setCurrentRow(row)
        elif self.element.type in ('inc', 'exc'):
            self.worker.build_query.emit(self.query_unique, self.element.last_query)

    def change_query(self):
        self.worker.build_query.emit(-1, '')
        self.results.clear()
        self._reset_query()

    def set_element(self, element):
        if element == self.element:
            return
        if self.element:
            self.element.auto_deselect()
        self.element = element
        if element is None:
            self.worker.build_query.emit(-1, '')
            self.outer_widget.hide()
        else:
            self.label.setPixmap(icons[element.type])
            self.entry.setText(element.value)
            self.change_query()
            self.outer_widget.show()
            self.entry.setFocus()

class Display(QObject):
    worker_result = pyqtSignal(int, list)
    def __init__(self):
        super(Display, self).__init__()

        self.worker = None

        self.query_unique = 0
        self.columns = None
        self.sort = None
        self.filters = None
        self.includes = None
        self.excludes = None
        self.raw = []

        self.launchers = []

        context_menu = QMenu()
        open_menu = QMenu()
        self.results = MouseLMRTreeWidget(tags=['display-tree'])
        self.results.setSelectionMode(QTreeWidget.ExtendedSelection)
        @self.results.customContextMenuRequested.connect
        def callback(point):
            context_menu.exec(point)
        self.results.header().hide()
        actions = QToolBar(tags=['display-toolbar'])
        tool_open = actions.addAction('Open')
        tool_open.setMenu(open_menu)
        tool_open.setEnabled(False)
        layout = QVBoxLayout(tags=['display-layout'])
        layout.addWidget(self.results)
        layout.addWidget(actions)
        self.outer_widget = QFrame(tags=['display-widget'])
        self.outer_widget.setLayout(layout)

        def spawn(command):
            print('spawning {}'.format(command))
            proc = subprocess.Popen(
                command,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            proc.stdin.close()
            proc.stdout.close()
            proc.stderr.close()

        def do_open(option):
            print('callin open')
            rows = [
                self.raw[index.row()]
                for index in self.results.selectedIndexes()
                if index.column() == 0
            ]
            if not rows:
                rows = self.raw
            if not rows:
                return
            paths = [
                unwrap(path) if option.get('unwrap', True) else path
                for path in [
                    next(iter(row['tags']['path']))
                    for row in rows
                ]
            ]
            if one_file in option['command']:
                for path in paths:
                    spawn([
                        path if arg == one_file else arg
                        for arg in option['command']
                    ])
            else:
                if all_files not in option['command']:
                    raise RuntimeError('Option {} doesn\'t have any filepath arguments.'.format(option['name']))
                args = []
                for arg in option['command']:
                    if arg == all_files:
                        args.extend(paths)
                    else:
                        args.append(arg)
                spawn(args)

        @collapse
        def update_launch_concensus():
            launch_sums = defaultdict(lambda: {'count': 0, 'launcher': None})
            rows = [
                self.raw[index.row()]
                for index in self.results.selectedIndexes()
            ]
            if not rows:
                rows = self.raw
            for data in rows:
                for key in data['tags']['launch_keys']:
                    launcher_bunch = keyed_launchers.get(key)
                    if launcher_bunch:
                        launch_sum = launch_sums.get(id(launcher_bunch))
                        if not launch_sum:
                            launch_sum = {
                                'count': 0,
                                'launcher_bunch': launcher_bunch,
                            }
                            launch_sums[id(launcher_bunch)] = launch_sum
                        launch_sum['count'] += 1
            self.launchers = []
            for top in sorted(launch_sums.items(), key=lambda x: x[1]['count']):
                if len(self.launchers) > 5:
                    break
                launcher_bunch = top[1]['launcher_bunch']
                if not launcher_bunch:
                    continue
                self.launchers.extend(launcher_bunch)
            self.launchers.extend(
                wildcard_launchers
            )

            def build_action(menu, launcher):
                action = menu.addAction(launcher['name'])
                def launch():
                    do_open(launcher)
                action.triggered.connect(launch)
            for menu in [open_menu, context_menu]:
                menu.clear()
                for launcher in self.launchers:
                    build_action(menu, launcher)
            if self.launchers:
                tool_open.setText('Open with ' + self.launchers[0]['name'])
            tool_open.setEnabled(bool(self.launchers))

        @self.worker_result.connect
        def handle_result(unique, rows):
            if unique != self.query_unique:
                return
            for row in rows:
                for key in row['tags'].keys():
                    known_columns[key] = None
            self.raw.extend(rows)
            self._redisplay()
            update_launch_concensus()

        @self.results.m_clicked_anywhere.connect
        def handle_m_clicked():
            self.results.clearSelection()

        @self.results.itemSelectionChanged.connect
        def callback():
            update_launch_concensus()

        @self.results.r_clicked_anywhere.connect
        def handle_r_clicked(position):
            context_menu.exec(position)

        @self.results.doubleClicked.connect
        def handle_clicked(index):
            if not self.launchers:
                return
            do_open(self.launchers[0])

        @tool_open.triggered.connect
        def handle_clicked(index):
            if not self.launchers:
                return
            do_open(self.launchers[0])

    @collapse
    def _reset_query(self, unique):
        self.worker.display_query.emit(unique, self.includes, self.excludes)

    def _redisplay(self):
        self.raw = ptcommon.sort(self.sort, self.raw)
        self.results.clear()
        #self.results.setRowCount(0)
        for row in self.raw:
            self.results.addTopLevelItem(QTreeWidgetItem([
                ', '.join(list(row['tags'].get(column, [])))
                for column in self.columns]))
        self.results.header().resizeSections(QHeaderView.ResizeToContents)

    def change_query(self):
        self.worker.display_query.emit(-1, set(), set())
        cleared = [False]
        def clear():
            if not cleared[0]:
                cleared[0] = True
            self.results.clear()

        includes = {
            element.value for element in elements if element.type == 'inc'}
        excludes = {
            element.value for element in elements if element.type == 'exc'}
        columns = []
        sort = []
        for element in elements:
            if (
                    element.type in ('col', 'sort_asc', 'sort_desc', 'sort_rand')
                    and element.value
                    and element.value not in columns
                    ):
                columns.append(element.value)
            if element.type == 'sort_asc':
                sort.append(('asc', element.value))
            elif element.type == 'sort_desc':
                sort.append(('desc', element.value))
            elif element.type == 'sort_rand':
                sort.append(('rand', element.value))

        if includes != self.includes or excludes != self.excludes:
            self.query_unique += 1
            known_columns = patricia.trie()
            self.raw = []
            self.includes = includes
            self.excludes = excludes
            clear()
            if self.includes or self.excludes:
                self._reset_query(self.query_unique)

        if columns != self.columns or sort != self.sort:
            self.columns = columns
            self.sort = sort
            if self.columns:
                self.results.setColumnCount(len(self.columns))
                self.results.setHeaderLabels(self.columns)
                self.results.header().show()
            else:
                self.results.header().hide()
                self.results.setColumnCount(1)
                self.columns = ['filename']
                self.sort.append(('asc', 'filename'))
            clear()
            self._redisplay()

wildcard_launchers = []
keyed_launchers = defaultdict(lambda: [])
def main():
    launchers_path = os.path.join(
        appdirs.user_config_dir('polytaxis-adventure'),
        'launchers.json',
    )
    try:
        with open(launchers_path, 'r') as launchers_file:
            launchers = json.load(launchers_file)
        for launcher in launchers:
            for key in launcher['keys']:
                if key == '*':
                    wildcard_launchers.append(launcher)
                else:
                    keyed_launchers[key].append(launcher)
    except:
        print('Failed to load {}:\n{}'.format(
            launchers_path,
            traceback.format_exc())
        )

    app = QApplication(sys.argv)

    global icon_remove
    icon_remove = QPixmap(res('icon_remove.png'))
    global icons
    icons = {
        key: QPixmap(res('icon_{}.png'.format(key)))
        for key in [
            'exc',
            'inc',
            'col',
            'sort_asc',
            'sort_desc',
            'sort_rand',
        ]
    }
    icons['logo'] = QPixmap(res('logo.png'))
    for icon in icons.values():
        if not icon:
            raise RuntimeError('Unable to load icon {}'.format(icon))

    class Worker(QObject):
        build_query = pyqtSignal(int, str)
        display_query = pyqtSignal(int, set, set)
        def __init__(self):
            super(Worker, self).__init__()

            self.build = None
            self.display = None

            self.current_build_query = None
            self.current_display_query = None
            self.db = ptcommon.QueryDB()
            self.queue = []
            self.idle = QTimer()
            self.idle.setInterval(0)
            @self.idle.timeout.connect
            def idle():
                if not self.queue:
                    self.idle.stop()
                    return
                work = self.queue.pop()
                try:
                    next(work)
                except StopIteration:
                    return
                self.queue.append(work)
            self.idle.start()

            @self.build_query.connect
            def build_query_handler(unique, arg):
                try:
                    self.queue.remove(self.current_build_query)
                except ValueError:
                    pass
                if unique == -1:
                    self.current_build_query = None
                    return
                @to_gen
                def work():
                    count = 0
                    work = self.db.query_tags('prefix', arg)
                    while True:
                        rows = list(limit(100, work))
                        if not rows:
                            raise StopIteration()
                        count += len(rows)
                        self.build.worker_result.emit(unique, rows)
                        if count >= 1000:
                            break
                        yield
                self.queue.append(work)
                self.current_build_query = work
                self.idle.start()

            @self.display_query.connect
            def display_query_handler(unique, includes, excludes):
                try:
                    self.queue.remove(self.current_display_query)
                except ValueError:
                    pass
                if unique == -1:
                    self.current_display_query = None
                    self.db.clear_cache()
                    return
                @to_gen
                def work():
                    count = 0
                    work = self.db.query(
                            includes, excludes,
                        add_path=True)
                    while True:
                        rows = list(limit(100, work))
                        if not rows:
                            raise StopIteration()
                        count += len(rows)
                        for row in rows:
                            path = next(iter(row['tags']['path']))
                            filename = ptcommon.split_abs_path(path)[-1]
                            row['tags']['filename'] = {filename}
                            filename_splits = filename.split('.')
                            launch_keys = set()
                            for index in range(1, len(filename_splits)):
                                launch_keys.add(
                                    '.' + '.'.join(filename_splits[index:]))
                            row['tags']['launch_keys'] = launch_keys
                        self.display.worker_result.emit(unique, rows)
                        if count >= 1000:
                            break
                        yield
                self.queue.append(work)
                self.current_display_query = work
                self.idle.start()

    worker_thread = QThread()
    worker_thread.start()

    worker = Worker()
    worker.moveToThread(worker_thread)

    # Query element specification
    build = ElementBuilder()
    build.worker = worker
    worker.build = build

    # Result display and interaction
    display = Display()
    display.worker = worker
    worker.display = display

    # Query bar
    appicon = QToolButton(tags=['appicon'])
    appicon.setIcon(QIcon(icons['logo']))
    appicon.setIconSize(QSize(48, 48))
    appicon.setToolTip('Clear query')
    @appicon.clicked.connect
    def callback(checked):
        for element in elements[:]:
            element.destroy()

    query = FlowLayout(tags=['query-layout'])
    query_empty = QLabel('empty query', tags=['query-empty'])
    query.addWidget(query_empty)
    query_toolbar = QToolBar(tags=['query-toolbar'])
    query_toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
    def create_query_element_action(eltype):
        ellabel = eltype_labels[eltype]
        action = QAction(QIcon(icons[eltype]), ellabel, query_toolbar, tags=['query-tool', eltype])
        query_toolbar.addAction(action)
        def create(ign1):
            class Element():
                type = eltype
                value = ''
                last_query = ''

                def recreate_widgets(self):
                    layout = QHBoxLayout(tags=['element-layout', eltype])
                    icon = QLabel(tags=['element-icon', eltype])
                    icon.setPixmap(icons[eltype])
                    layout.addWidget(icon)
                    self.text = QLabel(self.value, tags=['element-text', eltype])
                    layout.addWidget(self.text)
                    self.delete = QToolButton(tags=['element-remove', eltype])
                    self.delete.setIcon(QIcon(icon_remove))
                    layout.addWidget(self.delete)
                    self.toggle = ElementButton(tags=['element-toggle', eltype])
                    self.toggle.setLayout(layout)
                    self.delete.hide()

                    @self.toggle.toggled.connect
                    def click_action(checked):
                        if checked:
                            self.select()
                        else:
                            self.deselect()

                    def clear_drag():
                        for target in drag_targets:
                            query.removeWidget(target)
                        del drag_targets[:]

                    @self.toggle.drag_start.connect
                    def callback():
                        sindex = elements.index(self)
                        for index in range(len(elements) + 1):
                            if index in (sindex, sindex + 1):
                                continue
                            target = DragTarget(tags=['drag-target'])
                            @target.dropped.connect
                            def callback(index=index, sindex=sindex):
                                clear_drag()
                                dindex = index if index < sindex else index - 1
                                elements.insert(dindex, elements.pop(sindex))
                                display.change_query()
                                was_checked = self.toggle.checked()
                                query.removeWidget(self.toggle)
                                self.recreate_widgets()
                                query.insertWidget(dindex + 1, self.toggle)
                                if was_checked:
                                    self.select()
                            query.insertWidget(index + len(drag_targets) + 1, target)
                            drag_targets.append(target)

                    @self.toggle.drag_stop.connect
                    def callback():
                        clear_drag()

                    @self.delete.clicked.connect
                    def delete_action(checked):
                        self.destroy()

                def __init__(self):
                    self.recreate_widgets()
                    query.addWidget(self.toggle)
                    query_empty.hide()

                def set_value(self, value):
                    self.value = value
                    self.text.setText(value)
                    display.change_query()

                def auto_deselect(self):
                    self.toggle.setChecked(False)
                    self.delete.hide()

                def deselect(self):
                    build.set_element(None)
                    self.delete.hide()

                def select(self):
                    build.set_element(self)
                    self.toggle.setChecked(True)
                    self.delete.show()

                def destroy(self):
                    self.deselect()
                    elements.remove(self)
                    display.change_query()
                    query.removeWidget(self.toggle)
                    if not elements:
                        query_empty.show()

            element = Element()
            element.select()
            elements.append(element)

        action.triggered.connect(create)
    create_query_element_action('inc')
    create_query_element_action('exc')
    create_query_element_action('sort_asc')
    create_query_element_action('sort_desc')
    create_query_element_action('sort_rand')
    create_query_element_action('col')
    query_layout = QVBoxLayout(tags=['outer-query-layout'])
    query_layout.addLayout(query, 1)
    query_layout.addWidget(query_toolbar)

    total_query_layout = QHBoxLayout(tags=['top-layout'])
    total_query_layout.addWidget(appicon)
    total_query_layout.addLayout(query_layout, 1)

    # Assemblage
    bottom_splitter = QSplitter(Qt.Horizontal, tags=['bottom-splitter'])
    bottom_splitter.addWidget(build.outer_widget)
    bottom_splitter.addWidget(display.outer_widget)

    total_layout = QVBoxLayout(tags=['window-layout'])
    total_layout.addLayout(total_query_layout)
    total_layout.addWidget(bottom_splitter, 1)

    window = QFrame(tags=['window'])
    window.setObjectName('window')
    window.setLayout(total_layout)
    window.show()

    build.outer_widget.hide()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
from ctypes import cdll
import time
lib = cdll.LoadLibrary("/tmp/fibonacci.so")

def fib_count(n):
    if n < 1:
        return 0
    elif n < 3:
        return 1
    a, b = 1, 1
    f = 0
    for _ in range(3, n+1):
        f = a + b
        a = b
        b = f
    return f

def fib_recursive(n):
    if n < 1:
        return 0
    elif n < 2:
        return 1
    return fib_recursive(n-1) + fib_recursive(n-2)

def fib_recursive_hash(n):
    h = {}

    def f(n):
        if n < 1:
            h[n] = 0
            return 0
        elif n < 2:
            h[n] = 1
            return 1
        a = h.get(n-1, f(n-1))
        b = h.get(n-2, f(n-2))
        h[n] = a + b
        return a + b
    return f(n)

fib_num = 35
print("All values count fibonacci for n={}".format(fib_num))
t = float(time.time())
lib.fibonacci_recursive(fib_num)
rt = float(time.time()) - t
print("Time Taken for recursive: {} seconds".format(rt))

t = float(time.time())
fib_recursive(fib_num)
pt = float(time.time()) - t
print("Time Taken for python recursive: {} seconds".format(pt))
print("Difference: {} milli seconds".format((pt - rt)*1000))
print("")

t = float(time.time())
lib.fibonacci_hash_recursive(fib_num)
rt = float(time.time()) - t
print("Time Taken for hash: {} seconds".format(rt))

t = float(time.time())
fib_recursive_hash(fib_num)
pt = float(time.time()) - t
print("Time Taken for python recursive hash: {} seconds".format(pt))
print("Difference: {} milli seconds".format((pt - rt)*1000))
print("")

t = float(time.time())
lib.fibonacci_fast(fib_num)
rt = float(time.time()) - t
print("Time Taken for fast: {} seconds".format(rt))

t = float(time.time())
fib_count(fib_num)
pt = float(time.time()) - t
print("Time Taken for python fast: {} seconds".format(pt))
print("Difference: {} milli seconds".format((pt - rt)*1000))
print("")

print("done!")


text:
package logstash

// logstash.go defines the logtash plugin (using lumberjack protocol) as being
// registered with all output plugins

import (
	"expvar"
	"time"

	"github.com/urso/go-lumber/log"

	"github.com/elastic/beats/libbeat/common"
	"github.com/elastic/beats/libbeat/common/op"
	"github.com/elastic/beats/libbeat/logp"
	"github.com/elastic/beats/libbeat/outputs"
	"github.com/elastic/beats/libbeat/outputs/mode"
	"github.com/elastic/beats/libbeat/outputs/mode/modeutil"
	"github.com/elastic/beats/libbeat/outputs/transport"
)

var debug = logp.MakeDebug("logstash")

// Metrics that can retrieved through the expvar web interface.
var (
	ackedEvents            = expvar.NewInt("libbeatLogstashPublishedAndAckedEvents")
	eventsNotAcked         = expvar.NewInt("libbeatLogstashPublishedButNotAckedEvents")
	publishEventsCallCount = expvar.NewInt("libbeatLogstashPublishEventsCallCount")

	statReadBytes   = expvar.NewInt("libbeatLogstashPublishReadBytes")
	statWriteBytes  = expvar.NewInt("libbeatLogstashPublishWriteBytes")
	statReadErrors  = expvar.NewInt("libbeatLogstashPublishReadErrors")
	statWriteErrors = expvar.NewInt("libbeatLogstashPublishWriteErrors")
)

const (
	defaultWaitRetry = 1 * time.Second

	// NOTE: maxWaitRetry has no effect on mode, as logstash client currently does
	// not return ErrTempBulkFailure
	defaultMaxWaitRetry = 60 * time.Second
)

func init() {
	log.Logger = logstashLogger{}

	outputs.RegisterOutputPlugin("logstash", new)
}

func new(cfg *common.Config, _ int) (outputs.Outputer, error) {
	output := &logstash{}
	if err := output.init(cfg); err != nil {
		return nil, err
	}
	return output, nil
}

type logstash struct {
	mode  mode.ConnectionMode
	index string
}

func (lj *logstash) init(cfg *common.Config) error {
	config := defaultConfig
	if err := cfg.Unpack(&config); err != nil {
		return err
	}

	sendRetries := config.MaxRetries
	maxAttempts := sendRetries + 1
	if sendRetries < 0 {
		maxAttempts = 0
	}

	tls, err := outputs.LoadTLSConfig(config.TLS)
	if err != nil {
		return err
	}

	transp := &transport.Config{
		Timeout: config.Timeout,
		Proxy:   &config.Proxy,
		TLS:     tls,
		Stats: &transport.IOStats{
			Read:        statReadBytes,
			Write:       statWriteBytes,
			ReadErrors:  statReadErrors,
			WriteErrors: statWriteErrors,
		},
	}

	logp.Info("Max Retries set to: %v", sendRetries)
	var m mode.ConnectionMode
	if config.Pipelining == 0 {
		clients, err := modeutil.MakeClients(cfg, makeClientFactory(&config, transp))
		if err == nil {
			m, err = modeutil.NewConnectionMode(clients, !config.LoadBalance,
				maxAttempts, defaultWaitRetry, config.Timeout, defaultMaxWaitRetry)
		}
	} else {
		clients, err := modeutil.MakeAsyncClients(cfg,
			makeAsyncClientFactory(&config, transp))
		if err == nil {
			m, err = modeutil.NewAsyncConnectionMode(clients, !config.LoadBalance,
				maxAttempts, defaultWaitRetry, config.Timeout, defaultMaxWaitRetry)
		}
	}
	if err != nil {
		return err
	}

	lj.mode = m
	lj.index = config.Index

	return nil
}

func makeClientFactory(
	cfg *logstashConfig,
	tcfg *transport.Config,
) modeutil.ClientFactory {
	compressLvl := cfg.CompressionLevel
	maxBulkSz := cfg.BulkMaxSize
	to := cfg.Timeout

	return func(host string) (mode.ProtocolClient, error) {
		t, err := transport.NewClient(tcfg, "tcp", host, cfg.Port)
		if err != nil {
			return nil, err
		}
		return newLumberjackClient(t, compressLvl, maxBulkSz, to, cfg.Index)
	}
}

func makeAsyncClientFactory(
	cfg *logstashConfig,
	tcfg *transport.Config,
) modeutil.AsyncClientFactory {
	compressLvl := cfg.CompressionLevel
	maxBulkSz := cfg.BulkMaxSize
	queueSize := cfg.Pipelining - 1
	to := cfg.Timeout

	return func(host string) (mode.AsyncProtocolClient, error) {
		t, err := transport.NewClient(tcfg, "tcp", host, cfg.Port)
		if err != nil {
			return nil, err
		}
		return newAsyncLumberjackClient(t, queueSize, compressLvl, maxBulkSz, to, cfg.Index)
	}
}

func (lj *logstash) Close() error {
	return lj.mode.Close()
}

// TODO: update Outputer interface to support multiple events for batch-like
//       processing (e.g. for filebeat). Batch like processing might reduce
//       send/receive overhead per event for other implementors too.
func (lj *logstash) PublishEvent(
	signaler op.Signaler,
	opts outputs.Options,
	event common.MapStr,
) error {
	return lj.mode.PublishEvent(signaler, opts, event)
}

// BulkPublish implements the BulkOutputer interface pushing a bulk of events
// via lumberjack.
func (lj *logstash) BulkPublish(
	trans op.Signaler,
	opts outputs.Options,
	events []common.MapStr,
) error {
	return lj.mode.PublishEvents(trans, opts, events)
}


text:
layout: default
excerpt: I'm Mukil. A Web Developer and Tech Enthusiast. Know more about me, my works and posts.
---

<md-grid-list
      md-cols="1" md-cols-sm="2" md-cols-gt-sm="4" md-cols-gt-md="4"
      md-cols-gt-lg="6" md-row-height-gt-md="1:1" md-row-height="1:1"
      md-row-height-xs="4:3"
      md-gutter="8px" md-on-layout="show($event)" ng-hide="gridLay">

  <md-grid-tile md-rowspan="2" md-colspan="4"
                md-colspan-sm="2" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'blue-grey-700'}"
                md-ink-ripple="true" ng-click="navigate('/about/');">
    <tile image="/assets/about.svg" size="100% !important">
      <tile-header tag="Know who I am & what am I upto">About Me</tile-header>
      <tile-footer>About Me</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="2" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'orange-600'}"
                md-ink-ripple="true" ng-click="navigate('/portfolio/')">
    <tile image="/assets/code.svg" opacity="0.87">
      <tile-header tag="Collection of some of my projects">My Projects</tile-header>
      <tile-footer>Experience</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                class="tle" md-colors="{background: 'green-400'}"
                md-ink-ripple="true" ng-click="navigate('{% link _posts/2017-02-15-google-top-contributor.md %}');">
    <tile image="/assets/tc-badge.png" pos="90% 50%" opacity="0.87" size="150px" class="tile-right">
      <tile-header tag="Google Play Help Forum">Google Top Contributor</tile-header>
      <tile-footer>Community</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                class="tle" md-colors="{background: 'grey-900'}"
                md-ink-ripple="true" ng-click="navigate('/opensource/');">
    <tile image="/assets/github.svg" opacity="0.87" pos="90% 50%" size='150px' class="tile-right">
      <tile-header tag="How opensource changed my career">I love Opensource</tile-header>
      <tile-footer>OpenSource</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                class="tle" md-colors="{background: 'brown-700'}"
                md-ink-ripple="true" ng-click="navigate('{% link _posts/2017-01-08-freecodecamp.md %}')">
    <tile image="/assets/fcc.svg" opacity="0.87" size="150px" pos="90% 50%" class="tile-right">
      <tile-header tag="Being a student at FCC">Free Code Camp</tile-header>
      <tile-footer>Community</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="2" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'teal-500'}"
                md-ink-ripple="true" ng-click="navigate('/articles/arduino/')">
    <tile image="/assets/arduino.svg" opacity="1" size="250px">
      <tile-header tag="Into the world of Physical Computing">Arduino</tile-header>
      <tile-footer>Curiosity</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                class="tle" md-colors="{background: 'amber-500'}"
                md-ink-ripple="true" ng-click="navigate('/certificates/')">
    <tile image="/assets/medal.svg" pos="90% 50%" size="150px" opacity="0.87" class="tile-right">
      <tile-header tag="Certificates that I earned">Certificates</tile-header>
      <tile-footer>Achievements</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="2" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'pink-600'}"
                md-ink-ripple="true" ng-click="navigate('/articles/raspberrypi/')">
    <tile image="/assets/raspberrypi.svg" opacity="0.87" size="250px">
      <tile-header tag="Building a Smart Home with credit-card sized computer">Raspberry Pi</tile-header>
      <tile-footer>Passion</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'deep-purple-600'}"
                md-ink-ripple="true" ng-click="navigate('/articles/scouting/')">
    <tile image="/assets/scout-logo.svg" opacity="0.87" size="150px" pos="90% 50%" class="tile-right">
      <tile-header tag="Me as a Scout">Scouting</tile-header>
      <tile-footer>Passion</tile-footer>
    </tile>
  </md-grid-tile>

  <md-grid-tile md-rowspan="1" md-colspan="2"
                md-colspan-sm="1" md-colspan-xs="1"
                md-rowspan-sm="1" md-rowspan-xs="1"
                class="tle" md-colors="{background: 'cyan-900'}"
                md-ink-ripple="true" ng-click="navigate('/extra/')">
    <tile image="/assets/extra.svg" opacity="0.87" size="150px" pos="90% 50%" class="tile-right">
      <tile-header tag="My hobbies">Extras</tile-header>
      <tile-footer>Passion</tile-footer>
    </tile>
  </md-grid-tile>

</md-grid-list>

{% include sendMessage.html %}


text:
#region License

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VimeoApi.Models
{
    #region Result Sets

    public class DefaultResultSet<T>
    {
        public int? total { get; set; }
        public int? page { get; set; }
        public int? per_page { get; set; }
        public Paging paging { get; set; }
        public List<T> data { get; set; }
    }

    #endregion

    #region Result Data Models

    public class Privacy
    {
        public string view { get; set; }
        public string embed { get; set; }
        public bool download { get; set; }
        public bool add { get; set; }
        public string join { get; set; }
        public string videos { get; set; }
        public string comment { get; set; }
        public string forums { get; set; }
        public string invite { get; set; }
    }

    public class Picture
    {
        public string type { get; set; }
        public int width { get; set; }
        public int height { get; set; }
        public string link { get; set; }
    }

    public class Stat
    {
        public int? plays { get; set; }
        public int likes { get; set; }
        public int comments { get; set; }
        public int videos { get; set; }
        public int users { get; set; }
        public int moderators { get; set; }
        public int topics { get; set; }
        public int albums { get; set; }
        public int channels { get; set; }
        public int groups { get; set; }
    }

    public class Tag
    {
        public string name { get; set; }
        public string canonical { get; set; }
    }

    public class VideoTag
    {
        public string uri { get; set; }
        public string tag { get; set; }
    }

    public class Connection
    {
        public string credits { get; set; }
        public string activities { get; set; }
        public string albums { get; set; }
        public string channels { get; set; }
        public string feed { get; set; }
        public string followers { get; set; }
        public string following { get; set; }
        public string groups { get; set; }
        public string likes { get; set; }
        public string portfolios { get; set; }
        public string videos { get; set; }
        public string watchlater { get; set; }
        public string shared { get; set; }
        public string users { get; set; }
    }

    public class Metadata
    {
        public Connection connections { get; set; }
        public Interaction interactions { get; set; }
    }

    public class Follow
    {
        public bool added { get; set; }
        public DateTime? added_time { get; set; }
        public string type { get; set; }
        public string uri { get; set; }
    }

    public class Logos
    {
        public bool vimeo { get; set; }
        public bool custom { get; set; }
        public bool sticky_custom { get; set; }
    }

    public class Join
    {
        public bool added { get; set; }
        public DateTime? added_time { get; set; }
        public string status { get; set; }
        public string title { get; set; }
        public string uri { get; set; }
    }

    public class Watchlater
    {
        public bool added { get; set; }
        public DateTime? added_time { get; set; }
        public string uri { get; set; }
    }

    public class Like
    {
        public bool added { get; set; }
        public DateTime? added_time { get; set; }
        public string uri { get; set; }
    }

    public class Interaction
    {
        public Follow follow { get; set; }
        public Join join { get; set; }
        public Watchlater watchlater { get; set; }
        public Like like { get; set; }
    }

    public class Button
    {
        public bool like { get; set; }
        public bool watchlater { get; set; }
        public bool share { get; set; }
        public bool embed { get; set; }
        public bool vote { get; set; }
        public bool hd { get; set; }
    }

    public class Logo
    {
        public bool vimeo { get; set; }
        public bool custom { get; set; }
        public bool sticky_custom { get; set; }
    }

    public class Setting
    {
        public Button buttons { get; set; }
        public Logo logos { get; set; }
        public string outro { get; set; }
        public string portrait { get; set; }
        public string title { get; set; }
        public string byline { get; set; }
        public bool badge { get; set; }
        public bool byline_badge { get; set; }
        public bool playbar { get; set; }
        public bool volume { get; set; }
        public bool fullscreen_button { get; set; }
        public bool scaling_button { get; set; }
        public bool autoplay { get; set; }
        public bool autopause { get; set; }
        public bool loop { get; set; }
        public string color { get; set; }
        public bool link { get; set; }
        public object color_original { get; set; }
        public string custom_logo_url { get; set; }
        public string custom_logo_link_url { get; set; }
        public bool? custom_logo_use_link { get; set; }
        public int? logo_width { get; set; }
        public int? logo_height { get; set; }
    }

    public class EmbedPresets
    {
        public string uri { get; set; }
        public string name { get; set; }
        public Setting settings { get; set; }
    }

    public class Resource
    {
        public string uri { get; set; }
        public string name { get; set; }
    }

    public class Context
    {
        public string action { get; set; }
        public string resource_type { get; set; }
        public Resource resource { get; set; }
    }

    public class User
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string link { get; set; }
        public string location { get; set; }
        public string bio { get; set; }
        public DateTime created_time { get; set; }
        public string account { get; set; }
        public string[] content_filter { get; set; }
        public List<Picture> pictures { get; set; }
        public List<Website> websites { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
        public UploadQuota upload_quota { get; set; }
    }

    public class UploadTicket
    {
        /// <summary>
        /// The API endpoint for your upload ticket. You can query this to learn more about the upload
        /// </summary>
        public string uri { get; set; }
        /// <summary>
        /// Your unique ticket id.
        /// </summary>
        public string ticket_id { get; set; }
        /// <summary>
        /// The video you upload to this upload ticket will be associated with this user
        /// </summary>
        public User user { get; set; }

        /// <summary>
        /// An upload URL
        /// </summary>
        public string upload_link { get; set; }
        /// <summary>
        /// A secure upload URL
        /// </summary>
        public string upload_link_secure { get; set; }

        /// <summary>
        /// The URI you use when finishing the upload. You will make an HTTP DELETE request to this endpoint
        /// </summary>
        public string complete_uri { get; set; }

        /// <summary>
        /// An HTML upload form
        /// </summary>
        public string form { get; set; }
    }

    public class Space
    {
        /// <summary>
        /// The amount of bytes left in your quota for the current period
        /// </summary>
        public int free { get; set; }
        /// <summary>
        /// Your maximum quota for the current period
        /// </summary>
        public int max { get; set; }
        /// <summary>
        /// The amount of bytes you have uploaded this period
        /// </summary>
        public int used { get; set; }

    }

    public class Quota
    {
        /// <summary>
        /// Boolean indicating whether this user can upload an HD video
        /// </summary>
        public bool hd { get; set; }

        /// <summary>
        /// Boolean indicating whether this user can upload an SD video
        /// </summary>
        public bool sd { get; set; }
    }

    public class UploadQuota
    {
        public Space space { get; set; }
        public Quota quota { get; set; }
    }

    public class Website
    {
        public string name { get; set; }
        public string link { get; set; }
        public string description { get; set; }
    }

    public class Video
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string link { get; set; }
        public int duration { get; set; }
        public int width { get; set; }
        public int height { get; set; }
        public DateTime created_time { get; set; }
        public DateTime modified_time { get; set; }
        public string[] content_rating { get; set; }
        public string license { get; set; }
        public Privacy privacy { get; set; }
        public List<Picture> pictures { get; set; }
        public List<Tag> tags { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
        public EmbedPresets embed_presets { get; set; }
        public User user { get; set; }
        public string status { get; set; }
    }

    public class Paging
    {
        public string next { get; set; }
        public string previous { get; set; }
        public string first { get; set; }
        public string last { get; set; }
    }

    public class Comment
    {
        public string uri { get; set; }
        public string type { get; set; }
        public string text { get; set; }
        public DateTime created_on { get; set; }
        public User user { get; set; }
    }

    public class Credit
    {
        public string uri { get; set; }
        public Video video { get; set; }
        public string role { get; set; }
        public string name { get; set; }
        public User user { get; set; }
    }

    public class Album
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string link { get; set; }
        public int duration { get; set; }
        public string created_time { get; set; }
        public string modified_time { get; set; }
        public User user { get; set; }
        public Privacy privacy { get; set; }
        public List<Picture> pictures { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
    }

    public class Channel
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string link { get; set; }
        public DateTime created_time { get; set; }
        public DateTime modified_time { get; set; }
        public User user { get; set; }
        public List<Picture> pictures { get; set; }
        public Privacy privacy { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
    }

    public class Group
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string link { get; set; }
        public DateTime created_time { get; set; }
        public DateTime modified_time { get; set; }
        public Privacy privacy { get; set; }
        public List<Picture> pictures { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
        public User user { get; set; }
    }

    public enum AddingVideoToGroupResult
    {
        /// <summary>
        /// The video was successfully added to the Group
        /// </summary>
        Added,
        /// <summary>
        /// The video is pending addition to the Group
        /// </summary>
        Pending,
        /// <summary>
        /// The video is already in the Group
        /// </summary>
        AleadyExists
    }

    public class Feed
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string link { get; set; }
        public int duration { get; set; }
        public int width { get; set; }
        public int height { get; set; }
        public DateTime created_time { get; set; }
        public DateTime modified_time { get; set; }
        public string content_rating { get; set; }
        public string license { get; set; }
        public Privacy privacy { get; set; }
        public List<Picture> pictures { get; set; }
        public List<Tag> tags { get; set; }
        public Stat stats { get; set; }
        public Metadata metadata { get; set; }
        public EmbedPresets embed_presets { get; set; }
        public User user { get; set; }
        public Context context { get; set; }
        public string status { get; set; }
        public string review_link { get; set; }
    }

    public class Preset
    {
        public string uri { get; set; }
        public string name { get; set; }
        public Setting settings { get; set; }
        public User user { get; set; }
    }

    public class Domain
    {
        public string domain { get; set; }
        public string uri { get; set; }
    }

    public class Category
    {
        public string uri { get; set; }
        public string name { get; set; }
        public string link { get; set; }
        public bool top_level { get; set; }
        public List<Picture> pictures { get; set; }
        public Stat stats { get; set; }
        public List<Category> subcategories { get; set; }
        public Metadata metadata { get; set; }
    }

    #endregion
}


text:
<?php
require_once('database_connect.php');

//create short variables from flash
$user = $_POST['user'];
$pass = $_POST['pass'];
$sOutput = "";
  if (!$user || !$pass)
  {
     $sOutput = "empty";
	 echo "sOutput=".$sOutput;
	 exit;
  }
  else if($user)
  {
  	$sOutput = "Good";
  }
/* Connecting, selecting database */
$conn = db_connect();

/*check if connected or not*/
 if (!$conn)
 {
 	$sDataConnect = "noconn";
	echo "sDataConnect=".$sDataConnect;
	exit;
 }
 else if($conn)
 {
 /*make a query for user and password*/
 	$sDataConnect = "Connected";
	$result = mysql_query("select * from users
							where username = '$user'
							and password = '$pass'");
	/*get the catagories from the database to dynamically load them to flash*/
	$catagories = mysql_query("select * from catagory where catagoryID = 1");
	$arrCatagories = mysql_fetch_array($catagories);
	extract($arrCatagories);

	if (!$result)
	{
		$sValid = "noContact";
		echo "sValid=".$sValid."&sDataConnect=".$sDataConnect;
		mysql_close();
		exit;
	}
	if (mysql_num_rows($result)>0)
	{
		$sValid = "valid";
		if (!$catagories){
		$sValid = "nocat";
		echo "sValid=".$sValid;
		mysql_close();
		exit;
		}
		echo "sValid=".$sValid."&sDataConnect=".$sDataConnect."&cat1=".$cat1."&cat2=".$cat2."&cat3=".$cat3."&cat4=".$cat4."&cat5=".$cat5;
		mysql_close();
		exit;
	}
	else
	{
		$sValid = "notValid";
		echo "sValid=".$sValid."&sDataConnect=".$sDataConnect;
		mysql_close();
		exit;
	}

	//$sDataConnect = "Connected";
	//echo "sDataConnect=".$sDataConnect;
	//exit;
 }

  //echo "sOutput=".$sOutput."&sDataConnect=".$sDataConnect;

?>


text:
from itertools import islice, repeat, izip, cycle

# If PEP 3102 is accepted, the signature would be
#def iterCombinations(*iterables, blocksize=1):
def iterCombinations(*iterables, **kwds):
    '''Generates the combinations of the given iterables.

    @returns: An iterator over all combinations of the C{iterables}. Each yielded
        combination is a list of size C{len(iterables)} where the i-th element
        is drawn from the i-th iterable. B{Important note:} This list should not
        be modified between iterations; if you need to modify it, copy it to a
        new container.

    @param iterables: One or more arbitrary iterables.
    @param kwds: Currently only 'blocksize' allowed.
    @keyword blocksize: Determines the order of the yielded combinations. By
        default (C{blocksize=1}), the first iterable corresponds to the most outer
        loop (slowest change) and the last iterable corresponds to the most inner
        loop (fastest change).

        For larger blocksize, each iterable is first partitioned into consecutive
        blocks of size C{blocksize} (except perhaps for the last block which may
        be shorter). Then each combination is yielded by first iterating over
        each block combination C{B := (B1,B2,..Bn)} and then yielding each
        combination from B.

        More generally, C{blocksize} can be an iterable so that different
        C{iterables} can be partitioned by different block size. In this case,
        C{blocksize} is repeated as many time as necessary to match C{len(iterables)}.
        For instance::
            iterCombinations(range(4),range(6),range(8),'xyz', blocksize=(2,3))
        partitions C{range(4)} and C{range(8)} with blocksize=2, while C{range(6)}
        and 'xyz' are partitioned with blocksize=3.
    '''
    combo = [None] * len(iterables)
    blocksize = kwds.get('blocksize', 1)
    if isinstance(blocksize, int):
        sizes = repeat(blocksize)
    else:
        sizes = cycle(iter(blocksize))
    block_lists = [list(_iterblocks(it,sz)) for it,sz in izip(iterables,sizes)]
    for block_combo in _iterCombinations(block_lists, [None] * len(iterables)):
        for _ in _iterCombinations(block_combo, combo):
            yield combo

def _iterCombinations(groups, combo_list, index=0):
    # generate recursively all combinations of groups, updating combo_list
    # *in-place* for each combination.
    if index < len(groups)-1:
        for x in groups[index]:
            combo_list[index] = x
            for _ in _iterCombinations(groups,combo_list,index+1):
                yield combo_list
    else: # optimization to avoid the last level of recursion
        assert index == len(groups)-1
        for x in groups[index]:
            combo_list[index] = x
            yield combo_list

def _iterblocks(iterable, blocksize, factory=tuple):
    # split the iterable into blocks of blocksize
    iterable = iter(iterable)
    while True:
        block = factory(islice(iterable,blocksize))
        if not block: break
        yield block
        if len(block) < blocksize: break

# example
>>> for c in iterCombinations(range(5), 'abc'): print c
...
[0, 'a']
[0, 'b']
[0, 'c']
[1, 'a']
[1, 'b']
[1, 'c']
[2, 'a']
[2, 'b']
[2, 'c']
[3, 'a']
[3, 'b']
[3, 'c']
[4, 'a']
[4, 'b']
[4, 'c']

>>> for c in iterCombinations(range(5), 'abc', blocksize=2): print c
...
[0, 'a']
[0, 'b']
[1, 'a']
[1, 'b']
[0, 'c']
[1, 'c']
[2, 'a']
[2, 'b']
[3, 'a']
[3, 'b']
[2, 'c']
[3, 'c']
[4, 'a']
[4, 'b']
[4, 'c']


text:
#region Copyright 2017 D-Haven.org

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

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using TypeInfo = System.Reflection.TypeInfo;

#if NETSTANDARD
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
#endif

namespace DHaven.Faux.Compiler
{
    public partial class WebServiceCompiler
    {
        private enum BindingType { Core, Hystrix }
        private readonly ILogger<WebServiceCompiler> logger;
        private readonly FauxDiscovery discovery;
        private readonly IDictionary<BindingType,IWebServiceClassGenerator> serviceClassGenerators = new Dictionary<BindingType,IWebServiceClassGenerator>();

#if NETSTANDARD
        private readonly List<SyntaxTree> syntaxTrees = new List<SyntaxTree>();
#else
        private readonly List<string> codeSources = new List<string>();
#endif

        public WebServiceCompiler(FauxDiscovery discovery, IEnumerable<IWebServiceClassGenerator> classGenerators, ILogger<WebServiceCompiler> logger)
        {
            this.logger = logger;
            foreach(var classGenerator in classGenerators)
            {
                var type = classGenerator.GetType().Name.Contains("Hystrix") ? BindingType.Hystrix : BindingType.Core;
                serviceClassGenerators.Add(type, classGenerator);
            }
            this.discovery = discovery;

            foreach(var service in this.discovery.GetAllFauxInterfaces())
            {
                RegisterInterface(service);
            }
        }

        /// <summary>
        /// Registers a new type to be compiled.
        /// </summary>
        /// <param name="type">the type to register</param>
        public void RegisterInterface(TypeInfo type)
        {
            logger.LogDebug($"Registering the interface: {type.FullName}");

            var fullyQualifiedClassName = discovery.GetImplementationNameFor(type);
            if (fullyQualifiedClassName != null)
            {
                // already registered
                return;
            }

            var binding = type.GetCustomAttribute<HystrixFauxClientAttribute>() == null ? BindingType.Core : BindingType.Hystrix;
            var sourceCodeList = serviceClassGenerators[binding].GenerateSource(type, out fullyQualifiedClassName);
            discovery.RegisterType(type, fullyQualifiedClassName);

            foreach (var sourceCode in sourceCodeList)
            {
#if NETSTANDARD
                syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));
#else
                codeSources.Add(sourceCode);
#endif
            }

            logger.LogDebug($"Finished compiling the syntax tree for {fullyQualifiedClassName} generated from {type.FullName}");
        }

        public Assembly Compile(string assemblyName)
        {
#if NETSTANDARD
            var somethingToCompile = syntaxTrees.Any();
#else
            var somethingToCompile = codeSources.Any();
#endif

            // Always return something, the entry assembly will be able to load implementations since the assembly
            // is a dependency.  The platform compiled assembly will load what was generated at runtime.
            return somethingToCompile ? PlatformCompile(assemblyName) : Assembly.GetEntryAssembly();
        }

        public string GetImplementationName(TypeInfo type)
        {
            return discovery.GetImplementationNameFor(type);
        }
    }

    internal class CompilationException : Exception
    {
        public CompilationException(string message) : base(message)
        {}
    }
}


text:
package main

import (
	"bufio"
	"go/format"
	"io/ioutil"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	mi := make(map[string]string, 0)
	md := make(map[int]string, 0)

	file, err := os.Open(middlewareFile)
	fatalIfErr(err)

	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "#") {
			continue
		}

		items := strings.Split(line, ":")
		if len(items) != 3 {
			// ignore
			continue
		}
		priority, err := strconv.Atoi(items[0])
		fatalIfErr(err)

		if v, ok := md[priority]; ok {
			log.Fatalf("Duplicate priority '%d', slot already taken by %q", priority, v)
		}
		md[priority] = items[1]
		mi[items[1]] = middlewarePath + items[2] // Default, unless overriden by 3rd arg

		if strings.Contains(items[2], "/") { // External package has been given
			mi[items[1]] = items[2]
		}
	}

	genImports("core/zmiddleware.go", "core", mi)
	genDirectives("core/dnsserver/zdirectives.go", "dnsserver", md)
}

func genImports(file, pack string, mi map[string]string) {
	outs := header + "package " + pack + "\n\n" + "import ("

	if len(mi) > 0 {
		outs += "\n"
	}

	outs += "// Include all middleware.\n"
	for _, v := range mi {
		outs += `_ "` + v + `"` + "\n"
	}
	outs += ")\n"

	res, err := format.Source([]byte(outs))
	fatalIfErr(err)

	err = ioutil.WriteFile(file, res, 0644)
	fatalIfErr(err)
}

func genDirectives(file, pack string, md map[int]string) {

	outs := header + "package " + pack + "\n\n"
	outs += `
// Directives are registered in the order they should be
// executed.
//
// Ordering is VERY important. Every middleware will
// feel the effects of all other middleware below
// (after) them during a request, but they must not
// care what middleware above them are doing.

var directives = []string{
`

	var orders []int
	for k := range md {
		orders = append(orders, k)
	}
	sort.Ints(orders)

	for _, k := range orders {
		outs += `"` + md[k] + `",` + "\n"
	}

	outs += "}\n"

	res, err := format.Source([]byte(outs))
	fatalIfErr(err)

	err = ioutil.WriteFile(file, res, 0644)
	fatalIfErr(err)
}

func fatalIfErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

const (
	middlewarePath = "github.com/coredns/coredns/middleware/"
	middlewareFile = "middleware.cfg"
	header         = "// generated by directives_generate.go; DO NOT EDIT\n\n"
)


text:
namespace switches {

extern const char kXWalkDisableExtensionProcess[];
extern const char kXWalkExtensionProcess[];
extern const char kXWalkExternalExtensionsPath[];
extern const char kXWalkExtensionCmdPrefix[];

}  // namespace switches

#endif  // XWALK_EXTENSIONS_COMMON_XWALK_EXTENSION_SWITCHES_H_


text:
""" QiBuild """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function

import qisys.sh
import qisys.parsers
import qilinguist.builder
from qilinguist.worktree import LinguistWorkTree, new_linguist_project
from qilinguist.pml_translator import new_pml_translator

def get_linguist_worktree(args):
    """ Get Linguist Worktree """
    worktree = qisys.parsers.get_worktree(args, raises=False)
    if worktree:
        return LinguistWorkTree(worktree)
    return None

def get_linguist_projects(args, default_all=False):
    """ Get Linguist Projects """
    worktree = get_linguist_worktree(args)
    project_args = args.projects
    pml_paths = list()
    project_names = list()
    for arg in project_args:
        if arg.endswith(".pml"):
            pml_paths.append(qisys.sh.to_native_path(arg))
        else:
            if worktree:
                project_names.append(arg)
            else:
                raise Exception("Cannot use project names when running "
                                "outside a worktree")
    if not worktree and not pml_paths:
        raise Exception("You should specify at least a pml path when running "
                        "outside a worktree")
    res = list()
    if worktree:
        args.projects = project_names
        parser = LinguistProjectParser(worktree)
        try:
            res.extend(parser.parse_args(args, default_all=default_all))
        except CouldNotGuessProjectName:
            pass
    res.extend(get_pml_projects(pml_paths))
    return res

def get_pml_projects(pml_paths):
    """ Get Pml Projects """
    res = list()
    for pml_path in pml_paths:
        res.append(new_pml_translator(pml_path))
    return res

def get_linguist_builder(args, with_projects=True):
    """ Get Linguits Builder """
    _worktree = get_linguist_worktree(args)
    builder = qilinguist.builder.QiLinguistBuilder()
    if with_projects:
        projects = get_linguist_projects(args)
        builder.projects = projects
    return builder

class LinguistProjectParser(qisys.parsers.AbstractProjectParser):
    """ Implements AbstractProjectParser for a LinguistWorkTree """

    def __init__(self, linguist_worktree):
        """ LinguistProjectParser Init """
        super(LinguistProjectParser, self).__init__()
        self.linguist_worktree = linguist_worktree
        self.linguist_projects = linguist_worktree.linguist_projects

    def all_projects(self, args):
        """ All Projects """
        return self.linguist_projects

    def parse_no_project(self, args):
        """ Try to find the closest worktree project that matches the current directory """
        worktree = self.linguist_worktree.worktree
        parser = qisys.parsers.WorkTreeProjectParser(worktree)
        worktree_projects = parser.parse_no_project(args)
        if not worktree_projects:
            raise CouldNotGuessProjectName()
        # WorkTreeProjectParser returns None or a list of one element
        worktree_project = worktree_projects[0]
        linguist_project = new_linguist_project(self.linguist_worktree, worktree_project)
        if not linguist_project:
            raise CouldNotGuessProjectName()
        return self.parse_one_project(args, linguist_project.name)

    def parse_one_project(self, args, project_arg):
        """ Get one linguist project given its name """
        project = self.linguist_worktree.get_linguist_project(project_arg, raises=True)
        return [project]

class CouldNotGuessProjectName(Exception):
    """ CouldNotGuessProjectName Exception """

    def __str__(self):
        """ String Representation """
        return """
Could not guess linguist project name from current working directory
Please go inside a translatable project, or specify the project name
on the command line
"""


text:
package org.drools.cdi.test;

import org.drools.KnowledgeBase;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.StatelessKnowledgeSession;

public interface KProjectTestClass {
    public KnowledgeBase getKBase1();

    public KnowledgeBase getKBase2();

    public KnowledgeBase getKBase3();

    public StatelessKnowledgeSession getKBase1KSession1();

    public StatefulKnowledgeSession getKBase1KSession2();

    public StatefulKnowledgeSession getKBase2KSession3();

    public StatelessKnowledgeSession getKBase3KSession4();
}


text:
layout: post
title:  "oracle 11.2.0.2以后对数据库用户名重命名"
date:   2016-04-22 14:25:20 +0700
categories: [oracle]
---

[转自:]<http://www.xifenfei.com/2012/08/oracle%e7%94%a8%e6%88%b7%e9%87%8d%e5%91%bd%e5%90%8d.html>

从oracle 11.2.0.2开始提供了用户重命名的新特性,在以前的版本中,如果想对用户重命名,一般来说是先创建一个新的用户并授权,然后将原用户下的所有对象导入,然后删除旧的用户!

*数据库版本信息*

    SQL> select* from v$version;

    BANNER
    --------------------------------------------------------------------------------
    Oracle Database11g Enterprise Edition Release 11.2.0.3.0 - Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE11.2.0.3.0  Production
    TNS forLinux: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production

*创建测试环境*

    SQL> create user xifenfei identified by xifenfei;

    User created.

    SQL> grant connect,resource to xifenfei;

    Grant succeeded.

    SQL> conn xifenfei/xifenfei
    Connected.

    SQL> create table t_xifenfei   as select* from user_users;

    Table created.

    SQL> create index ind_t_xifenfei on t_xifenfei(user_id);

    Index created.

    SQL> conn / assysdba
    Connected.
    SQL> select object_type,object_name from dba_objects where owner='XIFENFEI';

    OBJECT_TYPE OBJECT_NAME
    ------------------- ---------------------------------------------------------
    TABLE   T_XIFENFEI
    INDEX   IND_T_XIFENFEI

*尝试修改用户名*

    SQL> alter user xifenfei rename to xff identified by xifenfei;
    alter user xifenfei rename to xff identified by xifenfei
    *
    ERROR atline 1:
    ORA-00922: missing orinvalid option

    --默认值是false
    SQL> col name for a32
    SQL> col value for a24
    SQL> col description for a70
    SQL> set linesize 150
    SQL> select a.ksppinm name,b.ksppstvl value,a.ksppdesc description
     from x$ksppi a,x$ksppcv b
      where a.inst_id = USERENV ('Instance')
      and b.inst_id = USERENV ('Instance')
      and a.indx = b.indx
      and upper(a.ksppinm) LIKE upper('%&param%')
      order by name
      /
    Enter value forparam: _enable_rename_user
    old   6:andupper(a.ksppinm) LIKEupper('%&param%')
    new   6:andupper(a.ksppinm) LIKEupper('%_enable_rename_user%')

    NAME VALUEDESCRIPTION
    -------------------------------- ------------------------ ------------------------------------------------
    _enable_rename_user  FALSEenable RENAME-clause using ALTERUSERstatement

    SQL> startup force restrict
    ORACLE instance started.

    Total System GlobalArea  230162432 bytes
    Fixed Size  1344088 bytes
    Variable Size  88083880 bytes
    Database Buffers  134217728 bytes
    Redo Buffers6516736 bytes
    Database mounted.
    Database opened.

    --_enable_rename_user=false,在restrict模式也不能修改用户名
    SQL> ALTER user XFF RENAME TO xffei IDENTIFIED BY xifenfei;
    ALTER user XFF RENAME TO xffei IDENTIFIED BY xifenfei
       *
    ERROR atline 1:
    ORA-00922: missing orinvalid option

*设置隐含参数*

    SQL> alter system set "_enable_rename_user"=true scope=spfile;

    System altered.

    SQL> shutdown immediate
    Database closed.
    Database dismounted.
    ORACLE instance shut down.

    SQL> startup restrict
    ORACLE instance started.

    Total System GlobalArea  230162432 bytes
    Fixed Size  1344088 bytes
    Variable Size  88083880 bytes
    Database Buffers  134217728 bytes
    Redo Buffers6516736 bytes
    Database mounted.
    Database opened.
    SQL> ALTER user xifenfei RENAME TO xff IDENTIFIED BY xifenfei;

    Useraltered.

*测试结果*

    SQL> startup force
    ORACLE instance started.

    Total System GlobalArea  230162432 bytes
    Fixed Size  1344088 bytes
    Variable Size  88083880 bytes
    Database Buffers  134217728 bytes
    Redo Buffers6516736 bytes
    Database mounted.
    Database opened.
    SQL> select object_type,object_name from dba_objects where owner='XIFENFEI';

    no rows selected

    SQL> select object_type,object_name from dba_objects where owner='XFF';

    OBJECT_TYPE OBJECT_NAME
    ------------------- ----------------------------------------------------
    TABLE   T_XIFENFEI
    INDEX   IND_T_XIFENFEI

    SQL> conn xff/xifenfei
    Connected.
    SQL> select count(*) from t_xifenfei;

      COUNT(*)
    ----------
     1

相关文档和上面的测试,得出结论:数据库版本在11.2.0.2及其以上版本,_enable_rename_user设置为true,数据库启动到restrict模式可以修改用户名


text:
package facebook4j;

import facebook4j.auth.Authorization;
import facebook4j.auth.MockAuthorization;
import facebook4j.auth.OAuthAuthorization;
import facebook4j.conf.Configuration;
import facebook4j.internal.http.HttpParameter;
import facebook4j.internal.http.MockHttpClientWrapper;
import facebook4j.internal.http.RequestMethod;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Ryuji Yamashita - roundrop at gmail.com
 */
class MockFacebookImpl extends FacebookImpl implements MockFacebook {
    private static final long serialVersionUID = -215346849507336373L;

    MockFacebookImpl(Configuration conf, Authorization auth) {
        super(conf, auth);
    }

    @Override
    protected void setHttp() {
        http = new MockHttpClientWrapper(conf);
    }

    @Override
    public void setOAuthAppId(String appId, String appSecret) {
        super.setOAuthAppId(appId, appSecret);
        if (auth instanceof MockAuthorization) {
            OAuthAuthorization oauth = new OAuthAuthorization(conf);
            oauth.setOAuthAppId(appId, appSecret);
            this.auth = oauth;
        }
    }

    public void setAppSecretProofEnabled(boolean appSecretProofEnabled) {
        if (auth instanceof MockAuthorization) {
            OAuthAuthorization oauth = new OAuthAuthorization(conf);
            oauth.setAppSecretProofEnabled(appSecretProofEnabled);
            this.auth = oauth;
        } else
        if (auth instanceof OAuthAuthorization) {
            ((OAuthAuthorization) auth).setAppSecretProofEnabled(appSecretProofEnabled);
        }
    }

    public void setMockJSON(String resourceName) {
        ((MockHttpClientWrapper) http).setMockJSON(resourceName);
    }

    public RequestMethod getHttpMethod() {
        return ((MockHttpClientWrapper) http).getRequest().getMethod();
    }

    public URL getEndpointURL() {
        try {
            return new URL(((MockHttpClientWrapper) http).getRequest().getURL());
        } catch (MalformedURLException e) {
            throw new AssertionError();
        }
    }

    public HttpParameter[] getHttpParameters() {
        return ((MockHttpClientWrapper) http).getRequest().getParameters();
    }

}


text:
extern "C" double computeDefault(double time)
{
  double u;
  u = sin(50 * time);
  return u;
}

SICONOS_EXPORT void computeB(double time, unsigned int sizeOfB, double* b, unsigned int sizeOfZ, double* z)
{
}


text:
package com.twitter.sdk.android.core.internal.scribe;

import com.google.gson.annotations.SerializedName;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.models.User;

public class ScribeItem {
    /**
     * Scribe item types. See ItemType in
     * See: source/tree/science/src/thrift/com/twitter/clientapp/gen/client_app.thrift
     */
    public static final int TYPE_TWEET = 0;
    public static final int TYPE_USER = 3;
    public static final int TYPE_MESSAGE = 6;

    /**
     * The type of item (tweet, message, etc).
     * Optional field.
     */
    @SerializedName("item_type")
    final Integer itemType;

    /**
     * A numerical id associated with the item.
     * Optional field.
     */
    @SerializedName("id")
    final Long id;

    /**
     *  A description of the item.
     *  Optional field.
     */
    @SerializedName("description")
    final String description;

    private ScribeItem(Integer itemType, Long id, String description) {
        this.itemType = itemType;
        this.id = id;
        this.description = description;
    }

    public static ScribeItem fromTweet(Tweet tweet) {
        return new ScribeItem.Builder()
                .setItemType(TYPE_TWEET)
                .setId(tweet.id)
                .build();
    }

    public static ScribeItem fromUser(User user) {
        return new ScribeItem.Builder()
                .setItemType(TYPE_USER)
                .setId(user.id)
                .build();
    }

    public static ScribeItem fromMessage(String message) {
        return new ScribeItem.Builder()
                .setItemType(TYPE_MESSAGE)
                .setDescription(message)
                .build();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final ScribeItem that = (ScribeItem) o;

        if (itemType != null ? !itemType.equals(that.itemType) : that.itemType != null) {
            return false;
        }

        if (id != null ? !id.equals(that.id) : that.id != null) {
            return false;
        }

        if (description != null ? !description.equals(that.description) : that.description
                != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = itemType != null ? itemType.hashCode() : 0;
        result = 31 * result + (id != null ? id.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        return result;
    }

    static class Builder {
        private Integer itemType;
        private Long id;
        private String description;

        public Builder setItemType(int itemType) {
            this.itemType = itemType;
            return this;
        }

        public Builder setId(long id) {
            this.id = id;
            return this;
        }

        public Builder setDescription(String description) {
            this.description = description;
            return this;
        }

        ScribeItem build() {
            return new ScribeItem(itemType, id, description);
        }
    }
}