text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_6"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.shopik.myapplication.Activity6">

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Activity 6"
        />
    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/clear"
        android:onClick="onClick"
        />
</LinearLayout>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Mobirise v4.1.7, mobirise.com">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" href="assets/images/kr-13.svg" type="image/x-icon">
  <meta name="description" content="">

  <link rel="stylesheet" href="assets/icons-mind/style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i">
  <link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css">
  <link rel="stylesheet" href="assets/et-line-font-plugin/style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&subset=latin">
  <link rel="stylesheet" href="assets/bootstrap-material-design-font/css/material.css">
  <link rel="stylesheet" href="assets/tether/tether.min.css">
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/shopping-cart/minicart-theme.css">
  <link rel="stylesheet" href="assets/dropdown/css/style.css">
  <link rel="stylesheet" href="assets/animate.css/animate.min.css">
  <link rel="stylesheet" href="assets/mobirise3-blocks-plugin/css/style.css">
  <link rel="stylesheet" href="assets/theme/css/style.css">
  <link rel="stylesheet" href="assets/mobirise-gallery/style.css">
  <link href="https://fonts.googleapis.com/css?family=Oswald:400,300,700" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Lora:400,700" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Raleway:400,300,700" rel="stylesheet">
  <link href="assets/fonts/style.css" rel="stylesheet">
  <link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">

                    <button class="navbar-toggler pull-xs-right hidden-md-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar">

                    </button>

Sell Your Tickets

Supplier's Demand

Designer's Demand

Request

                    <button hidden="" class="navbar-toggler navbar-close" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar">

                    </button>

Mobirise

Jain Song

송자인 , Korea, Asia

TimeLine

Part I

2016 S / S

Expresses the freedom and splendor of the seaside city with the Californian Glamorous

Current js & associates CEO / jain song Design Chief

2012. 8 Launched j Lite, a bridge line of jain song

Part II

2011. 9 jain song premium line

Launched jain song COLLECTION

2004. 9 Launched JAIN by JAINSONG, Design Chief

1998. 2 ~ 2004. 2 Kim Dongsoon Ul Timo Design Office

Concept:
CITY & NATURE

Natural and healthy chic. She expresses her own style with warm sensitivity that loves the environment and loves animals and beauty that shines from the inside.

Pursuit of natural lines and restrained detail, perfect tailoring

                        Previous

                        Next

                        ×
                        Close

 제인송

Designer : 송자인

Korea, Asia

DROP A MESSAGE

To : 송자인

Address:  서울특별시 강남구 도곡로 33길 4(역삼동)
Phone: 02-557-6231
Fax: 02-557-5241

Thanks for filling out form!

                                    <form action="https://mobirise.com/" method="post" data-form-title="DROP A MESSAGE">
                                        <input type="hidden" value="XdHpEefG8iyrVlviPXchnh36I4qOPOycL9ADM8Qah8KGA1gdwaSwwsr8eXK8urne2WSSMD+wPclh8sU9tHKcKkIIze1eIfZaDkAxjU7Vm2D7+xDbxDSLxfRi8xUiYNfD" data-form-email="true">

                                                 <input type="text" class="form-control" name="name" required="" data-form-field="Name" placeholder="Name*">

                                                 <input type="text" class="form-control" name="email" required="" data-form-field="Email" placeholder="Email*">

                                                 <input type="text" class="form-control" name="phone" required="" data-form-field="Phone" placeholder="Phone*">

                                                <textarea class="form-control" name="message" rows="7" data-form-field="Message" style="resize:none" placeholder="Message"></textarea>

<button type="submit" class="btn btn-black">SEND MESSAGE</button>

                                    </form>

  <input name="animation" type="hidden">

redpajama_set_name: RedPajamaGithub


text:
import { InsightApp } from './app.component';
import { TestBed, getTestBed } from '@angular/core/testing';
import { Platform } from 'ionic-angular';
import { NavMock } from '../mocks';
import { PopoverController, MenuController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ApiProvider } from '../providers/api/api';
import { CurrencyProvider } from '../providers/currency/currency';
import { DefaultProvider } from '../providers/default/default';
import { HttpModule } from '@angular/http';

describe('InsightApp', () => {
  let injector: TestBed;
  let app: InsightApp;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ],
      providers: [
        PopoverController,
        InsightApp,
        Platform,
        MenuController,
        SplashScreen,
        StatusBar,
        ApiProvider,
        CurrencyProvider,
        DefaultProvider
      ]
    });
    injector = getTestBed();
    app = injector.get(InsightApp);

    app['nav'] = (<any>new NavMock());
  });

  it('initializes with three possible pages', () => {
    expect(app['pages'].length).toEqual(3);
  });

  it('initializes with a root page', () => {
    expect(app['rootPage']).not.toBe(null);
  });

  it('opens a page', () => {
    spyOn(app['menu'], 'close');
    spyOn(app['nav'], 'setRoot');
    app.openPage(app['pages'][1]);
    expect(app['menu']['close']).toHaveBeenCalled();
  });
});


text:
package org.apache.airavata.wsmg.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;

import org.apache.airavata.wsmg.client.ConsumerServer;
import org.apache.airavata.wsmg.client.WsntMsgBrokerClient;
import org.apache.axis2.AxisFault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NotificationViewerFrame extends JFrame {

    private static final long serialVersionUID = -4924241323165353343L;

    private static final Logger logger = LoggerFactory.getLogger(NotificationViewerFrame.class);

    JPanel contentPane;

    BorderLayout borderLayout1 = new BorderLayout();

    JPanel jPanel1 = new JPanel();

    Border border1 = BorderFactory.createLineBorder(Color.gray, 2);

    JLabel jLabel1 = new JLabel();

    JButton jButtonStart = new JButton();

    JLabel jLabel2 = new JLabel();

    JTextField jTextBrokerUrl = new JTextField();

    JLabel jLabel3 = new JLabel();

    JTextField jTextPort = new JTextField();

    JLabel jLabel4 = new JLabel();

    JTextField jTextTopic = new JTextField();

    JTabbedPane jTabbedPane1 = new JTabbedPane();

    JScrollPane jScrollPane1 = new JScrollPane();

    JTextArea jTextAreaBrief = new JTextArea();

    JScrollPane jScrollPane2 = new JScrollPane();

    JTextArea jTextAreaWhole = new JTextArea();

    JButton jButtonClear = new JButton();

    ConsumerServer consumerServer = null;

    WsntMsgBrokerClient client;

    String subId = null;

    JButton jButtonStop = new JButton();

    GridBagLayout gridBagLayout1 = new GridBagLayout();

    public NotificationViewerFrame() {
        try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        client = new WsntMsgBrokerClient();

    }

    /**
     * Component initialization.
     *
     * @throws java.lang.Exception
     */
    private void jbInit() throws Exception {
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(borderLayout1);
        setSize(new Dimension(547, 429));
        setTitle("WS-Notification Viewer");
        jPanel1.setBackground(Color.white);
        jPanel1.setBorder(border1);
        jPanel1.setMaximumSize(new Dimension(180000, 180000));
        jPanel1.setLayout(gridBagLayout1);
        jLabel1.setFont(new java.awt.Font("Serif", Font.BOLD | Font.ITALIC, 28));
        jLabel1.setForeground(Color.blue);
        jLabel1.setText("WS-Notification Listener");
        jButtonStart.setToolTipText("Subscribe to the topic and start listening");
        jButtonStart.setText("Start");
        jButtonStart.addActionListener(new NotificationViewerFrame_jButton1_actionAdapter(this));
        jLabel2.setFont(new java.awt.Font("Dialog", Font.BOLD, 11));
        jLabel2.setText("BrokerURL");
        jTextBrokerUrl.setToolTipText("Enter Broker URL here.");
        jTextBrokerUrl.setText("http://localhost:8080/axis2/services/NotificationService");
        jLabel3.setFont(new java.awt.Font("Dialog", Font.BOLD, 11));
        jLabel3.setText("Listening Port");
        jTextPort.setToolTipText("Enter the port this listener will be listening to.");
        jTextPort.setText("19999");
        jLabel4.setFont(new java.awt.Font("Dialog", Font.BOLD, 11));
        jLabel4.setText("Topic");
        jTextTopic.setToolTipText("Enter the topic to subscribe.");
        jTextTopic.setText("topic");
        jTextAreaBrief.setToolTipText("Summary of the messages received.");
        jTextAreaBrief.setLineWrap(true);
        // jTextAreaWhole.setMinimumSize(new Dimension(490, 17));
        // jTextAreaWhole.setPreferredSize(new Dimension(490, 17));
        jTextAreaWhole.setToolTipText("Full content of the SOAP messages.");
        // jTextAreaWhole.setText("");
        jButtonClear.setToolTipText("Clear messages in the two message panes.");
        jButtonClear.setText("Clear Messages");
        jButtonClear.addActionListener(new NotificationViewerFrame_jButtonClear_actionAdapter(this));
        jButtonStop.setEnabled(false);
        jButtonStop.setToolTipText("Unsubscribe to the topic and stop listening.");
        jButtonStop.setText("Stop");
        jButtonStop.addActionListener(new NotificationViewerFrame_jButtonStop_actionAdapter(this));
        jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setAutoscrolls(true);
        jScrollPane1.setToolTipText("Summary of the messages received.");
        jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane2.setAutoscrolls(true);
        jScrollPane2.setToolTipText("Full content of the SOAP messages.");
        jTabbedPane1.add(jScrollPane1, "Brief Messages");
        jTabbedPane1.add(jScrollPane2, "Whole Messages");
        jPanel1.add(jLabel1, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.NONE, new Insets(7, 10, 0, 107), 20, -5));
        jPanel1.add(jButtonStop, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.NONE, new Insets(0, 48, 0, 80), 55, -4));
        jPanel1.add(jLabel4, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.NONE, new Insets(0, 36, 0, 8), 43, 4));
        jPanel1.add(jLabel3, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.NONE, new Insets(0, 36, 0, 0), 1, 4));
        jPanel1.add(jTextPort, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.HORIZONTAL, new Insets(7, 0, 0, 0), 144, -1));
        jPanel1.add(jButtonClear, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.NONE, new Insets(0, 46, 0, 78), 3, -4));
        jPanel1.add(jTextTopic, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.SOUTHWEST,
                GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 149, -1));
        jPanel1.add(jTextBrokerUrl, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST,
                GridBagConstraints.HORIZONTAL, new Insets(6, -1, 5, 1), 10, -1));
        jPanel1.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST,
                GridBagConstraints.NONE, new Insets(6, 37, 5, 0), 21, 4));
        jPanel1.add(jButtonStart, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
                GridBagConstraints.NONE, new Insets(8, 47, 0, 79), 57, -4));
        jScrollPane2.getViewport().add(jTextAreaWhole);
        jScrollPane1.getViewport().add(jTextAreaBrief);

        jPanel1.add(jTabbedPane1, new GridBagConstraints(0, 4, 3, 1, 1.0, 1.0, GridBagConstraints.CENTER,
                GridBagConstraints.BOTH, new Insets(0, 18, 57, 30), 0, 206));
        contentPane.add(jPanel1, java.awt.BorderLayout.CENTER);
    }

    public void jButtonStart_actionPerformed(ActionEvent event) {
        // jLabel1.setForeground(new Color(255,0,0));
        String brokerUrl = jTextBrokerUrl.getText().trim();
        String topic = jTextTopic.getText();

        String listeningPort = jTextPort.getText();

        int port = -1;

        try {
            port = Integer.parseInt(listeningPort);
        } catch (NumberFormatException nfe) {

            JOptionPane.showMessageDialog(this, nfe, "invalid port specified", JOptionPane.ERROR_MESSAGE);
            return;
        }

        client.init(brokerUrl);// important
        // Create a handler to handle the notifications arrived
        WsntViewerConsumerNotificationHandler handler = new WsntViewerConsumerNotificationHandler(this);

        String consumerUrl = null;

        try {
            String[] eprs = client.startConsumerService(port, handler);

            if (eprs.length > 0) {
                consumerUrl = eprs[0];
            } else {
                throw new AxisFault("no consumer url given by wse client api");
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e, "Unable to start consumer service", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            subId = client.subscribe(consumerUrl, topic, null);
        } catch (Exception e) {

            JOptionPane.showMessageDialog(this, e, "Unable to subscribe to topic", JOptionPane.ERROR_MESSAGE);

            client.shutdownConsumerService();
            return;
        }

        jButtonStart.setEnabled(false);
        jTextBrokerUrl.setEnabled(false);
        jTextTopic.setEnabled(false);
        jTextPort.setEnabled(false);
        jButtonStop.setEnabled(true);
        jTextAreaBrief.append("Listener started...\n");
        jTextAreaWhole.append("Listener started...\n");

    }

    public void jButtonStop_actionPerformed(ActionEvent e) {
        if (subId != null) {
            try {
                client.init(jTextBrokerUrl.getText().trim());
                client.unSubscribe(subId);
            } catch (Exception e1) {
                JOptionPane.showMessageDialog(this, e, "Unable to unsubscribe from topic", JOptionPane.ERROR_MESSAGE);
            }// TODO: add with replyTo URL
            subId = null;
        }

        client.shutdownConsumerService();

        jButtonStop.setEnabled(false);
        jButtonStart.setEnabled(true);
        jTextBrokerUrl.setEnabled(true);
        jTextTopic.setEnabled(true);
        jTextPort.setEnabled(true);
        jTextAreaBrief.append("Listener stoped.\n");
        jTextAreaWhole.append("Listener stoped.\n");

    }

    public void addBriefMessage(String message) {
        jTextAreaBrief.append(message + "\n");
        jTextAreaBrief.selectAll();
    }

    public void addWholeMessage(String message) {
        jTextAreaWhole.append(message + "\n");
        jTextAreaWhole.selectAll();
    }

    public void jButtonClear_actionPerformed(ActionEvent e) {
        jTextAreaBrief.setText("");
        jTextAreaWhole.setText("");
    }
}

class NotificationViewerFrame_jButtonStop_actionAdapter implements ActionListener {
    private NotificationViewerFrame adaptee;

    NotificationViewerFrame_jButtonStop_actionAdapter(NotificationViewerFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.jButtonStop_actionPerformed(e);
    }
}

class NotificationViewerFrame_jButtonClear_actionAdapter implements ActionListener {
    private NotificationViewerFrame adaptee;

    NotificationViewerFrame_jButtonClear_actionAdapter(NotificationViewerFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.jButtonClear_actionPerformed(e);
    }
}

class NotificationViewerFrame_jButton1_actionAdapter implements ActionListener {
    private NotificationViewerFrame adaptee;

    NotificationViewerFrame_jButton1_actionAdapter(NotificationViewerFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.jButtonStart_actionPerformed(e);

    }
}


text:
"use strict";

var fs = require('fs')
  , f = require('util').format;

/**
 * @ignore
 */
exports['Should correctly authenticate using x509'] = {
  metadata: { requires: { topology: 'ssl' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var ServerManager = require('mongodb-tools').ServerManager
      , MongoClient = configuration.require.MongoClient;

    // All inserted docs
    var docs = [];
    var errs = [];
    var insertDocs = [];

    // Read the cert and key
    var cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");

    // User name
    var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    // Default rs options
    var rsOptions = {
      host: 'server',
      // SSL information
      ssl:true,
      sslPEMKeyFile: __dirname + "/ssl/x509/server.pem",
      sslCAFile: __dirname + "/ssl/x509/ca.pem",
      sslCRLFile: __dirname + "/ssl/x509/crl.pem",
      sslMode: 'requireSSL',
      sslWeakCertificateValidation: null,

      // The client certificate
      key: cert,
      cert: cert,
      rejectUnauthorized: false,

      // ReplSet settings
      secondaries: 2
    }

    // Create server manager
    var serverManager = new ServerManager(rsOptions);

    // Start the server manager
    serverManager.start({purge:true, signal:-9, kill:true}, function() {
      // Connect and validate the server certificate
      MongoClient.connect("mongodb://server:27017/test?ssl=true&maxPoolSize=1", {
        server: {
            sslKey:key
          , sslCert:cert
        }
      }, function(err, db) {
        test.equal(null, err);
        test.ok(db != null);

        // Execute build info
        db.command({buildInfo:1}, function(err, result) {
          test.equal(null, err);
          var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
          if(version < 253) {
            db.close();
            return test.done();
          }

          // Add the X509 auth user to the $external db
          var ext = db.db('$external');
          ext.addUser(userName, {roles: [
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}
          ]}, function(err, result) {
            test.equal(null, err);
            test.equal(userName, result[0].user);
            test.equal('', result[0].pwd);
            db.close();

            // Connect using X509 authentication
            MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=true&maxPoolSize=1'
                , encodeURIComponent(userName), 'MONGODB-X509'), {
              server: {
                  sslKey:key
                , sslCert:cert
              }
            }, function(err, db) {
              test.equal(null, err);
              test.ok(db != null);

              db.close();

              serverManager.stop(function() {
                test.done();
              });
            });
          });
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should correctly handle bad x509 certificate'] = {
  metadata: { requires: { topology: 'ssl' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var ServerManager = require('mongodb-tools').ServerManager
      , MongoClient = configuration.require.MongoClient;

    // All inserted docs
    var docs = [];
    var errs = [];
    var insertDocs = [];

    // Read the cert and key
    var cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var serverPem = fs.readFileSync(__dirname + "/ssl/x509/server.pem");

    // User name
    var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    // Default rs options
    var rsOptions = {
      host: 'server',
      // SSL information
      ssl:true,
      sslPEMKeyFile: __dirname + "/ssl/x509/server.pem",
      sslCAFile: __dirname + "/ssl/x509/ca.pem",
      sslCRLFile: __dirname + "/ssl/x509/crl.pem",
      sslMode: 'requireSSL',
      sslWeakCertificateValidation: null,

      // The client certificate
      key: cert,
      cert: cert,
      rejectUnauthorized: false,

      // ReplSet settings
      secondaries: 2
    }

    // Create server manager
    var serverManager = new ServerManager(rsOptions);
    serverManager.start({purge:true, signal:-9, kill:true}, function() {
      // Connect and validate the server certificate
      MongoClient.connect("mongodb://server:27017/test?ssl=true&maxPoolSize=1", {
        server: {
            sslKey:key
          , sslCert:cert
        }
      }, function(err, db) {
        test.equal(null, err);
        test.ok(db != null);

        // Execute build info
        db.command({buildInfo:1}, function(err, result) {
          test.equal(null, err);
          var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
          if(version < 253) {
            db.close();
            return test.done();
          }

          // Add the X509 auth user to the $external db
          var ext = db.db('$external');
          ext.addUser(userName, {roles: [
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}
          ]}, function(err, result) {
            test.equal(null, err);
            test.equal(userName, result[0].user);
            test.equal('', result[0].pwd);
            db.close();

            // Connect using X509 authentication
            MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=true&maxPoolSize=1'
                , encodeURIComponent(userName), 'MONGODB-X509'), {
              server: {
                  sslKey:serverPem
                , sslCert:serverPem
              }
            }, function(err, db) {
              test.equal(null, db);
              test.equal(0, err.ok);
              test.equal("auth failed", err.errmsg);

              serverManager.stop(function() {
                test.done();
              });
            });
          });
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should give reasonable error on x509 authentication failure'] = {
  metadata: { requires: { topology: 'ssl' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var ServerManager = require('mongodb-tools').ServerManager
      , MongoClient = configuration.require.MongoClient;

    // All inserted docs
    var docs = [];
    var errs = [];
    var insertDocs = [];

    // Read the cert and key
    var cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");

    // User name
    var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    // Default rs options
    var rsOptions = {
      host: 'server',
      // SSL information
      ssl:true,
      sslPEMKeyFile: __dirname + "/ssl/x509/server.pem",
      sslCAFile: __dirname + "/ssl/x509/ca.pem",
      sslCRLFile: __dirname + "/ssl/x509/crl.pem",
      sslMode: 'requireSSL',
      sslWeakCertificateValidation: null,

      // The client certificate
      key: cert,
      cert: cert,
      rejectUnauthorized: false,

      // ReplSet settings
      secondaries: 2
    }

    // Create server manager
    var serverManager = new ServerManager(rsOptions);
    serverManager.start({purge:true, signal:-9, kill:true}, function() {
      // Connect and validate the server certificate
      MongoClient.connect("mongodb://server:27017/test?ssl=true&maxPoolSize=1", {
        server: {
            sslKey:key
          , sslCert:cert
        }
      }, function(err, db) {
        test.equal(null, err);
        test.ok(db != null);

        // Execute build info
        db.command({buildInfo:1}, function(err, result) {
          test.equal(null, err);
          var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
          if(version < 253) {
            db.close();
            return test.done();
          }

          // Add the X509 auth user to the $external db
          var ext = db.db('$external');
          ext.addUser(userName, {roles: [
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}
          ]}, function(err, result) {
            test.equal(null, err);
            test.equal(userName, result[0].user);
            test.equal('', result[0].pwd);
            db.close();

            // Connect using X509 authentication
            MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=true&maxPoolSize=1'
                , encodeURIComponent("WRONG_USERNAME"), 'MONGODB-X509'), {
              server: {
                  sslKey:key
                , sslCert:cert
              }
            }, function(err, db) {
              test.equal(null, db);
              test.equal(0, err.ok);
              test.equal("auth failed", err.errmsg);

              serverManager.stop(function() {
                test.done();
              });
            });
          });
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should give helpful error when attempting to use x509 without SSL'] = {
  metadata: { requires: { topology: 'ssl' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var ServerManager = require('mongodb-tools').ServerManager
      , MongoClient = configuration.require.MongoClient;

    // All inserted docs
    var docs = [];
    var errs = [];
    var insertDocs = [];

    // Read the cert and key
    var cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var serverPem = fs.readFileSync(__dirname + "/ssl/x509/server.pem");

    // User name
    var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    // Default rs options
    var rsOptions = {
      host: 'server',
    }

    // Create server manager
    var serverManager = new ServerManager(rsOptions);
    serverManager.start({purge:true, signal:-9, kill:true}, function() {
      // Connect and validate the server certificate
      MongoClient.connect("mongodb://server:27017/test?ssl=false&maxPoolSize=1", {
        server: {
            sslKey:key
          , sslCert:cert
        }
      }, function(err, db) {
        test.equal(null, err);
        test.ok(db != null);

        // Execute build info
        db.command({buildInfo:1}, function(err, result) {
          test.equal(null, err);
          var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
          if(version < 253) {
            db.close();
            return test.done();
          }

          // Add the X509 auth user to the $external db
          var ext = db.db('$external');
          ext.addUser(userName, {roles: [
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}
          ]}, function(err, result) {
            test.equal(null, err);
            test.equal(userName, result[0].user);
            test.equal('', result[0].pwd);
            db.close();

            // Connect using X509 authentication
            MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=false&maxPoolSize=1'
                , encodeURIComponent(userName), 'MONGODB-X509'), {
              server: {
                  sslKey:serverPem
                , sslCert:serverPem
              }
            }, function(err, db) {
              test.equal(null, db);
              test.ok(!!err);
              test.equal(0, err.ok);
              test.equal("SSL support is required for the MONGODB-X509 mechanism.", err.errmsg);

              serverManager.stop(function() {
                test.done();
              });
            });
          });
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should correctly reauthenticate against x509'] = {
  metadata: { requires: { topology: 'ssl' } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var ServerManager = require('mongodb-tools').ServerManager
      , MongoClient = configuration.require.MongoClient;

    // All inserted docs
    var docs = [];
    var errs = [];
    var insertDocs = [];

    // Read the cert and key
    var cert = fs.readFileSync(__dirname + "/ssl/x509/client.pem");
    var key = fs.readFileSync(__dirname + "/ssl/x509/client.pem");

    // User name
    var userName = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    // Default rs options
    var rsOptions = {
      host: 'server',
      // SSL information
      ssl:true,
      sslPEMKeyFile: __dirname + "/ssl/x509/server.pem",
      sslCAFile: __dirname + "/ssl/x509/ca.pem",
      sslCRLFile: __dirname + "/ssl/x509/crl.pem",
      sslMode: 'requireSSL',
      sslWeakCertificateValidation: null,

      // The client certificate
      key: cert,
      cert: cert,
      rejectUnauthorized: false,

      // ReplSet settings
      secondaries: 2
    }

    // Create server manager
    var serverManager = new ServerManager(rsOptions);

    // Start the server manager
    serverManager.start({purge:true, signal:-9, kill:true}, function() {
      // Connect and validate the server certificate
      MongoClient.connect("mongodb://server:27017/test?ssl=true&maxPoolSize=1", {
        server: {
            sslKey:key
          , sslCert:cert
        }
      }, function(err, db) {
        test.equal(null, err);
        test.ok(db != null);

        // Execute build info
        db.command({buildInfo:1}, function(err, result) {
          test.equal(null, err);
          var version = parseInt(result.versionArray.slice(0, 3).join(""), 10);
          if(version < 253) {
            db.close();
            return test.done();
          }

          // Add the X509 auth user to the $external db
          var ext = db.db('$external');
          ext.addUser(userName, {roles: [
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}
          ]}, function(err, result) {
            test.equal(null, err);
            test.equal(userName, result[0].user);
            test.equal('', result[0].pwd);
            db.close();

            // Connect using X509 authentication
            MongoClient.connect(f('mongodb://%s@server:27017/test?authMechanism=%s&ssl=true&maxPoolSize=1'
                , encodeURIComponent(userName), 'MONGODB-X509'), {
              server: {
                  sslKey:key
                , sslCert:cert
              }
            }, function(err, db) {
              test.equal(null, err);
              test.ok(db != null);

              db.collection('x509collection').insert({a:1}, function(err) {
                test.equal(null, err);

                db.collection('x509collection').findOne(function(err, doc) {
                  test.equal(null, err);
                  test.equal(1, doc.a);

                  db.serverConfig.once('reconnect', function() {
                    // Await reconnect and re-authentication
                    db.collection('x509collection').findOne(function(err, doc) {
                      test.equal(null, err);
                      test.equal(1, doc.a);

                      // Attempt disconnect again
                      db.serverConfig.allRawConnections()[0].connection.destroy();

                      // Await reconnect and re-authentication
                      db.collection('x509collection').findOne(function(err, doc) {
                        test.equal(null, err);
                        test.equal(1, doc.a);

                        db.close();

                        serverManager.stop(function() {
                          test.done();
                        });
                      });
                    });
                  })

                  // Force close
                  db.serverConfig.allRawConnections()[0].connection.destroy();
                });
              });
            });
          });
        });
      });
    });
  }
}


text: <users user-scopes="['default', 'clusterpost', 'admin']"></users>


text:
<?php

namespace PHPExiftool\Driver\Tag\Matroska;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DateTimeOriginal extends AbstractTag
{

    protected $Id = 1121;

    protected $Name = 'DateTimeOriginal';

    protected $FullName = 'Matroska::Main';

    protected $GroupName = 'Matroska';

    protected $g0 = 'Matroska';

    protected $g1 = 'Matroska';

    protected $g2 = 'Video';

    protected $Type = 'date';

    protected $Writable = false;

    protected $Description = 'Date/Time Original';

    protected $local_g2 = 'Time';
}


text:
package elasta.orm.delete.loader.impl;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import elasta.commons.Utils;
import elasta.core.promise.impl.Promises;
import elasta.core.promise.intfs.Promise;
import elasta.orm.delete.TableToTableDataMap;
import elasta.orm.delete.impl.TableToTableDataMapImpl;
import elasta.orm.delete.loader.DependencyDataLoader;
import elasta.orm.upsert.TableData;
import io.vertx.core.json.JsonObject;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by sohan on 3/12/2017.
 */
final public class TableDependenciesLoaderByDataMap {
    final Map<String, Collection<DependencyDataLoader>> map;
    final Map<TableData, TableData> dataMap;
    final TableDependenciesLoaderContext context;

    public TableDependenciesLoaderByDataMap(Map<String, Collection<DependencyDataLoader>> map, Map<TableData, TableData> dataMap, TableDependenciesLoaderContext context) {
        Objects.requireNonNull(map);
        Objects.requireNonNull(dataMap);
        Objects.requireNonNull(context);
        this.map = map;
        this.dataMap = dataMap;
        this.context = context;
    }

    public Promise<Void> load(TableData parentTableData) {

        if (Utils.not(map.containsKey(parentTableData.getTable()))) {
            return Promises.empty();
        }

        final Collection<DependencyDataLoader> dependencyDataLoaders = map.get(parentTableData.getTable());

        return loadTableDataRecursive(dependencyDataLoaders, parentTableData);
    }

    private Promise<Void> loadTableDataRecursive(
        Collection<DependencyDataLoader> dependencyDataLoaders,
        TableData parentTableData
    ) {

        if (context.contains(parentTableData)) {
            return Promises.empty();
        }

        context.add(parentTableData);

        putInTable(parentTableData);

        final List<Promise<List<TableData>>> promises = dependencyDataLoaders.stream()
            .map(dependencyDataLoader -> dependencyDataLoader.load(parentTableData))
            .map(
                promise -> promise
                    .thenP(
                        tableDatas -> {

                            final List<Promise<Void>> promiseList = tableDatas.stream()
                                .map(
                                    tableData -> loadTableDataRecursive(
                                        map.getOrDefault(tableData.getTable(), ImmutableList.of()),
                                        tableData
                                    ))
                                .collect(Collectors.toList());

                            return Promises.when(promiseList).map(voids -> (Void) null);

                        }))
            .collect(Collectors.toList());

        return Promises.when(promises).map(lists -> (Void) null);
    }

    private void putInTable(Map<TableData, TableData> dataMap, List<TableData> tableDatas) {

        tableDatas.forEach(this::putInTable);
    }

    private void putInTable(TableData tableData) {
        final String table = tableData.getTable();

        if (Utils.not(
            dataMap.containsKey(tableData)
        )) {
            dataMap.put(tableData, tableData);
            return;
        }

        TableData data = dataMap.get(tableData);
        dataMap.put(
            tableData,
            new TableData(
                table,
                tableData.getPrimaryColumns(),
                new JsonObject(
                    merge(tableData.getValues(), data.getValues())
                )
            )
        );
    }

    private Map<String, Object> merge(JsonObject values, JsonObject values1) {
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>(values.getMap());
        hashMap.putAll(values1.getMap());
        return ImmutableMap.copyOf(hashMap);
    }

    public static TableToTableDataMap toTableToTableDependenciesDataMap(Map<TableData, TableData> dataMap) {
        final Map<String, Map<TableData, TableData>> map = new HashMap<>();

        dataMap.forEach((td, tableData) -> {
            final String table = tableData.getTable();
            Map<TableData, TableData> tableDataMap = map.get(table);
            if (tableDataMap == null) {
                map.put(table, tableDataMap = new HashMap<>());
            }
            tableDataMap.put(
                tableData,
                tableData
            );
        });

        return new TableToTableDataMapImpl(
            copyRecursive(map)
        );
    }

    private static Map<String, Map<TableData, TableData>> copyRecursive(Map<String, Map<TableData, TableData>> map) {
        ImmutableMap.Builder<String, Map<TableData, TableData>> mapBuilder = ImmutableMap.builder();
        map.forEach((table, tableDatas) -> {
            mapBuilder.put(table, ImmutableMap.copyOf(tableDatas));
        });
        return mapBuilder.build();
    }
}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Many Shoes

						Expand All | Collapse All

Many Shoes

  She has two pairs of high heels. One of them has laces. The other one has a zipper. She has two pairs of running shoes. One of them is shiny. The other one is bright. She has two pairs of ballet flats. One of them is pink. The other one is brown. She wears her shoes to parties.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
"""
Extension attribute Variables used for attribute type inference.
See also compileclass.build_extension_symtab().
"""

from numba import symtab

class ExtensionAttributeVariable(symtab.Variable):
    """
    Variable created during type inference for assignments to extension
    attributes for which we don't know the type yet.

    When the assignment happens, update ext_type.attributedict.
    """

    def __init__(self, ext_type, attr_name, type, *args, **kwargs):
        super(ExtensionAttributeVariable, self).__init__(type, *args, **kwargs)
        self.ext_type = ext_type
        self.attr_name = attr_name

    def perform_assignment(self, rhs_type):
        self.type = rhs_type
        self.ext_type.attributedict[self.attr_name] = rhs_type


text:
'use strict';
// import Auto_userScopes from './userScopes.auto.js';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _q = require('q');

var _q2 = _interopRequireDefault(_q);

var _utils = require('../utils');

var _utils2 = _interopRequireDefault(_utils);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Auto_userScopes = function () {
  function Auto_userScopes(owner) {
    _classCallCheck(this, Auto_userScopes);

    this.sequelize = owner.sequelize;
    this.models = owner.models;
    this.security = owner.security;
  }

  _createClass(Auto_userScopes, [{
    key: 'create',
    value: function create(obj) {
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'create', [obj]);
    }
  }, {
    key: 'update',
    value: function update(obj) {
      var object_id_objects = obj.object_id_objects;
      delete obj.object_id_objects;
      var user_id_users = obj.user_id_users;
      delete obj.user_id_users;
      var where = {
        where: {
          object_id_objects: object_id_objects,
          user_id_users: user_id_users
        }
      };
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'update', [obj, where]);
    }
  }, {
    key: 'delete',
    value: function _delete(obj) {
      var params = {
        object_id_objects: obj.object_id_objects,
        user_id_users: obj.user_id_users
      };
      var where = {
        where: params
      };
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'destroy', [where]);
    }
  }, {
    key: 'findAll',
    value: function findAll(filters, notWhere) {
      filters = filters || {};
      var where = {
        where: filters
      };
      if (notWhere) {
        where = filters;
      }
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'findAll', [where]);
    }
  }, {
    key: 'findAndCountAll',
    value: function findAndCountAll(filters, notWhere) {
      filters = filters || {};
      var where = {
        where: filters
      };
      if (notWhere) {
        where = filters;
      }
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'findAndCountAll', [where]);
    }
  }, {
    key: 'findOne',
    value: function findOne(params, notWhere) {
      var where = {
        where: params
      };
      if (notWhere) {
        where = params;
      }
      return _utils2.default.executeModel(this.sequelize, this.models.userScopes, 'findOne', [where]);
    }
  }, {
    key: 'getById',
    value: function getById(object_id_objects, user_id_users) {
      var params = {
        object_id_objects: object_id_objects,
        user_id_users: user_id_users
      };
      return this.findOne(params);
    }
  }]);

  return Auto_userScopes;
}();

exports.default = Auto_userScopes;


text:
var amqp = require('amqplib');
var mongodb = require('mongodb').MongoClient

function run(conn) {
  process.once('SIGINT', function() { conn.close(); });
    return conn.createChannel().then(function(ch) {
      var ok = ch.assertQueue('task_queue', {durable: true});
      ok = ok.then(function() { ch.prefetch(1); });
      ok = ok.then(function() {
        ch.consume('task_queue', doWork, {noAck: false});
        console.log(" [*] Waiting for messages. To exit press CTRL+C");
      });
      return ok;

      function doWork(msg) {
        var body = msg.content.toString();
        console.log(" [x] Received '%s'", body);
        mongodb.connect('mongodb://database/dotnetlombardia', function(err, db) {
          var date = new Date()
          var hours = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString()
          var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString()
          var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString()
          db.collection('messages').update({_id: `${hours}-${minutes}-${seconds}`}, {$inc: {counter:1 }}, {upsert:true})
          db.close();
          setTimeout(function(){
            console.log("Connected successfully to server");
            ch.ack(msg);
          }, 1000)
        });
      }
    });
}

function connect() {
  amqp.connect('amqp://broker')
    .then((conn) => run(conn))
    .catch(() => {
      console.log("Error during connection. Try again later...")
      setTimeout(connect, 1000)
    })
}

connect()


text:
[![Build Status](https://travis-ci.org/amedeiros/micro-rb.svg?branch=master)](https://travis-ci.org/amedeiros/micro-rb) [![Gem Version](https://badge.fury.io/rb/micro-rb.svg)](https://badge.fury.io/rb/micro-rb)

# MicroRb

MicroRb allows you to develop micro services for the [micro](https://github.com/micro/micro) framework.
MicroRb uses the [proxy](https://github.com/micro/micro/tree/master/proxy) (previously called sidecar) that comes with micro. If you want to write services in Go see [go-micro](https://github.com/micro/go-micro) or in java see [ja-micro](https://github.com/Sixt/ja-micro).

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'micro-rb'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install micro-rb -v '0.1.0.rc2'

## Status

Currently in development. If I can get some pull requests that would be much appreciated.

## Google Protobufs

Currently supporting protobufs where each handler includes the module generated with requiring a Response and Request type. The example below is for the sum handler.

`$ protoc --ruby_out=. sum.proto`

```proto
syntax = "proto3";

package micro_rb.sum_handler;

message Request {
    int32 a = 1;
    int32 b = 2;
}

message Response {
    int32 total = 1;
}

```

## Usage

```ruby
require 'microrb'
require_relative '../examples/proto/sum_pb'

class MyHandler
  include MicroRb::Handler
  include MicroRb::SumHandler

  handler name: :test, metadata: { hello: 'Micro-Rb' }, rpc_method: :sum

  def sum(request: Request.new, response: Response.new)
    response.total = request.a + request.b

    response
  end
end

service_config = MicroRb::ServiceConfiguration.new(name: :test)
service_config.add_handler(MyHandler.new)

server = MicroRb::Servers::Web.new(service_config)
server.start!

```

Configuration has the following defaults for sidecar endpoint.

`Host: "http://127.0.0.1"`

`Port: 8081`

`Registy: "/registry"`

Configuration has the following defaults for the micro api.

`Host: http://127.0.0.1`

`Port: 3002`

`Rpc: "/rpc"`

Configuration can be changed.

```ruby
MicroRb::Configuration.configure do |c|
  c.sidecar_host     = 'http://mysite.com'
  c.sidecar_port     = '8080'
  c.sidecar_registry = '/awesome_registry'

  c.api_host  = 'http://mysite.com'
  c.api_port  = '8080'
  c.api_rpc   = '/awesome_micro_rb'
end
```

Want to run puma? No problem just add puma to your Gemfile and require the rack handler and tell the web server to use puma.
This works with thin etc because we just pass the options along to the rack server. Try it with the sum example!

```ruby
require 'rack/handler/puma'
service_config = MicroRb::ServiceConfiguration.new(name: :test, server: :puma)
server = MicroRb::Servers::Web.new(service_config)
```

Every handler must setup the following requirements at a minimum.
`handler name: :my_name, rpc_method: :some_method`

The `:rpc_method` must accept named parameters of `request:` and `response:`

Every handler must include a prtobuf module that has `Request` and `Response` constanst generated from protoc.

![alt text](https://github.com/amedeiros/micro-rb/blob/master/registry.png)
![alt text](https://github.com/amedeiros/micro-rb/blob/master/sum.png)

## Micro API

`micro api --address 0.0.0.0:3002`

```
$ http POST 0.0.0.0:3002/rpc method=MyHandler.sum service=test request='{"a": 1, "b": 2}'
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Content-Length: 11
Content-Type: application/json
Date: Tue, 09 May 2017 17:50:47 GMT

{
    "total": 3
}
```

```ruby
result = MicroRb::Clients::Rpc.call(service: 'test', method: 'MyHandler.sum', params: {a:1, b:2})
ap result
{
    "total" => 3
}
```

## Calling the service directly

```
$ http POST 0.0.0.0:3000 service=test method=MyHandler.sum id=1 params:='[{"a": 1, "b": 2}]'
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 31
Date: Tue, 09 May 2017 18:08:25 GMT
Server: WEBrick/1.3.1 (Ruby/2.4.0/2016-12-24)

{"result":{"total":3},"id":"1"}
```

```ruby
result = MicroRb::Clients::Http.call(uri: 'http://0.0.0.0:3000', service: 'test', method: 'MyHandler.sum', params: {a:1, b:2})
ap result

{
    "result" => {
        "total" => 3
    },
        "id" => nil
}
```

## Project Generator

```
microrb <options>
    -n, --new NAME                   Generate a new skeleton service.
    -e, --encryption                 Adds Symmetric Encryption gem to your new service.
    -a, --activerecord               Adds ActiveRecord to your gemfile and a default DB setup.
    -h, --help                       Display this help screen
```

To generate a new micro service project run the following. Note this also adds [Symmetric Encryption](https://github.com/rocketjob/symmetric-encryption) gem with the -e flag.

`microrb -n myservice -e`

This will output a new project with the example sum service ready to run.

```
Generating new service called myservice...
Fetching gem metadata from https://rubygems.org/.............
Fetching version metadata from https://rubygems.org/.
Resolving dependencies...
...... More bundler stuff here
Complete...
Please see https://rocketjob.github.io/symmetric-encryption/standalone.html for setting up SymmetricEncryption
Run sidecar: micro sidecar
Run micro web: micro --web_address 0.0.0.0:8080 web
Run me:  ./myservice/bin/myservice
```

```
./myservice/bin/myservice
[2017-05-05 14:28:52] INFO  WEBrick 1.3.1
[2017-05-05 14:28:52] INFO  ruby 2.3.1 (2017-03-06) [java]
[2017-05-05 14:28:52] INFO  WEBrick::HTTPServer#start: pid=48485 port=3000
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/amedeiros/micro-rb. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
import React, { Component } from 'react';

import './LyricsPane.css';

import Word from './Word.js';
import { NOINDEX } from './constants.js';

/** Shows the entire current verse in a big multi-column block. Not responsible
 * for the editing view. */
class LyricsPane extends Component {

  renderWord = (word) => {
    return (<Word i={word.i} key={word.i} raw={word.raw}
                focus={this.props.highlights.get(word.i) || 0}
                hover_cb={this.props.hover_cb}
            />);
  }

  renderLine = (line, idx) => {
    var words = line.map(this.renderWord);
    var x = [];
    // Hack to put spaces between word spans. We could just put them in the spans
    // themselves, but then we get funny underlining behaviour.
    for (let word of words) {
      x.push(word);
      x.push(" ");
    }
    return
{x.slice(0,-1)}
;
  }

  componentWillUnmount() {
    this.props.hover_cb(NOINDEX);
  }

  render() {
    var lines = this.props.verse.lines.map(this.renderLine);
    return (

            {this.props.loading &&

Loading...

            }
            {lines}

    );
  }
}

LyricsPane.propTypes = {
  verse: React.PropTypes.object.isRequired,
  loading: React.PropTypes.bool,
  hover_cb: React.PropTypes.func,
  highlights: React.PropTypes.instanceOf(Map),
};

export default LyricsPane;


text:
package proj.me.bitframe.frames.tournament;

import java.util.Arrays;

/**
 * Created by root on 25/7/17.
 */
public class TournamentType {
    private static class TournamentLeaves{
        int index = -1;
        PictureAttribute[] attrs;
        TournamentLeaves(PictureAttribute[] attrs){
            this.attrs = attrs;
            index = 0;
        }
    }

    private int type;
    private Builder builder;

    public TournamentType(int type){
        this.type = type;
    }

    public Builder build(PictureAttribute[] typeCombinations, int totalTournaments){
        if(builder != null) return builder.reset();
        builder = new Builder(totalTournaments)
                .buildTournamentTree(typeCombinations);
        return builder;
    }

    public static class Builder{
        private TournamentLeaves[] tournamentLeaves;
        private int totalTournaments;
        private PictureAttribute[] heap;
        private int heapSize;

        private Builder(int totalTournaments){
            this.totalTournaments = totalTournaments;
            tournamentLeaves = new TournamentLeaves[totalTournaments];
        }

        public Builder reset(){
            for(TournamentLeaves tournamentLeave : tournamentLeaves)
                if(tournamentLeave.index != -1) tournamentLeave.index = 0;
            return this;
        }

        private Builder buildTournamentTree(PictureAttribute[] typeCombinations){
            int size = typeCombinations.length;

            int comboSize = size / totalTournaments;

            for(int i = totalTournaments - 1;i>=0;i--){
                int length = comboSize < 0 ? 0 : comboSize;
                if(length == 0 && i != 0) continue;
                else if(i == 0) length = size - comboSize * (totalTournaments - 1);

                PictureAttribute[] combo = Arrays.copyOfRange(typeCombinations, 0, length);
                Arrays.sort(combo);
                tournamentLeaves[i] = new TournamentLeaves(combo);
            }

            int actualLeaves = 1;
            while(totalTournaments > actualLeaves) actualLeaves <<= 1;

            heap = new PictureAttribute[actualLeaves + actualLeaves - 1];

            int leaf = 0;
            for(int i = actualLeaves - 1;i< heap.length;i++){
                if(leaf < totalTournaments){
                    TournamentLeaves tournamentLeave = tournamentLeaves[leaf];
                    if(tournamentLeave.index == -1){
                        leaf++;
                        continue;
                    }
                    heap[i] = tournamentLeave.attrs[tournamentLeave.index++];
                    heapSize++;
                    leaf++;
                }else break;
            }

            heapSize += actualLeaves - 1;

            for(int i = actualLeaves - 1;i >= 0;i--) buildMaxHeap(i);

            return this;
        }

        private void buildMaxHeap(int index){
            if(index >= heapSize || index < 0) return;
            int left = index * 2 + 1;
            int right = index * 2 + 2;

            int position = index;
            if(left < heapSize && heap[left].compareTo(heap[position]) == 1) position = left;
            if(right < heapSize && heap[right].compareTo(heap[position]) == 1) position = right;

            if(position == index) return;

            PictureAttribute temp = heap[position];
            heap[position] = heap[index];
            heap[index] = temp;

            index = heap.length >> 1;
            if(position >= index && heap[position] == null){
                index = position - index;
                TournamentLeaves tournamentLeave = tournamentLeaves[index];
                if(tournamentLeave.index > -1 && tournamentLeave.index < tournamentLeave.attrs.length)
                    heap[position] = tournamentLeave.attrs[tournamentLeave.index++];
            }else buildMaxHeap(position);
        }

        private PictureAttribute extractMax(int indexesUsed){
            if(heapSize == 0) return null;
            PictureAttribute pictureAttribute = heap[0];
            heap[0] = heap[heapSize - 1];

            int index = heap.length >> 1;
            if(heapSize - 1 >= index){
                index = heapSize - 1 - index;

                TournamentLeaves tournamentLeave = tournamentLeaves[index];
                if(tournamentLeave.index == -1) heapSize--;
                else {
                    for (; tournamentLeave.index < tournamentLeave.attrs.length; tournamentLeave.index++)
                        if ((tournamentLeave.attrs[tournamentLeave.index].getIndexes() & indexesUsed) == 0)
                            break;

                    if (tournamentLeave.index < tournamentLeave.attrs.length) {
                        heap[heapSize - 1] = tournamentLeave.attrs[tournamentLeave.index++];
                    } else heapSize--;
                }

            }else heapSize--;

            buildMaxHeap(0);
            return pictureAttribute;
        }

        public PictureAttribute extractNextFrame(int indexesUsed){
            PictureAttribute pictureAttribute = extractMax(indexesUsed);

            while(pictureAttribute != null && (pictureAttribute.getIndexes() & indexesUsed) != 0)
                pictureAttribute = extractMax(indexesUsed);

            return pictureAttribute;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/card_upper_background"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/grade"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:capitalize="words"
            android:text="text"
            android:textColor="#ffffff"
            android:textSize="15.0dip" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:layout_marginTop="4dp"
        android:background="@drawable/card_background"
        android:gravity="right"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@+id/done"
            android:gravity="bottom" >

            <TextView
                android:id="@+id/option_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/grade_type"
                android:layout_below="@+id/grade_type"
                android:layout_centerHorizontal="true"
                android:text="Grades"
                android:textSize="15.0dip"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/grade_type"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="Lessons"
                android:textColor="#ff000000"
                android:textSize="15.0dip" />
        </RelativeLayout>

        <CheckBox
            android:id="@+id/done"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" />

        <ImageButton
            android:id="@+id/expand"
            android:layout_width="wrap_content"
            android:layout_height="10dp"
            android:layout_below="@+id/relativeLayout1"
            android:layout_centerHorizontal="true"
            android:background="@null"
            android:src="@drawable/ic_action_expand" />

    </RelativeLayout>

</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Nephi 2</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#partOfSpeech</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">proper noun</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Person</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://eom.byu.edu/index.php/Nephi_2</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/triple-index/nephi-2?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/gs/nephi-son-of-helaman</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#definition</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">In the Book of Mormon, a great Nephite prophet and missionary.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/guide-to-the-scriptures</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#altLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Son of Helaman</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#gender</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">male</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/helaman-3</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/lehi-4</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/nephi-2</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">2</sem:object>
  </sem:triple>
</sem:triples>


text:
/*
		graphPrototypeCanvas.html
		Written by: Stephen Lindberg
		Created: 6/28/11
		Last modified: 7/29/11
	*/
	var sizesArr = dataSets.sizes;
var conArr = dataSets.connectivities;
var urlArr = dataSets.setURLs;
	var dataCollectFinished = false;

	var graph;
	var jData;
	var jDataReadyFirstTime = true;

	var viewWidth;
	var viewHeight;

	var pen;
	var edgePen;
	var bgPen;
	var hidPen;

	var myCamera;

	var bgPtrn;

	var mouseX = 0;
	var mouseY = 0;
	var mouseClicked = false;

	var kb;

	var timer;
	var firstDrawTimer;
	var serverTimer;

	var numNodes;
	var connectivity;

	var times = new Array();
	var timesIter;
	var timesLoops;

	/* *
		main
		This function is called when all the elements of the document are ready. It initializes all the objects for our
			application and then starts up the update loop.
		Postconditions: The application is started and enters the update loop.
	* */

	$(document).ready(function()
	{
		var graphSizeIndex = sessionStorage.getItem("sizeIndex");
		if(!graphSizeIndex)
		{
			sessionStorage.setItem("sizeIndex",0);
			graphSizeIndex=0;
		}
		var conIndex = sessionStorage.getItem("conIndex");
		if(!conIndex)
		{
			sessionStorage.setItem("conIndex",0);
			conIndex = 0;
		}
		var urlIndex = sessionStorage.getItem("urlIndex");
		if(!urlIndex)
		{
			sessionStorage.setItem("urlIndex",0);
			urlIndex = 0;
		}

		// get contexts for our canvases
		var c = document.getElementById("edgeGroup");
		edgePen = c.getContext("2d");
		c = document.getElementById("nodeGroup");
		pen = c.getContext("2d");
		c = document.getElementById("bgCanvas");
		bgpen = c.getContext("2d");
		c = document.getElementById("canvasHidden");
		hidpen = c.getContext("2d");

		// create background pattern

		var ptrnImg = document.createElement("canvas");
		var ptrnPen = ptrnImg.getContext("2d");
		ptrnImg.width = 32;
		ptrnImg.height = 32;

		mpRect(ptrnPen,0,0,16,16,"lightblue","lightblue");
		mpRect(ptrnPen,16,16,16,16,"lightblue","lightblue");

		bgPtrn = new mpPattern(ptrnImg, "repeat",0,0,32,32);

		// set up the camera

		myCamera = new Camera([edgePen,pen]);
		myCamera.moveTo(320,240);

		timesLoops = 20;
		times[0] = 0; // total rendering time
		times[1] = timesLoops; // number of renderings
		times[102] = 0; // total server time
		timesIter = 0;

		numNodes = sizesArr[graphSizeIndex];
		connectivity = conArr[conIndex];
	//	numNodes = prompt("How many nodes?");
	//	connectivity = prompt("How much connectivity? [0.0 , 1.0]");

		makeGraph();

	});

	/* *
		makeGraph
		Creates a new graph instance.
	* */

	function makeGraph()
	{
		jDataReadyFirstTime = true;

		// set up the StopWatches
		timer = new StopWatch();
		firstDrawTimer = new StopWatch();
		serverTimer = new StopWatch();

		firstDrawTimer.expired = false;

		// Let's make a graph! :D
		if(graph)
			graph.destroy();
		graph = new Graph(document);
		graph.readJSON([firstDrawTimer, serverTimer], numNodes, connectivity);

		// enter the update loop

		updateCanvas();
	}

	/* *
		updateCanvas
		The main timer loop of the application. This method handles all interactivity and redraws the graph.
		Postconditions: The application is updated and is scheduled to be updated again after 20 ms. If this was the first
			time through the loop, an alert message will be displayed to inform the user how long it took to initially render the
			graph.
	* */

	function updateCanvas()
	{

		if(graph.jsonReady)
		{
			if(jDataReadyFirstTime)
			{
				viewWidth = graph.jsonData.globalCoordinateInformation.width;
				viewHeight = graph.jsonData.globalCoordinateInformation.height;

				jDataReadyFirstTime = false;

				myCamera.viewWidth = viewWidth;
				myCamera.viewHeight = viewHeight;

				myCamera.zoomToFit();

			}

			// Draw a background using our pattern
			mpClear(bgpen,"white");
			mpClear(bgpen,bgPtrn);

			// update the mouse

			myCamera.updateMouse(mouseX,mouseY);

			// begin drawing stuff

			mpClear(pen, myCamera);
			mpClear(edgePen, myCamera);

			pen.lineWidth = 3;
			mpCircle(pen,0,0,10,"#9999CC","#9999CC");
			mpRect(pen,0,0,viewWidth,viewHeight);

			if(graph.draw)
			{
				graph.draw(myCamera);
			}

		//	graph.drawToolTip(mouseX,mouseY);

			mpText(bgpen, "render time: " + times[timesIter + 1],10,50,"black","black");
			if(timesIter != 0)
				mpText(bgpen, "# Nodes: " + graph.numNodes + ", # Edges: " + graph.numEdges ,10,70,"black","black");

			mpImage(bgpen, hidpen.canvas ,0,0);

			// reset and start the redraw timer

			timer.start();

			// if this was our first loop through, alert the user how long it took to initially render the graph.

			if(!firstDrawTimer.expired)
			{
				firstDrawTimer.expired = true;

				var thistime = firstDrawTimer.getTime();
				var servertime = serverTimer.getTime();

				times[timesIter+2] = thistime;
				times[0] += thistime;
				times[timesIter+103] = servertime;
				times[102] += servertime;
				timesIter++;
				if(timesIter < timesLoops)
				{
					setTimeout("makeGraph()",20);
				}
				else
				{

					displayDataWindow(numNodes, connectivity, times, "Initial Rendering", "Canvas");

					// automation code

					//	alert("Finished drawing the graph. Time(ms): " + firstDrawTimer.getTime());
					var graphSizeIndex = sessionStorage.getItem("sizeIndex");
					var conIndex = sessionStorage.getItem("conIndex");
					var urlIndex = sessionStorage.getItem("urlIndex");
				//	alert("size:" + sizesArr[graphSizeIndex] +"\n" + "con: " + conArr[conIndex]);
					conIndex++;
					if(conIndex > 2)
					{
						conIndex = 0;
						graphSizeIndex++;
					}

					if(graphSizeIndex >= sizesArr.length)
					{
						urlIndex++;
						//window.location.reload();
						graphSizeIndex = 0;

					}
					sessionStorage.setItem("sizeIndex",graphSizeIndex);
					sessionStorage.setItem("conIndex",conIndex);
					sessionStorage.setItem("urlIndex",urlIndex);

					window.location.href = urlArr[urlIndex];
				}
			}
		}
		else
		{
			setTimeout("updateCanvas()",20);
		}
	}


text:
<?php

/**
 * This is the model class for table "{{user_login_attempts}}".
 *
 * The followings are the available columns in table '{{user_login_attempts}}':
 * @property integer $id
 * @property string $username
 * @property integer $user_id
 * @property string $performed_on
 * @property boolean $is_successful
 * @property string $session_id
 * @property integer $ipv4
 * @property string $user_agent
 *
 * The followings are the available model relations:
 * @property User $user
 */
abstract class ExampleUserLoginAttempt extends CActiveRecord
{
    /**
     * @inheritdoc
     */
    public function tableName()
    {
        return '{{user_login_attempts}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return array(
        );
    }

    /**
     * @inheritdoc
     */
    public function relations()
    {
        return array(
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('models', 'ID'),
            'username' => Yii::t('models', 'Username'),
            'user_id' => Yii::t('models', 'User'),
            'performed_on' => Yii::t('models', 'Performed On'),
            'is_successful' => Yii::t('models', 'Is Successful'),
            'session_id' => Yii::t('models', 'Session ID'),
            'ipv4' => Yii::t('models', 'IPv4'),
            'user_agent' => Yii::t('models', 'User Agent'),
        );
    }

    /**
     * @param  string           $className active record class name.
     * @return UserLoginAttempt the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    protected function beforeSave()
    {
        if ($this->isNewRecord) {
            /** @var CHttpRequest */
            $request = Yii::app()->request;
            $this->performed_on = date('Y-m-d H:i:s');
            $this->session_id = Yii::app()->session->sessionID;
            $this->ipv4 = ip2long($request->userHostAddress);
            $this->user_agent = $request->userAgent;
            if ($this->ipv4 > 0x7FFFFFFF) {
                $this->ipv4 -= (0xFFFFFFFF + 1);
            }
        }

        return parent::beforeSave();
    }

    /**
     * Checks if there are not too many login attempts using specified username in the specified number of seconds until now.
     * @param  string  $username
     * @param  integer $count_limit number of login attempts
     * @param  integer $time_limit  number of seconds
     * @return boolean
     */
    public static function hasTooManyFailedAttempts($username, $count_limit = 5, $time_limit = 1800)
    {
        $since = new DateTime();
        $since->sub(new DateInterval("PT{$time_limit}S"));
        $subquery = UserLoginAttempt::model()->dbConnection->createCommand()
            ->select('is_successful')
            ->from(UserLoginAttempt::model()->tableName())
            ->where('username = :username AND performed_on > :since')
            ->order('performed_on DESC')
            ->limit($count_limit)->getText();

        return $count_limit <= (int) UserLoginAttempt::model()->dbConnection->createCommand()
            ->select('COUNT(NOT is_successful OR NULL)')
            ->from("({$subquery}) AS t")
            ->queryScalar(array(':username' => $username, ':since' => $since->format('Y-m-d H:i:s')));
    }
}


text:
/*Write a program that reads three numbers and prints "increasing" if they are
* in increasing order, "decreasing" if they are in decreasing order, and "neither"
* otherwise. Here, "increasing" means "strictly increasing", with each value larger
* than its predecessor. The sequence 3 4 4 would not be considered increasing.
*/

import java.util.Scanner;

public class P3_05 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        double n1 = input.nextDouble();
        double n2 = input.nextDouble();
        double n3 = input.nextDouble();
        input.close();
        System.out.println((n1 > n2 == true) && (n2 > n3 == true)? "Decreasing":
                           (n1 < n2 == true) && (n2 < n3 == true)? "Increasing":
                                                                   "Neither");
    }
}


text:
  Parroy est
       un village
       localisé dans le département de Meurthe-et-Moselle en Lorraine. On dénombrait 170 habitants en 2008.

La ville propose quelques  équipements, elle dispose, entre autres, de deux boucles de randonnée.

Le parc de logements, à Parroy, se décomposait en 2011 en deux appartements et 98 maisons soit
 un marché relativement équilibré.

À proximité de Parroy sont situées les villes de
Réchicourt-la-Petite localisée à 4 km, 71 habitants,
Bathelémont-lès-Bauzemont située à 5 km, 59 habitants,
Mouacourt localisée à 1 km, 72 habitants,
Bezange-la-Petite située à 5 km, 93 habitants,
Hénaménil localisée à 3 km, 183 habitants,
Arracourt localisée à 6 km, 240 habitants,
 entre autres. De plus, Parroy est située à seulement douze km de Lunéville.

Si vous pensez venir habiter à Parroy, vous pourrez aisément trouver une maison à vendre.


text:
struct VirtualAllocBuffer
{
	char * m_region_base_addr;
	size_t m_end_offset;
	size_t m_region_size;
	size_t m_region_capacity;

	VirtualAllocBuffer () : m_region_base_addr(nullptr), m_end_offset(0), m_region_size(0), m_region_capacity(0) { }

	~VirtualAllocBuffer ()
	{
		rmReservedPages();
	}

	char * begin () { return m_region_base_addr; }
	char const * begin () const { return m_region_base_addr; }
	char * end () { return begin() + m_end_offset; }
	char const * end () const { return begin() + m_end_offset; }
	size_t capacity () const { return m_region_size; }
	size_t shiftEnd (size_t n) {  return m_end_offset += n; }
	void reset () { m_end_offset = 0; }

	bool mkReservedPages (size_t reserved_region_size)
	{
		LPVOID addr = VirtualAlloc(nullptr, reserved_region_size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_READWRITE);
		if (m_region_base_addr = static_cast<char *>(addr))
		{
			qDebug("MEMORY: virtualalloc at base=0x%x sz=%u", m_region_base_addr, reserved_region_size);
			m_region_capacity = reserved_region_size;
			return true;
		}
		assert(m_region_base_addr);
		return false;
	}
	bool mkCommitPages (char * addr, size_t commited_region_size)
	{
		LPVOID res = VirtualAlloc(addr, commited_region_size, MEM_COMMIT, PAGE_READWRITE);
		if (static_cast<char *>(res))
			return true;
		return false;
	}

	void rmReservedPages ()
	{
		if (m_region_base_addr)
		{
			qDebug("MEMORY: virtualfree at base=0x%x sz=%u", m_region_base_addr, m_region_capacity);
			VirtualFree(m_region_base_addr, 0, MEM_RELEASE);
			m_region_base_addr = nullptr;
		}
		//@TODO: MEM_RESET
	}

	constexpr size_t getPageSize () const { return 64 * 1024; }
	constexpr size_t getPageCount () const { return 16; }

	bool mkStorage (size_t reserved_region_size)
	{
		if (mkReservedPages(reserved_region_size))
		{
			if (mkCommitPages(m_region_base_addr, getPageCount() * getPageSize()))
			{
				m_region_size = getPageCount() * getPageSize();
				return true;
			}
		}
		return false;
	}

	void releaseStorage ()
	{
		rmReservedPages();
	}

	bool resizeStorage (size_t n)
	{
		size_t const curr_sz = m_region_size;
		size_t const commit_sz = n - curr_sz;
		if (curr_sz + commit_sz <= m_region_capacity && mkCommitPages(m_region_base_addr + curr_sz, commit_sz))
		{
			m_region_size += commit_sz;
// 		char buff[256];
// 		snprintf(buff, 256, "# resize %d  base=0x%08x curr=%d commit_sz=%d\n", n, m_region_base_addr, curr_sz, commit_sz);
// 		OutputDebugStringA(buff);
			return true;
		}
		return false;
	}

	size_t calcNextSize () const
	{
		size_t const sz = m_region_size + getPageCount() * getPageSize();
		return sz;
	}
};


text:
<?php

namespace OpenTable\BusinessBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SubLocation
 *
 * @ORM\Table(name="sub_location", indexes={@ORM\Index(name="locatioId", columns={"locatioId"})})
 * @ORM\Entity
 */
class SubLocation
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=200, nullable=false)
     */
    private $name;

    /**
     * @var \Location
     *
     * @ORM\ManyToOne(targetEntity="Location")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="locatioId", referencedColumnName="id")
     * })
     */
    private $locatioid;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return SubLocation
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set locatioid
     *
     * @param \OpenTable\BusinessBundle\Entity\Location $locatioid
     * @return SubLocation
     */
    public function setLocatioid(\OpenTable\BusinessBundle\Entity\Location $locatioid = null)
    {
        $this->locatioid = $locatioid;

        return $this;
    }

    /**
     * Get locatioid
     *
     * @return \OpenTable\BusinessBundle\Entity\Location
     */
    public function getLocatioid()
    {
        return $this->locatioid;
    }
}


text:
package io.dang.tomcat.session;

import com.google.common.collect.ImmutableMap;
import io.dang.tomcat.CassandraClient;
import org.scassandra.Scassandra;
import org.scassandra.ScassandraFactory;
import org.scassandra.http.client.*;
import org.scassandra.matchers.Matchers;
import org.testng.annotations.*;

import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;

import static org.scassandra.matchers.Matchers.containsQuery;
import static org.testng.Assert.*;
import static org.scassandra.cql.PrimitiveType.*;

public class CassandraClientTest {
    protected static Scassandra scassandra;
    protected static int binaryPort = 8042;
    protected static int adminPort = 8043;
    protected static PrimingClient primingClient;
    protected static ActivityClient activityClient;

    @BeforeClass
    public static void start() {
        scassandra = ScassandraFactory.createServer(binaryPort, adminPort);
        primingClient = scassandra.primingClient();
        activityClient = scassandra.activityClient();
        scassandra.start();
    }

    @AfterClass
    public static void stopScassandra() {
        scassandra.stop();
    }

    @BeforeMethod
    public void setup() {
        activityClient.clearAllRecordedActivity();
        primingClient.clearAllPrimes();
    }

    @Test
    public void connectionCreationTest() {
        CassandraClient cassandraClient = new CassandraClient("TestCluster", "TestKeyspace");

        String query = "SELECT * FROM SYSTEM.SCHEMA_KEYSPACES WHERE KEYSPACE_NAME = ?";
        Query expectedQuery = Query.builder().withQuery(query).withConsistency("ONE").build();

        Map<String, ?> row = ImmutableMap.of("dummy_row", "dummy_value");
        PrimingRequest prime = PrimingRequest.queryBuilder()
                .withQuery(query)
                .withRows(row)
                .withConsistency(PrimingRequest.Consistency.ONE)
                .build();

        primingClient.prime(prime);
        cassandraClient.connect("localhost", binaryPort);

        assertThat(activityClient.retrieveQueries(), containsQuery(expectedQuery));

        assertNotEquals(activityClient.retrieveConnections().size(), 0);

        cassandraClient.close();
    }
}


text:
define({
	"navigation": "Nachrichten",
	"message": "Nachricht",
    "messagePlaceholder": "Nachricht senden...",
    "send": "Senden",
    "clear": "Nachrichten löschen",
    "limit": "Nachrichten anzeigen",
	"nolimit": "Alle Nachrichten",
	"confirmClear": "Willst du wirklich alle Nachrichten löschen?"
});


text:
/**
* @author Alexander V. Astapchuk
* @version $Revision$
*/

package org.apache.harmony.security.tests.java.security;

import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;

import java.security.AccessControlException;
import java.security.AllPermission;
import java.security.Permission;
import java.security.UnresolvedPermission;

import junit.framework.TestCase;

/**
 * Unit test for AccessControlException.
 */
@TestTargetClass(AccessControlException.class)
public class AccessControlExceptionTest extends TestCase {

    /**
     * Tests AccessControlException(String)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "AccessControlException",
        args = {java.lang.String.class}
    )
    public void testAccessControlExceptionString() {
        new AccessControlException(null);
        new AccessControlException("Failure");
    }

    /**
     * Tests AccessControlException(String, Permission)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "AccessControlException",
        args = {java.lang.String.class, java.security.Permission.class}
    )
    public void testAccessControlExceptionStringPermission() {
        Permission perm = new AllPermission();
        AccessControlException controlException = new AccessControlException("001", perm);
        assertEquals("exception message", "001", controlException.getMessage());
        assertEquals("permission", perm, controlException.getPermission());
    }

    /**
     *
     * Tests AccessControlException.getPermission()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getPermission",
        args = {}
    )
    public void testGetPermission() {
        Permission perm = new UnresolvedPermission("unresolvedType",
                "unresolvedName", "unresolvedActions", null);
        AccessControlException ex = new AccessControlException("001", perm);
        assertSame(ex.getPermission(), perm);
    }
}


text:
title: Learning Redis from scratch
date: 2017-04-19 12:45:00 Z
categories:
- code
layout: post
subtitle: NoSQL, not now, not ever
---

![redis logo](http://www.cloudtalk.it/wp-content/uploads/2015/04/redis-database-intervista-sanfilippo.png)

More and more I've been finding roles that ask you to know some NoSQL database implementation — Mongo, Redis, Cassandra, and so forth.

The why gets us into some very thick weeds. [Couchbase][whitepaper], the maker of an open-source document-oriented NoSQL database, has a white paper on why NoSQL databases might be better for certain applications. In short:

1. They're schema-less, which means that your model can expand to fit however many attributes you want instead of sticking to a static schema.
2. You can store more types of data primitives in NoSQL databases. In most cases like Redis, they'll be serialized as a string and can be cast back when you retrieve it.
3. NoSQL databases work well with [horizontal scaling][horizontal-scaling]. They're designed to distribute loads between multiple machines more effectively than RDBMS's, which usually opt for vertical scalability.

There are obviously big discussions out RDBMS and NoSQL DBs that mostly boil down to one question: what are you actually doing with your data? If you're finding relations and doing calculations and joining your data, you'll want a RDBMS. If you just need a document-based store with the ability to save large chunks of binary-safe data, then NoSQL might be a better performer.

In any case, I wasn't out to make any production-scale apps with this database. I simply wanted to get to understand how it worked a bit better.

### Basics

Redis is a data structure store. It stores all its values in unique keys, via the `SET` and `GET` methods for normal primitives (strings, integers, floats) and specialized methods for lists, hashes, and sets.

Most languages come with packages that bind Redis commands to a client. Ruby has its own redis gem, which is structured similarly to what you might see with ActiveRecord:

```ruby
require 'redis'
redis = Redis.new
redis.set("message", "hello world!")
redis.get("message") #=> "hello world!"
```

### More Beyond the Basics

Because life is a little more complicated than strings and numbers, we can add things in sets and lists. Sets are unordered collections of **unique** strings, while lists are ordered by insertion with the ability to add new elements at the head or tail.

```ruby
redis.sadd("girl_names", ["Sally", "Jane", "Emily"])
redis.smembers("girl_names") #=> ["Sally", "Jane", "Emily"]
redis.lpush("boy_names", ["Joe", "John"])
redis.rpush("boy_names", "Jim")
redis.lrange("boy_names", 0, -1) #=> ["John", "Joe", "Jim"]
```

Redis also has support for hashes, and the redis gem has in-built support for native Ruby hashes.

```ruby
redis.mapped_hmset("user:1", { :name => "Clinton Nguyen", :age => 24 })
redis.hgetall("user:1") # => {"name"=>"Clinton Nguyen", "age"=>"24"}
```

Unfortunately everything comes back as a string, so you'll have to recast anything you need back into their requisite datatypes.

### Geospatial Data

For one of my coding challenges, I had to keep track of a set of Marvel heroes arbitrarily assigned to random US cities. Redis has in-built support for geopositions via the `GEOADD` command. This command makes a sorted set and takes in a key name, and multiple 3-tuples containing the name of the member, and its longitude and latitude.

The redis gem's built-in geoadd method can take in an ll array.

```ruby
def geoadd_chars(chars)
  chars.each do |character|
    DB::geoadd("hero_locations", JSON.parse(character["location"]["ll"]), character["name"])
    DB::set(character["name"], character.to_json)
  end
end
```

Redis also has methods for calculating the distance between set members with the `GEORADIUS` command. For instance, inserting your own coordinates in the set, you can figure out your distance compared to any other member of the set using the `GEODIST` command.

### Conclusions

All in all, on a small scale, redis provides a neat and simplistic store for data that can be serialized back and forth. I'd wager that once your concerns start overlapping with model relations, it's time to re-evaluate why you're using NoSQL over any other RDBMS's.

But I can see the power of this when you're handling large documents or otherwise need to handle blobs of data. There's nothing quite so similar in relational database land.

[whitepaper]: https://www.couchbase.com/nosql-resources/why-nosql
[horizontal-scaling]: https://dba.stackexchange.com/posts/4512/revisions


text:
using System;

namespace WGnet.Utils
{
    /// <summary>
    /// Класс для конвертаций Unix Timestamp и DateTime
    /// </summary>
    public static class WgDateTimeConverter
    {
        /// <summary>
        /// Конвертирует Unix Timestamp в DateTime
        /// </summary>
        /// <param name="timestamp">Unix Timestamp</param>
        /// <returns>Значение в формате DateTime</returns>
        public static DateTime DateFromTimestamp(this long timestamp)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
        }

        /// <summary>
        /// Конвертирует nullable Unix Timestamp в nullable DateTime
        /// </summary>
        /// <param name="timestamp">Nullable Unix Timestamp</param>
        /// <returns>Значение в формате nullable DateTime</returns>
        public static DateTime? DateFromTimestamp(this long? timestamp)
        {
            return timestamp == null
                ? (DateTime?) null
                : new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((double) timestamp);
        }

        /// <summary>
        /// Конвертирует nullable DateTime в nullable Unix Timestamp
        /// </summary>
        /// <param name="date">Nullable DateTime</param>
        /// <returns>Значение в nullable Unix Timestamp</returns>
        public static long? DateToTimestamp(this DateTime? date)
        {
            return date == null ? (long?) null : Convert.ToInt64((date - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Value.TotalSeconds);
        }

        /// <summary>
        /// Конвертирует DateTime в Unix Timestamp
        /// </summary>
        /// <param name="date">DateTime</param>
        /// <returns>Значение в Unix Timestamp</returns>
        public static long DateToTimestamp(this DateTime date)
        {
            return Convert.ToInt64((date - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
        }
    }
}


text:
@interface ControlChart : PlotItem<CPTPlotDataSource>
{
    NSArray *plotData;
    double meanValue;
    double standardError;
}

@end


text:
layout: portfolio-installation
title: Portfolio (installations)
comments: false

imageurl: /assets/image/fb-img-portfolio.jpg
paginate:
  permalink: /portfolio-installation-:num/
  collection: projects
  tag: installation
  per_page: 40
  reversed: true
---


text:
import pytest

from pytorch_lightning import Trainer
from pytorch_lightning.plugins import (
    DDPPlugin,
    DDPShardedPlugin,
    DDPSpawnPlugin,
    DDPSpawnShardedPlugin,
    DeepSpeedPlugin,
    TPUSpawnPlugin,
    TrainingTypePluginsRegistry,
)
from tests.helpers.runif import RunIf

def test_training_type_plugins_registry_with_new_plugin():
    class TestPlugin:

        distributed_backend = "test_plugin"

        def __init__(self, param1, param2):
            self.param1 = param1
            self.param2 = param2

    plugin_name = "test_plugin"
    plugin_description = "Test Plugin"

    TrainingTypePluginsRegistry.register(
        plugin_name, TestPlugin, description=plugin_description, param1="abc", param2=123
    )

    assert plugin_name in TrainingTypePluginsRegistry
    assert TrainingTypePluginsRegistry[plugin_name]["description"] == plugin_description
    assert TrainingTypePluginsRegistry[plugin_name]["init_params"] == {"param1": "abc", "param2": 123}
    assert TrainingTypePluginsRegistry[plugin_name]["distributed_backend"] == "test_plugin"
    assert isinstance(TrainingTypePluginsRegistry.get(plugin_name), TestPlugin)

    TrainingTypePluginsRegistry.remove(plugin_name)
    assert plugin_name not in TrainingTypePluginsRegistry

@pytest.mark.parametrize(
    "plugin_name, init_params",
    [
        ("deepspeed", {}),
        ("deepspeed_stage_1", {"stage": 1}),
        ("deepspeed_stage_2", {"stage": 2}),
        ("deepspeed_stage_2_offload", {"stage": 2, "offload_optimizer": True}),
        ("deepspeed_stage_3", {"stage": 3}),
        ("deepspeed_stage_3_offload", {"stage": 3, "offload_parameters": True, "offload_optimizer": True}),
    ],
)
def test_training_type_plugins_registry_with_deepspeed_plugins(plugin_name, init_params):

    assert plugin_name in TrainingTypePluginsRegistry
    assert TrainingTypePluginsRegistry[plugin_name]["init_params"] == init_params
    assert TrainingTypePluginsRegistry[plugin_name]["plugin"] == DeepSpeedPlugin

@RunIf(deepspeed=True)
@pytest.mark.parametrize("plugin", ["deepspeed", "deepspeed_stage_2_offload", "deepspeed_stage_3"])
def test_deepspeed_training_type_plugins_registry_with_trainer(tmpdir, plugin):

    trainer = Trainer(default_root_dir=tmpdir, plugins=plugin, precision=16)

    assert isinstance(trainer.training_type_plugin, DeepSpeedPlugin)

def test_tpu_spawn_debug_plugins_registry(tmpdir):

    plugin = "tpu_spawn_debug"

    assert plugin in TrainingTypePluginsRegistry
    assert TrainingTypePluginsRegistry[plugin]["init_params"] == {"debug": True}
    assert TrainingTypePluginsRegistry[plugin]["plugin"] == TPUSpawnPlugin

    trainer = Trainer(plugins=plugin)

    assert isinstance(trainer.training_type_plugin, TPUSpawnPlugin)

@pytest.mark.parametrize(
    "plugin_name, plugin",
    [
        ("ddp_find_unused_parameters_false", DDPPlugin),
        ("ddp_spawn_find_unused_parameters_false", DDPSpawnPlugin),
        ("ddp_sharded_spawn_find_unused_parameters_false", DDPSpawnShardedPlugin),
        ("ddp_sharded_find_unused_parameters_false", DDPShardedPlugin),
    ],
)
def test_ddp_find_unused_parameters_training_type_plugins_registry(tmpdir, plugin_name, plugin):

    trainer = Trainer(default_root_dir=tmpdir, plugins=plugin_name)

    assert isinstance(trainer.training_type_plugin, plugin)

    assert plugin_name in TrainingTypePluginsRegistry
    assert TrainingTypePluginsRegistry[plugin_name]["init_params"] == {"find_unused_parameters": False}
    assert TrainingTypePluginsRegistry[plugin_name]["plugin"] == plugin


text:
namespace pythonic
{

  namespace math
  {
    DEFINE_FUNCTOR_2(lgamma, std::lgamma);
  }
}

#endif


text:
class AddPreferredServiceToUser < ActiveRecord::Migration
  def change
    add_column :users, :preferred_service_id, :integer
    add_index :users, :preferred_service_id
  end
end


text:
isFile = function (url) {
  return !!WebAppInternals.staticFiles[url]
}


text:
class AddYubikeyMandatoryToAccount < ActiveRecord::Migration
  def self.up
    add_column :accounts, :yubikey_mandatory, :boolean, :null => false, :default => false
  end

  def self.down
    remove_column :accounts, :yubikey_mandatory
  end
end