text:
package com.joelapenna.foursquared;

import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.VenueUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Queries the system for any apps that can be used for sharing data,
 * like sms or email. Package exploration is largely taken from Mark
 * Murphy's commonsware projects:
 *
 * http://github.com/commonsguy/cw-advandroid
 *
 * @date September 22, 2010
 * @author Mark Wyszomierski (markww@gmail.com)
 *
 */
public class VenueShareActivity extends Activity {
    public static final String TAG = "VenueShareActivity";
    public static final boolean DEBUG = FoursquaredSettings.DEBUG;

    public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
            + ".VenueShareActivity.INTENT_EXTRA_VENUE";

    private StateHolder mStateHolder;
    private ShareAdapter mListAdapter;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DEBUG) Log.d(TAG, "onReceive: " + intent);
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
        setContentView(R.layout.venue_share_activity);
        setTitle(getString(R.string.venue_share_activity_title));

        Object retained = getLastNonConfigurationInstance();
        if (retained != null && retained instanceof StateHolder) {
            mStateHolder = (StateHolder) retained;
        } else {
            mStateHolder = new StateHolder();
            if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
                mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE));
            } else {
                Log.e(TAG, "VenueShareActivity requires a venue parcel its intent extras.");
                finish();
                return;
            }
        }

        ensureUi();
    }

    @Override
    public void onPause() {
        super.onPause();

        if (isFinishing()) {
            unregisterReceiver(mLoggedOutReceiver);
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        return mStateHolder;
    }

    private void ensureUi() {

        mListAdapter = new ShareAdapter(this, getPackageManager(), findAppsForSharing());

        ListView listView = (ListView)findViewById(R.id.listview);
        listView.setAdapter(mListAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                launchAppIntent(position);
            }
        });
    }

    private void launchAppIntent(int position) {
        ResolveInfo launchable = mListAdapter.getItem(position);
        ActivityInfo activity = launchable.activityInfo;
        ComponentName componentName = new ComponentName(
                activity.applicationInfo.packageName, activity.name);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setComponent(componentName);
        intent.setType("text/plain");
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "Foursquare Venue Share");
        intent.putExtra(android.content.Intent.EXTRA_TEXT,
                VenueUtils.toStringVenueShare(mStateHolder.getVenue()));
        startActivity(intent);

        finish();
    }

    private List<ResolveInfo> findAppsForSharing() {
        Intent intent = new Intent(Intent.ACTION_SEND, null);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("text/plain");
        List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);

        TreeMap<String, ResolveInfo> alpha = new TreeMap<String, ResolveInfo>();
        for (ResolveInfo it : activities) {
            alpha.put(it.loadLabel(getPackageManager()).toString(), it);
        }

        return new ArrayList<ResolveInfo>(alpha.values());
    }

    private class ShareAdapter extends ArrayAdapter<ResolveInfo> {

        public ShareAdapter(Context context, PackageManager pm, List<ResolveInfo> apps) {
            super(context, R.layout.user_actions_list_item, apps);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = newView(parent);
            }
            bindView(position, convertView);
            return(convertView);
        }

        private View newView(ViewGroup parent) {
            return (getLayoutInflater().inflate(R.layout.user_actions_list_item, parent, false));
        }

        private void bindView(int position, View view) {
            PackageManager packageManager = getPackageManager();
            ImageView icon = (ImageView)view.findViewById(R.id.userActionsListItemIcon);
            icon.setImageDrawable(getItem(position).loadIcon(packageManager));
            TextView label = (TextView)view.findViewById(R.id.userActionsListItemLabel);
            label.setText(getItem(position).loadLabel(packageManager));
        }
    }

    private static class StateHolder {

        private Venue mVenue;

        public StateHolder() {
        }

        public Venue getVenue() {
            return mVenue;
        }

        public void setVenue(Venue venue) {
            mVenue = venue;
        }
    }
}


text:
from frmwk import orm_db

from frmwk.model.mdMany2Many import user_roles

ROLE_ANONYMOUS = 'ANON'
ROLE_ADMINISTRATOR = 'ADMIN'

class Role(orm_db.Model):

    id = orm_db.Column(orm_db.String(8), primary_key = True)
    name = orm_db.Column(orm_db.String(64))
    users = orm_db.relationship('User',
        secondary = user_roles,
        primaryjoin = (user_roles.c.role_id == id),
        backref = orm_db.backref('role_user', lazy = 'dynamic'),
        lazy = 'dynamic')

    def __repr__(self): # pragma: no cover
        return '<Role %r>' % (self.id)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = {
	app: {
		title: 'Note4Share',
		description: 'Application to upload, share, and discuss class notes',
		keywords: 'MongoDB, Express, AngularJS, Node.js'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				//'public/lib/bootstrap/dist/css/bootstrap-theme.css',
				'public/lib/angular-ui-select/dist/select.css',
				'public/modules/core/css/rdash.css',
				'public/modules/core/css/font-awesome.min.css',
				'public/modules/core/css/core.css',
				'public/modules/users/css/users.css'
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-ui-select/dist/select.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/angular-image-spinner/dist/angular-image-spinner.js',
				'public/lib/spin.js/spin.js',
				'public/lib/ng-flow/dist/ng-flow-standalone.min.js',
				'public/lib/flow.js/dist/flow.min.js',
				'public/lib/ng-flow/dist/ng-flow.min.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};


text:
const marked = require('marked');
marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false
});

exports.renderResult = function(str) {
    return marked(str);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Essai Crypt. Exot. (Paris), Suppl. 108 (1837)

#### Original name
Lecidea condaminea Fée

### Remarks
null


text:
/*
 * UnifiedDataObjectImlp.java
 *
 * Created on 3. June 2007, 23:00
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.ujorm.implementation.map;

import java.util.Date;
import org.ujorm.Key;
import org.ujorm.core.KeyFactory;

/**
 * An UnifiedDataObject Implementation
 * @author Pavel Ponec
 */
public class MapUjoImplChild extends MapUjoImpl {

    private static final KeyFactory<MapUjoImplChild> f = KeyFactory.Builder.get(MapUjoImplChild.class);

    /** (Long) */
    public static final Key<MapUjoImplChild,Long>    PRO_P5 = f.newKey("P5");
    /** (Integer) */
    public static final Key<MapUjoImplChild,Integer> PRO_P6 = f.newKey("P6");
    /** (String) */
    public static final Key<MapUjoImplChild,String>  PRO_P7 = f.newKey("P7");
    /** (Date) */
    public static final Key<MapUjoImplChild,Date>    PRO_P8 = f.newKey("P8");
    /** (Float) */
    public static final Key<MapUjoImplChild,Float>   PRO_P9 = f.newKey("P9");

    static {
        f.lock();
    }

    /** Creates a new instance of UnifiedDataObjectImlp */
    public MapUjoImplChild() {
    }

}


text: search_result['4564']=["topic_0000000000000AFC.html","PaymentService.GenerateInvoice Method",""];


text:
<?php
/**
 * Whoops - php errors for cool kids
 * @author Filipe Dobreira <http://github.com/filp>
 */

namespace Whoops;
use Whoops\Run;

class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @return Run
     */
    protected function getRunInstance()
    {
        $run = new Run;
        $run->allowQuit(false);

        return $run;
    }
}


text:
var five = require("../lib/johnny-five");
var Edison = require("edison-io");
var board = new five.Board({
  io: new Edison()
});

board.on("ready", function() {

  // Plug the Temperature sensor module
  // into the Grove Shield's A0 jack
  var temperature = new five.Temperature({
    controller: "GROVE",
    pin: "A0"
  });

  // Plug the LCD module into any of the
  // Grove Shield's I2C jacks.
  var lcd = new five.LCD({
    controller: "JHD1313M1"
  });

  var f = 0;

  temperature.on("data", function() {

    // The LCD's background will change
    // color according to the temperature.
    //
    // Hot -> Warm: Red -> Yellow
    // Moderate: Green
    // Cool -> Cold: Blue -> Violet
    //
    // Experiment with sources of hot and
    // cold temperatures!
    //

    if (f === Math.round(this.fahrenheit)) {
      return;
    }

    f = Math.round(this.fahrenheit);

    var r = linear(0x00, 0xFF, f, 100);
    var g = linear(0x00, 0x00, f, 100);
    var b = linear(0xFF, 0x00, f, 100);

    // console.log("Fahrenheit:  %d°", f);

    lcd.bgColor(r, g, b).cursor(0, 0).print(f);
  });
});

// [Linear Interpolation](https://en.wikipedia.org/wiki/Linear_interpolation)
function linear(start, end, step, steps) {
  return (end - start) * step / steps + start;
}

// @markdown
// For this program, you'll need:
//
// ![Grove Base Shield v2](http://www.seeedstudio.com/depot/images/product/base%20shield%20V2_01.jpg)
//
// ![Grove - LCD RGB w/ Backlight](http://www.seeedstudio.com/wiki/images/0/03/Serial_LEC_RGB_Backlight_Lcd.jpg)
//
// ![Grove - Temperature Sensor](http://www.seeedstudio.com/wiki/images/thumb/b/b0/Temperature1.jpg/400px-Temperature1.jpg)
//
//
// @markdown


text:
/****************************************************************************
 * @file
 * @brief Implementation for the Administrator Commissioning Cluster
 ***************************************************************************/

#include <app-common/zap-generated/cluster-objects.h>
#include <app/AttributeAccessInterface.h>
#include <app/CommandHandler.h>
#include <app/ConcreteCommandPath.h>
#include <app/server/CommissioningWindowManager.h>
#include <app/server/Server.h>
#include <app/util/af.h>
#include <app/util/attribute-storage.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CommissionableDataProvider.h>
#include <platform/DeviceControlServer.h>
#include <protocols/interaction_model/Constants.h>
#include <setup_payload/SetupPayload.h>
#include <system/SystemClock.h>

using namespace chip;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::AdministratorCommissioning;
using namespace chip::Protocols;

class AdministratorCommissioningAttrAccess : public AttributeAccessInterface
{
public:
    // Register for the OperationalCredentials cluster on all endpoints.
    AdministratorCommissioningAttrAccess() :
        AttributeAccessInterface(Optional<EndpointId>::Missing(), Clusters::AdministratorCommissioning::Id)
    {}

    CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override;

    // Vendor ID and Fabric Index of the admin that has opened the commissioning window
    uint16_t mVendorId;
    FabricIndex mFabricIndex;
};

AdministratorCommissioningAttrAccess gAdminCommissioningAttrAccess;

CHIP_ERROR AdministratorCommissioningAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder)
{
    VerifyOrDie(aPath.mClusterId == Clusters::AdministratorCommissioning::Id);

    switch (aPath.mAttributeId)
    {
    case Attributes::WindowStatus::Id: {
        return aEncoder.Encode(Server::GetInstance().GetCommissioningWindowManager().CommissioningWindowStatus());
    }
    case Attributes::AdminFabricIndex::Id: {
        FabricIndex fabricIndex = (Server::GetInstance().GetCommissioningWindowManager().CommissioningWindowStatus() ==
                                   CommissioningWindowStatus::kWindowNotOpen)
            ? 0
            : mFabricIndex;
        return aEncoder.Encode(fabricIndex);
    }
    case Attributes::AdminVendorId::Id: {
        uint16_t vendorId = (Server::GetInstance().GetCommissioningWindowManager().CommissioningWindowStatus() ==
                             CommissioningWindowStatus::kWindowNotOpen)
            ? 0
            : mVendorId;
        return aEncoder.Encode(vendorId);
    }
    default:
        break;
    }

    return CHIP_NO_ERROR;
}

bool emberAfAdministratorCommissioningClusterOpenCommissioningWindowCallback(
    app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath,
    const Commands::OpenCommissioningWindow::DecodableType & commandData)
{
    auto commissioningTimeout = System::Clock::Seconds16(commandData.commissioningTimeout);
    auto & pakeVerifier       = commandData.PAKEVerifier;
    auto & discriminator      = commandData.discriminator;
    auto & iterations         = commandData.iterations;
    auto & salt               = commandData.salt;

    Optional<StatusCode> status           = Optional<StatusCode>::Missing();
    InteractionModel::Status globalStatus = InteractionModel::Status::Success;
    Spake2pVerifier verifier;

    ChipLogProgress(Zcl, "Received command to open commissioning window");

    FabricIndex fabricIndex       = commandObj->GetAccessingFabricIndex();
    const FabricInfo * fabricInfo = Server::GetInstance().GetFabricTable().FindFabricWithIndex(fabricIndex);
    auto & failSafeContext        = Server::GetInstance().GetFailSafeContext();
    auto & commissionMgr          = Server::GetInstance().GetCommissioningWindowManager();

    VerifyOrExit(fabricInfo != nullptr, status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(failSafeContext.IsFailSafeFullyDisarmed(), status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_BUSY));

    VerifyOrExit(commissionMgr.CommissioningWindowStatus() == CommissioningWindowStatus::kWindowNotOpen,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_BUSY));
    VerifyOrExit(iterations >= kSpake2p_Min_PBKDF_Iterations,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(iterations <= kSpake2p_Max_PBKDF_Iterations,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(salt.size() >= kSpake2p_Min_PBKDF_Salt_Length,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(salt.size() <= kSpake2p_Max_PBKDF_Salt_Length,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(commissioningTimeout <= commissionMgr.MaxCommissioningTimeout(),
                 globalStatus = InteractionModel::Status::InvalidCommand);
    VerifyOrExit(commissioningTimeout >= commissionMgr.MinCommissioningTimeout(),
                 globalStatus = InteractionModel::Status::InvalidCommand);
    VerifyOrExit(discriminator <= kMaxDiscriminatorValue, globalStatus = InteractionModel::Status::InvalidCommand);

    VerifyOrExit(verifier.Deserialize(pakeVerifier) == CHIP_NO_ERROR,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    VerifyOrExit(commissionMgr.OpenEnhancedCommissioningWindow(commissioningTimeout, discriminator, verifier, iterations, salt) ==
                     CHIP_NO_ERROR,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    ChipLogProgress(Zcl, "Commissioning window is now open");

    gAdminCommissioningAttrAccess.mFabricIndex = fabricIndex;
    gAdminCommissioningAttrAccess.mVendorId    = fabricInfo->GetVendorId();

exit:
    if (status.HasValue())
    {
        ChipLogError(Zcl, "Failed to open commissioning window. Cluster status %d", status.Value());
        commandObj->AddClusterSpecificFailure(commandPath, status.Value());
    }
    else
    {
        if (globalStatus != InteractionModel::Status::Success)
        {
            ChipLogError(Zcl, "Failed to open commissioning window. Global status " ChipLogFormatIMStatus,
                         ChipLogValueIMStatus(globalStatus));
        }
        commandObj->AddStatus(commandPath, globalStatus);
    }
    return true;
}

bool emberAfAdministratorCommissioningClusterOpenBasicCommissioningWindowCallback(
    app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath,
    const Commands::OpenBasicCommissioningWindow::DecodableType & commandData)
{
    auto commissioningTimeout = System::Clock::Seconds16(commandData.commissioningTimeout);

    Optional<StatusCode> status           = Optional<StatusCode>::Missing();
    InteractionModel::Status globalStatus = InteractionModel::Status::Success;
    ChipLogProgress(Zcl, "Received command to open basic commissioning window");

    FabricIndex fabricIndex       = commandObj->GetAccessingFabricIndex();
    const FabricInfo * fabricInfo = Server::GetInstance().GetFabricTable().FindFabricWithIndex(fabricIndex);
    auto & failSafeContext        = Server::GetInstance().GetFailSafeContext();
    auto & commissionMgr          = Server::GetInstance().GetCommissioningWindowManager();

    VerifyOrExit(fabricInfo != nullptr, status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));

    VerifyOrExit(commissionMgr.CommissioningWindowStatus() == CommissioningWindowStatus::kWindowNotOpen,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_BUSY));
    VerifyOrExit(failSafeContext.IsFailSafeFullyDisarmed(), status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_BUSY));
    VerifyOrExit(commissioningTimeout <= commissionMgr.MaxCommissioningTimeout(),
                 globalStatus = InteractionModel::Status::InvalidCommand);
    VerifyOrExit(commissioningTimeout >= commissionMgr.MinCommissioningTimeout(),
                 globalStatus = InteractionModel::Status::InvalidCommand);
    VerifyOrExit(commissionMgr.OpenBasicCommissioningWindow(commissioningTimeout, CommissioningWindowAdvertisement::kDnssdOnly) ==
                     CHIP_NO_ERROR,
                 status.Emplace(StatusCode::EMBER_ZCL_STATUS_CODE_PAKE_PARAMETER_ERROR));
    ChipLogProgress(Zcl, "Commissioning window is now open");

    gAdminCommissioningAttrAccess.mFabricIndex = fabricIndex;
    gAdminCommissioningAttrAccess.mVendorId    = fabricInfo->GetVendorId();

exit:
    if (status.HasValue())
    {
        ChipLogError(Zcl, "Failed to open commissioning window. Cluster status %d", status.Value());
        commandObj->AddClusterSpecificFailure(commandPath, status.Value());
    }
    else
    {
        if (globalStatus != InteractionModel::Status::Success)
        {
            ChipLogError(Zcl, "Failed to open commissioning window. Global status " ChipLogFormatIMStatus,
                         ChipLogValueIMStatus(globalStatus));
        }
        commandObj->AddStatus(commandPath, globalStatus);
    }
    return true;
}

bool emberAfAdministratorCommissioningClusterRevokeCommissioningCallback(
    app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath,
    const Commands::RevokeCommissioning::DecodableType & commandData)
{
    ChipLogProgress(Zcl, "Received command to close commissioning window");

    if (Server::GetInstance().GetCommissioningWindowManager().CommissioningWindowStatus() ==
        CommissioningWindowStatus::kWindowNotOpen)
    {
        ChipLogError(Zcl, "Commissioning window is currently not open");
        commandObj->AddClusterSpecificFailure(commandPath, StatusCode::EMBER_ZCL_STATUS_CODE_WINDOW_NOT_OPEN);
    }
    else
    {
        Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow();
        ChipLogProgress(Zcl, "Commissioning window is now closed");
        emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS);
    }
    return true;
}

void MatterAdministratorCommissioningPluginServerInitCallback()
{
    emberAfPrintln(EMBER_AF_PRINT_DEBUG, "Initiating Admin Commissioning cluster.");
    registerAttributeAccessOverride(&gAdminCommissioningAttrAccess);
}


text:
This is an adapter for using [Zepto.js](http://zeptojs.com) with [Highcharts](http://www.highcharts.com/) rather than jQuery.

Animations are not yet supported on non-DOM elements (such as the SVG wrapper object) since we are using Zepto CSS-based transformations.

## Usage

Include it between zepto and highcharts:

```html
<script src="zepto.js"></script>
<script src="highcharts-zepto.src.js"></script>
<script src="highcharts.src.js"></script>
```

Use `highcharts-zepto.src.js` but get the others from the official distributions.

See the examples for additional samples.

## License

MIT


text:
This Viewer provides an easy to use interface to the modding help files of Starbound

## Features
- Clear and simple user interface
- .md files are always taken from the starbound path
- Simple switching between documents
- Search and highlight matches in the file
- Document zoom: 50% - 200%
- (Re)setting of the Starbound path, for example to target the unstable branch instead

## User Interface

![Viewer GUI](https://vnyfta.dm2304.livefilestore.com/y3mlr-1WsiV-OVcEjdiP9Mfb7cGcOUYbjNEH9owBU3mI2VKr0l7BPDHs49Q8FC_kDrTKgmQrwu_l3r316bbs1D_Z3iAZd194GJHwx-kBdHlfbU10h_40jEy3i8PV9sz18dg3um0uM78736rDibTcPY6y5nBKep0ESFbKr8uTxlS_pk/StarboundApiDocViewer_2016-09-27_02-31-57.png?psid=1)

1. List of documents
2. Current document
3. Select another Starbound directory (i.e. unstable)
4. Searchbox - Starts to search automatically after you stopped typing for 0.8 seconds
  - `ENTER` (in Searchbox) Searches immetiadly
  - `CTRL + F` (from anywhere) - Jump to Searchbox
  - `ESC` (from anywhere) - Clear Searchbox and remove highlights from the document view
5. Jump to the previous match in the current document (`SHIFT + F3`)
6. Jump to the next match in the current document (`F3`)
7. Zoom controls

## Requirements

- Windows 7 or later
- Microsoft .NET 4.6.2 [Download from Microsoft](https://www.microsoft.com/en-us/download/details.aspx?id=53344)


text:
import Vue from 'vue'

import App from './App'
import router from './router'
import store from './store'

new Vue({
  el: '#app',
  render: h => h(App),
  router,
  store
})


text:
layout: post
title: "Como conectar Remote Keyboard via USB"
date: 2015-10-09 08:07:22
image: '/assets/img/remotekeyboard.png'
description:
tags: adb android spanish remotekeyboard
categories: tips
twitter_text:
---

Desde que descubrí RemoteKeyboard, tanto mi tablet como mi teléfono han cobrado una nueva vida. Ahora son compañeros en mi día a día, dándome una pantalla adicional para por ejemplo seguir mis conversaciones de IM, poder seguir lo que pasa en Slack, responder correos, mientras en mi monitor principal estoy con la terminal centrado en el trabajo propiamente dicho.

Para ello, encontré un teclado en android que se comporta muy bien, [Remote Keyboard](https://play.google.com/store/apps/details?id=de.onyxbits.remotekeyboard), el mismo permite que nos podamos conectar a un socket (escucha vía red en el puerto 2323), y en el caso que no tengamos red wifi disponible, también podemos hacer la conexión via **adb** con el usb.

## Para realizar la conexión via Wifi

1. Instalamos la aplicación en el teléfono
2. La abrimos, habilitamos el teclado, cuando nos muestra que levantó el socket nos dice la IP y el puerto en el que se encuentra
 ![](https://lh3.ggpht.com/tEW1thjWXlgHw5cine_DHsPVfyP-nZNJaPIXEapQjvQDj-RLAHJmEFeSaKZMaOrHCTQ=h900)
3. Luego nos conectamos desde la terminal de nuestro sistema operativo favorito mediante telnet
 ![](https://lh3.ggpht.com/7pSqMTjZYMH-uVn4-jkWYwd55YDTFVKFzQCBm-req0bMdPXjMyStF8mr0ElN8PiPHg=h900)
 **Tip** Utilizando por ejemplo guake, o yakuake, podemos dejar una terminal abierta y conectada a remotekeyboard, a la que podemos invocar con F12 cada vez que necesitemos escribir algo en nuestro dispositivo android.

## Para realizar la conexión via ADB

Si nos encontramos en un ambiente donde no tenemos WiFi, o en el cual no podemos conectar todos nuestros dispositivos a la misma red WiFi (por ejemplo en la oficina), también tenemos la posiblidad de conectarnos a Remote Keyboard mediante USB.

Para ello necesitamos:

- Tener instalado adb en nuestro sistema operativo, en Ubuntu y derivados sería un simple ```sudo apt-get install android-tools-adb```
- Tener habilitado el modo depuración USB de Android (desde las opciones para desarrolladores).

Luego conectamos mediante USB el dispositivo con Android, e iniciamos el servicio de adb:

    ╭─pulpo@wendy-reloaded  ~
    ╰─$ sudo adb start-server
    * daemon not running. starting it now on port 5037 *
    * daemon started successfully *

Hacemos **forward** del puerto en el que esté escuchando RemoteKeyboard, en este caso, **2323** (el default)

    ╭─pulpo@wendy-reloaded  ~
    ╰─$ adb forward tcp:2323 tcp:2323

Por último seremos capaces de conectarnos vía telnet a través de la placa de loopback de nuestra máquina, que redireccionará por adb la conexión mediante el usb al terminal android.

    ╭─pulpo@wendy-reloaded  ~
    ╰─$ telnet localhost 2323
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.

    Android Remote Keyboard

                 Welcome to your Android keyboard. Just type
        (\_/)     in this window to have key presses forwarded
        (^_^)      to your device (there will be no local echo).
        (___)O      If characters turn into garbage, check if your
                     client is configured to send them UTF-8 encoded.

        CTRL-C      Copy
        CTRL-V      Paste
        CTRL-X      Cut
        CTRL-A      Select All
        CTRL-L      Send action
        CTRL-S      Search key
        CTRL-Q      Back key
        CTRL-D      Disconnect from device
        CTRL-R      (Un-)Scramble text using ROT13
        INSERT      Substitute current word with a replacement.


text:
package org.springframework.social.twitter.api.impl;

import static org.junit.Assert.*;
import static org.springframework.http.HttpMethod.*;
import static org.springframework.http.MediaType.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.junit.Test;
import org.springframework.social.twitter.api.GeoCode;
import org.springframework.social.twitter.api.SearchParameters;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Tweet;

/**
 * Unit tests for advanced search using SearchParameter
 *
 * @author Rosty Kerei
 */
public class SearchParametersTest extends AbstractTwitterApiTest {

	@Test
	public void testSimple() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=50"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring");
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals("#spring", p.getQuery());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testGeoCode() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&geocode=37.781157%2C-122.39872%2C10mi&count=50"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").geoCode(new GeoCode(37.781157, -122.39872, 10, GeoCode.Unit.MILE));
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals("37.781157,-122.39872,10mi", p.getGeoCode().toString());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testLang() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&lang=nl&count=50"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").lang("nl");
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals("nl", p.getLang());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testLocale() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&locale=ja&count=50"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").locale("ja");
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals("ja", p.getLocale());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testResultType() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&result_type=popular&count=50"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").resultType(SearchParameters.ResultType.POPULAR);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals(SearchParameters.ResultType.POPULAR, p.getResultType());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testCount() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=25"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").count(25);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals(new Integer(25), p.getCount());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testUntil() throws ParseException {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=50&until=2012-01-31"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").until(new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-31"));
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals(new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-31"), p.getUntil());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testSinceId() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=50&since_id=10"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").sinceId(10);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals(new Long(10), p.getSinceId());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testMaxId() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=50&max_id=999"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));

		SearchParameters p = new SearchParameters("#spring").maxId(999);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertEquals(new Long(999), p.getMaxId());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testIncludeEntities() {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring&count=50&include_entities=false"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring").includeEntities(false);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertFalse(p.isIncludeEntities());
		assertSearchTweets(searchResults.getTweets());
	}

	@Test
	public void testComplex() throws ParseException {
		mockServer.expect(requestTo("https://api.twitter.com/1.1/search/tweets.json?q=%23spring"
						+ "&geocode=37.781157%2C-122.39872%2C10mi&lang=nl&locale=ja&result_type=popular"
						+ "&count=25&until=2012-01-31&since_id=10&max_id=999&include_entities=false"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("search"), APPLICATION_JSON));
		SearchParameters p = new SearchParameters("#spring")
			.geoCode(new GeoCode(37.781157, -122.398720, 10, GeoCode.Unit.MILE))
			.lang("nl")
			.locale("ja")
			.resultType(SearchParameters.ResultType.POPULAR)
			.count(25)
			.until(new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-31"))
			.sinceId(10)
			.maxId(999)
			.includeEntities(false);
		SearchResults searchResults = twitter.searchOperations().search(p);
		assertSearchTweets(searchResults.getTweets());
	}

	private void assertSearchTweets(List<Tweet> tweets) {
		assertTimelineTweets(tweets, true);
		assertEquals("en", tweets.get(0).getLanguageCode());
		assertEquals("de", tweets.get(1).getLanguageCode());
	}
}


text:
package my.com.codeplay.android_demo.views;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import my.com.codeplay.android_demo.R;

/**
 * Created by Tham on 30/10/2017.
 */

public class TextSelectionDemoActivity extends AppCompatActivity {
    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mActionMode = mode;

            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.text_selection, menu);
            // the default selection actions come with Copy, Share, and Select All,
            // may remove these actions by calling removeItem on the Menu with its
            // id, for example see the lines below:
            /*menu.removeItem(android.R.id.copy);*/
            /*menu.removeItem(android.R.id.shareText);*/
            /*menu.removeItem(android.R.id.selectAll);*/
            return true;
        }

        // Called each time the action mode is shown after onCreateActionMode, but
        // may be called multiple times if the mode is invalidated. Return false if
        // nothing is done.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_search:
                    mode.finish();
                    return true;
                case R.id.menu_translate:
                    mode.finish();
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mActionMode = null;
        }
    };
    // May save ActionMode as a member variable to make changes to the contextual action bar
    // in response to other events
    private ActionMode mActionMode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_selection_demo);

        final TextView textView = (TextView) findViewById(R.id.textview);
        textView.setCustomSelectionActionModeCallback(mActionModeCallback);
    }
}


text:
#ifndef GrGpuResourceCacheAccess_DEFINED
#define GrGpuResourceCacheAccess_DEFINED

#include "GrGpuResource.h"

/**
 * This class allows code internal to Skia privileged access to manage the cache keys of a
 * GrGpuResource object.
 */
class GrGpuResource::CacheAccess {
public:
    /**
     * Sets a content key for the resource. If the resource was previously cached as scratch it will
     * be converted to a content resource. Currently this may only be called once per resource. It
     * fails if there is already a resource with the same content key. TODO: make this supplant the
     * resource that currently is using the content key, allow resources' content keys to change,
     * and allow removal of a content key to convert a resource back to scratch.
     */
    bool setContentKey(const GrResourceKey& contentKey) {
        return fResource->setContentKey(contentKey);
    }

    /**
     * Changes whether the resource counts against the resource cache budget.
     */
    void setBudgeted(bool countsAgainstBudget) { fResource->setBudgeted(countsAgainstBudget); }

    /**
     * Is the resource currently cached as scratch? This means it has a valid scratch key and does
     * not have a content key.
     */
    bool isScratch() const {
        SkASSERT(fResource->fScratchKey.isScratch());
        return NULL == this->getContentKey() && !fResource->fScratchKey.isNullScratch();
    }

    /**
     * If this resource can be used as a scratch resource this returns a valid scratch key.
     * Otherwise it returns a key for which isNullScratch is true. The resource may currently be
     * used as content resource rather than scratch. Check isScratch().
     */
    const GrResourceKey& getScratchKey() const { return fResource->fScratchKey; }

    /**
     * If the resource has a scratch key, the key will be removed. Since scratch keys are installed
     * at resource creation time, this means the resource will never again be used as scratch.
     */
    void removeScratchKey() const { fResource->removeScratchKey();  }

    /**
     * If the resource is currently cached by a content key, the key is returned, otherwise NULL.
     */
    const GrResourceKey* getContentKey() const {
        if (fResource->fFlags & GrGpuResource::kContentKeySet_Flag) {
            return &fResource->fContentKey;
        }
        return NULL;
    }

    /**
     * Is the resource object wrapping an externally allocated GPU resource?
     */
    bool isWrapped() const { return fResource->isWrapped(); }

    /**
     * Does the resource count against the resource budget?
     */
    bool isBudgeted() const {
        bool ret = SkToBool(GrGpuResource::kBudgeted_Flag & fResource->fFlags);
        SkASSERT(!(ret && fResource->isWrapped()));
        return ret;
    }

    /**
     * Called by the cache to delete the resource under normal circumstances.
     */
    void release() {
        fResource->release();
        if (fResource->isPurgable()) {
            SkDELETE(fResource);
        }
    }

    /**
     * Called by the cache to delete the resource when the backend 3D context is no longer valid.
     */
    void abandon() {
        fResource->abandon();
        if (fResource->isPurgable()) {
            SkDELETE(fResource);
        }
    }

private:
    CacheAccess(GrGpuResource* resource) : fResource(resource) { }
    CacheAccess(const CacheAccess& that) : fResource(that.fResource) { }
    CacheAccess& operator=(const CacheAccess&); // unimpl

    // No taking addresses of this type.
    const CacheAccess* operator&() const;
    CacheAccess* operator&();

    GrGpuResource* fResource;

    friend class GrGpuResource; // to construct/copy this type.
};

inline GrGpuResource::CacheAccess GrGpuResource::cacheAccess() { return CacheAccess(this); }

inline const GrGpuResource::CacheAccess GrGpuResource::cacheAccess() const {
    return CacheAccess(const_cast<GrGpuResource*>(this));
}

#endif


text:
<?php

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '',
        ],
    ],
];

return $config;


text:
'use strict';

var fs = require('fs');
var path = require('path');
var gitconfig = require('git-config-path');
var parse = require('parse-git-config');
var extend = require('extend-shallow');

module.exports = function gitUserEmail(opts) {
  opts = extend({cwd: '/', path: gitconfig()}, opts);
  var config = parse.sync(opts);
  if (typeof config === 'object' && config.hasOwnProperty('user')) {
    return config.user.email;
  }
  return null;
};


text:
export type MetaDataType = { class: string, value: any }  // eslint-disable-line @typescript-eslint/no-explicit-any

export class MetaData {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  constructor(private data: Record<string, any>, private extraKey?: string) {
  }

  get(keys: string[]): MetaDataType[] {
    return this.slice(keys).filter((k) => typeof k.value === "string");
  }

  slice(keys: string[]): MetaDataType[] {
    if (!this.data)
      return [];

    if (this.extraKey)
      return this.sliceWithExtraKey(keys);
    else
      return this.sliceWithoutExtraKey(keys);
  }

  sliceWithExtraKey(keys: string[]): MetaDataType[] {
    const data = [];

    keys.forEach((k) => {
      if (this.data[k] && this.data[k][this.extraKey])
        data.push({ class: k, value: this.data[k][this.extraKey] });
    });

    return data;
  }

  sliceWithoutExtraKey(keys: string[]): MetaDataType[] {
    const data = [];

    keys.forEach((k) => {
      if (this.data[k])
        data.push({ class: k, value: this.data[k] });
    });

    return data;
  }
}


text:
function [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp(Matrices,Options)
%MPT_MPLP Explicitly solves the given linear program (LP)
%
% [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp(Matrices,Options)
%
% ---------------------------------------------------------------------------
% DESCRIPTION
% ---------------------------------------------------------------------------
% Multiparametric linear programming
%
% Solves the problem
%   V(x) = min H U + F x
%           U
%   s.t.   G U <= W + E x
%          bndA*x <= bndb
%
% As a solution we get 'nR' regions
%   Pn(i)={x : H x <= K}
%
% with the optimal control law
%   U = Fi{i} x + Gi{i}
%
% and the corresponding cost function expression
%   V(x) = Bi{i} x + Ci{i}
%
% ---------------------------------------------------------------------------
% INPUT
% ---------------------------------------------------------------------------
% Matrices - a struct with all the parameters which are needed.
%            See description above for explanation.
%   Matrices.H=H;
%   Matrices.G=G;
%   Matrices.W=W;
%   Matrices.E=E;
%   Matrices.bndA=bndA;   Limits on exploration space, i.e. bndA*x<=bndb
%   Matrices.bndb=bndb;
%
% Options.mplpver      - version of mpLP solver to use (3 is default)
% Options.verbose      - level of verbosity
% Options.lpsolver     - which LP solver to use (help mpt_solveLP)
% Options.max_iter     - maximum number of iterations of the algorithm
% Options.step_size    - length of step over a facet
% Options.f_perturb    - Perturbation of the optimization direction
% Options.nu           - How many elements to extract from the optimizer (to
%                        deal with slacks)
% Options.debug_level
%           Due to numerical problems tiny regions are sometimes difficult to
%           calculate, i.e. are not identified at all. This may create "gaps"
%           in the computed control law. For the exploration, these will be
%           jumped over and the exploration in the state space will continue.
%           "debug_level" can have three values:
%
%           0: No debug done
%           1: A tolerance is given to find gap in the region partition,
%              small empty regions inside the region partition will be discarded.
%              Note that this is generally not a problem, since the feedback law
%              is continuous and can therefore be interpolated easily.
%              Correction to the calculation of the outer hull.
%           2: Zero tolerance to find gap in the region partition, empty regions
%              if they exist, will be detected, i.e. the user will be notified.
%              Correction to the calculation of the outer hull.
%
% Note: If Options is missing or some of the fields are not defined, the default
%       values from mptOptions will be used
%
% ---------------------------------------------------------------------------
% OUTPUT
% ---------------------------------------------------------------------------
% Pn,Fi,Gi           - for region Pn(i).H*x <= Pn(i).K computed input is
%                      U=Fi{i}*x+Gi{i}
% activeConstraints  - Cell Array which stores the active constraints
%                      of the optimizer in each region.
% Phard              - Defines the feasible state space partition (i.e. union of
%                      all regions) as Phard.H*x<=Phard.K
% details            - a structure with the following fields:
%     nR      number of regions
%     Pn      polyhedral partition
%     Fi      control law
%     Gi      control law
%     BC      connection list
%     Bi      value function
%     Ci      value function
%     nHard   number of hard constraints
%     Phard   polytope given by hard constraints
%     nb      number of constraints for each region
%     LISTa   list of active constraints
%
% see also MPT_CONSTRUCTMATRICES, MPT_MPQP, MPT_OPTCONTROL, MPT_OPTCONTROLPWA

% Copyright is with the following author(s):
%
% (C) 2003 Michal Kvasnica, Automatic Control Laboratory, ETH Zurich,
%     kvasnica@control.ee.ethz.ch
% (C) 2003 Mato Baotic, Automatic Control Laboratory, ETH Zurich,
%     baotic@control.ee.ethz.ch
% (C) 2002 Francesco Borrelli, Automatic Control Laboratory, ETH Zurich

% ---------------------------------------------------------------------------
% Legal note:
%          This program is free software; you can redistribute it and/or
%          modify it under the terms of the GNU General Public
%          License as published by the Free Software Foundation; either
%          version 2.1 of the License, or (at your option) any later version.
%
%          This program is distributed in the hope that it will be useful,
%          but WITHOUT ANY WARRANTY; without even the implied warranty of
%          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%          General Public License for more details.
%
%          You should have received a copy of the GNU General Public
%          License along with this library; if not, write to the
%          Free Software Foundation, Inc.,
%          59 Temple Place, Suite 330,
%          Boston, MA  02111-1307  USA
%
% ---------------------------------------------------------------------------

error(nargchk(1,2,nargin));

global mptOptions;
if ~isstruct(mptOptions),
    mpt_error;
end
if nargin<2,
    Options=[];
end

if ~isfield(Options,'mplpver'),
    % 1 - original mpLP
    % 2 - improved version (requires QP solver)
    % 3 - mpLP solver introduced in MPT version 1.4.1 (requires QP solver)
    % 4 - improved version of the previous option (requires QP solver)
    % 5 - successor of solver 4, supports parameterized cost (requires QP solver)
    % 6 - latest version
    Options.mplpver=Inf;
end
if ~isfield(Options,'qpsolver'),
    Options.qpsolver = mptOptions.qpsolver;
end

if Options.qpsolver==-1,
    % cannot use "new" mpLP solvers without a QP solver
    Options.mplpver = 1;
end

% make sure all matrices are in full format. this is important to do, because we
% call mpt_solvelpi which doesn't convert sparse matrices to full for solvers
% which don't support them
Matrices.H  = full(Matrices.H);
Matrices.G  = full(Matrices.G);
Matrices.E  = full(Matrices.E);
Matrices.W  = full(Matrices.W);
if isfield(Matrices, 'F'),
    Matrices.F  = full(Matrices.F);
end
if isfield(Matrices, 'Y'),
    Matrices.Y  = full(Matrices.Y);
end
if isfield(Matrices, 'Cf'),
    Matrices.Cf  = full(Matrices.Cf);
end
if isfield(Matrices, 'Cx'),
    Matrices.Cx  = full(Matrices.Cx);
end
if isfield(Matrices, 'Cc'),
    Matrices.Cc  = full(Matrices.Cc);
end
if isfield(Matrices, 'bndA'),
    Matrices.bndA = full(Matrices.bndA);
end
if isfield(Matrices, 'bndb'),
    Matrices.bndb = full(Matrices.bndb);
end
if isfield(Matrices, 'D'),
    Matrices.D = full(Matrices.D);
end

switch Options.mplpver
    case 1,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver1(Matrices,Options);
        details.feasible = isfulldim(Pn);
    case 2,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver2(Matrices,Options);
        details.feasible = isfulldim(Pn);
    case 3,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver3(Matrices,Options);
    case 4,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver4(Matrices,Options);
    case 5,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver5(Matrices,Options);
    case 6,
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver6(Matrices,Options);
    case {7, Inf},
        [Pn,Fi,Gi,activeConstraints,Phard,details]=mpt_mplp_ver7(Matrices,Options);
    otherwise
        error('mpt_mplp: unknown solver in Options.mplpver!');
end

if Options.mplpver >= 6,
    if isfield(Options, 'nu'),
        % from mpt_mplp_ver6 on, optimizers corresponding to slack
        % variables are NOT removed automatically, thus we have to do it here
        nu = Options.nu;
        for idxRegions = 1:length(Fi),
            Fi{idxRegions} = Fi{idxRegions}(1:nu,:);
            Gi{idxRegions} = Gi{idxRegions}(1:nu,:);
        end
    end
end

if ~isfield(details, 'Bi'),
    details.Bi = {};
end
if ~isfield(details, 'Ci'),
    details.Ci = {};
end

% handle non-zero affine cost term
if isfield(Matrices, 'F'),
    F = Matrices.F(:)';
    if nnz(F)>0,
        Bi = details.Bi;
        for i = 1:length(Bi)
            Bi{i} = Bi{i} + F;
        end
        details.Bi = Bi;
    end
end


text:
package com.autotest.mybatis;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.internal.util.StringUtility;
import org.mybatis.generator.internal.util.messages.Messages;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by huairen on 2017/8/2.
 */
public class RenameExampleClassPlugin extends PluginAdapter {
    private String searchString;
    private String replaceString;
    private Pattern pattern;
    private boolean valid;

    public RenameExampleClassPlugin() {
    }

    @Override
    public boolean validate(List<String> warnings) {
        this.searchString = this.properties.getProperty("searchString");
        this.replaceString = this.properties.getProperty("replaceString");
        valid = StringUtility.stringHasValue(this.searchString) && StringUtility.stringHasValue(this.replaceString);
        if(valid) {
            this.pattern = Pattern.compile(this.searchString);
        } else {
//            if(!StringUtility.stringHasValue(this.searchString)) {
//                warnings.add(Messages.getString("ValidationError.18", "RenameExampleClassPlugin", "searchString"));
//            }
//
//            if(!StringUtility.stringHasValue(this.replaceString)) {
//                warnings.add(Messages.getString("ValidationError.18", "RenameExampleClassPlugin", "replaceString"));
//            }
        }

        return true;
    }
    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        if(valid) {
            String oldType = introspectedTable.getExampleType();
            Matcher matcher = this.pattern.matcher(oldType);
            oldType = matcher.replaceAll(this.replaceString);
            introspectedTable.setExampleType(oldType);
        }else {
            String oldType = introspectedTable.getBaseRecordType();
            String newType = oldType + "DO";
            introspectedTable.setBaseRecordType(newType);
            introspectedTable.setExampleType(newType + "Example");
            String oldMapper = introspectedTable.getMyBatis3JavaMapperType();
            String newMapper = oldMapper.replaceAll("Mapper$", "DAO");
            introspectedTable.setMyBatis3JavaMapperType(newMapper);
        }
    }
}


text:
package com.thehen101.csgoexternal.cheat;

import com.github.jonatino.misc.MemoryBuffer;
import com.thehen101.csgoexternal.CSGOExternal;
import com.thehen101.csgoexternal.cheat.base.Cheat;
import com.thehen101.csgoexternal.event.EventEntityPlayerLooped;
import com.thehen101.csgoexternal.event.EventLocalPlayerUpdate;
import com.thehen101.csgoexternal.event.EventMouseButtonPressed;
import com.thehen101.csgoexternal.event.EventMouseButtonReleased;
import com.thehen101.csgoexternal.event.EventTick;
import com.thehen101.csgoexternal.event.base.Event;
import com.thehen101.csgoexternal.memory.Netvar;
import com.thehen101.csgoexternal.memory.Offset;
import com.thehen101.csgoexternal.memory.gameobject.EntityPlayer;
import com.thehen101.csgoexternal.memory.value.ValueFloat;

public class CheatAimbot extends Cheat {
	private EntityPlayer localPlayer, target;
	private final float fov = 3F, speed = 18.0F;
	private final int mouseHeldButton = 5;
	public boolean canAim;

	public CheatAimbot(String cheatName, int cheatKeybind) {
		super(cheatName, cheatKeybind);
	}

	@Override
	public void onEvent(Event event) {
		if (event instanceof EventLocalPlayerUpdate) {
			EventLocalPlayerUpdate update = (EventLocalPlayerUpdate) event;
			this.localPlayer = update.getLocalPlayer();
		}
		if (event instanceof EventMouseButtonPressed) {
			EventMouseButtonPressed buttonPressed = (EventMouseButtonPressed) event;
			if (buttonPressed.getButtonPressed() == this.mouseHeldButton)
				this.canAim = true;
		}
		if (event instanceof EventMouseButtonReleased) {
			EventMouseButtonReleased buttonReleased = (EventMouseButtonReleased) event;
			if (buttonReleased.getButtonReleased() == this.mouseHeldButton)
				this.canAim = false;
		}
		if (event instanceof EventEntityPlayerLooped) {
			if (this.localPlayer == null || !this.canAim)
				return;
			EventEntityPlayerLooped otherPlayerLoopedEvent = (EventEntityPlayerLooped) event;
			EntityPlayer otherPlayer = otherPlayerLoopedEvent.getPlayer();
			if (otherPlayer.getBaseAddress() == 0)
				return;
			if (otherPlayer.getHealth().getValueInteger() >= 1
					&& otherPlayer.getLifeState().getValueInteger() == 0
					&& otherPlayer.getImmune().getValueBoolean() == false
					&& otherPlayer.getTeam().getValueInteger() != this.localPlayer.getTeam().getValueInteger()
					&& otherPlayer.getFlags().getValueInteger() != 0
					&& otherPlayer.getDormant().getValueInteger() == 0
					&& otherPlayer.getBoneManagerAddress() != 0) {
				float[] aimPos = this.getPlayerAimPosition();
				float[] target = this.getBonePosition(otherPlayer.getBoneManagerAddress(), 8);
				float[] angles = new float[] { this.getPitch(aimPos, target), this.getYaw(aimPos, target) };
				ValueFloat[] aimAngles = this.getPlayerAimAngles();
				if (CSGOExternal.INSTANCE.getCheatManager().getCheat(CheatRecoilControl.class).isEnabled()) {
					ValueFloat[] vp = this.getPlayerViewPunch(this.localPlayer.getBaseAddress());
					angles[0] -= vp[0].getValueFloat() * 2.0F;
					angles[1] -= vp[1].getValueFloat() * 2.0F;
				}
				this.fixAngles(angles);
				float[] myAngles = new float[] { aimAngles[0].getValueFloat(), aimAngles[1].getValueFloat() };
				float[] angDiff = this.getAngDiff(myAngles, angles);
				if (this.canAim(angDiff))
					this.target = otherPlayer;
			}

		}
		if (event instanceof EventTick) {
			if (this.localPlayer == null || this.target == null || !this.canAim)
				return;
			float[] aimPos = this.getPlayerAimPosition();
			float[] target = this.getBonePosition(this.target.getBoneManagerAddress(), 8);
			float[] angles = new float[] { this.getPitch(aimPos, target), this.getYaw(aimPos, target) };
			ValueFloat[] aimAngles = this.getPlayerAimAngles();
			if (CSGOExternal.INSTANCE.getCheatManager().getCheat(CheatRecoilControl.class).isEnabled()) {
				ValueFloat[] vp = this.getPlayerViewPunch(this.localPlayer.getBaseAddress());
				angles[0] -= vp[0].getValueFloat() * 2.0F;
				angles[1] -= vp[1].getValueFloat() * 2.0F;
			}
			this.fixAngles(angles);
			float[] smoothedAngles = new float[] { aimAngles[0].getValueFloat(), aimAngles[1].getValueFloat() };
			float[] angDiff = this.getAngDiff(smoothedAngles, angles);
			if (!this.canAim(angDiff))
				return;
			smoothedAngles[0] = smoothedAngles[0] + (angDiff[0] / this.speed);
			smoothedAngles[1] = smoothedAngles[1] + (angDiff[1] / this.speed);
			this.fixAngles(smoothedAngles);
			aimAngles[0].setValueFloat(smoothedAngles[0]);
			aimAngles[1].setValueFloat(smoothedAngles[1]);
			this.target = null;
		}
	}

	@Override
	public void onDisable() {
		this.target = null;
		this.localPlayer = null;
		this.canAim = false;
	}

	public ValueFloat[] getPlayerViewPunch(final int playerAddress) {
		final int punchAddress = playerAddress + Netvar.VIEWPUNCH.getOffset();
		return new ValueFloat[] { new ValueFloat(punchAddress),
				new ValueFloat(punchAddress + 0x4) };
	}

	private float[] getAngDiff(float[] myAngles, float[] snapAngles) {
		return new float[] { (snapAngles[0] - myAngles[0]), this.clampYaw(snapAngles[1] - myAngles[1]) };
	}

	private boolean canAim(float[] angles) {
		if (angles[0] < -this.fov || angles[0] > this.fov
				|| angles[1] < -this.fov || angles[1] > this.fov)
			return false;
		return true;
	}

	private float clampYaw(float yaw) {
		float newYaw = yaw;
		while (newYaw > 180.0F)
			newYaw -= 360.0F;
		while (newYaw < -180.0F)
			newYaw += 360.0F;
		return newYaw;
	}

	private void fixAngles(float[] angle) {
		while (angle[1] > 180.0F)
			angle[1] -= 360.0F;
		while (angle[1] < -180.0F)
			angle[1] += 360.0F;
		if (angle[0] > 89.0F)
			angle[0] = 89.0F;
		if (angle[0] < -89.0F)
			angle[0] = -89.0F;
		if (angle[1] > 180.0F)
			angle[1] = 180.0F;
		if (angle[1] < -180.0F)
			angle[1] = -180.0F;
	}

	private ValueFloat[] getPlayerAimAngles() {
		final int angleAddress = Offset.ENGINEPOINTER.getAddress() +
				Offset.SETVIEWANGLES.getAddress();
		return new ValueFloat[] { new ValueFloat(angleAddress),
				new ValueFloat(angleAddress + 0x4) };
	}

	private float[] getBonePosition(int boneManagerAddress, int boneId) {
		MemoryBuffer boneBuffer = CSGOExternal.INSTANCE.getCSGOProcess().read(
				boneManagerAddress + (0x30 * boneId), 0x30);
		return new float[] { boneBuffer.getFloat(0xC), boneBuffer.getFloat(0x2C),
				boneBuffer.getFloat(0x1C)};
	}

	private float[] getPlayerAimPosition() {
		float[] origin = new float[3];
		origin[0] = this.localPlayer.getPos()[0].getValueFloat()
				+ this.localPlayer.getViewOffset()[0].getValueFloat();
		origin[1] = this.localPlayer.getPos()[1].getValueFloat()
				+ this.localPlayer.getViewOffset()[1].getValueFloat();
		origin[2] = this.localPlayer.getPos()[2].getValueFloat()
				+ this.localPlayer.getViewOffset()[2].getValueFloat();
		return origin;
	}

	private float getYaw(float[] start, float[] end) {
		double yaw = 0F;
		double xDiff = start[0] - end[0];
		double zDiff = start[2] - end[2];
		if ((xDiff < 0 && zDiff < 0) || (xDiff < 0 && zDiff > 0)) {
			yaw = Math.toDegrees(Math.atan(zDiff / xDiff)) - 90;
		} else if (xDiff > 0 && zDiff < 0) {
			zDiff = end[2] - start[2];
			yaw = Math.toDegrees(Math.atan(xDiff / zDiff));
		} else if (xDiff > 0 && zDiff > 0) {
			xDiff = end[0] - start[0];
			yaw = Math.toDegrees(Math.atan(xDiff / zDiff)) - 180;
		}
		return (float) yaw + 90;
	}

	private float getPitch(float[] start, float[] end) {
		final double xd = start[0] - end[0];
		final double yd = start[1] - end[1];
		final double zd = start[2] - end[2];
		final double xzDiff = Math.sqrt(xd * xd + zd * zd);
		return (float) Math.toDegrees(Math.atan(yd / xzDiff));
	}
}


text:
function *gen(x) {
  try {
    (yield x).next(x);
  } catch (err) {
    yield err;
  }
  return x + 1;
}

var g = gen(3);
assert.deepEqual(g.next(), { value: 3, done: false });
var complaint = g.next(g); // Sending the generator to itself.
assert.ok(complaint.value instanceof Error);
assert.strictEqual(
  complaint.value.message,
  "Generator is already running"
);
assert.deepEqual(g.next(), { value: 4, done: true });


text:
var Command       = require( "zmvc" ).Command;
var PersonModel   = require( "../model/PersonModel" );
var Notifications = require( "../definitions/Notifications" );

module.exports = AddPersonCommand;

// declare the new AddPersonCommand

function AddPersonCommand() {}

// inherit from the Model prototype

Command.extend( AddPersonCommand, Command );

/* class properties / methods */

// invoked by the framework whenever the command is launched

AddPersonCommand.prototype.execute = function( aMessageType, aMessageData )
{
    console.log( "ADD PERSON COMMAND" );

    // grab a reference to the model

    var personModel = this.getModel( PersonModel.NAME );

    // validate data (aMessageData holds the value from
    // the form input field, submitted by Form.Controller

    var personId = aMessageData;

    if ( typeof personId === "string" && personId.length > 0 )
    {
        if ( personModel.hasPerson( personId )) {
            this.broadcast( Notifications.ERROR,
                "a person with name '" + personId + "' already existed." );
        }
        else {
            personModel.storePerson( personId );
            this.broadcast( Notifications.FEEDBACK,
                "person named '" + personId + "' added to the model." );
        }
    }
    else {
        this.broadcast( Notifications.ERROR,
            "form value '" + personId + "' is an invalid name." );
    }

    // all done
    this.done();
};


text:
package steps

import (
	"github.com/bitrise-io/bitrise-yml-converter/utils"
	bitriseModels "github.com/bitrise-io/bitrise/models"
	stepmanModels "github.com/bitrise-io/stepman/models"
)

const (
	// OldSlackMessageStepID ...
	OldSlackMessageStepID = "slack-message"
	// NewSlackStepID ...
	NewSlackStepID = "slack"
)

//----------------------
// old name: slack-message
// new name: slack

/*
old version source: https://github.com/bitrise-io/steps-slack-message.git

inputs:
  - SLACK_WEBHOOK_URL
  - SLACK_CHANNEL
  - SLACK_FROM_NAME
  - SLACK_ERROR_FROM_NAME
  - SLACK_MESSAGE_TEXT
  - SLACK_ERROR_MESSAGE_TEXT
  - SLACK_ICON_EMOJI
  - SLACK_ERROR_ICON_EMOJI
  - SLACK_ICON_URL
  - SLACK_ERROR_ICON_URL
*/

/*
new version source: https://github.com/bitrise-io/steps-slack-message.git

inputs:
- content
inputs:
- webhook_url
- channel
- from_username
- from_username_on_error
- message
- message_on_error
- emoji
- emoji_on_error
- icon_url
- icon_url_on_error
*/

// ConvertSlackMessage ...
func ConvertSlackMessage(convertedWorkflowStep stepmanModels.StepModel) ([]bitriseModels.StepListItemModel, error) {
	newStepID := NewSlackStepID
	inputConversionMap := map[string]string{
		"webhook_url":            "SLACK_WEBHOOK_URL",
		"channel":                "SLACK_CHANNEL",
		"from_username":          "SLACK_FROM_NAME",
		"from_username_on_error": "SLACK_ERROR_FROM_NAME",
		"message":                "SLACK_MESSAGE_TEXT",
		"message_on_error":       "SLACK_ERROR_MESSAGE_TEXT",
		"emoji":                  "SLACK_ICON_EMOJI",
		"emoji_on_error":         "SLACK_ERROR_ICON_EMOJI",
		"icon_url":               "SLACK_ICON_URL",
		"icon_url_on_error":      "SLACK_ERROR_ICON_URL",
	}

	return utils.ConvertStepAndCreateStepListItem(convertedWorkflowStep, newStepID, inputConversionMap)
}


text:
package org.drools.model.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import org.drools.model.Argument;
import org.drools.model.Binding;
import org.drools.model.Condition;
import org.drools.model.Condition.Type;
import org.drools.model.ConditionalConsequence;
import org.drools.model.Consequence;
import org.drools.model.Declaration;
import org.drools.model.DeclarationSource;
import org.drools.model.From;
import org.drools.model.Pattern;
import org.drools.model.RuleItem;
import org.drools.model.RuleItemBuilder;
import org.drools.model.SingleConstraint;
import org.drools.model.Variable;
import org.drools.model.consequences.ConditionalNamedConsequenceImpl;
import org.drools.model.consequences.NamedConsequenceImpl;
import org.drools.model.constraints.OrConstraints;
import org.drools.model.constraints.SingleConstraint1;
import org.drools.model.constraints.SingleConstraint10;
import org.drools.model.constraints.SingleConstraint11;
import org.drools.model.constraints.SingleConstraint12;
import org.drools.model.constraints.SingleConstraint13;
import org.drools.model.constraints.SingleConstraint2;
import org.drools.model.constraints.SingleConstraint3;
import org.drools.model.constraints.SingleConstraint4;
import org.drools.model.constraints.SingleConstraint5;
import org.drools.model.constraints.SingleConstraint6;
import org.drools.model.constraints.SingleConstraint7;
import org.drools.model.constraints.SingleConstraint8;
import org.drools.model.constraints.SingleConstraint9;
import org.drools.model.constraints.TemporalConstraint;
import org.drools.model.functions.accumulate.AccumulateFunction;
import org.drools.model.patterns.AccumulatePatternImpl;
import org.drools.model.patterns.CompositePatterns;
import org.drools.model.patterns.EvalImpl;
import org.drools.model.patterns.ExistentialPatternImpl;
import org.drools.model.patterns.PatternImpl;
import org.drools.model.patterns.QueryCallPattern;
import org.drools.model.view.AbstractExprViewItem;
import org.drools.model.view.AccumulateExprViewItem;
import org.drools.model.view.CombinedExprViewItem;
import org.drools.model.view.ExistentialExprViewItem;
import org.drools.model.view.Expr10ViewItemImpl;
import org.drools.model.view.Expr11ViewItemImpl;
import org.drools.model.view.Expr12ViewItemImpl;
import org.drools.model.view.Expr13ViewItemImpl;
import org.drools.model.view.Expr1ViewItemImpl;
import org.drools.model.view.Expr2ViewItemImpl;
import org.drools.model.view.Expr3ViewItemImpl;
import org.drools.model.view.Expr4ViewItemImpl;
import org.drools.model.view.Expr5ViewItemImpl;
import org.drools.model.view.Expr6ViewItemImpl;
import org.drools.model.view.Expr7ViewItemImpl;
import org.drools.model.view.Expr8ViewItemImpl;
import org.drools.model.view.Expr9ViewItemImpl;
import org.drools.model.view.ExprNViewItem;
import org.drools.model.view.ExprViewItem;
import org.drools.model.view.FixedValueItem;
import org.drools.model.view.InputViewItem;
import org.drools.model.view.InputViewItemImpl;
import org.drools.model.view.QueryCallViewItem;
import org.drools.model.view.TemporalExprViewItem;
import org.drools.model.view.ViewItem;

import static java.util.stream.Collectors.toList;

import static org.drools.model.FlowDSL.input;
import static org.drools.model.impl.NamesGenerator.generateName;

public class ViewFlowBuilder implements ViewBuilder {

    ViewFlowBuilder() { }

    public CompositePatterns apply( RuleItemBuilder<?>[] viewItemBuilders ) {
        BuildContext ctx = new BuildContext( viewItemBuilders );
        return ensureVariablesDeclarationInView(viewItems2Condition( ctx, Type.AND, true ), ctx);
    }

    private static CompositePatterns ensureVariablesDeclarationInView(CompositePatterns view, BuildContext ctx) {
        ctx.inputs.keySet().removeAll(ctx.usedVars);
        int i = 0;
        for (Map.Entry<Variable<?>, InputViewItemImpl<?>> entry : ctx.inputs.entrySet()) {
            view.addCondition(i++, new PatternImpl(entry.getKey()));
            ctx.usedVars.add(entry.getKey());
        }

        view.ensureVariablesDeclarationInView();
        view.getSubConditions().sort( ConditionComparator.INSTANCE );
        return view;
    }

    private static CompositePatterns viewItems2Condition(BuildContext ctx, Condition.Type type, boolean topLevel) {
        List<Condition> conditions = new ArrayList<>();
        Map<Variable<?>, Condition> conditionMap = new HashMap<>();
        Map<String, Consequence> consequences = topLevel ? new LinkedHashMap<>() : null;
        Iterator<RuleItem> ruleItemIterator = ctx.ruleItems.iterator();

        while (ruleItemIterator.hasNext()) {
            Map<Variable<?>, InputViewItemImpl<?>> scopedInputs = type.createsScope() ? new LinkedHashMap<>( ctx.inputs ) : ctx.inputs;
            RuleItem ruleItem = ruleItemIterator.next();

            if ( topLevel && ruleItem instanceof AbstractExprViewItem && ( (AbstractExprViewItem) ruleItem ).isQueryExpression() ) {
                ctx.isQuery = true;
            }

            if (ruleItem instanceof FixedValueItem) {
                conditions.add( new EvalImpl( (( FixedValueItem ) ruleItem).isValue() ) );
                continue;
            }

            if (ruleItem instanceof Consequence) {
                if (!topLevel) {
                    throw new IllegalStateException("A consequence can be only a top level item");
                }
                Consequence consequence = (Consequence) ruleItem;
                String name = ruleItemIterator.hasNext() ? generateName("consequence") : RuleImpl.DEFAULT_CONSEQUENCE_NAME;
                consequences.put(name, consequence);
                conditions.add( new NamedConsequenceImpl( name, consequence.isBreaking() ) );
                continue;
            }

            if (ruleItem instanceof ConditionalConsequence) {
                if (!topLevel) {
                    throw new IllegalStateException("A consequence can be only a top level item");
                }
                conditions.add( createConditionalNamedConsequence(consequences, (ConditionalConsequence) ruleItem) );
                continue;
            }

            ViewItem viewItem = (ViewItem) ruleItem;
            if ( viewItem instanceof CombinedExprViewItem ) {
                CombinedExprViewItem combined = (CombinedExprViewItem) viewItem;
                if (combined.getType() == Type.OR) {
                    Condition condition = conditionMap.get(combined.getFirstVariable());
                    if (condition instanceof PatternImpl) {
                        PatternImpl pattern = ( PatternImpl ) condition;
                        PatternImpl orPattern = new PatternImpl( pattern.getPatternVariable() );
                        for (ViewItem expr : combined.getExpressions()) {
                            orPattern = ( PatternImpl ) viewItem2Condition( expr, orPattern, ctx );
                        }
                        pattern.addConstraint( new OrConstraints(orPattern.getConstraint().getChildren()) );
                        continue;
                    }
                }
                conditions.add( viewItems2Condition( new BuildContext( ctx, combined.getExpressions(), scopedInputs ), combined.getType(), false ) );
                continue;
            }

            if ( viewItem instanceof QueryCallViewItem ) {
                QueryCallViewItem query = ( (QueryCallViewItem) viewItem );
                for ( Argument arg : query.getArguments()) {
                    if (arg instanceof Variable) {
                        ctx.usedVars.add( ( (Variable) arg ));
                        ctx.boundVars.add( ( (Variable) arg ));
                    }
                }
                conditions.add( new QueryCallPattern( query ) );
                continue;
            }

            if ( viewItem instanceof Binding) {
                Binding bindViewItem = (Binding) viewItem;
                PatternImpl pattern = (PatternImpl) conditionMap.get(bindViewItem.getInputVariable());
                if (pattern == null) {
                    // This should probably be the bindViewItem.getBoundVariable() instead of the input
                    // as the input variables can be many
                    pattern = new PatternImpl( bindViewItem.getInputVariable() );
                    pattern.addWatchedProps( bindViewItem.getWatchedProps() );
                    ctx.usedVars.add( bindViewItem.getInputVariable() );
                    conditions.add( pattern );
                    conditionMap.put( bindViewItem.getInputVariable(), pattern );
                }
                pattern.addBinding( bindViewItem );
                ctx.usedVars.add(viewItem.getFirstVariable());
                ctx.addBinding(bindViewItem);
                scopedInputs.putIfAbsent( viewItem.getFirstVariable(), (InputViewItemImpl) input( viewItem.getFirstVariable() ) );
                continue;
            }

            Variable<?> patterVariable = findPatterVariable( viewItem, scopedInputs.keySet() );

            if ( viewItem instanceof InputViewItemImpl ) {
                scopedInputs.put( patterVariable, (InputViewItemImpl) viewItem );
                PatternImpl condition = new PatternImpl( patterVariable );
                condition.addWatchedProps( (( InputViewItemImpl ) viewItem).getWatchedProps() );
                conditions.add( condition );
                conditionMap.put( patterVariable, condition );
                ctx.usedVars.add( patterVariable );
                continue;
            }

            if ( viewItem instanceof ExistentialExprViewItem ) {
                ExistentialExprViewItem existential = ( (ExistentialExprViewItem) viewItem );
                if (patterVariable != null && !ctx.isQuery) {
                    registerInputsFromViewItem( existential.getExpression(), conditionMap, scopedInputs, patterVariable );
                }
                Condition condition = new PatternImpl( patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable) );
                Condition.Type existentialType = existential.getType();
                ViewItem existentialExpr = existential.getExpression();
                while (existentialExpr instanceof ExistentialExprViewItem) {
                    existentialExpr = (( ExistentialExprViewItem ) existentialExpr).getExpression();
                }
                conditions.add( new ExistentialPatternImpl( viewItem2Condition( existentialExpr, condition, ctx ), existentialType ) );
                continue;
            }

            if ( ruleItem instanceof ExprViewItem && ctx.boundVars.contains( patterVariable ) ) {
                conditions.add( new EvalImpl( createConstraint( (ExprViewItem) ruleItem ) ) );
                continue;
            }

            ctx.usedVars.add( patterVariable );
            Condition condition;
            if ( type == Type.AND ) {
                condition = conditionMap.get( patterVariable );
                if ( condition == null ) {
                    condition = new PatternImpl( patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable) );
                    conditions.add( condition );
                    if (!(viewItem instanceof AccumulateExprViewItem)) {
                        conditionMap.put( patterVariable, condition );
                    }
                    scopedInputs.putIfAbsent( patterVariable, (InputViewItemImpl) input( patterVariable ) );
                }
            } else {
                condition = new PatternImpl( patterVariable );
                conditions.add( condition );
            }

            addInputFromVariableSource( scopedInputs, patterVariable );

            Condition modifiedPattern = viewItem2Condition( viewItem, condition, new BuildContext( ctx, scopedInputs ) );
            conditions.set( conditions.indexOf( condition ), modifiedPattern );

            if (!ctx.isQuery) {
                registerInputsFromViewItem( viewItem, conditionMap, scopedInputs, null );
            }

            if ( type == Type.AND && !(viewItem instanceof AccumulateExprViewItem) ) {
                conditionMap.put( patterVariable, modifiedPattern );
            }
        }

        return new CompositePatterns( type, conditions, ctx.usedVars, consequences );
    }

    private static void registerInputsFromViewItem( ViewItem viewItem, Map<Variable<?>, Condition> conditionMap, Map<Variable<?>, InputViewItemImpl<?>> scopedInputs, Variable<?> existentialVar ) {
        for (Variable var : viewItem.getVariables()) {
            if (var.isFact() && !conditionMap.containsKey( var ) && var != existentialVar) {
                scopedInputs.putIfAbsent( var, (InputViewItemImpl) input( var ) );
            }
        }
    }

    private static Variable<?> findPatterVariable( ViewItem viewItem, Set<Variable<?>> vars ) {
        Variable<?> patternVariable = viewItem.getFirstVariable();
        if (!vars.contains( patternVariable )) {
            return patternVariable;
        }

        // vars is an ordered set of the variables used so far
        // the pattern variable is the last used variables also present in the viewitem

        Variable<?>[] itemVars = viewItem.getVariables();
        for (Variable<?> var : vars) {
            for (Variable<?> itemVar : itemVars) {
                if (itemVar == var) {
                    patternVariable = itemVar;
                    break;
                }
            }
        }

        return patternVariable;
    }

    private static void addInputFromVariableSource( Map<Variable<?>, InputViewItemImpl<?>> inputs, Variable<?> patterVariable ) {
        if ( patterVariable instanceof Declaration ) {
            Declaration declaration = (( Declaration ) patterVariable);
            if ( declaration.getSource() instanceof From ) {
                Variable var = (( From ) declaration.getSource()).getVariable();
                if(var != null) { // If from is from a supplier source is missing
                    addInputFromVariableSource(inputs, var);
                    if (var.isFact()) {
                        inputs.putIfAbsent(var, (InputViewItemImpl) input(var));
                    }
                }
            }
        }
    }

    static ConditionalNamedConsequenceImpl createConditionalNamedConsequence(Map<String, Consequence> consequences, ConditionalConsequence cond) {
        return new ConditionalNamedConsequenceImpl( createConstraint( cond.getExpr() ),
                                                    createNamedConsequence( consequences, cond.getThen() ),
                                                    cond.getElse() != null ? createConditionalNamedConsequence( consequences, cond.getElse() ) : null );
    }

    static SingleConstraint createConstraint( ExprViewItem expr ) {
        if (expr instanceof Expr1ViewItemImpl) {
            return new SingleConstraint1( (Expr1ViewItemImpl) expr );
        }
        if (expr instanceof Expr2ViewItemImpl) {
            return new SingleConstraint2( (Expr2ViewItemImpl) expr );
        }
        if (expr instanceof Expr3ViewItemImpl) {
            return new SingleConstraint3( (Expr3ViewItemImpl) expr );
        }
        if (expr instanceof Expr4ViewItemImpl ) {
            return new SingleConstraint4( (Expr4ViewItemImpl) expr );
        }
        if (expr instanceof Expr5ViewItemImpl ) {
            return new SingleConstraint5( (Expr5ViewItemImpl) expr );
        }
        if (expr instanceof Expr6ViewItemImpl ) {
            return new SingleConstraint6( (Expr6ViewItemImpl) expr );
        }
        if (expr instanceof Expr7ViewItemImpl ) {
            return new SingleConstraint7( (Expr7ViewItemImpl) expr );
        }
        if (expr instanceof Expr8ViewItemImpl ) {
            return new SingleConstraint8( (Expr8ViewItemImpl) expr );
        }
        if (expr instanceof Expr9ViewItemImpl ) {
            return new SingleConstraint9( (Expr9ViewItemImpl) expr );
        }
        if (expr instanceof Expr10ViewItemImpl ) {
            return new SingleConstraint10( (Expr10ViewItemImpl) expr );
        }
        if (expr instanceof Expr11ViewItemImpl ) {
            return new SingleConstraint11( (Expr11ViewItemImpl) expr );
        }
        if (expr instanceof Expr12ViewItemImpl ) {
            return new SingleConstraint12( (Expr12ViewItemImpl) expr );
        }
        if (expr instanceof Expr13ViewItemImpl ) {
            return new SingleConstraint13( (Expr13ViewItemImpl) expr );
        }
        return null;
    }

    private static NamedConsequenceImpl createNamedConsequence( Map<String, Consequence> consequences, Consequence consequence ) {
        if (consequence == null) {
            return null;
        }
        String name = generateName("consequence");
        consequences.put(name, consequence);
        return new NamedConsequenceImpl( name, consequence.isBreaking() );
    }

    private static Condition viewItem2Condition( ViewItem viewItem, Condition condition, BuildContext ctx ) {
        if ( viewItem instanceof AbstractExprViewItem ) {
            ( (PatternImpl) condition ).addWatchedProps( (( AbstractExprViewItem ) viewItem).getWatchedProps() );
        }

        if ( viewItem instanceof Expr1ViewItemImpl ) {
            Expr1ViewItemImpl expr = (Expr1ViewItemImpl)viewItem;
            if (expr.getPredicate() != null) {
                ( (PatternImpl) condition ).addConstraint( new SingleConstraint1( expr ) );
            }
            return condition;
        }

        if ( viewItem instanceof ExprNViewItem ) {
            ( (PatternImpl) condition ).addConstraint( SingleConstraint.createConstraint( ( ExprNViewItem ) viewItem ) );
            return condition;
        }

        if (viewItem instanceof TemporalExprViewItem) {
            TemporalExprViewItem expr = (TemporalExprViewItem)viewItem;
            ( (PatternImpl) condition ).addConstraint( TemporalConstraint.createTemporalConstraint( expr ) );
            return condition;
        }

        if ( viewItem instanceof AccumulateExprViewItem) {
            AccumulateExprViewItem acc = (AccumulateExprViewItem)viewItem;

            for ( AccumulateFunction accFunc : acc.getAccumulateFunctions()) {
                ctx.usedVars.add(accFunc.getResult());
            }

            Condition newCondition;
            if (acc.getExpr() instanceof InputViewItem) {
                newCondition = condition;
            } else if (acc.getExpr() instanceof Binding) {
                Binding binding = (( Binding ) acc.getExpr());
                PatternImpl bindingPattern = new PatternImpl( binding.getInputVariable() );
                bindingPattern.addBinding( binding );
                newCondition = bindingPattern;
                ctx.usedVars.add( binding.getBoundVariable() );
            } else {
                newCondition = viewItem2Condition(acc.getExpr(), condition, ctx);
            }

            return new AccumulatePatternImpl(newCondition, acc.getAccumulateFunctions());
        }

        if ( viewItem instanceof CombinedExprViewItem ) {
            CombinedExprViewItem combined = (CombinedExprViewItem) viewItem;
            CompositePatterns patterns = viewItems2Condition( new BuildContext( ctx, combined.getExpressions() ), combined.getType(), false );
            return patterns.getSubConditions().size() == 1 ? patterns.getSubConditions().get(0) : patterns;
        }

        throw new UnsupportedOperationException( "Unknown ViewItem: " + viewItem );
    }

    private static class ConditionComparator implements Comparator<Condition> {

        private static final ConditionComparator INSTANCE = new ConditionComparator();

        @Override
        public int compare( Condition c1, Condition c2 ) {
            if (c1 instanceof Pattern && c2 instanceof Pattern) {
                Pattern p1 = (( Pattern ) c1);
                Pattern p2 = (( Pattern ) c2);
                if (p1.getPatternVariable() != null && p1.getPatternVariable() == getSourceVariable( p2 )) {
                    return -1;
                }
                if (p2.getPatternVariable() != null && p2.getPatternVariable() == getSourceVariable( p1 )) {
                    return 1;
                }
            }
            return 0;
        }

        private static Variable getSourceVariable( Pattern pattern) {
            Variable source = pattern.getPatternVariable();
            if (source instanceof Declaration) {
                DeclarationSource declarationSource = (( Declaration ) source).getSource();
                if (declarationSource instanceof From) {
                    return (( From ) declarationSource).getVariable();
                }
            }
            return null;
        }
    }

    private static class BuildContext {
        final List<RuleItem> ruleItems;
        final Map<Variable<?>, InputViewItemImpl<?>> inputs;
        final Set<Variable<?>> usedVars;
        final Set<Variable<?>> boundVars;
        final Map<Variable<?>, List<Binding>> bindings;

        boolean isQuery = false;

        BuildContext( RuleItemBuilder<?>[] viewItemBuilders ) {
            this( Stream.of( viewItemBuilders ).map( RuleItemBuilder::get ).collect( toList() ), new LinkedHashMap<>(),
                    new HashSet<>(), new HashSet<>(), new HashMap<>(), false );
        }

        BuildContext( BuildContext orignalContext, ViewItem[] view ) {
            this( Arrays.asList( view ), orignalContext.inputs, orignalContext.usedVars, orignalContext.boundVars, orignalContext.bindings, orignalContext.isQuery );
        }

        BuildContext( BuildContext orignalContext, Map<Variable<?>, InputViewItemImpl<?>> inputs ) {
            this( orignalContext.ruleItems, inputs, orignalContext.usedVars, orignalContext.boundVars, orignalContext.bindings, orignalContext.isQuery );
        }

        BuildContext( BuildContext orignalContext, ViewItem[] view, Map<Variable<?>, InputViewItemImpl<?>> inputs ) {
            this( Arrays.asList( view ), inputs, orignalContext.usedVars, orignalContext.boundVars, orignalContext.bindings, orignalContext.isQuery );
        }

        BuildContext( List<RuleItem> ruleItems, Map<Variable<?>, InputViewItemImpl<?>> inputs, Set<Variable<?>> usedVars,
                      Set<Variable<?>> boundVars, Map<Variable<?>, List<Binding>> bindings, boolean isQuery ) {
            this.ruleItems = ruleItems;
            this.inputs = inputs;
            this.usedVars = usedVars;
            this.boundVars = boundVars;
            this.bindings = bindings;
            this.isQuery = isQuery;
        }

        void addBinding(Binding bindViewItem) {
            boundVars.add(bindViewItem.getBoundVariable());
            bindings.computeIfAbsent( bindViewItem.getInputVariable(), v -> new ArrayList<>() ).add( bindViewItem );
        }
    }
}


text:
<?php

namespace Todo\Models;

class Task extends BaseModel {

    protected $fillable = [];

    public function user()
    {
        return $this->belongsTo('Todo\Models\User');
    }

    public function tags()
    {
        return $this->hasMany('Todo\Models\Tag');
    }

    public function comments()
    {
        return $this->hasMany('Todo\Models\Comment');
    }

}


text:
#region License

#endregion License

using System;
using System.Collections.Generic;

namespace GlfwExamples
{
    static class GlslLesson01
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Run()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Example());
            Cube e = new Cube();
            e.MainLoop();
        }
    }
}


text:
(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define([], factory);
  } else if (typeof exports !== "undefined") {
    factory();
  } else {
    var mod = {
      exports: {}
    };
    factory();
    global.gridTest = mod.exports;
  }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function () {

  'use strict';

  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
      var info = gen[key](arg);
      var value = info.value;
    } catch (error) {
      reject(error);
      return;
    }

    if (info.done) {
      resolve(value);
    } else {
      Promise.resolve(value).then(_next, _throw);
    }
  }

  function _asyncToGenerator(fn) {
    return function () {
      var self = this,
          args = arguments;
      return new Promise(function (resolve, reject) {
        var gen = fn.apply(self, args);

        function _next(value) {
          asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
        }

        function _throw(err) {
          asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
        }

        _next(undefined);
      });
    };
  }

  var _require = require('@carbon/test-utils/scss'),
      SassRenderer = _require.SassRenderer;

  var _SassRenderer$create = SassRenderer.create(__dirname),
      render = _SassRenderer$create.render;

  describe('@carbon/styles/scss/grid', function () {
    test('Public API', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _yield$render, get, _get, api;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return render("\n      @use 'sass:meta';\n      @use '../grid' as *;\n\n      $_: get('api', (\n        variables: (\n          grid-gutter: meta.variable-exists('grid-gutter'),\n          grid-breakpoints: meta.variable-exists('grid-breakpoints'),\n        ),\n        mixins: (\n          css-grid: meta.mixin-exists('css-grid'),\n          subgrid: meta.mixin-exists('subgrid'),\n          flex-grid: meta.mixin-exists('flex-grid'),\n        ),\n      ));\n    ");

            case 2:
              _yield$render = _context.sent;
              get = _yield$render.get;
              _get = get('api'), api = _get.value;
              expect(api).toEqual({
                variables: {
                  'grid-gutter': true,
                  'grid-breakpoints': true
                },
                mixins: {
                  'css-grid': true,
                  subgrid: true,
                  'flex-grid': true
                }
              });

            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    })));
  });
});